Gribouillis 1,391 Programming Explorer Team Colleague

Very nice, here is how it looks here.

Gribouillis 1,391 Programming Explorer Team Colleague

In principle, you can double-click on the code and then use ^C to copy the code without the line numbers.

Gribouillis 1,391 Programming Explorer Team Colleague

I only have the 'default' style. I get something better with a single frame

from tkinter import Tk
from tkinter.ttk import Frame, Label, Button, Style
from random import randrange
from functools import partial

class Game:

    def __init__(self):
        self.window = Tk()
        self.window.title("Onager Ornery Clicker")
        self.createwidgets()

    def create_styles(self):
        frame_style = Style()
        frame_style.theme_use('default')
        frame_style.configure("TFrame",
                              background='blue',
                              foreground='gold',
                              borderwidth='10',
                              relief='raised')

        title_style = Style()
        title_style.configure("TLabel", font='serif 30')

        instr_style = Style()
        instr_style.configure("TLabel", font='serif 12')



    def create_frames(self):
        self.frame = Frame(self.window)
        self.frame.rowconfigure(4+5)
        self.frame.columnconfigure(5)
        self.frame.grid(row=0, column=0)
        self.frame2 = self.frame

    def create_title(self):
        self.title = Label(self.frame,
                           style="title_style.TLabel",
                           text='Onager Ornery Clicker')
        self.title.grid(row=0, column=0, columnspan=5)

    def create_instr(self):
        self.instr = """        Correct click scores a point.
        Wrong click costs a point.
        You have 60 seconds.
        Click Start to begin.
        HAVE FUN!"""
        self.instr = Label(self.frame,
                           style="instr_style.TLabel",
                           text=self.instr)
        self.instr.grid(row=1, column=0, rowspan=3, columnspan=4)

    def create_start_button(self):
        self.start = Button(self.frame, text='Start')
        self.start.grid(row=1, column=4)

    def create_timer(self):
        self.timer = Label(self.frame, text='Time')
        self.timer.grid(row=2, column=4)

    def create_score(self):
        self.score = Label(self.frame, text='Score')
        self.score.grid(row=3, column=4)

    def shuffle(self):
        for i, button in enumerate(self.buttons, 1):
            button['text'] = "Don't Click Me!"
        index = randrange(len(self.buttons))
        self.buttons[index]['text'] = "Click Me!"

    def create_buttons(self):
        self.buttons = []
        for item in range(25):
            button = Button(self.frame2, width=len("Don't Click me!"))
            button['command'] = partial(self.button_clicked, button)
            row_num, col_num = divmod(item, 5)
            button.grid(row=(row_num+4), column=col_num)
            self.buttons.append(button)
        self.shuffle()

    def button_clicked(self, button):
        if button['text'] == "Click Me!":
            self.shuffle()

    def createwidgets(self):
        self.create_styles()
        self.create_frames()
        self.create_title()
        self.create_instr()
        self.create_start_button()
        self.create_timer()
        self.create_score()
        self.create_buttons()

clicker = Game()
clicker.window.mainloop()
Gribouillis 1,391 Programming Explorer Team Colleague

I can't run the script in kubuntu 14.04. I get

Traceback (most recent call last):                                                                                                                                                                                       
  File "foo.py", line 99, in <module>                                                                                                                                                                                    
    clicker = Game()                                                                                                                                                                                                     
  File "foo.py", line 11, in __init__                                                                                                                                                                                    
    self.createwidgets()                                                                                                                                                                                                 
  File "foo.py", line 90, in createwidgets                                                                                                                                                                               
    self.create_styles()
  File "foo.py", line 15, in create_styles
    frame_style.theme_use('normal')
  File "/usr/lib/python3.4/tkinter/ttk.py", line 523, in theme_use
    self.tk.call("ttk::setTheme", themename)
_tkinter.TclError: can't find package ttk::theme::normal
Gribouillis 1,391 Programming Explorer Team Colleague

It seems very good to me.

Gribouillis 1,391 Programming Explorer Team Colleague

Hello, I think you can start a long list of missing features. The first in sight are

  1. A shortcut to exit the editor
  2. Why is there no menubar ? Is it by design ?
  3. The text area does not update as it should when the window is resized with the mouse
  4. A font selection tool is missing (especially the font size selection)
  5. Syntax highlighting for languages such as python ?

To be fully honest, I think there are so many good editors that it is an potentially huge effort to write your own with very little chance to do something better than existing tools.

My favorite editor is Kate . It is very powerful and easy to use. Have you tried it ?

Gribouillis 1,391 Programming Explorer Team Colleague

Yes but when u is close enough to 0, exp(u) is close to 1 + u.

Gribouillis 1,391 Programming Explorer Team Colleague

I don't understand your question. If you write return H0*np.exp(r/Rh), the code works and draws a curve, which is almost a straight line (I suppose it is because 1/Rh is small).

Gribouillis 1,391 Programming Explorer Team Colleague

Try to remove all the calls to float(). They are not necessary, and numpy uses its own float type.

Gribouillis 1,391 Programming Explorer Team Colleague

No, this article only means that symbolic constants don't exist in the core of the python language, but programmers can use class instances or other ersatz as symbolic constants. The enum.Enum type of python 3 is one way to implement this, but there are many other implementations.

This has nothing to do with refactoring, which means essentially take existing code and rewrite some parts to make the code better and more robust.

Gribouillis 1,391 Programming Explorer Team Colleague

If you don't want to use classes, you can use symbolic constants, that's what C programmers do

SqContent_white = 3452
SqContent_black = 3453
SqContent_empty = 3454

Click_first = 654333
Click_second = 654334

Turn_white = 87644
Turn_black = 87645

def on_click(event):
    global turn, clic
    i, j, content, closest = decode_click(event)
    if turn == Turn_white:
        if content == SqContent_white:
            if clic == Click_first:
                ...
            else:
                ...
        elif content == SqContent_black:
            if clic == Click_first:
                ...
            else:
                ...
        elif content == SqContent_empty:
            if clic == Click_first:
                ...
            else:
                ...            
    else:
        assert(turn == Turn_black)
        if content == SqContent_white:
            if clic == Click_first:
                ...
            else:
                ...
        elif content == SqContent_black:
            if clic == Click_first:
                ...
            else:
                ...
        elif content == SqContent_empty:
            if clic == Click_first:
                ...
            else:
                ...            

def decode_click(event):
    x1 = event.x
    y1 = event.y
    i,j = (int(x1/dim_square), int(y1/dim_square))
    if board_representation[i][j]:
        content = SqContent_black if board_representation[i][j].islower() else SqContent_white

    else:
        content = SqContent_empty
    closest = canvas.find_closest(x1,y1)
    return i, j, content, closest

However, you'll have to learn classes very soon, because it is the tool you need to go further.

Gribouillis 1,391 Programming Explorer Team Colleague

@hericles The comma trick works only in python 2. With python 3, print is a full fledged function and the way to prevent the newline is to use the parameter end='' in the call to print() .

Gribouillis 1,391 Programming Explorer Team Colleague

You could perhaps make things easier by using enumeration types to represent the values of state variables, something like

from enum import Enum

class SqContent(Enum):
    white = 0
    black = 1
    empty = 2

class Click(Enum):
    first = 0
    second = 1

class Turn(Enum):
    white = 0
    black = 1

def on_click(event):
    global turn, clic
    i, j, content, closest = decode_click(event)
    if turn == Turn.white:
        if content == SqContent.white:
            if clic == Click.first:
                ...
            else:
                ...
        elif content == SqContent.black:
            if clic == Click.first:
                ...
            else:
                ...
        elif content == SqContent.empty:
            if clic == Click.first:
                ...
            else:
                ...            
    else:
        assert(turn == Turn.black)
        if content == SqContent.white:
            if clic == Click.first:
                ...
            else:
                ...
        elif content == SqContent.black:
            if clic == Click.first:
                ...
            else:
                ...
        elif content == SqContent.empty:
            if clic == Click.first:
                ...
            else:
                ...            

def decode_click(event):
    x1=event.x
    y1=event.y
    i,j=(int(x1/dim_square),int(y1/dim_square))
    if board_representation[i][j]:
        content = SqContent.black if board_representation[i][j].islower else SqContent.white

    else:
        content = SqContent.empty
    closest = canvas.find_closest(x1,y1)
    return i, j, content, closest
Gribouillis 1,391 Programming Explorer Team Colleague

The easiest way to maintain state variables is to work wih classes. You could have a class

class Game:
    def __init__(self):
        self.state = self.black_select
        ....

game = Game()
game.run()
Gribouillis 1,391 Programming Explorer Team Colleague

I don't understand the clic = 0 part. You can use

if len(t) == 4:
    ...
elif len(t) == 2:
    ...
else:
    ...
Gribouillis 1,391 Programming Explorer Team Colleague

You have 4 coordinates, it is probably the bounding rectangle of the object you clicked with the mouse.

Gribouillis 1,391 Programming Explorer Team Colleague

What does it mean ? It cannot fail ! try

print(repr(t))

if there is an error message, post it here

Gribouillis 1,391 Programming Explorer Team Colleague

This happens because t is not an iterable with 2 values. Print t or repr(t) to see what's going on.

Gribouillis 1,391 Programming Explorer Team Colleague

You can define a function to return the coordinates to move to

def destination(x, y):
    i, j = int(x/ux), int(y/uy)
    return i * vx + wx, j * vy + wy

All you have to do is to figure out the correct values for the constants ux, uy, vx, vy, wx, wy.

For example ux, uy, vx, vy may be dim_square and wx, wy may be -0.5 * dim_square. Also think about what happens if the user resizes the chessboard to a rectangle with the mouse. The constants may depend on the actual dimensions of the canvas.

Gribouillis 1,391 Programming Explorer Team Colleague

I had a better result by adding a call to refresh() at the end of display_game(). Also adding a print(board_representation) at the end of interpretor() shows an error

rnbqkbnrpppppppp0000000000000000000000000000000000000000PPPPPPPPRNBQKBNR at line 70 in Chessboard.py
[['r', 'p', ' ', ' ', ' ', ' ', ' ', 'P'], ['n', 'p', ' ', ' ', ' ', ' ', ' ', 'P'], ['b', 'p', ' ', ' ', ' ', ' ', ' ', 'P'], ['q', 'p', ' ', ' ', ' ', ' ', ' ', 'P'], ['k', 'p', ' ', ' ', ' ', ' ', ' ', 'P'], ['b', 'p', ' ', ' ', ' ', ' ', ' ', 'P'], ['n', 'p', ' ', ' ', ' ', ' ', ' ', 'P'], ['r', 'p', ' ', ' ', ' ', ' ', ' ', 'R']] at line 84 in Chessboard.py

Using the printat module mentioned above is very useful here. Write

from tkinter import *
from printat import printat
print = printat

at the top of Chessboard.py, and save module printat on the python path.

Gribouillis 1,391 Programming Explorer Team Colleague

I cannot run your code because I don't have the images of the pieces and the lvl file. Can you zip the folder pieces_image and attach the zip to a post ?

Gribouillis 1,391 Programming Explorer Team Colleague

If you read the above mentioned documentation for method coords(), you see that it can be used to move the object, instead of deleting and recreating the image. You should be able to do something like

def move_image(event):
    global x1,y1,x2,y2,img, init_image
    init_image=[]
    if clic==0: #First Clic
        t = canvas.coords("blackk")
        if not t:
            return
        x1, y1 = t
        closest=canvas.find_closest(x1,x1,halo=32)
        x1=int(x1)
        y1=int(y1)
        init_image.append(x1)
        init_image.append(y1)
        print(init_image)
    elif clic==1: #Second Clic
        x2=event.x
        y2=event.y
        canvas.coords("blackk", x2, y2)

Also, good python code never uses the global statement. A good thing to do is to remove all the global statements in your program.

Gribouillis 1,391 Programming Explorer Team Colleague

You can simply do nothing if the value is None

t = canvas.coords("blackk")
if not t:
    return
assert(len(t) == 2)
x1, y1 = t
...
Gribouillis 1,391 Programming Explorer Team Colleague

The canvas .coords() method is described here http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/canvas-methods.html . As you can see, it may return a variable number of coordinates. In your code, the canvas object with tag "blackk" is an image. Try

t = canvas.coords("blackk")
print(t)

to see what was returned.

Gribouillis 1,391 Programming Explorer Team Colleague

A block of python code, showing serious attempts to solve the problem is missing in your question. Helpers here are not attending a programming course, and usually don't do student's homework for them.

Gribouillis 1,391 Programming Explorer Team Colleague

What you can do is add print statements in the code in order to see what's getting executed. For example you can add print(line) at line 66 because the interpretor() function is supposed to be called with a line containing the game to be diplayed.

You can use my printat() function https://www.daniweb.com/programming/software-development/code/479747/print-with-line-and-file-information to help with this debugging part.

Gribouillis 1,391 Programming Explorer Team Colleague

Here https://docs.python.org/3/reference/expressions.html?highlight=precedence#value-comparisons are the comparison operators in python. You must write

if stu_points < 60:
    print("F")
grand_78 commented: I keep getting the "F" to go on a separate line, do you know how I could get the F to display on the same line as "45"? Thank you +0
Gribouillis 1,391 Programming Explorer Team Colleague

Ok, here it is.

Gribouillis 1,391 Programming Explorer Team Colleague

Your code needs an if statement to determine if stu_points is below 60 and print an F in that case.

Gribouillis 1,391 Programming Explorer Team Colleague

What you can do is add a dictionary

        self.as_meter = dict(
            mm=0.001, cm=0.01, inches=0.0254,
            feet=0.3048, yards=0.9144, meter=1.0,
            km=1000.0, miles=1609.344,
        )

Then you add lines to bind various variables

        self.measurements.trace('w', self.update_length)
        self.measurements1.trace('w', self.update_length)
        self.Text_Length_Left.trace('w', self.update_length)

You need to add a callback method

    def update_length(self, *args):
        try:
            v = float(self.Text_Length_Left.get())
        except ValueError:
            v = 0.0
            self.Text_Length_Left.set(str(v))
        m = v * self.as_meter [self.measurements.get()]
        r = m/self.as_meter[self.measurements1.get()]
        self.Text_Length_Right.set("{:.3e}".format(r))

You can also set a parameter state='readonly' for Entry_Length_Right and you must set the initial values for Combobox_Length_... before you call grid()

        self.Combobox_Length_Left.current(5)
        self.Combobox_Length_Right.current(5)
Gribouillis 1,391 Programming Explorer Team Colleague

Can you post the whole code ?

Gribouillis 1,391 Programming Explorer Team Colleague

What about Renaud Le Van Kim ?

More seriously, I can't run your code because my python has pandas 0.13.1 in ubuntu 14.04, and this version does not understand the parameter expand= in split().

Gribouillis 1,391 Programming Explorer Team Colleague

According to the python documentation

The combobox widget generates a <<ComboboxSelected>> virtual event when the user selects an element from the list of values.

It means that you could bind this event to one of your methods

mywidget.bind('<<ComboboxSelected>>', self.mymethod)

Then define a method

def mymethod(self, *args):
    print(args)

and see if something happens.

Gribouillis 1,391 Programming Explorer Team Colleague

This works for me

from tkinter import *
from time import time, sleep, clock
class Splash:

    def __init__(self, root, file, wait):
        self.__root = root
        self.__file = file
        self.__wait = wait + clock()


    def __enter__(self):
        # Hide the root while it is built.
        self.__root.withdraw()
        # Create components of splash screen.
        window = Toplevel(self.__root)
        splash = PhotoImage(master=window, file=self.__file)
        canvas = Label(window, textvariable=d_status, fg='white', bg='black', image=splash, compound=TOP)
        # Get the screen's width and height.
        scrW = window.winfo_screenwidth()
        scrH = window.winfo_screenheight()
        # Get the images's width and height.
        imgW = splash.width()
        imgH = splash.height()
        # Compute positioning for splash screen.
        Xpos = (scrW - imgW) // 3
        Ypos = (scrH - imgH) // 2
        # Configure the window showing the logo.
        window.overrideredirect(True)
        window.geometry('+{}+{}'.format(Xpos, Ypos))
        canvas.grid()
        # Show the splash screen on the monitor.
        window.update()
        # Save the variables for later cleanup.
        self.__window = window
        self.__canvas = canvas
        self.__splash = splash
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # Ensure that required time has passed.
        now = clock()
        if now < self.__wait:
            sleep(self.__wait - now)
        # Free used resources in reverse order.
        del self.__splash
        self.__canvas.destroy()
        self.__window.destroy()
        # Give control back to the root program.
        self.__root.update_idletasks()
        self.__root.deiconify()

    def foo(self, x):
        d_status.set(str(x))
        self.__root.update_idletasks()

def initializeMyApplication(notify_status):
    for x in range(5):
        notify_status(x)
        sleep(1)
        print(d_status.get())

def buildTheGUI(object):
    for x in range(100, 110):
        sleep(1)
        print(x)

root = Tk()
d_status = StringVar()
d_status.set("Initializing...")
with Splash(root, 'pix.gif', 3.0) as s:
   initializeMyApplication(s.foo)
   s.foo("Done!")
   buildTheGUI(root)
root.mainloop()
Gribouillis 1,391 Programming Explorer Team Colleague

Invalid syntax is always a very simple error. The only strange thing in your code is the colon at the end of the line. This can happen only when the line starts with a keyword such as if, elif, else, for, while, def, class, try, except, finally, with, lambda.

What is the beginning of the line ?

Gribouillis 1,391 Programming Explorer Team Colleague

You could use nan

from math import sqrt
nan = float('nan')
def mysqrt(x):
    return sqrt(x) if x >= 0.0 else nan

See https://en.wikipedia.org/wiki/NaN

Edit: Hi Tony! It's been a while...
Edit2: numpy.sqrt() already returns nan for negative numbers!
Edit3: please @steven.rose.94, use python tag as well as python3 to increase the audience of your posts.

Gribouillis 1,391 Programming Explorer Team Colleague

Try id = j['id'], and read a python tutorial!

Gribouillis 1,391 Programming Explorer Team Colleague

This code runs without error. I'm not sure it's computing what you want

import numpy as np
T = 5
N = 50

a= 2.     # will turn the spiral
v= 0.23
omega = 0.2
r0 = v/omega
t=np.linspace(0,T,N+1)
r= v*t
#theta = a + r/r0
theta  =  omega*t

x=r* np.cos( omega*t) 
y=r* np.sin( omega*t) 

dxdr = np.cos(theta) - (r/r0)*np.sin(theta)
dydr = np.sin(theta) + (r/r0)*np.cos(theta)

dydx = (r0*np.sin(theta) + r*np.cos(theta))/r0*np.cos(theta) - r*np.sin(theta)

#np.tan[incl]= dydx
incl = np.arctan(dydx) 


### Calculate cos(incl) ,sin(incl) :
sinincl = np.tan(incl)/np.sqrt(1+ np.tan(incl)*2)
cosincl = 1/np.sqrt(1+ np.tan(incl)*2)

Don't use square brackets when normal brackets are required. Also there is no object np.incl. Finally a function call can never appear on the left hand side of an = operator (One cannot have f(x) = 3 for example). This is not true for operators
such as += , *= , == etc.

Gribouillis 1,391 Programming Explorer Team Colleague

Okay, what will that do?

  1. You won't have the error message any more
  2. Your tar file would contain a single directory named gallery
Gribouillis 1,391 Programming Explorer Team Colleague

You may also use this trick

>>> lett = "tfc bhy qwz".split()
>>> dic = {x: i for i, w in enumerate(lett, 1) for x in w}
>>> dic
{'c': 1, 'b': 2, 'f': 1, 'h': 2, 'q': 3, 't': 1, 'w': 3, 'y': 2, 'z': 3}
Gribouillis 1,391 Programming Explorer Team Colleague

I think you are creating a tar bomb, a tar archive that explodes into many files instead of creating a single directory. Can't you try

tar --exclude-tag-all=backups -C ../.. -cf lesson21.tar gallery
Gribouillis 1,391 Programming Explorer Team Colleague

I think you can try and write it yourself. Obviously you know how to ask the user a question and how to handle an answer, don't you ?

rhys1619 commented: just asking would i start after the instructions +0
Gribouillis 1,391 Programming Explorer Team Colleague

You need to enclose everything in a loop

# rhys translation quiz

question_list = [
(   "What is Kia ora in english",
    "a. Hello\nb. Bye\nc. Greetings\nd. See ya\n",
    "a"),
(   "What is t?n? rawa atu koe in english",
    "a. Give it\nb. bye\nc. Thank you\nd. See ya\n",
    "c"),
(   "What is rorohiko in english",
    "a. TV\nb. Microwave\nc. Oven\nd. Computer\n",
    "d"),
(   "What is motuk? in english",
    "a. Van\nb. Car\nc. Truck\nd. bus\n",
    "c"),
(   "What is whare kotahi in english",
    "a. Deck\nb. Game\nc. Suit\nd. Card\n",
    "d"),
(   "What is haupa in english",
    "a. Food\nb. Drink\nc. Soup\nd. Water\n",
    "a"),
(   "What is Ng? Aho Whakaari in english",
    "a. Show\nb. Film\nc. Song\nd. Book\n",
    "b"),
(   "What is makawe in english",
    "a. Face\nb. Hair\nc. Neck\nd. Beard\n",
    "b"),
(   "What is tau in english",
    "a. Letter\nb. Number\nc. Space\nd. Shape\n",
    "b"),
(   "What is wini in english",
    "a. Win\nb. Lose\nc. Try again\nd. Quit\n",
    "a"),
]

play_again = True
while play_again:
    #intro and intrustions
    score = 0
    print ("""Welcome to the translation quiz
You will be ask a series of questions and have 2 tries per questions
If you get the correct answer you will get one point, half a point for getting it
your second try and zero points if you get it wrong twice.
GOOD LUCK!!!
""")

    for question, options, correct in question_list:
        print(question)
        print(options)
        #user will have to enter a,b,c or d for there answer
        response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n")
        #simple, if answer is correct print correct and move …
Gribouillis 1,391 Programming Explorer Team Colleague

Hello. It is the same as

def mine(a, b):
    return a >= (b - 1)

see https://docs.python.org/3/reference/expressions.html#operator-precedence

Gribouillis 1,391 Programming Explorer Team Colleague

Kubuntu is Ubuntu with the KDE desktop. It is a classical and robust desktop. Always choose LTS versions (see https://en.wikipedia.org/wiki/List_of_Ubuntu_releases). version 14.04 is supported until 2019. Also upgrade is easy between LTS versions.

Gribouillis 1,391 Programming Explorer Team Colleague

My choice is Kubuntu 14.04 long term support. Download it from here http://kubuntu.org/getkubuntu/

Gribouillis 1,391 Programming Explorer Team Colleague

Install module pyasn1 https://pypi.python.org/pypi/pyasn1 . You can probably install it by typing

pip install pyasn1

in a terminal.

Gribouillis 1,391 Programming Explorer Team Colleague

You can probably redirect to the 2.7 version by calling python2.7 yourscript.py or by changing the shebang line in your script to

#!/usr/bin/python2.7
Gribouillis 1,391 Programming Explorer Team Colleague

In your script, add

import sys
raise RuntimeError(sys.path)

This will show the directories used to find importable modules. If your directory is not here, you can try

from distutils.sysconfig import get_python_lib
raise RuntimeError(get_python_lib())

If this prints the site_packages directory where requests lives, you could try

import sys
from distutils.sysconfig import get_python_lib
sys.path.append(get_python_lib())

In ubuntu for example, the python library is not site-packages but dist-packages. You could try

import os
sp = os.path.join(os.path.dirname(get_python_lib()), 'site-packages')
sys.path.append(sp)
Gribouillis 1,391 Programming Explorer Team Colleague

Some code is missing, I get

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
 NameError: name 'pnt' is not defined

please post the code that generates your error message, plus full traceback.