Re: [Tutor] Error terminal

2019-08-07 Thread Mats Wichmann
On 8/7/19 5:27 PM, Richard Rizk wrote:
> Thank you Cameron for your message.
> 
> Please find below the error message i am receiving.
> 
> I think the command line i'm running is trying to connect with the
> python3.7 that i have on my computer which is a requirement for the command
> line to work but it keeps connecting to the default python2.7 that is on
> Macbook.
> 
> I'd love to jump on a 15min call if  it's possible for you.
> 
> Best regards,
> Richard
> 
> Error:
> -
> 
> DEPRECATION: Python 2.7 will reach the end of its life on January 1st,
> 2020. Please upgrade your Python as Python 2.7 won't be maintained after
> that date. A future version of pip will drop support for Python 2.7. More
> details about Python 2 support in pip, can be found at
> https://pip.pypa.io/en/latest/development/release-process/#python-2-support

Whichever way you get the Python you want to work for you, use the same
way to do installs.  Thus, if it works like this:

$ python3
Python 3.7.2 (default, Dec 27 2018, 07:35:45)
[Clang 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>


Then request your installations like this:

$ python3 -m pip install bunch-o-stuff


Your instructions probably said do "pip install bunch-o-stuff", don't do
it that way.


You can also check what you're getting this way (this is a snip from my
system, where the Python 3 came from homebrew, which is how I happen to
install it):

$ which python
/usr/bin/python# system version, you don't want this one
$ which python3
/usr/local/bin/python
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error terminal

2019-08-07 Thread Cameron Simpson

On 07Aug2019 13:08, Richard Rizk  wrote:
I wanted to send you this email to ask if you would have someone that 
can solve the problem I'm having with python.


I'm having issues with terminal on mac, is there someone that can help 
with this?


I probably can. Is this a Python problem, a Terminal problem, or some 
kind of mix?


Anyway, followup and describe your issue and we'll see.

Remember that this list drops attachments, so all your description 
should be text in the message, including and cut/paste of terminal 
output (which we usually want for context, and it is more precise than 
loose verbal descriptions alone).


Cheers,
Cameron Simpson 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Error terminal

2019-08-07 Thread Richard Rizk
Hello

I wanted to send you this email to ask if you would have someone that can solve 
the problem I'm having with python. 

I'm having issues with terminal on mac, is there someone that can help with 
this?

Best regards,
Richard
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error when trying to insert csv values into a sql table

2019-06-11 Thread Peter Otten
Cravan wrote:

> Here is the stack overflow link:
> https://stackoverflow.com/questions/56540292/error-when-trying-to-insert-csv-values-into-a-sql-table
> 
>  
> 
> I'm getting a weird error code when I try to store values from a csv into
> an sql table in a movie review assignment.

Like they say on stackoverflow: it very much looks like the movies table 
doesn't exist. Maybe you have forgotton a commit somewhere?

Please double-check that the table is actually created before you look for 
other less likely causes of your problem.

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


[Tutor] Error when trying to insert csv values into a sql table

2019-06-11 Thread Cravan
Here is the stack overflow link: 
https://stackoverflow.com/questions/56540292/error-when-trying-to-insert-csv-values-into-a-sql-table

 

I'm getting a weird error code when I try to store values from a csv into an 
sql table in a movie review assignment.

I have already edited my apostrophes and spacing and looked up examples from 
google to try and resolve my error to no avail. I also ensured that i defined 
DATABASE_URL properly. Sorry for the long traceback error at the end :P Please 
note that my csv values are stored in lists in each cell. They are arranged in 
a single column such as

The Lego Movie;2014;100;tt1490017;7.8

This is my main code

import os

from sqlalchemy import create_engine

from sqlalchemy.orm import scoped_session, sessionmaker

 

engine = create_engine(os.getenv("DATABASE_URL")) # database engine object from 
SQLAlchemy that manages connections to the database

  # DATABASE_URL is an 
environment variable that indicates where the database lives

 

db = scoped_session(sessionmaker(bind=engine)) 

def main():

    f = open("movies.csv","r")

    reader = csv.reader(f)

    for row in f: # loop gives each column a name

    vals = row.split(';')

    title = vals[0]

    year = vals[1]

    runtime = vals[2]

    imdbID = vals[3]

    imdbRating = vals[4]

    db.execute('INSERT INTO movies (Title, Year, Runtime, imdbID, 
imdbRating) VALUES (:title, :year, :runtime, :imdbID, :imdbRating)',

  {'title': title, 'year': year, 'runtime': runtime, 
'imdbID': imdbID, 'imdbRating': imdbRating}) # substitute values from CSV line 
into SQL command, as per this dict

    print(f"Added movie named {title} of {year} lasting {runtime} minutes. 
Its imdbID is {imdbID} and its imdbRating is {imdbRating}.")

This is the sql

CREATE TABLE movies (

  Title SERIAL PRIMARY KEY,

  Year INTEGER NOT NULL,

  Runtime INTEGER NOT NULL

  imdbID VARCHAR NOT NULL,

  imdbRating INTEGER NOT NULL

  );

This is the error i got:

Traceback (most recent call last):

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/engine/base.py", line 1244, in _execute_context

    cursor, statement, parameters, context

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/engine/default.py", line 550, in do_execute

    cursor.execute(statement, parameters)

psycopg2.errors.UndefinedTable: relation "movies" does not exist

LINE 1: INSERT INTO movies (Title, Year, Runtime, imdbID, imdbRating...

The above exception was the direct cause of the following exception:

 

Traceback (most recent call last):

  File "import.py", line 25, in 

    main()

  File "import.py", line 21, in main

    {'title': title, 'year': year, 'runtime': runtime, 'imdbID': imdbID, 
'imdbRating': imd

bRating}) # substitute values from CSV line into SQL command, as per this dict

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/orm/scoping.py", line 162, in do

    return getattr(self.registry(), name)(*args, **kwargs)

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/orm/session.py", line 1268, in execute

    clause, params or {}

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/orm/session.py", line 1268, in execute

    clause, params or {}

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/engine/base.py", line 988, in execute

    return meth(self, multiparams, params)

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/sql/elements.py", line 287, in _execute_on_connection

    return connection._execute_clauseelement(self, multiparams, params)

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/engine/base.py", line 1107, in _execute_clauseelement

    distilled_params,

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/engine/base.py", line 1248, in _execute_context

e, statement, parameters, cursor, context

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/engine/base.py", line 1466, in _handle_dbapi_exception

    util.raise_from_cause(sqlalchemy_exception, exc_info)

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/util/compat.py", line 383, in raise_from_cause

    reraise(type(exception), exception, tb=exc_tb, cause=cause)

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/util/compat.py", line 128, in reraise

    raise value.with_traceback(tb)

  File 

Re: [Tutor] error message

2019-03-21 Thread Alan Gauld via Tutor

On 21/03/19 05:13, Glenn Dickerson wrote:

Thank you for all of your responses to:

class Student():
 def__init__(self, name, major, gpa, is_on_probation):
 self.name = name
 self.major = major
 self.gpa = gpa
 self.is_on_probation = is_on_probation



Presumably the lines above ar in a separate file called Student.py?

And the lines below are in another file  called app.py?

If so thats a good start.
Steve (and others have already pointed out the need for a space after 
def (otherwise python looks for a function called def__init__() and 
wonderswhy yu have a colon after its  invocation)


But that will only lead you to the next error.


import Student
student1 = Student('Jim', 'Business', 3.1, False)


When accessing an object in an imported module you must precede
the object's name with the module:

student1 = Student.Student() # Student class in the Student module

Alternatively you can explicitly import the Student class (and nothing 
else!) from Student with:


from Student import Student

I which case you can use it as you do in your code.
In your case it doesn't really matter which of the two styles
you choose. In more complex programs explicit module naming
might make your code clearer (eg. if you have many modules).
Alternatively, pulling in the specific object might save
you some typing if you reference the object several times.
You need to choose which is most appropriate based on your code.

HTH

Alan G.

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


Re: [Tutor] error message

2019-03-21 Thread Steven D'Aprano
> I don't understand this error message. Thank you so much, Glenn Dickerson
> 
> Traceback (most recent call last):
>   File "/home/glen/app.py", line 1, in 
> import Student
>   File "/home/glen/Student.py", line 2
> def__init__(self, name, major, gpa, is_on_probation):
> ^
> SyntaxError: invalid syntax


Syntax errors are sometimes the hardest to decipher, because the message 
is usually pretty generic and uninformative, and the caret ^ will appear 
where the interpreter *notices* the problem, not where the problem 
*starts*.

In this case, the problem is you are missing a space between the "def" 
keyword and the "__init__" method name.


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


[Tutor] error message

2019-03-21 Thread Glenn Dickerson
Thank you for all of your responses to:

class Student():
def__init__(self, name, major, gpa, is_on_probation):
self.name = name
self.major = major
self.gpa = gpa
self.is_on_probation = is_on_probation


import Student
student1 = Student('Jim', 'Business', 3.1, False)
print(student1.name)

I don't understand this error message. Thank you so much, Glenn Dickerson

Traceback (most recent call last):
  File "/home/glen/app.py", line 1, in 
import Student
  File "/home/glen/Student.py", line 2
def__init__(self, name, major, gpa, is_on_probation):
^
SyntaxError: invalid syntax
>>>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error Python version 3.6 does not support this syntax.

2018-11-29 Thread Steven D'Aprano
On Fri, Nov 30, 2018 at 02:19:25AM +0530, srinivasan wrote:
> Dear Mats,
> 
> Thanks a lot for your quick responses, again the below line seems to
> be throwing the same error, is that should I again decode the line
> where am facing the issue to str? or could you please let me if there
> is any alternative solution for the same or workaround in python 3.6?

You don't need a "workaround", you need to fix the bug in your code:


> Traceback (most recent call last):
> , in parse_device_info
> string_valid = not any(keyword in info_string for keyword in block_list)
>   File "/home/srinivasan/Downloads/bt_tests/qa/test_library/bt_tests.py",
> line 52, in 
> string_valid = not any(keyword in info_string for keyword in block_list)
> TypeError: a bytes-like object is required, not 'str'

You get that error when you wrongly try to test for a string inside a 
bytes object:

py> 'string' in b'bytes'
Traceback (most recent call last):
  File "", line 1, in 
TypeError: a bytes-like object is required, not 'str'


You fix that by making sure both objects are strings, or both are bytes, 
which ever is better for your program:

py> 'a' in 'abc'  # string in string is okay
True
py> b'a' in b'abc'  # bytes in bytes is okay
True

py> 'a' in b'abc'  # string in bytes is NOT OKAY
Traceback (most recent call last):
  File "", line 1, in 
TypeError: a bytes-like object is required, not 'str'

py> b'a' in 'abc'  # bytes in string is NOT OKAY
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'in ' requires string as left operand, not bytes


Don't mix strings and bytes. It won't work.


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


Re: [Tutor] Error Python version 3.6 does not support this syntax.

2018-11-29 Thread srinivasan
Dear Mats,

Thanks a lot for your quick responses, again the below line seems to
be throwing the same error, is that should I again decode the line
where am facing the issue to str? or could you please let me if there
is any alternative solution for the same or workaround in python 3.6?

Code Snippet:

def parse_device_info(self, info_string):
"""Parse a string corresponding to a device."""
device = {}
block_list = ["[\x1b[0;", "removed"]
string_valid = not any(keyword in info_string for keyword in
block_list) ---> Again this line seems to be
the same issue

if string_valid:
try:
device_position = info_string.index("Device")
except ValueError:
pass
else:
if device_position > -1:
attribute_list = info_string[device_position:].split(" ", 2)
device = {
"mac_address": attribute_list[1],
"name": attribute_list[2]
}

return device

def get_paired_devices(self):
"""Return a list of tuples of paired devices."""
try:
out = self.get_output("paired-devices")
except BluetoothctlError as e:
print(e)
return None
else:
paired_devices = []
for line in out:
device = self.parse_device_info(line)
if device:
paired_devices.append(device)

return paired_devices

if __name__ == "__main__":

print("Init bluetooth...")
bl = Bluetoothctl()
print("Ready!")
bl.start_scan()
print("Scanning for 10 seconds...")
for i in range(0, 10):
print(i)
time.sleep(1)

bl.pair("64:A2:F9:06:63:79")
print("Pairing for 10 seconds...")
for i in range(0, 10):
print(i)
time.sleep(1)

# Seems to be an issue --
bl.get_paired_devices()
print("Getting Paired devices for 10 seconds...")
for i in range(0, 10):
print(i)
time.sleep(1)

Error Logs:

Traceback (most recent call last):
, in parse_device_info
string_valid = not any(keyword in info_string for keyword in block_list)
  File "/home/srinivasan/Downloads/bt_tests/qa/test_library/bt_tests.py",
line 52, in 
string_valid = not any(keyword in info_string for keyword in block_list)
TypeError: a bytes-like object is required, not 'str'

On Fri, Nov 30, 2018 at 1:18 AM Mats Wichmann  wrote:
>
> On 11/29/18 12:20 PM, srinivasan wrote:
> > Dear Python Experts,
> >
> > With the below code snippet, I am seeing the below error, I am using
> > python 3.6, could you please what could be the issue?
>
> > self.child = pexpect.spawn("bluetoothctl", echo = False)
> ...
> > self.child.send(command + "\n")
> > time.sleep(pause)
> > start_failed = self.child.expect(["bluetooth", pexpect.EOF])
> ...
> > return self.child.before.split("\r\n")
> > --->
> > the issue seems to be here
> > line 27, in get_output
> > return self.child.before.split("\r\n")
> > TypeError: a bytes-like object is required, not 'str'
>
> your types don't match. it's Python 3 so what you get back from talking
> to an external process is a bytes object. you're calling the split
> method on that object, but passing it a string to split on - that's what
> the error is saying.  It shouldn't be any more complicated to fix that
> than to give it a byte object:
>
> return self.child.before.split(b"\r\n")
>
> or... decode the object to a str before splitting on a string.
>
> but since you're specifically splitting on lines, you may as well use
> the splitlines method instead of the split method, since that's what it
> is designed for.
>
>
>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error Python version 3.6 does not support this syntax.

2018-11-29 Thread srinivasan
Dear Python Experts,

With the below code snippet, I am seeing the below error, I am using
python 3.6, could you please what could be the issue?

Code Snippet:
---
import time
import pexpect
import subprocess
import sys

class BluetoothctlError(Exception):
"""This exception is raised, when bluetoothctl fails to start."""
pass


class Bluetoothctl:
"""A wrapper for bluetoothctl utility."""

def __init__(self):
out = subprocess.check_output("rfkill unblock bluetooth", shell = True)
self.child = pexpect.spawn("bluetoothctl", echo = False)

def get_output(self, command, pause = 0):
"""Run a command in bluetoothctl prompt, return output as a
list of lines."""
self.child.send(command + "\n")
time.sleep(pause)
start_failed = self.child.expect(["bluetooth", pexpect.EOF])

if start_failed:
raise BluetoothctlError("Bluetoothctl failed after running
" + command)

return self.child.before.split("\r\n")
--->
the issue seems to be here

def start_scan(self):
"""Start bluetooth scanning process."""
try:
out = self.get_output("scan on")
except BluetoothctlError as e:
print(e)
return None

if __name__ == "__main__":

print("Init bluetooth...")
bl = Bluetoothctl()
print("Ready!")
bl.start_scan()
print("Scanning for 10 seconds...")
for i in range(0, 10):
print(i)
time.sleep(1)

Error Logs:
-
/home/srinivasan/Downloads/bt_tests/qa/venv/bin/python
/home/srinivasan/Downloads/bt_tests/qa/test_library/bt_tests.py
Init bluetooth...
Ready!
Traceback (most recent call last):
  File "/home/srinivasan/Downloads/bt_tests/qa/test_library/bt_tests.py",
line 169, in 
bl.start_scan()
  File "/home/srinivasan/Downloads/bt_tests/qa/test_library/bt_tests.py",
line 32, in start_scan
out = self.get_output("scan on")
  File "/home/srinivasan/Downloads/bt_tests/qa/test_library/bt_tests.py",
line 27, in get_output
return self.child.before.split("\r\n")
TypeError: a bytes-like object is required, not 'str'

Process finished with exit code 1

On Wed, Nov 28, 2018 at 12:17 AM Mats Wichmann  wrote:
>
> On 11/27/18 5:50 AM, srinivasan wrote:
> > Dear Python Experts,
> >
> > As still I am newbie and learning python, I am trying to reuse the
> > Bluetoothctl wrapper in Python from the link (
> > https://gist.github.com/egorf/66d88056a9d703928f93) I am using python3.6
> > version, In pycharm editor on the bold highlighted code snippets I see the
> > error message "Python version 3.6 does not support this syntax.",
>
> once again you've posted in a way that inserts lots of extra crud, you
> avoided that last time.
>
> The syntax change is simple (and works on most older Pythons too):
>
> except ErrorType, e:
>
> becomes
>
> except ErrorType as e:
>
>
> >
> > Could you please how help me how the below highlighted lines of code can be
> > can be ported to python3.6 version?
> >
> > *except BluetoothctlError, e:*
> >
> > *print(e)*
> > *return None*
> >
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error Python version 3.6 does not support this syntax.

2018-11-29 Thread Cameron Simpson

On 30Nov2018 02:19, srinivasan  wrote:

Thanks a lot for your quick responses, again the below line seems to
be throwing the same error, is that should I again decode the line
where am facing the issue to str? or could you please let me if there
is any alternative solution for the same or workaround in python 3.6?

Code Snippet:

   def parse_device_info(self, info_string):
   """Parse a string corresponding to a device."""
   device = {}
   block_list = ["[\x1b[0;", "removed"]
   string_valid = not any(keyword in info_string for keyword in
block_list) ---> Again this line seems to be
the same issue

[...]

   def get_paired_devices(self):
   """Return a list of tuples of paired devices."""
   try:
   out = self.get_output("paired-devices")
   except BluetoothctlError as e:
   print(e)
   return None
   else:
   paired_devices = []
   for line in out:
   device = self.parse_device_info(line)

[...]

Your problem is basicly that reading from command output gets you bytes 
data, not text (str) data. This is because pipes transfer bytes; that 
the command may issue text simply means that those bytes are an encoding 
of the text.


Your entire process treats the output as text, because the commands 
issue textual output.


Therefore, the most sensible thing to do at this point is to _decode_ 
the bytes into text as soon as you get them from the command, and then 
the rest of your programme can work in text (str) from then on.


So I would be inclined to change:

   for line in out:
   device = self.parse_device_info(line)

into (untested):

   for line_b in out:
   line = line_b.decode(errors='replace')
   device = self.parse_device_info(line)

That will turn line_b (a bytes object holding the line) into text before 
you try to do any parsing. From that point onward, everything is text 
(str) and you do not need to put any bytes->str stuff elsewhere in your 
programme.


Some remarks:

That decode line above uses the default bytes->str decoding, which is 
'utf-8'. That is probably how your system works, but if it is not you 
need to adjust accordingly. If the command ussues pure ASCII you'll be 
fine regardless.


The decode uses "errors='replace'", which means that if the bytes data 
are _not_ correct UTF-8 encoded text, the decoder will put some 
replacement characters in the result instead of raising an exception.  
This simplifies your code, and since you're parsing the output anyway 
for infomation the replacements should show up to your eye. The default 
decode mode is 'strict', which would raise an exception on an invalid 
encoding.


Purists might decode the output stream ("out") before the for-loop, but 
in most encodings including UTF-8, you can split on newlines (byte code 
10, ASCII NL) safely anyway, so we just split first and decode each 
"bytes" line individually.


In the loop I deliberately iterate over "line_b", and have the decoded 
text in "line", instead of doing something like:


   for line in out:
   line = line.decode()

That way I am always sure that I intend to talk about bytes in one place 
(line_b) and text (line) in another. Having variable that might contain 
bytes _or_ text leads to confusion and difficult debugging.


The core takeaway here is that you want to keep in mind whether you're 
working in bytes or text (str). Keep the division clean, that way all 
you other code can be written appropriately. So: the command pipe output 
is bytes. COnvert it to text before passing to your text parsing code.  
That way all the parsing code can work in text (str) and have no weird 
conversion logic.


Cheers,
Cameron Simpson 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error Python version 3.6 does not support this syntax.

2018-11-29 Thread Mats Wichmann
On 11/29/18 12:20 PM, srinivasan wrote:
> Dear Python Experts,
> 
> With the below code snippet, I am seeing the below error, I am using
> python 3.6, could you please what could be the issue?

> self.child = pexpect.spawn("bluetoothctl", echo = False)
...
> self.child.send(command + "\n")
> time.sleep(pause)
> start_failed = self.child.expect(["bluetooth", pexpect.EOF])
...
> return self.child.before.split("\r\n")
> --->
> the issue seems to be here
> line 27, in get_output
> return self.child.before.split("\r\n")
> TypeError: a bytes-like object is required, not 'str'

your types don't match. it's Python 3 so what you get back from talking
to an external process is a bytes object. you're calling the split
method on that object, but passing it a string to split on - that's what
the error is saying.  It shouldn't be any more complicated to fix that
than to give it a byte object:

return self.child.before.split(b"\r\n")

or... decode the object to a str before splitting on a string.

but since you're specifically splitting on lines, you may as well use
the splitlines method instead of the split method, since that's what it
is designed for.





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


Re: [Tutor] Error Python version 3.6 does not support this syntax.

2018-11-27 Thread Mats Wichmann
On 11/27/18 5:50 AM, srinivasan wrote:
> Dear Python Experts,
> 
> As still I am newbie and learning python, I am trying to reuse the
> Bluetoothctl wrapper in Python from the link (
> https://gist.github.com/egorf/66d88056a9d703928f93) I am using python3.6
> version, In pycharm editor on the bold highlighted code snippets I see the
> error message "Python version 3.6 does not support this syntax.",

once again you've posted in a way that inserts lots of extra crud, you
avoided that last time.

The syntax change is simple (and works on most older Pythons too):

except ErrorType, e:

becomes

except ErrorType as e:


> 
> Could you please how help me how the below highlighted lines of code can be
> can be ported to python3.6 version?
> 
> *except BluetoothctlError, e:*
> 
> *print(e)*
> *return None*
> 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Error Python version 3.6 does not support this syntax.

2018-11-27 Thread srinivasan
Dear Python Experts,

As still I am newbie and learning python, I am trying to reuse the
Bluetoothctl wrapper in Python from the link (
https://gist.github.com/egorf/66d88056a9d703928f93) I am using python3.6
version, In pycharm editor on the bold highlighted code snippets I see the
error message "Python version 3.6 does not support this syntax.",

Could you please how help me how the below highlighted lines of code can be
can be ported to python3.6 version?

*except BluetoothctlError, e:*

*print(e)*
*return None*

Full Code snippet:
==

import time
import pexpect
import subprocess
import sys

class BluetoothctlError(Exception):
"""This exception is raised, when bluetoothctl fails to start."""
pass

class Bluetoothctl:
"""A wrapper for bluetoothctl utility."""

def __init__(self):
out = subprocess.check_output("rfkill unblock bluetooth", shell =
True)
self.child = pexpect.spawn("bluetoothctl", echo = False)

def get_output(self, command, pause = 0):
"""Run a command in bluetoothctl prompt, return output as a list of
lines."""
self.child.send(command + "\n")
time.sleep(pause)
start_failed = self.child.expect(["bluetooth", pexpect.EOF])

if start_failed:
raise BluetoothctlError("Bluetoothctl failed after running " +
command)

return self.child.before.split("\r\n")

def start_scan(self):
"""Start bluetooth scanning process."""
try:
out = self.get_output("scan on")


*except BluetoothctlError, e:print(e)return
None*

def make_discoverable(self):
"""Make device discoverable."""
try:
out = self.get_output("discoverable on")



*   except BluetoothctlError, e:print(e)return
None*
def parse_device_info(self, info_string):
"""Parse a string corresponding to a device."""
device = {}
block_list = ["[\x1b[0;", "removed"]
string_valid = not any(keyword in info_string for keyword in
block_list)

if string_valid:
try:
device_position = info_string.index("Device")
except ValueError:
pass
else:
if device_position > -1:
attribute_list = info_string[device_position:].split("
", 2)
device = {
"mac_address": attribute_list[1],
"name": attribute_list[2]
}

return device

def get_available_devices(self):
"""Return a list of tuples of paired and discoverable devices."""
try:
out = self.get_output("devices")


*except BluetoothctlError, e:print(e)return
None*
else:
available_devices = []
for line in out:
device = self.parse_device_info(line)
if device:
available_devices.append(device)

return available_devices

def get_paired_devices(self):
"""Return a list of tuples of paired devices."""
try:
out = self.get_output("paired-devices")


*except BluetoothctlError, e:print(e)return
None*
else:
paired_devices = []
for line in out:
device = self.parse_device_info(line)
if device:
paired_devices.append(device)

return paired_devices

def get_discoverable_devices(self):
"""Filter paired devices out of available."""
available = self.get_available_devices()
paired = self.get_paired_devices()

return [d for d in available if d not in paired]

def get_device_info(self, mac_address):
"""Get device info by mac address."""
try:
out = self.get_output("info " + mac_address)


*except BluetoothctlError, e:print(e)return
None*
else:
return out

def pair(self, mac_address):
"""Try to pair with a device by mac address."""
try:
out = self.get_output("pair " + mac_address, 4)


*except BluetoothctlError, e:print(e)return
None*
else:
res = self.child.expect(["Failed to pair", "Pairing
successful", pexpect.EOF])
success = True if res == 1 else False
return success

def remove(self, mac_address):
"""Remove paired device by mac address, return success of the
operation."""
try:
out = self.get_output("remove " + mac_address, 3)


*except BluetoothctlError, e:print(e)return
None*
else:
res = self.child.expect(["not available", "Device has been
removed", pexpect.EOF])
success = True if res == 1 else False
return 

Re: [Tutor] Error in class definition of __init__

2018-02-15 Thread Alan Gauld via Tutor
On 15/02/18 01:27, Leo Silver wrote:
> Hello.
> 
> I'm trying to create a class to represent products which includes a list of
> volume based pricing and sets the first of these as the unit price:
> 
> def __init__(self, RatePlanID):
> self.id = RatePlanID
> self.name = RatePlans.toggleids[self.id]
> self.pricing = RatePlans.pricebreaks[self.name]
> self.unitprice = RatePlans.pricebreaks[self.name][0]
> 

You could simolify the last line to:

 self.unitprice = self.pricing[0]

BTW This process is poor practice since you are effectively
reading the data from a global object (whose definition you don't
share) It would be better to pass the RatePlans into the
init() ass a parameter. Also its bad OO practice to extract
lots of data out of another object to store in your own.
It suggests that either you should be storing a reference to the
object(self.ratePlan, say) or that your RatePlans collection
should be storing some other kind of object which can
be extracted by init (a PriceBreak maybe):

self.foo = RatePlans.getObject(RatePlanID)

Anyway, design issues aside...

> This code gives an IndexError:
> ...
> self.unitprice = RatePlans.pricebreaks[self.name][0]
> IndexError: list index out of range
> 
> However, the same code with the last line changed to:
> self.unitprice = RatePlans.pricebreaks[self.name][:1]

These do very different things.
The first uses indexing to extract a single item out of a collection.
The second creates a new collection based on an existing one, but it
does not require the slice values to exist, it will use defaults
if they don't.

> seems to work OK, 

When you say "work" I assume you mean you don;t get an error,
rather than that you have tested it and the unitprice
contains the correct data?

> The list I'm trying to process is:
> [(1, 21.0), (100, 19.6), (250, 18.4), (500, 17.6), (1000, 16.7), (2500,
> 14.7), (1, 13.7)]

Which list is this in your code?
Is it RatePlans or is it RatePlans.pricebreaks?
Or is it the list returned by RatePlans.pricebreaks[self.name]?
You need to be more specific. I'll assume the last one...

> and a cut and paste into the IDLE GUI let's me process it exactly as I
> expect (including picking the second element of the tuple, the price rather
> than the volume level):
 [(1, 21.0), (100, 19.6), (250, 18.4), (500, 17.6), (1000, 16.7), (2500,
> 14.7), (1, 13.7)][0][1]

But that's not what you are doing in your code.
You are using variables populated from another object (RatePlans).
Unless you have printed out the values in self.name etc to confirm
they are a valid list. The error message suggests you are retrieving
an empty list. Have you checked?

> What am I missing about the class definition that won't let me put this
> class in the init call?

Nothing, I think the problem is in your RatePlans data.
Coupled to the fact that you are trying to use some very
dodgy OO design.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Error in class definition of __init__

2018-02-15 Thread Peter Otten
Leo Silver wrote:

> Hello.
> 
> I'm trying to create a class to represent products which includes a list
> of volume based pricing and sets the first of these as the unit price:
> 
> def __init__(self, RatePlanID):
> self.id = RatePlanID
> self.name = RatePlans.toggleids[self.id]
> self.pricing = RatePlans.pricebreaks[self.name]

To debug your code print out the list and a few other things here with:

  print("name:", self.name)
  print("price breaks:", RatePlans.pricebreaks)
  print("pricebreaks[name]:", RatePlans.pricebreaks[self.name])

> self.unitprice = RatePlans.pricebreaks[self.name][0]
> 
> This code gives an IndexError:
> ...
> self.unitprice = RatePlans.pricebreaks[self.name][0]
> IndexError: list index out of range
> 
> However, the same code with the last line changed to:
> self.unitprice = RatePlans.pricebreaks[self.name][:1]

Slicing allows for the list to be shorter than specified:

>>> items = [1, 2, 3]
>>> items[:1]
[1]
>>> items[:100]
[1, 2, 3]

In your case it's an empty list:

>>> items = []
>>> items[0]
Traceback (most recent call last):
  File "", line 1, in 
IndexError: list index out of range
>>> items[:1]
[]

> 
> seems to work OK, although, I can't process it further and extract the
> second element of the pair.
> 
> The list I'm trying to process is:
> [(1, 21.0), (100, 19.6), (250, 18.4), (500, 17.6), (1000, 16.7), (2500,
> 14.7), (1, 13.7)]

I'm pretty sure that's not what you'll see printed if you follow my advice 
and add those print() calls above.

> and a cut and paste into the IDLE GUI let's me process it exactly as I
> expect (including picking the second element of the tuple, the price
> rather than the volume level):
 [(1, 21.0), (100, 19.6), (250, 18.4), (500, 17.6), (1000, 16.7), (2500,
> 14.7), (1, 13.7)][0][1]
> 21.0
> 
> What am I missing about the class definition that won't let me put this
> class in the init call?

This has nothing to do with __init__() specifically.


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


[Tutor] Error in class definition of __init__

2018-02-15 Thread Leo Silver
Hello.

I'm trying to create a class to represent products which includes a list of
volume based pricing and sets the first of these as the unit price:

def __init__(self, RatePlanID):
self.id = RatePlanID
self.name = RatePlans.toggleids[self.id]
self.pricing = RatePlans.pricebreaks[self.name]
self.unitprice = RatePlans.pricebreaks[self.name][0]

This code gives an IndexError:
...
self.unitprice = RatePlans.pricebreaks[self.name][0]
IndexError: list index out of range

However, the same code with the last line changed to:
self.unitprice = RatePlans.pricebreaks[self.name][:1]

seems to work OK, although, I can't process it further and extract the
second element of the pair.

The list I'm trying to process is:
[(1, 21.0), (100, 19.6), (250, 18.4), (500, 17.6), (1000, 16.7), (2500,
14.7), (1, 13.7)]

and a cut and paste into the IDLE GUI let's me process it exactly as I
expect (including picking the second element of the tuple, the price rather
than the volume level):
>>> [(1, 21.0), (100, 19.6), (250, 18.4), (500, 17.6), (1000, 16.7), (2500,
14.7), (1, 13.7)][0][1]
21.0

What am I missing about the class definition that won't let me put this
class in the init call?

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


Re: [Tutor] Error with sqlalchemy

2017-08-01 Thread Alan Gauld via Tutor
On 01/08/17 12:13, rakesh sharma wrote:

> I am getting the error
> 
> TypeError: utf_8_decode() argument 1 must be string or buffer, not long

That's not too helpful out of context, can you show us more
of the error trace? Can you show us the method that generates
it? Do you have any indication about which field is generating
the error?

> at this point in the code
> 
> ship_schedules = ShipSchedule.query.all()

One line out of context doesn't really help.
I'm assuming query is a class attribute in
the inherited Base class? Do you have to create
any overridden methods/attribute values to
make it work for your subclass?

I can't comment on the schemas because I don't know MySql
or Flask's ORM well enough to understand what may be happening.
But a bit more detail on the actual code triggering the
error and the error message itself would certainly not hurt.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Error with sqlalchemy

2017-08-01 Thread Mats Wichmann
On 08/01/2017 05:13 AM, rakesh sharma wrote:
> Hi All
> 
> 
> I am getting an error in python. Its a flask app that I am doing
> 
> I am getting the error
> 
> TypeError: utf_8_decode() argument 1 must be string or buffer, not long
> 
> at this point in the code
> 
> ship_schedules = ShipSchedule.query.all()
> 
> The schema definition is like that I gave below, there is no mismatch between 
> the schema and the table definition in the mysql DB.
> 
> class ShipSchedule(Base):
> 
> __tablename__ = 'ship_schedule'
> 
> vessel_imo_no = Column(Integer, primary_key=True, nullable=False)
> commodity_product_code = Column(String, nullable=False)
> port_port_code = Column(String, nullable=False)
> cargo_quantity = Column(String, nullable=False)
> activity = Column(String, nullable=False)
> date_from = Column(Date, nullable=False)
> date_to = Column(Date, nullable=False)
> 
> 
> """
> Ship schedule schema
> """
> 
> 
> class ShipScheduleSchema(Schema):
> vessel_imo_no = fields.Int(dump_only=True)
> commodity_product_code = fields.Str()
> port_port_code = fields.Str()
> cargo_quantity = fields.Int()
> activity = fields.Str()
> date_from = fields.Date()
> date_to = fields.Date()
> 
> the mysql table defintion is as follows
> 
> 
> [cid:e101f2ac-60ca-426a-8e53-01afd9e9414d]

this is not viewable, at least not here.

you've potentially got an issue in your cargo quantity definition in the
two classes, possibly take a closer look at that (String vs fields.Int()).

this is a pretty specialized sort of query, probably the sqlalchemy
community would be more expert in this stuff (given you said you've
exhausted stackoverflow already). maybe they have knowledge of some
consistency-checking tool that could detect mismatches?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Error with sqlalchemy

2017-08-01 Thread rakesh sharma
Hi All


I am getting an error in python. Its a flask app that I am doing

I am getting the error

TypeError: utf_8_decode() argument 1 must be string or buffer, not long

at this point in the code

ship_schedules = ShipSchedule.query.all()

The schema definition is like that I gave below, there is no mismatch between 
the schema and the table definition in the mysql DB.

class ShipSchedule(Base):

__tablename__ = 'ship_schedule'

vessel_imo_no = Column(Integer, primary_key=True, nullable=False)
commodity_product_code = Column(String, nullable=False)
port_port_code = Column(String, nullable=False)
cargo_quantity = Column(String, nullable=False)
activity = Column(String, nullable=False)
date_from = Column(Date, nullable=False)
date_to = Column(Date, nullable=False)


"""
Ship schedule schema
"""


class ShipScheduleSchema(Schema):
vessel_imo_no = fields.Int(dump_only=True)
commodity_product_code = fields.Str()
port_port_code = fields.Str()
cargo_quantity = fields.Int()
activity = fields.Str()
date_from = fields.Date()
date_to = fields.Date()

the mysql table defintion is as follows


[cid:e101f2ac-60ca-426a-8e53-01afd9e9414d]


please help on this, do not know the whats causing the issue.

I dint find any good answers in stackoverflow as all points to schema mismatch

thanks

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


Re: [Tutor] Error when trying to use classes

2017-02-07 Thread George Fischhof
2017-02-07 16:34 GMT+01:00 Rafael Skovron :

> I'm trying to learn how to use Classes but I keep getting  NameErrors no
> matter what code I put into the script.
>
> Any ideas why?
>
> My general workflow is I edit in vim, then invoke python3 interpreter,
> import the module and try to use the Class and methods from the class.
>
> For example, importing customer.py and assigning this object yields:
>
> >>> rafael = Customer('rafael',100.0)
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 'Customer' is not defined
>
>
>
> class Customer(object):
> """A customer of ABC Bank with a checking account. Customers have
> thefollowing properties:
> Attributes:name: A string representing the customer's
> name.balance: A float tracking the current balance of the
> customer's account."""
>
> def __init__(self, name, balance=0.0):
> """Return a Customer object whose name is *name* and starting
>   balance is *balance*."""
> self.name = name
> self.balance = balance
>
> def withdraw(self, amount):
> """Return the balance remaining after withdrawing *amount*
>dollars."""
> if amount > self.balance:
> raise RuntimeError('Amount greater than available balance.')
> self.balance -= amount
> return self.balance
>
> def deposit(self, amount):
> """Return the balance remaining after depositing *amount*
>   dollars."""
> self.balance += amount
> return self.balance
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


Hi,

with this statement:
>>> rafael = Customer('rafael',100.0)
you (the program) creates an instance of Customer class

to import the class (this is the first), you should use the import
statement:
>>> from customer import Customer
after this the program will work.

BR,
George

PS.: pycharm from JetBrains is a very good python ide. ... (instead of vim
;-) )
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error when trying to use classes

2017-02-07 Thread Alex Kleider

On 2017-02-07 07:34, Rafael Skovron wrote:
I'm trying to learn how to use Classes but I keep getting  NameErrors 
no

matter what code I put into the script.

Any ideas why?


Assuming the code you've edited using vim is in a file mymodule.py
And after invoking the interpreter you issue the following:

import mymodule.py

your instantiation statement needs to be

rafael = mymodule.Customer('rafael', 100.0)


Alternatively you can use the following import statement (not generally 
recommended:)

from mymodule import Customer





My general workflow is I edit in vim, then invoke python3 interpreter,
import the module and try to use the Class and methods from the class.

For example, importing customer.py and assigning this object yields:


rafael = Customer('rafael',100.0)

Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'Customer' is not defined



class Customer(object):
"""A customer of ABC Bank with a checking account. Customers have
thefollowing properties:
Attributes:name: A string representing the customer's
name.balance: A float tracking the current balance of the
customer's account."""

def __init__(self, name, balance=0.0):
"""Return a Customer object whose name is *name* and starting
  balance is *balance*."""
self.name = name
self.balance = balance

def withdraw(self, amount):
"""Return the balance remaining after withdrawing *amount*
   dollars."""
if amount > self.balance:
raise RuntimeError('Amount greater than available 
balance.')

self.balance -= amount
return self.balance

def deposit(self, amount):
"""Return the balance remaining after depositing *amount*
  dollars."""
self.balance += amount
return self.balance
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Error when trying to use classes

2017-02-07 Thread Alan Gauld via Tutor
On 07/02/17 15:34, Rafael Skovron wrote:

> My general workflow is I edit in vim, then invoke python3 interpreter,
> import the module and try to use the Class and methods from the class.
> 
> For example, importing customer.py and assigning this object yields:
> 
 rafael = Customer('rafael',100.0)
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 'Customer' is not defined

You didn't show us the import but I'm guessing
you just did

import customer

In that case you need to reference the module:

rafael = customer.Customer()

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Error

2016-10-04 Thread Ramanathan Muthaiah
>
> I began to learn Python and after saving a file gra.py tried to reopen it
> and got an error (in the Annex).
>
> What's the error on re-opening the file ?

Also, share what version of Python, OS and editor you are using.

FYI, this is a text only list, images of attachments will be filtered.

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


Re: [Tutor] Error

2016-10-04 Thread Alan Gauld via Tutor
On 04/10/16 18:41, Agnieszka Socha wrote:
> I began to learn Python and after saving a file gra.py tried to reopen it
> and got an error (in the Annex).

This is a text only list so attachments tend to get stripped off.

We need a lot more information I'm afraid.

What are you using to "reopen" the file? Are you using a text
editor or an IDE (like IDLE or eclipse?).

Show us the full error text and your code - just paste
it into the mail message.

It also might help to tell us the Python version and the OS.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


[Tutor] Error

2016-10-04 Thread Agnieszka Socha
I began to learn Python and after saving a file gra.py tried to reopen it
and got an error (in the Annex).

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


Re: [Tutor] Error: 'IndexedVar' object is not callable

2016-09-10 Thread Alan Gauld via Tutor
On 10/09/16 17:23, Pooja Bhalode wrote:

> I am trying to run Pyomo environment in Python on sublime text editor.

OK, For the pyomo stuff you should ask on the pyomo support site
(or I notice they do staxck overflow too)

> Python version of 2.7.11. I am running the code in sublime itself.

You maybe should try running it outside Sublime, it may give you more
useful error messages.

> Code:
> 
> m.z = ContinuousSet(bounds = (0,10))
> m.t = ContinuousSet(bounds = (0,10))
> where all the variables that I am defining, are varying along the z and t
> direction.

Most of that is mreaningless to us because we don;t know pyomo.
I'd never even heard of it until you said.

> Variables:
> m.C = Var(m.z,m.t)
> m.Cair = Var(m.z,m.t)
> m.masswater = Var(m.z,m.t)
> m.massair = Param(initialize = 1833.50)

Again that is all very pyomo specific. Its hard to comment
without knowing pyomo.


> After this, when I define the equations,
> 
> def _calculations(m,i,j):
> if i == 0 or i == 1 or j == 0:
> return Constraint.Skip
> 
> return m.wateraccumulated(j) == 916.50 - (m.C(i,j)*46*28/(28*18*1.205 +
> m.C(i,j) * 46*28))*2750

What happens if you do:

m.C = Var(m.z,m.t)
print m.C
print m.C(i,j)


> It tells me that TypeError: 'IndexedVar' object is not callable for m.C
> itself. I think the syntax is correct but I am not able to figure out why
> the variable is not callable.

Its not clear where the error is occurring, are you sure
that's all the error message says?? Usually there is a
whole heap of stuff about where the call happened
and its context.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Error: 'IndexedVar' object is not callable

2016-09-10 Thread Pooja Bhalode
Hi everyone,

I am sorry about the confusion earlier,
I am trying to run Pyomo environment in Python on sublime text editor.
Python version of 2.7.11. I am running the code in sublime itself.

The code is somewhat long, around 200 lines.
I can add snippets of it though.

Code:

m.z = ContinuousSet(bounds = (0,10))
m.t = ContinuousSet(bounds = (0,10))
where all the variables that I am defining, are varying along the z and t
direction.

Variables:
m.C = Var(m.z,m.t)
m.Cair = Var(m.z,m.t)
m.masswater = Var(m.z,m.t)
m.massair = Param(initialize = 1833.50)

that is C and Cair and all other variables are varying along z and t
direction.

After this, when I define the equations,

def _calculations(m,i,j):
if i == 0 or i == 1 or j == 0:
return Constraint.Skip

return m.wateraccumulated(j) == 916.50 - (m.C(i,j)*46*28/(28*18*1.205 +
m.C(i,j) * 46*28))*2750

if i == 0:
return m.vel(i,j) == m.inmassflowrate/ ((m.outerdiameter * m.outerdiameter
* m.pi/4)*m.densityfeed)
if i == 1:
return m.vel(i,j) == m.outmassflowrate/((m.outerdiameter * m.outerdiameter
* m.pi/4)*m.densityfeed)

return m.vel(i,j) == m.flowrate/((m.outerdiameter * m.outerdiameter *
m.pi/4)*m.densityfeed)
m.calculations = Constraint(m.z,m.t, rule = _calculations)

It tells me that TypeError: 'IndexedVar' object is not callable for m.C
itself. I think the syntax is correct but I am not able to figure out why
the variable is not callable.

I am aware that the language is slightly different than Python here, I am
just stuck and would appreciate any help here.

On Fri, Sep 9, 2016 at 9:49 PM, Alex Kleider  wrote:

> On 2016-09-09 18:13, Steven D'Aprano wrote:
>
>> Please read this article first for
>> how you can improve the chances of getting good answers to your
>> questions:
>>
>> http://sscce.org/
>>
>
> In addition to the link Seven provides above, I've also found the
> following to be worth perusing:
> http://www.catb.org/esr/faqs/smart-questions.html
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error: 'IndexedVar' object is not callable

2016-09-09 Thread Alex Kleider

On 2016-09-09 18:13, Steven D'Aprano wrote:

Please read this article first for
how you can improve the chances of getting good answers to your
questions:

http://sscce.org/


In addition to the link Seven provides above, I've also found the 
following to be worth perusing:

http://www.catb.org/esr/faqs/smart-questions.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error: 'IndexedVar' object is not callable

2016-09-09 Thread Steven D'Aprano
Hi Pooja, and welcome!


On Fri, Sep 09, 2016 at 02:50:57PM -0400, Pooja Bhalode wrote:
> Hi everyone,
> 
> I was getting this error which read ' 'IndexedVar' object is not callable '
> for a variable type.
> 
> The variable is defined as a class variable and has dimensions m.C(i,j) in
> z and t axis.

I'm afraid I have no idea what you are talking about here. What is an 
IndexedVar object? What does "dimensions m.C(i,j) in z and t axis" mean?

Is this from some third-party library? Which one?

I would help if you show us the actual code you are trying to run. Not 
your entire application, especially if it is big, but enough of the code 
that we can understand the context. Please read this article first for 
how you can improve the chances of getting good answers to your 
questions:

http://sscce.org/

> ERROR: Rule failed when generating expression for constraint concentration
> with index (10, 10):
> TypeError: 'IndexedVar' object is not callable
> ERROR: Constructing component 'concentration' from data=None failed:
> TypeError: 'IndexedVar' object is not callable


These do not look like standard Python errors. I would expect to see a 
traceback, which may look something like this:

Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python3.3/random.py", line 298, in sample
raise TypeError("Population must be a sequence or set.  For dicts, use 
list(d).")
TypeError: Population must be a sequence or set.  For dicts, use list(d).


How are you running this code?

My *wild-guess* is that if you change m.C(i, j) to m.C[i, j] it might 
fix this specific error, but it really is a guess.


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


Re: [Tutor] Error: 'IndexedVar' object is not callable

2016-09-09 Thread Alex Kleider

On 2016-09-09 11:50, Pooja Bhalode wrote:

Hi everyone,

I was getting this error which read ' 'IndexedVar' object is not 
callable '

for a variable type.


You haven't provided much information but it seems to me you are calling 
IndexedVar as though it were a function but it probably isn't a 
function.


some_name(zero_or_more_parameters)

is a function call, calling some_name.

If some_name hasn't been defined as a function:
def some_name():
  do something

then you can expect the error you got.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error: 'IndexedVar' object is not callable

2016-09-09 Thread Alan Gauld via Tutor
On 09/09/16 19:50, Pooja Bhalode wrote:

> I was getting this error which read ' 'IndexedVar' object is not callable '
> for a variable type.

Python error messages are very informative, but only if we can see them.
Please post the entire error message not just a summary.

> The variable is defined as a class variable and has dimensions m.C(i,j) in
> z and t axis.

Python variables are just names that reference objects,
so variables do not have any type per se, rather they
take the type of whatever they are currently referencing.

> Could someone please tell me the possible reasons for this happening.

"not callable" means that you are trying to call the variable
(using parens (...) ) on a variable that is not callable, in
this case an IndexedVar - whatever that is; it's not part
of the standard Python language so you are presumably using
some kind of third party add-on, (possibly SciPy?). It will
help if you tell us which libraries you are using. Anyway,
its most likely that you have assigned a variable to something
you expected to be a callable but is in fact an IndexedVar.
This could, for example, be the parameter of a function and
you have passed in the wrong kind of data, or it could
be the return value from a function that you assign to your variable.

> ERROR: Rule failed when generating expression for constraint concentration
> with index (10, 10):
> TypeError: 'IndexedVar' object is not callable
> ERROR: Constructing component 'concentration' from data=None failed:
> TypeError: 'IndexedVar' object is not callable

Those don't look like Python error messages. How are you
running this code? If it is an IDE then it may be
contributing to the confusion.

Also we can only guess what your code looks like.
Please post the code causing the error. As a minimum
the function/method involved. If possible all of it
(if less than ~100 lines?).

And please post the entire error message, plus a note of
your Python version and whatever library you are using.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Error help

2016-08-30 Thread Alan Gauld via Tutor

On 30/08/16 03:22, Matthew Lehmberg wrote:

I've been getting this error over and over and was wondering if someone
could help me fix it. [image: Inline image 1]


This is a text mailing list so attachments dont get through.
Plese repost with your error message cut n paste into the message.

Alan G

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


[Tutor] Error help

2016-08-30 Thread Matthew Lehmberg
I've been getting this error over and over and was wondering if someone
could help me fix it. [image: Inline image 1]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] error

2016-07-06 Thread Danny Yoo
>
> Have you checked that you have the requisite permissions? That the
> socket you are connecting to exists? If its a system call error the
> problem is most likely in your environment rather than your code.
>


That particular error is from Windows.  One common cause for it is a
network firewall, which normally is great because at least it's
working as a first line of defense.  If that's the case, you probably
want to tell your firewall to make an exception for your program.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] error

2016-07-06 Thread Alan Gauld via Tutor
On 06/07/16 18:27, Moses, Samuel wrote:
> I am getting an error.  I tired to run the script in wing IDE.
> 

Without the accompanying code we can only guess.

> I am getting this error,
> 
> "Traceback (most recent call last):
>   File "C:\Program Files (x86)\Wing IDE 5.1\bin\wingdb.py", line 822, in
> main
> args['firststop'], err, netserver, pwfile_path)
>   File "C:\Program Files (x86)\Wing IDE 5.1\bin\wingdb.py", line 649, in
> CreateServer
> pwfile_path, internal_modules=tuple(internal_modules))
>   File "C:\src\ide\bin\3.2\src/debug/tserver\netserver.pyc", line 922, in
> __init__
>   File "C:\src\ide\bin\3.2\src/debug/tserver\netserver.pyc", line 2234, in
> __PrepareConnectListener
>   File "C:\Python32\lib\socket.py", line 94, in __init__
> _socket.socket.__init__(self, family, type, proto, fileno)
> socket.error: [Errno 10107] A system call has failed"

Have you checked that you have the requisite permissions? That the
socket you are connecting to exists? If its a system call error the
problem is most likely in your environment rather than your code.

But check the values you pass into socket. Print them out
to check they are what you (and Python) expect...

> I tried printing "Christmas"

I have no idea what that means. Literally putting

print "Christmas"

in your code probably wouldn't help so I assume you
did something else?

> It said there was no TCP/IP connection.

What said? Was it another error trace? Or something else?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


[Tutor] error

2016-07-06 Thread Moses, Samuel
I am getting an error.  I tired to run the script in wing IDE.

I am getting this error,

"Traceback (most recent call last):
  File "C:\Program Files (x86)\Wing IDE 5.1\bin\wingdb.py", line 822, in
main
args['firststop'], err, netserver, pwfile_path)
  File "C:\Program Files (x86)\Wing IDE 5.1\bin\wingdb.py", line 649, in
CreateServer
pwfile_path, internal_modules=tuple(internal_modules))
  File "C:\src\ide\bin\3.2\src/debug/tserver\netserver.pyc", line 922, in
__init__
  File "C:\src\ide\bin\3.2\src/debug/tserver\netserver.pyc", line 2234, in
__PrepareConnectListener
  File "C:\Python32\lib\socket.py", line 94, in __init__
_socket.socket.__init__(self, family, type, proto, fileno)
socket.error: [Errno 10107] A system call has failed"

I tried printing "Christmas"
It said there was no TCP/IP connection.

Any suggestion would help

Thank you

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


Re: [Tutor] error in python code.

2016-06-21 Thread Danny Yoo
> You need to state some definitions so that we are sharing common
> terminology.  What does "skew" mean, for example?

Note to others: I'm guessing that this has something to do with GC
skew as described in https://en.wikipedia.org/wiki/GC_skew.  But I'd
rather not guess.  I'd like Riaz to explain in some detail what the
purpose of the function is supposed to be.


Otherwise, a technically correct solution to the problem that
satisfies the test dataset is the following silly function:


def Skew(genome):
return ['0', '-1', '0', '-1', '-1', '0', '0', '0', '1', '1',
   '1', '1', '2', '1', '1', '0', '1', '1', '0', '0', '1',
   '1', '2', '2', '1', '1', '0']
#


We know this can't be possibly right, but given what we know so far,
that's actually a good solution until we're given a purpose statement
of what the function is trying to compute.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] error in python code.

2016-06-21 Thread Danny Yoo
On Sun, Jun 19, 2016 at 10:38 PM, riaz tabassum  wrote:
> Sir  i have a problem to solve to python code. I have attached the pic of
> problem statement.


Hi Riaz,

Often when you're asking a question, starting with presentation of the
code is often the wrong order to attack a problem.


The reason is because code just *is*.  It executes.  Although we can
often detect certain patterns that are bug prone (as Peter notes with
iterating over a dictionary), other than that, the code looks like it
does something.

It runs, so it must be right, right?

No, of course not.

But that's the part you need to explain, the "what" and the "why".


What makes code "good" or "bad" is human evaluation, some expectation
that we have about what we want to happen.  These expectations are
something that's usually stated in terms *outside* of the code.


Specifically, when you say these two parts:

> Test Dataset:
> CGCAGATGTTTGCACGACTGTGACAC


> Correct output:
>
> ['0', '-1', '0', '-1', '-1', '0', '0', '0', '1', '1', '1', '1', '2', '1',
> '1', '0', '1', '1', '0', '0', '1', '1', '2', '2', '1', '1', '0']

then the immediate question is: why should that be the correct output?
 Why those numbers?  To an untrained eye, it seems like an entirely
arbitrary, meaningless sequence.


What do the numbers mean?

We can't trust the code to look for meaning, because presumably the
code is broken.

So we need something else.

You need to state some definitions so that we are sharing common
terminology.  What does "skew" mean, for example?


If you can explain the problem well enough, we should be able to
compute the correct output by hand, without looking at your code.



Hope that makes sense.  Please feel free to ask questions.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] error in python code.

2016-06-20 Thread Peter Otten
riaz tabassum wrote:

> Sir  i have a problem to solve to python code. I have attached the pic of
> problem statement.

This is a text-only mailing list. Please describe the problem you are trying 
to solve in plain English. Thank you.

> code which i write is pasted here.
> "def Skew(Genome):
> skew = {}
> #initializing the dictionary
> skew[0]=0#initializing the dictionary
> 
> for i  in  range(len(Genome)):
>   if i==0:
> 
>   if Genome[i]=='G':
> 
>   skew[i]=skew[i]+1
>   elif Genome[i]=='C':
> 
>skew[i]=skew[i]-1
>   else:
> 
>   skew[i]=skew[i]
> 
> 
>   elif Genome[i]=='G':
> 
>skew[i]=skew[i-1]+1
> 
> 
>   elif Genome[i]=='C':
>   skew[i]=skew[i-1]-1
> 
>   else:
>   skew[i]=skew[i-1]

Is the part above provided by your teacher? Then it's pobably correct and 
you can concentrate on

> # your code here
> return skew

Hint: the order of the items in a dict is undefined and you may even get 
different output when you run the same script twice.
As a simple way around this you can sort the keys and then create a list by 
looking up the corresponding values. 
Did you learn about list comprehensions? The sorted() function? Both may be 
useful.

> Genome="CGCAGATGTTTGCACGACTGTGACAC"
> print Skew(Genome).values()

That line should probably be 

print Skew(Genome)

as any data preprocessing is best done inside the Skew() function.
 
> #Sample Output:
> #0', '-1', '0', '-1', '-1', '0', '0', '0',
> #'1', '1', '1', '1', '2', '1', '1', '0', '1', '1',
> #'0', '0', '1', '1', '2', '2', '1', '1', '0'
> "
> 
> 
> But i am facing the problem that  i could not  include the first index
> which is initialized to zero in my answer.
> 
> 
> the error is shown as
> 
> Failed te #2.
> 
> Test Dataset:
> CGCAGATGTTTGCACGACTGTGACAC
> 
> Your output:
> ['-1', '0', '-1', '-1', '0', '0', '0', '1', '1', '1', '1', '2', '1',
> '1', '0', '1', '1', '0', '0', '1', '1', '2', '2', '1', '1', '0']
> 
> Correct output:
> 
> ['0', '-1', '0', '-1', '-1', '0', '0', '0', '1', '1', '1', '1', '2', '1',
> '1', '0', '1', '1', '0', '0', '1', '1', '2', '2', '1', '1', '0']
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


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


[Tutor] error in python code.

2016-06-20 Thread riaz tabassum
Sir  i have a problem to solve to python code. I have attached the pic of
problem statement.
code which i write is pasted here.
"def Skew(Genome):
skew = {}
#initializing the dictionary
skew[0]=0#initializing the dictionary

for i  in  range(len(Genome)):
  if i==0:

  if Genome[i]=='G':

  skew[i]=skew[i]+1
  elif Genome[i]=='C':

   skew[i]=skew[i]-1
  else:

  skew[i]=skew[i]


  elif Genome[i]=='G':

   skew[i]=skew[i-1]+1


  elif Genome[i]=='C':
  skew[i]=skew[i-1]-1

  else:
  skew[i]=skew[i-1]
# your code here
return skew


Genome="CGCAGATGTTTGCACGACTGTGACAC"
print Skew(Genome).values()

#Sample Output:
#0', '-1', '0', '-1', '-1', '0', '0', '0',
#'1', '1', '1', '1', '2', '1', '1', '0', '1', '1',
#'0', '0', '1', '1', '2', '2', '1', '1', '0'
"


But i am facing the problem that  i could not  include the first index
which is initialized to zero in my answer.


the error is shown as

Failed te #2.

Test Dataset:
CGCAGATGTTTGCACGACTGTGACAC

Your output:
['-1', '0', '-1', '-1', '0', '0', '0', '1', '1', '1', '1', '2', '1',
'1', '0', '1', '1', '0', '0', '1', '1', '2', '2', '1', '1', '0']

Correct output:

['0', '-1', '0', '-1', '-1', '0', '0', '0', '1', '1', '1', '1', '2', '1',
'1', '0', '1', '1', '0', '0', '1', '1', '2', '2', '1', '1', '0']
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Error getting cx_oracle to work with python 2.7

2015-01-13 Thread Arvind Ramachandran
Hi  All


I am trying to get import cx_oracle work on my windows laptop

I installed cx_Oracle-5.1.2-10g.win32-py2.7 on my laptop which is 64 bit as
the 64 bit msi seem to be specific for AMD desktops

Anyways after installed I do find cx_oracle.pyd in the lib site packages
folder

But when I try to pip install cx_oracle it gives an error saying it is
already established

When I issue python -c 'import cx_oracle' the error I get is
Import : EOL while scanning string literal
When I issue python -c import cx_oracle the error I get is
Import : No module named cx_oracle

My oracle version is 11.2.0.1.0

Please advice how I can get my oracle package to work so I can connected

If there is a better mailing list please let me know as well

-- 
Regards
Arvind Ramachandran

(414-530-8366)
=
Conference Dail In Numbers
Participant code  : 5751206
Leader code :7903519

USA1-517-466-2380   866-803-2146
INDIA
000-800-852-1259

=

-- 
This message and any files transmitted with it are the property of 
Sigma-Aldrich Corporation, are confidential, and are intended solely for 
the use of the person or entity to whom this e-mail is addressed. If you 
are not one of the named recipient(s) or otherwise have reason to believe 
that you have received this message in error, please contact the sender and 
delete this message immediately from your computer. Any other use, 
retention, dissemination, forwarding, printing, or copying of this e-mail 
is strictly prohibited.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error getting cx_oracle to work with python 2.7

2015-01-13 Thread Danny Yoo
 By the way, please use copy-and-paste when showing the inputs and
 outputs of what you're doing.  You should try to show verbatim output
 for any bug report or request for technical help.  If you don't, you
 can easily introduce mistakes that make it hard to diagnose what's
 going on.


I can't tell, given that you might be paraphrasing, whether or not you've typed

  cx_oracle

or:

  cx_Oracle

According to documentation on the web, it might make a difference.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error getting cx_oracle to work with python 2.7

2015-01-13 Thread Danny Yoo
On Tue, Jan 13, 2015 at 9:13 AM, Arvind Ramachandran
arvind.ramachand...@sial.com wrote:
 Hi  All


 I am trying to get import cx_oracle work on my windows laptop

 I installed cx_Oracle-5.1.2-10g.win32-py2.7 on my laptop which is 64 bit as
 the 64 bit msi seem to be specific for AMD desktops

 Anyways after installed I do find cx_oracle.pyd in the lib site packages
 folder

 But when I try to pip install cx_oracle it gives an error saying it is
 already established

 When I issue python -c 'import cx_oracle' the error I get is
 Import : EOL while scanning string literal
 When I issue python -c import cx_oracle the error I get is
 Import : No module named cx_oracle

 My oracle version is 11.2.0.1.0


Tutor is probably not going to be the best place to ask this database
question.  You should probably ask on cx-oracle-users:

 https://lists.sourceforge.net/lists/listinfo/cx-oracle-users


By the way, please use copy-and-paste when showing the inputs and
outputs of what you're doing.  You should try to show verbatim output
for any bug report or request for technical help.  If you don't, you
can easily introduce mistakes that make it hard to diagnose what's
going on.

I think that you've paraphrased the output from some of the error
messages, and it's making it really hard to tell what's going on.  The
message you're reporting looks really suspicious:

Import : No module named cx_oracle

because there are too many spaces between the colon and the message,
and it should be using the term ImportError, not just Import.  If
that's truly what you're getting, then something very strange is going
on.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error 22

2015-01-09 Thread diliup gabadamudalige
:)

On Thu, Jan 8, 2015 at 3:02 AM, Danny Yoo d...@hashcollision.org wrote:

  How I fix this error? when I open my python project (.py) it closes
  immediately.
 
  Since the op sent from Windows, I'm guessing he isn't opening up a cmd
  window then running his program.  But I'm not a windows guy lately.
  Perhaps someone can tell him how to invoke the program?

 I think we simply need more information.  Error 22 on Windows is,
 according to web searches, associated with some kind of device driver
 failure.  (What?!)

 So I am very confused.  Without knowing anything else about the
 program, I'm at a loss and my first instinct is to think that this has
 nothing to do with Python.  I think we don't have enough information,
 so let's hear back from the original questioner.
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 https://mail.python.org/mailman/listinfo/tutor




-- 
Diliup Gabadamudalige

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

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


Re: [Tutor] Error 22

2015-01-07 Thread Danny Yoo
 How I fix this error? when I open my python project (.py) it closes
 immediately.

 Since the op sent from Windows, I'm guessing he isn't opening up a cmd
 window then running his program.  But I'm not a windows guy lately.
 Perhaps someone can tell him how to invoke the program?

I think we simply need more information.  Error 22 on Windows is,
according to web searches, associated with some kind of device driver
failure.  (What?!)

So I am very confused.  Without knowing anything else about the
program, I'm at a loss and my first instinct is to think that this has
nothing to do with Python.  I think we don't have enough information,
so let's hear back from the original questioner.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error 22

2015-01-07 Thread Alan Gauld

On 08/01/15 01:14, ishay.yem...@gmail.com wrote:

How I fix this error? when I open my python project (.py) it closes immediately.

please help. /:



You need to tell us a lot more.

What does your project code do? What does it look like? Can you
send a small example that shows this error?

What OS are you using? What version of Python?
What development tool are you using to open your project?
How are you running the code?

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Error 22

2015-01-07 Thread Joel Goldstick
On Wed, Jan 7, 2015 at 1:06 PM, Alan Gauld alan.ga...@btinternet.com
wrote:

 On 08/01/15 01:14, ishay.yem...@gmail.com wrote:

 How I fix this error? when I open my python project (.py) it closes
 immediately.

 please help. /:



 Since the op sent from Windows, I'm guessing he isn't opening up a cmd
window then running his program.  But I'm not a windows guy lately.
Perhaps someone can tell him how to invoke the program?



 You need to tell us a lot more.

 What does your project code do? What does it look like? Can you
 send a small example that shows this error?

 What OS are you using? What version of Python?
 What development tool are you using to open your project?
 How are you running the code?

 --
 Alan G
 Author of the Learn to Program web site
 http://www.alan-g.me.uk/
 http://www.amazon.com/author/alan_gauld
 Follow my photo-blog on Flickr at:
 http://www.flickr.com/photos/alangauldphotos



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




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


[Tutor] Error 22

2015-01-07 Thread ishay.yemini
How I fix this error? when I open my python project (.py) it closes 
immediately. 

please help. /: 






Sent from Windows Mail
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error 22

2015-01-07 Thread Steven D'Aprano
On Thu, Jan 08, 2015 at 01:14:46AM +, ishay.yem...@gmail.com wrote:

 How I fix this error? when I open my python project (.py) it closes 
 immediately. 
 
 please help. /: 

You have given us no information to work with. You might as well have 
said my program doesn't work, please fix it. We don't know your 
program, we don't know your operating system, we don't know how you are 
opening your project, and we don't know where the mysterious Error 22 
in the subject line comes from. How can we possibly help you?



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


Re: [Tutor] Error 22

2015-01-07 Thread Mark Lawrence

On 08/01/2015 01:14, ishay.yem...@gmail.com wrote:

How I fix this error? when I open my python project (.py) it closes immediately.

please help. /:



Please provide us with your OS, Python version, the code that produced 
this error and the entire traceback.


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

Mark Lawrence

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


[Tutor] Error Cannot Import Name Core

2014-11-11 Thread Felisha Lawrence
Hello,
I am trying to install a version of pyart in OSX and I keep getting this
error

--ImportError
  Traceback (most recent call
last)ipython-input-21-bb2fade1b952 in module() 1 import pyart
/Users/felishalawrence/anaconda/lib/python2.7/site-packages/pyart/__init__.py
in module()  9 from .version import version as __version__
10 #import subpackages--- 11 from . import core 12 from . import
io 13 from . import correct
ImportError: cannot import name core


Any help as to what this means and how to fix it?

Thanks,
Felisha
-- 
Felisha Lawrence
Howard University Program for Atmospheric Sciences(HUPAS), Graduate Student

NASA URC/BCCSO Graduate Fellow
NOAA NCAS Graduate Fellow
Graduate Student Association for Atmospheric Sciences(GSAAS), Treasurer
(240)-535-6665 (cell)
felisha.lawre...@gmail.com (email)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error Cannot Import Name Core

2014-11-11 Thread Danny Yoo
On Tue Nov 11 2014 at 5:17:53 PM Felisha Lawrence 
felisha.lawre...@gmail.com wrote:

 Hello,
 I am trying to install a version of pyart in OSX and I keep getting this
 error

 --ImportError
Traceback (most recent call 
 last)ipython-input-21-bb2fade1b952 in module() 1 import pyart
 /Users/felishalawrence/anaconda/lib/python2.7/site-packages/pyart/__init__.py 
 in module()  9 from .version import version as __version__ 10 
 #import subpackages--- 11 from . import core 12 from . import io 13 
 from . import correct
 ImportError: cannot import name core


 Any help as to what this means and how to fix it?


I don't know what pyart is, unfortunately.

Web searches are hitting several projects that have the name 'pyart', but
have different functionality.  I will guess from context that you're
talking about:

http://arm-doe.github.io/pyart/

but can not be absolutely certain.  Please be specific about what
third-party package you're trying to use, because unfortunately it's
ambiguous.

How did you install pyart?  I would expect the error you're seeing only if
the third party package were incorrectly installed.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error Cannot Import Name Core

2014-11-11 Thread Dave Angel
Felisha Lawrence felisha.lawre...@gmail.com Wrote in message:
 Hello, 
 I am trying to install a version of pyart in OSX and I keep getting this 
 error 
 
 --
 ImportError   Traceback (most recent call last)
 ipython-input-21-bb2fade1b952 in module()
  1 import pyart
 
 /Users/felishalawrence/anaconda/lib/python2.7/site-packages/pyart/__init__.py 
 in module()
   9 from .version import version as __version__
  10 #import subpackages
 --- 11 from . import core
  12 from . import io
  13 from . import correct
 
 ImportError: cannot import name core
 
 Any help as to what this means and how to fix it?

Usually questions involving uncommon 3rd party packages do better
 elsewhere, first choice being the package's support site, and
 second being comp.lang.python . The tutor list is really focused
 on the python language and standard library. Still you may get
 lucky.

You should also always specify Python version, and exact source
 and version of the 3rd party package. Do this with the first
 query on any new thread you create, regardless of where you're
 posting. 

Still, I'm going to mae a wild guess, that the library is intended
 for Python 3.x, and you're trying to use it in 2.7

If my guess is right,  you could probably confirm it by giving the
 location for core.*  Somebody else might then confirm it has
 something to do with relative imports.

Or you could go back to the pyart site and see if they offer
 alternative downloads. 




-- 
DaveA

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


Re: [Tutor] Error in get pixel value in coordinate (x, y) using getPixel(x, y)

2014-08-18 Thread Whees Northbee
I'm so sorry for late reply, my laptop broken, the code actually I already
put in thread before so I'll copy to here..
I don't know how to get pixel, I just searched and many link using
'getPixel' to get value of pixel..
I know color frame using 3 channel B G R to get pixel, but I just want to
get pixel value in 1 channel, they said I need to use video in gray scale,
and I already convert my video to gray scale
Here's the code:

cap  =cv2.VideoCapture(c:\Users\Shiloh\Videos\AVI\MOV_5675.avi)
width=cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)
height   =cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)

NUM_SAMPLES  =20
RADIUS   =20
MIN_MATCHES  =2
SUBSAMPLE_FACTOR =16

c_xoff= [-1,  0,  1, -1, 1, -1, 0, 1, 0]
c_yoff= [-1,  0,  1, -1, 1, -1, 0, 1, 0]

while(1):
#Assign space and init
m_samples=[]

#height, width, depth=cap.shape
c_black=np.zeros( (height,width), dtype=np.uint8)
for i in range(0,NUM_SAMPLES,1):
m_samples.append(c_black)

m_mask=np.zeros( (width,height), dtype=np.uint8)
m_foregroundMathCount=np.zeros( (width,height), dtype=np.uint8)


# Capture frame-by-frame
ret, frame = cap.read()


#Init model from first frame
for i in range(0,width,1):
for j in range(0,height,1):
for k in range(0,NUM_SAMPLES,1):
random=np.random.randint(0,9)

row=i+c_yoff[random]
if(row0):
row=0
if(row=width):
row=width-1

col=j+c_xoff[random]
if(col0):
col=0
if(col=height):
col=height-1

m_samples[k][i][j]=getPixel(frame,row,col)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error message

2014-08-11 Thread Danny Yoo
Hi Richard,

I would recommend asking the PyGame folks on this one.  What you're
running into is specific to that external library, and folks who work
with PyGame have encountered the problem before: they'll know how to
diagnose and correct it.  For example:


http://stackoverflow.com/questions/7775948/no-matching-architecture-in-universal-wrapper-when-importing-pygame


http://stackoverflow.com/questions/8275808/installing-pygame-for-mac-os-x-10-6-8

What appears to be happening is a 32-bit vs 64-bit issue: you may have
installed a version of PyGame for one architecture, but should have
chosen the other.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Error message

2014-08-10 Thread RICHARD KENTISH
Hi!

Ive installed Python 2.7.8 and pygame 1.9.1 onto a macbook pro 10.9.4 Mavericks.

The code is taken direct from the 'making games' book. Here it is pasted from 
idle:

import pygame, sys
from pygame.locals import *

pygame.init()
displaysurf = pygame.dispaly.set_mode((400, 300))
pygame.display.set_caption('Hello World!')

while True: # main game loop
    for event in pygame.event.get():
        if event.type == quit:
            pygame.quit()
            sys.exit()
    pygame.display.update()

Here is the error I am getting.

Python 2.7.8 (v2.7.8:ee879c0ffa11, Jun 29 2014, 21:07:35) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type copyright, credits or license() for more information.
  RESTART 
 

Traceback (most recent call last):
  File /Users/richardkentish/Desktop/Python resources/blankgame.py, line 1, 
in module
    import pygame, sys
  File 
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py,
 line 95, in module
    from pygame.base import *
ImportError: 
dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so,
 2): no suitable image found.  Did find:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so:
 no matching architecture in universal wrapper


Thanks for your help.

Best wishes,

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


Re: [Tutor] Error message

2014-08-10 Thread Steven D'Aprano
On Sun, Aug 10, 2014 at 10:32:52AM +0100, RICHARD KENTISH wrote:
 Hi!
 
 Ive installed Python 2.7.8 and pygame 1.9.1 onto a macbook pro 10.9.4 
 Mavericks.
 
 The code is taken direct from the 'making games' book. Here it is pasted from 
 idle:

Whenever you have a mysterious error in Python that doesn't appear to be 
an error on your part -- and I admit that as a beginner, it's hard to 
tell which errors are yours and which aren't -- it's always worth trying 
again running Python directly. IDEs like IDLE sometimes do funny things 
to the environment in order to provide an Integrated Development 
Environment, and occasionally they can interfere with the clean running 
of Python code. So, just to be sure, I suggest you try running your code 
again outside of IDLE:

* Save your code to a file (which I see you've already done).

* Open up a terminal so you have a command line.

* Change into the directory where your file is saved. Type this command:

  cd /Users/richardkentish/Desktop/Python resources

  then press ENTER.

* Run the file directly using Python by typing this command:

  python blankgame.py

  then press ENTER.

If the error goes away, and you either get no error at all, or a 
different error, then it may be a problem with IDLE. Copy and paste the 
error here, and we can advise further.

Having said all that, looking at the exception you get:

 Traceback (most recent call last):
   File /Users/richardkentish/Desktop/Python resources/blankgame.py, line 1, 
 in module
     import pygame, sys
   File 
 /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py,
  line 95, in module
     from pygame.base import *
 ImportError: 
 dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so,
  
 2): no suitable image found.  Did find: 
 /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so:
  
 no matching architecture in universal wrapper

it looks to me like perhaps you have a version of Pygame which is not 
compatible with the Mac. How did you install it? I'm not a Mac expert 
(it's been about, oh, 17 years since I've used a Mac) but somebody else 
may be able to advise.


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


[Tutor] Error in printing out totalSystolic on paper (1018)

2014-08-10 Thread Ken G.

Receiving the following error from the terminal screen:

Traceback (most recent call last):
  File Blood Pressure05Print45.py, line 95, in module
pr.write(totalSystolic)
TypeError: expected a character buffer object

Portion of strip:
=

pr.write ( ), pr.write (pulse), pr.write (\n)
totalSystolic = totalSystolic + int(systolic)
totalDiastolic = totalDiastolic + int(diastolic)
totalPulse = totalPulse + int(pulse)
file1.close()
print
print totalSystolic, totalDiastolic, totalPulse

# sys.exit()

pr.write(totalSystolic)
# pr.write(totalDiastolic)
# pr.write(totalPulse)

==

I know that totalSystolic is 1018, totalDiastolic is 469 and
totalPulse is 465.

I can not figure out why pr.write won't print out 1018 on paper.

Using Python 2.7 on Ubuntu 12.04.5 and using Geany to process the strip.

Thanks for your suggestion.

Ken

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


Re: [Tutor] Error in printing out totalSystolic on paper (1018)

2014-08-10 Thread Peter Otten
Ken G. wrote:

 Receiving the following error from the terminal screen:
 
 Traceback (most recent call last):
File Blood Pressure05Print45.py, line 95, in module
 pr.write(totalSystolic)
 TypeError: expected a character buffer object
 
 Portion of strip:
 =
 
  pr.write ( ), pr.write (pulse), pr.write (\n)
  totalSystolic = totalSystolic + int(systolic)
  totalDiastolic = totalDiastolic + int(diastolic)
  totalPulse = totalPulse + int(pulse)
 file1.close()
 print
 print totalSystolic, totalDiastolic, totalPulse
 
 # sys.exit()
 
 pr.write(totalSystolic)
 # pr.write(totalDiastolic)
 # pr.write(totalPulse)
 
 ==
 
 I know that totalSystolic is 1018, totalDiastolic is 469 and
 totalPulse is 465.
 
 I can not figure out why pr.write won't print out 1018 on paper.
 
 Using Python 2.7 on Ubuntu 12.04.5 and using Geany to process the strip.
 
 Thanks for your suggestion.

Assuming that pr is a file object the write() method accepts only strings. 
You are passing an integer. To fix your code you can either convert 
explicitly

pr.write(str(totalSystolic))

or implicitly

print  pr, totalSystolic 

(as usual print appends a newline).

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


Re: [Tutor] Error in printing out totalSystolic on paper (1018)

2014-08-10 Thread Ken G.


On 08/10/2014 10:38 AM, Alex Kleider wrote:

On 2014-08-10 06:41, Ken G. wrote:

Receiving the following error from the terminal screen:

Traceback (most recent call last):
  File Blood Pressure05Print45.py, line 95, in module
pr.write(totalSystolic)
TypeError: expected a character buffer object

Portion of strip:
=

pr.write ( ), pr.write (pulse), pr.write (\n)
totalSystolic = totalSystolic + int(systolic)
totalDiastolic = totalDiastolic + int(diastolic)
totalPulse = totalPulse + int(pulse)
file1.close()
print
print totalSystolic, totalDiastolic, totalPulse

# sys.exit()

pr.write(totalSystolic)
# pr.write(totalDiastolic)
# pr.write(totalPulse)

==

I know that totalSystolic is 1018, totalDiastolic is 469 and
totalPulse is 465.

I can not figure out why pr.write won't print out 1018 on paper.

Using Python 2.7 on Ubuntu 12.04.5 and using Geany to process the strip.

Thanks for your suggestion.

Ken



I'm guessing that you've defined pr.write(string) to take a string 
object but have fed it an integer- hence type error: try 
pr.write(str(totalSystolic))

instead of just pr.write(totalSystolic)

By the way, those are incredibly high numbers! What units are you using?


Thank you, I will try pr.write(str(totalSystolic)). As for the high
numbers, they are a total of 8 readings, therefore,

Systolic:  1018/8 = 127.25
Diastolic:  469/8 = 58.625
Pulse:  465/8 = 58.125

Again, thanks.

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


Re: [Tutor] Error in printing out totalSystolic on paper (1018) [SOLVED]

2014-08-10 Thread Ken G.

Thanks you to the list for helping me solve my problem. I never
had problem using and printing on paper pr.write in my coding
until this latest one popped up. Yeah, this old dog is still
learning new tricks here. LOL.

Again, thanks.

Ken


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


Re: [Tutor] Error message

2014-08-10 Thread RICHARD KENTISH
Hi All,

I have found a work around - not entirely sure what I did but followed this 
website 
http://www.reddit.com/r/pygame/comments/21tp7n/how_to_install_pygame_on_osx_mavericks/

Still can't run through idle but dragging the saved .py file to the python 
launcher works!

Thanks for your help.

Best wishes,

Richard



 From: RICHARD KENTISH r.kent...@btinternet.com
To: tutor@python.org tutor@python.org 
Sent: Sunday, 10 August 2014, 10:32
Subject: [Tutor] Error message
 


Hi!

Ive installed Python 2.7.8 and pygame 1.9.1 onto a macbook pro 10.9.4 Mavericks.

The code is taken direct from the 'making games' book. Here it is pasted from 
idle:

import pygame, sys
from pygame.locals import *

pygame.init()
displaysurf = pygame.dispaly.set_mode((400, 300))
pygame.display.set_caption('Hello World!')

while True: # main game loop
    for event in pygame.event.get():
        if event.type == quit:
            pygame.quit()
            sys.exit()
    pygame.display.update()

Here is the error I am getting.

Python 2.7.8 (v2.7.8:ee879c0ffa11, Jun 29 2014, 21:07:35) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type copyright, credits or license() for more information.
  RESTART 
 

Traceback (most recent call last):
  File /Users/richardkentish/Desktop/Python resources/blankgame.py, line 1, 
in module
    import pygame, sys
  File 
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py,
 line 95, in module
    from pygame.base import *
ImportError: 
dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so,
 2): no suitable image found.  Did find:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so:
 no matching architecture in universal wrapper


Thanks for your help.

Best wishes,

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


Re: [Tutor] Error message

2014-08-10 Thread RICHARD KENTISH
Thanks for your response. I have tried your suggestion and get the same error.  
Here's the text from terminal.

Richards-MacBook-Pro:Python resources richardkentish$ pwd
/Users/richardkentish/desktop/Python resources
Richards-MacBook-Pro:Python resources richardkentish$ python blankgame.py
Traceback (most recent call last):
  File blankgame.py, line 1, in module
    import pygame, sys
  File 
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py,
 line 95, in module
    from pygame.base import *
ImportError: 
dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so,
 2): no suitable image found.  Did find:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so:
 no matching architecture in universal wrapper
Richards-MacBook-Pro:Python resources richardkentish$ 

I installed the python files from the python site, latest version for mac.

Best wishes,

Richard



 From: Steven D'Aprano st...@pearwood.info
To: tutor@python.org 
Sent: Sunday, 10 August 2014, 12:30
Subject: Re: [Tutor] Error message
 

On Sun, Aug 10, 2014 at 10:32:52AM +0100, RICHARD KENTISH wrote:
 Hi!
 
 Ive installed Python 2.7.8 and pygame 1.9.1 onto a macbook pro 10.9.4 
 Mavericks.
 
 The code is taken direct from the 'making games' book. Here it is pasted from 
 idle:

Whenever you have a mysterious error in Python that doesn't appear to be 
an error on your part -- and I admit that as a beginner, it's hard to 
tell which errors are yours and which aren't -- it's always worth trying 
again running Python directly. IDEs like IDLE sometimes do funny things 
to the environment in order to provide an Integrated Development 
Environment, and occasionally they can interfere with the clean running 
of Python code. So, just to be sure, I suggest you try running your code 
again outside of IDLE:

* Save your code to a file (which I see you've already done).

* Open up a terminal so you have a command line.

* Change into the directory where your file is saved. Type this command:

  cd /Users/richardkentish/Desktop/Python resources

  then press ENTER.

* Run the file directly using Python by typing this command:

  python blankgame.py

  then press ENTER.

If the error goes away, and you either get no error at all, or a 
different error, then it may be a problem with IDLE. Copy and paste the 
error here, and we can advise further.

Having said all that, looking at the exception you get:


 Traceback (most recent call last):
   File /Users/richardkentish/Desktop/Python resources/blankgame.py, line 1, 
 in module
     import pygame, sys
   File 
 /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py,
  line 95, in module
     from pygame.base import *
 ImportError: 
 dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so,
  
 2): no suitable image found.  Did find: 
 /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so:
  
 no matching architecture in universal wrapper

it looks to me like perhaps you have a version of Pygame which is not 
compatible with the Mac. How did you install it? I'm not a Mac expert 
(it's been about, oh, 17 years since I've used a Mac) but somebody else 
may be able to advise.


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


Re: [Tutor] Error in get pixel value in coordinate (x, y) using getPixel(x, y)

2014-08-08 Thread Steven D'Aprano
On Thu, Aug 07, 2014 at 06:49:02PM +0700, Whees Northbee wrote:
 Please help me... I'm using python 2.7.6, numpy 1.8.1, opencv 2.4.9..
 I want to get pixel value in one number like 255 not each value like these
 R(190), G(23), B(45) from coordinate (x,y)...
 I try these code
 m_samples[k][i][j]=getPixel(img,row,col)
 
 But get error:
 NameError: name 'getPixel' is not defined
 
 If I change the format become:
 m_samples[k][i][j]=img.getPixel(row,col)
 
 Still error:
 AttributeError: 'numpy.ndarray' object has no attribute 'getpixel'
 
 Please help me..

We cannot help you unless you help us. Where does getPixel come from? 
What does the documentation for it say?

getPixel is not a built-in Python function, and I don't believe it is a 
standard numpy or opencv function (although I could be wrong). So unless 
you tell us where getPixel comes from, we have no possible way of 
telling how to use it.


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


[Tutor] Error in get pixel value in coordinate (x, y) using getPixel(x, y)

2014-08-07 Thread Whees Northbee
Please help me... I'm using python 2.7.6, numpy 1.8.1, opencv 2.4.9..
I want to get pixel value in one number like 255 not each value like these
R(190), G(23), B(45) from coordinate (x,y)...
I try these code
m_samples[k][i][j]=getPixel(img,row,col)

But get error:
NameError: name 'getPixel' is not defined

If I change the format become:
m_samples[k][i][j]=img.getPixel(row,col)

Still error:
AttributeError: 'numpy.ndarray' object has no attribute 'getpixel'

Please help me..

Thanks,

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


Re: [Tutor] Error in get pixel value in coordinate (x, y) using getPixel(x, y)

2014-08-07 Thread Alan Gauld

On 07/08/14 12:49, Whees Northbee wrote:

Please help me... I'm using python 2.7.6, numpy 1.8.1, opencv 2.4.9..
I want to get pixel value in one number like 255 not each value like
these R(190), G(23), B(45) from coordinate (x,y)...


What do you expect that number to look like? The pixels are represented 
by the 3 colours RGB. Are you wanting to just join the 3 bytes together 
to create an arbitrary number? Or do you think this number will mean 
something?



I try these code
m_samples[k][i][j]=getPixel(img,row,col)

But get error:
NameError: name 'getPixel' is not defined


So the getPixel function doesn't exist in your namespace.
Where do you think it comes from?


If I change the format become:
m_samples[k][i][j]=img.getPixel(row,col)

Still error:
AttributeError: 'numpy.ndarray' object has no attribute 'getpixel'


And its not a part of a numpy ndarray - what made you think it was?

Arte you just guessing? Or did you saee some code that
uses getPixel() somewhere?


Please help me..


The tutor list is for those learning Python and its standard library. 
Numpy is not part of that, so your question is slightly off list. but 
your error looks so elementary that we may be able to help if you give 
us more information.


Also, please *always* send full error messages, not just the last line.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

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


Re: [Tutor] Error in get pixel value in coordinate (x, y) using getPixel(x, y)

2014-08-07 Thread Joel Goldstick
On Thu, Aug 7, 2014 at 7:49 AM, Whees Northbee ch.de2.2...@gmail.com wrote:
 Please help me... I'm using python 2.7.6, numpy 1.8.1, opencv 2.4.9..
 I want to get pixel value in one number like 255 not each value like these
 R(190), G(23), B(45) from coordinate (x,y)...
 I try these code
 m_samples[k][i][j]=getPixel(img,row,col)

 But get error:
 NameError: name 'getPixel' is not defined

 If I change the format become:
 m_samples[k][i][j]=img.getPixel(row,col)

 Still error:
 AttributeError: 'numpy.ndarray' object has no attribute 'getpixel'

 Please help me..

 Thanks,

 Northbee

What module is getPixel from? Do you have that module imported?
Its best if you show complete traceback, and other relevant code

I'm guessing that img is what you imported from numpy.ndarray.  But it
looks to me like getPixel comes from pil


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




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


Re: [Tutor] Error Handling in python

2014-07-25 Thread jitendra gupta
@All Thanks a lot,

Yes set -e It work fine. This is what I am looking for but I got some
extra things to learn :) .

Thanks you again

Thanks
Jitendra


On Thu, Jul 24, 2014 at 6:10 PM, Wolfgang Maier 
wolfgang.ma...@biologie.uni-freiburg.de wrote:

 On 24.07.2014 14:37, Chris “Kwpolska” Warrick wrote:


 It’s recommended to switch to the [[ syntax anyways, some people
 consider [ deprecated.  Also, [ is actually /bin/[ while [[ lives in
 your shell (and is therefore faster).

 About the equals sign, == is the preferred syntax, and = is also
 considered deprecated (zsh explicitly says so, bash says “only for
 POSIX compatibility”.


 I see. There is always something to learn, thanks (even if it's not
 Python-related as Steven points out correctly) :)


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

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


[Tutor] Error Handling in python

2014-07-24 Thread jitendra gupta
Hi All

My shell script is not throwing any error when I am having  some error in
Python code.

 test.py ~~
def main():
print Test
#some case error need to be thrown
raise Exception(Here is error)

if __name__ == __main__
main()
~~
 second.py ~~
def main():
print Second function is called


if __name__ == __main__
main()
~~

~ shellTest.sh ~~~
python test.py
python second.py
~~~

In this case, I dont want to run my second.py
Even I am throwing error from my test.py, but still second.py is getting
executed, which i dont want,


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


Re: [Tutor] Error Handling in python

2014-07-24 Thread Chris “Kwpolska” Warrick
On Thu, Jul 24, 2014 at 1:35 PM, jitendra gupta jitu.ic...@gmail.com wrote:
 Hi All

 My shell script is not throwing any error when I am having  some error in
 Python code.

 In this case, I dont want to run my second.py
 Even I am throwing error from my test.py, but still second.py is getting
 executed, which i dont want,

You must expilicitly ask your shell to do exit if something fails.  Like this:

~ shellTest.sh ~~~
#!/bin/bash
set -e
python test.py
python second.py
~~~

I explicitly set the shell to /bin/bash on the shebang line, and then
set the -e option to fail when a command exits with a non-zero status.

You should always have a shebang line in your shell files, and execute
them as ./shellTest.sh  (after chmod +x shellTest.sh); moreover, one
for Python files is recommended, like this: #!/usr/bin/env python

-- 
Chris “Kwpolska” Warrick http://chriswarrick.com/
PGP: 5EAAEA16
stop html mail | always bottom-post | only UTF-8 makes sense
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error Handling in python

2014-07-24 Thread Wolfgang Maier

On 24.07.2014 13:35, jitendra gupta wrote:

Hi All

My shell script is not throwing any error when I am having  some error
in Python code.

 test.py ~~
def main():
 print Test
 #some case error need to be thrown
 raise Exception(Here is error)

if __name__ == __main__
 main()
~~
 second.py ~~
def main():
 print Second function is called


if __name__ == __main__
 main()
~~

~ shellTest.sh ~~~
python test.py
python second.py
~~~

In this case, I dont want to run my second.py
Even I am throwing error from my test.py, but still second.py is getting
executed, which i dont want,



Your shell script calls runs the two Python scripts separately, that is, 
it first starts a Python interpreter telling it to run test.py .
When that is done (with whatever outcome !), it starts the interpreter a 
second time telling it to run second.py now.
The exception stops the execution of test.py, of course, and causes the 
interpreter to return, but your shell script is responsible for checking 
the exit status of the first script if it wants to run the second call 
only conditionally.


Try something like this (assuming bash):

python test.py
if [ $? = 0 ]; then
python second.py
fi

as your shell script.

By the way, both Python scripts you posted contain a syntax error, but I 
leave spotting it up to you.


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


Re: [Tutor] Error Handling in python

2014-07-24 Thread Steven D'Aprano
On Thu, Jul 24, 2014 at 05:05:24PM +0530, jitendra gupta wrote:
 Hi All
 
 My shell script is not throwing any error when I am having  some error in
 Python code.

This is a question about the shell, not about Python. I'm not an expert 
on shell scripting, but I'll try to give an answer.


 ~ shellTest.sh ~~~
 python test.py
 python second.py


One fix is to check the return code of the first python process:

[steve@ando ~]$ python -c pass
[steve@ando ~]$ echo $?
0
[steve@ando ~]$ python -c raise Exception
Traceback (most recent call last):
  File string, line 1, in module
Exception
[steve@ando ~]$ echo $?
1


Remember that to the shell, 0 means no error and anything else is an 
error. So your shell script could look like this:

python test.py
if [ $? -eq 0 ]
then
  python second.py
fi



Another way (probably better) is to tell the shell to automatically exit 
if any command fails:


set -e
python test.py
python second.py



Hope this helps,


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


Re: [Tutor] Error Handling in python

2014-07-24 Thread Chris “Kwpolska” Warrick
On Thu, Jul 24, 2014 at 2:01 PM, Wolfgang Maier
wolfgang.ma...@biologie.uni-freiburg.de wrote:
 Try something like this (assuming bash):

 python test.py
 if [ $? = 0 ]; then
 python second.py
 fi

 as your shell script.

The [ ] and = should be doubled.  But all this is not needed, all you need is:

python test.py  python second.py

However, you need to explicitly stack all the commands you want to
execute this way — so, if there are more things, `set -e` might also
be of use. (you would need an even uglier tree for `if`s.)

-- 
Chris “Kwpolska” Warrick http://chriswarrick.com/
PGP: 5EAAEA16
stop html mail | always bottom-post | only UTF-8 makes sense
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error Handling in python

2014-07-24 Thread Wolfgang Maier

On 24.07.2014 14:09, Chris “Kwpolska” Warrick wrote:

On Thu, Jul 24, 2014 at 2:01 PM, Wolfgang Maier
wolfgang.ma...@biologie.uni-freiburg.de wrote:

Try something like this (assuming bash):

python test.py
if [ $? = 0 ]; then
 python second.py
fi

as your shell script.


The [ ] and = should be doubled.


?? why that ?

But all this is not needed, all you need is:


python test.py  python second.py


I agree, that's far more elegant in this case.



However, you need to explicitly stack all the commands you want to
execute this way — so, if there are more things, `set -e` might also
be of use. (you would need an even uglier tree for `if`s.)


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


Re: [Tutor] Error Handling in python

2014-07-24 Thread Chris “Kwpolska” Warrick
On Thu, Jul 24, 2014 at 2:14 PM, Wolfgang Maier
wolfgang.ma...@biologie.uni-freiburg.de wrote:
 On 24.07.2014 14:09, Chris “Kwpolska” Warrick wrote:

 On Thu, Jul 24, 2014 at 2:01 PM, Wolfgang Maier
 wolfgang.ma...@biologie.uni-freiburg.de wrote:

 Try something like this (assuming bash):

 python test.py
 if [ $? = 0 ]; then
  python second.py
 fi

 as your shell script.


 The [ ] and = should be doubled.


 ?? why that ?

Double brackets can do more:

http://stackoverflow.com/questions/2188199/how-to-use-double-or-single-bracket-parentheses-curly-braces

-- 
Chris “Kwpolska” Warrick http://chriswarrick.com/
PGP: 5EAAEA16
stop html mail | always bottom-post | only UTF-8 makes sense
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error Handling in python

2014-07-24 Thread Wolfgang Maier

On 24.07.2014 14:19, Chris “Kwpolska” Warrick wrote:



python test.py
if [ $? = 0 ]; then
  python second.py
fi

as your shell script.



The [ ] and = should be doubled.



?? why that ?


Double brackets can do more:

http://stackoverflow.com/questions/2188199/how-to-use-double-or-single-bracket-parentheses-curly-braces



But more is not required here. What am I missing ?

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


Re: [Tutor] Error Handling in python

2014-07-24 Thread Chris “Kwpolska” Warrick
On Thu, Jul 24, 2014 at 2:23 PM, Wolfgang Maier
wolfgang.ma...@biologie.uni-freiburg.de wrote:
 On 24.07.2014 14:19, Chris “Kwpolska” Warrick wrote:


 python test.py
 if [ $? = 0 ]; then
   python second.py
 fi

 as your shell script.



 The [ ] and = should be doubled.



 ?? why that ?


 Double brackets can do more:


 http://stackoverflow.com/questions/2188199/how-to-use-double-or-single-bracket-parentheses-curly-braces


 But more is not required here. What am I missing ?

It’s recommended to switch to the [[ syntax anyways, some people
consider [ deprecated.  Also, [ is actually /bin/[ while [[ lives in
your shell (and is therefore faster).

About the equals sign, == is the preferred syntax, and = is also
considered deprecated (zsh explicitly says so, bash says “only for
POSIX compatibility”.

-- 
Chris “Kwpolska” Warrick http://chriswarrick.com/
PGP: 5EAAEA16
stop html mail | always bottom-post | only UTF-8 makes sense
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error Handling in python

2014-07-24 Thread Wolfgang Maier

On 24.07.2014 14:37, Chris “Kwpolska” Warrick wrote:


It’s recommended to switch to the [[ syntax anyways, some people
consider [ deprecated.  Also, [ is actually /bin/[ while [[ lives in
your shell (and is therefore faster).

About the equals sign, == is the preferred syntax, and = is also
considered deprecated (zsh explicitly says so, bash says “only for
POSIX compatibility”.



I see. There is always something to learn, thanks (even if it's not 
Python-related as Steven points out correctly) :)


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


[Tutor] Error message received when running “from scipy import interpolate”

2014-06-05 Thread Colin Ross
I am attempting to run the following in python:

from scipy import interpolate

I receive this error message:

Traceback (most recent call last):
  File stdin, line 1, in module
  File 
/Library/Python/2.7/site-packages/scipy-0.11.0.dev_0496569_20111005-py2.7-macosx-10.7-x86_64.egg/scipy/interpolate/__init__.py,
line 156, in module
from ndgriddata import *
  File 
/Library/Python/2.7/site-packages/scipy-0.11.0.dev_0496569_20111005-py2.7-macosx-10.7-x86_64.egg/scipy/interpolate/ndgriddata.py,
line 9, in module
from interpnd import LinearNDInterpolator, NDInterpolatorBase, \
  File numpy.pxd, line 172, in init interpnd
(scipy/interpolate/interpnd.c:7696)ValueError: numpy.ndarray has the
wrong size, try recompiling

I am currently running Mac OS X Lion 10.7.5 and Python 2.7.1. with MacPorts
installed.

I am attempting to run the code on a different computer than it was created
on. After doing some reading my understanding is that this error may be a
result of the ABI not being forward compatible. To try and solve the issue
I updated my MacPorts and then ran ($ sudo port upgrade outdated) to
upgrade the installed ports. However, the same error continues to appear
when I try and run the code.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error message received when running “from scipy import interpolate”

2014-06-05 Thread Alan Gauld

On 05/06/14 23:36, Colin Ross wrote:

I am attempting to run the following in python:

|from  scipyimport  interpolate|


This list is for those learning the core Python language and its 
standard library.


Support for scipy is probably best gained from the scipy forum
The MacPython list may also be able to help with MacOS specific queries.

But there are some Mac/Scipy users here so I'll leave it to them to 
chime in if they can help.



I receive this error message:

|Traceback  (most recent call last):
   File  stdin,  line1,  in  module
   File  
/Library/Python/2.7/site-packages/scipy-0.11.0.dev_0496569_20111005-py2.7-macosx-10.7-x86_64.egg/scipy/interpolate/__init__.py,
  line156,  in  module
 from  ndgriddataimport  *
   File  
/Library/Python/2.7/site-packages/scipy-0.11.0.dev_0496569_20111005-py2.7-macosx-10.7-x86_64.egg/scipy/interpolate/ndgriddata.py,
  line9,  in  module
 from  interpndimport  LinearNDInterpolator,  NDInterpolatorBase,  \
   File  numpy.pxd,  line172,  in  init 
interpnd(scipy/interpolate/interpnd.c:7696)
ValueError:  numpy.ndarray has the wrong size,  try  recompiling|

I am currently running Mac OS X Lion 10.7.5 and Python 2.7.1. with
MacPorts installed.

I am attempting to run the code on a different computer than it was
created on. After doing some reading my understanding is that this error
may be a result of the ABI not being forward compatible. To try and
solve the issue I updated my MacPorts and then ran ($ sudo port upgrade
outdated) to upgrade the installed ports. However, the same error
continues to appear when I try and run the code.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

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


[Tutor] Error

2014-04-21 Thread Geocrafter .
im trying to make a board, and is detecting the pieces. Here is my code:
http://pastebin.com/L3tQLV2g And here is the error:
http://pastebin.com/4FiJmywL  Do you knwo hwo to fix it?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error

2014-04-21 Thread Alan Gauld

On 21/04/14 19:41, Geocrafter . wrote:

im trying to make a board, and is detecting the pieces. Here is my
code:http://pastebin.com/L3tQLV2g And here is the error:
http://pastebin.com/4FiJmywL  Do you knwo hwo to fix it?


You are passing in a cell location that results in an index out of range.

Try figuring out what happens when x is 6 for example.

BTW Cant you combine those two enormous if statements into one by just 
passing ionm the test character(x or y) as an parameter?

Like this:

def check_around(x, y, test='x'):
   if test == 'x': check = 'o'
   elif test == 'o': check = 'x'
   else: raise ValueError

   if board[x][y] == test:
  if board[x - 3][y - 3] == check or board[x - 2][y - 3] == check
  or board[x - 1][y - 3] == check or...

However even better would be to get rid of the huge if statement and 
replace it with loops to generate the indices. Pythons range function 
can deal with negatives too:


Try:

 print list(range(-3,4))

to see if that gives you any ideas.

Finally your mqain code doesn't appear to do anything very much...

for x in range (0, 7):
for y in range (0, 7):
check_aroundx(x, y)

This only checks the x cells. It would be better practice
to have the function return a result that you can print
externally. Maybe return a list of touching cells say?

# sys.stdout.write (%c % (board[x][y]))
print

And these two lines don't do anything much.

Just some thoughts.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

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


[Tutor] Error :SyntaxError: 'break' outside loop

2013-08-19 Thread Zoya Tavakkoli
Hi everyone

I write this code for color segmentation ,but after Run I recived this
error:

SyntaxError: 'break' outside loop

I could not resolve that ,could you please help me?

python.2.7.5

import cv2
import numpy as np

cap = cv2.VideoCapture(C:\Users\Zohreh\Desktop\Abdomen.MST)

while (1):
 _, frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])

mask = cv2.inRange(hsv, lower_blue, upper_blue)
res = cv2.bitwise_and(frame,frame, mask= mask)

cv2.imshow(frame,frame)
cv2.imshow(mask,mask)
cv2.imshow(res,res)


k = cv2.waitkey(5)  0xFF
if k == 27:

 break


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


Re: [Tutor] Error :SyntaxError: 'break' outside loop

2013-08-19 Thread Chris Down
On 2013-08-18 10:18, Zoya Tavakkoli wrote:
 if k == 27:

  break

Well, you're not in a function here, so break doesn't make any sense. What is
it that you want to do?


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


Re: [Tutor] Error :SyntaxError: 'break' outside loop

2013-08-19 Thread Chris Down
On 2013-08-19 10:55, Chris Down wrote:
 On 2013-08-18 10:18, Zoya Tavakkoli wrote:
  if k == 27:
 
   break

 Well, you're not in a function here, so break doesn't make any sense. What is
 it that you want to do?

s/function/loop/


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


Re: [Tutor] Error :SyntaxError: 'break' outside loop

2013-08-19 Thread Steven D'Aprano
Hello Zoya, and welcome!


On Sun, Aug 18, 2013 at 10:18:06AM -0700, Zoya Tavakkoli wrote:
 Hi everyone
 
 I write this code for color segmentation ,but after Run I recived this
 error:
 
 SyntaxError: 'break' outside loop
 
 I could not resolve that ,could you please help me?

Is the error message not clear enough? You have a 'break' command 
outside of a loop. If the error message is not clear enough, please 
suggest something that would be more clear. Also, you should read the 
entire traceback, which will show you not just the error, but the exact 
line causing the problem.

For example, these two are legal:

# Legal
while x  100:
if y == 0:
break
...


# Also legal
for i in range(1000):
if x  20:
break
...


But not this:

# Not legal
if x  20:
break


You can't break out of a loop, if you aren't inside a loop to begin 
with.


 while (1):
  _, frame = cap.read()

You have a while loop with only one line. It loops forever, and never 
exits. Are you sure that's what you want?

By the way, it is much, much, much easier to see indentation when you 
make it four spaces or eight. Good programmer's editors let you set 
indentation to four or eight spaces. Even Notepad, which is *not* a 
programmer's editor, lets you hit the Tab key and indent. 


 hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

Because this line is not indented, it is not inside the loop.


 if k == 27:
 
  break

Again, because the if line is not indented, it is outside the loop, 
and so the break is illegal.


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


Re: [Tutor] Error in Game

2013-07-03 Thread bob gailer

On 7/2/2013 4:22 PM, Jack Little wrote:

I know the code is correct

As Joel said- how could it be, since you do not get the desired results?

When posting questions tell us:
- what version of Python?
- what operating system?
- what you use to edit (write) your code
- what you do to run your code
copy and paste the execution


, but it doesn't send the player to the shop. Here is the code:

def lvl3_2():
print You beat level 3!
print Congratulations!
print You have liberated the Bristol Channel!
print [Y] to go to the shop or [N] to advance.
final1=raw_input()
if final1.lower()==y:
shop2()
elif final1.lower()==n:
lvl4()
It is a good idea to add an else clause to handle the case where the 
user's entry does not match the if or elif tests.


It is not a good idea to use recursion to navigate a game structure. It 
is better to have each function return to a main program, have the main 
program determine the next step and invoke it.




Help?
Since we are volunteers, the more you tell us the easier it is for us to 
do that.


--
Bob Gailer
919-636-4239
Chapel Hill NC
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Error in Game

2013-07-02 Thread Jack Little
The player has an option to upgrade or not. I know the code is correct, but it 
doesn't send the player to the shop. Here is the code:

def lvl3_2():
    print You beat level 3!
    print Congratulations!
    print You have liberated the Bristol Channel!
    print [Y] to go to the shop or [N] to advance.
    final1=raw_input()
    if final1.lower()==y:
        shop2()
    elif final1.lower()==n:
        lvl4()



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


Re: [Tutor] Error in Game

2013-07-02 Thread Alan Gauld

On 02/07/13 21:22, Jack Little wrote:

The player has an option to upgrade or not. I know the code is correct,
but it doesn't send the player to the shop.


So what does it do?


def lvl3_2():
 print You beat level 3!
 print Congratulations!
 print You have liberated the Bristol Channel!
 print [Y] to go to the shop or [N] to advance.
 final1=raw_input()
 if final1.lower()==y:
 shop2()
 elif final1.lower()==n:
 lvl4()


Have you tried putting some debug print statement in?
For example

  
  if final1.lower()==y:
  print 'going to shop2'
  shop2()
  elif final1.lower()==n:
  print 'advancing'
  lvl4()

And in the shop2() and lvl4() functions a print to
show you got there?

Just some ideas.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


Re: [Tutor] Error in Game

2013-07-02 Thread Joel Goldstick
On Tue, Jul 2, 2013 at 4:22 PM, Jack Little jacklittl...@yahoo.com wrote:

 The player has an option to upgrade or not. I know the code is correct,
 but it doesn't send the player to the shop. Here is the code:

 def lvl3_2():
 print You beat level 3!
 print Congratulations!
 print You have liberated the Bristol Channel!
 print [Y] to go to the shop or [N] to advance.
 final1=raw_input()
 if final1.lower()==y:
 shop2()
 elif final1.lower()==n:
 lvl4()


What does 'upgrade' have to do with this code?
when you run this code, what is the traceback ?
How do you know the code is correct?  Isn't the definition of the code
being correct, that it will perform the logic you intended?



 Help?

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




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


Re: [Tutor] Error message...

2012-08-25 Thread Matthew Ngaha
Hi Victoria. im a total beginner aswell but i noticed something. shouldnt this 
line:

else: return s(0) == s(-1) and isPalindrome (s[1:-1])

be

 else: return s[0] == s[-1] and isPalindrome (s[1:-1])


it looks like you have the string s as a function which you are trying
to call. what you wanted was an index position right? which should be
s[] instead of s().

thanks for the help David. Sorry about the sent mail. Gmail is pretty
confusing for me:( ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error message...

2012-08-25 Thread Victoria Homsy
Thank you everyone for your help with my question - I understand what I was 
doing wrong now. I know I'm posting wrongly so I'm going to go and figure out 
how to do it properly for the future. Have a great day.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error message...

2012-08-24 Thread David
On 24/08/2012, Victoria Homsy victoriaho...@yahoo.com wrote:

 However, this does not work - I get another error message.
 Could somebody advise what I'm doing wrong here? Thank you.

1) You are not carefully reading the entire error message.
2) You are not allowing us to do it either.

Some other things too, probably, but we need to start with those two :)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Error message...

2012-08-23 Thread Victoria Homsy
Dear all, 

Sorry to bother you with a beginner's problem again... 

I have tried to write a program that can check if a string is a palindrome. My 
code is as follows:


def isPalindrome(s):
if len(s) = 1: return True
else: return s(0) == s(-1) and isPalindrome (s[1:-1])
isPalindrome('aba')


However, when I try to run it in terminal I get the following error message: 

Traceback (most recent call last):
  File recursion.py, line 5, in module
    isPalindrome('aba')
  File recursion.py, line 3, in isPalindrome
    else: return s(0) == s(-1) and isPalindrome (s[1:-1])
TypeError: 'str' object is not callable


I don't see why this wouldn't work...

Many thanks in advance. 

Kind regards,

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


Re: [Tutor] Error message...

2012-08-23 Thread Peter Otten
Victoria Homsy wrote:

 Sorry to bother you with a beginner's problem again...

This is the place for beginners.
 
 I have tried to write a program that can check if a string is a
 palindrome. My code is as follows:
 
 
 def isPalindrome(s):
 if len(s) = 1: return True
 else: return s(0) == s(-1) and isPalindrome (s[1:-1])
 isPalindrome('aba')
 
 
 However, when I try to run it in terminal I get the following error
 message:
 
 Traceback (most recent call last):
 File recursion.py, line 5, in module
 isPalindrome('aba')
 File recursion.py, line 3, in isPalindrome
 else: return s(0) == s(-1) and isPalindrome (s[1:-1])
 TypeError: 'str' object is not callable
 
 
 I don't see why this wouldn't work...

If you want to get the nth charactor you have to put the index in brackets, 
not parens:

 s = foo
 s(0) # wrong, python tries to treat s as a function
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: 'str' object is not callable
 s[0] # correct
'f'


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


Re: [Tutor] Error message...

2012-08-23 Thread Rob Day
On 23 August 2012 15:17, Victoria Homsy victoriaho...@yahoo.com wrote:


 def isPalindrome(s):
  if len(s) = 1: return True
 else: return s(0) == s(-1) and isPalindrome (s[1:-1])

 I don't see why this wouldn't work...

 Many thanks in advance.

 Kind regards,

 Victoria


Parentheses are used for function arguments in Python, whereas square
brackets are used for slices - so the first character of s is not s(0) but
s[0].

When you say s(0) and s(-1), Python thinks you're calling s as a function
with 0 or -1 as the argument - hence, str object is not callable.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error message...

2012-08-23 Thread Mark Lawrence

On 23/08/2012 15:17, Victoria Homsy wrote:

Dear all,

Sorry to bother you with a beginner's problem again...


You're welcome as that's what we're here for.



I have tried to write a program that can check if a string is a palindrome. My 
code is as follows:


def isPalindrome(s):
if len(s) = 1: return True
else: return s(0) == s(-1) and isPalindrome (s[1:-1])
isPalindrome('aba')


However, when I try to run it in terminal I get the following error message:

Traceback (most recent call last):
   File recursion.py, line 5, in module
 isPalindrome('aba')
   File recursion.py, line 3, in isPalindrome
 else: return s(0) == s(-1) and isPalindrome (s[1:-1])
TypeError: 'str' object is not callable


I don't see why this wouldn't work...


Always easier for another pair of eyes.  The TypeError tells you exactly 
what the problem is.  Just look very carefully at the return after the 
else and compare your use of the function parameter s.  Then kick 
yourself and have another go :)




Many thanks in advance.

Kind regards,

Victoria



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



--
Cheers.

Mark Lawrence.

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


Re: [Tutor] Error message...

2012-08-23 Thread Victoria Homsy
Excellent - thank you so much everyone. All is clear now!! 



 From: Mark Lawrence breamore...@yahoo.co.uk
To: tutor@python.org 
Sent: Thursday, 23 August 2012, 15:29
Subject: Re: [Tutor] Error message...
 
On 23/08/2012 15:17, Victoria Homsy wrote:
 Dear all,

 Sorry to bother you with a beginner's problem again...

You're welcome as that's what we're here for.


 I have tried to write a program that can check if a string is a palindrome. 
 My code is as follows:


 def isPalindrome(s):
 if len(s) = 1: return True
 else: return s(0) == s(-1) and isPalindrome (s[1:-1])
 isPalindrome('aba')


 However, when I try to run it in terminal I get the following error message:

 Traceback (most recent call last):
    File recursion.py, line 5, in module
      isPalindrome('aba')
    File recursion.py, line 3, in isPalindrome
      else: return s(0) == s(-1) and isPalindrome (s[1:-1])
 TypeError: 'str' object is not callable


 I don't see why this wouldn't work...

Always easier for another pair of eyes.  The TypeError tells you exactly 
what the problem is.  Just look very carefully at the return after the 
else and compare your use of the function parameter s.  Then kick 
yourself and have another go :)


 Many thanks in advance.

 Kind regards,

 Victoria



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


-- 
Cheers.

Mark Lawrence.

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


  1   2   3   >