Re: [Tutor] Can not install pycrypto on Windows 64bit with cygwin(python27)

2012-09-21 Thread Muse Gk
eryksun (), thanks for your help.

I had tried MinGW-w64 today, however, another more errors happen which
just like this (
http://stackoverflow.com/questions/6034390/compiling-with-cython-and-mingw-produces-gcc-error-unrecognized-command-line-o
). Another no solution error.

First, I tried to remove all instances of -mno-cygwin in
distutils\cygwinccompiler.py and got another different error.

Second, keep -mno-cygwin in distutils\cygwinccompiler.py, tried a
little version of  MinGW-w64 (
http://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win64/Personal%20Builds/rubenvb/gcc-4.5-release/
). This time finally kill the error "gcc: error: unrecognized command
line option '-mno-cygwin' ", however, got another one "collect2: ld
returned 1 exit status" instead.

It seems there is no way I can kill all errors. It took me hours and
hours to kill those errors, however, there is still another one. I am
feeling very depressed. I do not want to install pycrypto any more. :(

I hope there will be an easy way to install it in the short future.

gk

On Sat, Sep 22, 2012 at 2:32 AM, eryksun  wrote:
> On Fri, Sep 21, 2012 at 12:26 PM, Muse Gk  wrote:
>>
>> I have the very similar problem like this guy except I want to install
>> pycrypto ( https://www.dlitz.net/software/pycrypto/ ).
>> http://stackoverflow.com/questions/12005109/python-cannot-build-pycpuid
>
> Try MinGW-w64 running under Windows instead of Cygwin:
>
> website
> http://mingw-w64.sourceforge.net/
>
> rubenvb toolchain
> http://sourceforge.net/projects/mingw-w64/files/
> Toolchains%20targetting%20Win64/Personal%20Builds/rubenvb/gcc-4.7-release/
>
> Shortened URL for the above:
> http://goo.gl/Igujs
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I don't know why this program doesn't run

2012-09-21 Thread Gina

Thank you so much! That worked!

On 9/21/2012 7:17 PM, Dave Angel wrote:

Hi, you forgot to do a reply-all, so it didn't go to the list.  I'm
correcting that now, so don't worry about it.   if your email doesn't
support reply-all, then just add a cc of tutor@python.org


On 09/21/2012 08:09 PM, Gina wrote:

On 9/21/2012 6:47 PM, Dave Angel wrote:

On 09/21/2012 07:34 PM, Gina wrote:

I don't know why this program doesn't run, but if you know, please
tell me.
-thanks


So what happens when you try?  "Doesn't run" covers a multitude of
possibilities.

First one:

python Car Salesperson.py
python: can't open file 'Car': [Errno 2] No such file or directory
davea@think:~/temppython$

The fix for this one is to put quotes around the script name.  Or to
escape the blanks.  Or even better to rename the file so it doesn't have
spaces in it.


Please be specific.  You're running some OS, you launch some particular
version of Python, you give it some commandline, and you get some
unexpected result.  Use a lot of copy/paste and it's not too painful.


I have version 3 of python.

it will let me type in the type of car and then enter
then i type in the base price and when i hit enter, it says error


The problem is in your input statement:  base_price = input("What is the
base price?")

input (on Python version 3.x) always returns a string.  Sometimes that's
what you want, sometimes it's not.  In this case, just change to:

base_price = int(input("What is the base price?"))



This is the error message:
tax = base_price / 25
TypeError: unsupported operand type(s) for /: 'str' and 'int'

I tried adding int() in front of base_price but it still didn't work

Again, please be specific.  If you really tried this:

tax = int() base_price /25

then it naturally won't work.  But if you tried
 tax = int(base_price) / 25

it should have worked.  What error did you get?  Did it give the wrong
answer, or another exception traceback?

Anyway, I showed you my preference.  Convert data to their final type as
soon as possible after getting it from the user.  Not later when you're
trying to use it.




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I don't know why this program doesn't run

2012-09-21 Thread Dave Angel
Hi, you forgot to do a reply-all, so it didn't go to the list.  I'm
correcting that now, so don't worry about it.   if your email doesn't
support reply-all, then just add a cc of tutor@python.org


On 09/21/2012 08:09 PM, Gina wrote:
> On 9/21/2012 6:47 PM, Dave Angel wrote:
>> On 09/21/2012 07:34 PM, Gina wrote:
>>> I don't know why this program doesn't run, but if you know, please
>>> tell me.
>>> -thanks
>>>
>> So what happens when you try?  "Doesn't run" covers a multitude of
>> possibilities.
>>
>> First one:
>>
>> python Car Salesperson.py
>> python: can't open file 'Car': [Errno 2] No such file or directory
>> davea@think:~/temppython$
>>
>> The fix for this one is to put quotes around the script name.  Or to
>> escape the blanks.  Or even better to rename the file so it doesn't have
>> spaces in it.
>>
>>
>> Please be specific.  You're running some OS, you launch some particular
>> version of Python, you give it some commandline, and you get some
>> unexpected result.  Use a lot of copy/paste and it's not too painful.
>>
> I have version 3 of python.
> 
> it will let me type in the type of car and then enter
> then i type in the base price and when i hit enter, it says error
> 

The problem is in your input statement:  base_price = input("What is the
base price?")

input (on Python version 3.x) always returns a string.  Sometimes that's
what you want, sometimes it's not.  In this case, just change to:

base_price = int(input("What is the base price?"))


> This is the error message:
> tax = base_price / 25
> TypeError: unsupported operand type(s) for /: 'str' and 'int'
> 
> I tried adding int() in front of base_price but it still didn't work

Again, please be specific.  If you really tried this:

   tax = int() base_price /25

then it naturally won't work.  But if you tried
tax = int(base_price) / 25

it should have worked.  What error did you get?  Did it give the wrong
answer, or another exception traceback?

Anyway, I showed you my preference.  Convert data to their final type as
soon as possible after getting it from the user.  Not later when you're
trying to use it.



-- 

DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I don't know why this program doesn't run

2012-09-21 Thread Mark Lawrence

On 22/09/2012 00:44, Stephen Haywood wrote:

What doesn't work? What error message do you get? What have you done
to fix the errors? What version of Python are you using?

Stephen Haywood
Information Security Consultant
W: www.averagesecurityguy.info
T: @averagesecguy

On Sep 21, 2012, at 7:35 PM, Gina  wrote:


I don't know why this program doesn't run, but if you know, please tell me.
-thanks

___




Please don't top post on this list, thanks.

--
Cheers.

Mark Lawrence.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I don't know why this program doesn't run

2012-09-21 Thread Mark Lawrence

On 22/09/2012 00:34, Gina wrote:

I don't know why this program doesn't run, but if you know, please tell me.
-thanks


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



It helps us to help you if you give your OS, the complete error message 
that you get and your version of Python as well as the code.  "This 
program doesn't run" isn't much to go on.  Also putting a small piece of 
code inline rather than as an attachment is perfectly acceptable which 
I'll do now.


#adds extra fees to the base price of a car.

print(
"""
  Car Salesman

Totals the base price of a car with all other fees.
Please enter the requested information, and don't include
change.

"""
)

name = input("What kind of car is it?")
base_price = input("What is the base price?")

tax = base_price / 25
print("Tax: $", tax)

license_fee = base_price // 50
print("The license fee: $", license_fee)

maintenance = 45
print("The maintenance fee: $", maintenance)

insurance = 100
print("The insurance: $", insurance)

total = base_price + tax + license_fee + maintenance + insurance
print("After tax, the license fee, the maintenance fee, and the "
  "insurance fee, the ", name, "costs $", total, ".")


input("\n\nPress enter to exit.")


I'll hazard a guess that you're running Python 2.x and you get

What kind of car is it?Royce
Traceback (most recent call last):
  File "C:\Users\Mark\Car Salesperson.py", line 14, in 
name = input("What kind of car is it?")
  File "", line 1, in 
NameError: name 'Royce' is not defined

In which case change the input to raw_input and carry on to the next 
error :)


--
Cheers.

Mark Lawrence.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I don't know why this program doesn't run

2012-09-21 Thread Dave Angel
On 09/21/2012 07:34 PM, Gina wrote:
> I don't know why this program doesn't run, but if you know, please
> tell me.
> -thanks
>

So what happens when you try?  "Doesn't run" covers a multitude of
possibilities.

First one:

python Car Salesperson.py
python: can't open file 'Car': [Errno 2] No such file or directory
davea@think:~/temppython$

The fix for this one is to put quotes around the script name.  Or to
escape the blanks.  Or even better to rename the file so it doesn't have
spaces in it.


Please be specific.  You're running some OS, you launch some particular
version of Python, you give it some commandline, and you get some
unexpected result.  Use a lot of copy/paste and it's not too painful.

-- 

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I don't know why this program doesn't run

2012-09-21 Thread Stephen Haywood
What doesn't work? What error message do you get? What have you done
to fix the errors? What version of Python are you using?

Stephen Haywood
Information Security Consultant
W: www.averagesecurityguy.info
T: @averagesecguy

On Sep 21, 2012, at 7:35 PM, Gina  wrote:

> I don't know why this program doesn't run, but if you know, please tell me.
> -thanks
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How can I convert a variable name to a string?

2012-09-21 Thread Stephen Haywood
On Sep 21, 2012, at 6:14 AM, Dae James  wrote:

  How can I convert a variable name to a string ?
For example:
testVariable = 1000;
How can I get the string "testVariable" ?
Thank you~


Use a dictionary.

vars['testVariable'] = 1000

for key in vars:
print key
print vars[key]

--
Dae James

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] I don't know why this program doesn't run

2012-09-21 Thread Gina

I don't know why this program doesn't run, but if you know, please tell me.
-thanks
#adds extra fees to the base price of a car.

print(
"""
  Car Salesman
 
Totals the base price of a car with all other fees.
Please enter the requested information, and don't include
change.

"""
)

name = input("What kind of car is it?")
base_price = input("What is the base price?")

tax = base_price / 25
print("Tax: $", tax)

license_fee = base_price // 50
print("The license fee: $", license_fee)

maintenance = 45
print("The maintenance fee: $", maintenance)

insurance = 100
print("The insurance: $", insurance)

total = base_price + tax + license_fee + maintenance + insurance
print("After tax, the license fee, the maintenance fee, and the "
  "insurance fee, the ", name, "costs $", total, ".")


input("\n\nPress enter to exit.")
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How can I convert a variable name to a string?

2012-09-21 Thread Emile van Sebille

On 9/21/2012 2:11 AM Dae James said...

How can I convert a variable name to a string ?
For example:
testVariable = 1000;
How can I get the string "testVariable" ?


If what you're asking is 'how do I get the value associated with the the 
string "testVariable"?' then yuo can use something like:


locals()["testVariable"]

Emile



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generate array, different results

2012-09-21 Thread Prasad, Ramit
Pavel Andreev wrote:
> Hello all
> A question from very beginner.
> I generate a simple example array and then print its elements on the screen.
> 
> f=[[0]*3]*3  # array initialization

Your problem is above. Let us rewrite the above line as
a = [0]*3
f = [a]*3 

Variable `a` is a new list with 3 copies of the contents in the
list which is 0 (i.e. there are 3 zeros in the new list). 
There is no problem here because 0 is an immutable (cannot be 
changed) object. Now in the second line, the variable `f` 
is a new list with 3 copies of `a`. This basically boils
down to the equivalent of:
f = [ a for _ in xrange(3) ] # OR
f = [ a, a, a ]

You can see they are the same object by using is.

>>> f[0] is f[1]
True

`f[0]` and `f[1]` are both bound to the same list object.
Since lists are mutable objects, when you change `f[0]` you
are actually changing the object underlying `f[1]`.
You can fix your problem by the following instead.

f = [ [0]*3 for _ in xrange(3) ]


> for i in range(3):
> for j in range(3):
> f[i][j]=str(i)+str(j)# make simple example array
> print f[i][j],   # print resulting elements
> print '\n'
> 
> 
>  00   01   02
> 
>  10   11   12
> 
>  20   21   22
> 
> 
> So I generate element in loop and then print it and see all is ok.

The reason your loop works initially is that you are setting the 
value you want immediately before you print it. With each iteration
of `i` you are discarding the previous value. You can debug what is 
happening if you print `f`  at each step in the loop instead of 
`f[i][j]`. It will probably make a lot more sense than my explanation. 

 
> But after that if I print the whole generated array, I see different
> result with constant first number, as if "i" variable does not vary
> and equals to "2". What is wrong?
> 
> >>> print f
> 
> [['20', '21', '22'], ['20', '21', '22'], ['20', '21', '22']]
> 
> I use python 2.7


Feel free to ask for clarification if that explanation did not 
make sense.



This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generate array, different results

2012-09-21 Thread eryksun
On Fri, Sep 21, 2012 at 2:47 PM, Pavel Andreev  wrote:
>
> f=[[0]*3]*3  # array initialization

The above isn't giving you what you want. All 3 sublists are the same object:

>>> f = [[0]*3]*3

>>> map(id, f)
[149391980, 149391980, 149391980]

Do this instead:

>>> f = [[0]*3 for i in range(3)]

Each iteration in the comprehension creates a new list:

>>> map(id, f)
[149392364, 149392012, 149392428]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2012-09-21 Thread eryksun
On Fri, Sep 21, 2012 at 2:46 PM, Brett Dailey
 wrote:
>
> It just needs to be scaled to fit into each tile. You can just use one of your
> choice as a place holder for now and I'll just put my own in later.

I wrote up a version last night. Here's an image of the output:

http://i.imgur.com/h4Wcd.png

It scales the image (pygame.transform.smoothscale) by the largest of
the two scale factors. Thus one dimension fits and the other is
potentially oversized. This preserves the aspect ratio.  It then crops
an area the size of the cell out of the center by blit'ing to a new
surface with the pygame.SRCALPHA flag set.

mark_image = pygame.Surface(cell_size, flags=pygame.SRCALPHA)
mark_image.blit(image, (0,0), areatl + areabr)

This preserves transparency in the source image when you blit to a cell.

I chose the randomly marked cells like this:

num_marks = int(round(0.1 * num_cells))
marked_cells = set(random.sample(xrange(num_cells), num_marks))

To draw the grid, iterate over the rows and columns with a nested for
loop. Pick the background color out of a list of 2 colors. The index
is simply (row + col) % 2. As col increments in the inner loop, the
value toggles between 0 and 1. Then when it gets to the next row (i.e.
row += 1), the pattern shifts by 1. If the current cell number is in
marked_cells, blit the image also.

My implementation uses a Board class with the following methods:
__init__, update, update_image, set_marks, and draw. It also has two
class attributes: bgcolor and cell_colors.

The image I chose is a standard Gnome emoticon. Here's the icon's path
in my Debian installation:

/usr/share/icons/gnome/256x256/emotes/face-cool.png
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once.

2012-09-21 Thread Gregory Lund
>
> You need to add the folder where python.exe is to your PATH variable.

I just realized the path we're heading down here isn't going to work.
I need on .py file to be up an running so that I can add it to my tool
in ArcGIS.


>
> Oscar

I appreciate the help Oscar, and I believe it would work that way, but...

I need on .py file to be up an running so that I can add it to my tool
in ArcGIS.

I would like to revise my question and add some more specifics.

I must use Python 2.6!
This is a task that I really want to automate, the situation is static
and once I create this, I'll be golden (good).
I must create one, stand alone script (in Idle, I hope) that will:

1. Unzip a single original zipfile (in_Zip) to the contents of the
folder that the zipfile currently resides.
2. Go to the unique (NON ZIPPED) folders (actually student usernames
'aforker', 'allisw99', 'btaylor7', etc) that result from step 1.
(there may be anywhere from 1 to 40 of these unique student folders)
3. Within each unique folder ('aforker', 'allisw99', 'btaylor7', etc)
extract any and all (could be none, could be 3 or 4) .zip files
within, to their relative aforementioned unique folders ('aforker',
'allisw99', 'btaylor7', etc), while 'navigating' i.e. not getting hung
up on possible .pdf or docx files that may or may not reside in the
unique folders ('aforker', 'allisw99', 'btaylor7', etc)

This is what I've got so far: (and it 'works') (I'll modify later so
that I do not need to hard-code the original zipfile (in_Zip))
---

import os, os.path, zipfile inZip =
r'D:\D_Drive_Documents\Student_Work_Sample_usecopy1\2012-09-18
Lab_2.zip'

outDir = r"D:\D_Drive_Documents\Student_Work_Sample_usecopy1"

z = zipfile.ZipFile(in_Zip,'a')

z.extractall(outDir)

zipContents = z.namelist()

print zipContents

z.close


It works, I get the following in the Python Shell:

'>>>  RESTART '

'>>>'

['Lab_2/aforker/', 'Lab_2/aforker/aforker_Lab2.zip',
'Lab_2/allisw99/', 'Lab_2/allisw99/allisw99_Lab2.zip',
'Lab_2/allisw99/allisw99_Lab2_Bonus.pdf', 'Lab_2/allisw992/',
'Lab_2/allisw992/allisw99_Lab2_Bonus.pdf', 'Lab_2/btaylor7/',
'Lab_2/btaylor7/2nd_btaylor7_Lab2.zip',
'Lab_2/btaylor7/btaylor7_Lab2.zip', 'Lab_2/']

'>>> '

But, what I can't figure out is how to get 'into' each unique folder:
aforker, allisw99, etc. and then extract any and all zips within
'aforker', 'allisw99', etc.

I have no doubt that the suggestions posted here will work, but they
all seem to get away from a single .py file and
 a) I can't get them to work, and
b) it doesn't really help me because I need ONE stand alone .py file
to make this all work in ArcGIS.

 I will be using this to create an ArcGIS 'tool' that requires one
script (at least for me to comprehend it) :-)

Thank you in advance for any and all suggestions, tips etc.

For the record, I did try the following  (to at least try
something) at  the bottom of the code above:
---

for item in zipContents:
itemLoc = os.path.join(outDir,item)
y = zipfile.ZipFile(itemLoc,'a')
y.extractall(os.path.aplit(itemLoc)[0])
y.close


but I get the following error:

Traceback (most recent call last): File
"D:\D_Drive_Documents\Scripts\Unzip_a_zip_of_zips\Scripts\unzip_a_zip.py",
line 50, in y = zipfile.ZipFile(itemLoc,'a') File
"C:\Python26\ArcGIS10.0\lib\zipfile.py", line 687, in init self.fp =
open(file, modeDict[mode]) IOError: [Errno 13] Permission denied:
'D:\D_Drive_Documents\Student_Work_Sample_usecopy1\Lab_2/aforker/'

I guess my first issue is to resolve the 'Permission denied' problem.
And, I know I need an 'if' statement, somehow...

thanks in advance for any and all input!

Greg

PS, neophyte/rookie, trying to keep it simple. This is not my normal
daily task (good thing, right?)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Generate array, different results

2012-09-21 Thread Pavel Andreev
Hello all
A question from very beginner.
I generate a simple example array and then print its elements on the screen.

f=[[0]*3]*3  # array initialization
for i in range(3):
for j in range(3):
f[i][j]=str(i)+str(j)# make simple example array
print f[i][j],   # print resulting elements
print '\n'


 00   01   02

 10   11   12

 20   21   22


So I generate element in loop and then print it and see all is ok.

But after that if I print the whole generated array, I see different
result with constant first number, as if "i" variable does not vary
and equals to "2". What is wrong?

>>> print f

[['20', '21', '22'], ['20', '21', '22'], ['20', '21', '22']]

I use python 2.7
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can not install pycrypto on Windows 64bit with cygwin(python27)

2012-09-21 Thread eryksun
On Fri, Sep 21, 2012 at 12:26 PM, Muse Gk  wrote:
>
> I have the very similar problem like this guy except I want to install
> pycrypto ( https://www.dlitz.net/software/pycrypto/ ).
> http://stackoverflow.com/questions/12005109/python-cannot-build-pycpuid

Try MinGW-w64 running under Windows instead of Cygwin:

website
http://mingw-w64.sourceforge.net/

rubenvb toolchain
http://sourceforge.net/projects/mingw-w64/files/
Toolchains%20targetting%20Win64/Personal%20Builds/rubenvb/gcc-4.7-release/

Shortened URL for the above:
http://goo.gl/Igujs
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Can not install pycrypto on Windows 64bit with cygwin(python27)

2012-09-21 Thread Muse Gk
Friends,

I have the very similar problem like this guy except I want to install
pycrypto ( https://www.dlitz.net/software/pycrypto/ ).

http://stackoverflow.com/questions/12005109/python-cannot-build-pycpuid

We had done enough researches on Google, still can not get a solution.

Could some friends here give me or us a solution?

Thanks in advance.

BTW, English is not first language and I am not good at writing or
speaking in English, however reading is not a problems.
So hope no words make you confused.

gk
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] np array.any() question

2012-09-21 Thread Andre' Walker-Loud
> To summarize,
> with a numpy array called a, the OP is getting an error doing:
> 
> (3 < a < 5).any()
> 
>> ...
> 
> I think not.  The last expression you give will even return true if one
> of the values is > 3 and a DIFFERENT value is < 5.   And i suspect the
> OP only wants a TRUE if at least one item in the array is between 3 and 5.
> 
> I know nothing about numpy, but does it have a way to do an element-wise
> AND of two bool arrays of the same size?  Maybe it's a function call and
> not 'and'  Or maybe it's the & operator or something.

Yes, numpy does have a function like this:

numpy.all()  [ "and" function ]
numpy.any() [ "or" function ]



> I find the operator overloading i've seen in numpy to be very confusing,
> so I haven't tried to download it and try it out.  Maybe if I read the
> docs directly, instead of just seeing examples and problems here, I'd
> think differently.

here you go :)

http://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html#numpy.all
http://docs.scipy.org/doc/numpy/reference/generated/numpy.any.html#numpy.any

you can ask if any satisfy the conditions and return true if 1+ are true:

>>> a = numpy.array([  7.,   1.,   1.,   1.,   2.,   4.,   0.,   7.,   6.,  
>>> 10.])
>>> numpy.any([ 3 < a, a < 5])
True
>>> numpy.all([ 3 < a, a < 5])
False

or you can ask for an array back telling you which are true and which false:

>>> numpy.any([ 3 < a, a < 5], axis=0)
array([ True,  True,  True,  True,  True,  True,  True,  True,  True,  True], 
dtype=bool)
>>> numpy.any([ 3 < a, a < 5], axis=0)
array([False, False, False, False, False,  True, False, False, False, False], 
dtype=bool)


Note you are not limited to just comparing two arrays, but can compare as many 
as you like.

To the OP: in this case, google (insert whatever search engine you like) is 
your friend.  A good first bet is if there is some operation you like in 
python, other people like it also, and someone has taken the time to make a 
numpy version which acts element-wise on equal sized arrays.


Andre




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] np array.any() question

2012-09-21 Thread Dave Angel
On 09/21/2012 11:25 AM, Steven D'Aprano wrote:
> On 22/09/12 01:07, Bala subramanian wrote:
>> Friends,
>> May i know why do get a Valuerror if i check any value in a is between
>> 3.0 to 5.0 ?

To summarize,
with a numpy array called a, the OP is getting an error doing:
   

(3 < a < 5).any()


> This tries to calculate:
>
> (3 < a) and (a < 5)
>
> py> 3 < a
> array([False, False, False,  True,  True,  True], dtype=bool)
> py> a < 5
> array([ True,  True,  True,  True,  True, False], dtype=bool)
>
> but combining them with the "and" operator is ambiguous:
>
> py> (3 < a) and (a < 5)
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: The truth value of an array with more than one element
> is ambiguous. Use a.any() or a.all()
>
> Since the boolean "and" of the two arrays never gets calculated,
> the any method never gets called. You could do:
>
>
> py> (3 < a).any() and (a < 5).any()
> True
>
> which I think does what you want.
>

I think not.  The last expression you give will even return true if one
of the values is > 3 and a DIFFERENT value is < 5.   And i suspect the
OP only wants a TRUE if at least one item in the array is between 3 and 5.

I know nothing about numpy, but does it have a way to do an element-wise
AND of two bool arrays of the same size?  Maybe it's a function call and
not 'and'  Or maybe it's the & operator or something.

I find the operator overloading i've seen in numpy to be very confusing,
so I haven't tried to download it and try it out.  Maybe if I read the
docs directly, instead of just seeing examples and problems here, I'd
think differently.



-- 

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2012-09-21 Thread Steven D'Aprano

On 22/09/12 01:18, Jerry Hill wrote:

On Fri, Sep 21, 2012 at 10:33 AM, Prasad, Ramit
  wrote:

Ironically, that describes me. So what is the preference for large
code samples? Just always include it? What about for the main list?


It's tricky.

Ideally, you need to take your large code base, and reduce it into a
short piece of sample code that is runnable and reproduces your issue.


+1 on this.

See also:

http://sscce.org/

But, suppose you try really hard, and the shortest you can get your code
down is 200 lines (for example). What then?

There is no good answer. Speaking for myself, I would prefer that you
attach the file to your email. But others will be unhappy if you do
that, and will prefer that you use a pastebin. But if you use a pastebin,
I will be unhappy (I am probably not the only one). So whatever you do,
you will make somebody unhappy.

Oh well, that's life.




In many cases, the act of trimming your code down to that form will
actually cause you to find the answer to your own question without
even needing to send it.  This process is sometimes known as "rubber
ducking" -- 
http://www.codinghorror.com/blog/2012/03/rubber-duck-problem-solving.html

I can't count the number of times that I've had a problem, decided to
send it to a mailing list for help, and in the process of fully
describing the problem I'm having, come up with the solution without
even having to send the email.


I second that. Just the other day, I was puzzling over how to do something
in Python, involving the signal module. By the time I had written a *short*
(less than twenty lines) example showing what I was trying to do, I had
worked out how to do it and didn't need to send the email.

This was not an unusual case.



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] np array.any() question

2012-09-21 Thread Oscar Benjamin
On Sep 21, 2012 4:09 PM, "Bala subramanian" 
wrote:
>
> Friends,
> May i know why do get a Valuerror if i check any value in a is between
> 3.0 to 5.0 ?
> >>> import numpy as np
> >>> a=np.array([ 2.5,  2.6,  3.0 ,  3.5,  4.0 ,  5.0 ])
> >>> (a > 7).any()
> False
> >>> (a > 4).any()
> True
> >>> (3 < a < 5).any()
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: The truth value of an array with more than one element is
> ambiguous. Use a.any() or a.all()

You need to use ((3 < a) & (a <5)).any()

The problem is not with any(). The problem is that the multiple binary
comparison needs to convert its intermediate results to bool. So (3 < a <
5) is processed as:

(3 < a) and (a < 5)

To process the 'and' operator python needs to know if the first expression
is True. This means calling bool(3 < a). But, since (3 < a) is an array of
booleans it cannot be said to be True or False. This is what gives the
ValueError that you see.

If you use bitwise-and '&' instead of logical-and 'and' it will perform the
and operation separately on each element of each array which is what you
want.

Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] np array.any() question

2012-09-21 Thread Steven D'Aprano

On 22/09/12 01:07, Bala subramanian wrote:

Friends,
May i know why do get a Valuerror if i check any value in a is between
3.0 to 5.0 ?

import numpy as np
a=np.array([ 2.5,  2.6,  3.0 ,  3.5,  4.0 ,  5.0 ])
(a>  7).any()

False


This calculates an array of bools, then calls any() on it.

py> a > 7
array([False, False, False, False, False, False], dtype=bool)
py> (a > 7).any()
False



(a>  4).any()

True


This also builds an array of bools, then calls any():

py> a > 4
array([False, False, False, False, False,  True], dtype=bool)
py> (a > 4).any()
True




(3<  a<  5).any()

Traceback (most recent call last):
   File "", line 1, in
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()



This tries to calculate:

(3 < a) and (a < 5)

py> 3 < a
array([False, False, False,  True,  True,  True], dtype=bool)
py> a < 5
array([ True,  True,  True,  True,  True, False], dtype=bool)

but combining them with the "and" operator is ambiguous:

py> (3 < a) and (a < 5)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: The truth value of an array with more than one element
is ambiguous. Use a.any() or a.all()

Since the boolean "and" of the two arrays never gets calculated,
the any method never gets called. You could do:


py> (3 < a).any() and (a < 5).any()
True

which I think does what you want.



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2012-09-21 Thread Jerry Hill
On Fri, Sep 21, 2012 at 10:33 AM, Prasad, Ramit
 wrote:
> Ironically, that describes me. So what is the preference for large
> code samples? Just always include it? What about for the main list?

It's tricky.

Ideally, you need to take your large code base, and reduce it into a
short piece of sample code that is runnable and reproduces your issue.
 Yes, this can be hard to do, and yes, it can take a lot of time. It
should be as short as possible, trimming out all of the extraneous
functions and calls.  It needs to be short enough that someone
interested can actually read it and understand what you're trying to
accomplish.  It needs to be long enough to actually demonstrate the
problem you're having.

It's worth the trouble though -- anything longer than a page or two of
code is going to get glossed over by many readers -- they just don't
have time to read and understand your code, see where you're having a
problem and diagnose the issue for you.  You're much more likely to
get help with a 10 or 20 line sample than with a 100 or 200 line one,
much less something that's thousands of lines of code.

The people here are volunteers -- the best way to engage them in your
problem is to be respectful of their time.  Often, that means spending
extra time of your own to save their time.

In many cases, the act of trimming your code down to that form will
actually cause you to find the answer to your own question without
even needing to send it.  This process is sometimes known as "rubber
ducking" -- 
http://www.codinghorror.com/blog/2012/03/rubber-duck-problem-solving.html

I can't count the number of times that I've had a problem, decided to
send it to a mailing list for help, and in the process of fully
describing the problem I'm having, come up with the solution without
even having to send the email.

-- 
Jerry
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] application whitelisting

2012-09-21 Thread Steven D'Aprano

On 21/09/12 20:51, Albert-Jan Roskam wrote:

Hi,

My company just started application whitelisting. Now a new version of
a (benign!!) dll does not work as it (or rather, its file hash, if I
understood it correctly) is not whitelisted.


Then get it whitelisted. If your company doesn't have the ability to
update the whitelist when your software updates, it's even more stupid
than it seems.

Application whitelisting is a poor idea. The first time you run a
Windows update, *everything will break*. Unless of course you trust
software from Microsoft -- or rather, you trust software that you *think*
is from Microsoft. So right there you have a vulnerability: any malware
that can steal a certificate, or sign up for a "legitimate" certificate,
will be trusted.

Whitelisting doesn't protect you from infected PDF files, buffer overflows,
code injection attacks, XSS attacks, Flash, etc. It's yet another buzzword
that *at best* will temporarily protect you from a few threats while doing
absolutely nothing about solving the actual problem.



The code below is probably simplistic/naive, but it's a product of my
frustration + curiosity. The strategy was to generate a dll that has the
same file hash as the original dll by right-padding it with zero until
the desired checksum is found. Why a zero? No idea. ;-)


It's worse than that. If the application whitelist is using md5 (and wanna
bet that at least 50% of the commercial whitelist software out there is?),
then it is already broken. An attacker can easily take an arbitrary
application, and generate a new application with the same MD5 sum and the
same length, differing by 128 bytes.

http://www.mscs.dal.ca/~selinger/md5collision/

Is 128 bytes enough to compromise the application and turn it into an
attack tool? I don't know, but probably.



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2012-09-21 Thread Prasad, Ramit
Steven D'Aprano wrote:
> On 21/09/12 08:54, Prasad, Ramit wrote:
> > People on this list are not all receiving this via email.
> 
> 
> They're not? How else can you receive this? Unlike the main python-list,
> this isn't (as far as I know) mirrored on Usenet.
> 
> I wonder under what circumstances people could read this email without
> seeing any attachments.


My mistake, I was under the impression it was mirrored on Usenet.

> 
> 
> > It is
> > recommended that you post 1. plain text (instead of Rich Text or HTML)
> 
> Agreed.
> 
> > 2. Just include the code directly in the email if it is short (which this
> > is)
> 
> Agreed.
> 
> >or post to a website like pastebin for large samples.
> 
> Not agreed. Pastebins expire, or their websites disappear. In three
> months or three years, code pasted to a bin will probably no longer exist
> and nobody reading this thread via the web archives will have any clue
> what is being talked about.
> 
> Also, some people will be reading this thread via email but be behind a
> firewall that limits their access to the web so that they cannot reach
> the pastebin.
> 

Ironically, that describes me. So what is the preference for large
code samples? Just always include it? What about for the main list?


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about lists

2012-09-21 Thread Hugo Arts
On Fri, Sep 21, 2012 at 3:31 PM, Leo Degon  wrote:

> I'm trying to create a class where the main focus is creating a list whose
> elements are lists and the elements of those lists are collection of zeros
> and ones. I am trying to create functions to rotate the list ninety
> degrees, to reflect it. Having a few problems with the rotation.
> get TypeError: 'list' object is not callable
>
> def pset(n):
> for i in n:
> print(i)
> class board():
> def make(self,size):
> b=[]
> for i in range(size[0]):
> b.append([])
> for j in range(size[1]):
> b[i].append(0)
> return b
>
> def rotate(self,board,size):
> size[0],size[1]=size[1],size[0]
> new=board(size)
> lists=[]
> for j in range(size[1]):
> lists.append([])
> for i in range(size[0]).__reversed__():
> lists[j].append(board[i][j])
> for i in range(size[1]):
> for j in range(size[0]):
> new.board[i,j]=lists[i,j]
> return(new.board)
> def __init__(self,size):
> self.size=size
> self.board=self.make(size)
> y=[7,7]
> x=board(y)
> pset(x.board)
> x.board[0][0]=1
> print()
> pset(x.board)
> print()
> x.board=x.rotate(x.board,x.size)
> pset(x.board)
> print()
>
>
Please always include a full traceback, it makes the error much more
obvious. For example, running your code I get:

>>>
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
()
[1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
()

Traceback (most recent call last):
  File "C:/Users/hugo/Downloads/test.py", line 35, in 
x.board=x.rotate(x.board,x.size)
  File "C:/Users/hugo/Downloads/test.py", line 15, in rotate
new=board(size)
TypeError: 'list' object is not callable
>>>

This makes it fairly obvious what is going on. in the rotate function, you
have an argument called board, and your class is also called board. You
can't have the same name refer to two different things. What happens is
that the argument "masks" the class, making it inaccessible.

I should also say it is very confusing to have a class called board with an
attribute that is also called board. You should think about naming your
variables more clearly to minimize confusion.

HTH,
Hugo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about lists

2012-09-21 Thread Peter Otten
Leo Degon wrote:

> I'm trying to create a class where the main focus is creating a list whose
> elements are lists and the elements of those lists are collection of zeros
> and ones. I am trying to create functions to rotate the list ninety
> degrees, to reflect it. Having a few problems with the rotation.
> get TypeError: 'list' object is not callable
> 
> def pset(n):
> for i in n:
> print(i)
> class board():
> def make(self,size):
> b=[]
> for i in range(size[0]):
> b.append([])
> for j in range(size[1]):
> b[i].append(0)
> return b
> 
> def rotate(self,board,size):

The local parameter "board" shades the class with the same name, 

> size[0],size[1]=size[1],size[0]
> new=board(size)

so here you are not making a new board instance but instead trying to call 
the board parameter which is a list. To fix this problem you have to rename 
the parameter or the class. I recommend that you rename the class to Board 
(by convention class names start with an uppercase letter).

As to the parameter board, you actually don't need it at all -- you can 
instead make the board attribute of the new Board instance a rotated version 
of self.board.

(There are more bugs in your code, but I suggest you tackle them one at a 
time. Come back here if you need help fixing them)

> lists=[]
> for j in range(size[1]):
> lists.append([])
> for i in range(size[0]).__reversed__():
> lists[j].append(board[i][j])
> for i in range(size[1]):
> for j in range(size[0]):
> new.board[i,j]=lists[i,j]
> return(new.board)
> def __init__(self,size):
> self.size=size
> self.board=self.make(size)
> y=[7,7]
> x=board(y)
> pset(x.board)
> x.board[0][0]=1
> print()
> pset(x.board)
> print()
> x.board=x.rotate(x.board,x.size)
> pset(x.board)
> print()


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How can I convert a variable name to a string?

2012-09-21 Thread Steven D'Aprano

On 21/09/12 19:11, Dae James wrote:

How can I convert a variable name to a string ?
For example:
testVariable = 1000;
How can I get the string "testVariable" ?



You can't. Any value could have zero, one or many names, and there is no way
to go backwards from the object to the name.

What are you trying to do that you think you need this?



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about lists

2012-09-21 Thread Dave Angel
On 09/21/2012 09:31 AM, Leo Degon wrote:
> I'm trying to create a class where the main focus is creating a list whose
> elements are lists and the elements of those lists are collection of zeros
> and ones. I am trying to create functions to rotate the list ninety
> degrees, to reflect it. Having a few problems with the rotation.
> get TypeError: 'list' object is not callable

Where is the rest of the error message?  And don't forget to mention
which Python version you're using.

> def pset(n):
> for i in n:
> print(i)
> class board():

One Python convention which would have helped here is to use capital for
the class name, Board

Another one is to put __init__ first, since that tells us what instance
attributes you'll be using, and how they're initialized.

> def make(self,size):
> b=[]
> for i in range(size[0]):
> b.append([])
> for j in range(size[1]):
> b[i].append(0)
> return b
>
> def rotate(self,board,size):

You've now defined a new local called board, which shadows the class
name board.  Is there a reason you didn't use self.board ?  As it's
presently coded, this method doesn't seem to use any instance attributes.

> size[0],size[1]=size[1],size[0]
> new=board(size)
> lists=[]
> for j in range(size[1]):
> lists.append([])
> for i in range(size[0]).__reversed__():
> lists[j].append(board[i][j])
> for i in range(size[1]):
> for j in range(size[0]):
> new.board[i,j]=lists[i,j]
> return(new.board)
> def __init__(self,size):
> self.size=size
> self.board=self.make(size)
> y=[7,7]
> x=board(y)
> pset(x.board)
> x.board[0][0]=1
> print()
> pset(x.board)
> print()
> x.board=x.rotate(x.board,x.size)
> pset(x.board)
> print()
>
>


-- 

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question about lists

2012-09-21 Thread Leo Degon
I'm trying to create a class where the main focus is creating a list whose
elements are lists and the elements of those lists are collection of zeros
and ones. I am trying to create functions to rotate the list ninety
degrees, to reflect it. Having a few problems with the rotation.
get TypeError: 'list' object is not callable

def pset(n):
for i in n:
print(i)
class board():
def make(self,size):
b=[]
for i in range(size[0]):
b.append([])
for j in range(size[1]):
b[i].append(0)
return b

def rotate(self,board,size):
size[0],size[1]=size[1],size[0]
new=board(size)
lists=[]
for j in range(size[1]):
lists.append([])
for i in range(size[0]).__reversed__():
lists[j].append(board[i][j])
for i in range(size[1]):
for j in range(size[0]):
new.board[i,j]=lists[i,j]
return(new.board)
def __init__(self,size):
self.size=size
self.board=self.make(size)
y=[7,7]
x=board(y)
pset(x.board)
x.board[0][0]=1
print()
pset(x.board)
print()
x.board=x.rotate(x.board,x.size)
pset(x.board)
print()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] application whitelisting

2012-09-21 Thread Hugo Arts
On Fri, Sep 21, 2012 at 2:19 PM, Peter Otten <__pete...@web.de> wrote:
>
> Here's a back-of-the-envelope calculation:
>
> '4151e067c17a753fc5c4ec1c507d28c9' is a hexadecimal number with 32 digits,
> otherwise known as
>
> 340282366920938463463374607431768211456L
>
> If you are trying to hit that number using random additions to your file
> you
> can expect success after (that number)/2 attempts. Assuming you try 10
> million additions per second that will take about
>
> >>> (16**32//2)/(10**7 * 60 * 60 * 24 * 365)
> 539514153540300709448526L
>
> years.
>
> But you are lucky, md5 has been cracked. I don't know if there is a
> practical way to create a document with the same hash for any given hash
> though, so as a starting point I refer you to


As a short answer, there is no practical way to do this (there is a
theoretical one, but it's still computationally infeasible). There is a way
to generate two files (e.g. an innocent one and an evil one) with identical
md5 hashes just by appending a few thousand bytes to each file. If you get
the innocent file accepted into the whitelist both will work. At that point
it's easier to just get the ctypes dll on the whitelist itself though,
since it is innocent anyway.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] application whitelisting

2012-09-21 Thread Peter Otten
Albert-Jan Roskam wrote:

> Hi,
> 
> My company just started application whitelisting. Now a new version of a
> (benign!!) dll does not work as it (or rather, its file hash, if I
> understood it correctly) is not whitelisted. Is there any way I can use
> the same dll of a newer version? I know this sounds like a hacking
> request, but my intentions are sincere. My only purpose is to use ctypes
> to use the functions that are present in the new, but not the old, dll
> version.
> 
> 
> The code below is probably simplistic/naive, but it's a product of my
> frustration + curiosity. The strategy was to generate a dll that has the
> same file hash as the original dll by right-padding it with zero until the
> desired checksum is found. Why a zero? No idea. ;-)
> 
> PS: I guess virtual environment also cannot be used for this, right?
> 
> 
> import hashlib
> import contextlib
> 
> def generateFile(infile, desired_hash, hashtype="md5"):
> outfile = infile[:-4] + "_adjusted.dll"
> hashlib_ = hashlib.new(hashtype)
> with contextlib.nested(open(infile, "rb"), open(outfile, "wb")) as (f_in,
> f_out): observed_hash = hashlib_(f_in.read())
> found = observed_hash.hexdigest() == desired_hash
> counter = 0
> while True:
> counter += 1
> observed_hash.update("0")
> if found:
> f_out.write(f_in.read() + (counter * "0"))
> print "Got it: '%s'" f_out.name
> break
> 
> infile = r"D:\temp\myown.dll"
> generateFile(infile, '4151e067c17a753fc5c4ec1c507d28c9')

Here's a back-of-the-envelope calculation:

'4151e067c17a753fc5c4ec1c507d28c9' is a hexadecimal number with 32 digits, 
otherwise known as

340282366920938463463374607431768211456L

If you are trying to hit that number using random additions to your file you 
can expect success after (that number)/2 attempts. Assuming you try 10 
million additions per second that will take about

>>> (16**32//2)/(10**7 * 60 * 60 * 24 * 365)
539514153540300709448526L

years. 

But you are lucky, md5 has been cracked. I don't know if there is a 
practical way to create a document with the same hash for any given hash 
though, so as a starting point I refer you to 

http://en.wikipedia.org/wiki/Md5

Looking forward to see your final script...

Or you think a bit out of the box and ask for the required dll to be put on 
the whitelist.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] application whitelisting

2012-09-21 Thread Dave Angel
On 09/21/2012 06:51 AM, Albert-Jan Roskam wrote:
> Hi,
>
> My company just started application whitelisting. Now a new version of a 
> (benign!!) dll does not work as it (or rather, its file hash, if I understood 
> it correctly) is not whitelisted. Is there any way I can use the same dll of 
> a newer version? I know this sounds like a hacking request, but my intentions 
> are sincere. My only purpose is to use ctypes to use the functions that are 
> present in the new, but not the old, dll version.
>
>
> The code below is probably simplistic/naive, but it's a product of my 
> frustration + curiosity. The strategy was to generate a dll that has the same 
> file hash as the original dll by right-padding it with zero until the desired 
> checksum is found. Why a zero? No idea. ;-)

Two catches I can think of:  1) any decent white-lister would have both
a hashcode and a size for each file it's protecting.  2) On the average,
you'll be adding more bytes to that file than exist in all the disks of
all the computers in the solar system, MANY times over.  (The number in
decimal has something like 40 digits in it)

> PS: I guess virtual environment also cannot be used for this, right?
>
Not as far as I know, but there are many others much more familiar with
python virtual environment.

If this were my problem, and if i had sufficient rights on the machine,
I'd install a Virtual Machine, and run things there.  But of course
you'd have to get that past the white-listers.

> import hashlib
> import contextlib
>
> def generateFile(infile, desired_hash, hashtype="md5"):
> outfile = infile[:-4] + "_adjusted.dll"
> hashlib_ = hashlib.new(hashtype)
> with contextlib.nested(open(infile, "rb"), open(outfile, "wb")) as (f_in, 
> f_out):
> observed_hash = hashlib_(f_in.read())
> found = observed_hash.hexdigest() == desired_hash
> counter = 0
> while True:
> counter += 1
> observed_hash.update("0")
> if found:
> f_out.write(f_in.read() + (counter * "0"))

This limits file size to what will fit in memory in a single string.  
Assuming you have millions of petabytes of disk space and only a few
gigabytes of available RAM, you should write a loop for the counter
bytes, perhaps chunking it for compromise between memory and speed.  If
the numbers weren't SO huge, and if you were running on Linux, perhaps a
sparse file would save both a lot of time and a lot of actual disk
space.  I have no experience with them, however -- it'd be fun to learn.


> print "Got it: '%s'" f_out.name
> break
>
> infile = r"D:\temp\myown.dll"
> generateFile(infile, '4151e067c17a753fc5c4ec1c507d28c9')
>
There are known ways to break md5;  it's no longer considered
cryptographically secure.  But a trial and error method will take way
too long and this particular trial and error method will also take way
too much disk space.  Still, I'm surprised the creators of the whitelist
didn't use sha1 or sha256.

Two practical methods:  1) run it on your own machine, not under their
control   2) convince them to add your particular dll to their whitelist.

-- 

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How can I convert a variable name to a string?

2012-09-21 Thread Hugo Arts
On Fri, Sep 21, 2012 at 11:11 AM, Dae James  wrote:

> **
> How can I convert a variable name to a string ?
> For example:
> testVariable = 1000;
> How can I get the string "testVariable" ?
> Thank you~
>
>
Well, the locals() dictionary will have a "testVariable" entry in it.. but
if I may ask, why would you want to do this? I see no reason this would
ever be necessary.

Hugo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] application whitelisting

2012-09-21 Thread Albert-Jan Roskam
Hi,

My company just started application whitelisting. Now a new version of a 
(benign!!) dll does not work as it (or rather, its file hash, if I understood 
it correctly) is not whitelisted. Is there any way I can use the same dll of a 
newer version? I know this sounds like a hacking request, but my intentions are 
sincere. My only purpose is to use ctypes to use the functions that are present 
in the new, but not the old, dll version.


The code below is probably simplistic/naive, but it's a product of my 
frustration + curiosity. The strategy was to generate a dll that has the same 
file hash as the original dll by right-padding it with zero until the desired 
checksum is found. Why a zero? No idea. ;-)

PS: I guess virtual environment also cannot be used for this, right?


import hashlib
import contextlib

def generateFile(infile, desired_hash, hashtype="md5"):
    outfile = infile[:-4] + "_adjusted.dll"
    hashlib_ = hashlib.new(hashtype)
    with contextlib.nested(open(infile, "rb"), open(outfile, "wb")) as (f_in, 
f_out):
    observed_hash = hashlib_(f_in.read())
    found = observed_hash.hexdigest() == desired_hash
    counter = 0
    while True:
    counter += 1
    observed_hash.update("0")
    if found:
    f_out.write(f_in.read() + (counter * "0"))
    print "Got it: '%s'" f_out.name
    break

infile = r"D:\temp\myown.dll"
generateFile(infile, '4151e067c17a753fc5c4ec1c507d28c9')
 
Regards,
Albert-Jan


~~
All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~ ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How can I convert a variable name to a string?

2012-09-21 Thread Dae James
How can I convert a variable name to a string ? 
For example:
testVariable = 1000;
How can I get the string "testVariable" ?
Thank you~




Dae James___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor