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

Issue:
Exceptions as PsychoPy attempts to validate unfinished code
While typing code into a component's field prefixed with $, PsychoPy will repeatedly throw errors as you type. The error is as follows:
```
Traceback (most recent call last):
 File "C:\path\to\PsychoPy3\lib\site-packages\psychopy\app\builder\validators.py", line 205, in check
  names = compile(code, '', 'exec').co_names
TypeError: compile() arg 1 must be a string, bytes or AST object

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
 File "C:\path\to\PsychoPy3\lib\site-packages\psychopy\app\builder\validators.py", line 58, in Validate
  message, valid = self.check(parent)
 File "C:\path\to\PsychoPy3\lib\site-packages\psychopy\app\builder\validators.py", line 208, in check
  if not code.strip() == '':
AttributeError: 'NoneType' object has no attribute 'strip'

```

In my experience, it sends the same exception twice in a row, then waits until you start typing again, and will then throw it two times more, and so on.

I'm guessing PsychoPy is intending to show me some feedback on whether or not the code I am typing is valid, but I'm not seeing any feedback, so that could be part of the issue.

This is on the latest release v2020.2.2



Discussion:

Resolving patch:
diff --git a/psychopy/app/pavlovia_ui/project.py b/psychopy/app/pavlovia_ui/project.py
--- a/psychopy/app/pavlovia_ui/project.py
+++ b/psychopy/app/pavlovia_ui/project.py
@@ -494,6 +494,7 @@ def syncProject(parent, project=None, closeFrameWhenDone=False):
             return 0
 
     # a sync will be necessary so set the target to Runner stdout
+    parent.app.showRunner()
     syncFrame = parent.app.runner.stdOut
 
     if project._newRemote:
diff --git a/psychopy/experiment/params.py b/psychopy/experiment/params.py
--- a/psychopy/experiment/params.py
+++ b/psychopy/experiment/params.py
@@ -238,7 +238,7 @@ def getCodeFromParamStr(val):
     out = re.sub(r"[\\]\$", '$', tmp2)  # remove \ from all \$
     if utils.scriptTarget=='PsychoJS':
         out = py2js.expression2js(out)
-    return out
+    return out if out else ''
 
 
 def toList(val):


Test patch:
Repository: psychopy/psychopy

Issue:
Fields marked as code are not translated to JS
Any field that is prefixed with $ and contains python specific code will break once the project is exported as HTML, because that field will not be translated. This is easily reproduced by giving a text stimulus python specific code like `len([0,1])` and trying to run the study on Pavlovia. The error I get is `ReferenceError: len is not defined`.

I'm not so sure on how the translation process is structured, but this would be a nice thing to have. I work around the issue by setting those fields to a variable that I declare and set earlier in the routine (the code component then being translated as needed). This is on the latest release v2020.2.2


Discussion:

Resolving patch:
diff --git a/psychopy/experiment/params.py b/psychopy/experiment/params.py
--- a/psychopy/experiment/params.py
+++ b/psychopy/experiment/params.py
@@ -160,7 +160,13 @@ def __str__(self):
             if isinstance(self.val, basestring):
                 codeWanted = utils.unescapedDollarSign_re.search(self.val)
                 if codeWanted:
-                    return "%s" % getCodeFromParamStr(self.val)
+                    if utils.scriptTarget == 'PsychoJS':
+                        valJS = py2js.expression2js(self.val.strip('$'))
+                        if self.val != valJS:
+                            logging.debug("Rewriting with py2js: {} -> {}".format(self.val, valJS))
+                        return valJS
+                    else:
+                        return "%s" % getCodeFromParamStr(self.val)
                 else:  # str wanted
                     # remove \ from all \$
                     s = repr(re.sub(r"[\\]\$", '$', self.val))
diff --git a/psychopy/experiment/py2js.py b/psychopy/experiment/py2js.py
--- a/psychopy/experiment/py2js.py
+++ b/psychopy/experiment/py2js.py
@@ -21,6 +21,7 @@
     from io import StringIO
 else:
     from StringIO import StringIO
+from psychopy.experiment.py2js_transpiler import translatePythonToJavaScript
 
 
 class NamesJS(dict):
@@ -106,6 +107,14 @@ def expression2js(expr):
                 continue
             node.id = namesJS[node.id]
     jsStr = unparse(syntaxTree).strip()
+    if not any(ch in jsStr for ch in ("=",";","\n")):
+        try:
+            jsStr = translatePythonToJavaScript(jsStr)
+            if jsStr.endswith(';\n'):
+                jsStr = jsStr[:-2]
+        except:
+            # If translation fails, just use old translation
+            pass
     return jsStr
 
 def snippet2js(expr):


Test patch:
Repository: psychopy/psychopy

Issue:
Benchmark report has an incorrect URL (https://discourse.osychopy.org/)
Ubuntu 18.04, Anaconda Python, PsychoPy v2020.2.3
conda install instructions with psychopy env yaml 

Generate benchmark report $HOME/.psychopy3/benchmarkReport.html
Search the user-group archives link in benchmark report has an incorrect URL (https://discourse.osychopy.org/)


Discussion:

Resolving patch:
diff --git a/psychopy/tools/wizard.py b/psychopy/tools/wizard.py
--- a/psychopy/tools/wizard.py
+++ b/psychopy/tools/wizard.py
@@ -456,7 +456,7 @@ def htmlReport(self, items=None, fatal=False):
             htmlDoc += _translate('''<p>Resources:
                 | <a href="http://www.psychopy.org/documentation.html">On-line documentation</a>
                 | Download <a href="http://www.psychopy.org/PsychoPyManual.pdf">PDF manual</a>
-                | <a href="https://discourse.osychopy.org">Search the user-group archives</a>
+                | <a href="https://discourse.psychopy.org">Search the user-group archives</a>
                 </p>''')
             htmlDoc += '<hr><p></p>    <table cellspacing=8 border=0>\n'
             htmlDoc += '    <tr><td><font size=+1><strong>' + \


Test patch:
Repository: psychopy/psychopy

Issue:
RatingScale marker turns grey if the scale times out and does not refresh on next trial
Using PsychoPy v2020.1.2, the RatingScale marker turns grey if the scale times out and remains grey on all subsequent trials. The marker color is never reset to the original color.

This issue is substantially the same as #868 which was fixed, and then reintroduced in #1665.


Discussion:

Resolving patch:
diff --git a/psychopy/visual/ratingscale.py b/psychopy/visual/ratingscale.py
--- a/psychopy/visual/ratingscale.py
+++ b/psychopy/visual/ratingscale.py
@@ -857,6 +857,7 @@ def _initMarker(self, marker, markerColor, expansion):
         self.markerColor = markerColor
         self.markerYpos = self.offsetVert + self.markerOffsetVert
         # save initial state, restore on reset
+        self.markerColorOriginal = markerColor
 
     def _initTextElements(self, win, scale, textColor,
                           textFont, textSize, showValue, tickMarks):
@@ -903,6 +904,16 @@ def _initTextElements(self, win, scale, textColor,
         self.origScaleDescription = scale
         self.setDescription(scale)  # do last
 
+    def _setMarkerColor(self, color):
+        """Set the fill color or color of the marker"""
+        try:
+            self.marker.setFillColor(color, log=False)
+        except AttributeError:
+            try:
+                self.marker.setColor(color, log=False)
+            except Exception:
+                pass
+
     def setDescription(self, scale=None, log=True):
         """Method to set the brief description (scale).
 
@@ -1144,13 +1155,8 @@ def draw(self, log=True):
         if self.noResponse == False:
             # fix the marker position on the line
             if not self.markerPosFixed:
-                try:
-                    self.marker.setFillColor('DarkGray', log=False)
-                except AttributeError:
-                    try:
-                        self.marker.setColor('DarkGray', log=False)
-                    except Exception:
-                        pass
+                self._setMarkerColor('DarkGray')
+
                 # drop it onto the line
                 self.marker.setPos((0, -.012), ('+', '-')[self.flipVert],
                                    log=False)
@@ -1331,8 +1337,8 @@ def reset(self, log=True):
                 labels.setColor(self.textColor, log=False)
         self.noResponse = True
         # restore in case it turned gray, etc
-        self.resetMarker = str(self.marker)
-        self.resetMarker = self.resetMarker.replace('Window(...)', 'self.win')
+        self.markerColor = self.markerColorOriginal
+        self._setMarkerColor(self.markerColor)
         # placed by subject or markerStart: show on screen
         self.markerPlaced = False
         # placed by subject is actionable: show value, singleClick


Test patch:
Repository: psychopy/psychopy

Issue:
Slider component not rendered in routine order
Most components seem to be rendered in the order they are arranged in the Routine canvas: routines at the top are rendered first, then subsequent routines are rendered on top. Slider components do not respect the routine order and so can be obscured by other routines being rendered on top.


Discussion:

Resolving patch:
diff --git a/psychopy/experiment/components/slider/__init__.py b/psychopy/experiment/components/slider/__init__.py
--- a/psychopy/experiment/components/slider/__init__.py
+++ b/psychopy/experiment/components/slider/__init__.py
@@ -177,13 +177,15 @@ def writeInitCode(self, buff):
         if inits['units'].val == 'from exp settings':
             inits['units'].val = None
 
+        inits['depth'] = -self.getPosInRoutine()
+
         # build up an initialization string for Slider():
         initStr = ("{name} = visual.Slider(win=win, name='{name}',\n"
                    "    size={size}, pos={pos}, units={units},\n"
                    "    labels={labels}, ticks={ticks},\n"
                    "    granularity={granularity}, style={styles},\n"
                    "    color={color}, font={font},\n"
-                   "    flip={flip})\n"
+                   "    flip={flip}, depth={depth})\n"
                    .format(**inits))
         buff.writeIndented(initStr)
 
@@ -222,6 +224,8 @@ def writeInitCodeJS(self, buff):
         inits['styles'].val += ','
         inits['styles'].val = py2js.expression2js(inits['styles'].val)
 
+        inits['depth'] = -self.getPosInRoutine()
+
         # build up an initialization string for Slider():
         initStr = ("{name} = new visual.Slider({{\n"
                    "  win: psychoJS.window, name: '{name}',\n"
@@ -229,7 +233,7 @@ def writeInitCodeJS(self, buff):
                    "  labels: {labels}, ticks: {ticks},\n"
                    "  granularity: {granularity}, style: {styles},\n"
                    "  color: new util.Color({color}), \n"
-                   "  fontFamily: {font}, bold: true, italic: false, \n"
+                   "  fontFamily: {font}, bold: true, italic: false, depth: {depth}, \n"
                    ).format(**inits)
         initStr += ("  flip: {flip},\n"
                     "}});\n\n").format(flip=boolConverter[inits['flip'].val])


Test patch:
Repository: psychopy/psychopy

Issue:
Builder help link for Slider component is broken
The help button in the SliderComponent in the Builder view is broken because it points to https://www.psychopy.org/builder/components/slidercomponent.html which does not exist.


Discussion:

Resolving patch:
diff --git a/psychopy/experiment/components/slider/__init__.py b/psychopy/experiment/components/slider/__init__.py
--- a/psychopy/experiment/components/slider/__init__.py
+++ b/psychopy/experiment/components/slider/__init__.py
@@ -77,7 +77,7 @@ def __init__(self, exp, parentName,
                 stopType=stopType, stopVal=stopVal,
                 startEstim=startEstim, durationEstim=durationEstim)
         self.type = 'Slider'
-        self.url = "http://www.psychopy.org/builder/components/slidercomponent.html"
+        self.url = "http://www.psychopy.org/builder/components/slider.html"
         self.exp.requirePsychopyLibs(['visual', 'event'])
         self.targets = ['PsychoPy', 'PsychoJS']
 
diff --git a/psychopy/visual/slider.py b/psychopy/visual/slider.py
--- a/psychopy/visual/slider.py
+++ b/psychopy/visual/slider.py
@@ -41,7 +41,7 @@ class Slider(MinimalStim):
     ``getRT()`` to get the decision time, or ``getHistory()`` to obtain
     the entire set of (rating, RT) pairs.
 
-    For other examples see Coder Demos -> stimuli -> slider.py.
+    For other examples see Coder Demos -> stimuli -> ratingsNew.py.
 
     :Authors:
         - 2018: Jon Peirce


Test patch:
Repository: psychopy/psychopy

Issue:
autocomplete is raising an error on mac standalone
My guess is that jedi needs to be packaged differently so that it isn't "frozen"


Discussion:
I originally wrote a Python autocomplete system from scratch that worked well enough, a was a bit faster too but not as smart as Jedi. I might revive it if Jedi becomes a bit of a pain to work with.
Don't worry for now. I _think_ it will be an easy fix when packaging

Resolving patch:
diff --git a/setupApp.py b/setupApp.py
--- a/setupApp.py
+++ b/setupApp.py
@@ -104,7 +104,7 @@ def dyld_find(name, loader=None, **kwargs):
             'badapted', 'darc_toolbox',  # adaptive methods from Ben Vincent
             'questplus',
             'metapensiero.pj', 'dukpy', 'macropy',
-            'jedi',
+            'jedi','parso',
             'psychtoolbox',
             'freetype', 'h5py',
             ]


Test patch:
Repository: psychopy/psychopy

Issue:
Having a TextStim text that is empty or None misrepresented in JS
As discussed on the forum [here](https://discourse.psychopy.org/t/initialise-experiment-wont-end) and [here](https://discourse.psychopy.org/t/empty-text-leading-online-experiment-not-initializing), and quoting from the Crib Sheet, the JS ends up being `text: /*  */` which gives a SyntaxError. @TEParsons this looks similar to a TextBox bug you tackled the other day.

Demo: [run.pavlovia.org/thewhodidthis/textstim &rarr;](https://run.pavlovia.org/thewhodidthis/textstim/)


Discussion:

Resolving patch:
diff --git a/psychopy/app/_psychopyApp.py b/psychopy/app/_psychopyApp.py
--- a/psychopy/app/_psychopyApp.py
+++ b/psychopy/app/_psychopyApp.py
@@ -424,10 +424,6 @@ def onInit(self, showSplash=True, testMode=False):
         # we wanted debug mode while loading but safe to go back to info mode
         if not self.prefs.app['debugMode']:
             logging.console.setLevel(logging.INFO)
-        # Runner captures standard streams until program closed
-        if self.runner and not self.testMode:
-            sys.stdout = self.runner.stdOut
-            sys.stderr = self.runner.stdOut
 
         return True
 
@@ -590,6 +586,10 @@ def showRunner(self, event=None, fileList=[]):
             self.runner.Show()
             self.runner.Raise()
             self.SetTopWindow(self.runner)
+        # Runner captures standard streams until program closed
+        if self.runner and not self.testMode:
+            sys.stdout = self.runner.stdOut
+            sys.stderr = self.runner.stdOut
 
     def newRunnerFrame(self, event=None):
         # have to reimport because it is only local to __init__ so far
diff --git a/psychopy/experiment/components/__init__.py b/psychopy/experiment/components/__init__.py
--- a/psychopy/experiment/components/__init__.py
+++ b/psychopy/experiment/components/__init__.py
@@ -214,8 +214,12 @@ def getInitVals(params, target="PsychoPy"):
 
         # value should be None (as code)
         elif inits[name].val in [None, 'None', 'none', '']:
-            inits[name].val = 'None'
-            inits[name].valType = 'code'
+            if name in ['text']:
+                inits[name].val = None
+                inits[name].valType = 'extendedStr'
+            else:
+                inits[name].val = 'None'
+                inits[name].valType = 'code'
 
         # is constant so don't touch the parameter value
         elif inits[name].updates in ['constant', None, 'None']:


Test patch:
Repository: psychopy/psychopy

Issue:
setAutoDraw(false) skipped when video shorter than duration given in PsychoPy
This happens because when a **MovieStim** is done playing its status turns to `PsychoJS.Status.FINISHED`, but the check that is generated in place is expecting a status of `PsychoJS.Status.STARTED`:
```js
if (movie.status === PsychoJS.Status.STARTED && t >= frameRemains) {
  movie.setAutoDraw(false);
}
```

I believe having a check along the following lines might help:
```js
if ((movie.status === PsychoJS.Status.STARTED || movie.status === PsychoJS.Status.FINISHED) && t >= frameRemains) {
  movie.setAutoDraw(false);
}
```


Discussion:
interesting. Yes, that makes sense I guess, but it sounds strange said out loud! ;-) 

Resolving patch:
diff --git a/psychopy/experiment/components/_base.py b/psychopy/experiment/components/_base.py
--- a/psychopy/experiment/components/_base.py
+++ b/psychopy/experiment/components/_base.py
@@ -355,7 +355,7 @@ def writeStopTestCodeJS(self, buff):
             code = (f"frameRemains = {params['stopVal']} "
                     f" - psychoJS.window.monitorFramePeriod * 0.75;"
                     f"  // most of one frame period left\n"
-                    f"if ({params['name']}.status === PsychoJS.Status.STARTED "
+                    f"if (({params['name']}.status === PsychoJS.Status.STARTED || {params['name']}.status === PsychoJS.Status.FINISHED) "
                     f"&& t >= frameRemains) {{\n")
         # duration in time (s)
         elif (self.params['stopType'].val == 'duration (s)' and


Test patch:
Repository: psychopy/psychopy

Issue:
Setting continueRoutine = false has no effect in "Begin routine" tab in PsychoJS
To skip a routine in PsychoPy, one inserts a conditional that sets `continueRoutine = False` in the "Begin Routine" tab. This has no effect for PsychoJS, however. Users have found a work-around by inserting that conditional check in the "Each frame" tab instead (a common response is to point people to this piece of advice in Wakefield's crib sheet). But the work-around involves an inconsistency between the Python and JavaScript code components, and doesn't fit the conceptual model for when this code should run.

In PsychoJS scripts, this check occurs at the end of the "each frame" functions:

    // check if the Routine should terminate
    if (!continueRoutine) {  // a component has requested a forced-end of Routine
      return Scheduler.Event.NEXT;
    }

But no equivalent check exists in the "Begin routine" functions, which is presumably why custom routine-skipping code doesn't work there. 

Is anyone able to make this change so that the generated JavaScript matches the functionality of the Python scripts?


Discussion:

Resolving patch:
diff --git a/psychopy/experiment/routine.py b/psychopy/experiment/routine.py
--- a/psychopy/experiment/routine.py
+++ b/psychopy/experiment/routine.py
@@ -303,6 +303,13 @@ def writeRoutineBeginCodeJS(self, buff, modular):
                     "    thisComponent.status = PsychoJS.Status.NOT_STARTED;\n"
                     "   });\n"
                     "\nreturn Scheduler.Event.NEXT;\n" % self.params)
+        # are we done yet?
+        code = ("// check if the Routine should terminate\n"
+                "if (!continueRoutine) {"
+                "  // a component has requested a forced-end of Routine\n"
+                "  return Scheduler.Event.NEXT;\n"
+                "}\n")
+        buff.writeIndentedLines(code)
 
         buff.writeIndentedLines(code)
         buff.setIndentLevel(-1, relative=True)


Test patch:
Repository: psychopy/psychopy

Issue:
"Save As..." should update the editor file path to the new file location in title bar.
Title says it all. 


Discussion:
Thi smight sound strange but I'm not entirely sure why the editor needs to have a file path at all. The files themselves have an associated path (e.g. needed as cwd when running the script) but what does it mean for the app to have a path?
This refers to the informal text in the title bar not being updated. You know, where it says `/my/file/code.py - PsychoPy3 Coder` in the title bar.
Oh I see, just that, yes :-) 

Resolving patch:
diff --git a/psychopy/app/coder/coder.py b/psychopy/app/coder/coder.py
--- a/psychopy/app/coder/coder.py
+++ b/psychopy/app/coder/coder.py
@@ -2523,8 +2523,9 @@ def fileSaveAs(self, event, filename=None, doc=None):
             self.currentDoc.setLexerFromFileName()
             # re-analyse the document
             self.currentDoc.analyseScript()
-
+            # Update status bar and title bar labels
             self.statusBar.SetStatusText(self.currentDoc.getFileType(), 2)
+            self.SetLabel(f'{self.currentDoc.filename} - PsychoPy Coder')
 
         dlg.Destroy()
 


Test patch:
Repository: psychopy/psychopy

Issue:
Textbox not editable if multiple textbox components used 
Issue raised on forum https://discourse.psychopy.org/t/editable-textbox-not-responding/17786/5 if multiple textboxes are presented the second is not editable. See minimally working example here.
https://gitlab.pavlovia.org/lpxrh6/textboxbug2


Discussion:

Resolving patch:
diff --git a/psychopy/visual/window.py b/psychopy/visual/window.py
--- a/psychopy/visual/window.py
+++ b/psychopy/visual/window.py
@@ -1028,12 +1028,25 @@ def flip(self, clearBuffer=True):
         self.useLights = False
 
         # Check for mouse clicks on editables
-        if hasattr(self, '_editableChildren'):  # Make sure _editableChildren has actually been created
+        if hasattr(self, '_editableChildren'):
+            # Make sure _editableChildren has actually been created
+            editablesOnScreen = []
             for thisObj in self._editableChildren:
+                # Iterate through editables and decide which one should have focus
                 if isinstance(thisObj, weakref.ref):
-                    thisObj = thisObj()  # Solidify weakref
+                    # Solidify weakref if necessary
+                    thisObj = thisObj()
+                if isinstance(thisObj.autoDraw, (bool, int, float)):
+                    # Store whether this editable is on screen
+                    editablesOnScreen.append(thisObj.autoDraw)
+                else:
+                    editablesOnScreen.append(False)
                 if self._mouse.isPressedIn(thisObj):
+                    # If editable was clicked on, give it focus
                     self.currentEditable = thisObj
+            # If there is only one editable on screen, make sure it starts off with focus
+            if sum(editablesOnScreen) == 1:
+                self.currentEditable = self._editableChildren[editablesOnScreen.index(True)]
 
         flipThisFrame = self._startOfFlip()
         if self.useFBO and flipThisFrame:


Test patch:
Repository: psychopy/psychopy

Issue:
View ~> Open theme folder not working on macOS latest
No errors, just nothing happens


Discussion:

Resolving patch:
diff --git a/psychopy/app/themes/_themes.py b/psychopy/app/themes/_themes.py
--- a/psychopy/app/themes/_themes.py
+++ b/psychopy/app/themes/_themes.py
@@ -1053,7 +1053,15 @@ def __init__(self, frame):
         frame.Bind(wx.EVT_MENU, self.openThemeFolder, item)
 
     def openThemeFolder(self, event):
-        subprocess.call("explorer %(themes)s" % prefs.paths, shell=True)
+        # Choose a command according to OS
+        if sys.platform in ['win32']:
+            comm = "explorer"
+        elif sys.platform in ['darwin']:
+            comm = "open"
+        elif sys.platform in ['linux', 'linux2']:
+            comm = "dolphin"
+        # Use command to open themes folder
+        subprocess.call(f"{comm} {prefs.paths['themes']}", shell=True)
 
     def _applyAppTheme(self):
         for item in self.GetMenuItems():


Test patch: