Re: int vs. float

2017-02-11 Thread Marko Rauhamaa
boB Stepp :

> According to the OP's professor's challenge, the OP needs to recognize
> an input of "4.0" as a float and "4" as an integer, and to respond
> with an error message in the float case, or "decimal number" case as
> the OP phrased it.  Apparently only positive integers are acceptable
> input; all other inputs should generate an appropriate error message
> by input type.

Haven't been following the discussion, but this should be simply:

   ast.literal_eval("...")

For example:

   >>> ast.literal_eval("( 1.0, 3 )").__class__.__name__
   'tuple'


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


Re: int vs. float

2017-02-11 Thread Amit Yaron

On 11/02/17 09:47, boB Stepp wrote:

On Sat, Feb 11, 2017 at 1:00 AM, Amit Yaron  wrote:

On 10/02/17 21:15, Peter Pearson wrote:


On Fri, 10 Feb 2017 13:59:45 +0200, Amit Yaron 
wrote:


On 10/02/17 04:33, adam14711...@gmail.com wrote:



My computer programming professor challenged me to figure out a way
to manipulate my program to display one error message if the user
input is a zero or a negative number, and a separate error message if
the user input is a decimal number.  My program starts out:


[snip]


What should happen if the user types "1.0"?

To be flexible about this possibility, you could accept the number
as a float, and then complain if int(num) != num.


Another option:
Use 'float' instead of 'int'. and check using the method  'is_integer' of
floating point numbers:


3.5.is_integer()

False

4.0.is_integer()

True


According to the OP's professor's challenge, the OP needs to recognize
an input of "4.0" as a float and "4" as an integer, and to respond
with an error message in the float case, or "decimal number" case as
the OP phrased it.  Apparently only positive integers are acceptable
input; all other inputs should generate an appropriate error message
by input type.



Here's the output of the int function with a  string argument:
>>> int("4.0")
Traceback (most recent call last):
  File "", line 1, in 

You can use exception handling to detect numbers that do not match the 
regular expression for integers, and comparisons to check if a number is 
negative.




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


DJANGO image processing

2017-02-11 Thread Xristos Xristoou
I want to create a django app with the base64 help where the users can upload 
images(specific ".tiff" ext) using DJANGO forms without model and without that 
images store in my server. and i will the users can be get back new processing 
image.
i have success with encode/decode image with base64 and i can display that 
image in template using safari because that can display TIFF images.
here the code :
views.py
def convert_to_base64(image_file):
base64_string = base64.encodestring(image_file)
return "data:image/png;base64,"+base64_string

@csrf_exempt
def index(request):
form = ImageUploadForm(request.POST or None, request.FILES or None)
if request.method == "POST" and form.is_valid():
image_file = request.FILES['image'].read()
base64_string = convert_to_base64(image_file)
file = base64_string.decode('utf8')
   return render_to_response("blog/success.html", {"image_file":file})
return render_to_response('blog/calc.html', {'form': form}, 
RequestContext(request))
my problem is now after the base64 i cant use that image for image 
processing(work fine in standalone python script) and i take two error :
RuntimeError at /
not a string in the browser
and that message in command line :
"GET / HTTP/1.1" 200 346
ERROR 4: `II*' does not exist in the file system,
and is not recognised as a supported dataset name.
here the code :
@csrf_exempt
def index(request):
form = ImageUploadForm(request.POST or None, request.FILES or None)
if request.method == "POST" and form.is_valid():
image_file = request.FILES['image'].read()
base64_string = convert_to_base64(image_file)

file = base64_string.decode('utf8')
file_like = cStringIO.StringIO(image_file)
flow_direction_uri = "output.tif"
routing.flow_direction_d_inf(file_like, flow_direction_uri)
return render_to_response("blog/success.html", {"image_file":file})
return render_to_response('blog/calc.html', {'form': form}, 
RequestContext(request))
and if i use file = base64_string.decode('utf8') as input in my function then i 
take that error :
AttributeError at /
'NoneType' object has no attribute 'GetRasterBand'
and in command line i take to like that :
AIAAgACAAIAAgACAAIAAgACAAIAAgACA
AIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAA
gACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACA
AIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAA
with to many lines.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: int vs. float

2017-02-11 Thread Erik
[Dan, this isn't "aimed" at you personally, it's just a follow-up on the 
general point I am (and I think you are also) making]


On 11/02/17 02:17, Dan Sommers wrote:

At least it works both ways:

Python 3.5.3 (default, Jan 19 2017, 14:11:04)
[GCC 6.3.0 20170118] on linux
Type "help", "copyright", "credits" or "license" for more information.

s = "3"
f = float(s)
i = int(s)


Yes, but Peter said "accept the number as a float, and then complain if 
int(num) != num.", so he meant use "i = int(f)" (i.e., convert the float 
to an int, not the original string).


Anyway, that's just as bad, but in a different way ;) Using your example:

Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> s = "3"
>>> f = float(s)
>>> f
3.e+64
>>> i = int(f)
>>> i
3069679542094544616940918707231410151788522766336
>>> i == f
True
>>>

That's poor if "i" ends up being the value actually used later when the 
input is processed - it's NOT the value the user entered!


I imagine that this particular use-case is not trying to teach the OP 
about float/int issues, but about how to parse numerical strings from 
user-input (so these extreme cases are not expected to be part of the 
input range). I might be wrong, though.


However, these sorts of issues are a very important consideration for 
people writing real-world code where the input might be coming from an 
external source such as a database or output from a language which uses 
fixed-point or some other precise representation of decimals (e.g., COBOL).


Whenever you convert something that may not be an integer in the 
appropriate range to a float (using IEEE 754, at least) you must be 
aware that you may lose precision. The answer in this case is to do 
something similar to what Peter suggested, but to use Python's 'decimal' 
type as the intermediate representation rather than the float() type:


Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from decimal import Decimal as dec
>>> s = "0.5"
>>> d = dec(s)
>>> i = int(d)
>>> d
Decimal('0.5')
>>> i
0
>>> i == d
False
>>> s = "3"
>>> d = dec(s)
>>> i = int(d)
>>> d
Decimal('3')
>>> i
3
>>> i == d
True


No surprises there ;)

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


Re: int vs. float

2017-02-11 Thread Steve D'Aprano
On Sat, 11 Feb 2017 07:24 pm, Marko Rauhamaa wrote:

> boB Stepp :
> 
>> According to the OP's professor's challenge, the OP needs to recognize
>> an input of "4.0" as a float and "4" as an integer, and to respond
>> with an error message in the float case, or "decimal number" case as
>> the OP phrased it.  Apparently only positive integers are acceptable
>> input; all other inputs should generate an appropriate error message
>> by input type.
> 
> Haven't been following the discussion, but this should be simply:
> 
>ast.literal_eval("...")
> 
> For example:
> 
>>>> ast.literal_eval("( 1.0, 3 )").__class__.__name__
>'tuple'


In what way does returning a tuple match the requirement "return an int or a
float or generate an error message"?




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: int vs. float

2017-02-11 Thread Chris Angelico
On Sun, Feb 12, 2017 at 2:27 PM, Steve D'Aprano
 wrote:
>>
>> For example:
>>
>>>>> ast.literal_eval("( 1.0, 3 )").__class__.__name__
>>'tuple'
>
>
> In what way does returning a tuple match the requirement "return an int or a
> float or generate an error message"?

Easy. You just use a version of Python in which tuple is a subclass of int.

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


Re: int vs. float

2017-02-11 Thread Steve D'Aprano
On Sat, 11 Feb 2017 06:00 pm, Amit Yaron wrote:

> Another option:
> Use 'float' instead of 'int'. and check using the method  'is_integer'
> of floating point numbers:
> 
>  >>> 3.5.is_integer()
> False
>  >>> 4.0.is_integer()
> True


A bad option...

py> float('12345678901234567')
1.2345678901234568e+16

Notice the last digit of the mantissa?


Beyond a certain value, *all* floats are integer, because floats don't have
enough precision to include a fractional portion. 

py> float('12345678901234567.12345').is_integer()
True


The safest way to treat this is to attempt to convert to an int, if that
succeeds return the int; if it fails, try to convert to a float, and if
that succeeds, return the float.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: os.path.isfile

2017-02-11 Thread Steve D'Aprano
On Sat, 11 Feb 2017 06:50 am, Vincent Vande Vyvre wrote:

> Le 10/02/17 à 19:11, epro...@gmail.com a écrit :
>> Hello NG
>>
>> Python 3.5.2
>>
>> Windows 10
>>
>> os.path.isfile() no recognise file with double dot?
>>
>> eg. match.cpython-35.pyc
>>
>> Please somebody know something about that?
>>
>> Thank You in advance
>>
> Interesting, you're right.
> 
> Python 3.4.3 (default, Nov 17 2016, 01:08:31)
> [GCC 4.8.4] on linux
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> import os
>  >>> 
>
os.path.isfile('/home/vincent/oqapy-3/trunk/__pycache__/grid.cpython-34.pyc
> ')
> False
> 
> 
> Why ?


How do you know that file exists?

Why choose such a long file name where you risk introducing spaces or
newlines due to word-wrapping?


I cannot replicate your result using Python 3.5 on Linux:


py> path = '/tmp/spam.eggs.cheese.txt'
py> with open(path, 'w') as f:
... f.write('something')
...
9
py> import os
py> print(os.path.isfile(path))
True


I expect that you have a space at the end of the file name:

'/home/vincent/oqapy-3/trunk/__pycache__/grid.cpython-34.pyc '

instead of 

'/home/vincent/oqapy-3/trunk/__pycache__/grid.cpython-34.pyc'


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: os.path.isfile

2017-02-11 Thread Steve D'Aprano
On Sat, 11 Feb 2017 05:11 am, epro...@gmail.com wrote:

> Hello NG
> 
> Python 3.5.2
> 
> Windows 10
> 
> os.path.isfile() no recognise file with double dot?
> 
> eg. match.cpython-35.pyc



I doubt that very much. I expect you are probably writing something like
this:


path = 'My Documents\testing\path\match.cpython-35.pyc'
os.path.isfile(path)

and not realising that you have a TAB character in your string from the \t,
or something similar.

In Python, you should always use forward slashes for paths, even on Windows.

path = 'My Documents/testing/path/match.cpython-35.pyc'

Try printing the repr() of your path.





-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Rename file without overwriting existing files

2017-02-11 Thread Steve D'Aprano
On Fri, 10 Feb 2017 12:07 am, eryk sun wrote:

> On Thu, Feb 9, 2017 at 11:46 AM, Steve D'Aprano
>  wrote:
>>
>> So to summarise, os.rename(source, destination):
>>
>> - is atomic on POSIX systems, if source and destination are both on the
>>   same file system;
>> - may not be atomic on Windows?
>> - may over-write an existing destination on POSIX systems, but not on
>>   Windows;
>> - and it doesn't work across file systems.
> 
> On Windows in 2.7 and prior to 3.3, os.rename will silently copy and
> delete when the destination isn't on the same volume. 


Will the copy overwrite an existing file?


> It may even 
> silently leave the original file in place in some cases -- e.g. when
> the file is read-only and the user isn't allowed to modify the file
> attributes.
> 
> If the destination is on the same volume, renaming should be atomic
> via the system calls NtOpenFile and NtSetInformationFile. Ultimately
> it depends on the file system implementation of
> IRP_MJ_SET_INFORMATION, FileRenameInformation [1].
> 
>> The link/unlink trick:
>> - avoids over-writing existing files on POSIX systems at least;
>> - but maybe not Windows?
> 
> This works for renaming files on Windows as long as the file system
> supports hard links (e.g. NTFS). It's not documented on MSDN, but
> WinAPI CreateHardLink is implemented by calling NtSetInformationFile
> to set the FileLinkInformation, with ReplaceIfExists set to FALSE, so
> it fails if the destination exists. Note that this does not allow
> renaming directories. See the note for FileLinkInformation [1]; NTFS
> doesn't allow directory hard links. But why bother with this 'trick'
> on Windows?

I don't know, that's why I'm asking for guidance. I don't have a Windows
system to test on.

On Windows, how would you implement a file rename (potentially across file
system boundaries) which will not overwrite existing files? Just by calling
os.rename()?



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: os.path.isfile

2017-02-11 Thread eryk sun
On Sun, Feb 12, 2017 at 3:52 AM, Steve D'Aprano
 wrote:
> In Python, you should always use forward slashes for paths, even on Windows.

There are cases where slash doesn't work (e.g. some command lines;
\\?\ prefixed paths; registry subkey paths), so it's simpler to follow
a rule to always convert paths to backslash on Windows, using
os.path.normpath or pathlib.Path.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: os.path.isfile

2017-02-11 Thread Chris Angelico
On Sun, Feb 12, 2017 at 3:20 PM, eryk sun  wrote:
> On Sun, Feb 12, 2017 at 3:52 AM, Steve D'Aprano
>  wrote:
>> In Python, you should always use forward slashes for paths, even on Windows.
>
> There are cases where slash doesn't work (e.g. some command lines;
> \\?\ prefixed paths; registry subkey paths), so it's simpler to follow
> a rule to always convert paths to backslash on Windows, using
> os.path.normpath or pathlib.Path.

Registry subkeys aren't paths, and the other two cases are extremely
narrow. Convert slashes to backslashes ONLY in the cases where you
actually need to.

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


Re: int vs. float

2017-02-11 Thread Steve D'Aprano
On Sun, 12 Feb 2017 02:34 pm, Chris Angelico wrote:

> On Sun, Feb 12, 2017 at 2:27 PM, Steve D'Aprano
>  wrote:
>>>
>>> For example:
>>>
>>>>>> ast.literal_eval("( 1.0, 3 )").__class__.__name__
>>>'tuple'
>>
>>
>> In what way does returning a tuple match the requirement "return an int
>> or a float or generate an error message"?
> 
> Easy. You just use a version of Python in which tuple is a subclass of
> int.


Wouldn't a subclass of float be more appropriate? After all, floats have a
mantissa and an exponent, which kinda makes them a tuple...

*tongue firmly in cheek*


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: os.path.isfile

2017-02-11 Thread Steve D'Aprano
On Sun, 12 Feb 2017 03:20 pm, eryk sun wrote:

> On Sun, Feb 12, 2017 at 3:52 AM, Steve D'Aprano
>  wrote:
>> In Python, you should always use forward slashes for paths, even on
>> Windows.
> 
> There are cases where slash doesn't work (e.g. some command lines;
> \\?\ prefixed paths; registry subkey paths), so it's simpler to follow
> a rule to always convert paths to backslash on Windows, using
> os.path.normpath or pathlib.Path.

Okay, that makes sense. But we agree that when writing paths as string
literals, you should (nearly) always use forward slashes in Python.

Why not raw strings? Because raw strings aren't actually fully raw, and
consequently they don't allow the string to end with a backslash:


py> s = r'documents\'
  File "", line 1
s = r'documents\'
^
SyntaxError: EOL while scanning string literal


(I still don't understand why this isn't just treated as a bug in raw string
parsing and fixed...)



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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