Gribouillis 1,391 Programming Explorer Team Colleague

The problem is that when a variable appears on the left hand side of the = operator in a function, such as in

def foo():
    started = "fubar"

then the rule is that this variable is a local variable in function foo. It means that if there is another variable in the global namespace, such as

started = False

then these are two different variables, and setting started in foo() has no effect on the global variable started.

There are two main workarounds for this. The first one is a quick and dirty fix: you can add a globaldeclaration at the very beginning of function foo()

def foo():
    global started
    started = "fubar"

This works, but it is not good python programming because with more than one variable, it creates obfuscated code. You'll notice that serious python code almost never uses the global statement.

The second workaround is to use object attributes instead of global variables. The code could be written

class Game(object):
    def __init__(self):
        self.started = False

    def foo(self):
        self.started = "fubar"

if __name__ == '__main__':
    game = Game()
    game.foo()

This is by far the preferred way to handle this issue.

Gribouillis 1,391 Programming Explorer Team Colleague

A google search yields speedtest-cli which does just that. I don't know if it works in windows, but the author(s) put it in

Operating System :: OS Independent

so it may work.

Google and Pypi may have other results.

Gribouillis 1,391 Programming Explorer Team Colleague

Go here and click "download jar file via http". Then open a terminal and go to the directory where the file drjava... has been downloaded. Then type

java -jar drjava*

In the window that opens, write

public class HelloWorld {
    public static void main(String[] args) { 
        System.out.println("Hello, World");
    }
}

Click Compile, save as HelloWorld.java. Click Run.

Gribouillis 1,391 Programming Explorer Team Colleague

You need a loop to handle the case where the answer is not yes or no. For example

def yesno(question):
    while True:
        ans = input(question + ' (Y/n) ')
        ans = ans.strip().lower()
        if ans in ('', 'y', 'yes'):
            return 'yes'
        elif ans in ('n', 'no'):
            return 'no'
        else:
            print('Please answer yes or no ...')

def weather():
    raining = yesno('Is it raining?')
    if raining == 'no':
        print('Go outside 1')
        return
    ask = yesno('Do you have an umbrella?')
    if ask == 'yes':
        print('Go outside 2')
        return
    while raining == 'yes':
        print('Wait until it stops.')
        raining = yesno('Is it still raining?')
    print('Go outside 3!')

weather()

Edit: A tip for python, configure your editor to insert 4 space caracters when you hit the tab key. The recommended indention for python code is 4 spaces.

Gribouillis 1,391 Programming Explorer Team Colleague

I think there shouldn't be a for loop in Read(). Also there is an error in get_smallest()

#include <cassert>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;

struct people
{
    string name;
    int age;
};

people Read(people p)
{
    //for (unsigned int i = 0; i < 5; i++){
        cout << "name: ";
        cin >> p.name;
        cout << "age: ";
        cin >> p.age;
    //}
    return p;
}
vector<people> getData(people person)
{
    vector<people> v;
    for (unsigned int i = 0; i < 5; i++){
        person = Read(person);
        v.push_back(person);
    }
    return v;
}

int getSmallest(vector<people> v)
{
    assert(v.size());
    int smallest = v.at(0).age;
    for (unsigned int i = 0; i < v.size(); i++)
    {

            if (v.at(i).age < smallest)
                smallest = v.at(i).age;


    }
    return smallest;

}
void print(vector<people> v){
    cout << endl;
    for (unsigned int i = 0; i < v.size(); i++){
        cout << "name: " << v.at(i).name << endl;
        cout << "age: " << v.at(i).age << endl;
    }
}

int main(int argc, char* argv[])
{
    people p;
    vector<people> v;
    cout << "enter names & ages" << endl;
    v = getData(p);
    print(v);
    cout << "the smallest one" << endl;
    cout << getSmallest(v) << endl;

    return 0;
}
Gribouillis 1,391 Programming Explorer Team Colleague

This one works

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv) {
    char ar[200] = "Hello World";
    strcat(ar, " !");
    printf("%s\n", ar);

    char* q = ar;
    char **p = &q;
    printf("%s\n", *p);

    return 0;
}

note that I'm only an occasional C programmer.

Gribouillis 1,391 Programming Explorer Team Colleague

The most obvious thing in your code is that "Members.txt" will be opened many times, one for each iteration of the lines in "Rules.txt". This is probably not what you want. You don't need to open each file more than once. To make things easier since you are new to python, you could load the files' content at the beginning with

rule_lines = list(open("Rules.txt"))
member_lines = list(open("Members.txt"))

The next thing is that standard python code is normally indented with 4 space characters and not 8 spaces or tabs. You'd better configure your editor to use 4 space characters.

The missing part in your question is a small exemple of the files content. Without it, it is difficult to understand what you want to compare and your expected result.

Gribouillis 1,391 Programming Explorer Team Colleague

If X is a list instance, one can access its members with X.tail or X.next. On the other hand if X is a pointer to a list instance, one writes X->tail and X->next. It is only the syntax of C++. Notice that in the case of a pointer, there is a risk that X is the null pointer, in which case there will be a segmentation fault at run time.

One can declare pointers to list as fields in the list class because a pointer is only an address in memory. It takes a constant amount of memory which can be computed by the compiler. The size of an actual list instance is much bigger: it is the size of 3 pointers and an integer.

Gribouillis 1,391 Programming Explorer Team Colleague

It's a lot of code. You could perhaps go to the Job Offers section...

Gribouillis 1,391 Programming Explorer Team Colleague

You need to pass arguments for Date(), such as

date = Date(2016, 4, 30)
Gribouillis 1,391 Programming Explorer Team Colleague

Have a look at this quickstart page Click Here explaining how to build numpy arrays.

Gribouillis 1,391 Programming Explorer Team Colleague

Look at the whole error message, it tells you that the error is at line 17, because there are 2 paremeters named yearin your __init__() method.

Gribouillis 1,391 Programming Explorer Team Colleague

For Delta, you need optional parameters. For this you can define

def __init__(self, year=1970, month=1, day=1)

for example.

Gribouillis 1,391 Programming Explorer Team Colleague

It is much better for class Date, but you must create an instance with parameters, for example

date = Date(2016, 4, 29)

There should be a __init__()method for class Delta too, with convenient parameters.

Gribouillis 1,391 Programming Explorer Team Colleague

Nevertheless, 2N+1 calls exactly is a more precise result than O(N). There is no best case or worst case in this function in terms of number of calls. There is a best and worst case in terms of the length of the stack, but it is another question.

Gribouillis 1,391 Programming Explorer Team Colleague

For a tree with N nodes, the function will be called exactly 2N+1 times in my opinion (N times with a real node and N+1 times with a null node). You can prove this by induction on N by adding a leaf to a tree or by using the induction hypothesis on each of the two subtrees.

Gribouillis 1,391 Programming Explorer Team Colleague

You could write

cipher = [(key[(key.index(char) + offset) % 26] if char in key else char) for char in text]
Gribouillis 1,391 Programming Explorer Team Colleague

I don't think you need x2 and y2 in the call to delete(), canvas.delete(captured) should work. Also shouldn't the last call be written

canvas.coords(closest, (x_center, y_center))

?

What do you mean by a better way to delete the captured piece ?

Gribouillis 1,391 Programming Explorer Team Colleague

If you want to access the correct variable, you need to return its value in movecreate(). For examble, this function could return two values

return correct, movelist

The function that uses this could use

correct, movelist = movecreate(tour, b, d)
if movelist and (correct == 0): ...

edit: also it would be a great improvement if you could remove most of the global statements.

Gribouillis 1,391 Programming Explorer Team Colleague

Your code is very difficult to understand because it is not modular enough. You say you need to add something after if len(movecreate(tour,b,d))>0. Start by writing pseudo code to describe what you need to add. Describe it in plain english or french to start with.

Gribouillis 1,391 Programming Explorer Team Colleague

You must write

from game_engine import movecreate

but first you must move the definition of movecreate() outside the body of the engine() function. You don't need nested function definitions in your code, so don't use them as they hide the functions from the global namespace.

Gribouillis 1,391 Programming Explorer Team Colleague

Try k = i + 8 * j. The reverse conversion is j, i = divmod(k, 8).

Gribouillis 1,391 Programming Explorer Team Colleague

I suggest

def Density(rho0, r, Rc, Rd):
    return rho0 * np.exp(-np.maximum(r-Rc, 0)/Rd)
Gribouillis 1,391 Programming Explorer Team Colleague

@Karthik_4 in linux, the command to make the file myscript executable is

chmod +x myscript
Gribouillis 1,391 Programming Explorer Team Colleague

Very nice, here is how it looks here.

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

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

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

Hello, effbot.org says to keep a reference to the image object to prevent it from being garbage collected. You could try

self.our_image = tk.PhotoImage(master=self, file="side.png")

http://effbot.org/tkinterbook/label.htm

sureshk75 commented: That did the trick! Thank you +0
Gribouillis 1,391 Programming Explorer Team Colleague

There is a problem in the indention of function add_number() at the beginning of your code.

Apart from that, don't only post ValueError, instead, post the whole error message sent by python in your console. This error message contains most of the time the precise position in your code where the error occurs.

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