internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: psychopy/psychopy

Issue:
Builder 'Aperture' component cannot have indefinite duration
If a Builder 'Aperture' component is set to have an indefinite duration, the actual result is that it is enabled and then immediately disabled. Hence, it has no effect on other stimuli. Below is example code that gets generated when an indefinite duration is specified:

```
# *aperture* updates
if t >= 0.0 and aperture.status == NOT_STARTED:
    # keep track of start time/frame for later
    aperture.tStart = t  # underestimates by a little under one frame
    aperture.frameNStart = frameN  # exact frame index
    aperture.enabled = True
if aperture.status == STARTED and t >= (0.0 + (-win.monitorFramePeriod*0.75)): #most of one frame period left
    aperture.enabled = False
if aperture.status == STARTED:  # only update if being drawn
    aperture.setPos(mouse.getPos(), log=False)
```

The error is in the second if/then above, which should not occur. It is included as if there was a maximum duration in effect, but the value is omitted in the `(-win.monitorFramePeriod*0.75)` expression and hence the duration is effectively zero.

The fix here should be simple but I'm not familiar with playing with the Builder component generation code. So recording the bug here until I can figure out how to fix it (and test).

A work-around for users in the mean time would be to simply put an unfeasibly large number in the duration field (e.g. 9999).



Discussion:

Resolving patch:
diff --git a/psychopy/app/builder/components/aperture.py b/psychopy/app/builder/components/aperture.py
--- a/psychopy/app/builder/components/aperture.py
+++ b/psychopy/app/builder/components/aperture.py
@@ -78,11 +78,12 @@ def writeFrameCode(self, buff):
         buff.writeIndented("%(name)s.enabled = True\n" % self.params)
         # to get out of the if statement
         buff.setIndentLevel(-1, relative=True)
-        # writes an if statement to determine whether to draw etc
-        self.writeStopTestCode(buff)
-        buff.writeIndented("%(name)s.enabled = False\n" % self.params)
-        # to get out of the if statement
-        buff.setIndentLevel(-1, relative=True)
+        if self.params['stopVal'].val not in ['', None, -1, 'None']:
+            # writes an if statement to determine whether to draw etc
+            self.writeStopTestCode(buff)
+            buff.writeIndented("%(name)s.enabled = False\n" % self.params)
+            # to get out of the if statement
+            buff.setIndentLevel(-1, relative=True)
         # set parameters that need updating every frame
         # do any params need updating? (this method inherited from _base)
         if self.checkNeedToUpdate('set every frame'):


Test patch:
Repository: psychopy/psychopy

Issue:
"continueRoutine = True" in Builder generated code should occur earlier
To have conditional execution of a routine (e.g. a rest break every 10th trial), a code snippet like this is often suggested:

```
if not loopName.thisN in [9, 19, 29]:
    continueRoutine = False
```

It would be logical if such code was placed in the "Begin routine" tab of a code component. But this is executed immediately prior to a routine:

```
#-------Start Routine "trial"-------
continueRoutine = True
```

So a change affecting `continueRoutine` in the "begin routine" tab is immediately counteracted by the template code. 

Should the above line in the compiled code be shifted to _before_ where  any "begin routine" code is placed? Otherwise any attempt to end a routine has to occur in the "Every frame" tab. 

Needing to always put `continueRoutine` code in the "Every frame" tab has two disadvantages:
- Probably one frame of a routine will be presented before it can then be terminated. This could cause a visible flicker in stimuli, or some other undesired action.
- It encourages inappropriate mixing of logic, and needlessly performing a single check multiple times. That is, some `continueRoutine` checks should be evaluated only once, prior to a routine (e.g. checking a trial number), while other `continueRoutine` checks should be monitored continuously, on every frame. We should allow hose checks to be placed where they should be, logically and performance-wise.



Discussion:

Resolving patch:
diff --git a/psychopy/app/builder/experiment.py b/psychopy/app/builder/experiment.py
--- a/psychopy/app/builder/experiment.py
+++ b/psychopy/app/builder/experiment.py
@@ -1526,6 +1526,7 @@ def writeInitCode(self, buff):
         buff.writeIndentedLines(code % self.name)
         self._clockName = self.name + "Clock"
         buff.writeIndented('%s = core.Clock()\n' % self._clockName)
+        buff.writeIndented('continueRoutine = True\n')
         for thisCompon in self:
             thisCompon.writeInitCode(buff)
 
@@ -1556,8 +1557,7 @@ def writeMainCode(self, buff):
         code = ("for thisComponent in %sComponents:\n"
                 "    if hasattr(thisComponent, 'status'):\n"
                 "        thisComponent.status = NOT_STARTED\n"
-                '\n# -------Start Routine "%s"-------\n'
-                'continueRoutine = True\n')
+                '\n# -------Start Routine "%s"-------\n')
         buff.writeIndentedLines(code % (self.name, self.name))
         if useNonSlip:
             code = 'while continueRoutine and routineTimer.getTime() > 0:\n'


Test patch:
Repository: psychopy/psychopy

Issue:
pySerial API change
The pySerial [API](http://pythonhosted.org/pyserial/pyserial_api.html) has changed, and we need to adjust the respective PsychoPy code that uses pySerial.



Discussion:

Resolving patch:
diff --git a/psychopy/hardware/minolta.py b/psychopy/hardware/minolta.py
--- a/psychopy/hardware/minolta.py
+++ b/psychopy/hardware/minolta.py
@@ -128,10 +128,10 @@ def __init__(self, port, maxAttempts=1):
         if self.OK:
             self.com.close()  # not sure why this helps but on win32 it does!!
             # this is a slightly odd characteristic of the Minolta LS100
-            self.com.setByteSize(7)
-            self.com.setBaudrate(4800)
-            self.com.setParity(serial.PARITY_EVEN)  # none
-            self.com.setStopbits(serial.STOPBITS_TWO)
+            self.com.bytesize = 7
+            self.com.baudrate = 4800
+            self.com.parity = serial.PARITY_EVEN  # none
+            self.com.stopbits = serial.STOPBITS_TWO
             try:
                 if not self.com.isOpen():
                     self.com.open()
diff --git a/psychopy/hardware/pr.py b/psychopy/hardware/pr.py
--- a/psychopy/hardware/pr.py
+++ b/psychopy/hardware/pr.py
@@ -93,9 +93,9 @@ def __init__(self, port, verbose=None):
             self._error(msg % sys.platform)
         # setup the params for PR650 comms
         if self.OK:
-            self.com.setBaudrate(9600)
-            self.com.setParity('N')  # none
-            self.com.setStopbits(1)
+            self.com.baudrate = 9600
+            self.com.parity = 'N'  # none
+            self.com.stopbits = 1
             try:
                 # Pyserial >=2.6 throws an exception when trying to open a
                 # serial port that is already open. Catching that exception
@@ -315,9 +315,9 @@ def __init__(self, port):
             self._error(msg % self.portString)
         # setup the params for PR650 comms
         if self.OK:
-            self.com.setBaudrate(9600)
-            self.com.setParity('N')  # none
-            self.com.setStopbits(1)
+            self.com.baudrate = 9600
+            self.com.parity = 'N'  # none
+            self.com.stopbits = 1
             try:
                 self.com.close()  # attempt to close if it's currently open
                 self.com.open()


Test patch:
Repository: psychopy/psychopy

Issue:
Crash when increasing size of flow in PsychoPy Builder
I shrank the flow size and now am unable to increase it to its previous size. Both going to Tools > Increase flow or using keyboard shortcut causes the crash. Newly opening PsychoPy or working with an open experiment still reproduces the crash.

PsychoPy ~~1.84.1~~ / [EDIT: 1.84.2]
Mac OSX ~~10.11.6~~ / [EDIT: 10.12]



Discussion:

Resolving patch:
diff --git a/psychopy/app/builder/builder.py b/psychopy/app/builder/builder.py
--- a/psychopy/app/builder/builder.py
+++ b/psychopy/app/builder/builder.py
@@ -1276,37 +1276,37 @@ def makeMenus(self):
         self.viewMenu = wx.Menu()
         menuBar.Append(self.viewMenu, _translate('&View'))
         menu = self.viewMenu
-        menu.Append(self.IDs.openCoderView,
+        item = menu.Append(wx.ID_ANY,
                     _translate("&Open Coder view\t%s") % keys['switchToCoder'],
                     _translate("Open a new Coder view"))
-        wx.EVT_MENU(self, self.IDs.openCoderView, self.app.showCoder)
-        menu.Append(self.IDs.toggleReadme,
+        wx.EVT_MENU(self,item.GetId(), self.app.showCoder)
+        item = menu.Append(self.IDs.toggleReadme,
                     _translate(
                         "&Toggle readme\t%s") % self.app.keys['toggleReadme'],
                     _translate("Toggle Readme"))
-        wx.EVT_MENU(self, self.IDs.toggleReadme, self.toggleReadme)
-        menu.Append(self.IDs.tbIncrFlowSize,
+        wx.EVT_MENU(self, item.GetId(), self.toggleReadme)
+        item = menu.Append(wx.ID_ANY,
                     _translate(
                         "&Flow Larger\t%s") % self.app.keys['largerFlow'],
                     _translate("Larger flow items"))
-        wx.EVT_MENU(self, self.IDs.tbIncrFlowSize,
+        wx.EVT_MENU(self, item.GetId(),
                     self.flowPanel.increaseSize)
-        menu.Append(self.IDs.tbDecrFlowSize,
+        item = menu.Append(wx.ID_ANY,
                     _translate(
                         "&Flow Smaller\t%s") % self.app.keys['smallerFlow'],
                     _translate("Smaller flow items"))
-        wx.EVT_MENU(self, self.IDs.tbDecrFlowSize,
+        wx.EVT_MENU(self, item.GetId(),
                     self.flowPanel.decreaseSize)
-        menu.Append(self.IDs.tbIncrRoutineSize,
+        item = menu.Append(wx.ID_ANY,
                     _translate("&Routine Larger\t%s") % keys['largerRoutine'],
                     _translate("Larger routine items"))
-        wx.EVT_MENU(self, self.IDs.tbIncrRoutineSize,
+        wx.EVT_MENU(self, item.GetId(),
                     self.routinePanel.increaseSize)
-        menu.Append(self.IDs.tbDecrRoutineSize,
+        item = menu.Append(wx.ID_ANY,
                     _translate("&Routine Smaller\t%s") %
                     keys['smallerRoutine'],
                     _translate("Smaller routine items"))
-        wx.EVT_MENU(self, self.IDs.tbDecrRoutineSize,
+        wx.EVT_MENU(self, item.GetId(),
                     self.routinePanel.decreaseSize)
 
         # ---_experiment---#000000#FFFFFF-------------------------------------


Test patch:
Repository: psychopy/psychopy

Issue:
psychopyApp won't start with Matplotlib 1.5 installed
See http://discourse.psychopy.org/t/mac-specific-help/1540/3

We need to figure out
- whether this problem is Anaconda-specific (and would require fixing upstream)
- whether this problem is Mac-specific


Discussion:
I'm pretty sure this occurs anytime that wx has been imported before matplotlib. I haven't found out what changed in matplotlib, but I  imagine it has a different os more restrictive expectation of valid language encodings. I think the fix will be either a) change to matplotlib upstream to detect the current lang setting from wx or b) change to wx so that the default it sets is matplotlib-compatible

I definitely don't think it's a psychopy problem though, but a dependency clash
I wonder if this could be related: https://github.com/matplotlib/matplotlib/issues/5737
No, I think that issue was due to a matplotlib user trying to get two different gui clients (wx and QT) to run in Python at one time. We do occasionally see that problem too, but that's unrelated to this issue with language encoding.

Resolving patch:
diff --git a/psychopy/app/psychopyApp.py b/psychopy/app/psychopyApp.py
--- a/psychopy/app/psychopyApp.py
+++ b/psychopy/app/psychopyApp.py
@@ -8,6 +8,8 @@
 
 import sys
 from psychopy.app._psychopyApp import PsychoPyApp, __version__
+# fix OS X locale-bug on startup: sets locale to LC_ALL (must be defined!)
+import psychopy.locale_setup  # noqa
 
 # NB the PsychoPyApp classes moved to _psychopyApp.py as of version 1.78.00
 # to allow for better upgrading possibilities from the mac app bundle. this


Test patch:
Repository: psychopy/psychopy

Issue:
Multi-window rendering not possible when useFBO=True
When drawing to multiple windows when useFBO is enabled (on all), stimuli drawing does not work correctly since _selectWindow in WindowMixin does not bind the framebuffer of the target window when called. This causes drawing to be diverted to some other buffer causing unexpected results. 

This was discussed and solved on the Discourse board (https://discourse.psychopy.org/t/multiple-windows-with-usefbo-true/2285/15) where I proposed an interim solution. 

I'll handle this one.


Discussion:

Resolving patch:
diff --git a/psychopy/visual/basevisual.py b/psychopy/visual/basevisual.py
--- a/psychopy/visual/basevisual.py
+++ b/psychopy/visual/basevisual.py
@@ -1150,10 +1150,10 @@ def draw(self):
                                   'visual.BaseVisualStim.draw')
 
     def _selectWindow(self, win):
-        # don't call switch if it's already the curr window
-        if win != globalVars.currWindow and win.winType == 'pyglet':
-            win.winHandle.switch_to()
-            globalVars.currWindow = win
+        """Switch drawing to the specified window. Calls the window's 
+        _setCurrent() method which handles the switch.
+        """
+        self.win._setCurrent()
 
     def _updateList(self):
         """The user shouldn't need this method since it gets called
diff --git a/psychopy/visual/window.py b/psychopy/visual/window.py
--- a/psychopy/visual/window.py
+++ b/psychopy/visual/window.py
@@ -548,6 +548,26 @@ def saveFrameIntervals(self, fileName=None, clear=True):
             self.frameIntervals = []
             self.frameClock.reset()
 
+    def _setCurrent(self):
+        """Make this window current. If useFBO=True, the framebuffer is bound
+        after the context switch. 
+        """
+        if self != globalVars.currWindow and self.winType == 'pyglet':
+            self.winHandle.switch_to()
+            globalVars.currWindow = self
+
+            # if we are using an FBO, bind it
+            if self.useFBO:
+                GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT,
+                                        self.frameBuffer)
+                GL.glReadBuffer(GL.GL_COLOR_ATTACHMENT0_EXT)
+                GL.glDrawBuffer(GL.GL_COLOR_ATTACHMENT0_EXT)
+
+                # NB - check if we need these
+                GL.glActiveTexture(GL.GL_TEXTURE0)
+                GL.glBindTexture(GL.GL_TEXTURE_2D, 0)
+                GL.glEnable(GL.GL_STENCIL_TEST)
+
     def onResize(self, width, height):
         """A default resize event handler.
 


Test patch:
Repository: psychopy/psychopy

Issue:
cleanup hangs after microphone.record is called
I'm running the following code snippet to record using the microphone, and my script never terminates.  

``` .py
from psychopy import microphone
microphone.switchOn(48000, outputDevice=None, bufferSize=None)
mic = microphone.AdvAudioCapture()
mic.record(5)
```

I'm on Mac OS 10.7.5, using python 2.7.8 and psychopy 1.81.00rc1.  I ran the code using verbose mode (`python -v`) and noticed that the cleanup stage seems to hang. The full output is [here](https://gist.github.com/susinmotion/8531c8bcab810d61cae9) - notice that the last line, which never terminates, is `cleanup[2] psychopy.sound`. It looks like the sound module might be trying to clean up open files, but I'm not sure if that's the source of the problem.



Discussion:
I am getting this or very similar for playing sounds (when using pyo at least).


Resolving patch:
diff --git a/psychopy/sound/backend_pyo.py b/psychopy/sound/backend_pyo.py
--- a/psychopy/sound/backend_pyo.py
+++ b/psychopy/sound/backend_pyo.py
@@ -21,6 +21,7 @@
     # convert this import error to our own, pyo probably not installed
     raise exceptions.DependencyError(repr(err))
 
+import atexit
 import sys
 import threading
 pyoSndServer = None
@@ -213,6 +214,10 @@ def __del__(self):
         pyoSndServer.boot()
     core.wait(0.5)  # wait for server to boot before starting te sound stream
     pyoSndServer.start()
+    
+    #atexit is filo, will call stop then shutdown upon closing
+    atexit.register(pyoSndServer.shutdown)
+    atexit.register(pyoSndServer.stop)
     try:
         Sound()  # test creation, no play
     except pyo.PyoServerStateException:


Test patch:
Repository: psychopy/psychopy

Issue:
UnicodeChars constants defined twice with different values
Using [lgtm.com](https://lgtm.com/projects/g/psychopy/psychopy/snapshot/d0ddaca2429ab89b7f8575e1e14d271a5475d504/files/psychopy/iohub/constants.py#x1b62aba3ab970038%3A1)

In [IOhub](https://github.com/psychopy/psychopy/blob/master/psychopy/iohub/constants.py#L658), three constants are defined twice:
INSERT = 0xF727  # "Insert"
INSERT = 0xF73D  # "InsertChar"

DELETE = 0xF728  # "Delete"
DELETE = 0xF73E  # "DeleteChar"

PRINT = 0xF738  # "Print"
PRINT = 0xF72E  # "PrintScreen"

I am not sure what are the ramifications of this or what is the right way to fix it.




Discussion:
Not sure about this. I'm not sure I've ever seen a keyboard with Insert and InsertChar keys :-/ but I think it would be sensible to rename those variables as INSERT_CHAR, DELETE_CHAR and PRINT_SCREEN

Resolving patch:
diff --git a/psychopy/iohub/constants.py b/psychopy/iohub/constants.py
--- a/psychopy/iohub/constants.py
+++ b/psychopy/iohub/constants.py
@@ -707,7 +707,7 @@ class UnicodeChars(Constants):
         END = 0xF72B  # "End"
         PAGE_UP = 0xF72C  # "PageUp"
         PAGE_DOWN = 0xF72D  # "PageDown"
-        PRINT = 0xF72E  # "PrintScreen"
+        PRINT_SCREEN = 0xF72E  # "PrintScreen"
         SCROLL_LOCK = 0xF72F  # "ScrollLock"
         PAUSE = 0xF730  # "Pause"
         SYSREQ = 0xF731  # "SysReq"
@@ -723,8 +723,8 @@ class UnicodeChars(Constants):
         CLEAR = 0xF73A  # "ClearDisplay"
         INSERT_LINE = 0xF73B  # "InsertLine"
         DELETE_LINE = 0xF73C  # "DeleteLine"
-        INSERT = 0xF73D  # "InsertChar"
-        DELETE = 0xF73E  # "DeleteChar"
+        INSERT_CHAR = 0xF73D  # "InsertChar"
+        DELETE_CHAR = 0xF73E  # "DeleteChar"
         PREV = 0xF73F  # "Prev"
         NEXT = 0xF740  # "Next"
         SELECT = 0xF741  # "Select"


Test patch:
Repository: psychopy/psychopy

Issue:
visual.RatingScale doesn't display correct labels with choices that start with 0
When creating a `visual.RatingScale` with the `choices` option, if the `choices` list begins with an _integer_ or _float_ that is falsey (i.e. 0, or 0.0), the left most tick label does not get drawn. 

Example:
```
choices = list(np.arange(10))
spending_scale = visual.RatingScale(win=window, choices=choices,
                                                              showAccept=False,
                                                              noMouse=True,
                                                              stretch=2,
                                                              pos = (0,0),
                                                              textColor= 'White')
```
![image](https://user-images.githubusercontent.com/8481982/34645020-4449177c-f311-11e7-922f-018f31e2cbd2.png)

Version: Psychopy2 Standalone 1.85.3
OS: Mac OSX 10.11.6 El Capitan
Hardware: Macbook Pro Retina 15inch (Mid 2015)
  


Discussion:
I can post this in https://discourse.psychopy.org if that's preferable 
No need to post on discourse for this - it looks like a genuine bug. @dvbridges cold you have a dig around RatingScale and see if you can work out the problem?
No problem, looking now.

Resolving patch:
diff --git a/psychopy/visual/ratingscale.py b/psychopy/visual/ratingscale.py
--- a/psychopy/visual/ratingscale.py
+++ b/psychopy/visual/ratingscale.py
@@ -894,7 +894,7 @@ def _initTextElements(self, win, scale, textColor,
                 vertPosTmp = -2 * self.textSizeSmall * self.size + self.offsetVert
             for i, label in enumerate(self.labelTexts):
                 # need all labels for tick position, i
-                if label:  # skip '' placeholders, no need to create them
+                if label or label is not None: # 'is not None' allows creation of '0' (zero or false) labels
                     txtStim = TextStim(
                         win=self.win, text=str(label), font=textFont,
                         pos=[self.tickPositions[i // self.autoRescaleFactor],


Test patch:
Repository: psychopy/psychopy

Issue:
Small iohub.datastore weirdness
So there is this [weird code block](https://github.com/psychopy/psychopy/blob/88a359df45ce453d4fd95986cf902e66cf2fe480/psychopy/iohub/datastore/__init__.py#L581) in `iohub.datastore.__init__.py`:

``` python
try:
    global registered_close_open_data_files
    if registered_close_open_data_files is True:
        pass
except Exception:
    registered_close_open_data_files = True
    atexit.register(close_open_data_files, False)
```

As far as I can tell, `registered_close_open_data_files` is never defined in the top-level scope, meaning, the exception will always be raised. Therefore it appears to me this code could be simplified to:

``` python
registered_close_open_data_files = True
atexit.register(close_open_data_files, False)
```

@isolver, do you feel like looking into this? Not urgent, though ;) Thanks!



Discussion:
Agreed.

I think the code originally was being called from within a function and I
was trying to ensure that the 'atexit' callback was only ever registered
once.

Given the current code though, I think your suggestion makes sense. As you
suggested,  it is not urgent though.

Thanks.


Resolving patch:
diff --git a/psychopy/iohub/datastore/__init__.py b/psychopy/iohub/datastore/__init__.py
--- a/psychopy/iohub/datastore/__init__.py
+++ b/psychopy/iohub/datastore/__init__.py
@@ -477,13 +477,8 @@ def close_open_data_files(verbose):
             if verbose:
                 print2err('done')
 
-try:
-    global registered_close_open_data_files
-    if registered_close_open_data_files is True:
-        pass
-except Exception:
-    registered_close_open_data_files = True
-    atexit.register(close_open_data_files, False)
+registered_close_open_data_files = True
+atexit.register(close_open_data_files, False)
 
 ## ---------------------- Pytable Definitions ------------------- ##
 


Test patch:
Repository: psychopy/psychopy

Issue:
Problem with psychopy logging on linux
Perhaps I am using this incorrectly, but the following script produces no console output on Ubuntu 16.04:

```python
#! /usr/bin/env python

from psychopy import logging
logging.fatal('should be an error')
```

I'm using a conda virtualenv with the psychopy development version (current commit, version 1.90.0).

Thanks 



Discussion:

Resolving patch:
diff --git a/psychopy/app/preferencesDlg.py b/psychopy/app/preferencesDlg.py
--- a/psychopy/app/preferencesDlg.py
+++ b/psychopy/app/preferencesDlg.py
@@ -384,7 +384,7 @@ def __init__(self, parent, name, value, spec):
                         for thisDevName in devs:
                             if thisDevName not in options:
                                 options.append(thisDevName)
-                except (ValueError, OSError):
+                except (ValueError, OSError, DependencyError):
                     pass
             else:
                 options = spec.replace("option(", "").replace("'", "")
diff --git a/psychopy/logging.py b/psychopy/logging.py
--- a/psychopy/logging.py
+++ b/psychopy/logging.py
@@ -38,6 +38,7 @@
 from builtins import object
 from past.builtins import basestring
 from os import path
+import atexit
 import sys
 import codecs
 import locale
@@ -294,6 +295,8 @@ def flush(logger=root):
     """Send current messages in the log to all targets
     """
     logger.flush()
+# make sure this function gets called as python closes
+atexit.register(flush)
 
 
 def critical(msg, t=None, obj=None):


Test patch: