Re: Running flask on AWS SAM

2017-10-13 Thread sohcahtoa82
On Thursday, October 12, 2017 at 9:20:11 PM UTC-7, Frustrated learner wrote:
> Hello,
> 
> I have a flask based application which i am able to run locally.
> 
> $ python swagger_server/app.py 
>  * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
> 
> I am trying to port this over to aws. I have all the dependencies and code 
> organized in the same folder.
> 
> Here is the transaction and error:
> $ SERVER_NAME=0.0.0.0:3000 sam local start-api 
> 2017/10/12 21:02:20 Connected to Docker 1.32
> 2017/10/12 21:02:20 Fetching lambci/lambda:python3.6 image for python3.6 
> runtime...
> python3.6: Pulling from lambci/lambda
> Digest: 
> sha256:c77ea3986c471c2f93dfa2a86492e6306989505073795da3b22defa2b10846a6
> Status: Image is up to date for lambci/lambda:python3.6
> 
> Mounting swagger_server.app.app (python3.6) at http://127.0.0.1:3000/current 
> [GET]
> Mounting static files from public at /
> 
> You can now browse to the above endpoints to invoke your functions.
> You do not need to restart/reload SAM CLI while working on your functions,
> changes will be reflected instantly/automatically. You only need to restart
> SAM CLI if you update your AWS SAM template.
> 
> 2017/10/12 21:02:30 Invoking swagger_server.app.app (python3.6)
> 2017/10/12 21:02:30 Decompressing 
> /Users/shekartippur/playground/cyclopscloud/cyclopsglobal/swagger_server.zip
> START RequestId: 9518afce-6cf7-4f20-9a31-0a60907b5467 Version: $LATEST
> 'SERVER_NAME': KeyError
> Traceback (most recent call last):
>   File "/var/task/connexion/apps/abstract.py", line 266, in __call__
> return self.app(environ, start_response)
>   File "/var/task/flask/app.py", line 1997, in __call__
> return self.wsgi_app(environ, start_response)
>   File "/var/task/flask/app.py", line 1977, in wsgi_app
> ctx = self.request_context(environ)
>   File "/var/task/flask/app.py", line 1938, in request_context
> return RequestContext(self, environ)
>   File "/var/task/flask/ctx.py", line 242, in __init__
> self.url_adapter = app.create_url_adapter(self.request)
>   File "/var/task/flask/app.py", line 1765, in create_url_adapter
> server_name=self.config['SERVER_NAME'])
>   File "/var/task/werkzeug/routing.py", line 1299, in bind_to_environ
> wsgi_server_name = environ['SERVER_NAME']
> KeyError: 'SERVER_NAME'
> 
> END RequestId: 9518afce-6cf7-4f20-9a31-0a60907b5467
> REPORT RequestId: 9518afce-6cf7-4f20-9a31-0a60907b5467 Duration: 3257 ms 
> Billed Duration: 3300 ms Memory Size: 0 MB Max Memory Used: 38 MB
> 
> I looked up the error and dint find much help. Wondering what I could be 
> missing.

Instead of doing:

SERVER_NAME=0.0.0.0:3000 sam local start-api 

try this:

export SERVER_NAME="0.0.0.0:3000 sam local start-api"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Want to write a python code for sending and receiving frames over wifi/wlan0 using python

2017-10-12 Thread sohcahtoa82
On Thursday, October 12, 2017 at 1:08:55 AM UTC-7, T Obulesu wrote:
> Hello all, I want to send some frames defined by me{Example, 
> [0x45,0x43,0x32]} to the raspberry pi from any macine(Desktop/Laptop/other 
> raspberry pi). But I want to send those frames over wifi or use wlan0 using 
> python Any suggestions?

Check out a Python library called scapy.  It's used for raw packet forgery.

But as others mentioned, that kind of activity will require you to run as root. 
 Also, sending raw packets over Wifi specifically usually requires you to 
switch wlan0 to "monitor" mode, essentially making it unable to do anything 
else with it while your script is running.

Also, not every Wifi adapter even supports entering monitor mode.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Boolean Expressions

2017-09-26 Thread sohcahtoa82
On Tuesday, September 26, 2017 at 2:54:32 PM UTC-7, Chris Angelico wrote:
> On Wed, Sep 27, 2017 at 7:43 AM, Cai Gengyang  wrote:
> > Help check if my logic is correct in all 5 expressions
> >
> >
> > A) Set bool_one equal to the result of
> > False and False
> >
> > Entire Expression : False and False gives True because both are False
> 
> This is not correct, and comes from a confusion in the English
> language. In boolean logic, "and" means "both". For instance:
> 
> *IF* we have eggs, *AND* we have bacon, *THEN* bake a pie.
> 
> Can you bake an egg-and-bacon pie? You need *both* ingredients. The
> assertion "we have eggs" is True if we do and False if we do not; and
> the overall condition cannot be True unless *both* assertions are
> True.
> 
> In Python, the second half won't even be looked at if the first half
> is false. That is to say, Python looks beside the stove to see if
> there's a carton of eggs, and if it can't see one, it won't bother
> looking in the freezer for bacon - it already knows we can't bake that
> pie.
> 
> Your other questions are derived from this one, so you should be fine
> once you grok this one concept.
> 
> ChrisA

A way to prove this:

def funcA():
print('In function A')
return False

def funcB():
print('In function B')
return False

print(funcA() and funcB())

This will print 'In function A' followed by 'False'.  It will not print 'In 
function B' at all.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: String to Dictionary conversion in python

2017-09-19 Thread sohcahtoa82
On Thursday, September 14, 2017 at 11:01:46 PM UTC-7, santosh.y...@gmail.com 
wrote:
> Hi,
> 
> Can anyone help me in the below issue.
> 
> I need to convert string to dictionary 
> 
> string = " 'msisdn': '7382432382', 'action': 'select', 'sessionId': '123', 
> 'recipient': '7382432382', 'language': 'english'"
> 
> Can anyone help me with the code

We're not going to do your homework for you.  What have you tried?  What errors 
are you getting?  If you're replying with your code or an error, make sure to 
use Copy/Paste and DO NOT just manually re-type the code or error.  Also, make 
sure to post the entire traceback.

If literal_eval is out of the question, take a look at the str.split() 
function.  I'd split on a comma, then for each result, split on the colon, then 
strip out the single quotes.

The actual coding of that is an exercise for the reader.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Check Python version from inside script? Run Pythons script in v2 compatibility mode?

2017-07-07 Thread sohcahtoa82
On Friday, July 7, 2017 at 11:58:33 AM UTC-7, eryk sun wrote:
> On Fri, Jul 7, 2017 at 7:53 AM, Steve D'Aprano
>  wrote:
> > On Fri, 7 Jul 2017 04:30 pm, Ben S. wrote:
> >
> >> Is there a way to execute a python script with v3 python engine in v2
> >> compatibility mode? I am thinking about a command parameter like 
> >> (python.exe
> >> is v3.*):
> >>
> >>   python.exe -execute_as_v2 myscript.py
> >
> > No. Python 3 is always Python 3, and Python 2 is always Python 2. But what 
> > you
> > can do is install both, and then call
> >
> > python2.exe myscript.py
> >
> > python3.exe anotherscript.py
> 
> Windows Python installs two loaders for each version of Python:
> python.exe and pythonw.exe. No links or copies are created for
> pythonX[w].exe, pythonX.Y[w].exe, or pythonX.Y-32[w].exe. Instead,
> there are separate py.exe and pyw.exe launchers that use the registry
> to find and execute a loader for a given version, e.g.
> 
> py -2 myscript.py
> py -3.6-32 anotherscript.py
> 
> As of 3.6, the py launcher defaults to the highest version of Python 3
> that's installed. 64-bit Python is preferred on 64-bit Windows. The
> default version can be overridden by setting the PY_PYTHON environment
> variable.
> 
> That said, you don't have to manually run a script as an argument of
> py.exe or python.exe. For a default Python 3 installation, if the
> PATHEXT environment variable contains ".PY", then you can run
> "script.py" as
> 
> script arg1 ... argN
> 
> in CMD or PowerShell. If a script has a Unix shebang, the launcher
> will read it to run the required version of Python, if that version is
> installed.

Is there any particular reason the Windows python does it that way?  Certainly 
it wouldn't be too difficult to include a "python2.exe" and "python3.exe", even 
as symbolic links.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to build a simple neural network in 9 lines of Python code

2017-06-28 Thread sohcahtoa82
On Tuesday, June 27, 2017 at 12:31:49 PM UTC-7, John Ladasky wrote:
> On Tuesday, June 27, 2017 at 9:24:07 AM UTC-7, Sam Chats wrote:
> > https://medium.com/technology-invention-and-more/how-to-build-a-simple-neural-network-in-9-lines-of-python-code-cc8f23647ca1
> 
> OK, that's cheating a bit, using Numpy.  It's a nice little program, but it 
> leverages a huge, powerful library.

Agreed.

It's equivalent to saying "Hey you can create an HTTP server in only 3 lines!" 
when you're just making a call to SimpleHTTPServer.

If I create a AAA-quality game and pack it up so all I have to do is "import 
mygame; mygame.start()", then have I created a AAA-quality game in only two 
lines?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How can I make a sentinel value NOT be initialized in a class/method - OOP?

2017-01-13 Thread sohcahtoa82
On Friday, January 13, 2017 at 2:27:04 PM UTC-8, David D wrote:
> I am testing out some basic Object Oriented Programming in Python.  The 
> basics: 
> 
> -User enters a name 
> -While loop with a sentinel value of "quit" will continue entering names 
> until the sentinel value is reached 
> -The object is created with the inputted value (NAME and until a sentinel 
> value is entered) 
> -the object is then printed out using the constructor __str__ 
> 
> In my solution ( I am saying this because someone might have a work around 
> that doesn't include the following below) 
> -I want to use __init__ 
> -I want to use __str__ 
> -I want to use a while loop with a sentinel value 
> 
> EXPLANATION: 
> I want to have the user enter in their NAME using a while loop, with "quit" 
> being the sentinel value that breaks the loop.  Once the name is entered, an 
> object is created and it is passed into a constructor def __ini__ (self, 
> name) and then I have them return a string value using __str__ for the name 
> entered. 
> The issue I am having is that when i enter the sentinel value of QUIT, it 
> gets initialized as the name and printed out.  How can I get around this?  I 
> hope this makes sense.

It would help if you posted your code to see what you're doing.

Also, is the sentinel value supposed to be "quit" or "QUIT"?  If you're only 
checking for "quit", but you type "QUIT", it isn't going to work.  Programs 
execute exactly as you write them, and "quit" is not the same as "QUIT".
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Cache memory and its effect on list searching

2016-12-16 Thread sohcahtoa82
On Friday, December 16, 2016 at 6:27:24 PM UTC-8, Chris Angelico wrote:
> On Sat, Dec 17, 2016 at 1:20 PM,   wrote:
> > I thought this was curious behavior.  I created a list of random-looking 
> > strings, then made a sorted copy.  I then found that using "in" to see if a 
> > string exists in the sorted list took over 9 times as long!
> >
> 
> My numbers replicate yours (though my computer's faster). But my
> conclusion is different:
> 
> Python 3.7.0a0 (default:ecd218c41cd4, Dec 16 2016, 03:08:47)
> [GCC 6.2.0 20161027] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import hashlib
> >>> import timeit
> >>> hashes =  [hashlib.md5(bytes(str(i), "utf-8")).hexdigest() for i in 
> >>> range(1000)]
> >>> sortedhashes = sorted(hashes)
> >>> timeit.timeit('"x" in hashes', globals={'hashes': hashes}, number=10)
> 0.8167107938788831
> >>> timeit.timeit('"x" in hashes', globals={'hashes': sortedhashes}, 
> >>> number=10)
> 5.029693723190576
> >>> timeit.timeit('"x" in hashes', globals={'hashes': hashes}, number=10)
> 0.855183657258749
> >>> timeit.timeit('"x" in hashes', globals={'hashes': sortedhashes}, 
> >>> number=10)
> 5.0585526106879115
> >>> sethashes = set(hashes)
> >>> timeit.timeit('"x" in hashes', globals={'hashes': sethashes}, number=10)
> 6.13601878285408e-06
> 
> You want containment checks? Use a set :)
> 
> ChrisA

Ah, I forgot about the optimizations of a set.  The only time I ever find 
myself using set is when I want to remove all the duplicates in a list.  I 
convert it to a set and then back.

For fun, I ran an experiment:

### BEGIN listsearch.py
import hashlib 
import timeit
import sys

from bisect import bisect_left

def bisect_search(a, x, lo=0, hi=None):   # can't use a to specify default for 
hi
# From 
http://stackoverflow.com/questions/212358/binary-search-bisection-in-python
hi = hi if hi is not None else len(a) # hi defaults to len(a)
pos = bisect_left(a,x,lo,hi)  # find insertion position
return (pos if pos != hi and a[pos] == x else -1) # don't walk off the end

def bin_search(haystack, needle):
start = 0
end = len(haystack) - 1
while True:
if start > end:
return False
middle = (start + end) // 2
if needle < haystack[middle]:
end = middle - 1
continue
elif needle > haystack[middle]:
start = middle + 1
continue
elif needle == haystack[middle]:
return True

print('Python version: ', sys.version_info)
print('building hashes...')
hashes = [hashlib.md5(bytes(str(i), "utf-8")).hexdigest() for i in 
range(1000)]
print('sorting...')
sortedhashes = sorted(hashes)
print('creating set...')
sethashes = set(hashes)
print('Unsorted list:', timeit.timeit('"x" in hashes', globals={'hashes': 
hashes}, number=10))
print('Sorted:', timeit.timeit('"x" in hashes', globals={'hashes': 
sortedhashes}, number=10))
print('set:', timeit.timeit('"x" in hashes', globals={'hashes': sethashes}, 
number=10))
print('binary search:',  timeit.timeit('binsearch(hashes, "x")', 
globals={'hashes': sortedhashes, 'binsearch': bin_search}, number=10))
print('binary search with bisect:',  timeit.timeit('binsearch(hashes, "x")', 
globals={'hashes': sortedhashes, 'binsearch': bisect_search}, number=10))
### END listsearch.py

> python3 listsearch.py
Python version:  sys.version_info(major=3, minor=5, micro=2, 
releaselevel='final', serial=0)
building hashes...
sorting...
creating set...
Unsorted list: 1.7384763684627569
Sorted: 9.248799958145042
set: 1.4614161294446149e-06
binary search: 0.00010902164328108199
binary search with bisect: 1.7829276782066472e-05

Yup.  set is definitely the way to go!
-- 
https://mail.python.org/mailman/listinfo/python-list


Cache memory and its effect on list searching

2016-12-16 Thread sohcahtoa82
Alternatively...why you should definitely use binary searches:

Python 3.5.2+ (default, Aug 30 2016, 19:08:42) 
[GCC 6.2.0 20160822] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import hashlib
>>> import timeit
>>> hashes =  [hashlib.md5(bytes(str(i), "utf-8")).hexdigest() for i in 
>>> range(1000)]
>>> sortedhashes = sorted(hashes)
>>> timeit.timeit('"x" in hashes', globals={'hashes': hashes}, number=10)
1.9478233020054176
>>> timeit.timeit('"x" in hashes', globals={'hashes': sortedhashes}, number=10)
18.001392804995703

I thought this was curious behavior.  I created a list of random-looking 
strings, then made a sorted copy.  I then found that using "in" to see if a 
string exists in the sorted list took over 9 times as long!

At first, I thought since both lists are the same size, and the 'in' test is a 
linear search, shouldn't they take the same amount of time?  Even if there was 
some trickery with branch prediction happening, that would have benefited the 
sorted list.  Then I remembered how lists work in Python.  The original list is 
going to be mostly contiguous in memory, making the memory cache quite 
effective.  When I create the sorted copy, I'm creating a list of references to 
strings that are all over the place in memory, causing tons of cache misses.

Of course, the best solution was to implement a binary search.  That turned the 
membership check into a 300-700 microsecond operation.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to sort this without 'cmp=' in python 3?

2016-10-14 Thread sohcahtoa82
On Friday, October 14, 2016 at 4:35:08 PM UTC-7, 38016...@gmail.com wrote:
> nums=['3','30','34','32','9','5']
> I need to sort the list in order to get the largest number string: '953433230'
> 
> nums.sort(cmp=lambda a,b: cmp(a+b, b+a), reverse=True)
> 
> But how to do this in python 3?
> 
> Thank you

You don't need a lambda in this case.

Sort the strings in reverse order:
nums.sort(reverse=True)

Create a string:
biggestNum = ''.join(nums)

Or in a single line, which doesn't change the original value of nums:
biggestNum = ''.join(sorted(nums, reverse=True))

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Without compilation, how to find bugs?

2016-10-14 Thread sohcahtoa82
On Friday, October 14, 2016 at 5:46:14 AM UTC-7, Steve D'Aprano wrote:
> On Fri, 14 Oct 2016 08:04 pm, BartC wrote:
> 
> > On 14/10/2016 01:59, sohcahto...@gmail.com wrote:
> >> On Thursday, October 13, 2016 at 4:06:36 PM UTC-7, pozz wrote:
> > 
> >>> Are the things exactly how I understood, or do I miss something in
> >>> Python?
> >>
> >> As others have said, user a linter.
> > 
> > With Python you're supposed to just be able run any source code
> > instantly; how will using a 'lint' tool impact that process? Or is it
> > only meant to be used infrequently?
> 
> The process is little different between C and Python:
> 
> With C: during development, you run the compiler (which includes built-in
> static analysis) or stand-alone linter, and optionally any tests you have,
> etc. The deployed software rarely if ever includes static analysis.
> 
> With Python: during development, you optionally run linters, static
> analysis, tests, etc. After deployment, you rarely run static tests,
> linting, etc.
> 
> 
> >> I'd go a step further and use an actual code editor or IDE that includes
> >> some basic static analysis.  Using this example that Skip used:
> >>
> >> def func2(a, b):
> >> print(a, b)
> >>
> >> def func1(a):
> >> print(a)
> >>
> >> func2(1)
> >>
> >> Any code editor worth using will highlight the ) on the last line and
> >> tell you that there's a missing parameter.
> 
> That's a matter of opinion.
> 

Fair enough.  vi/vim is a popular editor for writing code, but I personally 
can't stand them.

Of course, that's another subject entirely.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Without compilation, how to find bugs?

2016-10-14 Thread sohcahtoa82
On Friday, October 14, 2016 at 2:05:01 AM UTC-7, BartC wrote:
> On 14/10/2016 01:59, sohcahto...@gmail.com wrote:
> > On Thursday, October 13, 2016 at 4:06:36 PM UTC-7, pozz wrote:
> 
> >> Are the things exactly how I understood, or do I miss something in Python?
> >
> > As others have said, user a linter.
> 
> With Python you're supposed to just be able run any source code 
> instantly; how will using a 'lint' tool impact that process? Or is it 
> only meant to be used infrequently?

I'm not the person to ask about lint usage in Python.  I don't use a linter.  I 
just use the static analysis built into my IDE.

> 
> > I'd go a step further and use an actual code editor or IDE that includes 
> > some basic static analysis.  Using this example that Skip used:
> >
> > def func2(a, b):
> > print(a, b)
> >
> > def func1(a):
> > print(a)
> >
> > func2(1)
> >
> > Any code editor worth using will highlight the ) on the last line and tell 
> > you that there's a missing parameter.
> 
> How can that work? I thought one of the biggest deals with Python is 
> that you can re-bind function names to anything else. So:
> 
> if cond:
>  func2 = 38
> else:
>  func2 = func1
> 
> Then func2(1) can either be perfectly correct, or completely erroneous!
> 
> (I have my own suspicions that functions in Python are predominantly 
> used in a boring, predictable, static manner (so allowing certain 
> optimisations - or error checking), but I got the impression from some 
> threads here that many apparently do little else in their code but bind 
> and rebind function names.)
> 
> -- 
> Bartc

If you don't know if a variable is an integer or a function, then you've got 
other problems.  That just doesn't look like clean code.

And yes, I know, Python doesn't have "variables", but rather objects bound to 
names, or names bound to objects, or however you want to say it, the idea is 
similar.

Back on track, in the case you mentioned, my IDE does not flag any errors.  
Even if I do this:

def func(y):
return y

x = 0
if x:
f = 1
else:
f = func

f(0)

My IDE highlights the f(0) line and says that f is not callable.  Obviously 
it's wrong, but that just shows that my IDE's static analysis has its limits.

(For the record, my IDE is PyCharm 2.7.3, which I know is HORRENDOUSLY out of 
data, but it's what I'm stick with at work for now)

Anyways...if at any point in the execution of a program there's uncertainty 
whether a name could be bound to an integer OR a function, that seems like a 
code smell, especially when it's name looks like a function.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Without compilation, how to find bugs?

2016-10-13 Thread sohcahtoa82
On Thursday, October 13, 2016 at 4:06:36 PM UTC-7, pozz wrote:
> I come from the C language, that is a compiled and strongly typed 
> language.  I learned many good tricks to write good code in C: choose a 
> coding style, turn on as many warnings as possible, explicitly declare 
> static variables and functions (when needed), explicitly declare const 
> variables (if the piece of code will not change them), explicitly 
> declare all the functions, and so on.
> 
> All the tricks have a common goal: to discover bugs as soon as possible, 
> mostly during compilation process. Indeed I usually find some bugs 
> during compilation (or static analysis). It seems to me very important.
> 
> Now I'm learning Python and it appears to me very simple, but at the 
> same time highly dangerous. For example, I can write a function that 
> accepts two arguments and call it with only one argument. I can execute 
> the script without any problem and I will not notice the bug until I 
> test exactly the erroneous line of code (the call with only one argument).
> 
> However, I think the language interpreter could emit the error before 
> launching the script even without executing the wrong instruction, 
> because it perfectly knows how many arguments the function wants and 
> that one instruction calls it with a wrong number of arguments.
> 
> Are the things exactly how I understood, or do I miss something in Python?

As others have said, user a linter.

I'd go a step further and use an actual code editor or IDE that includes some 
basic static analysis.  Using this example that Skip used:

def func2(a, b): 
print(a, b) 

def func1(a): 
print(a) 

func2(1)

Any code editor worth using will highlight the ) on the last line and tell you 
that there's a missing parameter.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to process syntax errors

2016-10-12 Thread sohcahtoa82
On Wednesday, October 12, 2016 at 3:01:26 AM UTC-7, mr.pune...@gmail.com wrote:
> Hi All
> 
> Its really good to see that some discussion happening around this topic. 
> Sorry I was out from my work for sometime so couldn't follow up but I really 
> find it useful. It gives me good opportunity to know python better as I 
> recently started learning python. 
> 
> Ok so I tell you why I need to catch syntax error during compilation and 
> process them. See below example, 
> 
> # I created a platform class with different method in a file and making it as 
> a package. 
> class platform:
> def connect(self):
> # connect device 
> def destroy(self):
> # destroy device
> def config(self, command):
> # Send command to configure device
> def show(self, command):
> # check device health
> 
> Now person who wants to write a script using above package can simply use 
> below approach. Which does not make him to have knowledge in python. 
> 
> DUT = platform()
> DUT connect
> DUT config {commands}
> DUT show {commands}
> DUT destroy
> 
> 
> But I know this is not easy to do in python. As they all invalid syntax for 
> python language. So I thought of grabing syntax errors and manipulate them as 
> below internally to call them while code is compiling. 
> 
> DUT = platform()
> DUT.connect()
> DUT.config(commands)
> DUT.show(commands)
> DUT.destroy()
> 
> Hope you understand my need of doing this. If there is another solution to 
> achieve what I am trying to. Please let me know. 
> 
> Thanks, Puneet

You have two possible solutions:

1. Write an interpreter that can read an interpret the commands without 
parentheses.
2. Tell your users to use the dot "." operator and parentheses.  You don't need 
to teach them Python, just how to properly format the script.

Personally, I'd go with option #2.

But as others have said, you can't get Python to just "work" without 
parentheses.  Sure, you COULD attempt to import the script the users have 
written and catch the SyntaxError exception, but what would you do with it?  At 
that point, you're going to have to interpret the line of code in the script 
yourself, and at that point, you should just be writing an interpreter and not 
attempting to treat the script as Python.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is that forwards first or backwards first? (Re: unintuitive for-loop behavior)

2016-10-03 Thread sohcahtoa82
On Monday, October 3, 2016 at 2:11:12 AM UTC-7, Gregory Ewing wrote:
> Rustom Mody wrote:
> > My new car goes in reverse when I put it in first gear but only on 
> > full-moon 
> > nights with the tank on reserve when the left light is blinking
> 
> OT aside: When I went to take my current car (a manual)
> for a test drive, I had to stop and ask the dealer how
> to put it into reverse.
> 
> Turns out the only difference between first and reverse
> on that model is whether you lift up a little ring on the
> shaft of the gear lever prior to engagement.
> 
> Who came up with *that* brilliant piece of user interface
> design I don't know. It seems specifically designed to
> encourage velocity sign errors when starting off...
> 
> -- 
> Greg

My car is similar, but the R is actually to the left of 1.  It looks like this:

R 1 3 5
+-+-+-+
  2 4 6

However, you can't get to R unless you lift the ring around the stick upwards.  
once you go to the far left, the ring stays up until you slide it out of the 
far left notch.  My previous car was the traditional:

1 3 5
+-+-+
2 4 R

Surprisingly, despite driving that previous car for 13 years, the switch was 
incredibly easy.  I've never accidentally gone to sixth gear instead of 
reverse, or forgotten to shift into sixth on the highway.  Also, accidentally 
going into first when I want to reverse has never happened.  I was actually 
pretty surprised.  I thought I'd mess it up constantly for the first couple 
months.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python non blocking multi-client service

2016-08-25 Thread sohcahtoa82
On Tue, Aug 23, 2016 at 11:39 PM,   wrote:
> On Tuesday, August 23, 2016 at 6:42:53 AM UTC-7, Chris Angelico wrote:
> > On Tuesday, August 23, 2016 at 4:09:07 PM UTC+3, dimao wrote:
> > >   except:
> > >print ('Error')
> >
> >
> > Don't do this.
> >
> > ChrisA
> 
> I did that only for the debug reasons :-)

That makes it even worse.  If you're trying to debug something, you want as 
much information as you can get, and you're throwing it all away.

If you want your program to keep going no matter what happened, at *least* 
print the stack trace, and not just "Error".
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I am new to python. I have a few questions coming from an armature!

2016-08-15 Thread sohcahtoa82
On Monday, August 15, 2016 at 8:07:32 AM UTC-7, alister wrote:
> On Mon, 15 Aug 2016 07:00:47 -0700, Sickfit92 wrote:
> 
> > 1. How long did it take you guys to master the language or, let me put
> > it this way to completely get the hang and start writing code?
> > 

> Some concepts took more time than others before I had the "Light bulb" 
> moment, Comprehensions & decorators being the most notable although 
> Lambda still escapes me, fortunately these can all be unrolled into 
> larger functions so are not essential in the early stages
> 


What helped me understand Lambdas is figuring out that they're really just a 
$1,000 term for a $5 concept.

A lambda is just a single-line function without a name (Unless you assign it to 
one).  A syntactic shortcut.

def square_plus_one(x):
return x ** 2 + 1

squared_plus_one_list = map(square_plus_one, some_list)

is equivalent to:

squared_plus_one_list = map(lambda x: x**2 + 1, some_list)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Don't understand why I'm getting this error

2016-07-14 Thread sohcahtoa82
On Thursday, July 14, 2016 at 10:39:35 AM UTC-7, Carter Temm wrote:
> Hi all.
> I've been looking at this for a bit, and can't seem to come to a possible 
> conclusion on what could be happening to get an error. Anyway, here is the 
> code, then I'll explain.
> 
> http://pastebin.com/raw/YPiTfWbG
> 
> the issue comes when using argv. But when I change
> 
> TIME = argv
> 
> to
> 
> TIME = 2
> 
> It does exactly what I intended, no issues. What's wrong? Thanks for any help.
> 
> 
> 
> Also, The error I get when trying to run is: Traceback (most recent call 
> last): File "sound_recorder.py", line 21, in  for i in range(0, 
> int(RATE / CHUNK * TIME)): OverflowError: range() result has too many items‬

argv is a list containing the name (or path depending on OS) of the script and 
all the command line parameters passed to it.  I suspect that the problem is 
that the contents of argv will be strings, but you need TIME to be an integer.  
Even if you use "python myScript.py 5", argv[1] will be a string because Python 
doesn't know if "5" is actually supposed to be an integer, or if your script 
might be expecting a file name, and you have a file named "5".

An OverflowError when using range(..) usually means your range is too big.  I'm 
assuming you're using Python 2.x.  Try printing int(RATE / CHUNK * TIME) to see 
if the value is what you're expecting.  Also consider using xrange(..).  It 
doesn't require the entire list to be stored in memory.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Assignment Versus Equality

2016-06-27 Thread sohcahtoa82
On Monday, June 27, 2016 at 7:09:35 AM UTC-7, Marko Rauhamaa wrote:
> Grant Edwards :
> 
> > On 2016-06-26, BartC  wrote:
> >
> >> (Note, for those who don't know (old) Fortran, that spaces and tabs
> >> are not significant. So those dots are needed, otherwise "a eq b"
> >> would be parsed as "aeqb".)
> >
> > I've always been baffled by that.
> >
> > Were there other languages that did something similar?
> 
> In XML, whitespace between tags is significant unless the document type
> says otherwise. On the other hand, leading and trailing space in
> attribute values is insignificant unless the document type says
> otherwise.
> 
> > Why would a language designer think it a good idea?
> >
> > Did the poor sod who wrote the compiler think it was a good idea?
> 
> Fortran is probably not too hard to parse. XML, on the other hand, is
> impossible to parse without the document type at hand. The document type
> not only defines the whitespace semantics but also the availability and
> meaning of the "entities" (e.g.,  for ©). Add namespaces to that,
> and the mess is complete.
> 
> 
> Marko

XML isn't a programming language.  I don't think it's relevant to the 
conversation.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Beginner Question

2016-06-02 Thread sohcahtoa82
On Thursday, June 2, 2016 at 6:38:56 AM UTC-7, Igor Korot wrote:
> Steven,
> 
> On Thu, Jun 2, 2016 at 1:20 AM, Steven D'Aprano
>  wrote:
> > On Thursday 02 June 2016 14:21, Igor Korot wrote:
> >
> >> Hi, guys,
> >>
> >> On Wed, Jun 1, 2016 at 9:42 PM, boB Stepp  wrote:
> >>> On Wed, Jun 1, 2016 at 7:55 PM, Marcin Rak 
> >>> wrote:
>  Hi to all
> 
>  I have a beginner question to which I have not found an answer I was able
>  to understand.  Could someone explain why the following program:
> 
>  def f(a, L=[]):
>  L.append(a)
>  return L
> 
>  print(f(1))
>  print(f(2))
>  print(f(3))
> 
>  gives us the following result:
> 
>  [1]
>  [1,2]
>  [1,2,3]
> 
>  How can this be, if we never catch the returned L when we call it, and we
>  never pass it on back to f???
> >>
> >> I think the OP question here is:
> >>
> >> Why it is printing the array?
> >
> > Because he calls the function, then prints the return result.
> >
> > print(f(1))
> >
> > calls f(1), which returns [1], then prints [1].
> >
> > Then he calls:
> >
> > print(f(2))
> >
> > which returns [1, 2] (but he expects [2]), then prints it. And so on.
> >
> >
> >> There is no line like:
> >>
> >> t = f(1)
> >> print t
> >
> > Correct. But there are lines:
> >
> > print(f(1))
> > print(f(2))
> > print(f(3))
> 
> I think you missed the point.
> 
> Compare:
> 
> def f(a, L=[]):
>  L.append(a)
>  return L
> 
> print(f(1))
> print(f(2))
> print(f(3))
> 
> vs.
> 
> def f(a, L=[]):
>  L.append(a)
>  return L
> 
> t = f(1)
> print t
> t = f(2)
> print t
> t = f(3)
> print t
> 
> For people that comes from C/C++/Java, the first syntax is kind of weird:
> you return a value from the function but the caller does not save it anywhere.
> Especially since the return is not a basic type and most of them are
> not familiar
> with scalar vs list context (sorry for the Perl terminology here)
> 
> Thank you.
> 
> 
> >
> >
> >
> > --
> > Steve
> >
> > --
> > https://mail.python.org/mailman/listinfo/python-list

I came from C/C++/Java, and the first syntax makes perfect sense to me.  You're 
just taking the result of a function and directly passing it as a parameter to 
another.  There's nothing confusing about that.  C/C++/Java let you do it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A strange one: a commented line throws an error

2016-05-16 Thread sohcahtoa82
On Monday, May 16, 2016 at 10:25:54 AM UTC-7, DFS wrote:
> print "test"
> # stz source pytz.timezone() instance (for naïve local datetimes)
> 
> $ python temp.py
>File "temp.py", line 2
> SyntaxError: Non-ASCII character '\xc3' in file temp.py on line 2, but 
> no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
> 
> 
> 
> 
> python 2.7.11 on Windows

Yup.  That's the error I would expect when you use non-ASCII characters in your 
code without declaring the character encoding as described in PEP 263, which is 
conveniently linked in the exception details.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: OT: limit number of connections from browser to my server?

2016-05-16 Thread sohcahtoa82
On Monday, May 16, 2016 at 10:35:28 AM UTC-7, Peter Otten wrote:
> Grant Edwards wrote:
> 
> > This is not Python specific, though I'm turning to Python to do some
> > experimentation and to try to prototype a solution.
> > 
> > Is there any way to limit the number of connections a browser uses to
> > download a web page?  Browser writers seems to assume that all https
> > servers are massively parallel server farms with hardware crypto
> > support.
> > 
> > So, when a browser wants to load a page that has the main html file, a
> > css file, a javascript library or two, and a few icons and background
> > bitmaps, they browser opens up a half-dozen SSL connections in
> > parallel.
> 
> [brainstorm-mode on]
> 
> I think HTTP/2 allows multiple requests over a single TCP connection.

HTTP/1.1 already supports it, but most browsers have it disabled by default.

https://en.wikipedia.org/wiki/HTTP_pipelining

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: String concatenation

2016-05-11 Thread sohcahtoa82
On Wednesday, May 11, 2016 at 12:14:43 PM UTC-7, Thomas 'PointedEars' Lahn 
wrote:
> sohcahto...@gmail.com wrote:
> 
> > I don't blame people for not wanting to use their real name on the
> > Internet, especially if you're a woman.  There are a lot of crazy people
> > out there that will find out where you live and send death threats just
> > because you disagree with them or you happen to be a woman that enjoys
> > video games or exists in the tech world.
> 
> FUD and paranoia.  And this is _not_ the Internet.
> 
> -- 
> PointedEars
> 
> Twitter: @PointedEars2
> Please do not cc me. / Bitte keine Kopien per E-Mail.

You call it FUD and paranoia, I call it reality.  Are you familiar with the 
term "doxxing"?  Are you familiar with the shenanigans of GamerGate and 
Anonymous/4chan?  Or even some people on reddit.  It doesn't just happen to 
celebrities, either.  Is it likely to happen to me?  No, not really, but that 
doesn't mean I shouldn't be concerned at the possibility.

And how is this mailing list NOT part of the Internet?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: String concatenation (was: Steve D'Aprano, you're the "master". What's wrong with this concatenation statement?)

2016-05-10 Thread sohcahtoa82
On Sunday, May 8, 2016 at 5:44:25 PM UTC-7, Thomas 'PointedEars' Lahn wrote:
> Also, it would be a good idea if you posted under your real name.  Internet 
> is the thing with cables; Usenet is the thing with people.  I for one tend 
> to avoid communicating with few-letter entities; exceptions to that would 
> probably include only E.T., M.J., ALF, and K.I.T.T.
> 
> -- 
> PointedEars
> 
> Twitter: @PointedEars2
> Please do not cc me. / Bitte keine Kopien per E-Mail.

I don't blame people for not wanting to use their real name on the Internet, 
especially if you're a woman.  There are a lot of crazy people out there that 
will find out where you live and send death threats just because you disagree 
with them or you happen to be a woman that enjoys video games or exists in the 
tech world.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The irony

2016-05-10 Thread sohcahtoa82
On Tuesday, May 10, 2016 at 11:03:47 AM UTC-7, DFS wrote:
> "There should be one-- and preferably only one --obvious way to do it."
> 
> https://www.python.org/dev/peps/pep-0020/
> 
> 

Each method of string concatenation has different uses.

> ---
> sSQL =  "line 1\n"
> sSQL += "line 2\n"
> sSQL += "line 3"

This method is simple, easy to read, and is fine for cases where you're not 
going to be concatenating more than a couple strings *AT RUN-TIME*.


> ---
> sSQL = ("line 1\n"
>  "line 2\n"
>  "line 3")

This performs implicit string concatenation *AT COMPILE TIME*.  It doesn't work 
if the strings you are putting together are variables.

> ---
> sSQL = "\n".join([
>   "line 1",
>   "line 2",
>   "line 3",
> ])

This joins several strings (at run time) with a string separating them.  Though 
an empty string, comma, or a new line are the most common strings to use, you 
can use any string.

> ---
> sSQL =  """line 1
> line 2
> line 3"""
> ---
> sSQL = """\
> line 1
> line 2
> line 3"""

These two are effectively the same, sure.  I'll give you that.

> ---
> sSQL = "line 1\n" \
> "line 2\n" \
> "line 3"

This is just implicit string concatenation and no real different than your 
second option except you used the explicit line continuation character instead 
of using the implicit line continuation created by using parentheses.

> ---
> 
> 
> Which is the "one obvious way" to do it?
> I liked:
> 
> sSQL =  "line 1\n"
> sSQL += "line 2\n"
> sSQL += "line 3"
> 
> 
> but it's frowned upon in PEP8.

It's frowned upon because it is incredibly slow when used a lot.  Every time 
you do a += on a string, it has to re-allocate memory, whereas other methods 
either figure it out at compile time or figure out how much memory will be 
needed and allocate it once.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pygame easy create

2016-05-09 Thread sohcahtoa82
On Monday, May 9, 2016 at 3:15:45 AM UTC-7, hariram...@gmail.com wrote:
> On Monday, May 9, 2016 at 10:50:47 AM UTC+5:30, hariram...@gmail.com wrote:
> > is there anyway (IDE/package) that allows me to create graphics/game just 
> > like that (by instructing..., if i say create hills on the screen, it 
> > should generate pygame code)Anyway :) :)
> 
> Atleast i tried with pyglet,felt that it will be easier than pygame. 
> still again throwing me error some GL is missed, why they wont be straight 
> forward in working if we select the env we have...
> 
> some sites says 2.7 and >=3(3.4+) will have pip module by default, but i am 
> using 3.4.3 where i dont have pip and also tried python get-pip.py which also 
> not worked..

"still again throwing me error some GL is missed"

Can you say *EXACTLY* what the error is?  And can you copy/paste the relevant 
lines of code that lead to that error?

Also, judging from your other messages, it looks like you might be needing to 
read the Python or PyGame tutorials.  Programming is problem solving.  You 
can't just saying "Draw a hill" and PyGame (or whatever module you're using) 
will draw a hill.  You need to write code that describes how to draw a hill.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: After a year using Node.js, the prodigal son returns

2016-05-04 Thread sohcahtoa82
On Wednesday, May 4, 2016 at 1:59:15 AM UTC-7, Steven D'Aprano wrote:
> A year ago, Gavin Vickery decided to move away from Python and give 
> Javascript with Node.js a try. Twelve months later, he has written about his 
> experiences:
> 
> 
> http://geekforbrains.com/post/after-a-year-of-nodejs-in-production
> 
> 
> 
> -- 
> Steve

"Packages that consist of trivial code no more than 10 lines of code are 
downloaded in the thousands every day from NPM."

*cough* left-pad *cough*
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Re: Error 0*80070570

2016-04-21 Thread sohcahtoa82
On Thursday, April 21, 2016 at 10:47:04 AM UTC-7, Allan Leo wrote:
> I need help with this setup error.
> -- Forwarded message --
> From: "Allan Leo" 
> Date: Apr 21, 2016 10:06 AM
> Subject: Re: Error 0*80070570
> To: 
> Cc:
> 
> 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.
> >

Justin already gave you something to try: read the log file and search Google 
for the error code.

How about you try those before asking a FOURTH time?  I'll even give you a 
handy link so you don't have to search yourself:

http://lmgtfy.com/?q=0x80070570+error+when+installing+python
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Xlms namespace

2016-04-20 Thread sohcahtoa82
On Wednesday, April 20, 2016 at 10:05:02 AM UTC-7, Joaquin Alzola wrote:
> Hi Guys
> 
> I am currently doing this:
> 
> IP client(Python) --> send SOAPXML request --> IP Server (Python)
> 
> SOAP request:
> http://schemas.xmlsoap.org/soap/envelope/; 
> xmlns:req="http:/
> /request.messagepush.interfaces.comviva.com" 
> xmlns:xsd="http://request.messagepush.interfaces
> .comviva.com/xsd">
> test\ntest\ntest<{[£ EURO&%]}>
> 
> From my IP Client:
> s.send(data_send.encode('utf-8'))
> 
> From my IPServer:
> xml_decoded = data.decode('utf-8')
>   xml_root = 
> ET.ElementTree(ET.fromstring(xml_decoded)).getroot()
>   for elem in xml_root.getiterator():
>  
> if('{http://request.messagepush.interfaces.comviva.com/xsd}shortCode'==elem.tag):
> shortCode = 
> (elem.text).rstrip()
>  
> if('{http://request.messagepush.interfaces.comviva.com/xsd}text'==elem.tag):
> send_text = 
> (elem.text).rstrip()
>  
> if('{http://request.messagepush.interfaces.comviva.com/xsd}item'==elem.tag):
> subscribers = 
> (elem.text).rstrip()
>   result_sms = 
> send_sms(subscribers,shortCode,send_text)
> 
> It is working fine but I am having problems with a couple of special 
> characters, & and <
> 
> The problem:
> test\ntest\ntest<{[£ EURO&%]}>
> 
> It seems as if I send this: <> and the character & then I have a problem.
> I need to use utf-8 as I need to make sure I get 160 characters in one SMS.
> 
> Error:
> Traceback (most recent call last):
>   File "./ipserver.py", line 52, in 
> main()
>   File "./ipserver.py", line 36, in main
> xml_root = ET.ElementTree(ET.fromstring(xml_decoded)).getroot()
>   File "/usr/lib64/python3.4/xml/etree/ElementTree.py", line 1325, in XML
> parser.feed(text)
> xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 19, 
> column 48
> This email is confidential and may be subject to privilege. If you are not 
> the intended recipient, please do not copy or disclose its content but 
> contact the sender immediately upon receipt.

If I had to make a guess, you need to escape the <, >, and  or else 
they'll get parsed by the XML parser.  Try sending 
"test\ntest\ntest{[£ EURO%]}"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Guido sees the light: PEP 8 updated

2016-04-19 Thread sohcahtoa82
On Tuesday, April 19, 2016 at 1:59:48 PM UTC-7, Chris Angelico wrote:
> On Wed, Apr 20, 2016 at 6:50 AM, Ben Finney  
> wrote:
> >> > On Tue, 19 Apr 2016 01:04 pm, Rustom Mody wrote:
> >> > > And more generally that programmers sticking to text when rest of world
> >> > > has moved on is rather backward:
> >
> > You haven't supported that claim at all, and I see endless text everyday
> > in "the rest of the world". So your claim is false.
> 
> In this part of the world, I'm seeing a lot of emails/news posts that
> consist of text. How does the rest of the world discuss important
> topics? Is everything done with infographics and meme pics?
> 
> ChrisA
> not that this is exactly an important topic, really...

Personally, I prefer smoke signals.  Range is decent, but the bandwidth is 
atrocious.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Guido sees the light: PEP 8 updated

2016-04-18 Thread sohcahtoa82
On Monday, April 18, 2016 at 2:14:17 PM UTC-7, Pete Forman wrote:
> Why is it that Python continues to use a fixed width font and therefore
> specifies the maximum line width as a character count?
> 
> An essential part of the language is indentation which ought to continue
> to mandate that lines start with a multiple of 4 em worth of space (or
> some other size or encode with hard tabs, that is not germane to my
> question). The content of the line need not be bound by the rules needed
> to position its start.
> 
> -- 
> Pete Forman

"Why is it that Python continues to use a fixed width font "

This guy is trolling, right?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Looking for feedback on weighted voting algorithm

2016-04-15 Thread sohcahtoa82
On Thursday, April 14, 2016 at 1:48:40 PM UTC-7, 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.
> 
> >

I disagree with your notion of not sanitizing inputs.

If I'm the only person that will be using my program, then sure, I won't 
sanitize inputs.  It was my mistake and I should read the traceback and know 
what I did wrong.

But if ANY third party is going to be using it, especially as part of a web 
service of some kind, I'd much rather sanitize the inputs and tell the user 
they did something bad than to have the script crash and give a 500 Internal 
Server Error to the user.

Even worse, I definitely wouldn't want to give any hints of the source code 
organization by letting the user see the traceback.  I'll log it privately so I 
can view it myself, of course.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [beginner] What's wrong?

2016-04-08 Thread sohcahtoa82
On Friday, April 1, 2016 at 3:57:40 PM UTC-7, Mark Lawrence wrote:
> On 01/04/2016 23:44, sohcahto...@gmail.com wrote:
> > On Friday, April 1, 2016 at 3:10:51 PM UTC-7, Michael Okuntsov wrote:
> >> Nevermind. for j in range(1,8) should be for j in range(8).
> >
> > I can't tell you how many times I've gotten bit in the ass with that 
> > off-by-one mistake whenever I use a range that doesn't start at zero.
> >
> > I know that if I want to loop 10 times and I either want to start at zero 
> > or just don't care about the actual number, I use `for i in range(10)`.  
> > But if I want to loop from 10 to 20, my first instinct is to write `for i 
> > in range(10, 20)`, and then I'm left figuring out why my loop isn't 
> > executing the last step.
> >
> 
> "First instinct"?  "I expected"?  The Python docs might not be perfect, 
> but they were certainly adequate enough to get me going 15 years ago, 
> and since then they've improved.  So where is the problem, other than 
> failure to RTFM?
> 
> -- 
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
> 
> Mark Lawrence

Holy hell, why such an aggressive tone?

I understand how range(x, y) works.  It's just a simple mistake that I 
frequently do it wrong and have to correct it after the first time I run it.  
It's not like I'm saying that the implementation needs to change.  I'm just 
saying that if I want to loop from 10 to 20, my first thought is to use 
range(10, 20).  It is slightly unintuitive.

*YES*, I know it is wrong.  *YES*, I understand why the correct usage would be 
range(10, 21) to get that list from 10 to 20.

Get off your high horse.  Not everybody is like you and has been using Python 
for 15 years and apparently never makes mistakes.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [beginner] What's wrong?

2016-04-01 Thread sohcahtoa82
On Friday, April 1, 2016 at 3:10:51 PM UTC-7, Michael Okuntsov wrote:
> Nevermind. for j in range(1,8) should be for j in range(8).

I can't tell you how many times I've gotten bit in the ass with that off-by-one 
mistake whenever I use a range that doesn't start at zero.

I know that if I want to loop 10 times and I either want to start at zero or 
just don't care about the actual number, I use `for i in range(10)`.  But if I 
want to loop from 10 to 20, my first instinct is to write `for i in range(10, 
20)`, and then I'm left figuring out why my loop isn't executing the last step.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why do you use python?

2016-03-21 Thread sohcahtoa82
On Saturday, October 31, 2009 at 12:11:02 AM UTC-7, sk wrote:
> What would be your answer if this question is asked to you in an
> interview?
> 
> a modified version might be:
> "Where would you use python over C/C++/Java?"
> 
> (because my resume says I know C/C++/Java)?

I use Python when speed of development is far more important than speed of 
execution.

I use C/C++ when speed of execution is priority and I don't care about being 
cross-platform.

Though for what it's worth, I've only been a software engineer using Python for 
two years, and I have yet to use C/C++ outside of small personal projects and 
school.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to waste computer memory?

2016-03-19 Thread sohcahtoa82
On Thursday, March 17, 2016 at 7:34:46 AM UTC-7, wxjm...@gmail.com wrote:
> Very simple. Use Python and its (buggy) character encoding
> model.
> 
> How to save memory?
> It's also very simple. Use a programming language, which
> handles Unicode correctly.

*looks at the other messages in this thread*

...

Whatever happened to the idea of not feeding the trolls?  This image depicts 
this thread perfectly:

http://i.imgur.com/sVtpZDK.png
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Another python question

2016-03-19 Thread sohcahtoa82
On Friday, March 18, 2016 at 3:46:44 PM UTC-7, Alan Gabriel wrote:
> Sorry for the multiple questions but my while loop is not working as intended.
> 
> Here is the code :
> n = 1
> list1 = []
> count = 0  #amount of times program repeats
> steps = 0 # amount of steps to reach 1
> step_list = []
> while n!=0:
> n= int(input())
> list1.append(n)
> length = len(list1)
> 
> while count < length:
> num= list1[count]
> while num!= 1:
> if num%2 == 0:
> num= int(num/2)
> print(num)
> steps+=1
> if num%2 == 1:
> num=int(3*num+1)
> print(num)
> steps+=1
> 
> count+=1
> step_list.append(steps)
> steps=0
> 
> This code is meant to get numbers from the user in different lines and 
> convert into a list. When this is done the first while loop  runs until it 
> checks all the numbers in the list. The 2nd while loop is meant to stop when 
> the number is equal to 1 however the 2nd while loop keeps running.
> 
> Sorry for the bad naming but I was in a rush, ty anyway

I'll give you a big hint.  Your problem is on this line:

if num%2 == 1:

Step through your program slowly.  What happens when num == 2?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Encapsulation in Python

2016-03-14 Thread sohcahtoa82
On Friday, March 11, 2016 at 6:39:53 PM UTC-8, Rick Johnson wrote:
> On Friday, March 11, 2016 at 9:48:22 AM UTC-6, Ian wrote:
> > On Thu, Mar 10, 2016 at 5:45 PM, Rick Johnson
> > The honorable Rick Johnson wrote:
> > > Many times, i would have preferred to define my module space
> > > across multiple files, multiple files that could share state
> > > without resorting to the yoga-style "import contortions",
> > > and/or the dreaded "circular import nightmares" that plague
> > > our community today.
> >
> > Sounds to me like you're blaming Python for your own poor design.
> > Possible solutions:
> >
> > 1) Don't do that. If your module is too big for one file, then it's
> > likely poorly organized and doesn't all belong in one module anyway.
> 
> Apparently you've missed the many heated arguments between
> Chris Angelico and myself concerning the size of source
> files. I have *ALWAYS* taken the position that source files
> should be kept as small as possible, but that position is
> more relevant in Python, were modules are defined by a
> single source file. I don't take the Java position that a
> module can only contain one class, but i like to keep the
> number of classes (IN MY SOURCE FILES) small.
> 
> At run-time, i don't care how large a "module namespace" may
> be. Sometimes a module namespace will be small, with only a
> few exposed symbols, but sometimes, a module namespace will
> expose thousands of symbols. The size of a "run-time module"
> is irrelevant in most languages, but here in Python, were
> module namespace is defined by the contents of *ONE SINGLE
> SOURCE FILE*, the whole ballgame is changed. If i need to
> create a module that contains many exposed symbols in
> Python, i'm forced to do one of the following:
> 
>   (1) Write all my code in a single *GIGANTIC* file...
> 
> or
> 
>   (2) Create one file that will be the "mother-ship module",
>   and N files that will be the "satellite modules", and from
>   inside the mother-ship, import all the symbols from all
>   the satellites. Ha, but in reality, it's not that simple,
>   because state does not "magically" travel between modules!
> 
> ##
> # foo.py #
> ##
> FOO_SHARED_STATE = "foo"
> import _fooSatilite1
> _fooSatilite1.FOO_SHARED_STATE = FOO_SHARED_STATE
> from _fooSatilite1 import *
> import _fooSatilite2
> _fooSatilite2.FOO_SHARED_STATE = FOO_SHARED_STATE
> from _fooSatilite2 import *
> print 'This is the mother-ship called foo'
> ...
> 
> 
> # _fooSatilite1.py #
> 
> from _fooConstants import *
> print 'This is foo-fighter1, reporting for duty'
> print FOO_SHARED_STATE
> ...
> 
> 
> # _fooSatilite2.py #
> 
> from _fooConstants import *
> print 'This is foo-fighter2, reporting for duty'
> print FOO_SHARED_STATE
> ...
> 
> But i find both to be absurd. Writing all code in a single
> file might be fine for a toy module that contains a handful
> of functions or classes or vars, but once we start creating 
> anything in the "professional size range", it will become 
> an "editing nightmare" of epic proportions!
> 
> But option two is no better, because once we cut and paste
> portions of the code into satellite files, we lose the
> ability to "easily share state". Then we're forced to start
> "hacking at the weeds" with import contortions and monkey
> patches, all the while, fearing the dreaded circular import.
> 
> 
> NO, THIS IS INSANITY!  WHAT WE NEED IS AN OPTION 3!
> 
>  (3) Allow a programmer to define module space at will
> 
> ##
> # foo.py #
> ##
> module foo
> FOO_SHARED_STATE = "foo"
> print 'This is the mother-ship called foo'
> ...
> 
> 
> # _fooSatilite1.py #
> 
> module foo
> print 'This is foo-fighter1, reporting for duty'
> print FOO_SHARED_STATE # NO MP REQUIRED!
> ...
> 
> 
> # _fooSatilite2.py #
> 
> module foo
> print 'This is foo-fighter2, reporting for duty'
> print FOO_SHARED_STATE # NO MP REQUIRED!
> ...
> 
> No need for import contortions, no need for monkey patching,
> but most importantly, no need for professional programmers
> to feel as though they are penchant little children, who
> need their "module diapers" wrapped for them by mommy
> Python, who, after popping one too many "mother's little
> helpers", has a nasty habit of wrapping our diapers too damn
> tight -- what a drag, it is, getting old...
> 
> > 2) Clearly define which module is to be imported first. Then follow
> > it. When module b is imported, it should import module a. When module
> > a is imported, it *shouldn't* import module b until it's defined all
> > of its own members first. If module a depends on anything from module
> > b at import time, then refactor so 

Re: Perl to Python again

2016-03-11 Thread sohcahtoa82
On Friday, March 11, 2016 at 3:42:36 PM UTC-8, Fillmore wrote:
> So, now I need to split a string in a way that the first element goes 
> into a string and the others in a list:
> 
> while($line = ) {
> 
>  my ($s,@values)  = split /\t/,$line;
> 
> I am trying with:
> 
> for line in sys.stdin:
>  s,values = line.strip().split("\t")
>  print(s)
> 
> but no luck:
> 
> ValueError: too many values to unpack (expected 2)
> 
> What's the elegant python way to achieve this?
> 
> Thanks

I'd call the split, assign it to a temp value, then pull from there, like this:

parts = line.strip().split('\t')
s = parts[0]
values = parts[1:]

There might be a one-line way to do it, but I can't think of one that doesn't 
rely on calling split() twice.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: context managers inline?

2016-03-10 Thread sohcahtoa82
On Thursday, March 10, 2016 at 10:33:47 AM UTC-8, Neal Becker wrote:
> Is there a way to ensure resource cleanup with a construct such as:
> 
> x = load (open ('my file', 'rb))
> 
> Is there a way to ensure this file gets closed?

with open('my file', 'rb') as f:
x = load(f)

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: it doesn't want to open

2016-03-09 Thread sohcahtoa82
On Wednesday, March 9, 2016 at 10:40:27 AM UTC-8, mashaer elmekki wrote:
> Sent from Windows Mail

Did you try to attach a screenshot or something?  This mailing list is text 
only.  Your attachment will be removed.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic love

2016-03-07 Thread sohcahtoa82
On Monday, March 7, 2016 at 2:51:50 PM UTC-8, Fillmore wrote:
> learning Python from Perl here. Want to do things as Pythonicly as possible.
> 
> I am reading a TSV, but need to skip the first 5 lines. The following 
> works, but wonder if there's a more pythonc way to do things. Thanks
> 
> ctr = 0
> with open(prfile,mode="rt",encoding='utf-8') as pfile:
>  for line in pfile:
>  ctr += 1
> 
>  if ctr < 5:
>  continue
> 
>  allVals = line.strip().split("\t")
>  print(allVals)

I'd read all the lines at once and then just slice the list.

with open(prfile, mode="rt", encoding="utf-8") as pfile:
lines = pfile.readlines()[5:]
for line in lines:
allVals = line.strip().split("\t")
print(allVals)

Obviously, this will only work well if your file is a reasonable size, as it 
will store the entire thing in memory at once.

On a side note, your "with open..." line uses inconsistent quoting.  You have 
"" on one string, but '' on another.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Continuing indentation

2016-03-04 Thread sohcahtoa82
On Friday, March 4, 2016 at 4:43:57 PM UTC-8, Simon Ward wrote:
> On 4 March 2016 23:31:43 GMT+00:00, Erik  wrote:
> >On 04/03/16 21:14, sohcahto...@gmail.com wrote:
> >> You guys are spending way too much time fighting over something that
> >is clearly subjective.  Nobody is "correct" here.  There's no right and
> >wrong, just simple preference.
> >
> >I will take that as a vote +1 that PEP8 is wrong (*). ;)
> >
> >E.
> >
> >(*) PEP8 defines a specific format and you are stating that no specific
> >
> >format can be considered correct.
> 
> Style guides are always going to be considered incorrect by some people, but 
> they should aim more for consistency (the hobgoblin that may be), which is 
> what makes code easier to grok. Stop arguing, start thinking about others who 
> will have to read your code. What is better in your subjective opinion means 
> very little. Having commonly understandable style is what matters, and what 
> style guides help (including PEP8).
> 
> Simon
> -- 
> Sent from Kaiten Mail. Please excuse my brevity.

Arguing whether or not a style guide is "incorrect" is as silly as arguing over 
whether lima beans are delicious.  I think they're disgusting, but you can't 
make a statement of fact about the topic.

Style guides are just guides.  They're a suggestion.  You can agree with them 
or disagree with them.  If I write a guide that dictates that every line of 
code should only include necessary indentation, a single token, and then a line 
continuation backslash if necessary, so code looks like this:

x \
= \
5
if \
y \
== \
z:
print \
'this is terrible'
print \
'but still not incorrect

It would be terrible, still but not incorrect.

This argument about whether binary operators should go on the end of one line 
or the beginning of the next is the C/C++/C#/Java/etc. fight about braces all 
over again.  It is entirely subjective, and I find it absolutely ridiculous 
that so many people are willing to argue until they're blue in the face about 
it.

If you're doing your own project, do it however you like it and ignore anyone 
that tells you that you're doing it "wrong".  Not formatting your code to match 
PEP 8 doesn't make your code formatted wrong, it just means you're choosing not 
to follow PEP 8 to a T.  Personally, I hate underscores in variable names that 
aren't constants.  I much prefer myVariableName over my_variable_name.  I think 
using underscores creates a sort of white space that makes it harder to read.  
Do I think that people that use underscores are wrong?  No.  They just have a 
different opinion.

I just can't understand why so many people get their panties all up in a bunch 
over how other people choose to format their code.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Continuing indentation

2016-03-04 Thread sohcahtoa82
On Friday, March 4, 2016 at 3:41:29 PM UTC-8, Ben Finney wrote:
> alister  writes:
> 
> > On Fri, 04 Mar 2016 10:23:37 +0900, INADA Naoki wrote:
> >
> > > Because PEP8 says:
> > > 
> > >> The preferred place to break around a binary operator is after the
> > >> operator, not before it. http://pep8.org/#maximum-line-length
> >
> > and that is to make it obvious that there is more to come.
> 
> That's a good way to express it.
> 
> I think there are competing models here:
> 
> * When breaking an expression between two lines, put the binary operator
>   at the end of the earlier line.
> 
>   This makes it obvious what's going on when reading the earlier line.
> 
> * When breaking an expression between two lines, put the binary operator
>   at the beginning of the later line.
> 
>   This makes it obvious what's going on when reading the continuation
>   line.
> 
> Both have merit. Both models make an almost-identical appeal to
> readability.
> 
> We can't put the binary operator in multiple places,



Who are you, the binary operator police?  Watch me!

if x == y and \
x == z and \
a > b \
or b > c \
and (d is not \
None \
):
pass

You're not the boss of me!

And that code hurt to write...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Continuing indentation

2016-03-04 Thread sohcahtoa82
On Friday, March 4, 2016 at 6:03:48 AM UTC-8, alister wrote:
> On Fri, 04 Mar 2016 10:12:58 +, cl wrote:
> 
> > Steven D'Aprano  wrote:
> >> On Fri, 4 Mar 2016 12:23 pm, INADA Naoki wrote:
> >> 
> >> 
> >> >>
> >> >> Indeed. I don't understand why, when splitting a condition such as
> >> >> this,
> >> >> people tend to put the operator at the end of each line.
> >> >>
> >> >>
> >> > Because PEP8 says:
> >> > 
> >> >> The preferred place to break around a binary operator is after the
> >> > operator, not before it. http://pep8.org/#maximum-line-length
> >> 
> >> PEP 8 is wrong :-)
> >> 
> > Yes, I agree.  In my mind the logic is:-
> > 
> > IF xxx
> > AND yyy AND zzz OR aaa
> > THEN do something
> > 
> > The PEP8 correct(er):-
> > 
> > IF xxx AND
> >  yyy AND zzz OR aaa
> > THEN do something
> > 
> > ... just seems all wrong and difficult to understand.
> 
> not at all
> the split after the operator shows that their is more to that line
> splitting before & the reader could believe that the condition ends there
> 
> PEP 8 is mos definitely correct on this one
> 
> 
> 
> -- 
> According to all the latest reports, there was no truth in any of the
> earlier reports.

I wouldn't call PEP 8 "correct".  I would say that you just simply agree with 
PEP 8's suggestion.

You guys are spending way too much time fighting over something that is clearly 
subjective.  Nobody is "correct" here.  There's no right and wrong, just simple 
preference.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to know if an object is still be referenced?

2016-03-02 Thread sohcahtoa82
On Wednesday, March 2, 2016 at 3:35:32 AM UTC-8, jf...@ms4.hinet.net wrote:
> Terry Reedy at 2016/3/2  UTC+8 3:04:10PM wrote:
> > On 3/1/2016 9:35 PM, jf...@ms4.hinet.net wrote:
> > > Recently I was puzzled by a tkinter problem. The codes below (from a 
> > > book) can display the picture correctly.
> > >
> > >  gifdir = "../gifs/"
> > >  from tkinter import *
> > >  win = Tk()
> > >  photo = PhotoImage(file=gifdir + "ora-pp.gif")
> > >  Button(win, image=photo).pack()
> > >  win.mainloop()
> > 
> > Since photo is a global name, the binding remain until you explicitly 
> > delete it or exit the app.
> > 
> > > And the codes below (from another book) will also work.
> > >
> > >  class DrumMachine:
> > >  
> > >  
> > >  def create_play_bar(self):
> > >  
> > >  
> > >  photo = PhotoImage(file='images/signature.gif')
> > >  label = Label(playbar_frame, image=photo)
> > >  label.image = photo
> > >  label.grid(row=start_row, column=50, padx=1, sticky='w')
> > >  
> > >  
> > 
> > Here photo is a local name and the binding disappears when the function 
> > exits.  I would rewrite it to follow pattern 1.
> > 
> >   self.photo = PhotoImage(file='images/signature.gif')
> >   label = Label(playbar_frame, image=self.photo)
> > 
> > To me, saving an attribute reference is not worth the extra line.
> > 
> > > In the second example, I noticed that the "photo" was referenced two times
> > > and I think it might be a redundancy so I remove the line "label.image = 
> > > photo". But it fails then.
> > 
> > On another question, I made the same suggestion.  Oops.
> > 
> > -- 
> > Terry Jan Reedy
> 
> Thanks, Terry. After reading your reply I noticed that I had make a mistake. 
> The "image" is not an attribute of the Button. It's an option. The 
> "label.image=photo" does a different thing. But it didn't help on solving my 
> puzzle.
> 
> If the problem was caused by the "photo" is a local, then binding the "photo" 
> to an local attribute ("label" is a local too) seems no meaning at all. But 
> it did make difference! No idea how the underneath mechanism works.
> 
> I run this example under the pdb and it can display the picture correctly 
> even without the "label.image=photo" statement. Why it fails on running at 
> real time? tk event scheduling? I don't know.
> 
> --Jach

"label" might be a local variable, but it's constructor includes a reference to 
the frame in which it is going.  The frame object will create a reference to 
the newly-created Label object.  At that point, there will be two references to 
the new Label object.  When the function exits and "label" goes out of scope, 
the object still exists because the frame still has a reference.

If you're a C/C++ programmer, another way of thinking of it is imagining EVERY 
variable is created on the heap, not the stack, and so it is safe to pass 
around references to "local" variables, even when the function that creates it 
exits.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: common mistakes in this simple program

2016-02-29 Thread sohcahtoa82
On Monday, February 29, 2016 at 10:21:57 AM UTC-8, Ganesh Pal wrote:
> >> How do we reraise the exception in python ,  I have used raise not
> >> sure how to reraise the exception
> >
> > raise with no arguments will reraise the exception currently being handled.
> >
> > except Exception:
> > logging.error("something went wrong")
> > raise
> 
> Thanks Ian for taking time and looking into the code ,  o k raise
> keyword for raising exception is fine .
> 
>  assert ret ==0,"ERROR (ret %d): " \
>  " \nout: %s\nerr: %s\n" % (ret, out, err)
>  except Exception as e:
>  print("Failed to run %s got %s" % (cmd, e))
>  return False
>  return True
> 
>  def prep_host():
>  """
>  Prepare clustering
>  """
>  for cmd in ["ls -al",
>  "touch /tmp/file1",
>  "mkdir /tmp/dir1"]:
>  try:
>  if not run_cmd_and_verify(cmd, timeout=3600):
>  return False
>  except:
> >>>
> >>> What exceptions are you expecting this to catch? run_cmd_and_verify
> >>> already catches any expected exceptions that it raises.
> 
> In my case the exception is nothing but the error  example if  we plan
> to run the command  say  #ifconfig -a and the command fails because of
> a type ( say u ran #igconfig -a).
> 
> we will the output as
> 
> # Failed to run igconfig -a got Error (ret=127)
> out :
> error: command not found: igconfig
> 
> So the execption is the error i.e Error (ret=127) out : error: command
> not found: igconfig,  Iam fine with this behaviour.
> 
> 
> >
> > But that exception is already caught by the run_cmd_and_verify
> > function, so what exception are you expecting to be caught *here*?
> 
> I wanted to run the command in a loop  and have a fxn for the pattern
> that repeats in this case the function is run_cmd_and_verify  , the
> only known way to me was using try with expect
> 
> I thought I will use try and have pass in except which  you don't recommend
> 
>for cmd in ["ls -al",
>  "touch /tmp/file1",
> "mkdir /tmp/dir1"]:
>   try:
>if not run_cmd_and_verify(cmd, timeout=3600):
> print "running command failed "
>return False
> except:
> pass
> 
> > You should virtually never just pass in an exception handler. Either
> > handle the exception, or log it and reraise it. If you're going to do
> > neither of those things, then don't use a try-except at all.
> 
> What alternative do I have other than try-expect ? can try - else be
> used  for my case?
> 
> Regards,
> GPal

Every time you say "try-expect", my head wants to explode.

It is called a "try-except" block, because you're using the key words "try" and 
"except" when you make one.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "from module import data; print(data)" vs "import module; print(module.data)"

2016-02-25 Thread sohcahtoa82
On Wednesday, February 24, 2016 at 5:07:57 PM UTC-8, Dan Stromberg wrote:
> Could people please compare and contrast the two ways of doing imports
> in the Subject line?
> 
> I've long favored the latter, but I'm working in a code base that
> prefers the former.
> 
> Is it fair to say that the former increases the surface area of your
> shared (sometimes mutable) state?
> 
> It's clear that the former saves keystrokes.
> 
> I find the latter a little more clear, because you don't have to go
> look for where a symbol came from.
> 
> Anything else?
> 
> Thanks!

If I'm only importing a single class or function from a module AND that class 
or function has a very meaningful name, I will use "from MyModule import 
MyUsefulClass".  Otherwise, I just use "import MyModule".

Now, I've noticed people talking about importing os.path.  Is there any reason 
to use "import os.path" rather than "import os"?  Both of them will still put 
the "os" module into the global namespace.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-17 Thread sohcahtoa82
On Wednesday, February 17, 2016 at 11:49:44 AM UTC-8, wrong.a...@gmail.com 
wrote:
> I am mostly getting positive feedback for Python.

Good!

> 
> It seems Python is used more for web based applications. Is it equally fine 
> for creating stand-alone *.exe's? Can the same code be compiled to run on 
> Linux or Android or web-based?


Python is not traditionally compiled.  It is interpreted.  That said, there are 
utilities out there than can compile a Python script to a Windows executable.  
I personally have never used them, so I don't know about their limitations.

As for Android, I've heard of frameworks for making Android apps with Python, 
but I don't know of any off the top of my head.

> 
> Is it possible to create GUI elements with a good IDE? Can they be defined 
> like in Visual Basic with given sizes, fonts, visible/invisible, etc.?

I'm fairly certain there are GUI editors for Python.  I don't use any because I 
don't write anything with a GUI.

> 
> Is it easy to do matrix operations in Python? Or do I need to write 
> subroutines like in Visual Basic?

Check out the numpy and scipy packages.

> 
> Could someone kindly tell me advantages and disadvantages of Python? Or any 
> better options? I have like 40-50 VB Forms and may be around 2 lines of 
> code. It will be a task to learn a new language and translate/re-write that 
> code.

IMO, Python's greatest advantage is readability.  Python's syntax just plain 
makes sense to me.  It is just an easy language to work with.  It's funny, 
really.  I used to be a hardcore C/C++ fanatic.  When I first started learning 
Python, I hated it.  I thought it made things too easy and held your hand too 
much.  Now, I love it because it makes things so easy and holds your hand.  I 
spend less time worrying about memory allocation and pointer syntax and more 
time actually getting things done.

I think Python's biggest disadvantage is performance.  If you write 100% pure 
Python code, it can be a bit on the slower side.  However, if you're doing 
heavy number crunching using numpy/scipy, they're mostly written in C and are 
quite fast.

Basically, the way I see it, if speed of development is much more important 
than speed of execution, typically Python is a good choice.

> 
> Thanks for your responses.

I'm hoping someone else will be able to give a better response to Python on 
Android and the GUI editor.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: working

2016-02-12 Thread sohcahtoa82
On Friday, February 12, 2016 at 1:47:24 AM UTC-8, Mohammed Zakria wrote:
> hello
> i want to know the company that ican work as freelance python devloper

There are some recruiters that read this mailing list and will send unsolicited 
e-mail about job openings, but they might pass right over you if you're not 
willing to spend the time to proofread your messages.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: psss...I want to move from Perl to Python

2016-01-29 Thread sohcahtoa82
On Friday, January 29, 2016 at 1:12:34 AM UTC-8, Ulli Horlacher wrote:
> Steven D'Aprano  wrote:
> 
> > Every time I make a half-hearted attempt to learn enough Perl syntax to get
> > started, I keep running into the differences between $foo, %foo and @foo
> > and dire warnings about what happens if you use the wrong sigil
> 
> I have started learning Python several times and surrendered because my
> brain was too Perl hardcoded after 30 years, but NOW I was successful :-)
> (I still find Perl syntax better...)
> 
> About the variables in short:
> 
> $foo is a scalar (number, string, reference, file handle)
> @foo is an array
> %foo is a hash (dictionary in Python slang)
> 
> and yes, you can use them all together in same code, they are different.
> 
> For more discussion about Perl syntax one should better go to
> comp.lang.perl
> 
> -- 
> Ullrich Horlacher  Server und Virtualisierung
> Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
> Universitaet Stuttgart Tel:++49-711-68565868
> Allmandring 30aFax:++49-711-682357
> 70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/

"(I still find Perl syntax better...)"

I'm convinced that anyone who actually prefers Perl's syntax over Python is 
suffering from Stockholm Syndrome.

People frequently joke about Perl being "write-only code" due to how frequently 
people will write code, not look at it for a week or so, then come back to it 
and not be able to understand what the code is doing without excessive 
comments.  Or they will say that Perl code is indistinguishable from line noise.

*These are not the hallmarks of a good syntax*

Readability counts.  I'd say readability is one of the most important features 
of a language, as you will read your code far more than you write it.  Perl is 
not readable.  I don't care how powerful your language is if you can't read it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: psss...I want to move from Perl to Python

2016-01-29 Thread sohcahtoa82
On Thursday, January 28, 2016 at 6:34:34 PM UTC-8, Chris Angelico wrote:
> On Fri, Jan 29, 2016 at 1:06 PM, Paul Rubin  wrote:
> > Fillmore  writes:
> >> I look and Python and it looks so much more clean
> >
> > Yes it is, I forgot everything I knew about Perl shortly after starting
> > to use Python.
> 
> https://xkcd.com/353/
> 
> Particularly the hover text. :)
> 
> ChrisA

I have this comic pinned to the outside wall of my cubicle at work, where I use 
Python for 98% of my work.

It's funny...when I first started using Python, I hated it because it held your 
hand and made everything too easy.  I was a major C, C++ and Java fanatic.  
Now, I LOVE Python because it holds your hand and makes everything so easy.

I still like C and C++, but have basically learned that each language has it's 
place.  I wouldn't try to write a AAA-quality game in Python, just like I 
wouldn't write something that should be a simple 50-line Python script in C++.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I'm missing something here...

2016-01-11 Thread sohcahtoa82
On Monday, January 11, 2016 at 3:27:21 PM UTC-8, Skip Montanaro wrote:
> Here's a dumb little bit of code, adapted from a slightly larger script:
> 
> #!/usr/bin/env python
> 
> "dummy"
> 
> import glob
> import os
> 
> def compare_prices(*_args):
> "dummy"
> return set()
> 
> def find_problems(cx1, cx2, cx3, prob_dates):
> "dummy"
> for fff in sorted(glob.glob("/path/to/*.nrm")):
> sym = os.path.splitext(os.path.basename(fff))[0]
> prob_dates |= compare_prices("E:%s"%sym, cx1, cx2, cx3)
> 
> When I run pylint against it, it complains:
> 
> junk.py:10: [W0613(unused-argument), find_problems] Unused argument 
> 'prob_dates'
> 
> I must be misunderstanding something about the |= operator as applied
> to sets. If I read the docs correctly, s1 |= s2 is equivalent to
> s1.update(s2). A dumb "test" at the prompt suggests that's true:
> 
> >>> s1 = set("abc")
> >>> s2 = set("cde")
> >>> s1 | s2
> set(['a', 'c', 'b', 'e', 'd'])
> >>> s1 |= s2
> >>> s1
> set(['a', 'c', 'b', 'e', 'd'])
> >>> s1 = set("abc")
> >>> s1.update(s2)
> >>> s1
> set(['a', 'c', 'b', 'e', 'd'])
> 
> If I change the last line of find_problems to call
> prob_dates.update(), the message disappears. Why is pylint (1.4.2 BTW)
> complaining that the prob_dates argument of find_problems is unused
> when I use the |= operator?
> 
> Thx,
> 
> Skip

The pipe character on its own also functions as the binary OR operator, with x 
|= y being a shortcut for x = x | y.

If prob_dates is an integer, then it is immutable and the your prob_dates |= 
compare_prices(...) line won't do anything (The variable is being set, but 
never again read outside the function and it doesn't change the function's 
return value), which is probably what pylint is complaining about.  Pylint 
doesn't know that your function is expecting a mutable iterable for the 
prob_dates argument.

If you change it to prob_dates.update(...), does pylint complain?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Problem to read from array

2015-11-23 Thread sohcahtoa82
On Monday, November 23, 2015 at 12:58:49 PM UTC-8, Crane Ugly wrote:
> Thank you all.
> Here is the last piece of code that caused me so much troubles but now 
> working the way I wanted it: 
> 
>   fRawData = []
>   with open(fStagingFile2) as fStagingFile2FH:
>   fRawData = [line.strip() for line in 
> fStagingFile2FH.readlines()] #  This is to read each element from 
> the file and chop off the end of line character
>   
>   fNumberOfColumns = 7
>   fNumberOfRows = len(fRawData)/fNumberOfColumns
> 
>   fRowID = 0
>   fParameters = []
>   for fRowID in range(0, len(fRawData), fNumberOfColumns):
>   fParameters.append(fRawData[fRowID:fRowID+fNumberOfColumns])
>  #  This is to convert 1D array to 2D
> 
> #  ... and down below section is an example of how to read each 
> element of the list
> #  and how to update it if I need so. That was also a problem before.
>   fRowID = 0
>   fColumnID = 0
>   for fRowID in range(fNumberOfRows):
>   for fColumnID in range(fNumberOfColumns):
>   if fColumnID == 0:
>   fParameters[fRowID][fColumnID] = ""
>   Message2Log("fParameters[" + str(fRowID) + "][" + 
> str(fColumnID) + "] = " + str(fParameters[fRowID][fColumnID]))
> 
> CU
> 
> On Saturday, November 21, 2015 at 4:52:35 PM UTC+1, Nathan Hilterbrand wrote:
> > On 11/21/2015 10:26 AM, BartC wrote:
> > > On 21/11/2015 10:41, vostrus...@gmail.com wrote:
> > >> Hi,
> > >> I have a file with one parameter per line:
> > >> a1
> > >> b1
> > >> c1
> > >> a2
> > >> b2
> > >> c2
> > >> a3
> > >> b3
> > >> c3
> > >> ...
> > >> The parameters are lines of characters (not numbers)
> > >>
> > >> I need to load it to 2D array for further manipulations.
> > >> So far I managed to upload this file into 1D array:
> > >>
> > >> ParametersRaw = []
> > >> with open(file1) as fh:
> > >>  ParametersRaw = fh.readlines()
> > >> fh.close()
> > >
> > > I tried this code based on yours:
> > >
> > > with open("input") as fh:
> > > lines=fh.readlines()
> > >
> > > rows = len(lines)//3
> > >
> > > params=[]
> > > index=0
> > >
> > > for row in range(rows):
> > > params.append([lines[index],lines[index+1],lines[index+2]])
> > > index += 3
> > >
> > > for row in range(rows):
> > > print (row,":",params[row])
> > >
> > > For the exact input you gave, it produced this output:
> > >
> > > 0 : ['a1\n', 'b1\n', 'c1\n']
> > > 1 : ['a2\n', 'b2\n', 'c2\n']
> > > 2 : ['a3\n', 'b3\n', 'c3\n']
> > >
> > > Probably you'd want to get rid of those \n characters. (I don't know 
> > > how off-hand as I'm not often write in Python.)
> > >
> > > The last bit could also be written:
> > >
> > > for param in params:
> > > print (params)
> > >
> > > but I needed the row index.
> > >
> > To get rid of the '\n' (lineend) characters:
> > 
> > with open(file1) as fh:
> >  ParametersRaw = [line.strip() for line in fh.readlines()]
> > 
> > or, more succinctly..
> > 
> >   with open(file1) as fh:
> >   ParametersRaw = [line.strip() for line in fh]
> > 
> > Comprehensions are your friend.
> > 
> > Nathan

What is the significance of prefixing all your variables with "f"?  I've 
frequently seen people use it to signify the variable is a float, but you're 
using it for things that aren't floats.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pip does not work anymore

2015-11-23 Thread sohcahtoa82
On Sunday, November 22, 2015 at 11:59:13 PM UTC-8, Cecil Westerhof wrote:
> When I try to install something with pip2 I get:
> Traceback (most recent call last):
>   File "/usr/bin/pip2", line 9, in 
> load_entry_point('pip==7.1.2', 'console_scripts', 'pip2')()
>   File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 
> 558, in load_entry_point
> return get_distribution(dist).load_entry_point(group, name)
>   File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 
> 2682, in load_entry_point
> return ep.load()
>   File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 
> 2355, in load
> return self.resolve()
>   File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 
> 2361, in resolve
> module = __import__(self.module_name, fromlist=['__name__'], level=0)
>   File "/usr/lib/python2.7/site-packages/pip/__init__.py", line 15, in 
> 
> from pip.vcs import git, mercurial, subversion, bazaar  # noqa
>   File "/usr/lib/python2.7/site-packages/pip/vcs/subversion.py", line 9, 
> in 
> from pip.index import Link
>   File "/usr/lib/python2.7/site-packages/pip/index.py", line 30, in 
> 
> from pip.wheel import Wheel, wheel_ext
>   File "/usr/lib/python2.7/site-packages/pip/wheel.py", line 35, in 
> 
> from pip._vendor.distlib.scripts import ScriptMaker
>   File "/usr/lib/python2.7/site-packages/pip/_vendor/distlib/scripts.py", 
> line 14, in 
> from .compat import sysconfig, detect_encoding, ZipFile
>   File "/usr/lib/python2.7/site-packages/pip/_vendor/distlib/compat.py", 
> line 31, in 
> from urllib2 import (Request, urlopen, URLError, HTTPError,
> ImportError: cannot import name HTTPSHandler
> 
> With pip3 I get the same problem.
> 
> It looks like openSUSE has done an upgrade in which it disabled ssl2.
> How can I get pip2/3 working again?
> 
> -- 
> Cecil Westerhof
> Senior Software Engineer
> LinkedIn: http://www.linkedin.com/in/cecilwesterhof

SSL2 *should* be disabled.  It was deprecated nearly 20 years ago, replaced by 
SSL3, and even THAT has been deprecated.  SSL2 is incredibly insecure.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How To Create A Endles List Of Lists In Python...???

2015-11-20 Thread sohcahtoa82
On Friday, November 20, 2015 at 10:16:34 AM UTC-8, robert...@si.t-com.hr wrote:
> Dana petak, 20. studenoga 2015. u 18:16:52 UTC+1, korisnik Denis McMahon 
> napisao je:
> > On Fri, 20 Nov 2015 08:43:04 +0100, HKRSS wrote:
> > 
> > > Thanks In Advance, Robert...;)
> > 
> > Just keep appending child lists to parent list:
> > 
> > l = []
> > 
> > while True:
> >l.append([])
> > 
> > Until you run out of memory
> > 
> > But I think that this answer although it appears accurate to the question 
> > is not a solution for anything useful, because it will just use all the 
> > memory up. So perhaps you need to express your question in a better 
> > manner.
> > 
> > -- 
> > Denis McMahon, denismfmcma...@gmail.com
> 
> I Think That LISP Is Only Solution, I Wil Give Up Frpm Python...
> 
> Thanks, Robert...;)

Is There A Reason You're Starting Every Word With A Capital Letter?

I mean, really, you're going out of your way and expending extra effort to type 
incorrectly.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: variable scope of class objects

2015-10-19 Thread sohcahtoa82
On Monday, October 19, 2015 at 11:39:59 AM UTC-7, JonRob wrote:
> Hi,
> 
> I've having trouble understanding the self concept as it applies to
> variables.  I think I understand how it affects methods.
> 
> I haven't been able to fully grasp the scope of class variables and
> the effect of the "self"  to the scope of the variable.
> 
> I (think) I understand that in the below case, the word self could be
> replaced with "BME280" to explicitly call out a variable.
> 
> But even still I don't know how explicit call out effects the scope of
> a variable.
> 
> The below pseudo code is distilled from my 1st attempt at a functional
> Python program on the RasPi.
> 
> My questions are:
> What is the scope of class variables?
> does the self. prefix modify this scope?
> 
> Thanks
> 
> Regards
> 
> JonRob
> 
> 
> 
> 
> #!/usr/bin/python
> # -- developed using Python 2.7.3
> 
> class BME280:
> 
> # all the below are class variables
> # those preceded by an underscore are predefined to some constant
> # those without the underscore are to be "working" variables.
> 
> _regT1   = 0x88
> _regH6   = 0xE7
> _coeff_P2= 0x82
> _coeff_P6= 0x32
> 
> filter   = 0#should these be "self"?
> t_fine   = 0
> 
> def __init__(self, address=0x76, debug=True):
> self.i2c = Adafruit_I2C(address)
> self.address = address
> self.debug = debug
> 
> def pressure_calc(self):
> var1 = self.i2c.readU16(self._regT1,False)
> p = (1048576.0 - var1) * _coeff_P2
> return p
> 
> def read_pressure(self):  #called  by main application
> pressure_hPa = pressure_calc(self) /10 
> # apply compensation
> return pressure_hPa

Class variables are accessible without creating an instance of a class.  Also, 
changing the value of a class variable affects ALL instances of that class.  
This is because the variable belongs to the class itself, not any of the 
instances of that class.

"self" is used to tell the interpreter that the variable/function you are 
accessing is a member of an instance of that class.

Here's an example:

class MyObject(object):
count = 0
def __init__(value):
MyObject.count += 1
self.value = value

def printStuff():
print("My value is ", self.value)

print(MyObject.count)   # This will print 0
a = MyObject('a')
print(MyObject.count)   # This will print 1
print(a.count)  # This will also print 1
a.printStuff()  # This will print "My value is a"
b = MyObject('b')
print(a.count)  # This will print 2
print(b.count)  # This will also print 2
b.printStuff()  # This will print "My value is b"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TCP sockets python timeout public IP adresss

2015-10-16 Thread sohcahtoa82
On Friday, October 16, 2015 at 2:44:53 AM UTC-7, lucasfneves14 wrote:
> How did you do it?

I took the advice of just being myself.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pyarmor, guard your python scripts

2015-10-05 Thread sohcahtoa82
On Thursday, September 17, 2015 at 10:55:19 PM UTC-7, Jondy Zhao wrote:
> On Friday, September 18, 2015 at 11:06:25 AM UTC+8, Ben Finney wrote:
> > Jondy Zhao  writes:
> > 
> > > For example, I develop a game by python. What I want to do is that the
> > > player or the agent could not simply copy the game to others. For the
> > > player or the agent, they needn't research the game.
> > 
> > Deciding for the customer what they may not do, on their own computer,
> > is quite hostile. Please don't enable such restrictions.
> > 
> 
> This is only one possible way to distribute encrypted scripts. As I thought 
> the user of Pyarmor would be the producer of commercial software, so they 
> could bind their license file to netcard, harddisk, cpu, etc.
> 
> > -- 
> >  \   "We must find our way to a time when faith, without evidence, |
> >   `\disgraces anyone who would claim it." --Sam Harris, _The End of |
> > _o__) Faith_, 2004 |
> > Ben Finney

DRM does not prevent piracy.

End of story.

The only thing DRM does is piss off your legitimate users by forcing them to 
jump through hoops if they happen to upgrade or replace their computer.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Check if a given value is out of certain range

2015-09-30 Thread sohcahtoa82
On Tuesday, September 29, 2015 at 1:33:23 PM UTC-7, Mark Lawrence wrote:
> On 29/09/2015 17:48, Rob Gaddi wrote:
> > On Tue, 29 Sep 2015 10:16:04 +0530, Laxmikant Chitare wrote:
> >
> >> Hi,
> >>
> >> I know there is an elegant way to check if a given value is within
> >> certain range.
> >> Example - To check if x is between zero and ten, I can do 0 < x 10.
> >>
> >> Is there any similar elegant way to check if a value is out of certain
> >> range?
> >> Example - To check if x is either less than zero or greater than ten?
> >> Right now I am using x < 0 or x > 10.
> >>
> >> Regards,
> >> Laxmikant
> >
> > not (0 <= x <= 10)
> >
> 
> Yuck.
> 
> -- 
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
> 
> Mark Lawrence

What is so "yuck" about that?  What would you do instead?  It seems like the 
best solution to me.  Easy to read, fast to execute.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Idiosyncratic python

2015-09-24 Thread sohcahtoa82
On Wednesday, September 23, 2015 at 11:02:38 PM UTC-7, Steven D'Aprano wrote:
> I was looking at an in-house code base today, and the author seems to have a 
> rather idiosyncratic approach to Python. For example:
> 
> 
> for k, v in mydict.items(): 
> del(k)
> ...
> 
> 
> instead of the more obvious
> 
> for v in mydict.values(): 
> ...
> 
> 
> 
> What are your favorite not-wrong-just-weird Python moments?
> 
> 
> 
> -- 
> Steve

I used to work with a guy that would put the verb at the END of a function 
name, rather than the beginning.  For example, rather then 
"GetSupportedVersion", he'd use "SupportedVersionGet".  Of course, I know 
plenty of people here will say it should be "get_supported_version", but that's 
another discussion entirely.

Another guy would frequently use "Grab" instead of "Get".  The fact that he 
used a different verb than the common convention though wasn't NEARLY as 
infuriating as the fact that he was inconsistent about it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A little test for you Guys

2015-09-22 Thread sohcahtoa82
On Tuesday, September 22, 2015 at 11:45:00 AM UTC-7, Lj Fc wrote:
> you have 10 minutes Good luck!!
> 
> 
> 1. What is PEP8 ?
> 
> 2. What are the different ways to distribute some python source code ?
> 
> 2 Lists
> 
> Let's define the function plural :
> 
> def plural(words):
> plurals = []
> for word in words:
>plurals.append(word + 's')
> return plurals
> 
> for word in plural(['cabagge','owl','toy']):
> print word
> 
> Question : How could the code of the function plural be optimised?
> 
> 3 Dictionaries
> 
> Here are two dictionnaries :
> 
> input = {
> 'foo1': 'bar1',
> 'chose': 'truc',
> 'foo2': 'bar2',
> }
> output = {
> 'bar1': 'foo1',
> 'truc': 'chose',
> 'bar2': 'foo2'
> }
> 
> Question : Propose a function that returns output when you provide input ?
> 
> 4 Iterators
> 
> Let's consider this program :
> 
> def program_1():
> yield 1
> yield 2
> yield 3
> 
> g = program_1()
> a = list(g)
> b = list(g)
> c = g()
> 
> Question : At the end of the program,
> 
> 1. What is the type of g ?
> 2. What is the value of a ?
> 3. What is the value of b ?
> 4. What is the value of c ?
> 
> 5 Decorators
> 
> Let's consider now :
> 
> def str2print(f):
> def str2print_wrap(*args, **kwargs):
> """wrapper"""
> s = f(*args, **kwargs)
> print s
>return str2print_wrap
> 
> def hello(s):
> """ Return "Hello $s" """
> return "%s %s" % ("Hello", s)
> 
> Questions :
> 
> 1. Decorate the method 'hello' with 'str2printf' and write the corresponding 
> code.
> 2. What is the effect of the decorator on a call to the new method 'hello' ?
> 3. What is the return value of hello.__doc__

Pretty sure this guy is asking us to do his homework.  :-P
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Problem configuring apache to run python cgi on Ubuntu 14.04

2015-09-21 Thread sohcahtoa82
On Monday, September 21, 2015 at 11:41:54 AM UTC-7, tropical...@gmail.com wrote:
> Hello everybody,
> 
> I installed the LAMP stack on in Ubuntu, but I am having
> problems configuring Apache to run python CGI scripts.
> 
> I ran:
> sudo a2enmod cgi
> 
> I added to apache2.conf
> 
> Options +ExecCGI
> AddHandler cgi-script .py
> 
> 
> I created index.py:
> #!/usr/bin/env python
> # -*- coding: UTF-8 -*-# enable debugging
> import cgitb
> 
> cgitb.enable()
> print("Content-Type: text/html;charset=utf-8")
> print("Hello World!")
> 
> But it is still not working.
> 
> Can anybody help me out?
> 
> Thanks in advance.

"It isn't working" is about as useful as telling a mechanic "My car doesn't 
work" without giving details on what exactly is happening.

What exactly isn't working?  What error message are you getting?

The first thing I would check is to make sure the permissions on index.py are 
set to allow execution.  It is easy to forget to do that.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Bug!

2015-08-21 Thread sohcahtoa82
On Friday, August 21, 2015 at 3:42:36 PM UTC-7, hamilton wrote:
 On 8/21/2015 1:41 PM, Chris Angelico wrote:
  Python 3.5 does not support Windows XP.
 
 Is there a simple explanation for this ?
 
 Or is it just is.

I have no relationship with the Python developers, but I would say that running 
such an old operating system is simply irresponsible due to security issues and 
should be discouraged in any way possible.

Windows XP is 14 years old.  In the computing world, that's *ancient*.  It's 
time to upgrade and join the modern world.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: except block isn't catching exception

2015-08-07 Thread sohcahtoa82
On Thursday, August 6, 2015 at 5:46:19 PM UTC-7, Chris Angelico wrote:
 On Fri, Aug 7, 2015 at 10:34 AM,  sohcahto...@gmail.com wrote:
  Despite my except KeyboardInterrupt, the KeyboardInterrupt forced by the 
  thread.interrupt_main() in the worker thread isn't being caught.
 
  Other things worth noting is that the exception takes about 3 seconds after 
  the call to thread.interrupt_main().  It appears to not actually happen 
  until the sock.accept() times out.  If the call to sock.settimeout(5) is 
  removed, the KeyboardInterrupt never appears and flow is still blocked on 
  the sock.accept().
 
  My Python version is 2.7.3.  I know its out of date, but I don't really 
  have a choice.
 
 As far as I know, the only effect of thread.interrupt_main() is to set
 a flag saying Hey main thread, next time you go checking for these
 things, there's a KeyboardInterrupt waiting for you. It doesn't
 actually send an OS-level signal, which means it cannot interrupt a
 blocking call. So you have a few choices:
 
 1) Shorten the timeout on sock.accept() to an (if you'll excuse the
 pun) acceptable delay, and then simply check a flag. Something like
 this:
 
 interrupt = False
 while not interrupt:
 try:
 connection, _ = sock.accept()
 except socket.timeout:
 # On timeout, check flag and keep sleeping
 pass
 
 If you wish to also have an actual timeout, you could monitor that separately.
 
 2) Instead of blocking on sock.accept directly, have another event
 which the other thread can raise, which will wake the main thread. You
 could use select.select() for this.
 
 3) Bury the details of select.select() away behind a nice framework
 like asyncio, merge your two threads, and run everything through a
 back-end event loop.
 
 4) Use separate processes, and signal the interrupt using an OS-level
 notification (on Unix systems, SIGINT; on Windows, there's an
 equivalent called BreakSignal or something). This will break out of
 the underlying system call that handles accept().
 
 thread.interrupt_main() is similar to just setting a global that you
 periodically check, except that the periodic check is handled for you
 by the system. That's really all.
 
 ChrisA

I'll probably go for the first solution.  It's the simplest, and simple is 
usually good.  In my application, there aren't going to be any consequences for 
the main thread not unblocking *immediately* when a worker thread requests it.

Though I still doesn't understand why the exception isn't caught when I'm 
explicitly trying to catch it.  I even tried changing the try/except block to 
this:

try:
connection, _ = sock.accept()
except KeyboardInterrupt:
print 'KeyboardInterrupt caught!'
except socket.timeout:
print 'Socket timeout caught!'
except:
print 'other exception caught!'
finally:
print 'finally!'

The result prints:

Interrupting main
main interrupted!
finally!
Traceback (most recent call last): 
  File exception_test.py, line 23, in module 
connection, _ = sock.accept() 
KeyboardInterrupt
-- 
https://mail.python.org/mailman/listinfo/python-list


except block isn't catching exception

2015-08-06 Thread sohcahtoa82
I've run into strange behavior involving a blocking call to a socket accept() 
on the main thread and thread.interrupt_main() being called on a worker thread. 
 Here's my code:

# BEGIN exception_test.py
import socket
import thread
import threading
import time


def worker():
time.sleep(2)
print 'Interrupting main'
thread.interrupt_main()
print 'main interrupted!'

sock = socket.socket()
sock.bind(('127.0.0.1', 8080))
sock.settimeout(5)
sock.listen(0)

t = threading.Thread(target=worker)
t.start()

try:
connection, _ = sock.accept()
except KeyboardInterrupt:
print 'KeyboardInterrupt!'
except socket.timeout:
print 'Socket timeout!'

print 'exiting'

# END exception_test.py

I would expect this output:

Interrupting main
main interrupted!
KeyboardInterrupt caught!
exiting

But instead, I'm seeing this:

Interrupting main
main interrupted!
Traceback (most recent call last):
  File exception_test.py, line 23, in module
connection, _ = sock.accept()
KeyboardInterrupt

Despite my except KeyboardInterrupt, the KeyboardInterrupt forced by the 
thread.interrupt_main() in the worker thread isn't being caught.

Other things worth noting is that the exception takes about 3 seconds after the 
call to thread.interrupt_main().  It appears to not actually happen until the 
sock.accept() times out.  If the call to sock.settimeout(5) is removed, the 
KeyboardInterrupt never appears and flow is still blocked on the sock.accept().

My Python version is 2.7.3.  I know its out of date, but I don't really have a 
choice.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Uninstall

2015-08-04 Thread sohcahtoa82
On Tuesday, August 4, 2015 at 7:29:29 AM UTC-7, Grant Edwards wrote:
 On 2015-08-04, milos zorica miloshzor...@gmail.com wrote:
 
  you can't fully uninstall python from OSX, linux, BSD as there are many
  python dependent system tools
 
 Well, technically you _can_ uninstall Python if you really want, but
 all sorts of things will stop working.  In some cases, it's very hard
 to recover from that situation.  Among the things that will stop
 working on some flavors of Linux are the system utilities you normally
 use to install things like Python.
 
 -- 
 Grant Edwards   grant.b.edwardsYow! World War III?
   at   No thanks!
   gmail.com

milos: You can't uninstall Python because it will break things
Grant: Actually, you CAN uninstall Python, but it will break things

I really fucking hate how pedantic some of the people on this mailing list are.

milos wasn't wrong.  You just chose to take his message too literally.  I 
thought it was pretty clear that when milos said can't, he really meant 
shouldn't.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Integers with leading zeroes

2015-07-21 Thread sohcahtoa82
On Tuesday, July 21, 2015 at 10:22:44 AM UTC-7, Antoon Pardon wrote:
 On 07/19/2015 07:39 AM, Steven D'Aprano wrote:
  In Python 2, integer literals with leading zeroes are treated as octal, so
  09 is a syntax error and 010 is 8.
  
  This is confusing to those not raised on C-style octal literals, so in
  Python 3 leading zeroes are prohibited in int literals. Octal is instead
  written using the prefix 0o, similar to hex 0x and binary 0b.
  
  Consequently Python 3 makes both 09 and 010 a syntax error.
  
  However there is one exception: zero itself is allowed any number of leading
  zeroes, so 0 is a legal way to write zero as a base-10 int literal.
  
  Does anyone use that (mis)feature?
  
 
 Yes. I like to sometime write numbers with leading zeros.
 Sometimes these numbers represent codeblocks of a fixed
 number of digits. Always writing those numbers with this
 number of digits helps being aware of this. It is also
 easier for when you need to know how many leading zero's
 such a number has.

IMO, leading zeroes just looks like visual noise, and if I wanted to align 
numbers, I'd just use spaces.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Integers with leading zeroes

2015-07-21 Thread sohcahtoa82
On Tuesday, July 21, 2015 at 11:07:43 AM UTC-7, Emile van Sebille wrote:
 On 7/21/2015 10:58 AM, sohcahto...@gmail.com wrote:
 
  IMO, leading zeroes just looks like visual noise, and if I wanted to align 
  numbers, I'd just use spaces.
 
 
 Aligning numbers using spaces doesn't always align -- using zeros does.
 
 Emile

You've got me confused.  They should align just fine if you're using a 
fixed-width font.

If you're not using a fixed-width font in your programming, then I don't know 
what to say to you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Integers with leading zeroes

2015-07-21 Thread sohcahtoa82
On Tuesday, July 21, 2015 at 11:38:53 AM UTC-7, sohca...@gmail.com wrote:
 On Tuesday, July 21, 2015 at 11:07:43 AM UTC-7, Emile van Sebille wrote:
  On 7/21/2015 10:58 AM, sohcahto...@gmail.com wrote:
  
   IMO, leading zeroes just looks like visual noise, and if I wanted to 
   align numbers, I'd just use spaces.
  
  
  Aligning numbers using spaces doesn't always align -- using zeros does.
  
  Emile
 
 You've got me confused.  They should align just fine if you're using a 
 fixed-width font.
 
 If you're not using a fixed-width font in your programming, then I don't know 
 what to say to you.

I should probably state that I may use leading zeroes when using hexadecimal 
numbers.  For example, I might write 0x000ABCDE, rather than 0xABCDE, but 
that's only if I'm using a lot of 32-bit values.  If I only care about a single 
byte, I will use 0x01, for example.

But for base-10, I would never use leading zeroes.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to play

2015-07-20 Thread sohcahtoa82
On Sunday, July 19, 2015 at 12:04:26 PM UTC-7, Aron Barsam wrote:
 i have trouble trying to play python please can you respond soon 

...

 play python

http://i.imgur.com/x2KwTbw.jpg
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how do you play python because i have gone on the website but i haven't managed to code?

2015-07-17 Thread sohcahtoa82
On Thursday, July 16, 2015 at 12:31:04 PM UTC-7, Aron Barsam wrote:
 how do you play python because i have gone on the website but i haven't 
 managed to code?

http://i.imgur.com/x2KwTbw.jpg
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Proposed keyword to transfer control to another function

2015-07-17 Thread sohcahtoa82
On Friday, July 17, 2015 at 12:17:55 AM UTC-7, Antoon Pardon wrote:
 On 07/17/2015 01:46 AM, Chris Angelico wrote:
  Open for bikeshedding: What should the keyword be? We can't use
  exec, which would match Unix and shell usage, because it's already
  used in a rather different sense in Python. Current candidates:
  transfer, goto, recurse, and anything else you suggest.
 
 I propose the combination return from. I think it is similar enough
 with yield from to justify this and it also won't need an extra
 keyword, so no programs will be broken because they used transfer,
 goto or whatever other new keyword as an identifier.
 
 Should there be someone who is willing to spend time on this, I wish
 him all luck and strength he can find. I think it would be best if
 it was done by someone who is interrested in using this in his own
 programs. Because it is all very fine talking about the pro and
 cons here and I certainly would use it, the question is, how wide
 spread would the use become and is it worth the time and effort to
 introduce it. If future use turns out to be disappointing such a
 coder can at least think of it as something that was useful for
 himself.
 
 -- 
 Antoon.

return from or yield from looks too much like a COMEFROM 
instruction/statement.

https://en.wikipedia.org/wiki/COMEFROM
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Idle Not Working.

2015-07-08 Thread sohcahtoa82
Help us help you.  every time I try to bring up Idle I cannot does not tell 
us the problem.

Do you get error messages?  What do they say?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Idle Not Working.

2015-07-08 Thread sohcahtoa82
On Wednesday, July 8, 2015 at 2:12:29 PM UTC-7, Mark Lawrence wrote:
 On 08/07/2015 19:44, sohcahto...@gmail.com wrote:
  Help us help you.  every time I try to bring up Idle I cannot does not 
  tell us the problem.
 
  Do you get error messages?  What do they say?
 
 
 Would you please be kind enough to quote context when replying. 
 Pythonistas might be smart, but apart from myself and Steven D'Aprano 
 I'm not aware of anyone who can read minds.  Thank you.
 
 -- 
 My fellow Pythonistas, ask not what our language can do for you, ask
 what you can do for our language.
 
 Mark Lawrence

Oops.  I usually do, but for some reason Google Groups didn't this time.  My 
apologies.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Classic OOP in Python

2015-06-17 Thread sohcahtoa82
On Wednesday, June 17, 2015 at 1:39:31 PM UTC-7, Marko Rauhamaa wrote:
 Ned Batchelder n...@nedbatchelder.com:
 
  TDD is about writing tests as a way to design the best system, and
  putting testing at the center of your development workflow. It works
  great with Python even without interfaces.
 
 I wonder how great it really is. Testing is important, that's for sure,
 but to make it a dogmatic starting point of development is not that
 convincing.
 
 The way it was explained to me was that in TDD you actually don't write
 code to any requirements or design: you simply do the least to pass the
 tests. Thus, say you need to write a program that inputs a string and
 outputs the same string surrounded by parentheses (the requirement), the
 starting point might be this test case:
 
- run the program
- give it the word hello as input
- check that the program prints out (hello)
 
 The right TDD thing would be to satisfy the test with this program:
 
input()
print((hello))
 
 That *ought* to be the first version of the program until further test
 cases are added that invalidate it.
 
 
 Another interesting ism I have read about is the idea that the starting
 point of any software project should be the user manual. The developers
 should then go and build the product that fits the manual.
 
 
 Marko

I had a Java class where we had to learn TDD, and that's the way TDD was taught 
to us, and I hated it.  We watched a video of this guy explaining TDD with a 
hat that was red on the front and green on the back.  It involved writing a 
simple failing unit test, then write code to fix it, then refactor the tests 
and/or code.

As an in-class exercise, we had to write an implementation of Conway's Game of 
Life.  I threw TDD out the window and just wrote the damn program in under 15 
minutes, then another 10 minutes to write unit tests that tested every possible 
code branch and several invalid inputs.  Meanwhile, the people doing TDD the 
right way didn't even have a complete program after over an hour.

The brand of TTD we were taught would end up multiplying development time by at 
least a factor of 3, and by the time you were done, at least 75% of the tests 
you had written will have been removed due to rampant refactoring.

IMO, that kind of TTD is an utter waste of time.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Classic OOP in Python

2015-06-17 Thread sohcahtoa82
On Wednesday, June 17, 2015 at 12:21:32 PM UTC-7, Jason P. wrote:
 Hello Python community.
 
 I come from a classic background in what refers to OOP. Mostly Java and PHP 
 ( 5.3). I'm used to abstract classes, interfaces, access modifiers and so on.
 
 Don't get me wrong. I know that despite the differences Python is fully 
 object oriented. My point is, do you know any book or resource that explains 
 in deep the pythonic way of doing OOP?
 
 For example, I'm gonna try to develop a modest application from ground up 
 using TDD. If it had been done in Java for instance, I would made extensive 
 use of interfaces to define the boundaries of my system. How would I do 
 something like that in Python?
 
 
 Many thanks!

You don't need interfaces with Python.  Duck typing makes that all possible.  
This is perfectly valid:

class Dog(object):
def move(self):
print Dog is moving

class Car(object):
def move(self):
print Car is moving

things = [Dog(), Car()]
for thing in things:
thing.move()

Despite Dog and Car being completely different classes with no relationship 
with each other, the code runs just fine.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Testing random

2015-06-16 Thread sohcahtoa82
On Tuesday, June 16, 2015 at 3:01:06 PM UTC-7, Thomas 'PointedEars' Lahn wrote:
 Ned Batchelder wrote:
 
  [...]
  This is done empirically, by producing `nseq` sequences of
  `nrolls` rolls of the die.  Each sequence is examined to
  see if it has a zero.  The total number of no-zero
  sequences divided `nseq` is the probability.
 
 No, it is not.  It is the relative frequency for *this* number of trials and 
 *this* run of the experiment.
 
  
  no_zeros = 0
  for _ in xrange(nseq):
  seq = die_rolls(nrolls)
  if not any_zeros(seq):
  no_zeros += 1
  return float(no_zeros)/nseq
  
  for n in range(10, 101, 10):
  # Calculate the probability of getting no zeros by trying
  # it a million times.
  prob = probability_of_no_zero(n, 100)
  print n = {:3d}, P(no zero) = {:.8f}.format(n, prob)
  
  
  
  Running this gives:
  
  $ pypy testrandom.py
  n =  10, P(no zero) = 0.34867300
  n =  20, P(no zero) = 0.12121900
  n =  30, P(no zero) = 0.04267000
  n =  40, P(no zero) = 0.01476600
  n =  50, P(no zero) = 0.00519900
  n =  60, P(no zero) = 0.00174100
  n =  70, P(no zero) = 0.00061600
  n =  80, P(no zero) = 0.00020600
  n =  90, P(no zero) = 0.6300
  n = 100, P(no zero) = 0.2400
  
  
  As n increases, the probability of having no zeros goes down.
 
 Your programmatic proof, as all the other intuitive-empirical proofs, 
 and all the other counter-arguments posted before in this thread, is flawed.  
 As others have pointed out at the beginning of this thread, you *cannot* 
 measure or calculate probability or determine randomness programmatically 
 (at least not with this program).  I repeat: Probability is what relative 
 frequency (which you can measure) *approaches* for *large* numbers.  100 is 
 anything but large, to begin with.  What is large depends on the 
 experiment, not on the experimentator.  And with independent events, the 
 probability for getting zero does not increase because you have been getting 
 non-zeros before.  It simply does not work this way.

Nobody is arguing that.  You're arguing against something that nobody is 
suggesting.


 
 If you had read the article I referred you to, you would have known that 
 this approach, this program, is bogus.  I see no logic to continue here as 
 long as you do not realize and recognize the Gambler's fallacy on which all 
 arguments presented so far, including yours, are based.  I would only be 
 wasting more precious free time by repeating myself in one way or another.


If the odds of getting a 0 is 1 out of 10, then the odds of NOT getting a zero 
is 9/10.  Which means the odds of picking 10 numbers and not getting ANY zeroes 
is (9/10)^10, which is approximately 0.35.  This has NOTHING to do with the 
Gambler's Fallacy.



 
 This should give you pause: In real mathematics, events with zero 
 probability can occur.

Nobody will disagree with that.  The probability of me winning the lottery is 
zero if I don't buy a ticket.

 
 -- 
 PointedEars
 
 Twitter: @PointedEars2
 Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Testing random

2015-06-16 Thread sohcahtoa82
On Tuesday, June 16, 2015 at 4:48:36 PM UTC-7, Thomas 'PointedEars' Lahn wrote:
 Ned Batchelder wrote:
 
  On Tuesday, June 16, 2015 at 6:01:06 PM UTC-4, Thomas 'PointedEars' Lahn
  wrote:
  Your programmatic proof, as all the other intuitive-empirical proofs,
  and all the other counter-arguments posted before in this thread, is
  flawed. As others have pointed out at the beginning of this thread, you
  *cannot* measure or calculate probability or determine randomness
  programmatically (at least not with this program).
  
  You *can* estimate probability with a program, which is what is happening
  here.
 
 No.  Just no.
 
  I repeat: Probability is what relative
  frequency (which you can measure) *approaches* for *large* numbers.  100
  is anything but large, to begin with.
  
  The number of trials in this program is not 100, it is 1 million.  You
  seem uninterested in trying to understand.
 
 It still would _not_ a measure or a calculation of *probability*.  So much 
 for uninterested in trying to understand.
  
  What is large depends on the experiment, not on the experimentator.  
  And with independent events, the probability for getting zero does not 
  increase because you have been getting non-zeros before.  It simply does 
  not work this way.
  
  Again, if you look at the code, you'll see that we are not talking about
  the probability of getting a zero on the next roll.  We are talking about
  the probability of getting no zeros in an N-roll sequence.  I have no idea 
  how you have misunderstood this for so long.
 
 You do not understand that it boils down to the same problem.

Actually, no, they're not.  They're entirely different problems.  What are the 
odds of getting 8 zeros in a row? is a *COMPLETELY* different question from 
What are the odds of getting a zero on the next roll?


The 
 probability of only having sons is _not_ greater than that of having
 sons and one daughter or vice-versa.  And for that it does _not_ matter
 how many children you have *because* it does _not_ matter how many
 children you had before.  The probability for a boy or a girl is *always*
 the same.  You are _not_ due for a boy if you have many girls, and not for a 
 girls if you have many boys.  But that is precisely what your flawed logic 
 is implying.

Yes, we all know what the gambler's fallacy is, but that's not what anyone is 
arguing.

If you pick 8 random numbers between 0 and 9 (inclusive), then the odds of 
getting all zeros is (1/10)^8.  Do you agree with that?

The odds of getting NO zeros is (9/10)^8.  Do you agree with that?

Note that NEITHER of these scenarios say anything about a pre-condition.  The 
first question is *NOT* asking If you picked 7 random numbers between 0 and 9 
and got 0 for all 7, what are the odds of getting another 0?  The answer to 
that is obviously 1/10, and anybody arguing something else would certainly be 
committing the Gambler's fallacy.

 
 Learn probability theory, and use a dictionary in Python when you want to 
 count random hits.

I know enough probability theory to know that you're either wrong or you keep 
changing the problem to something nobody else has said in order to think you're 
right.

 
 -- 
 PointedEars
 
 Twitter: @PointedEars2
 Please do not cc me. / Bitte keine Kopien per E-Mail.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating .exe file in Python

2015-06-15 Thread sohcahtoa82
On Monday, June 15, 2015 at 5:08:58 AM UTC-7, Mark Lawrence wrote:
 On 15/06/2015 12:42, subhabrata.bane...@gmail.com wrote:
  Dear Group,
 
  I am trying to learn how to create .exe file for Python. I tried to work 
  around
  http://www.py2exe.org/index.cgi/Tutorial of Py2exe. The sample program went 
  nice.
  But if I try to make exe for larger programs with methods and classes I am 
  getting error.
 
  If any one of the esteemed members may kindly suggest how to work out.
  I am using Python2.7+ on Windows 7 Professional.
 
  Regards,
  Subhabrata Banerjee.
 
 
 I'm awfully sorry but both my main and backup crystal balls are being 
 repaired due to overuse.  I am getting error is about as much use as a 
 wet fart in a thunderstorm.  So given that I never much liked guessing 
 games anyway as I'm not much good at them, how about telling us 
 precisely what error you're getting.  In that way one or more of our 
 most esteemed colleagues might be able to help.
 
 -- 
 My fellow Pythonistas, ask not what our language can do for you, ask
 what you can do for our language.
 
 Mark Lawrence

as much use as a wet fart in a thunderstorm

I gotta remember that one.  :-D

But on topic...I really don't understand what makes people think we can 
*possibly* help them by only saying I'm getting an error without saying what 
the error is.

I mean, even before I ever became a programmer, I knew that if I needed help 
fixing something, I needed to give as much information as I could.  Exact error 
messages, detailed description of what I was doing, what I've done to try to 
fix it, etc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Set a flag on the function or a global?

2015-06-15 Thread sohcahtoa82
On Monday, June 15, 2015 at 4:57:53 PM UTC-7, Steven D'Aprano wrote:
 I have a function in a module which is intended to be used by importing 
 that name alone, then used interactively:
 
 from module import edir
 edir(args)
 
 
 edir is an enhanced version of dir, and one of the enhancements is that 
 you can filter out dunder methods. I have reason to believe that people 
 are split on their opinion on whether dunder methods should be shown by 
 default or not: some people want to see them, others do not. Since edir 
 is meant to be used interactively, I want to give people a setting to 
 control whether they get dunders by default or not.
 
 I have two ideas for this, a module-level global, or a flag set on the 
 function object itself. Remember that the usual way of using this will be 
 from module import edir, there are two obvious ways to set the global:
 
 import module
 module.dunders = False
 
 # -or-
 
 edir.__globals__['dunders'] = False
 
 
 Alternatively, I can use a flag set on the function object itself:
 
 edir.dunders = False
 
 
 Naturally you can always override the default by explicitly specifying a 
 keyword argument edir(obj, dunders=flag).
 
 Thoughts and feedback? Please vote: a module global, or a flag on the 
 object? Please give reasons, and remember that the function is intended 
 for interactive use.
 
 
 -- 
 Steven D'Aprano

Using a keyword argument for the edir function is the most intuitive and easy 
to read, IMO.

Also, if two people are working on the same script, it could create problems if 
one person wants to filter them, but the other doesn't.  That would create a 
state that they would both have to monitor and keep setting back and forth, 
rather than each one just setting an argument on their calls.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Testing random

2015-06-12 Thread sohcahtoa82
On Friday, June 12, 2015 at 3:12:26 PM UTC-7, Thomas 'PointedEars' Lahn wrote:
 Ian Kelly wrote:
 
  [...] Thomas 'PointedEars' Lahn [...] wrote:
  Ian Kelly wrote:
  The probability of 123456789 and 1 are equal. The probability
  of a sequence containing all nine numbers and a sequence containing
  only 1s are *not* equal.d
  There is a contradiction in that statement.  Can you find it?
  
  Yes. I phrased my statement as if I were addressing a rational
  individual, in clear contradiction of the current evidence.
  
  Seriously, if you reject even the statement I made above, in spite of
  all the arguments that have been advanced in this thread, in spite of
  the fact that this is very easy to demonstrate empirically, then I
  don't think there's any fertile ground for discussion here.
 
 /Ad hominem/ when out of arguments.  How typical.
 
 Do you deny that 123456789 *is* a sequence containing all nine numbers 
 (digits, really), and that 1 *is* a sequence containing only 1s?
 
 Do you deny that therefore your second sentence contradicts the first one?
 
 -- 
 PointedEars
 
 Twitter: @PointedEars2
 Please do not cc me. / Bitte keine Kopien per E-Mail.

I'm struggling to see the contradiction here.

Yes, 123456789 is a sequence containing all nine numbers.  And as someone else 
said, 123456798 is also a sequence containing all numbers.  987654321 contains 
all numbers.  There are 9*8*7*6*5*4*3*2*1 (Usually expressed as 9!, and equal 
to 362,880) distinct ways to order nine numbers.

However, there is only ONE way to order a series of all 1s.

There's no contradiction here.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: OT ish Blocking telemarketers

2015-06-12 Thread sohcahtoa82
On Friday, June 12, 2015 at 3:23:32 PM UTC-7, Seymore4Head wrote:
 Is there a program what runs on Windows that uses a national blacklist
 to block phone calls?

Are you talking about a Windows Phone?  Windows for a PC doesn't make phone 
calls unless that's a new feature that I don't know about.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How may I Integrate Python Code with REST

2015-06-12 Thread sohcahtoa82
On Friday, June 12, 2015 at 10:52:30 AM UTC-7, subhabrat...@gmail.com wrote:
 Dear Group,
 
 I wrote a Python code. In the code there are two modules where we may insert 
 data from outside. They are updating some training module and updating index. 
 As a standalone code this is working fine. 
 
 I need to port this code to REST. I tried to learn Flask. My Practice for 
 Flask is okay. I can put,get,delete. 
 
 But how may I proceed I am not getting much idea. I bit new in REST. 
 If any one of the esteemed members may kindly provide an idea how may I 
 proceed? 
 
 Regards,
 Subhabrata Banerjee.

It is slightly unclear what you're asking.  REST isn't a programming language 
or a module or anything like that.  It is a software architecture style.

Flask is often used for implementing a REST interface.  If you understand how 
to use Flask, you're basically there already.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: zip as iterator and bad/good practices

2015-06-12 Thread sohcahtoa82
On Friday, June 12, 2015 at 4:44:08 PM UTC-7, Terry Reedy wrote:
 On 6/12/2015 4:34 PM, Laura Creighton wrote:
  The real problem is removing things from lists when you are iterating
  over them, not adding things to the end of lists.
 
 One needs to iterate backwards.
 
   ints = [0, 1, 2, 2, 1, 4, 6, 5, 5]
 
   for i in range(len(ints)-1, -1, -1):
   if ints[i] % 2:
   del ints[i]
   
   ints
 [0, 2, 2, 4, 6]
 
 But using a list comp and, if necessary, copying the result back into 
 the original list is much easier.
 
   ints = [0, 1, 2, 2, 1, 4, 6, 5, 5]
   ints[:] = [i for i in ints if not i % 2]
   ints
 [0, 2, 2, 4, 6]
 
 
 -- 
 Terry Jan Reedy

On the second line of your final solution, is there any reason you're using 
`ints[:]` rather than just `ints`?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: zip as iterator and bad/good practices

2015-06-12 Thread sohcahtoa82
On Friday, June 12, 2015 at 5:27:21 PM UTC-7, Chris Angelico wrote:
 On Sat, Jun 13, 2015 at 10:02 AM,  sohcahto...@gmail.com wrote:
ints = [0, 1, 2, 2, 1, 4, 6, 5, 5]
ints[:] = [i for i in ints if not i % 2]
ints
  [0, 2, 2, 4, 6]
 
 
  --
  Terry Jan Reedy
 
  On the second line of your final solution, is there any reason you're using 
  `ints[:]` rather than just `ints`?
 
 If you use ints = [...], it rebinds the name ints to the new list.
 If you use ints[:] = [...], it replaces the entire contents of the
 list with the new list. The two are fairly similar if there are no
 other references to that list, but the replacement matches the
 mutation behaviour of remove().
 
 def just_some(ints):
 ints[:] = [i for i in ints if not i % 2]
 
 ChrisA

Ah that makes sense.  Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: OT ish Blocking telemarketers

2015-06-12 Thread sohcahtoa82
On Friday, June 12, 2015 at 5:03:25 PM UTC-7, Seymore4Head wrote:
 On Fri, 12 Jun 2015 15:57:53 -0700 (PDT), sohcahto...@gmail.com wrote:
 
 On Friday, June 12, 2015 at 3:23:32 PM UTC-7, Seymore4Head wrote:
  Is there a program what runs on Windows that uses a national blacklist
  to block phone calls?
 
 Are you talking about a Windows Phone?  Windows for a PC doesn't make phone 
 calls unless that's a new feature that I don't know about.
 
 I guess I should have said...A program that runs on Windows
 that uses a modem and a national blacklist to block phone calls.

On a home telephone, you can't block phone calls client-side so-to-speak.  At 
best, you can have a phone that can choose not to ring based on the number 
calling, but in my experience, most telemarketers block their caller ID from 
showing up so that wouldn't work anyways.  Also, any OTHER phones connected to 
the same line would still ring unless one of phones answered the call and 
then hung up, which is something a modem could do.

Are you in the USA?  Have you checked out the Do Not Call registry? 
https://www.donotcall.gov/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't like the OO part of python. In particular the self keyword everywhere.

2015-06-11 Thread sohcahtoa82
On Thursday, June 11, 2015 at 4:19:59 AM UTC-7, Skybuck Flying wrote:
 Hello,
 
 I don't like the object orientated part of Python.
 
 The idea/prospect of having to write self everywhere... seems very 
 horrorific and a huge time waster.
 
 (Perhaps the module thing of python might help in future not sure about 
 that).
 
 What are your thoughts on the self thing/requirement.
 
 I only want replies from expert programmers, cause we need a language for 
 expert programmers...
 
 Not noobies that need to be hand-held...
 
 Personally I think I could do just fine with the self keyword everywhere.
 
 So question is... can the python interpreter/compiler be written in such a 
 way that self can be left out ?
 
 In other words: Is there any hope... that this part of the language will be 
 cleaned up some day ?
 
 Are there any tricks to get rid of it ?
 
 Maybe white like in Delphi ?
 
 I haven't written much OO code yet in Python... and don't plan on doing it 
 too...
 
 Cause it looks hellish confusing... and clouded/clodded.
 
 I think I have better things to do then to insert self everywhere...
 
 It's almost like self masturbation  LOL.
 
 Bye,
   Skybuck =D

We just had a huge thread about the self thing less than two weeks ago.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Testing random

2015-06-10 Thread sohcahtoa82
On Wednesday, June 10, 2015 at 10:06:49 AM UTC-7, Thomas 'PointedEars' Lahn 
wrote:
 Jussi Piitulainen wrote:
 
  Thomas 'PointedEars' Lahn writes:
  Jussi Piitulainen wrote:
  Thomas 'PointedEars' Lahn writes:
8 3 6 3 1 2 6 8 2 1 6.
  
  There are more than four hundred thousand ways to get those numbers
  in some order.
  
  (11! / 2! / 2! / 2! / 3! / 2! = 415800)
 
  Fallacy.  Order is irrelevant here.
  
  You need to consider every sequence that leads to the observed counts.
 
 No, you need _not_, because – I repeat – the probability of getting a 
 sequence of length n from a set of 9 numbers whereas the probability of 
 picking a number is evenly distributed, is (1∕9)ⁿ [(1/9)^n, or 1/9 to the 
 nth, for those who do to see it because of lack of Unicode support at their 
 system].  *Always.*  *No matter* which numbers are in it.  *No matter* in 
 which order they are.  AISB, order is *irrelevant* here.  *Completely.*
 
 This is _not_ a lottery box; you put the ball with the number on it *back 
 into the box* after you have drawn it and before you draw a new one.
 
  One of those sequences occurred. You don't know which.
 
 You do not have to.
 
  When tossing herrings […]
 
 Herrings are the key word here, indeed, and they are deep dark red.
 
  Code follows. Incidentally, I'm not feeling smart here. 
 
 Good.  Because you should not feel smart in any way after ignoring all my 
 explanations.
 
  [nonsense]
 
 -- 
 PointedEars
 
 Twitter: @PointedEars2
 Please do not cc me. / Bitte keine Kopien per E-Mail.

To put it another way, let's simplify the problem.  You're rolling a pair of 
dice.  What are the chances that you'll see a pair of 3s?

Look at the list of possible roll combinations:

1 1 1 2 1 3 1 4 1 5 1 6
2 1 2 2 2 3 2 4 2 5 2 6
3 1 3 2 3 3 3 4 3 5 3 6
4 1 4 2 4 3 4 4 4 5 4 6
5 1 5 2 5 3 5 4 5 5 5 6
6 1 6 2 6 3 6 4 6 5 6 6

36 possible combinations.  Only one of them has a pair of 3s.  The answer is 
1/36.

What about the chances of seeing 2 1?

Here's where I think you two are having such a huge disagreement.  Does order 
matter?  It depends what you're pulling random numbers out for.

The odds of seeing 2 1 are also only 1/36.  But if order doesn't matter in your 
application, then 1 2 is equivalent.  The odds of getting 2 1 OR 1 2 is 2/36, 
or 1/18.

But whether order matters or not, the chances of getting a pair of threes in 
two rolls is ALWAYS 1/36.

If this gets expanded to grabbing 10 random numbers between 1 and 9, then the 
chances of getting a sequence of 10 ones is still only (1/9)^10, *regardless of 
whether or not order matters*.  There are 9^10 possible sequences, but only 
*one* of these is all ones.

If order matters, then 7385941745 also has a (1/9)^10 chance of occurring.  
Just because it isn't a memorable sequence doesn't give it a higher chance of 
happening.

If order DOESN'T matter, then 1344557789 would be equivalent, and the odds are 
higher.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can Python function return multiple data?

2015-06-05 Thread sohcahtoa82
On Wednesday, June 3, 2015 at 2:57:00 PM UTC-7, Mark Lawrence wrote:
 On 03/06/2015 22:35, Chris Angelico wrote:
  On Wed, Jun 3, 2015 at 11:56 PM, Thomas Rachel
  nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa...@spamschutz.glglgl.de
  wrote:
  Am 03.06.2015 um 01:56 schrieb Chris Angelico:
 
  and it's pretty convenient. In C, the nearest equivalent is passing a
  number of pointers as parameters, and having the function fill out
  values. Python's model is a lot closer to what you're saying than C's
  model is :)
 
 
  At least, C functions can return structs...
 
  Oh, yes, I forgot about that. Thought that was C++ but not C, partly
  because I never do it in either language. Although in a sense, a
  struct is still a single thing.
 
  ChrisA
 
 
 Don't forget that C functions can accept structs as input.  Possibly not 
 a good idea as I found out many years ago pre ANSIC when I forgot that 
 little old ampersand, so the compiler didn't pick it up, but then with 
 modern computers having so much memory who really cares if you burn a 
 little bit of stack on structures rather than pointers to structures?
 
 Now does Python pass by value or by reference?  Happily sits back and 
 waits for 10**6 emails to arrive as this is discussed for the 10**6th time.
 
 -- 
 My fellow Pythonistas, ask not what our language can do for you, ask
 what you can do for our language.
 
 Mark Lawrence

Boy, you really called it on the 10**6 emails thing.  This thread certainly 
exploded.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can Python function return multiple data?

2015-06-03 Thread sohcahtoa82
On Wednesday, June 3, 2015 at 2:57:00 PM UTC-7, Mark Lawrence wrote:
 On 03/06/2015 22:35, Chris Angelico wrote:
  On Wed, Jun 3, 2015 at 11:56 PM, Thomas Rachel
  nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa...@spamschutz.glglgl.de
  wrote:
  Am 03.06.2015 um 01:56 schrieb Chris Angelico:
 
  and it's pretty convenient. In C, the nearest equivalent is passing a
  number of pointers as parameters, and having the function fill out
  values. Python's model is a lot closer to what you're saying than C's
  model is :)
 
 
  At least, C functions can return structs...
 
  Oh, yes, I forgot about that. Thought that was C++ but not C, partly
  because I never do it in either language. Although in a sense, a
  struct is still a single thing.
 
  ChrisA
 
 
 Don't forget that C functions can accept structs as input.  Possibly not 
 a good idea as I found out many years ago pre ANSIC when I forgot that 
 little old ampersand, so the compiler didn't pick it up, but then with 
 modern computers having so much memory who really cares if you burn a 
 little bit of stack on structures rather than pointers to structures?
 
 Now does Python pass by value or by reference?  Happily sits back and 
 waits for 10**6 emails to arrive as this is discussed for the 10**6th time.
 
 -- 
 My fellow Pythonistas, ask not what our language can do for you, ask
 what you can do for our language.
 
 Mark Lawrence

People actually argue that Python passes by value?  This is easily proven wrong 
by passing a mutable object to a function and changing it within the function.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Multiple thread program problem

2015-06-03 Thread sohcahtoa82
On Wednesday, June 3, 2015 at 4:45:52 PM UTC-7, M2 wrote:
 On Wednesday, June 3, 2015 at 5:34:31 PM UTC-5, Waffle wrote:
  You think (f) makes a tuple, but it does not.
  the parentesis is not the tuple constructor, the comma is
  try:
  t=thread.start_new_thread(proc,(f,))
 
 Thanks for the pointer waffle.
 The program executes now but still not the way I want it.
 I think I will need to tweak it a bit as the code is executing with the same 
 argument from the file /tmp/python/1 multiple times whereas it needs to be 
 executed only ones but in parallel. Let me figure that out.
 
 
 Once again thanks for all the help provided on this thread.

Check your usages of line and f.  You have spots where you probably meant 
line instead of f, and others where you have f where you probably meant 
line.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can Python function return multiple data?

2015-06-02 Thread sohcahtoa82
On Tuesday, June 2, 2015 at 2:27:37 PM UTC-7, fl wrote:
 Hi,
 
 I just see the tutorial says Python can return value in function, it does 
 not say multiple data results return situation. In C, it is possible.
 How about Python on a multiple data return requirement?
 
 
 Thanks,

You return a tuple, set, or other iterable.  For example:

def return_two_values():
return 1, 2

a, b = return_two_values()
print a
print b

This would print:
1
2

Note though that when doing something like this, you have to be really careful 
that if you have multiple calls to `return` in your function, that they will 
ALL return the same number of values.  Otherwise, when the tuple/list/etc. is 
unpacked, you'll get an error.

def return_two_values():
# ... do some stuff
if someCondition:
print someCondition was true!
return 0
return 1, 2

a, b = return_two_values()

Here, if someCondition ended up being False, then an exception would be thrown.

Keep in mind that the unpacking of the returned value into the variables `a` 
and `b` works with *ANY* iterable.  So if you returned 'abc' and unpacked it 
into three variables, then the first would contain 'a', the second 'b', and the 
third 'c'.

You can also just return a dictionary if you want to return multiple values.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Where is 'palindrome' defined?

2015-06-01 Thread sohcahtoa82
On Monday, June 1, 2015 at 5:55:14 PM UTC-7, fl wrote:
 On Sunday, May 31, 2015 at 9:46:56 PM UTC-7, fl wrote:
  Hi,
  
  When I search solution of reverse a string/number, I came across a short
  function online:
  
   def palindrome(num):
  return str(num) == str(num)[::-1]
  
  I thought that it is a general function. And with the following variable:
  
   a
  '1234_'
  
   parlindrome(a)
  
  Traceback (most recent call last):
File pyshell#126, line 1, in module
  parlindrome(a)
  NameError: name 'parlindrome' is not defined
  
  
  Then, I find that parlindrome is a special checking mirrored word.
  I use Python 2.7.9. Why does the error message show   
  
  name 'parlindrome' is not defined
  
  
  
  Thanks,
 
 Thanks, I realize that it was spelled wrong. Now, with the correct spelling
 the result is a 'False'. I have expected it gives reversed string. Is the 
 function behaves correct or not?
 
 
 Thanks,
 
 
 
 
  a='1234'
  def palindrome(num):
   return str(num) == str(num)[::-1]
  palindrome(a)
 False
  palindrome(fread)
 False

If you want the reversed string, then just use a[::-1].  Your palindrome 
function simply returns a boolean telling you whether or not the string you 
gave it is a palindrome.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is considered an advanced topic in Python?

2015-05-29 Thread sohcahtoa82
On Friday, May 29, 2015 at 9:02:06 AM UTC-7, Mike Driscoll wrote:
 Hi,
 
 I've been asked on several occasions to write about intermediate or advanced 
 topics in Python and I was wondering what the community considers to be 
 intermediate or advanced. I realize we're all growing in our abilities 
 with the language, so this is going to be very subjective, but I am still 
 curious what my fellow Python developers think about this topic.
 
 Thanks,
 Mike

Metaclasses.

I've read about them.  I still don't understand them, why you would want them, 
and what you gain from them.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is considered an advanced topic in Python?

2015-05-29 Thread sohcahtoa82
On Friday, May 29, 2015 at 10:18:29 AM UTC-7, Ethan Furman wrote:
 On 05/29/2015 10:03 AM, sohcahto...@gmail.com wrote:
  On Friday, May 29, 2015 at 9:02:06 AM UTC-7, Mike Driscoll wrote:
 
  I've been asked on several occasions to write about intermediate or 
  advanced topics
   in Python and I was wondering what the community considers to be 
  intermediate or
   advanced. I realize we're all growing in our abilities with the 
  language, so this
   is going to be very subjective, but I am still curious what my fellow 
  Python
   developers think about this topic.
 
  Metaclasses.
 
  I've read about them.  I still don't understand them, why you would want 
  them, and what you gain from them.
 
 Metaclasses change the way a class behaves.
 
 For example, the new (in 3.4) Enum class uses a metaclass.
 
class SomeEnum(Enum):
   first = 1
   second = 2
   third = 3
 
 The metaclass changes normal class behavior to:
 
- support iterating: list(SomeEnum) -- [SomeEnum.first, SomeEnum.second, 
 SomeEnum.third]
- support a length:  len(SomeEnum) -- 3
- not allow new instances to be created:  -- SomeEnum(1) is SomeEnum(1)  
 # True
 
 --
 ~Ethan~

Regarding the first two, you can implement __iter__ and __len__ functions to 
create that functionality, though those functions would operate on an instance 
of the class, not the class itself.

As for the third, can't you override the __new__ function to make attempts to 
create a new instance just return a previously created instance?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread sohcahtoa82
On Thursday, May 28, 2015 at 2:50:18 PM UTC-7, Skybuck Flying wrote:
 Hello,
 
 I was just coding and ran into a little logic problem which is as follows:
 
 There are two booleans/variables which can be either false or true.
 
 The desired thrutle table is:
 
 A = input
 B = input
 C = output
 
 A B C:
 ---
 F F T
 F T F
 T F T
 T T T
 
 Surpisingly enough I don't think there is a casual/common operator for this 
 thruth table.
 
 AND does not apply.
 OR does not apply.
 XOR does not apply.
 
 So I would need some combined operators to give the desired result.
 
 I tried logic below... but funny enough it failed, now I feel like a noob 
 lol and share this funny little fail logic with you.
 
 Can you improve/fix the logic ?
 
 This is python code, but this^ logic/thruth table problem basically applies 
 to any programming language:
 
 # loop has to run if:
 # while DesiredResult==True:
 # Desired truth table for BotWaitForCooldown and CooldownDetected
 # BotWaitForCooldown:  CooldownDetected: Desired Result:
 # False   FalseTrue
 # False   True False
 # True FalseTrue
 # True True True
 # desired/suiting logic:
 # (BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected))
 
 def TestLogic( BotWaitForCooldown, CooldownDetected ):
 return BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected) 
 # this logic is flawed, please improve logic.
 
 if TestLogic( False, False ) == True:
 print test 1 ok
 else:
 print test 1 failed
 
 if TestLogic( False, True ) == False:
 print test 2 ok
 else:
 print test 2 failed
 
 if TestLogic( True, False ) == True:
 print test 3 ok
 else:
 print test 3 failed
 
 if TestLogic( True, True ) == True:
 print test 4 ok
 else:
 print test 4 failed
 
 Bye,
   Skybuck.

I think the logic you're really looking for is:

return BotWaitForCooldown or (not (BotWaitForCooldown or CooldownDetected))
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread sohcahtoa82
On Thursday, May 28, 2015 at 3:17:10 PM UTC-7, Michael Torrie wrote:
 On 05/28/2015 03:58 PM, sohcahto...@gmail.com wrote:
  I think the logic you're really looking for is:
  
  return BotWaitForCooldown or (not (BotWaitForCooldown or CooldownDetected))
 
 Yes this is the simplest form.  For more complicated truth tables you
 can create a K map and then apply a reduction algorithm to it.  This is
 commonly done in logic circuits to reduce the number of gates to the
 minimum.  While not faster, it can be expressed as:
 
 return BotWaitForCooldown or not BotWaitForCooldown and not
 CooldownDectected
 
 Order of operations puts the ands above the ors.

Order of operations might put the ands above the ors, but I still like using 
parentheses in expressions like that as I think it makes it more clear.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Survey -- Move To Trash function in Python?

2015-05-15 Thread sohcahtoa82
On Friday, May 15, 2015 at 11:27:18 AM UTC-7, rand...@fastmail.us wrote:
 On Fri, May 15, 2015, at 00:25, Chris Angelico wrote:
  The main thing is that trashing invites the system to delete the file
  at its leisure,
 
 I've never seen a system whose trash can emptied itself without user
 intervention.

Windows won't empty the entire trash without user intervention, but is IS 
configured by default to only use up to a specific amount of hard drive space.  
Once the trash reaches its capacity, it'll start removing files from it to make 
room for more.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python re to extract useful information from each line

2015-04-29 Thread sohcahtoa82
On Wednesday, April 29, 2015 at 1:42:18 PM UTC-7, Kashif Rana wrote:
 Hello Experts
 
 I have below lines with some variations.
 
 1- set policy id 1000 from Untrust to Trust Any 1.1.1.1 HTTP nat 
 dst ip 10.10.10.10 port 8000 permit log
 
 2- set policy id 5000 from Trust to Untrust Any microsoft.com HTTP 
 nat src permit schedule 14August2014 log
 
 3- set policy id 7000 from Trust to Untrust Users Any ANY nat src 
 dip-id 4 permit log
 
 4- set policy id 7000 from Trust to Untrust servers Any ANY deny
 
 Please help me to write the regular expression to extract below information 
 in parenthesis, if exist from each line. Please note that some items may 
 exist or not like nat or log
 
 set policy id (id) from (from) to (to) (source) (destination) (service) nat 
 (src or dst) (dip-id 4) or (ip 10.10.10.10) port (dst-port) (action) schedule 
 (schedule) (log)

If you don't have to worry about spaces in your strings, I'd just use split().  
If you DO need to worry about spaces, it'd be trivial to write your own parser 
that stepped through the string a single character at a time.  The shlex module 
does this, but might not work for you.  I don't know how it would handle an IP 
address.
-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   >