Re: help on "from deen import *" vs. "import deen"

2016-11-17 Thread Steven D'Aprano
On Thursday 17 November 2016 17:48, [email protected] wrote:

> Steven D'Aprano at 2016/11/17 12:06:19PM wrote:
>> You understand how this works?
> 
> Yes, thank you for your detail explanation.
> 
>> import russia as _tmp
>> president = _tmp.president
>> del _tmp
> 
> This one I can understand. But the previous one
> 
>>>_tmp = int('5')
>>>for name in dir(_tmp):
>>>if not name.startswith('_'):
>>>locals()[name] = getattr(_tmp, name)
>>>del _tmp
> 
> which I am still on scratching my head.


dir(obj) returns a list of all the attributes of obj:

py> dir(5)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', 
'__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', 
'__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', 
'__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', 
'__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', 
'__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', 
'__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', 
'__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', 
'__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', 
'__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 
'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']


Most of those are __ dunder __ methods reserved by Python. Don't touch them.

So if you look at each name in turn, pick out the ones that DON'T begin with an 
underscore:

['bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']


Then use getattr(obj, name) to return the value of that attribute, which may be 
a method:

py> getattr(5, 'bit_length')



and then save it in the local namespace:

py> x = -1
py> locals()['x'] = 999
py> x
999


(But watch out: assignment using locals() doesn't always work, for technical 
reasons it may not work inside a function.)


> Now the question moves from "how" to "why":
> 
> Why "del _tmp" at the last step? 

Technically, there is no "del _tmp" because there is no _tmp created first. The 
import command doesn't create the _tmp variable in the first place, so there's 
no need to delete it.

But there's no easy way to do that from pure Python code, so the easiest way is 
to use a temporary variable and then delete it afterwards.


> The only reason I can thought of is
> "information hiding", but from whom? A global variable has its reason to be
> as a global. It may need to be modified later to influence others behavior.
> Using delete to hide the name seems unnecessary and redundant. 

This has very little to do with global variables. This is about importing 
names. If you want to import the module as a whole, then use

import module

but if you want to import attributes of the module, then use:

from module import foo, bar, baz

If you want both, do both.



The most important thing you should learn from this thread is:

- avoid using "from module import *" as it is usually more trouble 
  than it is worth.


It is confusing and leads to more problems than it solves. If Python was being 
invented now, rather than 20 years ago, I would expect that there would be no 
"import *" in the language.




-- 
Steven
299792.458 km/s — not just a good idea, it’s the law!

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


Re: What exactly is a python variable?

2016-11-17 Thread Steven D'Aprano
On Thursday 17 November 2016 16:40, Veek M wrote:

> In C:
> int x = 10;
> results in storage being allocated and type and location are fixed for
> the life of the program.
> 
> In Python,
> x = 10
> 
> causes an object '10' to be created but how exactly is 'x' handled?
> Symbol Table lookup at compile time? 

No. Symbol table lookup at run time.

For functions, you can access a copy of the symbol table with:

locals()

You can access the actual global symbol table (not a copy) with:

globals()


Every module has its own independent global symbol table.



-- 
Steven
299792.458 km/s — not just a good idea, it’s the law!

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


mush 2.4.0 released! - Type-based dependency injection for scripts

2016-11-17 Thread Chris Withers

Hi All,

I'm very happy to announce the a new release of Mush, a light weight 
dependency injection framework aimed at enabling the easy testing and 
re-use of chunks of code that make up scripts.


This release includes:

- Add support for cloning depending on what label was used to add
  callables.

- Add Runner.add_label() helper to just add a label at the end of the
  runner.

- Document and flesh out Plugs.

- Switch to full Semantic Versioning.

For a worked example of how to use Mush to reduce the copy'n'paste in 
your scripts, please see here:


http://mush.readthedocs.io/en/latest/examples.html

Full docs are here:

http://mush.readthedocs.io/en/latest/index.html

Downloads are here:

https://pypi.python.org/pypi/mush

Compatible with Python 2.7, 3.3+ on Linux, Mac OS X and Windows.

Any problems, please give me a shout on the [email protected] 
list!


cheers,

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


Re: What exactly is a python variable?

2016-11-17 Thread BartC

On 17/11/2016 05:40, Veek M wrote:

In C:
int x = 10;
results in storage being allocated and type and location are fixed for
the life of the program.

In Python,
x = 10

causes an object '10' to be created but how exactly is 'x' handled?
Symbol Table lookup at compile time? Is every 'x' being substituted out
of existence? Because type(x) gives 'int' so..


Try:

 import dis

 def fn():
 |   global x
 |   x=10

 dis.dis(fn)

(I don't know how to disassemble code outside a function, not from 
inside the same program. Outside it might be: 'python -m dis file.py')


This might show stuff like:

  0 LOAD_CONST   1 (10)
  3 STORE_GLOBAL 0 (x)

So already giving a better idea of what might be going on compared with 
'x=10' which is practically the same in any language.


(I'm guessing "x" is looked up at this point, created if it doesn't 
exist, and associated with the value 'integer 10'.)


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


Error in webscraping problem

2016-11-17 Thread stanleydasilva93
I am trying to solve the following problem.  Two numbers appear on a website. 
The user has to enter the gcd (greatest common divisor) and hit the 
submit button.  The catch is that the time limit is far too slow for
any human processes -- it must be fully automated. The numbers change
each time the user attempts the problem.

Unfortunately, I can't release the name of the website because of 
corporate confidentiality but I'm hoping someone may have some clues
as to what I'm doing wrong.  The code is below.  FinalResults.html
gives me a "Wrong Answer" message.

As a check, I kept a record of the results for one pair of numbers.
I called the webpage corresponding to a fixed pair "testRequest.txt"
The code:  

 myfile = open("testRequest.txt" , "r")
 page = myfile.read()

is used to check that the first number, second number, and solution, are
all as they should be.

I would be very grateful for any help or advice on the next steps.
Part of the problem is in debugging.

Thanks,
Stanley.


import sys
sys.path.append('C:/Users/silviadaniel/Anaconda3/Lib/site-packages')
import mechanize
import requests
import fractions
url = "http://someWebsite.com/test";
br = mechanize.Browser()
br.open(url)
br.select_form(nr = 0) 
# There is only one form involved so  this is probably ok

print br.form
# reads http://website.com/submit application/x-www-form-urlencoded
# 
# =) (readonly)>>

data = requests.get(url)
page = data.text
begTag = ""
endTag = ""
firstIndex = page.find(begTag)
secondIndex = page.find(endTag)
shift = len(begTag)
posNumber = firstIndex + shift
firstNumber = int(page[posNumber:secondIndex])
firstIndex = page.find(begTag, firstIndex + 1)
secondIndex = page.find(endTag, secondIndex + 1)
posNumber = firstIndex + shift
secondNumber = int(page[posNumber:secondIndex])
solution = str(fractions.gcd(firstNumber, secondNumber))
br["divisor"] = solution
print firstNumber # Looks sensible -- first number probably correct
print secondNumber # Looks sensible -- also checked
print solution # Is indeed the correct gcd
res = br.submit()

content = res.read()
with open("FinalResults.html", "w") as f:
f.write(content)
# Unfortunately, I examine this file to find "Wrong Answer"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What exactly is a python variable?

2016-11-17 Thread Steve D'Aprano
On Thu, 17 Nov 2016 10:37 pm, BartC wrote:

> Try:
> 
>   import dis
> 
>   def fn():
>   |   global x
>   |   x=10
> 
>   dis.dis(fn)
> 
> (I don't know how to disassemble code outside a function, not from
> inside the same program. Outside it might be: 'python -m dis file.py')


You can use the byte-code compiler to compile the code first:


For an expression, you can use:

code = compile("x + 1", "", "eval")


The middle argument, shown here as an empty string "", is used for an
optional string identifying the source of the code. E.g. a file name.

The third argument, here shown as "eval", determines the compilation mode.
The eval() function can only evaluate a single expression, so the name of
the mode is the same.

For a single statement, as seen by the interactive interpreter, use:

code = compile("result = x + 1", "", "single")


For multiple statements (as in a module), or a single statement *not* in the
interactive interpreter, use:

code = compile("result = x + 1", "", "exec")

code = compile("""
x = 999
result = x + 1
print(result)
""", "", "exec")

Then once you have your code object, you can disassemble it:

dis.dis(code)

or exec/eval it:

exec(code)
eval(code)  # only if the compilation mode was "eval"


In the most recent versions of Python, dis.dis() will also accept a string:

py> dis.dis('y = x + 1')
  1   0 LOAD_NAME0 (x)
  3 LOAD_CONST   0 (1)
  6 BINARY_ADD
  7 STORE_NAME   1 (y)
 10 LOAD_CONST   1 (None)
 13 RETURN_VALUE





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

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


How to test for type or instance of dict_values?

2016-11-17 Thread Thorsten Kampe
How can I test for type or instance of dictviews like dict_values?

`isinstance({}.values, dict_values)` gives
`NameError: name 'dict_values' is not defined`

"""
>>> type({}.values())

"""

Thorsten


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


Re: How to test for type or instance of dict_values?

2016-11-17 Thread Peter Otten
Thorsten Kampe wrote:

> How can I test for type or instance of dictviews like dict_values?

Why do you want to?
 
> `isinstance({}.values, dict_values)` gives
> `NameError: name 'dict_values' is not defined`

You can "fix" this with

>>> dict_values = type({}.values())

or, depending on the use case, use another test:

>>> isinstance({}.values(), collections.abc.ValuesView)
True

> """
 type({}.values())
> 
> """
> 
> Thorsten


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


Re: What exactly is a python variable?

2016-11-17 Thread BartC

On 17/11/2016 12:20, Steve D'Aprano wrote:

On Thu, 17 Nov 2016 10:37 pm, BartC wrote:



(I don't know how to disassemble code outside a function, not from
inside the same program. Outside it might be: 'python -m dis file.py')



In the most recent versions of Python, dis.dis() will also accept a string:

py> dis.dis('y = x + 1')
  1   0 LOAD_NAME0 (x)
  3 LOAD_CONST   0 (1)
  6 BINARY_ADD
  7 STORE_NAME   1 (y)
 10 LOAD_CONST   1 (None)
 13 RETURN_VALUE



Py2 gave me (for "y=x+1"):

  0 SETUP_EXCEPT30781 (to 30784)
  3 STORE_SLICE+3
  4 <49>

Py3.4 works as you say but after that result I was disinclined to take 
it further!


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


Re: Access to the caller's globals, not your own

2016-11-17 Thread MRAB

On 2016-11-17 05:40, Dan Sommers wrote:

On Thu, 17 Nov 2016 16:17:51 +1100, Steven D'Aprano wrote:


... factory functions are great. But I'm saying that as the writer of
the library, not the user of the library. Can you imagine expecting
users to do this?



from math import trig
sin = trig.build('sine')
result = sin(0.1)


No, but I could expect users to do this:

import math # trig functions take radians by default
math = math.degree_math # but I like degrees

Or to choose from one of these:

import math # trig functions take radians by default
import math.degree_math as math # but I like degrees

Or to choose from one of these:

import math.radian_math as math # use the radians version
import math.degree_math as math # use the degrees version

The complexity is taken on once, by the library author, who (presumably)
understands the complexity better than the users do.


[snip]
I wonder if it would be possible to make modules callable. You would do 
this by adding a __call__ function, and this function could be a factory 
function:


import math
degree_math = math('degree')

This would be equivalent to:

import math
degree_math = math.__call__('degree')

Also, a possible syntax extension:

import math('degree') as degree_math

This would be equivalent to:

import math as __temp__
degree_math = __temp__.__call__('degree')
del __temp__

If you wrote:

import math('degree')

this would be equivalent to:

import math as __temp__
math = __temp__.__call__('degree')
del __temp__

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


Overlapping co-ordiantes of rectangles fail to print in python

2016-11-17 Thread arunsocs
 I am working with following code in which I am trying to output co ordinates 
of overlapping rectangles.. However the code fails to output the co ordinates. 
I am customizing the following code This is the input

1.6 1.2 7.9 3.1
1.2 1.6 3.4 7.2
2.6 11.6 6.8 14.0
9.6 1.2 11.4 7.5
9.6 1.7 14.1 2.8 

This is the code:

from __future__ import division
from collections import namedtuple
from itertools import combinations

Point = namedtuple( 'Point', ['x','y'] )

class Rectangle:
def __init__( self, coordinates ):
self.min = Point( coordinates[0], coordinates[1] )
self.max = Point( coordinates[2], coordinates[3] )

@property
def center( self ):
return Point( (self.max.x + self.min.x)/2, (self.max.y + self.min.y)/2 )

@property
def area( self ):
return (self.max.x - self.min.x) * (self.max.y - self.min.y)

def intersect( self, otherRect ):
x_vals = sorted([self.max.x, self.min.x, otherRect.max.x, 
otherRect.min.x])
y_vals = sorted([self.max.y, self.min.y, otherRect.max.y, 
otherRect.min.y])

possibleIntersections = []
intersections = []

for i in range(3):
for j in range(3):
possibleIntersections.append( Rectangle([x_vals[i], y_vals[j], 
x_vals[i+1], y_vals[j+1]]) )

for r in possibleIntersections:
if self.contains( r.center ) and otherRect.contains( r.center ) and 
r.area > 0:
intersections.append( r )

return intersections

def contains( self, point ):
return self.min.x <= point.x and point.x <= self.max.x and self.min.y 
<= point.y and point.y <= self.max.y

def __repr__( self ):
return '[{0},{1}]'.format( self.min, self.max )

def readInputconvert( filename ):
rects = []
with open(filename,'r') as f:
count = int(f.readline().rstrip());

for _ in range( count ):
rects.append( Rectangle( map( float, f.readline().rstrip().split(' 
') ) ) )

return rects

rectangles = readInputconvert( 'input.txt' ) # read input

sign = -1
area = sum( map( lambda x: x.area, rectangles) )

for i in range(2,len(rectangles)+1):
for rects in combinations( rectangles, i ):
intersections = [rects[0]]
rects = rects[1:]
for rectangle in rects:
newintersections = []
for otherR in intersections:
newintersections.extend( rectangle.intersect(otherR) )

intersections = newintersections
print intersections

#intersectingArea = sum( map( lambda x: x.area, intersections ) )
#rea = area + (sign * intersectingArea)

sign = sign*-1

Where I need to change the code to output all overlapping rectangles and its co 
ordinates?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Error in webscraping problem

2016-11-17 Thread Chris Angelico
On Thu, Nov 17, 2016 at 10:55 python-ideas
PM,   wrote:
> I am trying to solve the following problem.  Two numbers appear on a website. 
> The user has to enter the gcd (greatest common divisor) and hit the
> submit button.  The catch is that the time limit is far too slow for
> any human processes -- it must be fully automated. The numbers change
> each time the user attempts the problem.
>
> Unfortunately, I can't release the name of the website because of
> corporate confidentiality but I'm hoping someone may have some clues
> as to what I'm doing wrong.  The code is below.  FinalResults.html
> gives me a "Wrong Answer" message.

It's a programming challenge. Have fun with it! :)

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


Re: How to test for type or instance of dict_values?

2016-11-17 Thread Thorsten Kampe
* Peter Otten (Thu, 17 Nov 2016 13:38:26 +0100)
> 
> Thorsten Kampe wrote:
> 
> > How can I test for type or instance of dictviews like dict_values?
> 
> Why do you want to?

Thanks, for the `collections.abc.ValuesView` tip.

The code in question is part of an attempt to get the dimensions of 
multi-dimensional lists, the `isinstance` is there in order to 
exclude strings.

"""
def dim(seq):
dimension = []
while isinstance(seq, (list, tuple)):
dimension.append(len(seq))
try:
seq = seq[0]
except IndexError:  # sequence is empty
break
return dimension
"""

Thorsten

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


Re: help on "from deen import *" vs. "import deen"

2016-11-17 Thread Michael Torrie
On 11/16/2016 07:01 PM, [email protected] wrote:
> Michael Torrie at 2016/11/16 11:15:11AM wrote:
>> ... The globals object is a dictionary and is itself mutable.  But
>> when we assign a new object to a particular dictionary key, it
>> tosses out the old reference and makes the key now refer to the new
>> object.  It does not do anything to the old object itself.
> 
> The last question: Is it possible, in the current Python version, to
> re-bind a global name in module "deen" after it was imported "from
> deen import *"?

Sigh. If you understood what everyone has been explaining, you'd know
that the answer to that is no.  That's not the way variables in Python
work.  The only way to rebind deen.foo is to do as Chris suggested in
his reply and always refer to it with "deen.foo".

Once a variable is imported from a library it becomes a local variable
in your module (well a local global variable, since variables can only
be global to the module itself).  It starts out life referring to the
same object as the global attribute inside of deen. But once you assign
to the local name, it is rebound to a new object.  Do you understand that?


> I mean it might be better to have two labels to label chair and couch
> separately, instead of one:-)

Like I said, whether the names you use are appropriate is completely up
to you.  But this statement seems to imply you're still not getting it
and still thinking of variables as boxes like they are in other
languages, rather than labels that can only point to one thing at a
time.  Python's variables are different from other languages, but in an
understandable way.  Sit back and think about it, play with the python
command prompt. Run id() on a variable, assign something else to it, and
run id() on it again.  As Dennis said, understanding Python variables,
though not difficult, needs to be second nature to you or you'll be
fighting Python and hating the experience.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What exactly is a python variable?

2016-11-17 Thread Anton Mamaenko
Just a couple of days ago I was asking myself a similar question, and found 
this blog article: 
https://jeffknupp.com/blog/2013/02/14/drastically-improve-your-python-understanding-pythons-execution-model/

Clarified a lot of things to me. 

, Anton

> On 17 Nov 2016, at 16:19, BartC  wrote:
> 
>> On 17/11/2016 12:20, Steve D'Aprano wrote:
>> On Thu, 17 Nov 2016 10:37 pm, BartC wrote:
> 
>>> (I don't know how to disassemble code outside a function, not from
>>> inside the same program. Outside it might be: 'python -m dis file.py')
> 
>> In the most recent versions of Python, dis.dis() will also accept a string:
>> 
>> py> dis.dis('y = x + 1')
>>  1   0 LOAD_NAME0 (x)
>>  3 LOAD_CONST   0 (1)
>>  6 BINARY_ADD
>>  7 STORE_NAME   1 (y)
>> 10 LOAD_CONST   1 (None)
>> 13 RETURN_VALUE
> 
> 
> Py2 gave me (for "y=x+1"):
> 
>  0 SETUP_EXCEPT30781 (to 30784)
>  3 STORE_SLICE+3
>  4 <49>
> 
> Py3.4 works as you say but after that result I was disinclined to take it 
> further!
> 
> -- 
> Bartc
> -- 
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to test for type or instance of dict_values?

2016-11-17 Thread Terry Reedy

On 11/17/2016 9:57 AM, Thorsten Kampe wrote:


The code in question is part of an attempt to get the dimensions of
multi-dimensional lists, the `isinstance` is there in order to
exclude strings.


You can do the exclusion directly.



"""
def dim(seq):
dimension = []
while isinstance(seq, (list, tuple)):


while not isinstance(seq, str) # or (str, bytes, ...)


dimension.append(len(seq))
try:
seq = seq[0]
except IndexError:  # sequence is empty
break
return dimension
"""

Thorsten




--
Terry Jan Reedy

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


Re: What exactly is a python variable?

2016-11-17 Thread Terry Reedy

On 11/17/2016 12:40 AM, Veek M wrote:

In C:
int x = 10;
results in storage being allocated and type and location are fixed for
the life of the program.

In Python,
x = 10

causes an object '10' to be created but how exactly is 'x' handled?
Symbol Table lookup at compile time?


Modules and class names are set into and gotten from a symbol table at 
*runtime* (except that module globals start with some initial reserved 
names).  Globals() returns the modules symbol table, which is a dict. 
To see the initialization, execute "print(globals())" on startup.  For 
CPython 3.6.0b3 executed via IDLE's shell:


>>> globals()
{'__name__': '__main__',
 '__doc__': None,
 '__package__': None,
 '__loader__': ,
 '__spec__': None,
 '__annotations__': {},
 '__builtins__': }

Class dicts are created at runtime and also have default entries.

>>> class C: pass

>>> print(C.__dict__)
{'__module__': '__main__', '__dict__': objects>, '__weakref__': , 
'__doc__': None}


>>> print(dir(C))  # include attributes inherited from object.
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', 
'__init__', '__init_subclass__', '__le__', '__lt__', '__module__', 
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']



Is every 'x' being substituted out of existence?


In CPython, function local names are replaced by int indexes into a list 
of objects, but still 'exist'.  They are kept with the code object as a 
list.  It is used for printing locals() and for disassembly output.  The 
latter is deceptive in this regard if you do not know that the names are 
substituted back for the indexes).


The local namespace, an attribute code does not have any default entries.

>>> def f(): print(locals())

>>> f()
{}

The code object itself and the function object that wraps a code object 
both have numerous special-name attributes.


--
Terry Jan Reedy

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


Re: Access to the caller's globals, not your own

2016-11-17 Thread Rob Gaddi
Steven D'Aprano wrote:

> On Thursday 17 November 2016 04:52, Rob Gaddi wrote:
>
>>> import library
>>> result = library.make_spam(arg)
>>>
>>>
>>> versus:
>>>
>>> import library
>>> make_spam = library.make_library()
>>> result = make_spam(arg)
>>>
>>> What a drag.
>>>
>>>
>> 
>> And there you have it; an entire extra line at import time.
>
> Multiplied by every function that has a configurable default. Multiplied by 
> every module that imports any of those functions, *whether or not* they 
> change 
> the default. If there are four functions, the user has to do this:
>
> import library
> make_spam = library.make_spam_factory()
> make_eggs = library.make_eggs_factory()
> make_cheese = library.make_cheese_factory()
> make_toast = library.make_toast_factory()
>
>
> before they can even begin to do what they actually want to do, which is make 
> spam, eggs, cheese etc. And yes, there's likely to be four or more of these 
> functions.
>

No, no no no.  You misunderstood the approach that I think most of us
were on, which is

  import library
  Library = library.Library()
  Library.SPAMPARAM = 'jam'

  i_want_spam_now = Library.make_spam(99)

One extra line for the import, plus one for each default setting they
want to override (which you're stuck with either way).  I suppose you
could even pass all those overrides in to the Library __init__, but now
we're in the weeds.

And again, for the ones that don't want to mess with the default params,
you can have:

  import library.defaultinstance as Library


-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Overlapping co-ordiantes of rectangles fail to print in python

2016-11-17 Thread Peter Pearson
On Thu, 17 Nov 2016 06:27:49 -0800 (PST), [email protected] wrote:
>  I am working with following code in which I am trying to output co
>  ordinates of overlapping rectangles.. However the code fails to
>  output the co ordinates. I am customizing the following code

[about 100 lines of code removed]

> Where I need to change the code to output all overlapping rectangles
> and its co ordinates?

First, insert a print statement to determine whether the problem is
  (a) no overlapping rectangles are being found, or
  (b) the overlapping rectangles that are found are not being printed.

If (a), proceed to investigate whether
  (a1) there are, in fact, no overlapping rectangles, or
  (a2) your code is failing to recognize overlapping rectangles.

And so forth . . .

-- 
To email me, substitute nowhere->runbox, invalid->com.
-- 
https://mail.python.org/mailman/listinfo/python-list


Can signal.alarm be safely cleared in python?

2016-11-17 Thread Pedro Franco de Carvalho
Assume a python program sets a handler function for the
`signal.SIGALRM` signal, and then schedules an alarm in T seconds with
`signal.alarm(T)`.

Assume the program later cancels any scheduled alarm with `signal.alarm(0)`.

Can the program safely assume that after the call to `signal.alarm(0)`
completes no alarm handling function will be called?

The reason I ask is that the signal module documentation [1] says that:

"A Python signal handler does not get executed inside the low-level
(C) signal handler. Instead, the low-level signal handler sets a flag
which tells the virtual machine to execute the corresponding Python
signal handler at a later point(for example at the next bytecode
instruction)."

Since this "later point" is not specified, could it be that a the
alarm is triggered and calls the low-level C handler shortly before
the call to `signal.alarm(0)`, but the python signal handler is only
executed at some point after this call?

[1]: 
https://docs.python.org/3.6/library/signal.html#execution-of-python-signal-handlers)
-- 
https://mail.python.org/mailman/listinfo/python-list


Python does not start

2016-11-17 Thread Jelena Tavcar
How do I find stdlib files?
Regards
-- 
https://mail.python.org/mailman/listinfo/python-list


modify screen pop up

2016-11-17 Thread John Zayatz via Python-list
when running pycharm the modify
setup window keep coming on the screen. I have uninstalled and
reinstalled python and pycharm multiple times. Do you have a solution?
Thank You"
-- 
https://mail.python.org/mailman/listinfo/python-list


python package: financial_life

2016-11-17 Thread martin . pyka
Hi everybody,

I recently uploaded a project I am working on for some months. It is called 
financial_life and the purpose of it is to simulate monetary flows between 
different accounts (like normal bank accounts, loans etc.). The simulations let 
you explore different financial strategies and figure out their long term 
impact on your asset. 

While you would need a lot of auxiliary tables in excel to achieve the same 
thing, in financial_life almost every line of code contributes only to the 
description of the problem. Thereby, with comparatively few amount of code 
lines, pretty complex simulations can be defined.

https://github.com/MartinPyka/financial_life

I hope, this package is helpful for some of you.

Best,
Martin
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Overlapping co-ordiantes of rectangles fail to print in python

2016-11-17 Thread BartC

On 17/11/2016 14:27, [email protected] wrote:

 I am working with following code in which I am trying to output co ordinates 
of overlapping rectangles.. However the code fails to output the co ordinates. 
I am customizing the following code This is the input

1.6 1.2 7.9 3.1
1.2 1.6 3.4 7.2
2.6 11.6 6.8 14.0
9.6 1.2 11.4 7.5
9.6 1.7 14.1 2.8


(Is there a line count at the start of the file?)


sign = -1
area = sum( map( lambda x: x.area, rectangles) )

for i in range(2,len(rectangles)+1):
for rects in combinations( rectangles, i ):
intersections = [rects[0]]
rects = rects[1:]
for rectangle in rects:
newintersections = []
for otherR in intersections:
newintersections.extend( rectangle.intersect(otherR) )

intersections = newintersections
print intersections

#intersectingArea = sum( map( lambda x: x.area, intersections ) )
#rea = area + (sign * intersectingArea)

sign = sign*-1

Where I need to change the code to output all overlapping rectangles and its co 
ordinates?


I tried your code and got a bunch of output, mostly [] lines like this:

[]
[]
[]
[]
[]
[[Point(x=1.6, y=1.6),Point(x=3.4, y=3.1)]]
[]
[]
[[Point(x=1.6, y=1.6),Point(x=3.4, y=3.1)]]
[]

What output did you expect for this input data?

(I plotted your data and out of five rectangles A,B,C,D,E (not in the 
same order as your data), then A and B overlap, as do C and D, while E 
is by itself.


Did you want the output to be, for example, A and B, with the 
coordinates of the common region, and the same for C and D?


What happens if 3 or more rectangles overlap?

What about if A overlaps B; B overlaps C; C overlaps D; and D overlaps 
A? Suppose then that all those are contained within E?


You need some specifications. I assume all rectangles are horizontally 
aligned (they have to be with just 4 coordinates), and the input data 
normalised so that the top-left corner appears first.)


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


Re: Python does not start

2016-11-17 Thread Joel Goldstick
On Thu, Nov 17, 2016 at 2:59 PM, Jelena Tavcar  wrote:
> How do I find stdlib files?
> Regards
> --
> https://mail.python.org/mailman/listinfo/python-list

First of all, your subject line doesn't seem related to your body
text.  Second of all, stdlib is a C thing as I recall, not python.
Can you be a bit more forthcoming about your issue?

-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
-- 
https://mail.python.org/mailman/listinfo/python-list


how to control formatting of a namedtuple in a list

2016-11-17 Thread Boylan, Ross
Even after defining custom __str__ and __format__ methods they don't affect the 
display of objects when they are in a list.  Is there a way to change that, 
other than explicitly converting each list element to a string?

The last line of output below shows that when I format the list I get standard 
formatting of my objects instead of my custom format.

Code
#! /usr/bin/python3
from collections import namedtuple

class Foo(namedtuple("Foo", "x")):
__slots__ = ()

def __str__(self):
  return "foolish({})".format(self.x)

def __format__(self, spec):
  return self.__str__()

f=Foo(4)
print(f)
print(str(f))
print("{}".format(f))
print("{}".format([f]))  # a list with one f

Output
foolish(4)
foolish(4)
foolish(4)
[Foo(x=4)]

I'm running Python 3.4.

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


Re: how to control formatting of a namedtuple in a list

2016-11-17 Thread Chris Angelico
On Fri, Nov 18, 2016 at 10:04 AM, Boylan, Ross  wrote:
> Even after defining custom __str__ and __format__ methods they don't affect 
> the display of objects when they are in a list.  Is there a way to change 
> that, other than explicitly converting each list element to a string?
>

Yep! Inside a list, it's the repr that gets shown. So you should be
able to do this:

class Foo(namedtuple("Foo", "x")):
def __repr__(self):
  return "foolish({})".format(self.x)

This will also affect the other forms - if you don't define __str__,
it'll use __repr__. So this should be all you need.

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


RE: how to control formatting of a namedtuple in a list

2016-11-17 Thread Boylan, Ross
Thank you; I can confirm that overriding __repr__ makes the list display as I 
wanted.

The decision to use repr inside the list seems very odd, given the context, 
namely formatting something for display or looking for a simple string 
representation.  It seems more natural to me to use str or, if in a format, the 
default formatting all the way down.  Is there a good reason it's repr?

Ross

From: Python-list [[email protected]] on 
behalf of Chris Angelico [[email protected]]
Sent: Thursday, November 17, 2016 3:24 PM
To: [email protected]
Subject: Re: how to control formatting of a namedtuple in a list

On Fri, Nov 18, 2016 at 10:04 AM, Boylan, Ross  wrote:
> Even after defining custom __str__ and __format__ methods they don't affect 
> the display of objects when they are in a list.  Is there a way to change 
> that, other than explicitly converting each list element to a string?
>

Yep! Inside a list, it's the repr that gets shown. So you should be
able to do this:

class Foo(namedtuple("Foo", "x")):
def __repr__(self):
  return "foolish({})".format(self.x)

This will also affect the other forms - if you don't define __str__,
it'll use __repr__. So this should be all you need.

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


Re: how to control formatting of a namedtuple in a list

2016-11-17 Thread MRAB

On 2016-11-17 23:49, Boylan, Ross wrote:

Thank you; I can confirm that overriding __repr__ makes the list display as I 
wanted.

The decision to use repr inside the list seems very odd, given the context, 
namely formatting something for display or looking for a simple string 
representation.  It seems more natural to me to use str or, if in a format, the 
default formatting all the way down.  Is there a good reason it's repr?


> Ross

Given a string, say:

>>> s = 'foo'

str shows:

>>> print(str(s))

whereas repr shows:

>>> print(repr(s))
'foo'

If it was in a list, would you want it to show:

[foo]

or:

['foo']

?



From: Python-list [[email protected]] on 
behalf of Chris Angelico [[email protected]]
Sent: Thursday, November 17, 2016 3:24 PM
To: [email protected]
Subject: Re: how to control formatting of a namedtuple in a list

On Fri, Nov 18, 2016 at 10:04 AM, Boylan, Ross  wrote:

Even after defining custom __str__ and __format__ methods they don't affect the 
display of objects when they are in a list.  Is there a way to change that, 
other than explicitly converting each list element to a string?



Yep! Inside a list, it's the repr that gets shown. So you should be
able to do this:

class Foo(namedtuple("Foo", "x")):
def __repr__(self):
  return "foolish({})".format(self.x)

This will also affect the other forms - if you don't define __str__,
it'll use __repr__. So this should be all you need.

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



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


Re: how to control formatting of a namedtuple in a list

2016-11-17 Thread Ned Batchelder
On Thursday, November 17, 2016 at 6:50:07 PM UTC-5, Boylan, Ross wrote:
> Thank you; I can confirm that overriding __repr__ makes the list display as I 
> wanted.
> 
> The decision to use repr inside the list seems very odd, given the context, 
> namely formatting something for display or looking for a simple string 
> representation.  It seems more natural to me to use str or, if in a format, 
> the default formatting all the way down.  Is there a good reason it's repr?


I think of it as str is for customers, repr is for developers. Or, repr is
for nerds, str is for civilians, etc.  If you print a list, then you will
get square brackets and commas separating the display.  That is, you are
already getting a nerdy output. So the contents of the list are also
displayed in the nerdy way, with repr.

If you want a nice display of the contents, you also have to control the
display of the list itself, so you can do whatever you need, and use str
on the contents yourself.

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


Re: how to control formatting of a namedtuple in a list

2016-11-17 Thread Ethan Furman

On 11/17/2016 04:09 PM, MRAB wrote:

On 2016-11-17 23:49, Boylan, Ross wrote:



Thank you; I can confirm that overriding __repr__ makes the list display as I 
wanted.

The decision to use repr inside the list seems very odd, given the context, 
namely formatting something for display or looking for a simple string 
representation.  It seems more natural to me to use str or, if in a format, the 
default formatting all the way down.  Is there a good reason it's repr?


Given a string, say:

>>> s = 'foo'

str shows:

>>> print(str(s))

whereas repr shows:

>>> print(repr(s))
'foo'

If it was in a list, would you want it to show:

[foo]

or:

['foo']

?


Another example:

 >>> foo = 'ham, eggs, cheese'
 >>> bar = 'bacon, toast'

if list used str instead of repr:

 >>> print(list(foo, bar))
 [ham, eegs, cheese, bacon, toast]

How many items are in that list?  (Hint: it isn't 5. ;)

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


Re: Python does not start

2016-11-17 Thread Terry Reedy

On 11/17/2016 2:59 PM, Jelena Tavcar wrote:

How do I find stdlib files?


Python coded stdlib files are, at least on Windows, in /Lib

--
Terry Jan Reedy

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


Re: What exactly is a python variable?

2016-11-17 Thread Steve D'Aprano
On Fri, 18 Nov 2016 12:19 am, BartC wrote:

> On 17/11/2016 12:20, Steve D'Aprano wrote:
>> On Thu, 17 Nov 2016 10:37 pm, BartC wrote:
> 
>>> (I don't know how to disassemble code outside a function, not from
>>> inside the same program. Outside it might be: 'python -m dis file.py')
> 
>> In the most recent versions of Python, dis.dis() will also accept a
>> string:
>>
>> py> dis.dis('y = x + 1')
>>   1   0 LOAD_NAME0 (x)
>>   3 LOAD_CONST   0 (1)
>>   6 BINARY_ADD
>>   7 STORE_NAME   1 (y)
>>  10 LOAD_CONST   1 (None)
>>  13 RETURN_VALUE
> 
> 
> Py2 gave me (for "y=x+1"):
> 
>0 SETUP_EXCEPT30781 (to 30784)
>3 STORE_SLICE+3
>4 <49>
> 
> Py3.4 works as you say but after that result I was disinclined to take
> it further!


You may have missed the bit where I said "In the most recent versions".
Python 2.7 will be interpreting the string "y=x+1" as compiled byte-code,
and disassembling it into junk.

If in doubt, just use the compile() function first.



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

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


Re: What exactly is a python variable?

2016-11-17 Thread Chris Angelico
On Fri, Nov 18, 2016 at 11:47 AM, Steve D'Aprano
 wrote:
> You may have missed the bit where I said "In the most recent versions".
> Python 2.7 will be interpreting the string "y=x+1" as compiled byte-code,
> and disassembling it into junk.
>

Heh. That's a side benefit of the Py3 bytes/unicode split - you can
instantly distinguish between program text and compiled bytes. :)

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


Re: What exactly is a python variable?

2016-11-17 Thread BartC

On 18/11/2016 00:47, Steve D'Aprano wrote:

On Fri, 18 Nov 2016 12:19 am, BartC wrote:


On 17/11/2016 12:20, Steve D'Aprano wrote:



In the most recent versions of Python, dis.dis() will also accept a
string:

py> dis.dis('y = x + 1')
  1   0 LOAD_NAME0 (x)
  3 LOAD_CONST   0 (1)
  6 BINARY_ADD
  7 STORE_NAME   1 (y)
 10 LOAD_CONST   1 (None)
 13 RETURN_VALUE



Py2 gave me (for "y=x+1"):

   0 SETUP_EXCEPT30781 (to 30784)
   3 STORE_SLICE+3
   4 <49>

Py3.4 works as you say but after that result I was disinclined to take
it further!



You may have missed the bit where I said "In the most recent versions".
Python 2.7 will be interpreting the string "y=x+1" as compiled byte-code,
and disassembling it into junk.


I did my tests ('dis.dis("x=10")') before your post and before my 
original post. Py2 generated nonsense so I tried something else.


That Py2's dis.dis() accepts a string argument but treats it as compiled 
byte-code sounds like a bug. Unless it's a feature.


--
Bartc

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


RE: how to control formatting of a namedtuple in a list

2016-11-17 Thread Boylan, Ross
Actually,
>> print(list(foo, bar))
Traceback (most recent call last):  

  File "", line 1, in

TypeError: list() takes at most 1 argument (2 given)   

Though 
>>> [foo, bar]
['ham, eggs, cheese', 'bacon, toast'] 
which admittedly would be confusing if the strings weren't quoted. But display, 
or formatted values, are not intended to allow reconstruction of the objects; 
that's what repr is for. 

The argument that the display of list is already low-level, and so everything 
inside the list should be displayed low-level, seems a bit of a stretch.

Overriding repr is serviceable for me, but it requires violating the intended 
semantics of repr, namely that the result could be converted back to the 
original object. I'm trying to get a display that has only some of the 
information in the object.  My understanding is that str is supposed to provide 
that.

At any rate, I agree there are reasons to use repr inside a list.

Ross

From: Python-list [[email protected]] on 
behalf of Ethan Furman [[email protected]]
Sent: Thursday, November 17, 2016 4:18 PM
To: [email protected]
Subject: Re: how to control formatting of a namedtuple in a list

On 11/17/2016 04:09 PM, MRAB wrote:
> On 2016-11-17 23:49, Boylan, Ross wrote:

>> Thank you; I can confirm that overriding __repr__ makes the list display as 
>> I wanted.
>>
>> The decision to use repr inside the list seems very odd, given the context, 
>> namely formatting something for display or looking for a simple string 
>> representation.  It seems more natural to me to use str or, if in a format, 
>> the default formatting all the way down.  Is there a good reason it's repr?
>
> Given a string, say:
>
> >>> s = 'foo'
>
> str shows:
>
> >>> print(str(s))
>
> whereas repr shows:
>
> >>> print(repr(s))
> 'foo'
>
> If it was in a list, would you want it to show:
>
> [foo]
>
> or:
>
> ['foo']
>
> ?

Another example:

  >>> foo = 'ham, eggs, cheese'
  >>> bar = 'bacon, toast'

if list used str instead of repr:

  >>> print(list(foo, bar))
  [ham, eegs, cheese, bacon, toast]

How many items are in that list?  (Hint: it isn't 5. ;)

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


Re: What exactly is a python variable?

2016-11-17 Thread Ned Batchelder
On Thursday, November 17, 2016 at 8:35:15 PM UTC-5, BartC wrote:
> That Py2's dis.dis() accepts a string argument but treats it as compiled 
> byte-code sounds like a bug. Unless it's a feature.

In Python 2, plain-old strings are byte-strings, so there's no way for
dis.dis to distinguish between a string literal full of code, and a
byte-string full of bytecode.

So it's not a bug, and it also is not a feature. It just is.

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


Re: help on "from deen import *" vs. "import deen"

2016-11-17 Thread jfong
Steven D'Aprano at 2016/11/17 4:04:04PM wrote:
> The most important thing you should learn from this thread is:
> 
> - avoid using "from module import *" as it is usually more trouble 
>   than it is worth.
> 
> 
> It is confusing and leads to more problems than it solves. If Python was 
> being 
> invented now, rather than 20 years ago, I would expect that there would be no 
> "import *" in the language.

It's the greatest advice I ever had in Python:-)

--Jach

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


Re: help on "from deen import *" vs. "import deen"

2016-11-17 Thread Nathan Ernst
I would also toss in there: never name a script test.py. Causes nothing but
trouble, at least in python2.

On Nov 17, 2016 8:01 PM,  wrote:

> Steven D'Aprano at 2016/11/17 4:04:04PM wrote:
> > The most important thing you should learn from this thread is:
> >
> > - avoid using "from module import *" as it is usually more trouble
> >   than it is worth.
> >
> >
> > It is confusing and leads to more problems than it solves. If Python was
> being
> > invented now, rather than 20 years ago, I would expect that there would
> be no
> > "import *" in the language.
>
> It's the greatest advice I ever had in Python:-)
>
> --Jach
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help on "from deen import *" vs. "import deen"

2016-11-17 Thread jfong
Michael Torrie at 2016/11/17 11:38:32PM wrote:
> Like I said, whether the names you use are appropriate is completely up
> to you.  But this statement seems to imply you're still not getting it
> and still thinking of variables as boxes like they are in other
> languages, rather than labels that can only point to one thing at a
> time.

As a knowledge, I do know the re-bind tricky Python had on its variable, and 
that's mostly I stumbled so far when writing Python codes.

> Python's variables are different from other languages, but in an
> understandable way.  

Unfortunately it's also different from human language.

> As Dennis said, understanding Python variables,
> though not difficult, needs to be second nature to you or you'll be
> fighting Python and hating the experience.

That's the point: to build a second nature.

But it won't be easy because of we use human language used everyday:-(

--Jach



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


Re: help on "from deen import *" vs. "import deen"

2016-11-17 Thread Michael Torrie
On 11/17/2016 07:23 PM, [email protected] wrote:
>> Python's variables are different from other languages, but in an
>> understandable way.  
> 
> Unfortunately it's also different from human language.

How so? I don't find this to be true at all.
-- 
https://mail.python.org/mailman/listinfo/python-list


key and ..

2016-11-17 Thread Val Krem via Python-list


Hi all,
Sorry for asking such a basic question butI am trying  to merge two files(file1 
and file2) and do some stuff. Merge the two files by the first column(key). 
Here is the description of files and what I would like to do.


file1

key c1   c2
1  759   939
2  345 154571
3  251 350711
4 3749  22159
5  676  76953
6   46756


file2
key  p1p2
1   759939
2   345 154571
3   251 350711
4  3915  23254
5  7676  77953
7   256   4562

create file3
a) merge the two files by (key) that exit in  file1 and file2
b) create two variables dcp1 = c1- p1 and dcp2= c2-p2
c) sort file3 by dcp2(descending) and output

create file4:-  which exist in file1 but not in file2
create file5:-  that exist in file2 but not in file1;


Desired output files

file3
key   c1c2 p1  p2 dcp1   dcp2
4   3749  22159  3915  23254  -166  -1095
5676  76953  7676  77953 -7000  -1000
1759939   759939 0  0
2345 154571   345 154571 0  0
3251 350711   251 350711 0  0

file4
key c1   p1
6   46   756

file5
key p1   p2
7  256  4562



Thank you in advance
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help on "from deen import *" vs. "import deen"

2016-11-17 Thread jfong
Michael Torrie at 2016/11/18 11:03:12AM wrote:
> >> Python's variables are different from other languages, but in an
> >> understandable way.  
> > 
> > Unfortunately it's also different from human language.
> 
> How so? I don't find this to be true at all.

The fact that most novices will stumble on Python variable many times until it 
becomes his "second nature" proves it's different from the human language:-)

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


Re: key and ..

2016-11-17 Thread justin walters
On Thu, Nov 17, 2016 at 7:05 PM, Val Krem via Python-list <
[email protected]> wrote:

>
>
> Hi all,
> Sorry for asking such a basic question butI am trying  to merge two
> files(file1 and file2) and do some stuff. Merge the two files by the first
> column(key). Here is the description of files and what I would like to do.
>
>
> file1
>
> key c1   c2
> 1  759   939
> 2 345 154571
> 3  251 350711
> 4 3749  22159
> 5  676  76953
> 6   46756
>
>
> file2
> key  p1p2
> 1   759939
> 2   345 154571
> 3   251 350711
> 4  3915  23254
> 5  7676  77953
> 7   256   4562
>
> create file3
> a) merge the two files by (key) that exit in  file1 and file2
> b) create two variables dcp1 = c1- p1 and dcp2= c2-p2
> c) sort file3 by dcp2(descending) and output
>
> create file4:-  which exist in file1 but not in file2
> create file5:-  that exist in file2 but not in file1;
>
>
> Desired output files
>
> file3
> key   c1c2 p1  p2 dcp1   dcp2
> 4   3749  22159  3915  23254  -166  -1095
> 5676  76953  7676  77953 -7000  -1000
> 1759939   759939 0  0
> 2345 154571   345 154571 0  0
> 3251 350711   251 350711 0  0
>
> file4
> key c1   p1
> 6   46   756
>
> file5
> key p1   p2
> 7  256  4562
>
>
>
> Thank you in advance
> --
> https://mail.python.org/mailman/listinfo/python-list
>

1. Take each file and read it using file.open() declaring a variable to
store the string.
2. Use list.split('\n') to split the file into an array of lines.
3. Build a list of dictionaries by splitting each line at whitespace and
calling int() on the values
of each column for each file.
4. Do what you have to do math wise between each dict storing the values in
a new dict. You can
write this out directly to the file or append it to a new list.
5. Use file.open() to write the resulting lines to a new file.
6. transform one of the lists into a set and use set.difference() or
set.intersection() to create
a new list. This list will be unordered by default, so you may want to
run it through
sorted(set, key=lambda row: row['key']).
7. repeat step 5 above to write out to file 4 and 5. no need to transform
the list into a set again.
Just find the difference/interference again.

This isn't the fastest or most efficient way of doing it, but it is
probably the most straight forward.
If these files are quite large you may want to take a different approach in
the interest of performance
and memory. If you don't want to use dicts, you should have no problem
substituting tuples or
nested lists.

The whole thing could be made into a generator as well.

Basically, there are a lot of ways to approach this.

Hope that helped at least a little bit.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help on "from deen import *" vs. "import deen"

2016-11-17 Thread Michael Torrie
On 11/17/2016 08:41 PM, [email protected] wrote:
> The fact that most novices will stumble on Python variable many times
> until it becomes his "second nature" proves it's different from the
> human language:-)

The fact is that most novices don't stumble when dealing with Python
variables. The nature of name binding vs memory boxes does trip up
people occasionally, but most grasp it quickly and move on.

Since you are unwilling to prove your assertion or even provide a single
example (you did once speak of couches and chairs but your reference
made little sense), we can make no further progress.

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


Re: Error in webscraping problem

2016-11-17 Thread Gregory Ewing

[email protected] wrote:

I am trying to solve the following problem.  Two numbers appear on a website.
The user has to enter the gcd (greatest common divisor) and hit the submit
button.  The catch is that the time limit is far too slow for any human
processes -- it must be fully automated.


That's an extremely weird set of requirements. What is it,
some kind of anti-captcha, proving that you're *not* a
human?


print firstNumber # Looks sensible -- first number probably correct
print secondNumber # Looks sensible -- also checked
print solution # Is indeed the correct gcd
res = br.submit()

content = res.read()
with open("FinalResults.html", "w") as f:
f.write(content)
# Unfortunately, I examine this file to find "Wrong Answer"


If the numbers are correct, there must be something wrong
with the way you're submitting the form.

Maybe the site is expecting some cookies or header values
that you're not sending?

Are you able to submit a result successfully by hand
using a browser? If so, you might be able to use Firefox's
debugging facilities to capture the exact response being
sent, including headers and cookies.

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


how to simulate the situation in DNA evolution for finding the minimum population needed and minimum samples selected to mating in order to no extinction in any one of original species and new species

2016-11-17 Thread meInvent bbird
how to simulate the situation in DNA evolution for finding the minimum 
population needed and minimum samples selected to mating in order to no 
extinction in any one of original species and new species

assume mating are randomly selected to become a couple,
how to keep species good which means no extinction in original species

i use i+j to get new species, 
but i do not know whether there is limit in evolution, i assume
limit is 7, then extra evolution will go back to past species and 
cycle again

import matplotlib.pyplot as plt
import random
dict = {}
dist = {}
maxnum = 5
allowedmax = 7
for i in range(1,allowedmax+1):
dist[str(i)] = 0

rr = range (1,maxnum)
for i in range (1,maxnum):
for j in range (1,maxnum):
if i < j:
print("(" +str(i) + "," + str(j) + ")");
dict[str(i) + str(j)] = 1;
dist[str(i+j)] = dist[str(i+j)] + 1
if i+j > max(rr or [0]):
 rr = rr + [i+j];

original = rr;
for numberofevolutions in range(1,10):
rr2 = []
samples = random.sample(original, len(original)-2)
print("total rr")
print(str(rr))
print("samples")
print(str(samples))
for i in samples:
for j in samples:
if i < j:
print("(" +str(i) + "," + str(j) + ")");
if i+j > allowedmax:
dict[str(i) + str(j)] = (i+j) % allowedmax;
dist[str((i+j) % allowedmax)] = dist[str((i+j) % 
allowedmax)] + 1
if ((i+j) % allowedmax) > max(rr2 or [0]):
rr2 = rr2 + [((i+j) % allowedmax)];
else:
dict[str(i) + str(j)] = i+j;
dist[str(i+j)] = dist[str(i+j)] + 1
if i+j > max(rr2 or [0]):
rr2 = rr2 + [i+j];
temp = rr
rr = rr2
rr2 = temp

plt.bar(range(len(dist)), dist.values(), align='center')
plt.xticks(range(len(dist)), dist.keys())
plt.show()
-- 
https://mail.python.org/mailman/listinfo/python-list


Unable to sniff outgoing traffic using raw sockets in python2.7

2016-11-17 Thread Ayush Aggarwal
Hello,

Following is my code :

#!/usr/bin/python

import socket
import struct
import binascii

rawSocket = socket.socket(socket.PF_PACKET,socket.SOCK_RAW,socket.htons(0x0800))
# use 0x0800 for IPv4 packets , 0x0003 is for sniffing all kinds of packets

while True:
pkt= rawSocket.recvfrom(2048)

ethernetHeader = pkt[0][0:14]

pr = unicode(ethernetHeader, errors='replace')
print pr
eth_hdr = struct.unpack("!6s6s2s",ethernetHeader)

print "Source MAC Address :" , binascii.hexlify(eth_hdr[1])
print "Destination MAC Address : " , binascii.hexlify(eth_hdr[0])
print "Protocol : " , binascii.hexlify(eth_hdr[2])
ipHeader = pkt[0][14:34]
ip_hdr = struct.unpack("!12s4s4s",ipHeader)
print "Source ip ADDRESS : " + socket.inet_ntoa(ip_hdr[1])
print "Destination IP Address: " + socket.inet_ntoa(ip_hdr[2])
# initial part of the tcp header
tcpHeader = pkt[0][34:54]
tcp_hdr = struct.unpack("!HH16s",tcpHeader)
print "Source Port ADDRESS : " ,tcp_hdr[0]
print "Destination Port ADDRESS : " , tcp_hdr[1]


Issues :
1. Unable to capture any outgoing IPv4 traffic. I ran the sniff()
method in Scapy and it does capture the outgoing packets.

2. I am NOT USING PROMISCUOUS MODE , still most of the packes I am
receiving neither have my IP or MAC in either of the source or
destination fields.

3. Captured data is different from the one observed using Scapy or Wireshark.

Request you to kindly clarify these observations.

Thanks and Regards,
Ayush
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What exactly is a python variable?

2016-11-17 Thread Ben Finney
Ned Batchelder  writes:

> So it's not a bug, and it also is not a feature. It just is.

+1 QotW

-- 
 \“A free press is one where it's okay to state the conclusion |
  `\  you're led to by the evidence.” —Bill Moyers |
_o__)  |
Ben Finney

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