Re: Checking if email is valid

2023-11-01 Thread De ongekruisigde via Python-list
On 2023-11-01, Mats Wichmann  wrote:
> On 11/1/23 05:35, Simon Connah via Python-list wrote:
>> OK. I've been doing some reading and that you should avoid regex to check 
>> email addresses. So what I was thinking was something like this:
>
> To be a little more specific, Avoid Rolling Your Own RegEx.  It's very 
> tricky, and you will get it subtly wrong.

Use e.g.: https://gitea.ksol.io/karolyi/py3-validate-email

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


Re: Simple webserver

2023-10-20 Thread De ongekruisigde via Python-list
On 2023-10-20, Chris Angelico  wrote:
> On Fri, 20 Oct 2023 at 22:31, Janis Papanagnou via Python-list
> wrote:
>>
>> On 19.10.2023 01:23, Chris Angelico wrote:
>> >
>> > Broadly speaking, your ideas are great. Any programming language CAN
>> > be used for the server (and I've used several, not just Python).
>>
>> Out of curiosity; what where these languages? - If there's one I
>> already know I might save some time implementing the server. :-)
>>
>
> I've done websocket servers in Python, Node.js, and Pike, and possibly
> others but I can't recall at the moment. Might have done one in Ruby,
> but that would have just been part of playing around and comparing
> features ("how easy is it to do  in Ruby").
>
> ChrisA

*Big list of http static server one-liners*

Each of these commands will run an ad hoc http static server
in your current (or specified) directory, available at
http://localhost:8000. Use this power wisely.


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


Re: WHAT THE ERROR ON MY CODE???

2022-06-28 Thread De ongekruisigde
On 2022-06-28, Chris Angelico  wrote:
> ‪On Wed, 29 Jun 2022 at 01:37, ‫נתי שטרן‬‎  wrote:‬
>> headers["Authorization"] = "Basic
>> YjMwMzcwODY3NTUzNDMwNTg5NzA2MjkyNDFmMDE1YWY6VjNKYTk2Y1F4RTFzeTdYbzRnbkt0a2k1djhscXUyU01oSE5VWUwwRg=="
>>
>
> The error is that you just revealed your credentials to the whole
> world. This is a public mailing list.
>
> In fact, you just revealed your credentials to TWO mailing lists at once.

I think the term 'script kiddie' applies here.


> Good job.
>
> ChrisA


-- 
Without followers, evil cannot spread.  
 
[Spock, "And The Children Shall Lead", stardate 5029.5]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to test characters of a string

2022-06-08 Thread De ongekruisigde
On 2022-06-08, 2qdxy4rzwzuui...@potatochowder.com 
<2qdxy4rzwzuui...@potatochowder.com> wrote:
> On 2022-06-09 at 04:15:46 +1000,
> Chris Angelico  wrote:
>
>> On Thu, 9 Jun 2022 at 04:14, <2qdxy4rzwzuui...@potatochowder.com> wrote:
>> >
>> > On 2022-06-09 at 03:18:56 +1000,
>> > Chris Angelico  wrote:
>> >
>> > > On Thu, 9 Jun 2022 at 03:15, <2qdxy4rzwzuui...@potatochowder.com> wrote:
>> > > >
>> > > > On 2022-06-08 at 08:07:40 -,
>> > > > De ongekruisigde  wrote:
>> > > >
>> > > > > Depending on the problem a regular expression may be the much simpler
>> > > > > solution. I love them for e.g. text parsing and use them all the 
>> > > > > time.
>> > > > > Unrivaled when e.g. parts of text have to be extracted, e.g. from 
>> > > > > lines
>> > > > > like these:
>> > > > >
>> > > > >   root:x:0:0:System 
>> > > > > administrator:/root:/run/current-system/sw/bin/bash
>> > > > >   dhcpcd:x:995:991::/var/empty:/run/current-system/sw/bin/nologin
>> > > > >   nm-iodine:x:996:57::/var/empty:/run/current-system/sw/bin/nologin
>> > > > >   avahi:x:997:996:avahi-daemon privilege separation 
>> > > > > user:/var/empty:/run/current-system/sw/bin/nologin
>> > > > >   sshd:x:998:993:SSH privilege separation 
>> > > > > user:/var/empty:/run/current-system/sw/bin/nologin
>> > > > >   geoclue:x:999:998:Geoinformation 
>> > > > > service:/var/lib/geoclue:/run/current-system/sw/bin/nologin
>> > > > >
>> > > > > Compare a regexp solution like this:
>> > > > >
>> > > > >   >>> g = 
>> > > > > re.search(r'([^:]*):([^:]*):(\d+):(\d+):([^:]*):([^:]*):(.*)$' , s)
>> > > > >   >>> print(g.groups())
>> > > > >   ('geoclue', 'x', '999', '998', 'Geoinformation service', 
>> > > > > '/var/lib/geoclue', '/run/current-system/sw/bin/nologin')
>> > > > >
>> > > > > to the code one would require to process it manually, with all the 
>> > > > > edge
>> > > > > cases. The regexp surely reads much simpler (?).
>> > > >
>> > > > Uh...
>> > > >
>> > > > >>> import pwd # https://docs.python.org/3/library/pwd.html
>> > > > >>> [x for x in pwd.getpwall() if x[0] == 'geoclue']
>> > > > [pwd.struct_passwd(pw_name='geoclue', pw_passwd='x', pw_uid=992, 
>> > > > pw_gid=992, pw_gecos='Geoinformation service', 
>> > > > pw_dir='/var/lib/geoclue', pw_shell='/sbin/nologin')]
>> > >
>> > > That's great if the lines are specifically coming from your system's
>> > > own /etc/passwd, but not so much if you're trying to compare passwd
>> > > files from different systems, where you simply have the files
>> > > themselves.
>> >
>> > In addition to pwent to get specific entries from the local password
>> > database, POSIX has fpwent to get a specific entry from a stream that
>> > looks like /etc/passwd.  So even POSIX agrees that if you think you have
>> > to process this data manually, you're doing it wrong.  Python exposes
>> > neither functon directly (at least not in the pwd module or the os
>> > module; I didn't dig around or check PyPI).
>> 
>> So.. we can go find some other way of calling fpwent, or we can
>> just parse the file ourselves. It's a very VERY simple format.
>
> If you insist:
>
> >>> s = 
> 'nm-iodine:x:996:57::/var/empty:/run/current-system/sw/bin/nologin'
> >>> print(s.split(':'))
> ['nm-iodine', 'x', '996', '57', '', '/var/empty', 
> '/run/current-system/sw/bin/nologin']
>
> Hesitantly, because this is the Python mailing list, I claim (a) ':' is
> simpler than r'([^:]*):([^:]*):(\d+):(\d+):([^:]*):([^:]*):(.*)$', and
> (b) string.split covers pretty much the same edge cases as re.search.

Ah, but you don't catch the be numeric of fields (0-based) 2 and 3! But
agreed, it's not the best of examples.


-- 
 You're rewriting parts of Quake in *Python*?
 MUAHAHAHA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to test characters of a string

2022-06-08 Thread De ongekruisigde
On 2022-06-08, 2qdxy4rzwzuui...@potatochowder.com 
<2qdxy4rzwzuui...@potatochowder.com> wrote:
> On 2022-06-08 at 08:07:40 -0000,
> De ongekruisigde  wrote:
>
>> Depending on the problem a regular expression may be the much simpler
>> solution. I love them for e.g. text parsing and use them all the time.
>> Unrivaled when e.g. parts of text have to be extracted, e.g. from lines
>> like these:
>> 
>>   root:x:0:0:System administrator:/root:/run/current-system/sw/bin/bash
>>   dhcpcd:x:995:991::/var/empty:/run/current-system/sw/bin/nologin
>>   nm-iodine:x:996:57::/var/empty:/run/current-system/sw/bin/nologin
>>   avahi:x:997:996:avahi-daemon privilege separation 
>> user:/var/empty:/run/current-system/sw/bin/nologin
>>   sshd:x:998:993:SSH privilege separation 
>> user:/var/empty:/run/current-system/sw/bin/nologin
>>   geoclue:x:999:998:Geoinformation 
>> service:/var/lib/geoclue:/run/current-system/sw/bin/nologin
>> 
>> Compare a regexp solution like this:
>> 
>>   >>> g = re.search(r'([^:]*):([^:]*):(\d+):(\d+):([^:]*):([^:]*):(.*)$' , s)
>>   >>> print(g.groups())
>>   ('geoclue', 'x', '999', '998', 'Geoinformation service', 
>> '/var/lib/geoclue', '/run/current-system/sw/bin/nologin')
>> 
>> to the code one would require to process it manually, with all the edge
>> cases. The regexp surely reads much simpler (?).
>
> Uh...
>
> >>> import pwd # https://docs.python.org/3/library/pwd.html
> >>> [x for x in pwd.getpwall() if x[0] == 'geoclue']
> [pwd.struct_passwd(pw_name='geoclue', pw_passwd='x', pw_uid=992, 
> pw_gid=992, pw_gecos='Geoinformation service', pw_dir='/var/lib/geoclue', 
> pw_shell='/sbin/nologin')]

Yeah... Well, it was just an example and it must be clear by now I'm not
a Python programmer.

-- 
 You're rewriting parts of Quake in *Python*?
 MUAHAHAHA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to test characters of a string

2022-06-08 Thread De ongekruisigde
On 2022-06-08, Christian Gollwitzer  wrote:
> Am 07.06.22 um 23:01 schrieb Christian Gollwitzer:
>
>>> In [3]: re.sub(r'^\d+\s*', '', s) Out[3]: 'Trinket'
>>>
>
> that RE does match what you intended to do, but not exactly what you 
> wrote in the OP. that would be '^\d\d.'  start with exactly two digits 
> followed by any character.

Indeed but then I'd like '\d{2}' even better.


>   Christian


-- 
 You're rewriting parts of Quake in *Python*?
 MUAHAHAHA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to test characters of a string

2022-06-08 Thread De ongekruisigde
On 2022-06-08, Dave  wrote:
> I hate regEx and avoid it whenever possible, I’ve never found something that 
> was impossible to do without it.

I love regular expressions and use them where appropriate. Saves tons of
code and is often much more readable than the pages of code required to
do the same.

-- 
 You're rewriting parts of Quake in *Python*?
 MUAHAHAHA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to test characters of a string

2022-06-08 Thread De ongekruisigde
On 2022-06-08, dn  wrote:
> On 08/06/2022 10.18, De ongekruisigde wrote:
>> On 2022-06-08, Christian Gollwitzer  wrote:
>>> Am 07.06.22 um 21:56 schrieb Dave:
>>>> It depends on the language I’m using, in Objective C, I’d use isNumeric, 
>>>> just wanted to know what the equivalent is in Python.
>>>>
>>>
>>> Your problem is also a typical case for regular expressions. You can 
>>> create an expression for "starts with any number of digits plus optional 
>>> whitespace" and then replace this with nothing:
>> 
>> Regular expressions are overkill for this and much slower than the
>> simple isdigit based solution.
>
> ...
>
>> Regular expressions are indeeed extremely powerful and useful but I tend
>> to avoid them when there's a (faster) normal solution.
>
> Yes, simple solutions are (likely) easier to read.

Depending on the problem a regular expression may be the much simpler
solution. I love them for e.g. text parsing and use them all the time.
Unrivaled when e.g. parts of text have to be extracted, e.g. from lines
like these:

  root:x:0:0:System administrator:/root:/run/current-system/sw/bin/bash
  dhcpcd:x:995:991::/var/empty:/run/current-system/sw/bin/nologin
  nm-iodine:x:996:57::/var/empty:/run/current-system/sw/bin/nologin
  avahi:x:997:996:avahi-daemon privilege separation 
user:/var/empty:/run/current-system/sw/bin/nologin
  sshd:x:998:993:SSH privilege separation 
user:/var/empty:/run/current-system/sw/bin/nologin
  geoclue:x:999:998:Geoinformation 
service:/var/lib/geoclue:/run/current-system/sw/bin/nologin

Compare a regexp solution like this:

  >>> g = re.search(r'([^:]*):([^:]*):(\d+):(\d+):([^:]*):([^:]*):(.*)$' , s)
  >>> print(g.groups())
  ('geoclue', 'x', '999', '998', 'Geoinformation service', '/var/lib/geoclue', 
'/run/current-system/sw/bin/nologin')

to the code one would require to process it manually, with all the edge
cases. The regexp surely reads much simpler (?).


> RegEx-s are more powerful (and well worth learning for this reason), but
> are only 'readable' to those who use them frequently.
>
> Has either of you performed a timeit comparison?

No need: the isdigit solution doesn't require the overhead of a regex
processor.

-- 
 You're rewriting parts of Quake in *Python*?
 MUAHAHAHA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to replace characters in a string?

2022-06-08 Thread De ongekruisigde
On 2022-06-08, Dave  wrote:
> Hi All,
>
> I decided to start a new thread as this really is a new subject.
>
> I've got two that appear to be identical, but fail to compare. After getting 
> the ascii encoding I see that they are indeed different, my question is how 
> can I replace the \u2019m with a regular single quote mark (or apostrophe)?

You're not facing this alone:

 https://changelog.complete.org/archives/9938-the-python-unicode-mess

Perhaps useful insights can be found at:

 https://realpython.com/python-encodings-guide/

> +++

-- 
 You're rewriting parts of Quake in *Python*?
 MUAHAHAHA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to test characters of a string

2022-06-07 Thread De ongekruisigde
On 2022-06-08, Christian Gollwitzer  wrote:
> Am 07.06.22 um 21:56 schrieb Dave:
>> It depends on the language I’m using, in Objective C, I’d use isNumeric, 
>> just wanted to know what the equivalent is in Python.
>> 
>
> Your problem is also a typical case for regular expressions. You can 
> create an expression for "starts with any number of digits plus optional 
> whitespace" and then replace this with nothing:

Regular expressions are overkill for this and much slower than the
simple isdigit based solution.


>> chris@linux-tb9f:~> ipython
>> Python 3.6.15 (default, Sep 23 2021, 15:41:43) [GCC]
>> Type 'copyright', 'credits' or 'license' for more information
>> IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help.
>> 
>> In [1]: import re
>>  
>>
>> 
>> In [2]: s='05 Trinket'   
>>  
>>
>> 
>> In [3]: re.sub(r'^\d+\s*', '', s)
>>  
>>
>> Out[3]: 'Trinket'
>> 
>
> If it doesn't match, it will do nothing:
>
>> In [4]: s='Es geht los'  
>>  
>>
>> 
>> In [5]: re.sub(r'^\d+\s*', '', s)
>>  
>>
>> Out[5]: 'Es geht los'
>
> Some people on this list don't like regexes but for tasks like this they 
> are made and working well.

Regular expressions are indeeed extremely powerful and useful but I tend
to avoid them when there's a (faster) normal solution.


> ^ is "starts with"
> \d is any digit
> \s is any space
> + is at least one
> * is nothing or one of
>
> Christian

-- 
 You're rewriting parts of Quake in *Python*?
 MUAHAHAHA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to test characters of a string

2022-06-07 Thread De ongekruisigde
On 2022-06-07, Dave  wrote:
> Thanks a lot for this! isDigit was the method I was looking for and couldn’t 
> find.
>
> I have another problem related to this, the following code uses the code you 
> just sent. I am getting a files ID3 tags using eyed3, this part seems to work 
> and I get expected values in this case myTitleName (Track name) is set to 
> “Deadlock Holiday” and myCompareFileName is set to “01 Deadlock Holiday” 
> (File Name with the Track number prepended). The is digit test works and 
> myCompareFileName is set to  “Deadlock Holiday”, so they should match, right? 
>
> However the if myCompareFileName != myTitleName always gives a mismatch! What 
> could cause two string that look the fail to not match properly?

Possibly leading or trailing spaces, or upper/lower case differences?


> myCompareFileName = myFile
> if myCompareFileName[0].isdigit() and myCompareFileName[1].isdigit():
> myCompareFileName = myCompareFileName[3:]
>
> if myCompareFileName != myTitleName:
> print('File Name Mismatch - Artist: ',myArtistName,'  Album: 
> ',myAlbumName,'  Track:',myTitleName,'  File: ',myFile)
> Thanks a lot
> Dave
>
>> On 7 Jun 2022, at 21:58, De ongekruisigde 
>>  wrote:
>> 
>> On 2022-06-07, Dave  wrote:
>>> Hi,
>>> 
>>> I’m new to Python and have a simple problem that I can’t seem to find the 
>>> answer.
>>> 
>>> I want to test the first two characters of a string to check if the are 
>>> numeric (00 to 99) and if so remove the fist three chars from the string. 
>>> 
>>> Example: if “05 Trinket” I want “Trinket”, but “Trinket” I still want 
>>> “Trinket”. I can’t for the life of work out how to do it in Python?
>> 
>> 
>>  s[3:] if s[0:2].isdigit() else s
>> 
>> 
>>> All the Best
>>> Dave
>>> 
>> 
>> -- 
>>  You're rewriting parts of Quake in *Python*?
>>  MUAHAHAHA
>> -- 
>> https://mail.python.org/mailman/listinfo/python-list
>


-- 
 You're rewriting parts of Quake in *Python*?
 MUAHAHAHA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to test characters of a string

2022-06-07 Thread De ongekruisigde
On 2022-06-07, Stefan Ram  wrote:
> Dave  writes:
>>Example: if "05 Trinket" I want "Trinket"
>
>   We're not supposed to write complete solutions, 

Okay, wasn't aware of this group policy; will keep it in mind.

-- 
 You're rewriting parts of Quake in *Python*?
 MUAHAHAHA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to test characters of a string

2022-06-07 Thread De ongekruisigde
On 2022-06-07, Dave  wrote:
> Hi,
>
> I’m new to Python and have a simple problem that I can’t seem to find the 
> answer.
>
> I want to test the first two characters of a string to check if the are 
> numeric (00 to 99) and if so remove the fist three chars from the string. 
>
> Example: if “05 Trinket” I want “Trinket”, but “Trinket” I still want 
> “Trinket”. I can’t for the life of work out how to do it in Python?


  s[3:] if s[0:2].isdigit() else s


> All the Best
> Dave
>

-- 
 You're rewriting parts of Quake in *Python*?
 MUAHAHAHA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "py" command for Linux and Mac?

2022-05-12 Thread De ongekruisigde
On 2022-05-12, Mats Wichmann  wrote:
> On 5/12/22 10:25, Dan Stromberg wrote:
>> Hi folks.
>> 
>> I heard there's a Windows-like "py" command for Linux (and Mac?).
>> 
>> I'm finally getting to porting a particular project's Python 2.7 code to
>> 3.x, and one of the first steps will probably be changing a lot of "python2
>> script.py" to use #!/usr/bin/env python2 and chmod +x.  Then we can update
>> the scripts one at a time to use #!/usr/bin/env python3.
>> 
>> However, would this be Linux-and-Mac-only?  I'm not at all sure this code
>> will ever move to Windows, but in case it does, would a "py" command work
>> on all 3 if I use #!/usr/bin/env py?
>
> The py command (python lanucher) respects shebang lines.

Linux by itself respects shebang lines, so you don't need a separate
launcher program. Just put e.g.:

#! /usr/bin/env python

at the top of your Python file.

-- 
In the beginning there was darkness and the darkness was without form
and void. And in addition to the darkness there was also me. And I moved
upon the face of the darkness and I saw that I was alone. ... ... ...
Let there be light. [Bomb 20; John Carpenter's Dark Star - 1974]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Questions about XML processing?

2020-11-08 Thread Hernán De Angelis


On 2020-11-07 20:03, Dieter Maurer wrote:

Hernán De Angelis wrote at 2020-11-6 21:54 +0100:

...
However, the hard thing to do here is to get those only when
tagC/note/title/string='value'. I was expecting to find a way of
specifying a certain construction in square brackets, like
[@string='value'] or [@/tagC/note/title/string='value'], as is usual in
XML and possible in xml.etree. However this proved difficult (at least
for me). So this is the "brute" solution I implemented:

You might have a look at `lxml`.
It supports XPath (1.0) which is more powerfull in selecting nodes
than `etree`.


Yes, I am having a look at that. Thanks.

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


Re: Questions about XML processing?

2020-11-07 Thread Hernán De Angelis
No, it is XML metadata. I also believe there should be a better way using
[@...] expressions in the path.

H.

Den lör 7 nov. 2020 13:14Shaozhong SHI  skrev:

> Hi, Hernan,
>
> Did you try to parse GML?
>
> Surely, there can be very concise and smart ways to do these things.
>
> Regards,
>
> David
>
> On Fri, 6 Nov 2020 at 20:57, Hernán De Angelis <
> variablestarli...@gmail.com> wrote:
>
>> Thank you Terry, Dan and Dieter for encouraging me to post here. I have
>> already solved the problem albeit with a not so efficient solution.
>> Perhaps, it is useful to present it here anyway in case some light can
>> be added to this.
>>
>> My job is to parse a complicated XML (iso metadata) and pick up values
>> of certain fields in certain conditions. This goes for the most part
>> well. I am working with xml.etree.elementtree, which proved sufficient
>> for the most part and the rest of the project. JSON is not an option
>> within this project.
>>
>> The specific trouble was in this section, itself the child of a more
>> complicated parent: (for simplicity tags are renamed and namespaces
>> removed)
>>
>>
>>  
>>
>>  Something
>>
>>
>>  Something else
>>
>>
>>  
>>
>>  value
>>
>>
>>  
>>
>> 2020-11-06
>>
>>
>>  
>>
>>  
>>
>>  
>>
>>  
>>
>>
>> Basically, I have to get what is in tagC/string but only if the value of
>> tagC/note/title/string is "value". As you see, there are several tagC,
>> all children of tagB, but tagC can have different meanings(!). And no, I
>> have no control over how these XML fields are constructed.
>>
>> In principle it is easy to make a "findall" and get strings for tagC,
>> using:
>>
>> elem.findall("./tagA/tagB/tagC/string")
>>
>> and then get the content and append in case there is more than one
>> tagC/string like: "Something, Something else".
>>
>> However, the hard thing to do here is to get those only when
>> tagC/note/title/string='value'. I was expecting to find a way of
>> specifying a certain construction in square brackets, like
>> [@string='value'] or [@/tagC/note/title/string='value'], as is usual in
>> XML and possible in xml.etree. However this proved difficult (at least
>> for me). So this is the "brute" solution I implemented:
>>
>> - find all children of tagA/tagB
>> - check if /tagA/tagB/tagC/note/title/string has "value"
>> - if yes find all tagA/tagB/tagC/string
>>
>> In quasi-Python:
>>
>> string = []
>> element0 = elem.findall("./tagA/tagB/")
>>  for element1 in element0:
>>  element2 = element1.find("./tagA/tagB/tagC/note/title/string")
>>      if element2.text == 'value'
>>  element3 = element1.findall("./tagA/tagB/tagC/string)
>>  for element4 in element3:
>>  string.append(element4.text)
>>
>>
>> Crude, but works. As I wrote above, I was wishing that a bracketed
>> clause of the type [@ ...] already in the first "findall" would do a
>> more efficient job but alas my knowledge of xml is too rudimentary.
>> Perhaps something to tinker on in the coming weeks.
>>
>> Have a nice weekend!
>>
>>
>>
>>
>>
>> On 2020-11-06 20:10, Terry Reedy wrote:
>> > On 11/6/2020 11:17 AM, Hernán De Angelis wrote:
>> >> I am confronting some XML parsing challenges and would like to ask
>> >> some questions to more knowledgeable Python users. Apparently there
>> >> exists a group for such questions but that list (xml-sig) has
>> >> apparently not received (or archived) posts since May 2018(!). I
>> >> wonder if there are other list or forum for Python XML questions, or
>> >> if this list would be fine for that.
>> >
>> > If you don't hear otherwise, try here.  Or try stackoverflow.com and
>> > tag questions with python and xml.
>> >
>> >
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 3

2020-11-07 Thread Hernán De Angelis
Hi,

Wikipedia has an article on the duodecimal system, that includes an
explanation of how to convert from decimal and the other way around.

https://en.wikipedia.org/wiki/Duodecimal?wprov=sfla1

Peerrhaps it can be easily implemented as a function. Good luck.

H.



Den lör 7 nov. 2020 07:55Nick Li  skrev:

> Does anyone know how to turn a decimal number into duodecimal or if there
> is a function built-in for it?
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Questions about XML processing?

2020-11-06 Thread Hernán De Angelis
Thank you Terry, Dan and Dieter for encouraging me to post here. I have 
already solved the problem albeit with a not so efficient solution. 
Perhaps, it is useful to present it here anyway in case some light can 
be added to this.


My job is to parse a complicated XML (iso metadata) and pick up values 
of certain fields in certain conditions. This goes for the most part 
well. I am working with xml.etree.elementtree, which proved sufficient 
for the most part and the rest of the project. JSON is not an option 
within this project.


The specific trouble was in this section, itself the child of a more 
complicated parent: (for simplicity tags are renamed and namespaces removed)


  
    
  
    Something
  
  
    Something else
  
  
    
  
    value
  
  
    
  
2020-11-06
  
  
    
  
    
  
    
  
    
  

Basically, I have to get what is in tagC/string but only if the value of 
tagC/note/title/string is "value". As you see, there are several tagC, 
all children of tagB, but tagC can have different meanings(!). And no, I 
have no control over how these XML fields are constructed.


In principle it is easy to make a "findall" and get strings for tagC, using:

elem.findall("./tagA/tagB/tagC/string")

and then get the content and append in case there is more than one 
tagC/string like: "Something, Something else".


However, the hard thing to do here is to get those only when 
tagC/note/title/string='value'. I was expecting to find a way of 
specifying a certain construction in square brackets, like 
[@string='value'] or [@/tagC/note/title/string='value'], as is usual in 
XML and possible in xml.etree. However this proved difficult (at least 
for me). So this is the "brute" solution I implemented:


- find all children of tagA/tagB
- check if /tagA/tagB/tagC/note/title/string has "value"
- if yes find all tagA/tagB/tagC/string

In quasi-Python:

string = []
element0 = elem.findall("./tagA/tagB/")
    for element1 in element0:
    element2 = element1.find("./tagA/tagB/tagC/note/title/string")
    if element2.text == 'value'
    element3 = element1.findall("./tagA/tagB/tagC/string)
    for element4 in element3:
    string.append(element4.text)


Crude, but works. As I wrote above, I was wishing that a bracketed 
clause of the type [@ ...] already in the first "findall" would do a 
more efficient job but alas my knowledge of xml is too rudimentary. 
Perhaps something to tinker on in the coming weeks.


Have a nice weekend!





On 2020-11-06 20:10, Terry Reedy wrote:

On 11/6/2020 11:17 AM, Hernán De Angelis wrote:
I am confronting some XML parsing challenges and would like to ask 
some questions to more knowledgeable Python users. Apparently there 
exists a group for such questions but that list (xml-sig) has 
apparently not received (or archived) posts since May 2018(!). I 
wonder if there are other list or forum for Python XML questions, or 
if this list would be fine for that.


If you don't hear otherwise, try here.  Or try stackoverflow.com and 
tag questions with python and xml.




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


Questions about XML processing?

2020-11-06 Thread Hernán De Angelis

Hi everyone

I am confronting some XML parsing challenges and would like to ask some 
questions to more knowledgeable Python users. Apparently there exists a 
group for such questions but that list (xml-sig) has apparently not 
received (or archived) posts since May 2018(!). I wonder if there are 
other list or forum for Python XML questions, or if this list would be 
fine for that.


Thanks in advance

/H.

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


Re: Post request and encoding

2020-11-03 Thread Hernán De Angelis

I see. Should be "encoding". Thanks.

/H.

On 2020-11-03 19:30, Dieter Maurer wrote:

Hernán De Angelis wrote at 2020-11-2 10:06 +0100:

...
My request has the form:

header = {'Content-type':'application/xml', 'charset':'utf-8'}

Not your problem (which you have already resolved) but:
`charset` is not an individual header but a parameter
for the `Content-Type` header. For `xml` `utf-8` is the default charset.

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


Re: Post request and encoding

2020-11-02 Thread Hernán De Angelis

I see, my mistake was (tacitly) assuming that encode() could work in place.

Now I see that it should work in a previous line as you wrote.

Thank you!

/H.

On 2020-11-02 18:32, Karsten Hilbert wrote:

On Mon, Nov 02, 2020 at 06:21:15PM +0100, Hernán De Angelis wrote:

For the record:


Just reply to myself and whoever might find this useful.

encode() must be done within the request call:

Nope (but it can, as you showed).


header = {'Content-type':'application/xml', 'charset':'UTF-8'}
response = requests.post(server, data=request.encode('utf-8'),
headers=header)

not in a previous separate line as I did.

Your separate line was wrong as much as ayone can guess:


I have tried of course adding

request.encode('utf-8')

before sending the request but it has not lead to a different result.

You would have needed to do:

request = request.encode('utf-8')

because .encode() does not operate in-place.

Karsten
--
GPG  40BE 5B0E C98E 1713 AFA6  5BC0 3BEA AC80 7D4F C89B

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


Re: Post request and encoding

2020-11-02 Thread Hernán De Angelis

Just reply to myself and whoever might find this useful.

encode() must be done within the request call:

header = {'Content-type':'application/xml', 'charset':'UTF-8'}
response = requests.post(server, data=request.encode('utf-8'), 
headers=header)


not in a previous separate line as I did.

Now it works. This wasn't an obvious way to proceed for me.

/H.


On 2020-11-02 10:06, Hernán De Angelis wrote:

Hi everyone,

I am writing a program that sends a post request to a server. The post 
request may include keywords with Swedish characters (åöä).


I noticed that requests that include strings without those characters 
return a useful expected response. On the other hand, posts including 
those characters return an 'empty' response. However, if I save that 
same request to a file and send it using wget I do get a useful 
response. This suggests to me that the problem should be in how the 
post is sent or processed before being sent and not in how it is 
generated.


My request has the form:

header = {'Content-type':'application/xml', 'charset':'utf-8'}
response = requests.post(server, data=request, headers=header)

I have tried of course adding

request.encode('utf-8')

before sending the request but it has not lead to a different result.

I have spent several hours trying to understand whats going on here. I 
thought at first that this had to do with an issue described here: 
https://github.com/psf/requests/issues/5560 but apparently that issue 
was closed as it was deemed to be unrelated to the requests library.



Has anyone experienced this before? Is there something obvious I am 
missing here?


I am not new to programming but relatively new to Python, so bear with 
me please.



Thanks in advance

/H.


If it is of any use, I post the following too:

python3 -m requests.help
{
"chardet": {
"version": "3.0.4"
},
"cryptography": {
"version": "3.1.1"
},
"idna": {
"version": "2.10"
},
"implementation": {
"name": "CPython",
"version": "3.8.5"
},
"platform": {
"release": "5.9.1-1-default",
"system": "Linux"
},
"pyOpenSSL": {
"openssl_version": "1010108f",
"version": "19.1.0"
},
"requests": {
"version": "2.24.0"
},
"system_ssl": {
"version": "1010108f"
},
"urllib3": {
"version": "1.25.10"
},
"using_pyopenssl": true
}


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


Post request and encoding

2020-11-02 Thread Hernán De Angelis

Hi everyone,

I am writing a program that sends a post request to a server. The post 
request may include keywords with Swedish characters (åöä).


I noticed that requests that include strings without those characters 
return a useful expected response. On the other hand, posts including 
those characters return an 'empty' response. However, if I save that 
same request to a file and send it using wget I do get a useful 
response. This suggests to me that the problem should be in how the post 
is sent or processed before being sent and not in how it is generated.


My request has the form:

header = {'Content-type':'application/xml', 'charset':'utf-8'}
response = requests.post(server, data=request, headers=header)

I have tried of course adding

request.encode('utf-8')

before sending the request but it has not lead to a different result.

I have spent several hours trying to understand whats going on here. I 
thought at first that this had to do with an issue described here: 
https://github.com/psf/requests/issues/5560 but apparently that issue 
was closed as it was deemed to be unrelated to the requests library.



Has anyone experienced this before? Is there something obvious I am 
missing here?


I am not new to programming but relatively new to Python, so bear with 
me please.



Thanks in advance

/H.


If it is of any use, I post the following too:

python3 -m requests.help
{
"chardet": {
"version": "3.0.4"
},
"cryptography": {
"version": "3.1.1"
},
"idna": {
"version": "2.10"
},
"implementation": {
"name": "CPython",
"version": "3.8.5"
},
"platform": {
"release": "5.9.1-1-default",
"system": "Linux"
},
"pyOpenSSL": {
"openssl_version": "1010108f",
"version": "19.1.0"
},
"requests": {
"version": "2.24.0"
},
"system_ssl": {
"version": "1010108f"
},
"urllib3": {
"version": "1.25.10"
},
"using_pyopenssl": true
}

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


Re: Decorators with arguments?

2020-05-25 Thread Christopher de Vidal
Peter Otten, Cameron Simpson, thank you for your detailed replies :-) I
confess, I didn't quite understand all you were saying. (Still only an
intermediate-level programmer.) But Cameron what you said questioning my
use of decorators and maybe a class instead got me thinking. I realized
what I needed was a function within a function. Couldn't have gotten there
without your help. Working code:

#!/usr/bin/env python3
from google.cloud import firestore
import firebase_admin
from firebase_admin import credentials
import json
import mqtt
from time import sleep

def bridge(col_name):
def on_snapshot(col_snapshot, changes, read_time):
data = dict()
for doc in col_snapshot:
serial = doc.id
data[serial] = json.dumps(doc.to_dict()['value'])
for change in changes:
serial = change.document.id
mqtt_topic = col_name + '/outgoing/' + serial
if change.type.name in ['ADDED', 'MODIFIED']:
contents = data[serial]
mqtt.publish(mqtt_topic, contents)
elif change.type.name == 'REMOVED':
mqtt.publish(mqtt_topic, '')


@mqtt.incoming
def mqtt_subscribe(serial, value):
# TODO Passing a None entry to delete from MQTT doesn't trigger
this
#   callback, so it doesn't delete from Firestore. Need this ugly
#   workaround 'clear_mqtt'.
if value == 'clear_mqtt':
value = None
mqtt.publish(col_name + '/incoming/' + serial, None)
mqtt.publish(col_name + '/outgoing/' + serial, None)
db.collection(col_name).document(serial).set({'value': value})


col_watch = db.collection(col_name).on_snapshot(on_snapshot)
mqtt.subscribe(col_name + '/incoming/#', mqtt_subscribe)
return col_watch


cred = credentials.Certificate("certs/firebase.json")
firebase_admin.initialize_app(cred)
db = firestore.Client()
mqtt.connect()
adapters = list()
for collection in ['door_status', 'cpu_temp']:
adapters.append(bridge(collection))
while True:
sleep(1)
for adapter in adapters:
adapter.unsubscribe()

Christopher de Vidal

Would you consider yourself a good person? Have you ever taken the 'Good
Person' test? It's a fascinating five minute quiz. Google it.


On Fri, May 15, 2020 at 9:55 AM Peter Otten <__pete...@web.de> wrote:

> Christopher de Vidal wrote:
>
> > Help please? Creating an MQTT-to-Firestore bridge and I know a decorator
> > would help but I'm stumped how to create one. I've used decorators before
> > but not with arguments.
> >
> > The Firestore collection.on_snapshot() method invokes a callback and
> sends
> > it three parameters (collection_snapshot, changes, and read_time). I need
> > the callback to also know the name of the collection so that I can
> publish
> > to the equivalent MQTT topic name. I had thought to add a fourth
> parameter
> > and I believe a decorator is the right approach but am stumped how to add
> > that fourth parameter. How would I do this with the code below?
> >
> > #!/usr/bin/env python3
> > from google.cloud import firestore
> > import firebase_admin
> > from firebase_admin import credentials
> > import json
> > import mqtt
> >
> >
>
> firebase_admin.initialize_app(credentials.Certificate("certs/firebase.json"))
> > db = firestore.Client()
> > mqtt.connect()
> >
> >
> > def load_json(contents):
> > try:
> > return json.loads(contents)
> > except (json.decoder.JSONDecodeError, TypeError):
> > return contents
> >
> >
> > def on_snapshot(col_name, col_snapshot, changes, read_time):
> > data = dict()
> > for doc in col_snapshot:
> > serial = doc.id
> > contents = load_json(doc.to_dict()['value'])
> > data[serial] = contents
> > for change in changes:
> > serial = change.document.id
> > mqtt_topic = col_name + '/' + serial
> > contents = data[serial]
> > if change.type.name in ['ADDED', 'MODIFIED']:
> > mqtt.publish(mqtt_topic, contents)
> > elif change.type.name == 'REMOVED':
> > mqtt.publish(mqtt_topic, None)
> >
> >
> > # Start repeated code section
> > # TODO Better to use decorators but I was stumped on how to pass
> arguments
> > def door_status_on_snapshot(col_snapshot, changes, read_time):
> > on_snapshot('door_status', col_snapshot, changes, read_time)
> &g

Decorators with arguments?

2020-05-14 Thread Christopher de Vidal
Help please? Creating an MQTT-to-Firestore bridge and I know a decorator
would help but I'm stumped how to create one. I've used decorators before
but not with arguments.

The Firestore collection.on_snapshot() method invokes a callback and sends
it three parameters (collection_snapshot, changes, and read_time). I need
the callback to also know the name of the collection so that I can publish
to the equivalent MQTT topic name. I had thought to add a fourth parameter
and I believe a decorator is the right approach but am stumped how to add
that fourth parameter. How would I do this with the code below?

#!/usr/bin/env python3
from google.cloud import firestore
import firebase_admin
from firebase_admin import credentials
import json
import mqtt

firebase_admin.initialize_app(credentials.Certificate("certs/firebase.json"))
db = firestore.Client()
mqtt.connect()


def load_json(contents):
try:
return json.loads(contents)
except (json.decoder.JSONDecodeError, TypeError):
return contents


def on_snapshot(col_name, col_snapshot, changes, read_time):
data = dict()
for doc in col_snapshot:
serial = doc.id
contents = load_json(doc.to_dict()['value'])
data[serial] = contents
for change in changes:
serial = change.document.id
mqtt_topic = col_name + '/' + serial
contents = data[serial]
if change.type.name in ['ADDED', 'MODIFIED']:
mqtt.publish(mqtt_topic, contents)
elif change.type.name == 'REMOVED':
mqtt.publish(mqtt_topic, None)


# Start repeated code section
# TODO Better to use decorators but I was stumped on how to pass arguments
def door_status_on_snapshot(col_snapshot, changes, read_time):
on_snapshot('door_status', col_snapshot, changes, read_time)


door_status_col_ref = db.collection('door_status')
door_status_col_watch =
door_status_col_ref.on_snapshot(door_status_on_snapshot)

# Repetition...
def cpu_temp_on_snapshot(col_snapshot, changes, read_time):
on_snapshot('cpu_temp', col_snapshot, changes, read_time)


cpu_temp_col_ref = db.collection('cpu_temp')
cpu_temp_col_watch = cpu_temp_col_ref.on_snapshot(cpu_temp_on_snapshot)
# End repeated code section

# Start repeated code section
door_status_col_watch.unsubscribe()
cpu_temp_col_watch.unsubscribe()
# Repetition...
# End repeated code section

Christopher de Vidal

Would you consider yourself a good person? Have you ever taken the 'Good
Person' test? It's a fascinating five minute quiz. Google it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Fw: Python installation problem

2020-04-01 Thread HERNANDEZ AGUIRRE JOSE GABRIEL DE LA DOLOROSA



En Mar, 31 Marzo, 2020 en 18:48, yo  escribió:
 

Para: python-list@python.org

I  installed  the Python software , but I could not find the python.exe file 
with the Unscramble software


What do you advise ?


Regards



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


Why an InitVar pseudo field in dataclasses cannot have a default_factory?

2019-07-17 Thread Jacobo de Vera
Hi all,

I was surprised by an error when trying to set a default_factory for an
InitVar pseudo-field in a dataclass. Inspecting the code in dataclasses.py
led me to this:

# Special restrictions for ClassVar and InitVar.
if f._field_type in (_FIELD_CLASSVAR, _FIELD_INITVAR):
if f.default_factory is not MISSING:
raise TypeError(f'field {f.name} cannot have a '
'default factory')
# Should I check for other field settings? default_factory
# seems the most serious to check for.  Maybe add others.  For
# example, how about init=False (or really,
# init=)?  It makes no sense for
# ClassVar and InitVar to specify init=.

So this case is very explicitly prevented but I could not see why. Does
anybody know what problem this is trying to prevent or what is the
rationale behind this restriction?

I asked in stackoverflow[1] and I was suggested to ask here.

[1] https://stackoverflow.com/questions/57056029

Thanks,
Jacobo de Vera
@jovianjake
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: can not use pycharm

2019-06-14 Thread Informatico de Neurodesarrollo



El 10/06/19 a las 13:28, aris escribió:


Hello,this is my first time trying to learn coding and programming and I wanted to 
start with python.Though,when I download pycharm, I go to 
configure>settings>project interpreter and i can not put a project interpreter( 
I have download python version 3) .What should I do?thank you for your time.



Hi Aris:
You must go to: File -> Settings
and below of "Version Control" you find like this: Project:"project 
name" -> Project Interpreter and the top at your right hand you find 
litle button and you can add (configure) an interpreter: Virtualenv 
Enviroment, Conda Env., System Interpreter, Pipenv Env.., etc.


You must use the last (at least a version after mars of the last year ), 
because include the pipenv support.


I hope that can help you.

PD Before all, you must have already installed pipenv in your system.

--

Ing. Jesús Reyes Piedra
Admin Red Neurodesarrollo,Cárdenas
La caja decía:"Requiere windows 95 o superior"...
Entonces instalé LINUX.


--
Este mensaje le ha llegado mediante el servicio de correo electronico que 
ofrece Infomed para respaldar el cumplimiento de las misiones del Sistema 
Nacional de Salud. La persona que envia este correo asume el compromiso de usar 
el servicio a tales fines y cumplir con las regulaciones establecidas

Infomed: http://www.sld.cu/

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


Re: Farewell, Python 3.4

2019-05-10 Thread Informatico de Neurodesarrollo

Good job, Larry !!!


El 08/05/19 a las 11:36, Larry Hastings escribió:


It's with a note of sadness that I announce the final retirement of 
Python 3.4.  The final release was back in March, but I didn't get 
around to actually closing and deleting the 3.4 branch until this 
morning.


Python 3.4 introduced many features we all enjoy in modern Python--the 
asyncio, ensurepip, and enum packages, just to name three.  It's a 
release I hope we all remember fondly.


My eternal thanks to all the members of the release team that worked 
on Python 3.4:


   Georg Brandl

   Julien Palard

   Martin von Löwis

   Ned Deily

   Steve Dower

   Terry Reedy

   and all the engineers of the Python infrastructure team.

Special thanks to Benjamin Peterson and Ned Deily, who frequently 
scurried around behind the scenes cleaning up the messes I cluelessly 
left in my wake.


Having closed 3.4, I am now retired as Python 3.4 Release Manager.  I 
regret to inform all of you that you're still stuck with me as Python 
3.5 Release Manager until sometime next year.



My very best wishes,


//arry/



--

Ing. Jesús Reyes Piedra
Admin Red Neurodesarrollo,Cárdenas
La caja decía:"Requiere windows 95 o superior"...
Entonces instalé LINUX.


--
Este mensaje le ha llegado mediante el servicio de correo electronico que 
ofrece Infomed para respaldar el cumplimiento de las misiones del Sistema 
Nacional de Salud. La persona que envia este correo asume el compromiso de usar 
el servicio a tales fines y cumplir con las regulaciones establecidas

Infomed: http://www.sld.cu/

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


Re: Might be doing this wrong? (Turtle graphics)

2019-03-21 Thread Informatico de Neurodesarrollo
If you run on linux system? May be you are already installed for python 
3, but not for python (python 2.7) or vice_versa .


Checks this.

(The code work fine, openSuSE Leap 15)


El 20/03/19 a las 19:34, jasonanyil...@gmail.com escribió:

So, I typed in code:
from turtle import *
forward(100)
right(120)
clear()
It didn't work! It kept on saying that there was an indent and the first line 
was wrong. Help!


--

Ing. Jesús Reyes Piedra
Admin Red Neurodesarrollo,Cárdenas
La caja decía:"Requiere windows 95 o superior"...
Entonces instalé LINUX.


--
Este mensaje le ha llegado mediante el servicio de correo electronico que 
ofrece Infomed para respaldar el cumplimiento de las misiones del Sistema 
Nacional de Salud. La persona que envia este correo asume el compromiso de usar 
el servicio a tales fines y cumplir con las regulaciones establecidas

Infomed: http://www.sld.cu/

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


Re: tkinter

2019-03-20 Thread Informatico de Neurodesarrollo
Thanks MRAB, for your advice. I will have close the connection before, 
the code fixed are below.


def isInternet():
        testConn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        testConn.settimeout(5)
        output = testConn.connect_ex(('8.8.8.8', 80))
        testConn.close() <---
        if output == 0:
            return True
        else:
            return False


El 19/03/19 a las 17:55, MRAB escribió:

On 2019-03-19 19:46, Informatico de Neurodesarrollo wrote:

Thanks for all yours recommendations, finally I was successfully
finished my first project about tkinter (and I hope, not the last).

Here is the finally code:

#!/usr/bin/env python
#
#  DetectConn_2_0.py
#
#

from tkinter import *
import time, socket

def isInternet():
          testConn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
         # Force a time limit to conect to the host (5 seg), may be more
or less
       testConn.settimeout(5)
       output = testConn.connect_ex(('10.44.0.1', 80))


The following lines will cause a return from the function, so the 
testConn.close() line will never be reached.


Fortunately, the socket will be closed anyway, when the garbage 
collection occurs.



          if output == 0:
              return True
          else:
              return False
          testConn.close()

def colorupdate():
      if isInternet():
          root.config(background="#38EB5C")
      else:
          root.config(background="#F50743")
      root.after(5000, colorupdate)

root = Tk()
root.title("Connection")
root.geometry("80x50")
root.resizable(width=False, height=False)

colorupdate()
root.mainloop()


Thanks again




--

Ing. Jesús Reyes Piedra
Admin Red Neurodesarrollo,Cárdenas
La caja decía:"Requiere windows 95 o superior"...
Entonces instalé LINUX.


--
Este mensaje le ha llegado mediante el servicio de correo electronico que 
ofrece Infomed para respaldar el cumplimiento de las misiones del Sistema 
Nacional de Salud. La persona que envia este correo asume el compromiso de usar 
el servicio a tales fines y cumplir con las regulaciones establecidas

Infomed: http://www.sld.cu/

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


Re: tkinter

2019-03-19 Thread Informatico de Neurodesarrollo
Thanks for all yours recommendations, finally I was successfully 
finished my first project about tkinter (and I hope, not the last).


Here is the finally code:

#!/usr/bin/env python
#
#  DetectConn_2_0.py
#
#

from tkinter import *
import time, socket

def isInternet():
        testConn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
       # Force a time limit to conect to the host (5 seg), may be more 
or less

     testConn.settimeout(5)
     output = testConn.connect_ex(('10.44.0.1', 80))
        if output == 0:
            return True
        else:
            return False
        testConn.close()

def colorupdate():
    if isInternet():
        root.config(background="#38EB5C")
    else:
        root.config(background="#F50743")
    root.after(5000, colorupdate)

root = Tk()
root.title("Connection")
root.geometry("80x50")
root.resizable(width=False, height=False)

colorupdate()
root.mainloop()


Thanks again


--

Ing. Jesús Reyes Piedra
Admin Red Neurodesarrollo,Cárdenas
La caja decía:"Requiere windows 95 o superior"...
Entonces instalé LINUX.


--
Este mensaje le ha llegado mediante el servicio de correo electronico que 
ofrece Infomed para respaldar el cumplimiento de las misiones del Sistema 
Nacional de Salud. La persona que envia este correo asume el compromiso de usar 
el servicio a tales fines y cumplir con las regulaciones establecidas

Infomed: http://www.sld.cu/

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


Re: tkinter

2019-03-18 Thread Informatico de Neurodesarrollo

Thanks, I was noted it. I have figure out, how can I do that.

I keep in touch


El 18/03/19 a las 14:09, MRAB escribió:

On 2019-03-18 16:00, Informatico de Neurodesarrollo wrote:

Hello friends:

I am a beginner on programming in python.

I want make a simple program that test continuously (every 5 seg) the
connection  to internet and change the background color when are not
available. I try this , but not work properly:

   #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
from tkinter import *
import socket, time

def DetectarConexion():
      testConn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
      try:
          testConn.connect(('8.8.8.8', 80))
          testConn.close()
          return True
      except:
          testConn.close()
          return False

root = Tk()
root.title("Conexión")
root.geometry("80x50")

You have a problem here: the loop will repeat forever, so you'll never 
reach the root.mainloop() line and show the GUI.



while True:
      if DetectarConexion():
          # Background:Green
          root.config(background="#38EB5C")
      else:
          # Background:Red
          root.config(background="#F50743")
      time.sleep(5)

root.mainloop()


Any ideas, will be welcome.



--

Ing. Jesús Reyes Piedra
Admin Red Neurodesarrollo,Cárdenas
La caja decía:"Requiere windows 95 o superior"...
Entonces instalé LINUX.


--
Este mensaje le ha llegado mediante el servicio de correo electronico que 
ofrece Infomed para respaldar el cumplimiento de las misiones del Sistema 
Nacional de Salud. La persona que envia este correo asume el compromiso de usar 
el servicio a tales fines y cumplir con las regulaciones establecidas

Infomed: http://www.sld.cu/

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


Re: tkinter

2019-03-18 Thread Informatico de Neurodesarrollo
This code work fine, every 5 second test the connection to this machine 
(10.44.0.15) on my network.


#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  DetectConn_1_0.py
#
#First: Testing connection
#

import socket, time

def isInternet():
    testConn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    output = testConn.connect_ex(('10.44.0.15', 80))
    if output == 0:
    return True
    else:
    return False
    testConn.close()

while True:
    if isInternet():
        print("Hay conexión")
    else:
        print("No hay conexión")

    time.sleep(5)


What's next?, I am all eyes

El 18/03/19 a las 12:44, Chris Angelico escribió:

On Tue, Mar 19, 2019 at 3:33 AM Informatico de Neurodesarrollo
 wrote:

Hello friends:

I am a beginner on programming in python.

Cool! Then I would recommend making your program as simple as you possibly can.


I want make a simple program that test continuously (every 5 seg) the
connection  to internet and change the background color when are not
available. I try this , but not work properly:

   #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
from tkinter import *
import socket, time

def DetectarConexion():
  testConn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  try:
  testConn.connect(('8.8.8.8', 80))
  testConn.close()
  return True
  except:
  testConn.close()
  return False

This part of the code is completely independent of the Tkinter code.
Split it up into the two parts and develop each one separately.


root = Tk()
root.title("Conexión")
root.geometry("80x50")

while True:
  if DetectarConexion():
  # Background:Green
  root.config(background="#38EB5C")
  else:
  # Background:Red
  root.config(background="#F50743")
  time.sleep(5)

root.mainloop()


You have two separate parts to this code, and it's possible that
neither of them is working. I would recommend concentrating first on
the connection status function. Remove everything about Tkinter, and
replace it with a simple print() call:

while True:
 if DetectarConexion():
 print("Connection is happy")
 else:
 print("Connection is down!")
 time.sleep(5)

Now you can work on making sure your connection tester is working.
What exactly are you testing? What goes wrong when you don't have a
connection?

Specific advice:
1) Avoid using the bare "except:" clause. It may be hiding bugs in your code.
2) Make sure you're trying something that actually does work.
Connecting to 8.8.8.8 port 80 isn't going to succeed even if your
connection is live.

Start with that, and you should be able to get a lot further with your testing.

Have fun with it! If you run into trouble, post your updated code,
what you're trying, and what's happening.

Chris Angelico


--

Ing. Jesús Reyes Piedra
Admin Red Neurodesarrollo,Cárdenas
La caja decía:"Requiere windows 95 o superior"...
Entonces instalé LINUX.


--
Este mensaje le ha llegado mediante el servicio de correo electronico que 
ofrece Infomed para respaldar el cumplimiento de las misiones del Sistema 
Nacional de Salud. La persona que envia este correo asume el compromiso de usar 
el servicio a tales fines y cumplir con las regulaciones establecidas

Infomed: http://www.sld.cu/

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


tkinter

2019-03-18 Thread Informatico de Neurodesarrollo

Hello friends:

I am a beginner on programming in python.

I want make a simple program that test continuously (every 5 seg) the 
connection  to internet and change the background color when are not 
available. I try this , but not work properly:


 #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
from tkinter import *
import socket, time

def DetectarConexion():
    testConn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        testConn.connect(('8.8.8.8', 80))
        testConn.close()
        return True
    except:
        testConn.close()
        return False

root = Tk()
root.title("Conexión")
root.geometry("80x50")

while True:
    if DetectarConexion():
        # Background:Green
        root.config(background="#38EB5C")
    else:
        # Background:Red
        root.config(background="#F50743")
    time.sleep(5)

root.mainloop()


Any ideas, will be welcome.


T.I.A


--

Ing. Jesús Reyes Piedra
Admin Red Neurodesarrollo,Cárdenas
La caja decía:"Requiere windows 95 o superior"...
Entonces instalé LINUX.


--
Este mensaje le ha llegado mediante el servicio de correo electronico que 
ofrece Infomed para respaldar el cumplimiento de las misiones del Sistema 
Nacional de Salud. La persona que envia este correo asume el compromiso de usar 
el servicio a tales fines y cumplir con las regulaciones establecidas

Infomed: http://www.sld.cu/

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


Re: subprocess svn checkout password issue

2019-03-15 Thread Martin De Kauwe
On Saturday, 16 March 2019 16:50:23 UTC+11, dieter  wrote:
> Martin De Kauwe  writes:
> 
> > I'm trying to write a script that will make a checkout from a svn repo and 
> > build the result for the user. However, when I attempt to interface with 
> > the shell it asks the user for their filename and I don't know how to 
> > capture this with my implementation. 
> >
> > user = "XXX578"
> > root="https://trac.nci.org.au/svn/cable";
> > repo_name = "CMIP6-MOSRS"
> >
> > cmd = "svn checkout %s/branches/Users/%s/%s" % (root, user, repo_name)
> > p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
> >   stdout=subprocess.PIPE, 
> > stderr=subprocess.PIPE)
> > error = subprocess.call(cmd, shell=True)
> > if error is 1:
> > raise("Error downloading repo"
> >
> > I tried adding .wait(timeout=60) to the subprocess.Popen command but that 
> > didn't work.
> >
> > Any advice on whether there is an augmentation to the above, or a better 
> > approach, would be much appreciated. I need to solve this with standard 
> > python libs as I'm trying to make this as simple as possible for the user.
> 
> That is non-trivial.
> 
> Read the "svn" documentation. You might be able to pass in the
> required information by other means, maybe an option, maybe
> an envvar, maybe via a configuration file.
> 
> Otherwise, you must monitor what it written to the subprocess'
> "stdout" and "stderr", recognized the interaction request
> perform the interaction with the user and send the result
> to the subprocess' stdin.

Thanks, I think this solution will work.

import subprocess
import getpass

user = "XXX578"
root="https://trac.nci.org.au/svn/cable";
repo_name = "CMIP6-MOSRS"

pswd = "'" + getpass.getpass('Password:') + "'"
cmd = "svn checkout %s/branches/Users/%s/%s --password %s" %\
 (root, user, repo_name, pswd)
error = subprocess.call(cmd, shell=True)
if error is 1:
raise("Error checking out repo")
-- 
https://mail.python.org/mailman/listinfo/python-list


subprocess svn checkout password issue

2019-03-15 Thread Martin De Kauwe
Hi,

I'm trying to write a script that will make a checkout from a svn repo and 
build the result for the user. However, when I attempt to interface with the 
shell it asks the user for their filename and I don't know how to capture this 
with my implementation. 

user = "XXX578"
root="https://trac.nci.org.au/svn/cable";
repo_name = "CMIP6-MOSRS"

cmd = "svn checkout %s/branches/Users/%s/%s" % (root, user, repo_name)
p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
  stdout=subprocess.PIPE, 
stderr=subprocess.PIPE)
error = subprocess.call(cmd, shell=True)
if error is 1:
raise("Error downloading repo"

I tried adding .wait(timeout=60) to the subprocess.Popen command but that 
didn't work.

Any advice on whether there is an augmentation to the above, or a better 
approach, would be much appreciated. I need to solve this with standard python 
libs as I'm trying to make this as simple as possible for the user.

The full script is here if that helps:

https://github.com/mdekauwe/CABLE_benchmarking/blob/master/scripts/get_cable.py

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


Re: ESR "Waning of Python" post

2018-10-12 Thread Vito De Tullio
Chris Angelico wrote:

>> Reference counting was likely a bad idea to begin with.
> 
> Then prove CPython wrong by making a fantastically better
> implementation that uses some other form of garbage collection.

I'm not talking about the "goodness" of the implemetations, but AFAIK jython 
and ironpython doesn't have the refcount gb (and they don't even have the 
GIL...)


-- 
By ZeD

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


Re: How to upload to Pythonhosted.org

2017-11-30 Thread Irmen de Jong
On 11/30/2017 03:31 AM, Ben Finney wrote:
> Irmen de Jong  writes:
> 
>> On 11/30/2017 02:06 AM, waylan wrote:
>>> So, how do I upload an update to my documentation?
>>
>> I ran into the same issue. From what I gathered, Pythonhosted.org is
>> in the process of being dismantled and it hasn't allowed new doc
>> uploads for quite some time now. I switched to using readthedocs.io
>> instead.
> 
> The issue that many are facing is how to update the pages *at the
> existing URL* to tell visitors where to go next. Cool URIs don't change
> https://www.w3.org/Provider/Style/URI.html> but, when they do, we
> are obliged to update the existing pages to point to the new ones.

Sorry, yes, that is the problem I experience as well. My library's old version
documentation is somehow frozen on Pythonhosted.org (and obviously still pops 
up as the
first few google hits).


> So, if pythonhosted.org is indeed being dismantled, there should be a
> way to update the pages there for informing visitor where they should go
> next.
> 
> If that's not possible and instead the service is just locked down,
> that's IMO a mistake.

I agree with that. I think it's an unsolved issue until now, that gets some 
discussion
in this github issue https://github.com/pypa/warehouse/issues/582


Irmen




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


Re: How to upload to Pythonhosted.org

2017-11-29 Thread Irmen de Jong
On 11/30/2017 02:06 AM, waylan wrote:
> I've been hosting documentation for many years on pythonhosted.org. However, 
> I can't seem to upload any updates recently. The homepage at 
> http://pythonhosted.org states:
> 
>> To upload documentation, go to your package edit page 
>> (http://pypi.python.org/pypi?%3Aaction=pkg_edit&name=yourpackage), and fill 
>> out the form at the bottom of the page.
> 
> However, there is no longer a form at the bottom of the edit page for 
> uploading documentation. Instead I only see:
> 
>> If you would like to DESTROY any existing documentation hosted at 
>> http://pythonhosted.org/ProjectName Use this button, There is no undo.
>>
>> [Destroy Documentation]
> 
> I also went to pypi.org and logged in there. But I don't see any options for 
> editing my projects or uploading documentation on that site.
> 
> So, how do I upload an update to my documentation?
> 
> Waylan
> 


I ran into the same issue. From what I gathered, Pythonhosted.org is in the 
process of
being dismantled and it hasn't allowed new doc uploads for quite some time now.
I switched to using readthedocs.io instead. That one is faster and has the 
additional
benefit that you can configure it in such a way that you don't have to upload 
docs
yourself anymore; it can rebuild them on the fly when it detects a change in 
your github
repo

Irmen

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


Re: Code Snippets

2017-11-01 Thread Irmen de Jong
On 11/01/2017 06:25 PM, Stefan Ram wrote:

> import random
> ...
> random.random()
> 
>   Now, the user has to cut the import, paste it to the top
>   of his code, then go back to the list of snippets, find
>   the same snippet again, copy the expression, go to his code,
>   then find the point where he wanted to insert the snippet again,
>   and finally insert the snippet. And still there now is a
>   risk of name collisions. So, it seems to me that __import__
>   is just so much better!

..or suggest them to use an IDE instead? For instance in PyCharm you can type:
random.random()   (squiggle appears under random)

(it suggests: Import This name)  
(it suggests: from random) 
done, an import random has been added at the top of my module.


Irmen


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


Re: How to determine lowest version of Python 3 to run?

2017-10-05 Thread Irmen de Jong
On 10/05/2017 04:23 AM, Christopher Reimer wrote:

> I'm leaning towards installing the latest minor version of each available 
> major version, running tox to run the unit tests against each one, and seeing 
> what blows up.

Perhaps you can use the service of Travis (travis-ci.org) to avoid installing 
the Python
versions yourself. They have lots of older versions available to run tests on.

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


Re: auto installing dependencies with pip to run a python zip application ?

2017-09-28 Thread Irmen de Jong
On 09/28/2017 09:40 AM, Paul Moore wrote:
> Are you aware of pipsi? If you do `pipsi install somepackage` it
> creates a new virtualenv in ~/.local/.venvs, populates it with
> somepackage and its dependencies, and then puts the entry point
> scripts for somepackage into ~/.local/bin. It may be a useful way of
> delivering your program, rather than building the virtualenv
> management in yourself.

No I wasn't aware of this tool, thanks for sharing. It's not what I am
looking for but it's always nice to know of some alternatives

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


Re: auto installing dependencies with pip to run a python zip application ?

2017-09-27 Thread Irmen de Jong
On 09/27/2017 09:50 AM, Paul Moore wrote:

>>> What you could do is pip install your binary dependencies into a
>>> directory in $TEMP using --target, then add that directory to
>>> sys.path. Probably easier than building a full virtualenv. Bundle pip
>>> with your app if you can't assume your users will have pip available.
>>
>> Interesting idea, although like this wouldn't I have to download the
>> dependencies every time I launch my game? (unless I re-use the same
>> temporary directory every time)
> 
> Ah, I'd assumed that's what you were doing with the virtualenv, I
> hadn't realised you were talking about a one-off setup step. Yeah,
> re-using a temporary directory doesn't buy you much compared to using
> a virtualenv (particularly if you can target versions of Python that
> have the built in venv module).

Well, I was planning on using a fixed name/location for the virtualenv.
That way when you request pip to install the dependencies again at next
launch, it will detect them already satisfied and not download/reinstall
everything. I could even test for their existence first myself in my
application (which is what I'm already doing now, to give the user a
clear error message) and only invoke pip when a dependency is missing.


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


Re: Boolean Expressions

2017-09-26 Thread Irmen de Jong
On 09/27/2017 12:23 AM, Cai Gengyang wrote:
> 
> I'm trying to understand the logic behind AND. I looked up Python logic tables
> 
> False and False gives False
> False and True gives False
> True and False gives False
> True and True gives True.
> 
> So does that mean that the way 'and' works in Python is that both terms must 
> be True (1) for the entire expression to be True ? Why is it defined that 
> way, weird ? I was always under the impression that 'and' means that when you 
> have both terms the same, ie either True and True or False and False , then 
> it gives True

There is nothing Python specific about this, by the way.
It is how AND - ∧ - has been defined in Boolean Algebra forever.  It's a
logical conjunction of its operands, it doesn't test for the 'equality'
of its operands.  https://en.wikipedia.org/wiki/Logical_conjunction


Irmen



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


Re: auto installing dependencies with pip to run a python zip application ?

2017-09-26 Thread Irmen de Jong
On 09/26/2017 10:49 PM, Paul Moore wrote:
> On 26 September 2017 at 19:47, Irmen de Jong  wrote:
>> Any thoughts on this? Is it a good idea or something horrible? Has
>> someone attempted something like this before perhaps?
> 
> When I've done this, I've bundled my dependencies in with my zipapp.
> Of course that's trickier if you have binary dependencies like pillow.

Yeah I've considered that for a moment but I think sometimes you've also
got to deal with licensing issues. I'd rather avoid this.

> What you could do is pip install your binary dependencies into a
> directory in $TEMP using --target, then add that directory to
> sys.path. Probably easier than building a full virtualenv. Bundle pip
> with your app if you can't assume your users will have pip available.

Interesting idea, although like this wouldn't I have to download the
dependencies every time I launch my game? (unless I re-use the same
temporary directory every time)


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


Re: auto installing dependencies with pip to run a python zip application ?

2017-09-26 Thread Irmen de Jong
On 09/26/2017 09:19 PM, Thomas Jollans wrote:
>> - use venv.EnvBuilder() to create a new virtualenv somewhere in the
>> user's home directory (~./virtualenvs/mygreatgame ?)
> 
> The appropriate place for this kind of thing, on Linux, would be
> $XDG_DATA_HOME, default "~/.local/share/", i.e.:
> 
> f"{os.getenv('XDG_DATA_HOME', os.path.expanduser(
> '~/.local/share'))}/{my_app}/{subdir}"
> 
> Other operating system have other conventions. (On Windows I think
> os.getenv('APPDATA') is a good place to start)

Ah, yes thanks for this reminder. I used the appdirs library elsewhere
to take care of this but this is not available (yet) until we are
running in the virtual env

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


auto installing dependencies with pip to run a python zip application ?

2017-09-26 Thread Irmen de Jong
Hi,
I've been using Python's executable zip application feature to neatly
package my little game into a single "executable" file.
Here "executable" means the user can simply start it by doubleclicking
it, or launching it from a shell prompt. Of course the user already has
to have a proper Python installation on their system but that's okay for me.

However, I would like to also take care of the library dependencies of
my game. Currently it requires pillow and sounddevice. If the user
doesn't have these installed, the game exits with an error message
telling the user to install these dependencies manually. I was thinking
about a way to automate this so that you don't have to install anything
manually to run the game.

I was thinking about the following solution:
- assume bare default Python (3.5+) installation
- use venv.EnvBuilder() to create a new virtualenv somewhere in the
user's home directory (~./virtualenvs/mygreatgame ?)
- use the with_pip=True argument so we also get pip installed into it
- exec() the python executable from the new virtual env and let that
"pip install -r mygamerequirements.txt"
- inject "./mygame.pyz" in sys.modules[0]
- run the game's main class and play!

Notice that I'm not looking for a fully standalone executable created by
things as cx_freeze, just something that is usable from within my zipped
application.

Any thoughts on this? Is it a good idea or something horrible? Has
someone attempted something like this before perhaps?

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


Re: Fw: Problems Installing Python36

2017-09-22 Thread Irmen de Jong
On 09/22/2017 08:34 PM, Stephan Houben wrote:

> I was vaguely tempted to offer the Mingw-w64 (GCC) Python as an
> alternative, since it doesn't rely on any optionally-installed Microsoft
> DLLs and so avoids this issue. But I suppose that is not really the
> newbie-friendly solution the OP was looking for...

Mingw? Perhaps better to choose Anaconda/Miniconda instead if you go for
an alternative implementation...

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


Re: Fw: Problems Installing Python36

2017-09-20 Thread Irmen de Jong
On 14/09/2017 05:46, Michael Torrie wrote:
> On 09/12/2017 03:05 AM, Thomas Jollans wrote:
>> Other people on this list:
>> This isn't the first time I've someone with this issue here. It's
>> probably putting off plenty of potential new users who don't make as
>> much effort to find a solution. I can't say I understand the ins and
>> outs of installing things on Windows... is there anything that can be done?
> 
> Last time I brought this up, someone mentioned that the Python installer
> is supposed to automatically install this runtime library if it's not
> installed already.  If so, why are so many people having this problem?
> 

That is what I'm wondering as well.

The only thing I can think of is that it asks windows update to install said KB 
update
but that it depends on something else that isn't installed or that the user 
running the
installation doesn't have the rights to install windows updates. (I suspect 
something
will be logged in the event viewer somewhere...?)

Or that it doesn't attempt to download it at all and that we are misinformed :P


Btw, I personally never had any issues installing Python on Windows.

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


v2.0 released of: a Boulder Dash clone with retro graphics and sound

2017-09-10 Thread Irmen de Jong
On 06/09/2017 23:17, Irmen de Jong wrote:

> 
> https://github.com/irmen/bouldercaves
> 

My Boulder Dash clone is now at version 2.0 because a few important things that 
were
lacking are now implemented:

* authentic mode:
The game is now displayed in a small screen that scrolls smoothly over the 
level, like
the original game. It also has the retro c-64 color palette enabled. You enable 
this via
a command line option.

* pre-recorded demo:
If you press F9 or wait a while at the title screen, the game plays back a 
prerecorded
demo of cave A, like the original game.

* synthesized sounds:
Instead of using sampled sounds you can now run the game with a software sound
synthesizer that creates the sounds in real time, including the title music. 
I've tried
to simulate the sounds of the original game but ended up with slightly 
different ones.
Maybe I'll tweak the synth to make them closer to the original, but there's a 
charm to
the variation as well I think.


All in all I am very pleased with the results. I didn't expect it to be possible
creating a decently performing arcade game using just the bare essentials:
- default tkinter to draw everything on the screen
- pillow to load images
- sounddevice to play sounds (optional).

I posted this update because I now consider it a full game [1] and I think it's
interesting to see that this can be realized in Python without any of the 
specialized
'game libraries' (pygame, etc) being used. While tkinter sometimes has troubles 
updating
the screen at 30 hz, the Python code itself is barely breaking a sweat, even 
the sound
synth.


Have fun
Irmen de Jong


[1] full game: errr... there's still no highscore table. Sorry :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: a Boulder Dash clone with retro graphics and sound

2017-09-06 Thread Irmen de Jong
On 05/09/2017 00:02, Irmen de Jong wrote:

https://github.com/irmen/bouldercaves

> There's just two things missing I think:
> - high score table
> - being able to play multiple sounds simultaneously, as the amoeba and
> magic wall sounds are lacking at the moment.

In version 1.2 sound mixing is implemented so the game can now play multiple 
samples
simultaneously, and is able to play sounds in a loop. This means it now 
properly plays
the title screen music, and the amoeba and magic wall sounds are now also in 
the game.
(and I fixed a magic wall behavior bug as well)

Saving and displaying high scores are left as an exercise for the reader :)


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


a Boulder Dash clone with retro graphics and sound

2017-09-04 Thread Irmen de Jong
Hi,

Yet another continuation of my graphics experiments with tkinter. In the
previous project I've been using tkinter bitmaps to simulate a
commodore-64 screen where I exploited the possibility to change the
foreground and background color of the bitmap on the fly. This
conveniently matches the way the commodore 64 draws its (character-mode)
graphics.

This time I switched to a screen filled with hundreds of tkinter's
PhotoImage objects, that can display full color images. However
continuing in the spirit of the 8 bit era, instead of creating something
with high-res full color graphics, I created a Boulder Dash clone using
retro graphics.

It's a fully functional game. You can get it here:
https://github.com/irmen/bouldercaves
(if you just want to play it and aren't interested in the code, get the
.pyz Python zip app from the releases section)

The game contains the 20 levels of the original 1980's Boulder Dash, and
also plays music and soundfx. By default it uses a slightly more
colorful sprite set than the original, but you can tell it to switch to
the limited Commodore-64 color palette.

You need Python 3.5+ and pillow and sounddevice/pyaudio to play it. If
you disable sound, only pillow is enough. It runs very well at 30hz
refresh rate on my Linux box, but seem to have some performance issues
on Windows and Mac OS. Your mileage may vary, and you can tweak some
parameters on the command line to eventually make it run smoothly.

It was a joy to learn about the inner workings of one of my favorite
games when I was a kid, and how to translate that into modern software.

I haven't been able to finish the game so far! I guess I have to learn
again how to actually play this after 30 years.

There's just two things missing I think:
- high score table
- being able to play multiple sounds simultaneously, as the amoeba and
magic wall sounds are lacking at the moment.
(And the sprite set I used contains a lot more objects and creatures
than the original game so it begs for adding extended game logic and
levels with new mechanics... who knows...)

This project was heavily inspired by:
http://codeincomplete.com/posts/javascript-boulderdash/
and http://www.boulder-dash.nl/


Have fun :-)

Irmen

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


Re: wrote a commodore-64 emulator using just Python

2017-09-04 Thread Irmen de Jong
On 08/13/2017 03:50 PM, Irmen de Jong wrote:
> Hi,
> 
> As another experiment with using just tkinter for graphics, this time I 
> created a
> Commodore-64 emulator. You can find it here https://github.com/irmen/pyc64

[...]

> There's also https://github.com/mnaberez/py65 so... possibilities?

Well, I went ahead and integrated that with my emulator. With just a
slight modification (that is now merged into the py65 library) I could
hook it up to the bytearray that my emulator uses to simulate the C64's
RAM. And letting the 'SYS' basic command kick of the 6502 simulator,
rather than doing nothing, it suddenly was able to actually run real
(although simple) Commodore-64 programs. Speed seems to be around 0.5x
real-time on my machine.

The py65 library also already provides a simple machine code monitor
(assembler/disassembler) that you can use to inspect or write the
machine code in the C64's memory. With some effort it should be possible
to run it in the emulated screen, but for now, interaction with it is
done on the console prompt.

It was a great deal of fun integrating this into my project and I found
it quite spectacular to see some existing Commodore-64 programs actually
running unaltered.  Even when they're doing nothing more than changing
the screen colors and unpacking an image. At half speed. But still :-)


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


Re: tkinter keypress events are a mess for numpad keys

2017-08-29 Thread Irmen de Jong
On 29/08/2017 06:32, Terry Reedy wrote:

> *The* documentation (for 8.6) is the tcl.tk/man doc set:
> https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm
> For the level of detail you are looking at, they are essential.
> 
> The nmt docs for 8.5 are neither complete (intentionally not) nor always 
> correct nor
> always up to date.  The tk docs may also have errors, just as our do, but I 
> presume one
> can file a report somewhere and possibly get a fix.

Hi Terry thanks for pointing me to that resource.
I'll have a look at https://www.tcl.tk/man/tcl8.6/TkCmd/keysyms.htm
but I don't have high hopes because I already tried empirically to figure out 
the
distinguishing attributes of the keypress event object, on various platforms 
(Mac OS,
Linux, Windows)...

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


tkinter keypress events are a mess for numpad keys

2017-08-28 Thread Irmen de Jong
Hi,

Using tkinter in python3, I was trying to intercept individual keypresses (and 
releases)
of keys on the numeric keypad. I want to use this as a simple joystick 
simulation.
While you can bind the  event, actually doing something sensible with 
it in a
cross platform way seems utterly impossible.

The distinguishing attribute of the event object is different depending on what 
OS
you're using (keysym, keycode, keysym_num) and on Windows registering some keys 
doesn't
even seem to work (or they're confused with the same keys on the normal 
keyboard area).
The keysym names/values in the documentation are not correct either
(I'm mainly looking at 
http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/key-names.html)


My original question with the details on stackoverflow:
https://stackoverflow.com/questions/45869902/better-way-to-deal-with-tks-keyboard-events-mess-for-numpad-keys-in-pythontkin

Unfortunately there hasn't been a useful response or answer.

A gist with a small example program is here:
https://gist.github.com/irmen/2c9d6bb0afb16b464805410c108a2885

Does anyone here have a clue perhaps?
Or have any idea why this is so messy?


Thank you!
Irmen
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: wrote a commodore-64 emulator using just Python

2017-08-14 Thread Irmen de Jong
On 08/13/2017 03:50 PM, Irmen de Jong wrote:

> Now, it's not a "true" emulator: obviously it doesn't simulate the C64 on a 
> hardware
> level. It does however implement enough to load and run simple basic programs 
> that can
> show interesting PETSCII pictures by manipulating the colors and characters 
> on the screen.

As people have been asking me about this: NO - you cannot run any
existing C-64 software with my program. I should have put the word
emulator in quotes I suppose. The program is mostly an experiment with
tkinter graphics, in this case reproducing the C-64 (textmode) screen.
The 'BASIC interpreter' is just enough to be able to print stuff to the
screen and POKE the memory to change the contents of the screen and the
colors.

If you want to run your old c-64 software, use a _real_ emulator such as
Vice or ccs64 - this was never my goal :)

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


wrote a commodore-64 emulator using just Python

2017-08-13 Thread Irmen de Jong
Hi,

As another experiment with using just tkinter for graphics, this time I created 
a
Commodore-64 emulator. You can find it here https://github.com/irmen/pyc64
You only need the pillow library to be able to run this. I guess most people 
have that
one already anyway.

It works pretty well :)   (although having some slight speed/timing issues on 
windows)

Now, it's not a "true" emulator: obviously it doesn't simulate the C64 on a 
hardware
level. It does however implement enough to load and run simple basic programs 
that can
show interesting PETSCII pictures by manipulating the colors and characters on 
the screen.

And perhaps you can think of doing some other silly things because part of the 
BASIC
dialect is just executed using eval() in python. What about hooking this up as 
a ssh
client to get access to your server in a way nobody thought possible? :-P
There's also https://github.com/mnaberez/py65 so... possibilities?


Fun fact: emulator source is smaller than 64KB

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


Re: SSL/TLS support in Pyro4

2017-08-04 Thread Irmen de Jong
On 04/08/2017 15:44, Robin Becker wrote:
> ..
>>
>> Hi Robin
>>
>> I am not sure how this is any benefit over the self-signed root certs that I 
>> now use?
>>
>> Except for the fact that these are a root cert as well and don't use any CA 
>> trust chain.
>> To be able to validate this cert, I have to load it as a CA cert on the 
>> validating side.
>> Which isn't bad perse.
>>
>> I've used openssl as mentioned here to create my certs:
>> https://docs.python.org/3.7/library/ssl.html#self-signed-certificates
> .Welle I was thinking perhaps you had trouble with self signed certs 
> for some
> reason. I only used CA type setup because some recipe for mongo clusters 
> seems to want
> that. I think the mariadb clusters were fine with simple self signed certs. 
> However, if
> I control the cluster can I not just distribute the cert to all members and 
> have them
> validate it against itself or does python refuse to do that? I vaguely 
> remember some
> python apis allow the authority chain to be specified.

You can specify a CAcert using load_verify_locations on the ssl context. Is 
that what
you meant? I figured out that if you set that to the peer's certificate it will 
then be
accepted.  I understand it as much as "hey openssl here is a root cert that you 
should
trust if you encounter it".
Without doing this, the cert is denied on the SSL level (unless you set the ssl 
options
to no-cert-required but that is definitely not what I wanted)

Bottom line is I learned something new :)

And also that Python's standard ssl library isn't as bad as I remember it to be 
a few
years ago.  Is there still a reason to use, say, PyOpenSSL anymore?


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


Re: SSL/TLS support in Pyro4

2017-08-04 Thread Irmen de Jong
On 03/08/2017 20:30, Irmen de Jong wrote:

> Alternatively, is there a cheap way to get an 'official' SSL certificate for 
> testing
> purposes.  I don't think letsencrypt can help here because it is only for web 
> sites?
> (and their certs are only valid for a very short period)

With some host file trickery (had to fool my dev machine into thinking it is my 
web
server) I managed to get it all to work with a letsencrypt cert as well.

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


Re: SSL/TLS support in Pyro4

2017-08-04 Thread Irmen de Jong
On 04/08/2017 10:26, Robin Becker wrote:
> On 03/08/2017 19:30, Irmen de Jong wrote:
> .
>>
>> I wonder if any current (or new) users of Pyro4 want to check this out? The 
>> biggest
>> concern I have is that I only have dummy (self-signed) certificates so I 
>> can't test it
>> with "real" certs to see if the validation works correctly.
> ..
> 
> I've used self created authorities with mariadb and mongo to secure local 
> clusters.
> Could this provide private secure certs for pyro?

Hi Robin

I am not sure how this is any benefit over the self-signed root certs that I 
now use?

Except for the fact that these are a root cert as well and don't use any CA 
trust chain.
To be able to validate this cert, I have to load it as a CA cert on the 
validating side.
Which isn't bad perse.

I've used openssl as mentioned here to create my certs:
https://docs.python.org/3.7/library/ssl.html#self-signed-certificates


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


SSL/TLS support in Pyro4

2017-08-03 Thread Irmen de Jong
Hi,

Pyro4 (http://pyro4.readthedocs.io) allows you to call methods on Python 
objects running
on other machines, as if they were just normal local objects.

Regarding the network communication: it hasn't got any real security mechanisms 
built-in
and always explicitly depended on external tools or systems to provide this 
(such as VPN
or SSL tunneling). Until now: I've finally started adding SSL/TLS support to 
Pyro4
itself. The work-in-progress 4.62 version has it (git master branch). Docs are 
still
lacking right now but there is a working ssl example included.

I wonder if any current (or new) users of Pyro4 want to check this out? The 
biggest
concern I have is that I only have dummy (self-signed) certificates so I can't 
test it
with "real" certs to see if the validation works correctly.

Alternatively, is there a cheap way to get an 'official' SSL certificate for 
testing
purposes.  I don't think letsencrypt can help here because it is only for web 
sites?
(and their certs are only valid for a very short period)


Cheers
Irmen de Jong

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


Re: Issues with Python

2017-07-30 Thread Irmen de Jong
On 30/07/2017 23:31, Ode Idoko wrote:
> Hi, I am new to Python and though I have been able to download the 3.6 
> version on my laptop , I still have issues with the syntax. While writing a 
> program to execute, it will display syntax error with different shades of 
> color usually green or yellow. 
> What can I do about this? How do I know the error and effect it? Can't it be 
> programmed like we have in excel that will tell you error and prompt you if 
> you wish to accept the right formula format? 
> Please I need more information on this. 
> Thanks. 
> Ode 
> 
> Sent from my iPhone
> 

You'll have to learn the language if you want to do anything meaningful with it.
Python isn't anything like excel formula's, it is a full general multipurpose
programming language.  If you make a mistake, it usually is almost impossible 
to deduce
what you meant to write instead. (because otherwise we wouldn't have to program 
our
computers anymore and instead let them figure out automatically what we wanted 
to do,
right? Just joking)

Because you are comparing it to excel formulas: are you sure you've chosen the 
right
tool for whatever the task is that you wanted to solve?
If so: may I suggest first working through the Python tutorial.
https://docs.python.org/3/tutorial/index.html


Irmen

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


Re: zipapp should not include temporary files?

2017-07-28 Thread Irmen de Jong
On 28/07/2017 18:36, Irmen de Jong wrote:
> On 27/07/2017 00:03, Paul Moore wrote:
>> If you want to create a feature request for a filter function on 
>> bugs.python.org and assign it to me, I'll take a look at it. \
> 
> 
> I will do this, thanks in advance.

Should have included a link perhaps. Here it is: 
http://bugs.python.org/issue31072

Irmen

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


Re: Installation Python 3.6.x on Windows using command line installer (without GUI)

2017-07-28 Thread Irmen de Jong
On 27/07/2017 20:55, Andreas Jung wrote:
> 
> I need to installed Python 3.6.x on Windows as part of an automated process 
> without user-interaction. Recently Python releases provided MSI files for 
> installation using the "msiexec" utility however there are no more MSI 
> release files available for Python 3.6.X. Are there any alternatives?
> 
> -aj
> 

https://docs.python.org/3/using/windows.html#installing-without-ui

Irmen

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


Re: zipapp should not include temporary files?

2017-07-28 Thread Irmen de Jong
On 27/07/2017 00:03, Paul Moore wrote:
> On Wednesday, 26 July 2017 18:37:15 UTC+1, Irmen de Jong  wrote:

>> What do you think? Should the zipapp module perhaps be improved to 
>> automatically skip
>> obvious temporary files or perhaps allow to provide a filter function?

> If you want to create a feature request for a filter function on 
> bugs.python.org and assign it to me, I'll take a look at it. \


I will do this, thanks in advance.

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


zipapp should not include temporary files?

2017-07-26 Thread Irmen de Jong
Hi,

when creating an executable zip file using the zipapp module, it's a little sad 
to see
that no effort is done to filter out obvious temporary files: the resulting 
zipfile
contains any *.pyc/pyo files and other things such as .git, .tox, .tmp folders.

The documentation says "zip is created from the contents of the directory" so 
strictly
speaking it's not wrong that it is doing this. However I think it is 
inconvenient,
because we either have to clean out the directory manually first before zipping 
it, or
afterwards, remove stuff from the resulting zipfile.

What do you think? Should the zipapp module perhaps be improved to 
automatically skip
obvious temporary files or perhaps allow to provide a filter function?


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


Re: JSON encoding PDF or Excel files in Python 2.7

2017-07-21 Thread Irmen de Jong
On 21/07/2017 20:52, Skip Montanaro wrote:
> I would like to JSON encode some PDF and Excel files. I can read the content:
> 
> pdf = open("somefile.pdf", "rb").read()
> 
> but now what?  json.dumps() insists on treating it as a string to be
> interpreted as utf-8, and bytes == str in Python 2.x. I can't
> json.dumps() a bytearray. I can pickle the raw content and json.dumps
> that, but I can't guarantee the listener at the other end will be
> written in Python. Am I going to have to do something like
> base64-encode the raw bytes to transmit them?
> 
> Thx,
> 
> Skip
> 

Yes, json is a text based format and can't contain arbitrary binary data. So 
you'll have
to encode the bytes into some textual form first.
If you think base-64 is too verbose you might try base-85 instead which is 
slightly more
efficient (available since python 3.4 in the base64 module)?

Irmen


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


Re: pythonhosted.org status?

2017-07-03 Thread Irmen de Jong
On 02/07/2017 11:27, breamore...@gmail.com wrote:
> On Sunday, July 2, 2017 at 10:03:34 AM UTC+1, Irmen de Jong wrote:
>> Hi,
>> I'm using pythonhosted.org to host the docs for various projects but it has 
>> either been
>> very slow or unavailable over the past week. Anyone else having the same 
>> problems?
>> Should I perhaps consider putting my docs on readthedocs.org instead?
>>
>> Irmen
> 
> I get:-
> 
> "Service Unavailable
> 
> The service is temporarily unavailable. Please try again later."
> 
> http://downforeveryoneorjustme.com says it's down.

Thanks, I forgot about that site. Quite handy for things like this.

I've decided to mirror my docs on readthedocs.org, an added bonus is their 
automated
documentation build system that relieves me from having to create, zip and 
upload the
docs myself.

> 
> Kindest regards.
> 
> Mark Lawrence.
> 

Cheers
Irmen

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


pythonhosted.org status?

2017-07-02 Thread Irmen de Jong
Hi,
I'm using pythonhosted.org to host the docs for various projects but it has 
either been
very slow or unavailable over the past week. Anyone else having the same 
problems?
Should I perhaps consider putting my docs on readthedocs.org instead?

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


Re: Progress on the Gilectomy

2017-06-10 Thread Irmen de Jong
On 10-6-2017 14:54, Steve D'Aprano wrote:
> Larry Hastings is working on removing the GIL from CPython:
> 
> https://lwn.net/Articles/723949/


Here is Larry's "How's it going" presentation from Pycon 2017 on this subject
https://www.youtube.com/watch?v=pLqv11ScGsQ

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


Re: Transitioning from Linux to Windows

2017-06-05 Thread Irmen de Jong
On 3-6-2017 15:44, chitt...@uah.edu wrote:
> Ideally, I would like to set up the user on their Windows 7/10 system so that 
> they can "login" to the ubuntu system (say putty) - change working directory 
> (to where desired) - run the script (on the ubuntu system) - and scp the file 
> back to the windows desktop.


You can use Pyro4 to directly call the python scripts running on your ubuntu 
system from
python code on the windows machines, thereby avoiding the hassle of having to 
deal with
a remote shell session.
It does require you to run a Pyro4 daemon on the linux box and deal with 
security in
some other way.

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


Re: Very Slow Disk Writes when Writing Large Data Blocks

2017-06-02 Thread Irmen de Jong
On 2-6-2017 20:14, remmm wrote:

> These write speeds are in the range of 18 to 25 MBytes per second for 
> spinning disks and about 50 Mbytes/sec for SSDs.  Keep in mind these numbers 
> should be more like 120 MBytes/sec for spinning disks and 300 MBytes/sec for 
> SSDs.  

You'll only reach those numbers in the ideal situation. Is there just one 
program doing
this disk i/o, sequentially, from a single thread?
If it is not, you are probably suffering disk i/o trashing once you filled up 
the
drive's cache buffers.

For example using Crystal Disk Mark on one of my HDD drives it reports max 60 
MBytes/sec
write speed sequentially in the ideal case (ok, it is not a very fast drive...) 
but only
0.7 (!) in the random 4k block case.

Apparently Linux deals with this better than Windows, for your situation.

Other than that the only other thing I can think of is interference of other 
programs on
the system, such as malware protection or anti-virus tooling that is trying to 
scan your
big files at the same time.  That should be visible in Window's resource 
monitor tool
however, I think.


> I've since written test code using just python "write" 

Post it somewhere?

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


Re: Bug or intended behavior?

2017-06-02 Thread Irmen de Jong
On 2-6-2017 19:17, sean.diza...@gmail.com wrote:
> Can someone please explain this to me?  Thanks in advance!
> 
> ~Sean
> 
> 
> Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 12:39:47) 
> [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
 print "foo %s" % 1-2
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: unsupported operand type(s) for -: 'str' and 'int'



The % operator has higher precedence than the - operator.
See https://docs.python.org/3/reference/expressions.html#operator-precedence
So what you wrote is equivalent to:

print ("foo %s" % 1) - 2

which means subtract the number 2 from the string "foo 1". Hence the error.

Solution is to use parentheses to make sure the things are evaluated in the 
order you
intended:

print "foo %s" % (1-2)


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


adding type hints to one of my projects, things learned

2017-05-24 Thread Irmen de Jong
mypy). PyCharm is not (yet)
  smart enough to see that an import is really used even if it is just a type 
hint comment.
  To be honest, PyCharm has a point, because it is *mypy* that uses it, not 
*python*...
  But it causes me to have to accept several warnings that aren't.

- The code becomes harder to read. In some cases, _a lot harder_ because
  some type hints can become quite elaborate (list of dicts mapping str to 
tuple... etc)
  You can ease the pain a bit by creating your own type classes but
  this clutters the module namespace.



Things learned, thoughts


After adding type hints to all of Tale's code, a lot of time
was spent fixing mistakes (in the hints I wrote) and several bugs (that mypy 
found).

After all of this, I learned that

- using type hints helps uncover bugs and improves IDE feedback and code 
understanding
- it is quite a lot of work to add it to an existing code base and "get it 
right" (= no
mypy errors)
- it has to be done in an 'unnatural' way sometimes, because of the way Python 
parses stuff
- it can clutter up code that was very concise and clean before.


But the most important thing really:

**...static typing (via type hints + mypy tooling) clashes with Python's 
dynamic duck
type nature.**
It all still feels 'off' to me, in the context of Python. It introduces new 
kinds of
problems, that we didn't have
without them, and the syntax is not as 'natural' as I hoped.

Right now, I am not really sure if I want to continue to use type hints.
In Tale I probably will because it now has them everywhere already, but
my other projects have to wait.

As this is the first and only time so far that I have used type hints,
it is very likely that I made some mistakes or missed a better solution to
some of the issues I encountered.
Please correct me on them or give me some tips on improving my application
and understanding of Python's type hints. Thank you!



Irmen de Jong
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: SSL certificate of a server on Windows

2017-05-23 Thread Irmen de Jong
On 23-5-2017 10:19, COPIN Mathieu. wrote:
> Hi, 
> 
> I want to get a server certificate from the host-name.
> 
> I know I could do something like :
>> call(openssl, s_client, -showcerts, -connect, hostname:port)
> 
> 
> But the thing is to do it without openssl because I want to run the script on 
> Windows.
> 
> Any suggestions ?
> Mathieu
> 

I guess you mean: without calling "openssl.exe"


import ssl
cert = sll.get_server_certificate(("www.google.com", 443))

See
https://docs.python.org/3.6/library/ssl.html#ssl.get_server_certificate



Irmen


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


Re: How to install Python package from source on Windows

2017-05-18 Thread Irmen de Jong
On 18-5-2017 3:30, Dennis Lee Bieber wrote:
>   Late-comer... I'm pretty sure 1.4, if not 1.3 was the version
> documented in the first books I bought on the language...
> 
>   And I bought because AmigaOS was listed as a viable candidate (thanks
> Irmen) -- within a week I had written an outgoing SMTP daemon that
> correctly handled TO/CC/BCC while relaying through my ISP (Using AREXX to
> SPOOL outgoing messages from AmigaELM

(offtopic:)
Awesome. I remember it was a lot of fun and a good learning opportunity for me 
back in
the days to port Python to AmigaOS and even adding some AREXX support to it as 
well.
I think the latest version I ported was Python 2.0 somewhere in the 2000's. 
Always nice
to hear people actually used it :)

-irmen

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


Re: Out of memory while reading excel file

2017-05-10 Thread Irmen de Jong
On 10-5-2017 17:12, Mahmood Naderan wrote:

> So, I think numpy is unable to manage the memory.

That assumption is very likely to be incorrect.


>> np.array([[i.value for i in j] for j in p.rows])

I think the problem is in the way you feed your excel data into the numpy array
constructor. The code above builds many redundant python lists from the data 
you already
have in memory, before even calling the numpy array function.

I strongly suggest finding a proven piece of code to read large excel files 
like the
example from Peter Otten's reply.

Irmen

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


Re: Install python via MS batch file

2017-05-06 Thread Irmen de Jong
On 6-5-2017 7:14, Mahmood Naderan wrote:
> Hello,
> I have downloaded python-3.6.1-amd64.exe and it is fine to install it through 
> GUI. However, I want to write a batch file to install it via command line. 
> Since the installation process is interactive, it seems that the auto-install 
> batch file is difficult. What I want to do is:
> 
> set python path
> install in the default location.
> 
> Any idea about that?
> 
> 
>  Regards,
> Mahmood
> 


Yeah, there should be extensive support for this.
See https://docs.python.org/3/using/windows.html#installing-without-ui

(I haven't tried it myself though)

Irmen

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


Re: write arrays to disk

2017-04-16 Thread Irmen de Jong
On 16-4-2017 14:28, jorge.conr...@cptec.inpe.br wrote:
> Hi,
> 
> I'm new on Python software. I would like to write on disk arrays in binary or 
> ascii
> format. Can someone please help me?
> 
> Thanks,
> 
> Conrado

What kind of data is in the arrays?
Who or what will be reading the files?
And most importantly: what have you tried yourself so far?

Irmen

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


Re: IOError: [Errno 12] Not enough space

2017-04-12 Thread Irmen de Jong
On 12-4-2017 7:54, LnT wrote:
> 
> Hi Irmen,
> 
> you may please find full log @ https://pastebin.mozilla.org/9018753

I have no idea what I'm looking at.

But my initial response was wrong, see the reply by eryk sun; your error has 
nothing to
do with disk space but rather, a lack of system memory.

Irmen

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


Re: IOError: [Errno 12] Not enough space

2017-04-11 Thread Irmen de Jong
On 11-4-2017 14:30, LnT wrote:
> Hi,
> 
> version information
> 
> python 27

Please be more precise, there is no Python 27. (Yeah it is clear you meant 2.7 
but still)

> java version "1.8.0_111"
That should not be relevant

> OS -Win 10 , 64Bit , 8GB RAM , 60GB HD

60 GB is not a lot of space for windows...


> executing python test script (robotframework) for a we bapplication 
> Application url will be invoked by Firefox 38.0
> 
> Please find below log:
> 
> Opening browser 'firefox' to base url 'https://onbdev.nbpa.com/zae'
> [ WARN ] Keyword 'Capture Page Screenshot' could not be run on failure: No 
> browser is open
> | FAIL |
> IOError: [Errno 12] Not enough space
> 

That's not much information. Is there really not anything else in the log? Like 
a
traceback, that may give some clues what the application is doing when it is 
running out
of disk space?


> 
> I have cleared %TEMP% and reran the script.
> But still I see this.
> 
> Could you please show me some Light ?
> 

Based on the info you provided, the only solution I can think of is: free more 
space.
Something in your application is trying to write stuff and there's simply not 
enough
space on the disk to do so.


-i


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


Re: python and databases

2017-03-14 Thread Irmen de Jong
On 14-3-2017 20:59, Xristos Xristoou wrote:
> I have a database in  microsoft ACCESS with about 150 records.. if I want to 
> get some
> data from this database using  a query in python and i want to store in some
> variables in python that will do this ? to avoid the 150 if ...: Using the 
> standard
> library the python? know easily put it an SQL query but i canot use additional
> library python.
> 

Is the data in the Access database static? 150 records is not much data. You 
might be
able to extract it ONCE, and store it directly in Python data structures 
instead. Or
extract it and store it in a sqlite database instead, which you can use from 
Python
using the standard library's sqlite3 module.

If the data is dynamic however because it is being changed by other sources, 
you'll have
to use a third party library to get to it I think


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


Re: Error installing python on Windows

2017-02-24 Thread Irmen de Jong
On 24-2-2017 12:18, Michelle Tan wrote:
> Hello all
> 
> I am new to python.
> 
> Trying to install Python and encountered this error message : "The program
> can't start because api-ms-win-crt-runtime-I1-1-0.dll is missing from your
> computer."
> 
> Tried to repair and reinstall Python however i may have missed out some
> installation. What should I do to resolve this issue?  Thanks for your
> help!
> 

Make sure your windows is up to date! That dll should be installed as part of 
one of the
regular windows updates. Google may be able to tell you the specific KB number 
of the
particular update.


Irmen

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


Re: Python 3.6 installation doesn't add launcher to PATH

2017-02-24 Thread Irmen de Jong
On 24-2-2017 13:38, ChrisW wrote:
> The installation guidelines for Python 3.6 say:
> 
> "Per-user installations of Python do not add the launcher to PATH unless the 
> option was selected on installation." 
> (https://docs.python.org/3/using/windows.html#from-the-command-line).
> 
> However, I've installed Python 3.6 with the 'include PATH' checkbox ticked 
> for my user only, and although C:\Windows\py.exe exists, it has not been 
> added to my PATH. 
> 
> I also tried installing for all users, and this also doesn't add it to the 
> PATH.
> 
> Is this a bug, or have I done something wrong?!
> 

Hm, I don't remember having this issue when installing this myself.

Are you sure you're checking it from a newly opened cmd.exe *after* the install
finished?  Already opened windows won't see the change until restarted.

Irmen

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


Re: How to create a Python 3.6 traceroute without SOCK RAW?

2017-02-23 Thread Irmen de Jong
On 24-2-2017 0:20, Juan C. wrote:
> On Thu, Feb 23, 2017 at 7:42 PM, Irmen de Jong  wrote:
>>
>> import os
>> os.system("traceroute www.google.com")
> 
> Indeed, that would work, but it isn't a great approach in my opinion
> because I would rely on a system command, in this case Windows uses
> tracert while UNIX uses traceroute, one could fix that with a if-else
> to check the os and then use the correct command, but it just make it
> feel even more like a workaround and not a definitive solution.
> 

I don't consider this a workaround at all. Why reinvent the wheel?
Also: once you're going to deal with low level socket API you're going to run 
into
platform differences anyway.

Irmen

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


Re: How to create a Python 3.6 traceroute without SOCK RAW?

2017-02-23 Thread Irmen de Jong
On 23-2-2017 22:33, Juan C. wrote:
> I need to implement a traceroute inside my script but I can't escalate 
> privileges.  Unix uses UDP for traceroute, but I didn't find any material 
> regarding UDP traceroute in Python.

import os
os.system("traceroute www.google.com")

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


Re: python decorator

2017-02-22 Thread Irmen de Jong
On 22-2-2017 8:39, Argentinian Black ops lll wrote:
> Thanks for the quick response...! you saved me a lot of time, thank you!
> 

I don't know if you want/have to use your own custom caching decorator, but are 
you
aware of the lru_cache decorator that's part of the standard library?

https://docs.python.org/3/library/functools.html#functools.lru_cache


Irmen

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


Re: CSV

2017-02-22 Thread Irmen de Jong
On 22-2-2017 18:26, Braxton Alfred wrote:
> Why does this not run?  It is right out of the CSV file in the Standard Lib.

What does "not run" mean.
We can't help if you are not telling us the exact error message you're getting 
(if any)


> filename = 'c:\users\user\my documents\Braxton\Excel\personal\bp.csv'

That being said, there's at least a problem with this line because you're not 
escaping
the backslashes. So the resulting filename string is not what you intended it 
to be (try
printing it to see what I mean).

Several solutions possible:
- switch to using forward slashes /  this works on windows too.
- use a raw string literal  r'.'
- or escape the backslashes \\


Irmen

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


Re: WANT: bad code in python (for refactoring example)

2017-02-14 Thread Irmen de Jong
On 14-2-2017 23:44, Makoto Kuwata wrote:
> Hi,
> 
> Is there any *just right* python code to refactor?
> In other words, I'm finding bad code example in python.
> 
> (background)
> I'm teaching Python to some novice programmer, and
> want to show refactoring example to them.
> 
> (required)
> * not good code
> * not too large (for novice programmer)
> * not too complex (for novice programmer)
> * released under open source license
> 
> If you know good material in github or bitbucket to refactor,
> let me know it.
> 
> --
> regards,
> kwatch
> 


No code in text form, but I find the following video by Raymond Hettinger very 
clear
about the values of refactoring otherwise seemingly fine code

https://youtu.be/wf-BqAjZb8M?t=12m39s

code starts at 12 min. 40 sec.

It does require a bit of background knowledge about Python and the PEP8 code 
style and
API design.

Irmen

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


Re: What library/package to use for parsing XML?

2017-01-30 Thread Irmen de Jong
On 30-1-2017 18:58, Chris Green wrote:
> I want to parse some XML data, it's the address book data from the
> linux program osmo.  The file I want to parse is like this:-
> 

[snip]

> 
> I basically want to be able to extract the data and output in other
> formats - e.g. write to a Sqlite3 database and/or CSV.
> 
> So what do I need to import (and probably install first) to do this?

No need to install anything. Python has batteries included.

Parse your XML with xml.etree.ElementTree
[https://docs.python.org/3/library/xml.etree.elementtree.html]
Read/write CSV with csv
[https://docs.python.org/3/library/csv.html]
Put stuff in sqlite3 database and query it using sqlite3
[https://docs.python.org/3/library/sqlite3.html]


-irmen


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


Re: What are your opinions on .NET Core vs Python?

2017-01-30 Thread Irmen de Jong
On 30-1-2017 21:33, Joseph L. Casale wrote:
>> Python still has my heart, but .NET Core tempts me. One great thing of
>> coding in C# would be no GIL.
> 
> Seriously, check out the benchmarks at https://github.com/aspnet/benchmarks.

Results vary quite a bit there.
For instance take the json serialization benchmark:
https://www.techempower.com/benchmarks/#section=data-r13&hw=ph&test=json
There's 6 python frameworks performing better than aspcore in this chart...


Irmen

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


Re: Cannot import GDAL

2017-01-11 Thread Irmen de Jong
On 11-1-2017 18:31, Falter, Donald [USA] wrote:
> I am new to Python and I am trying to utilize GDAL.  I installed Python 3.6.
> I installed the following: gdal-201-1800-core.msi and 
> GDAL-2.1.2.win32-py3.4.msi.

Those don't match. You'll have to use a MSI built for py3.6, one thinks.

Either install and use Python 3.4 with this (rather than 3.6) or find the 
approprite
installer for python 3.6. It seems that you can get one here:
http://www.lfd.uci.edu/~gohlke/pythonlibs/#gdal


Irmen

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


Re: Work between multiple processes

2017-01-11 Thread Irmen de Jong
On 10-1-2017 23:57, Patrick Zhou wrote:
> Hi Irmen,
> 
> I have successfully got it to work with both side as python but so far having 
> trouble with pyrolite.jar which is downloaded from 
> https://mvnrepository.com/artifact/net.razorvine/pyrolite/4.4
> 
> 

[...]

> 
> which "getDst" works on Java but hangs on handshake() in the call function. 
> 
> Any thought? Thanks. -P
> 

Yeah, don't use the oldest version of the library available, use the newest ;-)
https://mvnrepository.com/artifact/net.razorvine/pyrolite/4.15


Irmen

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


Re: Announcement: TLSv1.2 will become mandatory in the future for Python.org Sites

2017-01-10 Thread Irmen de Jong
On 10-1-2017 16:01, Donald Stufft wrote:
>> TypeError: the JSON object must be str, not ‘bytes'
> Huh, just tested, my original snippet works on Python 3.6 but fails on Python 
> 3.5. 


My guess is that is due to an improvement in 3.6 mentioned here:
https://docs.python.org/3/whatsnew/3.6.html#json

Irmen


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


Re: Work between multiple processes

2017-01-06 Thread Irmen de Jong
On 4-1-2017 23:14, zxpat...@gmail.com wrote:
> Hi everyone,
>
> I ran into a case that I need to create a work process of an application
(Jython so has to call using java.exe) which will collect the data based on 
what main process indicates.
>
> (1) I tried multiprocessing package, no luck. Java.exe can't be called from
Process class?
>
> (2) I tried subprocess. subprocess.communicate function will wait for the
work process to terminate so to return.
>
>
> either (1) or (2) doesn't work out well. Please suggest.  Global system
queue?
>
> Thanks,
> Patrick.
>


Is it a requirement that the workdf process is also Jython?

If not: you could spawn a Python subprocess that hosts a Pyro4 daemon. 
Utilizing the Pyrolite java client library you can call methods in it from the 
java/jython side.  (Unfortunately it is not yet possible (due to jython 
incompatibilities) to use the full Pyro4 library on the Jython side as well). 
Not sure if it meets your set of requirements but have a look at 
http://pythonhosted.org/Pyro4/
http://pythonhosted.org/Pyro4/pyrolite.html


Irmen

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


Re: Work between multiple processes

2017-01-05 Thread Irmen de Jong
On 4-1-2017 23:14, zxpat...@gmail.com wrote:
> Hi everyone,
> 
> I ran into a case that I need to create a work process of an application 
> (Jython so has to call using java.exe) which will collect the data based on 
> what main process indicates. 
> 
> (1) I tried multiprocessing package, no luck. Java.exe can't be called from 
> Process class?
> 
> (2) I tried subprocess. subprocess.communicate function will wait for the 
> work process to terminate so to return.
> 
>  
> either (1) or (2) doesn't work out well. Please suggest.  Global system queue?
> 
> Thanks,
> Patrick.
> 


Is it a requirement that the workdf process is also Jython?

If not: you could spawn a Python subprocess that hosts a Pyro4 daemon.
Utilizing the Pyrolite java client library you can call methods in it from the
java/jython side.  (Unfortunately it is not yet possible (due to jython
incompatibilities) to use the full Pyro4 library on the Jython side as well).
Not sure if it meets your set of requirements but have a look at
http://pythonhosted.org/Pyro4/
http://pythonhosted.org/Pyro4/pyrolite.html


Irmen

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


Re: Choosing a Python IDE. what is your Pythonish recommendation? I do not know what to choose.

2017-01-02 Thread Irmen de Jong
On 2-1-2017 12:38, Antonio Caminero Garcia wrote:

> The thing with the from-the-scratch full featured IDEs (Eclipse, IntelliJ, 
> Pycharm)
> is that they look like a space craft dashboard and that unwarranted resources
> consumption and the unnecessary icons. I want my IDE to be minimalistic but 
> powerful.
> My screen should be mostly “made of code” as usually happens in Vim, Sublime 
> or Atom.
> However, Pycharm is really cool and python oriented.

[...]

> Sublime is my current and preferred code editor. 


If you like Sublime, and its minimalistic 'Distraction Free Mode', you'll be 
delighted
to know that this exact same feature is in PyCharm as well.
Select it (View->Enter distraction free mode), and gone is all the screen 
clutter and
even the menu bar if you so desire. You can focus on just your code. And all of
PyCharm's features are still there a mouse click or keyboard shortcut away.


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


Re: Printing a generator returns "", need to print its values

2016-12-05 Thread Irmen de Jong
On 5-12-2016 19:39, vmaha...@centerpointmedia.com wrote:
> On Wednesday, November 16, 2016 at 3:25:39 PM UTC-5, Peter Otten wrote:
>> vmaha...@centerpointmedia.com wrote:
>>
>>> I am running Python2.7, wherein I am running the following price of code:
>>>
>>> y = m.predict(input_fn=lambda:input_fn(df_predict), as_iterable=True)
>>> print ('Predictions: {}'.format(str(y)))
>>>
>>> The output of the following is "">> 0x7f0476373e10>"
>>>
>>> However, the desired output must be in the format [1 0 0 1 1 0 0 1].
>>>
>>> Can someone help me print the output in this format
>>
>> You give no context, but my suggestion would be to try and omit the 
>>
>> as_iterable=True
>>
>> part...
> 
> 
> Can someone help me print a generator object?
> 

Have you tried Peter's suggestion?

If that didn't work (but what is that as_iterable argument for then?) just 
iterate over
the result and print each value as it comes out of the generator:

print("Predictions:")
for value in y:
print(value)


Irmen

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


Re: Result is not Displayed

2016-11-22 Thread Irmen de Jong
On 22-11-2016 9:18, prihantoro2...@gmail.com wrote:
> Dear all, 
> 
> i am new to Python and have this problem
> 
> =
> import nltk
> puzzle_letters = nltk.FreqDist('egivrvonl')
> obligatory = 'r'
> wordlist = nltk.corpus.words.words()
> [w for w in wordlist if len(w) >= 6
> and obligatory in w
> and nltk.FreqDist(w) <= puzzle_letters]
> print puzzle_letters
> ==
> 
> this gives me 
> while the expected outcome is ['glover', 'govern', ...]
> did i miss something?


Review your code carefully. You're printing the wrong thing at the end, and 
you're doing
nothing with the list comprehension that comes before it.

-irmen

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


  1   2   3   4   5   6   7   8   9   10   >