I'm a student learning to program, and my current assignment is to write a graphing calculator using the Simple Graphics library. I got everything working, except for coloring the lines. The first line should be red, the second should be green and the third one blue, then they repeat. Here is the code I added for the colors:
if count % 3 == 1:
print("red")
setColor = ("red")
elif count % 3 == 2:
print("green")
setColor = ("green")
else:
print("blue")
setColor = ("blue")
Earlier in the code, I set count = 1 and at the end of my drawing loop, I have count = count + 1.
Whenever I try to use the program, all the lines appear black. When I look at the terminal, I see "red", "green" and "blue" all being printed successfully at the right times. Using RGB values to define the color doesn't help either.
Does anyone have any idea of what I could be doing wrong? I can post the entire code for drawing the lines, but I thought people wouldn't want to sift through 30 lines.
setColor = ("color") should just be setColor("color"). setColor is a function, that takes in input and performs an action. If it was a variable, which is just a name for some data that you will provide, your code would be correct. (Variables almost never have verbs in their names.)
Related
I am working with a Pandas dataFrame of an experiment that describes hand and head coordinates in VR (just_trials). In each trial, a virtual environment appears, then a black screen, and then again a virtual environment.
I have a column that describes the trial number ("staircaseCounterIndex", and another column that describes what the subject sees: a room or a black screen ("SceneName").
For example:
Because the data set shows me millisecond coordinates of motion, the values in SceneName, and in staircaseCounterIndex do not change as long as the scene has not changed or the trial is over, respectively.
I want to add a new column to the data set that will count me the times the subject has seen the room (i.e. after a room has appeared when previously there was a black screen will add +1 to the count).
Below is the code:
step_index = []
first_step = -2
step_num = 0
for i in range(2, np.shape(just_trials)[0]):
print(i)
if (first_step == just_trials['staircaseCounterIndex'][i]) and (just_trials['SceneName'][i] == 'Room'): # and just_trials['SceneName'][i-1] == 'Room': ## **Here is the error** ##
step_index.append(step_num)
elif just_trials['SceneName'][i] == 'BlackScreen':
step_index.append(0)
else:
step_num += 1
first_step = just_trials['staircaseCounterIndex'][i]
step_index.append(step_num)
My problem is that when I try to run the code pycharm encounters an error in the third iteration of the For loop:
the line where the error occurs is marked in the code above.
But when I run the debugger, everything works just fine.
Would be thankful for your help,
Paz.
Try with .iloc for indexing.
just_trials['staircaseCounterIndex'].iloc[i]
I'm creating a mini program & I'm trying to check whether the user inputs what I want them to -- They're only supposed to type one of the following: happy, sad, angry,nervous,excited but for some reason its ignoring that entire if statement and even the table (rectangle) I drew doesn't appear as well?
from graphics import *
win = GraphWin("Moods", 800, 500)
#Creating the input Box + A Go Button.
inputBox=Entry(Point(400,250),12)
inputBox.draw(win)
colour=inputBox.getText().lower()
message=Text(Point(400,50),"Click to go next!")
message.setFace('courier')
message.setSize(20)
message.draw(Win)
submsg1=Text(Point(400,100),"")
submsg1.setText("(Allowed moods are: Happy, Sad, Angry, Nervous,
Excited)")
submsg1.setFace('courier')
submsg1.setSize(15)
submsg1.setStyle('italic')
submsg1.draw(win)
clickPoint = win.getMouse()
#Checking user inputs the right way.
if not colour.isalpha():
error=Text(Point(400,300),"Please type either: happy, sad, angry")
error.draw(win)
elif (colour !="happy" or colour !="sad" or colour !="angry"):
error=Text(Point(400,300),"Please type either: happy, sad, angry")
error.draw(win)
else:
#Clearing Second Frame, for next screen.
inputBox.undraw()
goButton.undraw()
error.undraw()
message.undraw()
submsg1.undraw()
#Moving to next frame.
table=Rectangle(Point(50,400),Point(750,400))
table.setFill("blue")
table.draw(win)
Basically what is happening with your code is that this line here;
elif (colour !="happy" or colour !="sad" or colour !="angry"):
this will execute if one of the conditions is true because of how the or works. because one of them will always be true (because the user cannot enter happy and sad at the same time).
so for your example you will want the and function as then all of the conditions will have to be true for it to run.
elif (colour !="happy" and colour !="sad" and colour !="angry"):
now to finish off you need to move this line colour=inputBox.getText().lower() to below this line clickPoint = win.getMouse() but before the if because getText is an event which executes when you call it, so at the moment when you call it at beginning it gets nothing because the user hasnt entered anything yet.
so it should look like this;
clickPoint = win.getMouse()
colour=inputBox.getText().lower()
#Checking user inputs the right way.
if not colour.isalpha():
Instead of
elif (colour !="happy" or colour !="sad" or colour !="angry"):
use
elif (colour !="happy" and colour !="sad" and colour !="angry"):
(and instead of or) as your original condition is always satisfied.
I am fairly new to the python language and psychopy. I am practicing it by creating dummy experiments. Here, I am trying to create an experiment about bayesian brain. Non-vertical lines will be presented to the participant while no respond is expected from the participants, just exposure. Then for the last trial (it stays on the monitor for longer period of time to be responded), it is expected from the participant to judge whether the last line trial is vertical or not? (after exposing to non-vertical lines, I am expecting to see a change in perception of verticality).
However, there are so many things that I couldn't learn from the web. I am pretty sure you guys can help me easily.
My primary problem is; how to set up the orientation of the line? I found out the stim.ori but not sure how to use it on 'line' stimuli. Below I've attached the codes that I made so far. Also, I have added some extra questions with #.
I tried to be clear as much as I can. Sorry for my bad english.
Thank you!
from psychopy import visual, core, event #import some libraries from PsychoPy
import random
#create a window
mywin = visual.Window([800,600],monitor="testMonitor", units="deg")
#stimuli
lineo = visual.Line(mywin, start=(-5, -1), end=(-5, 1))
fixation = visual.GratingStim(mywin, size=0.2, pos=[0,0], color = 'black')
#draw the stimuli and update the window
n = 5 # trial number
i = 0
while i < n:
#fixation
fixation.draw()
mywin.flip()
presses = event.waitKeys(1)
# stimulus
orientationlist = [20,30,40,50,60] # I want to draw the orientation info from this list
x = random.choice(orientationlist)
lineo.ori((x)) #
lineo.draw()
mywin.flip()
presses= event.waitKeys(2)
i +=1
if i == 5: # how do I change the number into the length of the trial; len(int(n) didnt work.
lineo.draw()
mywin.flip()
presses = event.waitKeys(4)
#quiting
# I dont know how to command psychopy for quiting the
# experiment when 'escape' is pressed.
#cleanup
mywin.close()
core.quit()
There's a few things that you would want to do differently. I've updated your code and marked changes with the comment "CHANGE". Changing the orientation of a stimulus is pretty consistent in psychopy, so it's no different for Line than any other visual stimulus type.
from psychopy import visual, core, event #import some libraries from PsychoPy
import random
#create a window
mywin = visual.Window([800,600],monitor="testMonitor", units="deg")
#stimuli
lineo = visual.Line(mywin, start=(-5, -1), end=(-5, 1))
fixation = visual.GratingStim(mywin, size=0.2, pos=[0,0], color = 'black')
orientationlist = [20,30,40,50,60] # CHANGED. No need to redefine on every iteration of the while-loop.
#draw the stimuli and update the window
n = 5 # trial number
for i in range(n): # CHANGED. This is much neater in your case than a while loop. No need to "manually" increment i.
#fixation
fixation.draw()
mywin.flip()
event.waitKeys(1) # CHANGED. No need to assign output to anything if it isn't used.
# stimulus
lineo.ori = random.choice(orientationlist) # CHANGED. Alternative: lineo.setOri(random.choice(orientationlist)).
lineo.draw()
mywin.flip()
event.waitKeys(2)
# At this point, all the stimuli have been shown. So no need to do an if-statement within the loop. The following code will run at the appropriate time
lineo.draw()
mywin.flip()
event.waitKeys(keyList=['escape']) # CHANGED. Listen for escape, do not assign to variable
# CHANGED. No need to call core.quit() or myWin.close() here since python automatically cleans everything up on script end.
I have a stimulus loop in psychopy that displays images for 4 seconds that subjects make binary decisions about. I would like to give them feedback as to which choice they have made.
I.e.: a image gets displayed for 4 seconds with white 'YES' and 'NO' displayed on either side of it. When the user presses a key, the corresponding word turns red. If they then press a different key, it switches. After 4 seconds, the next image appear with white words.
Does anyone know how to go about doing this? Many thanks for any suggestions.
You can do this with a custom code component. Add the code component to your routine.
Under the "Each Frame" tab add the following code:
if (t >=4) and (t < 8):
if clear_keys:
event.getKeys()
clear_keys = False
else:
theseKeys = event.getKeys(keyList=['y', 'n'])
if 'y' in theseKeys:
Yes.color = 'red'
No.color = 'white'
elif 'n' in theseKeys:
Yes.color = 'white'
No.color = 'red'
Under the "Begin Experiment" tab add the following code:
clear_keys = True
You will need to change the Yes and No objects in the script to the names of your text components. You will also need to change the number 4 to the start time of the picture and number 8 to the end time.
Here is a picture of my trial as an example.
There seems to be something strange going on in this loop. I tried to debug it, and I have no explanation for what is going on.
This code is from another Stack Overflow post, and I made some edits to it.
modelImages = ['/home/lie/Desktop/dylan.jpg','/home/lie/Desktop/melissa.jpg']
for modelImage in modelImages:
**print modelImage**
template=cv2.imread(modelImage)
templateg = cv2.cvtColor(template,cv2.COLOR_BGR2GRAY)
keys = surf.detect(templateg)
keys,desc = surfDescriptorExtractor.compute(templateg, keys)
count = 0
for h,des in enumerate(desc):
des = np.array(des,np.float32).reshape((1,64))
retval, results, neigh_resp, dists = knn.find_nearest(des,1)
res,dist = int(results[0][0]),dists[0][0]
if dist<0.1: # draw matched keypoints in red color
count=count + 1
print "space"**
The important parts have asterisks. This is a portion of the code that was suppose to identify similarities among images of faces. What the code does is not important. The strange part is that this loop is executing 1 time for an array of size two.
The output is:
/home/lie/Desktop/dylan.jpg
/home/lie/Desktop/melissa.jpg
space
Notice that both strings in modelImages are printed before space. By the way this is part of a function that is called from a loop. This seems to be more of a python issue than an opencv issue. It almost seems like there is a hidden continue statment
Thanks