Albert-Jan Roskam | 22 Aug 23:10 2014

simple unicode question

Hi,

I have data that is either floats or byte strings in utf-8. I need to cast both to unicode strings. I am
probably missing something simple, but.. in the code below, under "float", why does [B] throw an error but
[A] does not?

# Python 2.7.3 (default, Feb 27 2014, 19:39:10) [GCC 4.7.2] on linux2
>>> help(unicode)
Help on class unicode in module __builtin__:

class unicode(basestring)
 |  unicode(string [, encoding[, errors]]) -> object
 |  
 |  Create a new Unicode object from the given encoded string.
 |  encoding defaults to the **current default string encoding**.
 |  errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.
# ... 
>>> import sys
>>> sys.getdefaultencoding()
'ascii'

# float: cannot explicitly give encoding, even if it's the default
>>> value = 1.0
>>> unicode(value)      # [A]
u'1.0'
>>> unicode(value, sys.getdefaultencoding())  # [B]

Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    unicode(value, sys.getdefaultencoding())
(Continue reading)

atp2gr | 22 Aug 15:48 2014
Picon

Please get me started in django

Hi

I have developed a python maths game in 2.7 and want to try and run it from the web.  PLEASE can you guide me in getting started.  Im not very familiar with command line  operations. 

I have installed python 3.4 does that help.

If this is not the best place to get help with django can you recommend an interactive site.

Thanks

Peter

Sent from Windows Mail

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Mimi Ou Yang | 22 Aug 04:43 2014
Picon

Question about if functions

name = input("Enter your name: )

age = input("Enter your age: )

age = int(age)

if (name and age == jimmy and 35):
    print ("BLABLABLABLABLABLAB")




how can I make a code that has the same effect has the code that I wrote even though it isn’t a real working code. I hope you understand this code. Basically, it asks you your name and age. And then, if (the name input and the age input) ==  (jimmy and 35):
it prints blablablablablabl




_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Alessandro Di Bella | 21 Aug 13:01 2014
Picon

Development of administration utility

Hi,

We are currently investigating different languages and technologies to develop an command line administration utility.
Python is one of the options we are looking at for the job but currently we have no relevant skill set so I thought I'd post some question to get an idea if using python is something worth pursuing or not.

The utility should have the following characteristics:
  1. support for sub commands and parameters (e.g. svn or git)
  2. integration with bash_completion
  3. Modular. The idea would be that by installing different  packages (or RPMs), new sub-commands and parameters will be made available to the utility. E.g.,
    1. "Base" package is installed: subcommand available is "view-config "
    2.  "Base" and "database" package are installed, subcommands available are "view-config" and "backup-db"
  4. Support for executing remote commands via ssh
I have no doubt that with enough effort, a Python application could be developed to implement the above.
However, I'm not too sure if Python is the right tools for the job particularly about point 3:
  1. Is there a built-in discovery mechanism like Java SPI (http://docs.oracle.com/javase/tutorial/sound/SPI-intro.html)?
  2. Are there any libraries/framework we could build upon or would we  need to start from scratch?
  3. Should we consider 2.x or 3.x in order to ensure cross system compatibility (linux, windows)?
Any feedback on any of the points above would be greatly appreciated.

Regards,

Alessandro


_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Flynn, Stephen (L & P - IT | 21 Aug 11:03 2014
Picon

sys module - what does "It is always available" mean in the docs?

The documentation (https://docs.python.org/3/library/sys.html) for
Python 3.4.1 says that "This module provides access to some variables
used or maintained by the interpreter and to functions that interact
strongly with the interpreter. It is always available."

I interpreted that last sentence as "It's built in", so I made the
assumption I didn't need to import it in order to use it.

This is not the case - it still needs to be imported before I can use
anything defined within it.

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64
bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> print(sys.maxsize)
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    print(sys.maxsize)
NameError: name 'sys' is not defined
>>> import sys
>>> print(sys.maxsize)
9223372036854775807
>>>  

So, what does the documentation mean by explicitly pointing out that sys
is always available? To me, it's misleading but I'm obviously missing a
subtlety.

I've asked this question on /learnpython on reddit recently and the best
explanation is that it's built by the interpreter at runtime, so it
can't fail to import due to a broken installation. Any other offers?

As an addendum, I fired up my local docs via "Module Docs" and "This is
always available" *isn't* in the docs page for sys. I'd assumed they
were built from the same sources but apparently not.
-- 
Steve Flynn

This email and any attachment to it are confidential.  Unless you are the intended recipient, you may not
use, copy or disclose either the message or any information contained in the message. If you are not the
intended recipient, you should delete this email and notify the sender immediately.

Any views or opinions expressed in this email are those of the sender only, unless otherwise stated.  All
copyright in any Capita material in this email is reserved.

All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business
purposes. 

Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or
transmission of this email to the fullest extent permitted by law.
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Mark Lawrence | 21 Aug 10:32 2014
Picon

Top posting

Please note everybody that I'm giving up trying to help out here as I 
can't cope with the stream of top posted replies.  They make long 
threads such as the recent "Re: Building Starships -- object of type 
'int' has no len()" unreadable to me.

--

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

LN A-go-go | 21 Aug 04:12 2014

import values, calculate distance

Python Mentors,

I can't get this code to run and at times, I can't even save it.  It is sections of code used from previous exercises, put it together and it just isn't right. 

Thank-you,
LN


The method is as follows:

  1. Run the distance calculations for pt1 to all other points, and print or save the results.
  2. Set a holding variable for pt1 values, then switch the values from pt1 to pt2 (so pt2 is now in the first position of your coordinate list).
  3. Calculate the new distances for pt2 to all other points, and print or save the results.
  4. Switch pt2 and pt1 so that they are back in their original positions.
  5. Re-set the holding variable for pt1 values, then switch the values from pt1 to pt3 (so pt3 is now in the first position of your coordinate list). 
    Calculate the new distances for pt3 to all other points, and print or save the results.
    … continue with this method until all points are done.

  6. Here is the text file of points:

    ID X Y
    PT1 2.6 8.7
    PT2 5.6 10.3
    PT3 8.9 45.7
    PT4 10.4 6.2
    PT5 2.1 21.4
    PT6 8.7 78.2
    PT7 44.5 15.2
    PT8 23.6 45.8
    PT9 43.1 2.3
    PT10 1.1 62.5





     
    # Description: read in all of the given data file and then calculate
    # the distance between each of the data points and then write or print out the results
    # to a new text file.

    # Open path to file, readlines and create variables, run a 'while' loop, split the line (initialize with import string) into the three variable lists
    infile = open("z:/filepath/coordinate.txt","r")
    line = infile.readline()
    import math
    import string
    IDCODE = []
    XCOORDINATE = []
    YCOORDINATE = []
    n = 0
    while True:
     line = infile.readline()
     if not line: break
     ID,X,Y = string.split(line)
     XNUM = float(X)
     YNUM = float(Y)
     n = n + 1
     XCOORDINATE.append(XNUM)
     YCOORDINATE.append(YNUM)
     IDCODE.append(ID) 
     
    print (XCOORDINATE, YCOORDINATE), IDCODE
    #
    # activate the math modular function (use import math function) in order to use the
    #square root function
    dist = {}
    def distance(n,p,s, XCOORDINATE, YCOORDINATE, IDCODE):
     import math
     p = 1
     s = 0
     DP = []
     while p < n:
       DT= math.sqrt((XCOORDINATE[p]-XCOORDINATE[0])**2 + (YCOORDINATE[p]-YCOORDINATE[0])**2)
      DP.append(DT)
      p = p + 1
     while s < n-1:
      dist[DP[s]] = IDCOORDINATE[s+1]
      s = s + 1
      
      for key in sorted(dist):
       print dist[key],[key]
     return dist
    def switch(n,XCOORDINATE, YCOORDINATE, IDCODE):
     import math, string
     idcodezero = IDCODE[0]
     xcodezero = XCOORDINATE[0]
     ycodezero = YCOORDINATE[0]
     z = 1
     while z <=n - 1:
      IDCODE[0] = IDCODE[z]
      XCOORDINATE[0] = XCOORDINATE[z]
      YCOORDINATE[0] = YCOORDINATE[z]
      IDCODE[z] = IDCODEzero
      XCOORDINATE[z] = XCOORDINATEzero
      YCOORDINATE[z] = YCOORDINATEzero
      DR = distance(n,XCOORDINATE, YCOORDINATE, IDCODE)
      IDCODE[z] = IDCODE[0]
      XCOORDINATE[z] = XCOORDINATE[0]
      YCOORDINATE[z] = YCOORDINATE[0]
      IDCODE[0] = IDCODEzero
      XCOORDINATE[0] = XCOORDINATEzero
      YCOORDINATE[0] = YCOORDINATEzero
      DP = []
      z = z + 1
      
    #

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Lucia Stockdale | 21 Aug 05:03 2014
Picon

Question

Hi everyone,

I have been writing a program to print words backwards until an an empty line of input is entered,
but after I put in the input it comes up with TypeError.

This is my goal:

Line: hello world
olleh dlrow
Line: extra
artxe
Line: i love python
i evol nohtyp
Line:

This is my current code:

line = input('Line: ')
while line != '':
  line = line[len(line):0:-1]
  line = line.split()
  line = line.reverse()
  line = (' '.join(line))
  print(line)

Thanks
Lucia

This email is intended for the use of the named individual or entity and may contain confidential and
privileged information. Any dissemination, distribution or copying by anyone other than the intended
recipient of this email is strictly prohibited. Confidentiality and legal privilege are not waived or
lost as a result of mistaken delivery. Attachments are opened and transmitted at the user's own risk. Any
representations or opinions expressed are those of the individual sender, and not necessarily those of
Melbourne Girls Grammar.
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Dima Kulik | 20 Aug 14:35 2014
Picon

Parsing txt file

Hi to all. I have a problem with parsing file.
I have txt file exported from AD and it has such structure:

DistinguishedName : CN=*** ,OU=*** ,OU=*** ,DC=*** ,DC=***,DC=***
GroupCategory     : Distribution
GroupScope        : Universal
Name              : ****
ObjectClass       : group
ObjectGUID        : 0b74b4e2-aad1-4342-a8f4-2fa7763e1d49
SamAccountName    : ****
SID               : S-1-5-21-1801674531-492894223-839522115-16421


i need to export to file all stings which start from "Name"

I've tried to make little parser:

keywords = ['Name', 'Name:']
input_file=open("Mail_Groups.txt","r").readlines()
output_file=open("Out.txt","w")
for line in input_file:
    for word in line.split():
        if word in keywords:
            output_file.write(line)

but the output is clear.

What the problem is? Can some one help me?
--
Dima Kulik
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
diliup gabadamudalige | 20 Aug 15:45 2014
Picon

Fwd: Embedding resources

Hi Danny!

The routine works fine and so does this one.


The only problem with all these are that that the time taken to read these files and to either make a list or send to screen is WAY TOO LONG.
The only one that works without much delay is in the file I have attached. It is a bit of code that I wrote with verbose print statements to follow the program in action while testing. As this uses base64 only there is no secure encryption. Please have a look at it and try to improve it.

Am I doing this correctly? Are these messages getting to the community?




On Wed, Aug 20, 2014 at 1:18 PM, diliup gabadamudalige <diliupg <at> gmail.com> wrote:
Hi Danny!

You are always there to lend a helping hand I've noticed! Thanks for the quick response! Let me try the code and get back to you.



On Wed, Aug 20, 2014 at 1:02 PM, Danny Yoo <dyoo <at> hashcollision.org> wrote:


On Aug 19, 2014 11:53 PM, "diliup gabadamudalige" <diliupg <at> gmail.com> wrote:
>
> Hi all!
>
> Is there any way I can bundle all my graphics only using Python and Pygame so that the user may not be able to read them out of the program?

(Changing subject line to more descriptive title)

Would something like http://www.pygame.org/pcr/image2py/index.php apply to your problem?




--
Diliup Gabadamudalige

http://www.diliupg.com
http://soft.diliupg.com/

**********************************************************************************************
This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions.
**********************************************************************************************




--
Diliup Gabadamudalige

http://www.diliupg.com
http://soft.diliupg.com/

**********************************************************************************************
This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions.
**********************************************************************************************

"""
Author: Diliup Gabadamudalige. diliupg <at> gmail.com>

Copyright: If you wish to use this code please keep this multiline comment,
           along with function source. Thank you.

read the files in the current directory and get all files except ones in the exempt list or directories..
Get the file extension.
and convert them by using maketrans without file extensions.
When converting from original files with file extensions, remove the file extension(with the .), reverse
it and add it to the begining of the filename.
encode the file.
add new file ext " <at> lm".
eg: file name -> picture.tiff -> ffit.picture ->AFKDiO$1#&mL <at> lm.
encoded files added to a directory "coded" which is created if not exist.
decoded files added to a directory "decoded" which is created if not exist.

path = your path where the files are
run = True -> encode
run = False -> decode
"""

import os
import string
import base64
from master_vars import alpha, coder

def main(path, code = None, ex = [".wpr", ".wpu", ".py", ".pyc", ". <at> lm"]):

    getfiles = []
    path = path
    code = code  #
    exclude = ex
    items = os.listdir(path)

    if code:  # if code = True then encode
        mode = "encode"
        if not os.path.exists("coded"):
            os.makedirs("coded")

    else:  # else decode
        mode = "decode"
        ## if decode mode and coded folder does not exist exit program
        if not os.path.exists("coded"):
            print "nothing to decode."

        elif not os.path.exists("decoded") and os.path.exists("coded"):
            os.makedirs("decoded")
        elif os.path.exists("decoded"):
            items = os.listdir(path + "\\" + "coded")

    ## get the names of the files in the path which are not in the exclude list
    ## encode or decode either way this works correct
    for n in items:
        if code:
            fpath = path + "\\" + n
            if  os.path.isfile(fpath):  # check if file is not a directory
                if n[n.index("."):] not in exclude:
                    getfiles.append(n)
        else:
            fpath = path + "\\coded\\" + n
            if n.endswith(". <at> lm"):  # get only the converted files
                getfiles.append(n)

    print "file names to process:", getfiles
    print

    for f in getfiles:
        if code:
            ## decode and reverse file name
            namea = f.translate(string.maketrans(alpha,coder))
            nameb = namea[::-1] + ". <at> lm"
            code_to_dir = path + "\\coded\\" + nameb
            read_file = path + "\\" + f

        else:
            ## drop the file ext. decode and reverse
            namea = f[:-4].translate(string.maketrans(coder, alpha))

            ## file name + reversed
            nameb = namea [::-1]
            decode_to_dir = path + "\\decoded\\" + nameb
            read_file = path + "\\coded\\" + f

        print "new file name not invert no ext:", namea
        print "new file name:", nameb
        print "old file name:", f
        print

        with open(read_file , "rb") as from_disk:
            if code:
                str1 = base64.b64encode(from_disk.read())
                with open(code_to_dir, "wb") as to_disk:
                    to_disk.write(str1)
            else:
                str1 = base64.b64decode(from_disk.read())
                with open(decode_to_dir, "wb") as to_disk:
                    to_disk.write(str1)


    print mode + "ed ", len(getfiles), " files."

if __name__=='__main__':
    path = "d:\PYTHON\diliupg\SoftwareDG\Educational\Learn_music\encode_decode"
    # if path not supplied use the current working directory
    if not path:
        path = os.getcwd()
    code = True
    main(path, code)
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
abid saied | 20 Aug 13:00 2014
Picon

How to end this program


    # OK, I'm stuck on setting up an instruction that ends the program once you
    # say either 'yes' or 'no'. And if you don't say 'yes' or 'no', and you reach
    # the end, the program comes to an end. Please remember I'm a newbie and would
    # appreciate any advise in plain simple English, like I was 5 years old!

import time

def main():
    print()
    print("YES/NO Game ")
    time.sleep(2)
    print()
    print()

    print("In this game, I will ask you a series of questions, if you answer YES or NO, you loose!")
    print()
    print("Remember to answer in Capitals!")
    print()
    time.sleep(2)
    print("Starting the game ...")
    print()
    time.sleep(2)
    name = input("What is your name? ")
    print()
    time.sleep(2) 
    print("ok " + (name) + (", time for the questions..."))
    print()
    time.sleep(2)

    
    answer = input("How old are you?  ")
    if answer == "YES":
        print("...You said yes, you loose!")
    elif answer == "NO":
        print ("...You said NO, you loose!")

    
    answer = input("Do you like apples? ")
    if answer == "YES":
        print("...You said yes, you loose!")
    elif answer == "NO":
        print ("...You said NO, you loose!")

    
    answer = input("Do you enjoy music?  ")
    if answer == "YES":
        print("...You said yes, you loose!")
    elif answer == "NO":
        print ("...You said NO, you loose!")

    answer = input("Have you ever been on a train?  ")
    if answer == "YES":
        print("...You said yes, you loose!")
    elif answer == "NO":
        print ("...You said NO, you loose!")

    answer = input("Do you watch 'Home and Away'?  ")
    if answer == "YES":
        print("...You said yes, you loose!")
    elif answer == "NO":
        print ("...You said NO, you loose!")

    answer = input("What is 50/5?  ")
    if answer == "YES":
        print("...You said yes, you loose!")
    elif answer == "NO":
        print ("...You said NO, you loose!")

    answer = input("Can a duck fly?  ")
    if answer == "YES":
        print("...You said yes, you loose!")
    elif answer == "NO":
        print ("...You said NO, you loose!")

        answer = input("Can you drive a car?  ")
    if answer == "YES":
        print("...You said yes, you loose!")
    elif answer == "NO":
        print ("...You said NO, you loose!")

        answer = input("Do you still watch cartoons?  ")
    if answer == "YES":
        print("...You said yes, you loose!")
    elif answer == "NO":
        print ("...You said NO, you loose!")

        answer = input("Can a duck fly?  ")
    if answer == "YES":
        print("...You said yes, you loose!")
    elif answer == "NO":
        print ("...You said NO, you loose!")

    
    print("OK, you win!You didn't say 'YES' or 'NO', well done!")
    time.sleep(2)

Abid Saied
abidsaied <at> gmail.com

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Gmane