Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-11 Thread Manolo Martínez
On 11/10/14 at 09:00pm, Grant Edwards wrote:
> That's the saddest troll I've seen in ages.

That, on the other hand, is a pretty decent bit of trolling.
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Python script that does batch find and replace in txt files

2014-11-11 Thread Clayton Kirkwood


>-Original Message-
>From: Python-list [mailto:python-list-
>[email protected]] On Behalf Of Syed Khalid
>Sent: Sunday, November 09, 2014 1:08 PM
>To: [email protected]
>Subject: Re: Python script that does batch find and replace in txt files
>
>My Script,
>
>I have added
>
>import glob, codecs, re, os
>
>regex = re.compile(r"Age: |Sex: |House No: ") # etc etc Script I
>executed in EditRocket :
>
>for txt in glob.glob("/D:/Python/source/*.txt"):
>with codecs.open(txt, encoding="utf-8") as f:
>oldlines = f.readlines()
>for i, line in enumerate(oldlines):
>if "Contact's Name:" in line:
>break
>newlines = [regex.sub("", line).strip().replace("-", "_") for line
>in oldlines[i:]
>with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w:
>w.write(os.linesep.join(newlines))
>

To my young eyes, it looks like you are missing a ] at the end of the line
before the with.

>
>Error Message :
>
>  File "EamClean.log", line 12
>with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w:
>   ^
>SyntaxError: invalid syntax
>
>Kindly do the needful
>
>
>
>--
>https://mail.python.org/mailman/listinfo/python-list



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


RE: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-11 Thread Clayton Kirkwood


>-Original Message-
>From: Python-list [mailto:python-list-
>[email protected]] On Behalf Of Grant Edwards
>Sent: Monday, November 10, 2014 1:01 PM
>To: [email protected]
>Subject: Re: I don't read docs and don't know how to use Google. What
>does the print function do?
>
>On 2014-11-10, [email protected]  wrote:
>
>> Please help me this assignment is due in an hour.  Don't give me
>> hints, just give me the answer because I only want a grade.  I'm not
>> actually interested in learning how to program, but I know software
>> engineers make lots of money so I want to be one.
>
>That's the saddest troll I've seen in ages.

Uh, how are you going to maintain a programming job if you don't know how to
program? I don't want to act but I know Brad Pitt makes lots of money doing
it, so I want to be Brad Pitt. Not! Not going to happen. Although I suspect
for a price you could bring all of your professional programming jobs to
somebody here, but I think you would pay out more than you would make.

Clayton
>
>--
>Grant Edwards   grant.b.edwardsYow! I just forgot my
>whole
>  at   philosophy of life!!!
>  gmail.com
>--
>https://mail.python.org/mailman/listinfo/python-list



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


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-11 Thread Chris Angelico
On Tue, Nov 11, 2014 at 10:21 AM, Clayton Kirkwood  wrote:
> Uh, how are you going to maintain a programming job if you don't know how to
> program? I don't want to act but I know Brad Pitt makes lots of money doing
> it, so I want to be Brad Pitt. Not! Not going to happen. Although I suspect
> for a price you could bring all of your professional programming jobs to
> somebody here, but I think you would pay out more than you would make.
>

I'm not entirely sure how it works, but it does happen. I've been
writing code for over two decades, and trying to earn a living at it
for one and a bit, and in all that time, I have *never even once*
found a job by applying in the classic way and sending in a resume.
There are blog posts out there about how large proportions of
applicants can't even write simple code on command... and I've taken
the questions and shown them to my siblings (who protest that they're
definitely not programmers), proving that a basic smattering of
mathematical nous puts you above people who are trying to earn money
from coding.

It's like a carpenter, looking for a skilled assistant, and getting
people who don't know which end of a saw to hold.

It's like a prospective accountant not knowing the words "credit" and "debit".

It's like someone trying to rule a country just on the basis of
looking good on television... okay, so maybe there's one other
"industry" where the incompetent have a shot at it.

But fortunately, it's not everyone. There are the "bad eggs" who waste
everyone's time, but there are plenty of truly competent people too.
It's just a matter of figuring out which are the "will-be-competent"
and which are the "totally lazy and not going anywhere", and there's
not always a lot to distinguish them by.

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


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-11 Thread alister
On Mon, 10 Nov 2014 21:36:54 +, Denis McMahon wrote:

> On Mon, 10 Nov 2014 10:56:18 -0800, sohcahtoa82 wrote:
> 
>> ... I know software engineers make lots of money so I want to be one.
> 
> I hear that pretty boy male escorts can make even more money than
> software engineers.
> 
> They also don't need to learn how to program, which is something
> software engineers do need to do, so it sounds as if you'd be better off
> signing up with an escort agency.

in both cases you start at the bottom, as a rent boy you stay there



-- 
He thinks by infection, catching an opinion like a cold.
-- 
https://mail.python.org/mailman/listinfo/python-list


ANN: eGenix pyOpenSSL Distribution 0.13.6

2014-11-11 Thread eGenix Team: M.-A. Lemburg

ANNOUNCING

   eGenix.com pyOpenSSL Distribution

 Version 0.13.6


 An easy-to-install and easy-to-use distribution
 of the pyOpenSSL Python interface for OpenSSL -
available for Windows, Mac OS X and Unix platforms


This announcement is also available on our web-site for online reading:
http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.13.6.html


INTRODUCTION

The eGenix.com pyOpenSSL Distribution includes everything you need to
get started with SSL in Python.

It comes with an easy-to-use installer that includes the most recent
OpenSSL library versions in pre-compiled form, making your application
independent of OS provided OpenSSL libraries:

http://www.egenix.com/products/python/pyOpenSSL/

pyOpenSSL is an open-source Python add-on that allows writing SSL/TLS-
aware network applications as well as certificate management tools:

https://launchpad.net/pyopenssl/

OpenSSL is an open-source implementation of the SSL/TLS protocol:

http://www.openssl.org/


NEWS

This new release of the eGenix.com pyOpenSSL Distribution updates the
included OpenSSL version to the latest OpenSSL 1.0.1h version and adds
a few more context options:

New in OpenSSL
--

 * Reenabled the SSLv2 support in the bundled OpenSSL libraries which
   we had removed in 0.13.5, since removing the SSLv2 symbols resulted
   in too many compatibility problems with existing code such as e.g.

>>> import OpenSSL
>>> import ssl
Traceback (most recent call last):
  File "", line 1, in 
  File "ssl.py", line 60, in 
import _ssl
ImportError: _ssl.so: undefined symbol: SSLv2_method

   The ImportError is the result of using the 0.13.5 version of the
   OpenSSL libs with an ssl module which was compiled against a system
   version with SSLv2 support, effectively making the ssl module
   unusable.

   To protect against SSLv2 and SSLv3 downgrade attacks, please make
   sure you setup the SSL context to disallow using SSLv2 and SSLv3,
   e.g.

context = SSL.Context(SSL.SSLv23_METHOD)
context.set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3)

New in pyOpenSSL


 * OpenSSL.__version__ is now updated to the distribution version
   rather than left at "0.13" as it was in previous releases. It now
   shows "0.13.6" for this release.

 * Emphasized on the need to "import OpenSSL" early to prevent Python
   from loading the system OpenSSL libraries instead of the embedded
   ones. Be sure to read the section Loading the embedded OpenSSL
   Libraries of the documentation for details on how to make sure that
   the embedded libraries are loaded:

   http://www.egenix.com/products/python/pyOpenSSL/doc/#LoadingOpenSSL

Please see the product changelog for the full set of changes:

   http://www.egenix.com/products/python/pyOpenSSL/changelog.html

pyOpenSSL / OpenSSL Binaries Included
-

In addition to providing sources, we make binaries available that
include both pyOpenSSL and the necessary OpenSSL libraries for all
supported platforms: Windows x86 and x64, Linux x86 and x64, Mac OS X
PPC, x86 and x64.

We've also added egg-file distribution versions of our eGenix.com
pyOpenSSL Distribution for Windows, Linux and Mac OS X to the
available download options. These make setups using e.g. zc.buildout
and other egg-file based installers a lot easier.


DOWNLOADS

The download archives and instructions for installing the package can
be found at:

http://www.egenix.com/products/python/pyOpenSSL/


UPGRADING

Before installing this version of pyOpenSSL, please make sure that
you uninstall any previously installed pyOpenSSL version. Otherwise,
you could end up not using the included OpenSSL libs.

___
SUPPORT

Commercial support for these packages is available from eGenix.com.
Please see

http://www.egenix.com/services/support/

for details about our support offerings.


MORE INFORMATION

For more information about the eGenix pyOpenSSL Distribution, licensing
and download instructions, please visit our web-site or write to
[email protected].

Enjoy,
-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Nov 11 2014)
>>> Python Projects, Consulting and Support ...   http://www.egenix.com/
>>> mxODBC.Zope/Plone.Database.Adapter ...   http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egeni

Re: A syntax question

2014-11-11 Thread alister
On Mon, 10 Nov 2014 19:53:56 -0500, Dennis Lee Bieber wrote:

> On Mon, 10 Nov 2014 14:56:11 GMT, alister
>  declaimed the following:
> 
>>On Mon, 10 Nov 2014 14:54:55 +, alister wrote:
>>
>>> On Mon, 10 Nov 2014 14:44:53 +, Grant Edwards wrote:
>>> 
 On 2014-11-10, David Palao  wrote:
 
>> My crystal ball is currently in for repair and is not expected back
>> in the foreseeable future.
>
> Without a crystal ball, this prediction might be not well founded.
 
 That isn't a prediction.  It's an explicit statement of no
 prediction.
 He said that it is "not expected back" rather than "expected not to
 be back".  They're two different things.  The former asserts a _lack_
 of expection/prediction.  The latter asserts an
 expectation/prediction.
>>> 
>>> It was only a a joke maybe it was a bit to subtle
>>
>>I didn't expect the Spanish inquisition (Damn wish Id though of that
>>before sending the last post)
> 
>   They're now the Congregation of the Doctrine of the Faith -- 
formerly
> led by the person who became Pope Benedict.

but "I didnt expect the congregation of the Doctrine of the Faith" is not 
on topic.




-- 
Never trust an automatic pistol or a D.A.'s deal.
-- John Dillinger
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "Natural" use of cmp= in sort

2014-11-11 Thread Ian Kelly
On Tue, Nov 11, 2014 at 12:44 AM, Paddy  wrote:
> Thanks Ian. The original author states "...and it is sure that the given 
> inputs will give an output, i.e., the inputs will always be valid.", which 
> could be taken as meaning that all inputs are sufficient, well formed, and 
> contain all relations as their first example does.

Well, I brought it up because the start of that sentence is "There can
be multiple inequalities as answer but I need any one which is
correct...". The only way there would be more than one correct answer
would be if the inputs were only partially ordered. I take the second
part of the sentence as meaning only that the input can be safely
assumed to be consistent.

> Yes, I knew that there are cases where a cmp function is more natural than 
> key; the idea is to squirrel out a few. We have already made the, (well 
> reasoned in my opinion), decision to go down the key= route in Python 3. I 
> also like to track where my algorithms might originally map to cmp=. (It is 
> not often).

Basically any time you have a comparison that isn't easily expressed
by mapping the values to some bunch of ordered objects. As an example
of what I mean, we can easily sort alphabetically using a key
function:

sorted(items, key=str)

And we can easily sort reverse alphabetically:

sorted(items, key=str, reverse=True)

And we can easily sort alphabetically on multiple criteria:

sorted(items, key=lambda x: (str(x.last_name), str(x.first_name)))

But what if we want to combine those last two requirements? Suppose we
have a table that we want to present sorted primarily in ascending
order on one column, and secondarily in descending order on another.
We can't just add the reverse argument argument to the previous
expression, because that would reverse the sort order for both
columns. But there is no simple key function for strings that will
reverse the sort without using the reverse argument.

There are basically two ways to approach this. One is to implement a
cmp function and pass it to cmp_to_key. The other is to create a class
with comparison methods that result in the desired order, and use the
class as the key; this is really just a variation ot the cmp_to_key
approach.
-- 
https://mail.python.org/mailman/listinfo/python-list


What is \1 here?

2014-11-11 Thread satishmlmlml
What does \1 do in the following piece of code(fourth line)?
import re
print(re.sub('[ABC]', '*', 'XAXAXBXBXCXC'))
print(re.sub('[ABC]_', '*', 'XA-XA_XB-XB_XC-XC_'))
print(re.sub('(.) spam', 'spam\\1', 'x spam, y spam'))
def mapper(matchobj):
   return 'spam' + matchobj.group(1)
print(re.sub('(.) spam', mapper, 'x spam, y spam'))

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


Re: "Natural" use of cmp= in sort

2014-11-11 Thread Paddy
On Tuesday, 11 November 2014 09:07:14 UTC, Ian  wrote:
> On Tue, Nov 11, 2014 at 12:44 AM, Paddy  wrote:
> > Thanks Ian. The original author states "...and it is sure that the given 
> > inputs will give an output, i.e., the inputs will always be valid.", which 
> > could be taken as meaning that all inputs are sufficient, well formed, and 
> > contain all relations as their first example does.
> 
> Well, I brought it up because the start of that sentence is "There can
> be multiple inequalities as answer but I need any one which is
> correct...". The only way there would be more than one correct answer
> would be if the inputs were only partially ordered. I take the second
> part of the sentence as meaning only that the input can be safely
> assumed to be consistent.
> 
> > Yes, I knew that there are cases where a cmp function is more natural than 
> > key; the idea is to squirrel out a few. We have already made the, (well 
> > reasoned in my opinion), decision to go down the key= route in Python 3. I 
> > also like to track where my algorithms might originally map to cmp=. (It is 
> > not often).
> 
> Basically any time you have a comparison that isn't easily expressed
> by mapping the values to some bunch of ordered objects. 

Yep. I want to track when this comes up for me and others during their normal 
programming rather than in examples made to highlight the issue.

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


What is ?s here?

2014-11-11 Thread satishmlmlml
What does ?s do in the following piece of code?

import re, pprint
text = open('books.xml').read()
pattern = '(?s)isbn="(.*?)".*?(.*?)'
found = re.findall(pattern, text)
mapping = {isbn: title for (isbn, title) in found}
pprint.pprint(mapping)

Here is books.xml


   
 Python & XML
 December 2001
 Jones, Drake
   

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


Re: What is \1 here?

2014-11-11 Thread Mark Lawrence

On 11/11/2014 09:18, [email protected] wrote:

What does \1 do in the following piece of code(fourth line)?
import re
print(re.sub('[ABC]', '*', 'XAXAXBXBXCXC'))
print(re.sub('[ABC]_', '*', 'XA-XA_XB-XB_XC-XC_'))
print(re.sub('(.) spam', 'spam\\1', 'x spam, y spam'))
def mapper(matchobj):
return 'spam' + matchobj.group(1)
print(re.sub('(.) spam', mapper, 'x spam, y spam'))



What did your last skivvy die of, overwork?

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

Mark Lawrence

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


FW: Trouble with Python

2014-11-11 Thread Ashleigh .



 To whom it may concern,


I am currently trying to run some code in python(x,y). It was working perfectly 
a couple of weeks ago but recently it hasn't been. Every time it runs, the 
program crashes and becomes unresponsive resulting in me having to exit. 
It has happened on multiple computers, all using windows, and I was wondering 
if you could help me with my problem.
I have attached a copy of my code.


Thank you
Ashleigh Deal

  # importing libraries
# this code loads the processed city data and does some comparison of the London and other city time series


from netCDF4 import Dataset
from netcdftime import utime
import numpy as np
import matplotlib.pyplot as plt
import pylab
from matplotlib.dates import DateFormatter, MonthLocator
import datetime

import sys

# get command line arguments
city_name=str(sys.argv[1])
city_name=city_name.replace(" ","_")
fname='proc_data/'+city_name+'_max.nc'

# read in data
nc=Dataset(fname,'r')
london=nc.variables['London'][:]
city=nc.variables[city_name][:]

london_clim=nc.variables['London Climatology'][:]
city_clim=nc.variables[city_name+' Climatology'][:]


# time information
time=nc.variables['time']
cdftime = utime(time.units,'standard')
time=cdftime.num2date(nc.variables['time'][:])
day=np.fromiter((time[x].day for x in range(0,len(time))),np.int)
month=np.fromiter((time[x].month for x in range(0,len(time))),np.int)
year=np.fromiter((time[x].year for x in range(0,len(time))),np.int)

nc.close()


# difference in max temperature (positive values mean London T higher)
diff=london-city

# four different example plots

##
# plot 1 - for all time percentage of London exceedence per month

# count number of positive days (and total number of days) per month
prop=np.empty([12])
for m in range(1,13):
 ind=np.where(month == m)
 prop[m-1]=sum(diff[ind] > 0)/float(len(ind[0]))

fig1, ax1 = plt.subplots(figsize=(7,7))

month_names=['J','F','M','A','M','J','J','A','S','O','N','D']
pos=np.arange(len(month_names))+0.5

p1 = ax1.bar(pos,prop,color='r', align='center')

ax1.set_title('Days with temperature in London greater than '+city_name)
ax1.set_ylabel('Percentage of days 1880-2010')
pylab.xticks(pos,month_names)
fig1.savefig('plots/'+city_name+'_months.png')


##

# plot 2 - has number of exceedences changed over the dataset time period

# count number of positive days (and total number of days) per month
prop_ann=np.empty(13)
for y in range(0,13):
 ind=np.where((year >= 1880+(y*10)) & (year < 1889+(y*10)))
 prop_ann[y-1]=sum(diff[ind] > 0)/float(len(ind[0]))

fig2, ax2 = plt.subplots(figsize=(10,5))

dec_names=['1880s','1890s','1900s','1910s','1920s','1930s',
   '1940s','1950s','1960s','1970s','1980s','1990s',
   '2000s']
pos=np.arange(len(dec_names))+0.5

p1 = ax2.bar(pos,prop_ann,color='g', align='center')

ax2.set_title('Days with temperature in London greater than '+city_name)
ax2.set_ylabel('Percentage of days 1880-2010')
pylab.xticks(pos,dec_names)
fig2.savefig('plots/'+city_name+'_decades.png')

##

# plot 3 - scatter plot of exceedence vs. London temperature during April

# where is month equal to April (4)
ind=np.where(month == 4)

fig3, ax3 = plt.subplots(figsize=(7,7))

p1 = ax3.plot(london[ind],diff[ind],'m+')

ax3.set_ylabel('Difference with '+city_name)
ax3.set_xlabel('Temperature in London')
fig3.savefig('plots/'+city_name+'_scatter.png')

##

# plot 4 - daily climatology of two cities

# make datetime array for climatology
clim_time=[datetime.datetime(1993,1,1,12)+datetime.timedelta(x) 
for x in range(0,365)]

months=MonthLocator(range(1,13),bymonthday=15)
monthFormatter=DateFormatter('%b')

london_std=np.empty([12])
for i in np.arange(1,13):
ind=np.where(month == i)
london_std[i-1]=np.std(london[ind])

city_std=np.empty([12])
for i in np.arange(1,13):
ind=np.where(month == i)
city_std[i-1]=np.std(city[ind])

fig4, ax4 = plt.subplots(figsize=(7,7))
p1 = ax4.plot(clim_time,london_std,'b',label='London')
p2 = ax4.plot(clim_time,city_std,'r',label=city_name)

ax4.xaxis.set_major_locator(months)
ax4.xaxis.set_major_formatter(monthFormatter)
ax4.xaxis_date()
ax4.set_ylabel('Climatological maximum temperature / $^\circ$C')

ax4.legend()
fig4.savefig('plots/'+city_name+'_clim.png')

# show all figures can be commented out
plt.show()



per_above_thresh=np.empty([31])
for temp in np.arange(0,31):
ind=np.where(london > temp)
diff=london[ind] - city[ind]
pos=np.sum(diff > 0)
prop=float(pos)/float(len(diff))
per_above_thresh[temp] = prop

fig5, ax5 = plt.subplots(figsize=(7,7))

ax5.plot((np.arange(0,31)),per_above_thresh)

ax5.set_ylabel('percentage of days 1880 - 2010')
ax5.set_xlabel('Temperature Difference')

plt.show()


-- 

Trouble with python

2014-11-11 Thread Ashleigh Deal
To whom it may concern,


I am trying to use python as part of my part 3 project but my coding has 
suddenly stopped working. I am using python(x,y) and it was working perfectly a 
couple of weeks ago but recently it hasn't been. Every time it runs, the 
program crashes and becomes unresponsive resulting in me having to exit.
It has happened on multiple computers in the met department, agriculture and 
also on my own laptop and I was wondering if you could help me with my problem. 
I have spoken to my supervisor already and he doesn't know what is wrong with 
it.
I have attached a copy of my code, one version in word and one in python.


Thank you
Ashleigh Deal?


python code.docx
Description: python code.docx
# importing libraries
# this code loads the processed city data and does some comparison of the 
London and other city time series


from netCDF4 import Dataset
from netcdftime import utime
import numpy as np
import matplotlib.pyplot as plt
import pylab
from matplotlib.dates import DateFormatter, MonthLocator
import datetime

import sys

# get command line arguments
city_name=str(sys.argv[1])
city_name=city_name.replace(" ","_")
fname='proc_data/'+city_name+'_max.nc'

# read in data
nc=Dataset(fname,'r')
london=nc.variables['London'][:]
city=nc.variables[city_name][:]

london_clim=nc.variables['London Climatology'][:]
city_clim=nc.variables[city_name+' Climatology'][:]


# time information
time=nc.variables['time']
cdftime = utime(time.units,'standard')
time=cdftime.num2date(nc.variables['time'][:])
day=np.fromiter((time[x].day for x in range(0,len(time))),np.int)
month=np.fromiter((time[x].month for x in range(0,len(time))),np.int)
year=np.fromiter((time[x].year for x in range(0,len(time))),np.int)

nc.close()


# difference in max temperature (positive values mean London T higher)
diff=london-city

# four different example plots

##
# plot 1 - for all time percentage of London exceedence per month

# count number of positive days (and total number of days) per month
prop=np.empty([12])
for m in range(1,13):
 ind=np.where(month == m)
 prop[m-1]=sum(diff[ind] > 0)/float(len(ind[0]))

fig1, ax1 = plt.subplots(figsize=(7,7))

month_names=['J','F','M','A','M','J','J','A','S','O','N','D']
pos=np.arange(len(month_names))+0.5

p1 = ax1.bar(pos,prop,color='r', align='center')

ax1.set_title('Days with temperature in London greater than '+city_name)
ax1.set_ylabel('Percentage of days 1880-2010')
pylab.xticks(pos,month_names)
fig1.savefig('plots/'+city_name+'_months.png')


##

# plot 2 - has number of exceedences changed over the dataset time period

# count number of positive days (and total number of days) per month
prop_ann=np.empty(13)
for y in range(0,13):
 ind=np.where((year >= 1880+(y*10)) & (year < 1889+(y*10)))
 prop_ann[y-1]=sum(diff[ind] > 0)/float(len(ind[0]))

fig2, ax2 = plt.subplots(figsize=(10,5))

dec_names=['1880s','1890s','1900s','1910s','1920s','1930s',
   '1940s','1950s','1960s','1970s','1980s','1990s',
   '2000s']
pos=np.arange(len(dec_names))+0.5

p1 = ax2.bar(pos,prop_ann,color='g', align='center')

ax2.set_title('Days with temperature in London greater than '+city_name)
ax2.set_ylabel('Percentage of days 1880-2010')
pylab.xticks(pos,dec_names)
fig2.savefig('plots/'+city_name+'_decades.png')

##

# plot 3 - scatter plot of exceedence vs. London temperature during April

# where is month equal to April (4)
ind=np.where(month == 4)

fig3, ax3 = plt.subplots(figsize=(7,7))

p1 = ax3.plot(london[ind],diff[ind],'m+')

ax3.set_ylabel('Difference with '+city_name)
ax3.set_xlabel('Temperature in London')
fig3.savefig('plots/'+city_name+'_scatter.png')

##

# plot 4 - daily climatology of two cities

# make datetime array for climatology
clim_time=[datetime.datetime(1993,1,1,12)+datetime.timedelta(x) 
for x in range(0,365)]

months=MonthLocator(range(1,13),bymonthday=15)
monthFormatter=DateFormatter('%b')

london_std=np.empty([12])
for i in np.arange(1,13):
ind=np.where(month == i)
london_std[i-1]=np.std(london[ind])

city_std=np.empty([12])
for i in np.arange(1,13):
ind=np.where(month == i)
city_std[i-1]=np.std(city[ind])

fig4, ax4 = plt.subplots(figsize=(7,7))
p1 = ax4.plot(clim_time,london_std,'b',label='London')
p2 = ax4.plot(clim_time,city_std,'r',label=city_name)

ax4.xaxis.set_major_locator(months)
ax4.xaxis.set_major_formatter(monthFormatter)
ax4.xaxis_date()
ax4.set_ylabel('Climatological maximum temperature / $^\circ$C')

ax4.legend()
fig4.savefig('plots/'+city_name+'_clim.png')

# show all figures can be commented out
plt.show()



per_above_thresh=np.empty([31])
for temp in np.arange(0,31):
ind=np.where(london > temp)
diff=london[ind] - city[ind]
pos=np.sum(diff > 0)
prop=float(pos)/float(len(diff))
per_above_thresh[temp] = p

Re: What is \1 here?

2014-11-11 Thread Ned Batchelder

On 11/11/14 4:18 AM, [email protected] wrote:

What does \1 do in the following piece of code(fourth line)?
import re
print(re.sub('[ABC]', '*', 'XAXAXBXBXCXC'))
print(re.sub('[ABC]_', '*', 'XA-XA_XB-XB_XC-XC_'))
print(re.sub('(.) spam', 'spam\\1', 'x spam, y spam'))
def mapper(matchobj):
return 'spam' + matchobj.group(1)
print(re.sub('(.) spam', mapper, 'x spam, y spam'))



Maybe you can't tell from the reception you're getting here: People are 
growing tired of your questions about basic Python behavior.  They want 
you to find a way to learn for yourself.  You're asking about regular 
expressions.  The Python docs have an extensive page detailing how they 
work: https://docs.python.org/3/library/re.html


You need to learn how to find this stuff out for yourself. Ben Finney 
even gave you a pointer to a helpful site for experimenting with 
regexes: http://pythex.org/


--
Ned Batchelder, http://nedbatchelder.com

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


Re: Trouble with python

2014-11-11 Thread Ben Finney
Ashleigh Deal  writes:

> I am trying to use python as part of my part 3 project but my coding
> has suddenly stopped working. I am using python(x,y) and it was
> working perfectly a couple of weeks ago but recently it hasn't been.

What has changed in the meantime, which could conceivably affect the
program's behaviour?

> Every time it runs, the program crashes and becomes unresponsive
> resulting in me having to exit.

When you say “the program crashes”, that implies it stops with a fatal
error. What is the complete error message text?

-- 
 \ “If you ever teach a yodeling class, probably the hardest thing |
  `\  is to keep the students from just trying to yodel right off. |
_o__) You see, we build to that.” —Jack Handey |
Ben Finney

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


Re:What is \1 here?

2014-11-11 Thread Dave Angel
[email protected] Wrote in message:
> What does \1 do in the following piece of code(fourth line)?
> import re
> print(re.sub('[ABC]', '*', 'XAXAXBXBXCXC'))
> print(re.sub('[ABC]_', '*', 'XA-XA_XB-XB_XC-XC_'))
> print(re.sub('(.) spam', 'spam\\1', 'x spam, y spam'))
> def mapper(matchobj):
>return 'spam' + matchobj.group(1)
> print(re.sub('(.) spam', mapper, 'x spam, y spam'))
> 
> 

Recommend you use raw strings when defining regex patterns.  Then
 you wouldn't have to double the backslash.

To see what re.sub will see, try
print ('spam\\1')

As for what the function does with that, I'll have to guess, as I
 don't do regex. I'd guess it'll match any digit.

-- 
DaveA

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


Re: Need some help with NetGroupAddUser

2014-11-11 Thread Jaimin Ajmeri
  cfl.rr.com> writes:

> 
> New B question -- Need help with win32net.NetGroupAddUser.  I used Mark
Hammond 
> sample code to create a new user from his book Python Programming on Win32. I 
> then added one line to add the newuser to a group.
> def CreateUserAndShare(userName, fullName):
> homeDir = "%s\\%s" % (serverName, userName)
> # Create user data in information level 3 (PyUSER_INFO_3) format.
> userData = {}
> userData['name'] = userName
> userData['full_name'] = fullName
> userData['password'] = userName
> userData['flags'] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT
> userData['priv'] = win32netcon.USER_PRIV_USER
> userData['home_dir'] = homeDir
> userData['home_dir_drive'] = "P:"
> userData['primary_group_id'] = ntsecuritycon.DOMAIN_GROUP_RID_USERS
> userData['password_expired'] = 1 # User must change password next logon.
> 
> # Create the user
> win32net.NetUserAdd(serverName, 3, userData)
> win32net.NetGroupAddUser(serverName, "Administrator", userName)
> 
> This is my error:
> pywintypes.api_error: (2220, 'NetGroupAddUser', 'The group name could not be 
> found.')
> What should I be using for the groupname parameter, I've tried them all, 
> Administrator, Guests, Users ext Any help will be greatly appreciated. 
> Thanks,
> kc
> 
> 

Hello kcollins15,

   Just try this.

import win32api
import win32net

###

Code to create user goes here

###

##

# Code to add created user to a group (on a local machine)

serverName = "" + win32api.GetComputerName()
domain = win32api.GetDomainName()
data = [{"domainandname" : domain + "\\TestUser"}]
print "Adding"
win32net.NetLocalGroupAddMembers(serverName,"Users",3,data)
print "Added Successfully !!"

##

This is working piece of code. It worked for me, I needed to add newly
created user to the group called "Users".

Just replace "Users" with "Administrator". 

I'll get back soon on how and when NetGroupAddUser() should be used.

Hope it helps...!
Jaimin Ajmeri 



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


Re: Trouble with python

2014-11-11 Thread Joel Goldstick
On Tue, Nov 11, 2014 at 6:53 AM, Ben Finney  wrote:
> Ashleigh Deal  writes:
>
>> I am trying to use python as part of my part 3 project but my coding
>> has suddenly stopped working. I am using python(x,y) and it was
>> working perfectly a couple of weeks ago but recently it hasn't been.
>
> What has changed in the meantime, which could conceivably affect the
> program's behaviour?
>
>> Every time it runs, the program crashes and becomes unresponsive
>> resulting in me having to exit.
>
> When you say “the program crashes”, that implies it stops with a fatal
> error. What is the complete error message text?
>
> --
>  \ “If you ever teach a yodeling class, probably the hardest thing |
>   `\  is to keep the students from just trying to yodel right off. |
> _o__) You see, we build to that.” —Jack Handey |
> Ben Finney
>

A couple of points:  Its best to cut and paste your code directly into
your email text.  And use plaintext, not rtf (emails with different
fonts, etc.)  This way your code will be exactly what you typed.  You
should say which version of python.  I don't know what python(x,y)
means, but python 3.4 or 2.7 is useful information.

If you feel that the code used to work, but doesn't now, then how
about the data file?  Has the data you are studying changed?
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: locale.getlocale() in cmd.exe vs. Idle

2014-11-11 Thread Albert-Jan Roskam
- Original Message -
> From: Terry Reedy 
> To: [email protected]
> Cc: 
> Sent: Monday, November 10, 2014 9:31 PM
> Subject: Re: locale.getlocale() in cmd.exe vs. Idle
> 
> On 11/10/2014 4:22 AM, Albert-Jan Roskam wrote:
>>  Hi,
>> 
>>  Why do I get different output for locale.getlocale() in Idle vs. cmd.exe?



> 
> Idle runs code in an environment that is slightly altered from the 
> standard python startup environment'.  idlelib.IOBinding has this
> '''
> # Try setting the locale, so that we can find out
> # what encoding to use
> try:
>  import locale
>  locale.setlocale(locale.LC_CTYPE, "")
> '''
 
Hi Terry,
 
Thank you. Any idea why setlocale (a *setter*) returns something other than 
None? (this question is not related to the (None, None) thing of getlocale, 
just curious). Would it be a good idea to put this setlocale line in site.py? 
Or should it be in __init__.py to make the code more portable?

> idlelib.run, which runs in the user-code subprocess, imports IOBinding. 
> Setting LC_CTYPE is sufficient for getlocale() to not return null values.

So then I would have all the locale categories of the 'bare' locale (sorry, I 
don't know what else I should call it), except for LC_CTYPE, which is derived 
from my system. So in LC_NUMERIC I'd still have the en_US period/comma for 
decimal/thousand grouping, respectively, but I switch to the nl_NL LC_CTYPE. I 
doubt if it matters, but still: will this not introduce an ueber hard-to-find 
possible bug when I use re.LOCALE? 
 
> C:\Users\Terry>python -c "import locale; 
> print(locale.getlocale())"
> 
> (None, None)
> 
> C:\Users\Terry>python -c "import locale; 
> locale.setlocale(locale.LC_CTYPE, ''); print(locale.getlocale())"
> ('English_United States', '1252')
 
What is the difference between getlocale and getdefaultlocale anyway? The 
docstrings are even partially the same. The notatation of getlocale appears to 
be OS-specific ("English_United States" in Windows) and not Unix-like (cf. 
getdefaultlocale: en_US)
 
regards,
Albert-Jan
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need some help with NetGroupAddUser

2014-11-11 Thread MRAB

On 2014-11-11 04:30, Jaimin Ajmeri wrote:

   cfl.rr.com> writes:



New B question -- Need help with win32net.NetGroupAddUser.  I used Mark

Hammond

sample code to create a new user from his book Python Programming on Win32. I
then added one line to add the newuser to a group.
def CreateUserAndShare(userName, fullName):
homeDir = "%s\\%s" % (serverName, userName)
# Create user data in information level 3 (PyUSER_INFO_3) format.
userData = {}
userData['name'] = userName
userData['full_name'] = fullName
userData['password'] = userName
userData['flags'] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT
userData['priv'] = win32netcon.USER_PRIV_USER
userData['home_dir'] = homeDir
userData['home_dir_drive'] = "P:"
userData['primary_group_id'] = ntsecuritycon.DOMAIN_GROUP_RID_USERS
userData['password_expired'] = 1 # User must change password next logon.

# Create the user
win32net.NetUserAdd(serverName, 3, userData)
win32net.NetGroupAddUser(serverName, "Administrator", userName)

This is my error:
pywintypes.api_error: (2220, 'NetGroupAddUser', 'The group name could not be
found.')
What should I be using for the groupname parameter, I've tried them all,
Administrator, Guests, Users ext Any help will be greatly appreciated.
Thanks,
kc




Hello kcollins15,

Just try this.

import win32api
import win32net

###

Code to create user goes here

###

##

# Code to add created user to a group (on a local machine)

serverName = "" + win32api.GetComputerName()
domain = win32api.GetDomainName()
data = [{"domainandname" : domain + "\\TestUser"}]
print "Adding"
win32net.NetLocalGroupAddMembers(serverName,"Users",3,data)
print "Added Successfully !!"

##

This is working piece of code. It worked for me, I needed to add newly
created user to the group called "Users".

Just replace "Users" with "Administrator".

I'll get back soon on how and when NetGroupAddUser() should be used.

Hope it helps...!
Jaimin Ajmeri


I think you're replying to a post that's more than 10 years old!

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


Re: What is \1 here?

2014-11-11 Thread Albert-Jan Roskam
- Original Message -
> From: Ned Batchelder 
> To: [email protected]
> Cc: 
> Sent: Tuesday, November 11, 2014 12:52 PM
> Subject: Re: What is \1 here?

 

 
> You need to learn how to find this stuff out for yourself. Ben Finney 
> even gave you a pointer to a helpful site for experimenting with 
> regexes: http://pythex.org/
 
Cool. I also like this one, which hardly anybody appears to use:

python C:\Python27\Tools\Scripts\redemo.py
 
The functionality is virtually the same.
-- 
https://mail.python.org/mailman/listinfo/python-list


Communicating with a PHP script (and pretending I'm a browser)

2014-11-11 Thread Larry Martell
I have a PHP app that I want to convert to django. But I want to do it
stages. All the heavy lifting is in the PHP code, so first, I want to
just use templates and views to generate the HTML, but still call the
PHP code. Then later convert the PHP to python.

My issue is that the PHP code expects to get all it's input from the
REQUEST object and I've consumed that in the view. Is there any way I
can somehow supply that to the PHP code?

Is there some way python can communicate like curl ... it needs to
send the request string in the body of a POST request to the URL that
will route to the PHP script and get the output back.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-11 Thread Chris Angelico
On Wed, Nov 12, 2014 at 2:48 AM, Larry Martell  wrote:
> Is there some way python can communicate like curl ... it needs to
> send the request string in the body of a POST request to the URL that
> will route to the PHP script and get the output back.

That is possible, but probably more effort than it's worth. It'll
likely be easier to just do the translation all at once.

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


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-11 Thread Marc Aymerich
On Tue, Nov 11, 2014 at 4:48 PM, Larry Martell  wrote:
>
> I have a PHP app that I want to convert to django. But I want to do it
> stages. All the heavy lifting is in the PHP code, so first, I want to
> just use templates and views to generate the HTML, but still call the
> PHP code. Then later convert the PHP to python.
>
> My issue is that the PHP code expects to get all it's input from the
> REQUEST object and I've consumed that in the view. Is there any way I
> can somehow supply that to the PHP code?
>
> Is there some way python can communicate like curl ... it needs to
> send the request string in the body of a POST request to the URL that
> will route to the PHP script and get the output back.


Yes,
I supose you can extract the needed information from the django
Request object and call the php script passing the needed variables as
environment state.

as a guideline you can do something like

cmd = (
'REDIRECT_STATUS=200 '
'REQUEST_METHOD=GET '
'SCRIPT_FILENAME=htdocs/index.php '
'SCRIPT_NAME=/index.php '
'PATH_INFO=/ '
'SERVER_NAME=site.tld '
'SERVER_PROTOCOL=HTTP/1.1 '
'REQUEST_URI=/nl/page '
'HTTP_HOST=site.tld '
'/usr/bin/php-cgi'
)
subprocess.Popen(cmd, stdout=subprocess.PIPE)



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


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-11 Thread Larry Martell
On Tue, Nov 11, 2014 at 10:54 AM, Chris Angelico  wrote:
> On Wed, Nov 12, 2014 at 2:48 AM, Larry Martell  
> wrote:
>> Is there some way python can communicate like curl ... it needs to
>> send the request string in the body of a POST request to the URL that
>> will route to the PHP script and get the output back.
>
> That is possible, but probably more effort than it's worth. It'll
> likely be easier to just do the translation all at once.

I would tend to agree, but that's not what my client wants. Also, it's
A LOT of PHP code so it does make some small amount of sense.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-11 Thread Larry Martell
On Tue, Nov 11, 2014 at 11:00 AM, Marc Aymerich  wrote:
> On Tue, Nov 11, 2014 at 4:48 PM, Larry Martell  
> wrote:
>>
>> I have a PHP app that I want to convert to django. But I want to do it
>> stages. All the heavy lifting is in the PHP code, so first, I want to
>> just use templates and views to generate the HTML, but still call the
>> PHP code. Then later convert the PHP to python.
>>
>> My issue is that the PHP code expects to get all it's input from the
>> REQUEST object and I've consumed that in the view. Is there any way I
>> can somehow supply that to the PHP code?
>>
>> Is there some way python can communicate like curl ... it needs to
>> send the request string in the body of a POST request to the URL that
>> will route to the PHP script and get the output back.
>
>
> Yes,
> I supose you can extract the needed information from the django
> Request object and call the php script passing the needed variables as
> environment state.
>
> as a guideline you can do something like
>
> cmd = (
> 'REDIRECT_STATUS=200 '
> 'REQUEST_METHOD=GET '
> 'SCRIPT_FILENAME=htdocs/index.php '
> 'SCRIPT_NAME=/index.php '
> 'PATH_INFO=/ '
> 'SERVER_NAME=site.tld '
> 'SERVER_PROTOCOL=HTTP/1.1 '
> 'REQUEST_URI=/nl/page '
> 'HTTP_HOST=site.tld '
> '/usr/bin/php-cgi'
> )
> subprocess.Popen(cmd, stdout=subprocess.PIPE)

Thanks very much Marc. In the example, how is the request string passed in?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-11 Thread Joel Goldstick
On Tue, Nov 11, 2014 at 11:37 AM, Larry Martell  wrote:
> On Tue, Nov 11, 2014 at 10:54 AM, Chris Angelico  wrote:
>> On Wed, Nov 12, 2014 at 2:48 AM, Larry Martell  
>> wrote:
>>> Is there some way python can communicate like curl ... it needs to
>>> send the request string in the body of a POST request to the URL that
>>> will route to the PHP script and get the output back.
>>
>> That is possible, but probably more effort than it's worth. It'll
>> likely be easier to just do the translation all at once.
>
> I would tend to agree, but that's not what my client wants. Also, it's
> A LOT of PHP code so it does make some small amount of sense.
> --
> https://mail.python.org/mailman/listinfo/python-list

Is your client technically savvy? If not, then what is he paying you
for? It sounds like he may be paying you to implement his bad idea.
Maybe you can outline a better approach that he can buy into

-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Problem with autopy and a specific app

2014-11-11 Thread Luis Roberto Romano
Hi.

I need to manipulate the mouse. I found the "autopy" package.
It's working perfectly with any application, except in one of them.
The software's name is: AVerMedia Capture Studio.

Did anybody use this module? Did anybody get any trouble with some app?

Thanks

-- 
--
Luis R. Romano

PS: here is my code:

http://pastebin.com/g6fqHsxS
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: locale.getlocale() in cmd.exe vs. Idle

2014-11-11 Thread random832


On Tue, Nov 11, 2014, at 09:47, Albert-Jan Roskam wrote:
> - Original Message -
> > From: Terry Reedy 
> > To: [email protected]
> > Cc: 
> > Sent: Monday, November 10, 2014 9:31 PM
> > Subject: Re: locale.getlocale() in cmd.exe vs. Idle
> > 
> > On 11/10/2014 4:22 AM, Albert-Jan Roskam wrote:
> >>  Hi,
> >> 
> >>  Why do I get different output for locale.getlocale() in Idle vs. cmd.exe?
> 
> 
> 
> > 
> > Idle runs code in an environment that is slightly altered from the 
> > standard python startup environment'.  idlelib.IOBinding has this
> > '''
> > # Try setting the locale, so that we can find out
> > # what encoding to use
> > try:
> >  import locale
> >  locale.setlocale(locale.LC_CTYPE, "")
> > '''
>  
> Hi Terry,
>  
> Thank you. Any idea why setlocale (a *setter*) returns something other
> than None?

setlocale returns the actual value that the locale was set to.


 (this question is not related to the (None, None) thing of
> getlocale, just curious). Would it be a good idea to put this setlocale
> line in site.py? Or should it be in __init__.py to make the code more
> portable?
> 
> > idlelib.run, which runs in the user-code subprocess, imports IOBinding. 
> > Setting LC_CTYPE is sufficient for getlocale() to not return null values.
> 
> So then I would have all the locale categories of the 'bare' locale
> (sorry, I don't know what else I should call it), except for LC_CTYPE,
> which is derived from my system. So in LC_NUMERIC I'd still have the
> en_US period/comma for decimal/thousand grouping, respectively, but I
> switch to the nl_NL LC_CTYPE. I doubt if it matters, but still: will this
> not introduce an ueber hard-to-find possible bug when I use re.LOCALE? 
>  
> > C:\Users\Terry>python -c "import locale; 
> > print(locale.getlocale())"
> > 
> > (None, None)
> > 
> > C:\Users\Terry>python -c "import locale; 
> > locale.setlocale(locale.LC_CTYPE, ''); print(locale.getlocale())"
> > ('English_United States', '1252')
>  
> What is the difference between getlocale and getdefaultlocale anyway? The
> docstrings are even partially the same. The notatation of getlocale
> appears to be OS-specific ("English_United States" in Windows) and not
> Unix-like (cf. getdefaultlocale: en_US)
>  
> regards,
> Albert-Jan
> -- 
> https://mail.python.org/mailman/listinfo/python-list


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


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-11 Thread Marc Aymerich
On Tue, Nov 11, 2014 at 5:43 PM, Larry Martell  wrote:
> On Tue, Nov 11, 2014 at 11:00 AM, Marc Aymerich  wrote:
>> On Tue, Nov 11, 2014 at 4:48 PM, Larry Martell  
>> wrote:
>>>
>>> I have a PHP app that I want to convert to django. But I want to do it
>>> stages. All the heavy lifting is in the PHP code, so first, I want to
>>> just use templates and views to generate the HTML, but still call the
>>> PHP code. Then later convert the PHP to python.
>>>
>>> My issue is that the PHP code expects to get all it's input from the
>>> REQUEST object and I've consumed that in the view. Is there any way I
>>> can somehow supply that to the PHP code?
>>>
>>> Is there some way python can communicate like curl ... it needs to
>>> send the request string in the body of a POST request to the URL that
>>> will route to the PHP script and get the output back.
>>
>>
>> Yes,
>> I supose you can extract the needed information from the django
>> Request object and call the php script passing the needed variables as
>> environment state.
>>
>> as a guideline you can do something like
>>
>> cmd = (
>> 'REDIRECT_STATUS=200 '
>> 'REQUEST_METHOD=GET '
>> 'SCRIPT_FILENAME=htdocs/index.php '
>> 'SCRIPT_NAME=/index.php '
>> 'PATH_INFO=/ '
>> 'SERVER_NAME=site.tld '
>> 'SERVER_PROTOCOL=HTTP/1.1 '
>> 'REQUEST_URI=/nl/page '
>> 'HTTP_HOST=site.tld '
>> '/usr/bin/php-cgi'
>> )
>> subprocess.Popen(cmd, stdout=subprocess.PIPE)
>
> Thanks very much Marc. In the example, how is the request string passed in?


Yeah, a more complete example would be

cmd = (
'REDIRECT_STATUS={status} '
'REQUEST_METHOD={method} '
'SCRIPT_FILENAME={file} '
'SCRIPT_NAME=/index.php '
'PATH_INFO={path} '
'SERVER_NAME=site.tld '
'SERVER_PROTOCOL=HTTP/1.1 '
'REQUEST_URI={path} '
'HTTP_HOST=site.tld '
'/usr/bin/php-cgi'
).format(
status=request.status,
method=request.method,
path=request.path,
file=my_php_path_mapper(request.path),
)

php = subprocess.Popen(cmd, stdout=subprocess.PIPE)
response, err = php.communicate()
if php.return_code != 0:
return ResponseError(content=err)
return Response(content=response)


still incomplete and mostly wrong, but good enough to illustrate the
main pattern :)


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


Re: locale.getlocale() in cmd.exe vs. Idle

2014-11-11 Thread random832


On Tue, Nov 11, 2014, at 09:47, Albert-Jan Roskam wrote:
> - Original Message -
> > From: Terry Reedy 
> > To: [email protected]
> > Cc: 
> > Sent: Monday, November 10, 2014 9:31 PM
> > Subject: Re: locale.getlocale() in cmd.exe vs. Idle
> > 
> > On 11/10/2014 4:22 AM, Albert-Jan Roskam wrote:
> >>  Hi,
> >> 
> >>  Why do I get different output for locale.getlocale() in Idle vs. cmd.exe?
> 
> 
> 
> > 
> > Idle runs code in an environment that is slightly altered from the 
> > standard python startup environment'.  idlelib.IOBinding has this
> > '''
> > # Try setting the locale, so that we can find out
> > # what encoding to use
> > try:
> >  import locale
> >  locale.setlocale(locale.LC_CTYPE, "")
> > '''
>  
> Hi Terry,
>  
> Thank you. Any idea why setlocale (a *setter*) returns something other
> than None?

setlocale returns the actual value that the locale was set to, which is
often (always in case of "") not the same as the value that was passed
in. The C function it is based on would return NULL on an error instead
of raising an exception.

>>> locale.setlocale(locale.LC_CTYPE,"")
'en_US.UTF-8'


 (this question is not related to the (None, None) thing of
> getlocale, just curious). Would it be a good idea to put this setlocale
> line in site.py? Or should it be in __init__.py to make the code more
> portable?
> 
> > idlelib.run, which runs in the user-code subprocess, imports IOBinding. 
> > Setting LC_CTYPE is sufficient for getlocale() to not return null values.
> 
> So then I would have all the locale categories of the 'bare' locale
> (sorry, I don't know what else I should call it), except for LC_CTYPE,
> which is derived from my system. So in LC_NUMERIC I'd still have the
> en_US period/comma for decimal/thousand grouping, respectively, but I
> switch to the nl_NL LC_CTYPE. I doubt if it matters, but still: will this
> not introduce an ueber hard-to-find possible bug when I use re.LOCALE? 
>  
> > C:\Users\Terry>python -c "import locale; 
> > print(locale.getlocale())"
> > 
> > (None, None)
> > 
> > C:\Users\Terry>python -c "import locale; 
> > locale.setlocale(locale.LC_CTYPE, ''); print(locale.getlocale())"
> > ('English_United States', '1252')
>  
> What is the difference between getlocale and getdefaultlocale anyway? The
> docstrings are even partially the same. The notatation of getlocale
> appears to be OS-specific ("English_United States" in Windows) and not
> Unix-like (cf. getdefaultlocale: en_US)
>  
> regards,
> Albert-Jan
> -- 
> https://mail.python.org/mailman/listinfo/python-list


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


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-11 Thread Larry Martell
On Tue, Nov 11, 2014 at 12:18 PM, Marc Aymerich  wrote:
> On Tue, Nov 11, 2014 at 5:43 PM, Larry Martell  
> wrote:
>> On Tue, Nov 11, 2014 at 11:00 AM, Marc Aymerich  wrote:
>>> On Tue, Nov 11, 2014 at 4:48 PM, Larry Martell  
>>> wrote:

 I have a PHP app that I want to convert to django. But I want to do it
 stages. All the heavy lifting is in the PHP code, so first, I want to
 just use templates and views to generate the HTML, but still call the
 PHP code. Then later convert the PHP to python.

 My issue is that the PHP code expects to get all it's input from the
 REQUEST object and I've consumed that in the view. Is there any way I
 can somehow supply that to the PHP code?

 Is there some way python can communicate like curl ... it needs to
 send the request string in the body of a POST request to the URL that
 will route to the PHP script and get the output back.
>>>
>>>
>>> Yes,
>>> I supose you can extract the needed information from the django
>>> Request object and call the php script passing the needed variables as
>>> environment state.
>>>
>>> as a guideline you can do something like
>>>
>>> cmd = (
>>> 'REDIRECT_STATUS=200 '
>>> 'REQUEST_METHOD=GET '
>>> 'SCRIPT_FILENAME=htdocs/index.php '
>>> 'SCRIPT_NAME=/index.php '
>>> 'PATH_INFO=/ '
>>> 'SERVER_NAME=site.tld '
>>> 'SERVER_PROTOCOL=HTTP/1.1 '
>>> 'REQUEST_URI=/nl/page '
>>> 'HTTP_HOST=site.tld '
>>> '/usr/bin/php-cgi'
>>> )
>>> subprocess.Popen(cmd, stdout=subprocess.PIPE)
>>
>> Thanks very much Marc. In the example, how is the request string passed in?
>
>
> Yeah, a more complete example would be
>
> cmd = (
> 'REDIRECT_STATUS={status} '
> 'REQUEST_METHOD={method} '
> 'SCRIPT_FILENAME={file} '
> 'SCRIPT_NAME=/index.php '
> 'PATH_INFO={path} '
> 'SERVER_NAME=site.tld '
> 'SERVER_PROTOCOL=HTTP/1.1 '
> 'REQUEST_URI={path} '
> 'HTTP_HOST=site.tld '
> '/usr/bin/php-cgi'
> ).format(
> status=request.status,
> method=request.method,
> path=request.path,
> file=my_php_path_mapper(request.path),
> )
>
> php = subprocess.Popen(cmd, stdout=subprocess.PIPE)
> response, err = php.communicate()
> if php.return_code != 0:
> return ResponseError(content=err)
> return Response(content=response)
>
>
> still incomplete and mostly wrong, but good enough to illustrate the
> main pattern :)


So I would put the contents of what I want in the request object in
the file request.path?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-11 Thread Larry Martell
On Tue, Nov 11, 2014 at 11:43 AM, Joel Goldstick
 wrote:
> On Tue, Nov 11, 2014 at 11:37 AM, Larry Martell  
> wrote:
>> On Tue, Nov 11, 2014 at 10:54 AM, Chris Angelico  wrote:
>>> On Wed, Nov 12, 2014 at 2:48 AM, Larry Martell  
>>> wrote:
 Is there some way python can communicate like curl ... it needs to
 send the request string in the body of a POST request to the URL that
 will route to the PHP script and get the output back.
>>>
>>> That is possible, but probably more effort than it's worth. It'll
>>> likely be easier to just do the translation all at once.
>>
>> I would tend to agree, but that's not what my client wants. Also, it's
>> A LOT of PHP code so it does make some small amount of sense.
>
> Is your client technically savvy? If not, then what is he paying you
> for? It sounds like he may be paying you to implement his bad idea.
> Maybe you can outline a better approach that he can buy into

They are technically savvy. They are a 100% PHP shop. They have a big,
complicated app that they've been working on for 10 years. No one
there knows python or django. They want to put some new frontends on
their app. I was bought in for another project (involving Google Tag
Manager and Google Analytics), which I completed. Then they asked me
about this project. I told them they should redo their app in Flask or
Django. It took some cajoling, but they eventually said OK. But then a
few days later they said before I went off and reimplemented
everything in python, could I just build the new frontend and call the
existing PHP code. This would enable them to get the new frontends out
to their clients sooner, and then I could go back and port the PHP to
python. I don't see what is so wrong with that.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-11 Thread Marc Aymerich
On Tue, Nov 11, 2014 at 6:26 PM, Larry Martell  wrote:
> On Tue, Nov 11, 2014 at 12:18 PM, Marc Aymerich  wrote:
>> On Tue, Nov 11, 2014 at 5:43 PM, Larry Martell  
>> wrote:
>>> On Tue, Nov 11, 2014 at 11:00 AM, Marc Aymerich  wrote:
 On Tue, Nov 11, 2014 at 4:48 PM, Larry Martell  
 wrote:
>
> I have a PHP app that I want to convert to django. But I want to do it
> stages. All the heavy lifting is in the PHP code, so first, I want to
> just use templates and views to generate the HTML, but still call the
> PHP code. Then later convert the PHP to python.
>
> My issue is that the PHP code expects to get all it's input from the
> REQUEST object and I've consumed that in the view. Is there any way I
> can somehow supply that to the PHP code?
>
> Is there some way python can communicate like curl ... it needs to
> send the request string in the body of a POST request to the URL that
> will route to the PHP script and get the output back.


 Yes,
 I supose you can extract the needed information from the django
 Request object and call the php script passing the needed variables as
 environment state.

 as a guideline you can do something like

 cmd = (
 'REDIRECT_STATUS=200 '
 'REQUEST_METHOD=GET '
 'SCRIPT_FILENAME=htdocs/index.php '
 'SCRIPT_NAME=/index.php '
 'PATH_INFO=/ '
 'SERVER_NAME=site.tld '
 'SERVER_PROTOCOL=HTTP/1.1 '
 'REQUEST_URI=/nl/page '
 'HTTP_HOST=site.tld '
 '/usr/bin/php-cgi'
 )
 subprocess.Popen(cmd, stdout=subprocess.PIPE)
>>>
>>> Thanks very much Marc. In the example, how is the request string passed in?
>>
>>
>> Yeah, a more complete example would be
>>
>> cmd = (
>> 'REDIRECT_STATUS={status} '
>> 'REQUEST_METHOD={method} '
>> 'SCRIPT_FILENAME={file} '
>> 'SCRIPT_NAME=/index.php '
>> 'PATH_INFO={path} '
>> 'SERVER_NAME=site.tld '
>> 'SERVER_PROTOCOL=HTTP/1.1 '
>> 'REQUEST_URI={path} '
>> 'HTTP_HOST=site.tld '
>> '/usr/bin/php-cgi'
>> ).format(
>> status=request.status,
>> method=request.method,
>> path=request.path,
>> file=my_php_path_mapper(request.path),
>> )
>>
>> php = subprocess.Popen(cmd, stdout=subprocess.PIPE)
>> response, err = php.communicate()
>> if php.return_code != 0:
>> return ResponseError(content=err)
>> return Response(content=response)
>>
>>
>> still incomplete and mostly wrong, but good enough to illustrate the
>> main pattern :)
>
>
> So I would put the contents of what I want in the request object in
> the file request.path?

I just invented the attribute names that django actually uses, but you
can look at the excellent django documentation for the correct ones

https://docs.djangoproject.com/en/dev/ref/request-response/

still this is a toy example and probably it would be a pain in the ass
to really map the mixed URLs between the two web applications.

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


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-11 Thread Larry Martell
On Tue, Nov 11, 2014 at 12:31 PM, Marc Aymerich  wrote:
> On Tue, Nov 11, 2014 at 6:26 PM, Larry Martell  
> wrote:
>> On Tue, Nov 11, 2014 at 12:18 PM, Marc Aymerich  wrote:
>>> On Tue, Nov 11, 2014 at 5:43 PM, Larry Martell  
>>> wrote:
 On Tue, Nov 11, 2014 at 11:00 AM, Marc Aymerich  
 wrote:
> On Tue, Nov 11, 2014 at 4:48 PM, Larry Martell  
> wrote:
>>
>> I have a PHP app that I want to convert to django. But I want to do it
>> stages. All the heavy lifting is in the PHP code, so first, I want to
>> just use templates and views to generate the HTML, but still call the
>> PHP code. Then later convert the PHP to python.
>>
>> My issue is that the PHP code expects to get all it's input from the
>> REQUEST object and I've consumed that in the view. Is there any way I
>> can somehow supply that to the PHP code?
>>
>> Is there some way python can communicate like curl ... it needs to
>> send the request string in the body of a POST request to the URL that
>> will route to the PHP script and get the output back.
>
>
> Yes,
> I supose you can extract the needed information from the django
> Request object and call the php script passing the needed variables as
> environment state.
>
> as a guideline you can do something like
>
> cmd = (
> 'REDIRECT_STATUS=200 '
> 'REQUEST_METHOD=GET '
> 'SCRIPT_FILENAME=htdocs/index.php '
> 'SCRIPT_NAME=/index.php '
> 'PATH_INFO=/ '
> 'SERVER_NAME=site.tld '
> 'SERVER_PROTOCOL=HTTP/1.1 '
> 'REQUEST_URI=/nl/page '
> 'HTTP_HOST=site.tld '
> '/usr/bin/php-cgi'
> )
> subprocess.Popen(cmd, stdout=subprocess.PIPE)

 Thanks very much Marc. In the example, how is the request string passed in?
>>>
>>>
>>> Yeah, a more complete example would be
>>>
>>> cmd = (
>>> 'REDIRECT_STATUS={status} '
>>> 'REQUEST_METHOD={method} '
>>> 'SCRIPT_FILENAME={file} '
>>> 'SCRIPT_NAME=/index.php '
>>> 'PATH_INFO={path} '
>>> 'SERVER_NAME=site.tld '
>>> 'SERVER_PROTOCOL=HTTP/1.1 '
>>> 'REQUEST_URI={path} '
>>> 'HTTP_HOST=site.tld '
>>> '/usr/bin/php-cgi'
>>> ).format(
>>> status=request.status,
>>> method=request.method,
>>> path=request.path,
>>> file=my_php_path_mapper(request.path),
>>> )
>>>
>>> php = subprocess.Popen(cmd, stdout=subprocess.PIPE)
>>> response, err = php.communicate()
>>> if php.return_code != 0:
>>> return ResponseError(content=err)
>>> return Response(content=response)
>>>
>>>
>>> still incomplete and mostly wrong, but good enough to illustrate the
>>> main pattern :)
>>
>>
>> So I would put the contents of what I want in the request object in
>> the file request.path?
>
> I just invented the attribute names that django actually uses, but you
> can look at the excellent django documentation for the correct ones
>
> https://docs.djangoproject.com/en/dev/ref/request-response/
>
> still this is a toy example and probably it would be a pain in the ass
> to really map the mixed URLs between the two web applications.


OK, I see what you're saying now. Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-11 Thread Denis McMahon
On Tue, 11 Nov 2014 10:48:41 -0500, Larry Martell wrote:

> Is there some way python can communicate like curl ... it needs to send
> the request string in the body of a POST request to the URL that will
> route to the PHP script and get the output back.

http://www.lmgtfy.com/?q=python+http+request

and perhaps

http://www.lmgtfy.com/?q=python+parse+html

Personally I think last time I wanted to do we scraping in python I used 
requests and beautifulsoup, but ymmv.

-- 
Denis McMahon, [email protected]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is ?s here?

2014-11-11 Thread Denis McMahon
On Tue, 11 Nov 2014 01:37:21 -0800, satishmlmlml wrote:

> What does ?s do in the following piece of code?

It tells you to learn about regex.

-- 
Denis McMahon, [email protected]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is \1 here?

2014-11-11 Thread Denis McMahon
On Tue, 11 Nov 2014 01:18:02 -0800, satishmlmlml wrote:

> What does \1 do in the following piece of code(fourth line)?

It tells you to learn about regex.

http://www.pcre.org/pcre.txt

-- 
Denis McMahon, [email protected]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is \1 here?

2014-11-11 Thread Mark Lawrence

On 11/11/2014 15:20, Albert-Jan Roskam wrote:

- Original Message -

From: Ned Batchelder 
To: [email protected]
Cc:
Sent: Tuesday, November 11, 2014 12:52 PM
Subject: Re: What is \1 here?






You need to learn how to find this stuff out for yourself. Ben Finney
even gave you a pointer to a helpful site for experimenting with
regexes: http://pythex.org/


Cool. I also like this one, which hardly anybody appears to use:

python C:\Python27\Tools\Scripts\redemo.py

The functionality is virtually the same.



FTR redemo.py has been removed from Python 3 at some point.

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

Mark Lawrence

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


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-11 Thread Ethan Furman

On 11/11/2014 09:30 AM, Larry Martell wrote:


They are technically savvy. They are a 100% PHP shop. They have a big,
complicated app that they've been working on for 10 years. No one
there knows python or django. They want to put some new frontends on
their app. I was bought in for another project (involving Google Tag
Manager and Google Analytics), which I completed. Then they asked me
about this project. I told them they should redo their app in Flask or
Django. It took some cajoling, but they eventually said OK. But then a
few days later they said before I went off and reimplemented
everything in python, could I just build the new frontend and call the
existing PHP code. This would enable them to get the new frontends out
to their clients sooner, and then I could go back and port the PHP to
python. I don't see what is so wrong with that.


Sounds like an excellent game plan to me.  :)

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


Re: "Natural" use of cmp= in sort

2014-11-11 Thread Ian Kelly
On Tue, Nov 11, 2014 at 2:21 AM, Paddy  wrote:
> On Tuesday, 11 November 2014 09:07:14 UTC, Ian  wrote:
>> On Tue, Nov 11, 2014 at 12:44 AM, Paddy  wrote:
>> > Thanks Ian. The original author states "...and it is sure that the given 
>> > inputs will give an output, i.e., the inputs will always be valid.", which 
>> > could be taken as meaning that all inputs are sufficient, well formed, and 
>> > contain all relations as their first example does.
>>
>> Well, I brought it up because the start of that sentence is "There can
>> be multiple inequalities as answer but I need any one which is
>> correct...". The only way there would be more than one correct answer
>> would be if the inputs were only partially ordered. I take the second
>> part of the sentence as meaning only that the input can be safely
>> assumed to be consistent.
>>
>> > Yes, I knew that there are cases where a cmp function is more natural than 
>> > key; the idea is to squirrel out a few. We have already made the, (well 
>> > reasoned in my opinion), decision to go down the key= route in Python 3. I 
>> > also like to track where my algorithms might originally map to cmp=. (It 
>> > is not often).
>>
>> Basically any time you have a comparison that isn't easily expressed
>> by mapping the values to some bunch of ordered objects.
>
> Yep. I want to track when this comes up for me and others during their normal 
> programming rather than in examples made to highlight the issue.

The example that I posted is one that I recall being brought up on
this list in the past, but I don't have a link for you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Advice

2014-11-11 Thread Mary-Frances McNamee
To whom it may concern,

I am currently working on a bit of coding for a raspberry pi, I was wondering 
maybe I could get some advice? I want my program to run for a certain time, for 
example 7am-2.30am everyday. Is this possible?

I would appreciate any help. Thank you for your time.


Regards
Mary-Frances

[cid:[email protected]]

Environmental Products & Services Ltd
Email: [email protected]
Tel: +44 (0) 28 30833081 Fax: +44 (0) 28 30257556
Address: 5 Shepherd's Drive, Carnbane Industrial Estate, Newry, Co. Down N. 
Ireland BT35 6JQ
Website | Brochure 
(PDF) | 
Videos | Product 
Pack

Company Registration No. N.I.34654
All Incoming and Outgoing emails are scanned using Sophos Anti-Virus - Ver 10.2

[cid:[email protected]]

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


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-11 Thread Joel Goldstick
On Tue, Nov 11, 2014 at 12:55 PM, Ethan Furman  wrote:
> On 11/11/2014 09:30 AM, Larry Martell wrote:
>>
>>
>> They are technically savvy. They are a 100% PHP shop. They have a big,
>> complicated app that they've been working on for 10 years. No one
>> there knows python or django. They want to put some new frontends on
>> their app. I was bought in for another project (involving Google Tag
>> Manager and Google Analytics), which I completed. Then they asked me
>> about this project. I told them they should redo their app in Flask or
>> Django. It took some cajoling, but they eventually said OK. But then a
>> few days later they said before I went off and reimplemented
>> everything in python, could I just build the new frontend and call the
>> existing PHP code. This would enable them to get the new frontends out
>> to their clients sooner, and then I could go back and port the PHP to
>> python. I don't see what is so wrong with that.
>
>

You obviously have thought this through.  It just raises red flags for me.

> Sounds like an excellent game plan to me.  :)
>
> --
> ~Ethan~
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Advice

2014-11-11 Thread Ian Kelly
On Tue, Nov 11, 2014 at 9:53 AM, Mary-Frances McNamee <
[email protected]> wrote:
>
> I am currently working on a bit of coding for a raspberry pi, I was
wondering maybe I could get some advice? I want my program to run for a
certain time, for example 7am-2.30am everyday. Is this possible?

You can set up a cron job to start your program every day at whatever time
you want: http://en.wikipedia.org/wiki/Cron

To shut down the program, have your program periodically check the time and
exit if the time is past the time you want to shut down. Exactly how you do
this would depend on how the program is structured.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Advice

2014-11-11 Thread Rob Gaddi
On Tue, 11 Nov 2014 16:53:18 +
Mary-Frances McNamee  wrote:

> To whom it may concern,
> 
> I am currently working on a bit of coding for a raspberry pi, I was wondering 
> maybe I could get some advice? I want my program to run for a certain time, 
> for example 7am-2.30am everyday. Is this possible?
> 
> I would appreciate any help. Thank you for your time.
> 
> 
> Regards
> Mary-Frances

Your keyword search is 'cron'.

-- 
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


I love assert

2014-11-11 Thread Peter Cacioppi
I get the impression that most Pythonistas aren't as habituated with assert 
statements as I am. Is that just a misimpression on my part? If not, is there a 
good reason to assert less with Python than other languages?

As far as I can tell, Python supports assert perfectly well. When run with the 
optimization flagging, the asserts are truly removed.

I think one needs to take care with some basic assert coding - it's not a 
substitute for unit tests, it doesn't absolve you of normal exception 
responsibilities, and, most of all, it should be used for passive inspection 
and not action. But given these guidelines, I still find it very useful as 
"active comments".

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


Re: What is rstrip() in python?

2014-11-11 Thread Will Acheson
On Sunday, November 9, 2014 6:12:24 AM UTC-5, [email protected] wrote:
> What is rstrip() in python?
> 
> What does it do in the following piece of code?
> 
> import sqlite3
> conn = sqlite3.connect('dbase1')
> curs = conn.cursor()
> 
> file = open('data.txt')
> rows = [line.rstrip().split(',') for line in file]

rstrip() removes whitespace, newline characters, tab characters, and carrige 
return characters (\n \t \r respectively) on the tail of a string.  

Or it can be used with an input parameter to remove all instances of that 
parameter from the tail of a string.

ex:
 stringy = "i am helpful  \t\t\t\t\n\n  "
 stringy = stringy.rstrip()
 print stringy

stdout: "i am helpful"

or:
 stringy = "my favorite number is 80"
 stringy = stringy.rstrip('0')
 print stringy

stdout: "my favorite number is 8"



pretty simple method, helpful for parsing out formatting characters from 
scraped content from webpages.
https://docs.python.org/2/library/stdtypes.html?highlight=rstrip#str.rstrip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-11 Thread Ben Finney
Peter Cacioppi  writes:

> I get the impression that most Pythonistas aren't as habituated with
> assert statements as I am. Is that just a misimpression on my part? If
> not, is there a good reason to assert less with Python than other
> languages?

I don't know about comparisons like “use less with Python than other
languages”. But I can explain why I don't use ‘assert’ much.

> As far as I can tell, Python supports assert perfectly well. When run
> with the optimization flagging, the asserts are truly removed.

Exactly. I prefer the code I write to have as few surprises as possible.
A reader familiar with Python should be able to read it and know what it
does; ideally, even if that reader doesn't recall every detail of how
Python operates.

An ‘assert’ statement in the code will sometimes be active, and
sometimes be a no-op, for *exactly* the same code under different
circumstances. That's a trap for the reader, and I'd rather not set it.

> I think one needs to take care with some basic assert coding - it's
> not a substitute for unit tests, it doesn't absolve you of normal
> exception responsibilities, and, most of all, it should be used for
> passive inspection and not action. But given these guidelines, I still
> find it very useful as "active comments".

It's fine for debugging code while developing. But, in my opinion, it
should never stay there, and should be removed before committing to VCS.

-- 
 \ “True greatness is measured by how much freedom you give to |
  `\  others, not by how much you can coerce others to do what you |
_o__)   want.” —Larry Wall |
Ben Finney

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


Re: Python script that does batch find and replace in txt files

2014-11-11 Thread Denis McMahon
On Sun, 09 Nov 2014 11:58:49 -0800, Syed Khalid wrote:

> Python script that does batch find and replace in txt files Need a
> python script that opens all .txt files in a folder find replace/delete
> text and save files.

Sounds like you need sed, not python.

-- 
Denis McMahon, [email protected]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-11 Thread Ethan Furman

On 11/11/2014 11:40 AM, Peter Cacioppi wrote:


I get the impression that most Pythonistas aren't as habituated with assert 
statements
 as I am. Is that just a misimpression on my part? If not, is there a good 
reason to
 assert less with Python than other languages?

As far as I can tell, Python supports assert perfectly well. When run with the 
optimization
 flagging, the asserts are truly removed.

I think one needs to take care with some basic assert coding - it's not a 
substitute for
 unit tests, it doesn't absolve you of normal exception responsibilities, and, 
most of all,
 it should be used for passive inspection and not action. But given these 
guidelines, I
 still find it very useful as "active comments".


asserts are a specialized tool, easily abused.  Sounds like you are using them 
exactly as intended.

The key question to ask (if one is curious whether one is using assert correctly) is:  if all the asserts are removed, 
and my programs gets bad data, will it keep going as if it had gotten good data?  Or, will it fail at the point it 
should have failed, or will it fail somewhere else?


--
~Ethan~

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


Re: Python modules

2014-11-11 Thread Will Acheson
On Sunday, November 9, 2014 11:51:41 PM UTC-5, Steve Hayes wrote:
> I have a book on Python that advocates dividing programs into modules, and
> importing them when needed. 
> 
> I have a question about this.
> 
> I can understand doing that in a compiled language, where different modules
> can be imported from all sorts of places when the program is compiled. 
> 
> But I understand that Python is an interpreted language, and If I wrote a
> program in Python like that, and wanted to run it on another computer, how
> would it find all the modules to import at run-time, unless I copied the whole
> directory structure over to the other computer?
> 
> 
> 
> 
> -- 
> Steve Hayes from Tshwane, South Africa
> Web:  http://www.khanya.org.za/stevesig.htm
> Blog: http://khanya.wordpress.com
> E-mail - see web page, or parse: shayes at dunelm full stop org full stop uk

I have had a lot of trouble with executing relative imports with some of my 
projects in python.  

Are there any best practices or methods besides '../../' type hard-coding?

In one project, a spider using scrapy, I used this method to import a module 
from 'the other side' of a file directory. 


spider_lib_path = os.path.realpath(os.path.dirname(__file__) + 
'/../../../../../library/python')
object_builder_printer = imp.load_source('object_builder_printer', 
spider_lib_path + '/object_builder_printer.py')
object_builder = object_builder_printer.object_builder_printer(settings)


the file structure was:

spiders/
-current/
--app/
---spiders/
scrapy/
-Charlotte/
--1.0/
---pipelines.py (the file that needs to import object_builder_printer.py)

--library/
---python/
object_builder_printer.py


I think the issue had something to do with there being duplicitous file names, 
as in, there are multiple directories named 'spiders'.




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


Re: I love assert

2014-11-11 Thread Rob Gaddi
On Tue, 11 Nov 2014 11:40:38 -0800 (PST)
Peter Cacioppi  wrote:

> I get the impression that most Pythonistas aren't as habituated with assert 
> statements as I am. Is that just a misimpression on my part? If not, is there 
> a good reason to assert less with Python than other languages?
> 
> As far as I can tell, Python supports assert perfectly well. When run with 
> the optimization flagging, the asserts are truly removed.
> 
> I think one needs to take care with some basic assert coding - it's not a 
> substitute for unit tests, it doesn't absolve you of normal exception 
> responsibilities, and, most of all, it should be used for passive inspection 
> and not action. But given these guidelines, I still find it very useful as 
> "active comments".
> 

I tend to be a big fan, but it is easy to forget about the one big rake
assert leaves in your lawn.  You CAN NOT use an assert with any
function that has a side effect or you break everything.

assert test_and_set(var)

That line there is pretty obvious about what's going on, but with the
ability to turn class data members transparently into properties, using
asserts safely actually requires a shocking amount of self-discipline.

assert obj.read_accesses < 10

-- 
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: I love assert

2014-11-11 Thread Mark Lawrence

On 11/11/2014 19:40, Peter Cacioppi wrote:

I get the impression that most Pythonistas aren't as habituated with assert 
statements as I am. Is that just a misimpression on my part? If not, is there a 
good reason to assert less with Python than other languages?

As far as I can tell, Python supports assert perfectly well. When run with the 
optimization flagging, the asserts are truly removed.

I think one needs to take care with some basic assert coding - it's not a substitute for 
unit tests, it doesn't absolve you of normal exception responsibilities, and, most of 
all, it should be used for passive inspection and not action. But given these guidelines, 
I still find it very useful as "active comments".



Please check this out 
https://mail.python.org/pipermail/python-list/2013-November/660401.html 
as it was released to critical acclaim :)


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

Mark Lawrence

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


Combining lists to dictionary

2014-11-11 Thread Denis McMahon
Hi

Given x,y are a lists of keys and value that I wish to combine to a 
dictionary, such that x[n] is the key for value y[n], which is preferred:

z = {a:b for (a,b) in zip(x,y)}
z = {x[n]:y[n] for n in range(min(len(x),len(y)))}

The zip feels more elegant, but it seems clunky to use the zip method to 
create a list of tuples just to split them up into key:value pairs. 
However the zip method handles the inequal length list problem. Granted 
it would probably be advisable to check that x and y are the same length 
before starting anyway.

-- 
Denis McMahon, [email protected]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-11 Thread TP
On Tue, Nov 11, 2014 at 11:40 AM, Peter Cacioppi 
wrote:

> I think one needs to take care with some basic assert coding - it's not a
> substitute for unit tests, it doesn't absolve you of normal exception
> responsibilities, and, most of all, it should be used for passive
> inspection and not action. But given these guidelines, I still find it very
> useful as "active comments".


I first came across asserts when using Wing IDE. See "Helping Wing Analyze
Code" [1] explains why using assert and isinstance will let Wing IDE
autocomplete things it otherwise couldn't.

PyCharm uses docstrings to accomplish the same task [2] but can also use
asserts/isinstance [3].

[1] https://wingware.com/doc/edit/helping-wing-analyze-code

[2] https://www.jetbrains.com/pycharm/webhelp/type-hinting-in-pycharm.html


[3]
http://stackoverflow.com/questions/9040387/is-there-a-way-to-explicitly-tell-pycharm-what-class-an-attribute-is-an-instance
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Combining lists to dictionary

2014-11-11 Thread Gary Herron

On 11/11/2014 12:43 PM, Denis McMahon wrote:

Hi

Given x,y are a lists of keys and value that I wish to combine to a
dictionary, such that x[n] is the key for value y[n], which is preferred:

z = {a:b for (a,b) in zip(x,y)}
z = {x[n]:y[n] for n in range(min(len(x),len(y)))}

The zip feels more elegant, but it seems clunky to use the zip method to
create a list of tuples just to split them up into key:value pairs.
However the zip method handles the inequal length list problem. Granted
it would probably be advisable to check that x and y are the same length
before starting anyway.



Are you using python 2 or 3.  (It ought to be 3 :-) .)

In Python3, zip does not create a list, but rather an iterator which 
returns tuples.  Not clunky at all, but rather an efficient 
implementation of the loop which you hand coded in your other example.


From help(zip):

class zip(object)
 |  zip(iter1 [,iter2 [...]]) --> zip object
 |
 |  Return a zip object whose .__next__() method returns a tuple where
 |  the i-th element comes from the i-th iterable argument.  The 
.__next__()

 |  method continues until the shortest iterable in the argument sequence
 |  is exhausted and then it raises StopIteration.

...


Gary Herron


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

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


Re: I love assert

2014-11-11 Thread Albert-Jan Roskam


- Original Message -

> From: Ethan Furman 
> To: [email protected]
> Cc: 
> Sent: Tuesday, November 11, 2014 9:08 PM
> Subject: Re: I love assert
> 
> On 11/11/2014 11:40 AM, Peter Cacioppi wrote:
>> 
>>  I get the impression that most Pythonistas aren't as habituated with 
> assert statements
>>   as I am. Is that just a misimpression on my part? If not, is there a good 
> reason to
>>   assert less with Python than other languages?
>> 
>>  As far as I can tell, Python supports assert perfectly well. When run with 
> the optimization
>>   flagging, the asserts are truly removed.
>> 
>>  I think one needs to take care with some basic assert coding - it's not 
> a substitute for
>>   unit tests, it doesn't absolve you of normal exception 
> responsibilities, and, most of all,
>>   it should be used for passive inspection and not action. But given these 
> guidelines, I
>>   still find it very useful as "active comments".
> 
> asserts are a specialized tool, easily abused.  Sounds like you are using 
> them 
> exactly as intended.


Would you say that assert is baaadly abused in nose?*) I never tried it, but 
probably all tests pass when Python is run with -O or -OO.

*) Actually, I love that package. Much cleaner than unittest.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-11 Thread Ethan Furman

On 11/11/2014 01:09 PM, Albert-Jan Roskam wrote:

Ethan Furman wrote:


asserts are a specialized tool, easily abused.  Sounds like you are using them
exactly as intended.


Would you say that assert is baaadly abused in nose?*) I never tried it, but
 probably all tests pass when Python is run with -O or -OO.


I don't know, haven't used it nor read the code.  It would certainly not be 
good if it failed in optimized mode.

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


PDF Library with full CSS3 Support

2014-11-11 Thread mojo
Looking for a Python PDF Generation library that supports CSS3.  Suggestions?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Combining lists to dictionary

2014-11-11 Thread Rob Gaddi
On Tue, 11 Nov 2014 20:43:01 + (UTC)
Denis McMahon  wrote:

> Hi
> 
> Given x,y are a lists of keys and value that I wish to combine to a 
> dictionary, such that x[n] is the key for value y[n], which is preferred:
> 
> z = {a:b for (a,b) in zip(x,y)}
> z = {x[n]:y[n] for n in range(min(len(x),len(y)))}
> 
> The zip feels more elegant, but it seems clunky to use the zip method to 
> create a list of tuples just to split them up into key:value pairs. 
> However the zip method handles the inequal length list problem. Granted 
> it would probably be advisable to check that x and y are the same length 
> before starting anyway.
> 
> -- 
> Denis McMahon, [email protected]

To add to what Gary said, the explicit dict() init knows how to handle
an iterable that emits pairs of data.  So you can simplify further down to:

z = dict(zip(x, y))

If you're running Python2, and really that concerned about the extra
memory used by zip returning a list rather than an iterator, you can
use itertools.izip

-- 
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: I love assert

2014-11-11 Thread Grant Edwards
On 2014-11-11, Ben Finney  wrote:

> An ‘assert’ statement in the code will sometimes be active, and
> sometimes be a no-op, for *exactly* the same code under different
> circumstances.

Yep, it's the same in C, C++, Java, PHP, and other languages.  I think
most people know that asserts can be disabled (either at run-time or
compile time), and often are for performance reasons.

> That's a trap for the reader, and I'd rather not set it.

Personally, I find that too many asserts often makes code hard to read
just because of the visual clutter and the veritical "spread" it
induces.

-- 
Grant Edwards   grant.b.edwardsYow! I hope I bought the
  at   right relish ... z
  gmail.com...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-11 Thread Albert-Jan Roskam


- Original Message -

> From: Ethan Furman 
> To: Albert-Jan Roskam 
> Cc: "[email protected]" 
> Sent: Tuesday, November 11, 2014 10:15 PM
> Subject: Re: I love assert
> 
> On 11/11/2014 01:09 PM, Albert-Jan Roskam wrote:
>>  Ethan Furman wrote:
>>> 
>>>  asserts are a specialized tool, easily abused.  Sounds like you are 
> using them
>>>  exactly as intended.
>> 
>>  Would you say that assert is baaadly abused in nose?*) I never tried it, 
> but
>>   probably all tests pass when Python is run with -O or -OO.
> 
> I don't know, haven't used it nor read the code.  It would certainly not 
> be good if it failed in optimized mode.


antonia@antonia-HP-2133 /tmp $ cat test.py
def test_func_1():
assert 1 == 2

def test_func_2():
x = 1; y = 2
assert x == y

if __name__ == "__main__":
import nose
nose.main()


antonia@antonia-HP-2133 /tmp $ python -O test.py
..
--
Ran 2 tests in 0.015s

OK

antonia@antonia-HP-2133 /tmp $ python -O -m nose test.py
..
--
Ran 2 tests in 0.003s

OK


antonia@antonia-HP-2133 /tmp $ python test.py
FF
==
FAIL: test.test_func_1
--
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/tmp/test.py", line 2, in test_func_1
assert 1 == 2
AssertionError

==
FAIL: test.test_func_2
--
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/tmp/test.py", line 6, in test_func_2
assert x == y
AssertionError

--
Ran 2 tests in 0.044s

FAILED (failures=2)

antonia@antonia-HP-2133 /tmp $ python -m nose test.py
... (same as previous)


antonia@antonia-HP-2133 /tmp $ nosetests -O -v test.py   
Usage: nosetests [options]

nosetests: error: no such option: -O   # phweeew
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-11 Thread Chris Angelico
On Wed, Nov 12, 2014 at 4:55 AM, Ethan Furman  wrote:
> On 11/11/2014 09:30 AM, Larry Martell wrote:
>>
>>
>> They are technically savvy. They are a 100% PHP shop. They have a big,
>> complicated app that they've been working on for 10 years. No one
>> there knows python or django. They want to put some new frontends on
>> their app. I was bought in for another project (involving Google Tag
>> Manager and Google Analytics), which I completed. Then they asked me
>> about this project. I told them they should redo their app in Flask or
>> Django. It took some cajoling, but they eventually said OK. But then a
>> few days later they said before I went off and reimplemented
>> everything in python, could I just build the new frontend and call the
>> existing PHP code. This would enable them to get the new frontends out
>> to their clients sooner, and then I could go back and port the PHP to
>> python. I don't see what is so wrong with that.
>
>
> Sounds like an excellent game plan to me.  :)

I wouldn't go so far as "excellent", but certainly it's not
nonsensical. It's just a question of balancing the cost of the
hybridization (development effort that, once the Python rewrite is
complete, will be discarded) against the time gain of getting
*something* sooner. Also, this will probably have a significant impact
on performance/throughput, so everyone needs to be aware that
benchmarking Python by looking at the new app's performance would be
horribly unfair. But this is a viable proposal.

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


Re: Python modules

2014-11-11 Thread Ben Finney
Will Acheson  writes:


> I have had a lot of trouble with executing relative imports with some
> of my projects in python.
>
> Are there any best practices or methods besides '../../' type
> hard-coding?

The important point to learn with Python's import system, as contrasted
with various other languages, is that it is *intentionally* abstracted
from the filesystem hierarchy.

That allows all kinds of helpful infrastructure, but it also comes with
the cost of learning how to let Python know where modules are to be
imported from; it's not a simple case of stating filesystem locations.

The point which tripped me up for a long time, and which I have to keep
reminding myself of:


Python looks for modules in its import search path. Corollary: structure
your project into a hierarchy of packages, including the top level, and
specify all relative imports starting at that top-level package.


Often the cause of my intra-project import woes comes from having
several *discrete* packages, but trying to do relative imports between
them::

hurgen/# Note: ‘hurgen’ is not a Python package.
foo/
__init__.py
spam.py
beans.py
bar/
__init__.py
eggs.py
ham.py

This is a poor structure, because Python needs to be told about each of
‘foo’ and ‘bar’ separately if relative imports are to work. Worse, a
module invoked as the top-level module (e.g. ‘eggs.py’) can't do imports
relative to itself, because it isn't even aware it's in a package!

Better is to structure the project explicitly under a top-level named
Python package::

hurgen/
__init__.py
foo/
__init__.py
spam.py
beans.py
bar/
__init__.py
eggs.py
ham.py

and import all the project's modules relative to the ‘hurgen’ package.

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


Re: I love assert

2014-11-11 Thread Terry Reedy

On 11/11/2014 2:40 PM, Peter Cacioppi wrote:

I get the impression that most Pythonistas aren't as habituated with
assert statements as I am. Is that just a misimpression on my part?
If not, is there a good reason to assert less with Python than other
languages?


We love 'assert' so much that we have 20-30 'assertXYZ' variations in 
unittest.  The statement 'assert expression' is almost equivalent to


if not expression: raise AssertionError('expression')

We have perhaps 100 mostly more specialized exceptions builtin and in 
the stdlib.  There is nearly always a better, more specific exception 
and error message.



As far as I can tell, Python supports assert perfectly well. When run
with the optimization flagging, the asserts are truly removed.


Separating tests from main code removes test asserts from the main code. 
 Removal by -0 relegates bare assert to specialized usage.



I think one needs to take care with some basic assert coding - it's
not a substitute for unit tests, it doesn't absolve you of normal
exception responsibilities, and, most of all, it should be used for
passive inspection and not action. But given these guidelines, I
still find it very useful as "active comments".


How much usage depends considerably on the programmer.

--
Terry Jan Reedy

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


Re: I love assert

2014-11-11 Thread Ben Finney
Terry Reedy  writes:

> We love 'assert' so much that we have 20-30 'assertXYZ' variations in
> unittest.

A function will not be disabled by a run-time option to the Python
interpreter.

> The statement 'assert expression' is almost equivalent to
>
> if not expression: raise AssertionError('expression')

With the important difference that this will be active no matter what
options Python's interpreter is run with. That makes it quite a
different proposition from using ‘assert’ statements.

-- 
 \ “You don't need a book of any description to help you have some |
  `\kind of moral awareness.” —Dr. Francesca Stavrakoloulou, bible |
_o__)  scholar, 2011-05-08 |
Ben Finney

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


Re: I love assert

2014-11-11 Thread Tim Chase
On 2014-11-11 11:40, Peter Cacioppi wrote:
> I get the impression that most Pythonistas aren't as habituated
> with assert statements as I am. Is that just a misimpression on my
> part?

I tend to use it to catch my bone-headedness rather than actual
tests.  I'm particularly fond of one that catches me typing
"obj.exceptions" rather than "obj.exemptions" (both are common and
occasionally interchangeable terms in $DAYJOB) something along the
lines of

  assert hasattr(obj, "exceptions"), "idiot programmer"

-tkc



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


Re: I love assert

2014-11-11 Thread Peter Cacioppi
On Tue, Nov 11, 2014 at 12:57 PM, TP  wrote:

> On Tue, Nov 11, 2014 at 11:40 AM, Peter Cacioppi  > wrote:
>
>> I think one needs to take care with some basic assert coding - it's not a
>> substitute for unit tests, it doesn't absolve you of normal exception
>> responsibilities, and, most of all, it should be used for passive
>> inspection and not action. But given these guidelines, I still find it very
>> useful as "active comments".
>
>
> I first came across asserts when using Wing IDE. See "Helping Wing Analyze
> Code" [1] explains why using assert and isinstance will let Wing IDE
> autocomplete things it otherwise couldn't.
>
> PyCharm uses docstrings to accomplish the same task [2] but can also use
> asserts/isinstance [3].
>
> [1] https://wingware.com/doc/edit/helping-wing-analyze-code
>
> [2] https://www.jetbrains.com/pycharm/webhelp/type-hinting-in-pycharm.html
> 
>
> [3]
> http://stackoverflow.com/questions/9040387/is-there-a-way-to-explicitly-tell-pycharm-what-class-an-attribute-is-an-instance
>
>
I use PyCharm. Thanks for [2], it's a keeper
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-11 Thread Ethan Furman

On 11/11/2014 03:02 PM, Peter Cacioppi wrote:

On Tue, Nov 11, 2014 at 12:57 PM, TP wrote:


PyCharm uses docstrings to accomplish the same task [2] but can also use 
asserts/isinstance [3].

[2] https://www.jetbrains.com/pycharm/webhelp/type-hinting-in-pycharm.html



I use PyCharm. Thanks for [2], it's a keeper


Please, please don't use isinstance when you don't need to.  It just makes your code unusable to anybody who wants/needs 
to use a different-yet-compatible type than the one you checked for.


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


pip Install errors for bcrypt on OSX 10.10 Yosemite

2014-11-11 Thread Michael Weems
$ sudo pip install bcrypt
Downloading/unpacking bcrypt
  Downloading bcrypt-1.0.2.tar.gz (40kB): 40kB downloaded
  Running setup.py (path:/private/tmp/pip_build_root/bcrypt/setup.py) egg_info 
for package bcrypt
Package libffi was not found in the pkg-config search path.
Perhaps you should add the directory containing `libffi.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libffi' found
Package libffi was not found in the pkg-config search path.
Perhaps you should add the directory containing `libffi.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libffi' found
Package libffi was not found in the pkg-config search path.
Perhaps you should add the directory containing `libffi.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libffi' found
Package libffi was not found in the pkg-config search path.
Perhaps you should add the directory containing `libffi.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libffi' found
Package libffi was not found in the pkg-config search path.
Perhaps you should add the directory containing `libffi.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libffi' found
c/_cffi_backend.c:13:10: fatal error: 'ffi.h' file not found
#include 
 ^
1 error generated.
Traceback (most recent call last):
  File "", line 17, in 
  File "/private/tmp/pip_build_root/bcrypt/setup.py", line 104, in 
"Programming Language :: Python :: 3.3",
  File 
"/usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py",
 line 111, in setup
_setup_distribution = dist = klass(attrs)
  File "build/bdist.macosx-10.10-x86_64/egg/setuptools/dist.py", line 262, 
in __init__
  File "build/bdist.macosx-10.10-x86_64/egg/setuptools/dist.py", line 287, 
in fetch_build_eggs
  File "build/bdist.macosx-10.10-x86_64/egg/pkg_resources.py", line 631, in 
resolve
  File "build/bdist.macosx-10.10-x86_64/egg/pkg_resources.py", line 874, in 
best_match
  File "build/bdist.macosx-10.10-x86_64/egg/pkg_resources.py", line 886, in 
obtain
  File "build/bdist.macosx-10.10-x86_64/egg/setuptools/dist.py", line 338, 
in fetch_build_egg
  File 
"build/bdist.macosx-10.10-x86_64/egg/setuptools/command/easy_install.py", line 
613, in easy_install
  File 
"build/bdist.macosx-10.10-x86_64/egg/setuptools/command/easy_install.py", line 
643, in install_item
  File 
"build/bdist.macosx-10.10-x86_64/egg/setuptools/command/easy_install.py", line 
833, in install_eggs
  File 
"build/bdist.macosx-10.10-x86_64/egg/setuptools/command/easy_install.py", line 
1055, in build_and_install
  File 
"build/bdist.macosx-10.10-x86_64/egg/setuptools/command/easy_install.py", line 
1043, in run_setup
distutils.errors.DistutilsError: Setup script exited with error: command 
'clang' failed with exit status 1
Complete output from command python setup.py egg_info:
Package libffi was not found in the pkg-config search path.

Perhaps you should add the directory containing `libffi.pc'

to the PKG_CONFIG_PATH environment variable

No package 'libffi' found

Package libffi was not found in the pkg-config search path.

Perhaps you should add the directory containing `libffi.pc'

to the PKG_CONFIG_PATH environment variable

No package 'libffi' found

Package libffi was not found in the pkg-config search path.

Perhaps you should add the directory containing `libffi.pc'

to the PKG_CONFIG_PATH environment variable

No package 'libffi' found

Package libffi was not found in the pkg-config search path.

Perhaps you should add the directory containing `libffi.pc'

to the PKG_CONFIG_PATH environment variable

No package 'libffi' found

Package libffi was not found in the pkg-config search path.

Perhaps you should add the directory containing `libffi.pc'

to the PKG_CONFIG_PATH environment variable

No package 'libffi' found

c/_cffi_backend.c:13:10: fatal error: 'ffi.h' file not found

#include 

 ^

1 error generated.

Traceback (most recent call last):

  File "", line 17, in 

  File "/private/tmp/pip_build_root/bcrypt/setup.py", line 104, in 

"Programming Language :: Python :: 3.3",

  File 
"/usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py",
 line 111, in setup

_setup_distribution = dist = klass(attrs)

  File "build/bdist.macosx-10.10-x86_64/egg/setuptools/dist.py", line 262, in 
__init__

  File "build/bdist.macosx-10.10-x86_64/egg/setuptools/dist.py", line 287, in 
fetch_build_eggs

  File "build/bdist.macosx-10.10-x86_64/egg/pkg_resources.py", line 631, in 
resolve

  File "build/bdist.macosx-10.10-x86_64/egg/pkg_resources.py", line 874, in 
best_match

  File "build/bdist.macosx-10.10-x86_64/egg/pkg_resources.py", line 886, in 
obtain

  File "build/bdist.macosx-10.10-x86_64/egg/setuptools/dist.py", line 338, 

html page mail link to webmail program

2014-11-11 Thread Ethan Furman

Just in case that subject line is not perfectly clear:  ;)

My wife (using a Win7 machine) will be on a web page that has a link to mail somebody.  She clicks on it, and it opens 
the currently installed but unused Thunderbird.


Ideally, what would happen is a new window/tab would open to gmail with a new compose window with the email address in 
place and the cursor in the subject line.


Is this already done somewhere?  If not, any ideas on which libs/packages to 
use to make it happen?

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


Re: html page mail link to webmail program

2014-11-11 Thread Ben Finney
Ethan Furman  writes:

> My wife (using a Win7 machine) will be on a web page that has a link
> to mail somebody.  She clicks on it, and it opens the currently
> installed but unused Thunderbird.
>
> Ideally, what would happen is a new window/tab would open to gmail
> with a new compose window with the email address in place and the
> cursor in the subject line.

What is the Python question? I can't see anywhere that you would be
using Python code to address this.

-- 
 \“Some people, when confronted with a problem, think ‘I know, |
  `\   I'll use regular expressions’. Now they have two problems.” |
_o__)   —Jamie Zawinski, in alt.religion.emacs |
Ben Finney

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


Re: Combining lists to dictionary

2014-11-11 Thread Roy Smith
In article ,
 Denis McMahon  wrote:

> Hi
> 
> Given x,y are a lists of keys and value that I wish to combine to a 
> dictionary, such that x[n] is the key for value y[n], which is preferred:
> 
> z = {a:b for (a,b) in zip(x,y)}
> z = {x[n]:y[n] for n in range(min(len(x),len(y)))}
> 
> The zip feels more elegant, but it seems clunky to use the zip method to 
> create a list of tuples just to split them up into key:value pairs.

I would definitely use the first one.  It's so much easier to read.  If 
I was worried that the lists might be so long that the cost of building 
the intermediate list mattered, I'd use izip() instead of zip().
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Combining lists to dictionary

2014-11-11 Thread Ben Finney
Denis McMahon  writes:

> Hi
>
> Given x,y are a lists of keys and value that I wish to combine to a 
> dictionary, such that x[n] is the key for value y[n], which is preferred:
>
> z = {a:b for (a,b) in zip(x,y)}

This one, with the caveat to use PEP-8 compatible formatting::

z = {a: b for (a, b) in zip(x, y)}

> z = {x[n]:y[n] for n in range(min(len(x),len(y)))}

Too much indirection for no gain that I can see.

> The zip feels more elegant, but it seems clunky to use the zip method to 
> create a list of tuples just to split them up into key:value pairs.

I think ‘zip’ has this as a primary intended purpose, so it seems fine
to me.

-- 
 \ “Of all classes the rich are the most noticed and the least |
  `\  studied.” —John Kenneth Galbraith, _The Age of Uncertainty_, |
_o__) 1977 |
Ben Finney

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


Re: I love assert

2014-11-11 Thread Ethan Furman

On 11/11/2014 01:46 PM, Albert-Jan Roskam wrote:

Ethan Furman wrote:


I don't know, haven't used it nor read the code.  It would certainly not
be good if it failed in optimized mode.


antonia@antonia-HP-2133 /tmp $ python -O test.py
Ran 2 tests in 0.015s
OK

antonia@antonia-HP-2133 /tmp $ python -O -m nose test.py
Ran 2 tests in 0.003s
OK

antonia@antonia-HP-2133 /tmp $ python test.py
Ran 2 tests in 0.044s
FAILED (failures=2)

antonia@antonia-HP-2133 /tmp $ python -m nose test.py
Ran 2 tests in 0.044s
FAILED (failures=2)

antonia@antonia-HP-2133 /tmp $ nosetests -O -v test.py
Usage: nosetests [options]

nosetests: error: no such option: -O   # phweeew


In other words, nose the module doesn't handle optimized mode, and apparently 
nosetests cannot run in optimized mode.

On the other hand, unittest:
--
from unittest import TestCase, main

class TestTest(TestCase):
def test_optimized(self):
self.assertTrue(1 == 2)

if __name__ == '__main__':
main()
--

ethan@media:~/source$ python3.4 test.py
Ran 1 test in 0.001s
FAILED (failures=1)

ethan@media:~/source$ python3.4 -O test.py
Ran 1 test in 0.001s
FAILED (failures=1)


I'll stick with unittest.

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


Re: html page mail link to webmail program

2014-11-11 Thread Ethan Furman

On 11/11/2014 05:08 PM, Ben Finney wrote:

Ethan Furman  writes:


My wife (using a Win7 machine) will be on a web page that has a link
to mail somebody.  She clicks on it, and it opens the currently
installed but unused Thunderbird.

Ideally, what would happen is a new window/tab would open to gmail
with a new compose window with the email address in place and the
cursor in the subject line.


What is the Python question? I can't see anywhere that you would be
using Python code to address this.


Really?  Huh.

Okay, the explicit Python question:  Clicking on a mail link in a web browser can start an external program.  I would 
like that external program to be a Python script that: opens a new tab in the currently running browser (or a new 
default browser window), loads up the default web mail client (or one specified if there is no way to know/have a 
default), navigates to the compose pane (or starts there if possible), enters in the email address from the link that 
was passed to it, and, if not too much more, move the cursor to the subject field.


Surely this can be done in Python.

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


Re: html page mail link to webmail program

2014-11-11 Thread Ben Finney
Ethan Furman  writes:

> Okay, the explicit Python question: Clicking on a mail link in a web
> browser can start an external program. I would like that external
> program to be a Python script that [controls an already-running web
> browser to visit a URL and operate a web application].
>
> Surely this can be done in Python.

Perhaps. I'd advise a web search for “python script web browser”, and be
prepared for also learning how your specific operating system allows
programs to control each other in separate processes.

-- 
 \   “Either he's dead or my watch has stopped.” —Groucho Marx |
  `\   |
_o__)  |
Ben Finney

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


Re: I love assert

2014-11-11 Thread Dan Stromberg
On Tue, Nov 11, 2014 at 11:40 AM, Peter Cacioppi
 wrote:
> I get the impression that most Pythonistas aren't as habituated with assert 
> statements as I am. Is that just a misimpression on my part? If not, is there 
> a good reason to assert less with Python than other languages?
>
> As far as I can tell, Python supports assert perfectly well. When run with 
> the optimization flagging, the asserts are truly removed.
>
> I think one needs to take care with some basic assert coding - it's not a 
> substitute for unit tests, it doesn't absolve you of normal exception 
> responsibilities, and, most of all, it should be used for passive inspection 
> and not action. But given these guidelines, I still find it very useful as 
> "active comments".

assert is terrific (stops bugs in their tracks), though many things
should be done with more targeted exceptions.

I guess you could do a survey.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-11 Thread Chris Angelico
On Wed, Nov 12, 2014 at 7:03 AM, Ben Finney  wrote:
> An ‘assert’ statement in the code will sometimes be active, and
> sometimes be a no-op, for *exactly* the same code under different
> circumstances. That's a trap for the reader, and I'd rather not set it.

This is no worse than other forms of preprocessor magic. I've seen
this kind of thing in plenty of C projects:

#ifdef DEBUG_MODE
#define DEBUG print
#else
#define DEBUG(...)
#endif

... further down ...
DEBUG("We're here: %d:%d", foo, bar);

If you're not in debug mode, this won't be evaluated. You can have
"active code" inside its args if you want to, but only if it's
exclusively part of the debugging output:

DEBUG("We've hit this line %d times", ++hitcount);

Again, not materially different from assert, and plenty of projects
have this. Maybe people just need to understand "assert == DEBUG" and
all's clear?

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


Re: html page mail link to webmail program

2014-11-11 Thread Chris Angelico
On Wed, Nov 12, 2014 at 12:42 PM, Ben Finney  wrote:
> Ethan Furman  writes:
>
>> Okay, the explicit Python question: Clicking on a mail link in a web
>> browser can start an external program. I would like that external
>> program to be a Python script that [controls an already-running web
>> browser to visit a URL and operate a web application].
>>
>> Surely this can be done in Python.
>
> Perhaps. I'd advise a web search for “python script web browser”, and be
> prepared for also learning how your specific operating system allows
> programs to control each other in separate processes.

Or just look at antigravity.py in the standard library, which has a
way of invoking a web browser - probably something trivially easy,
like calling on the webbrowser module, but it's more fun to look it up
via the arcane.

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


Re: I love assert

2014-11-11 Thread Ben Finney
Chris Angelico  writes:

> On Wed, Nov 12, 2014 at 7:03 AM, Ben Finney  
> wrote:
> > An ‘assert’ statement in the code will sometimes be active, and
> > sometimes be a no-op, for *exactly* the same code under different
> > circumstances. That's a trap for the reader, and I'd rather not set
> > it.
>
> This is no worse than other forms of preprocessor magic.

That other languages do it doesn't argue in favour of it. It argues,
rather, that we should be glad not to have it in our Python code.

> Again, not materially different from assert, and plenty of projects
> have this. Maybe people just need to understand "assert == DEBUG" and
> all's clear?

The more things people need to keep in mind when reading my code that
isn't stated explicitly in the code, the worse I consider the code to
be.

Python is a small, clear, expressive language. It has the valuable
property that one does not need to keep in mind a lot of reminders of
unexpected behaviour; good Python code behaves as it explicitly says it
will, with very few implied surprises.

To preserve this valuable but fragile property, I recommend treating
‘assert’ as a clever but obfuscatory trick, opposed to that property of
Python. So an ‘assert’ statement should, IMO, not remain in the code
past a debugging session.

-- 
 \  “The entertainment industry calls DRM "security" software, |
  `\ because it makes them secure from their customers.” —Cory |
_o__) Doctorow, 2014-02-05 |
Ben Finney

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


Re: I love assert

2014-11-11 Thread Chris Angelico
On Wed, Nov 12, 2014 at 1:35 PM, Ben Finney  wrote:
> The more things people need to keep in mind when reading my code that
> isn't stated explicitly in the code, the worse I consider the code to
> be.

Then the ternary if/else operator should also be abolished.

track["APIC:"].data if "APIC:" in track else None

(With PEP 463, this would be:
track["APIC:"].data except KeyError: None
But this is from Python 2.7 code, so that was never going to happen anyway.)

When you read the if/else version, you need to remember that it's
evaluated middle-to-outside rather than outside-to-inside, and more
importantly, that the first expression won't be evaluated at all if
the key isn't present. So should we treat if/else as a "clever but
obfuscatory trick, opposed to that property of Python" too? Or should
people just get to know the language they're using? At least with
'assert', it's consistent across all Python programs; with my DEBUG
example, it's per-project, as it's custom crafted.

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


Re: Combining lists to dictionary

2014-11-11 Thread Dave Angel
Ben Finney  Wrote in message:
> Denis McMahon  writes:
> 
>> Hi
>>
>> Given x,y are a lists of keys and value that I wish to combine to a 
>> dictionary, such that x[n] is the key for value y[n], which is preferred:
>>
>> z = {a:b for (a,b) in zip(x,y)}
> 
> This one, with the caveat to use PEP-8 compatible formatting::
> 
> z = {a: b for (a, b) in zip(x, y)}

Or just z = dict(zip (x, y))
> 



-- 
DaveA

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