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

Issue:
Can't open excel Forms template in macOS
On a mac, if I open a new Form Component and try to use ![image](https://user-images.githubusercontent.com/380582/108697703-19005e80-74fb-11eb-88bf-3a1c25f5f50a.png)

I get this error. I guess startfile is a windows thing

```
Traceback (most recent call last):
  File “/Applications/PsychoPy.app/Contents/Resources/lib/python3.6/psychopy/app/builder/dialogs/paramCtrls.py”, line 346, in openExcel
AttributeError: module ‘os’ has no attribute ‘startfile’
```


Discussion:

Resolving patch:
diff --git a/psychopy/app/builder/dialogs/paramCtrls.py b/psychopy/app/builder/dialogs/paramCtrls.py
--- a/psychopy/app/builder/dialogs/paramCtrls.py
+++ b/psychopy/app/builder/dialogs/paramCtrls.py
@@ -6,6 +6,9 @@
 # Distributed under the terms of the GNU General Public License (GPL).
 
 import os
+import subprocess
+import sys
+
 import wx
 
 from psychopy.app.colorpicker import PsychoColorPicker
@@ -334,18 +337,22 @@ def validate(self, evt=None):
     def openExcel(self, event):
         """Either open the specified excel sheet, or make a new one from a template"""
         file = self.rootDir / self.GetValue()
-        if file.is_file() and file.suffix in self.validExt:
-            os.startfile(file)
-        else:
+        if not (file.is_file() and file.suffix in self.validExt): # If not a valid file
             dlg = wx.MessageDialog(self, _translate(
                 f"Once you have created and saved your table, please remember to add it to {self.Name}"),
                              caption="Reminder")
             dlg.ShowModal()
             if hasattr(self.GetTopLevelParent(), 'type'):
                 if self.GetTopLevelParent().type in self.templates:
-                    os.startfile(self.templates[self.GetTopLevelParent().type])
-                    return
-            os.startfile(self.templates['None']) # Open blank template
+                    file = self.templates[self.GetTopLevelParent().type] # Open type specific template
+                else:
+                    file = self.templates['None'] # Open blank template
+        # Open whatever file is used
+        try:
+            os.startfile(file)
+        except AttributeError:
+            opener = "open" if sys.platform == "darwin" else "xdg-open"
+            subprocess.call([opener, file])
 
     def findFile(self, event):
         _wld = f"All Table Files({'*'+';*'.join(self.validExt)})|{'*'+';*'.join(self.validExt)}|All Files (*.*)|*.*"


Test patch:
Repository: psychopy/psychopy

Issue:
possible onKey exception in 2021.1.0
Based on this [discourse post](https://discourse.psychopy.org/t/importerror-sys-meta-path-is-none-python-is-likely-shutting-down/20641/4), user updated to 2021.1.0 and now gets this exception in the experiment:

```
File “/Applications/PsychoPy.app/Contents/Resources/lib/python3.6/pyglet/event.py”, line 415, in dispatch_event
if getattr(self, event_type)(*args):
File “/Applications/PsychoPy.app/Contents/Resources/lib/python3.6/psychopy/visual/backends/pygletbackend.py”, line 376, in onKey
thisKey = pyglet.window.key.symbol_string(evt).lower()
File “/Applications/PsychoPy.app/Contents/Resources/lib/python3.6/pyglet/window/key.py”, line 145, in symbol_string
if symbol < 1 << 32:
TypeError: ‘<’ not supported between instances of ‘NoneType’ and ‘int’
```

Asked for a copy of the experiment to see if it something specific to the project.

Looks like we should be checking that `evt` is not None in pygletbackend.onKey?



Discussion:

Resolving patch:
diff --git a/psychopy/visual/backends/pygletbackend.py b/psychopy/visual/backends/pygletbackend.py
--- a/psychopy/visual/backends/pygletbackend.py
+++ b/psychopy/visual/backends/pygletbackend.py
@@ -367,23 +367,24 @@ def dispatchEvents(self):
         :return:
         """
         wins = _default_display_.get_windows()
-
         for win in wins:
             win.dispatch_events()
 
     def onKey(self, evt, modifiers):
         "Check for tab key then pass all events to event package"
-        thisKey = pyglet.window.key.symbol_string(evt).lower()
-        if thisKey == 'tab':
-            self.onText('\t')
-        event._onPygletKey(evt, modifiers)
+        if evt is not None:
+            thisKey = pyglet.window.key.symbol_string(evt).lower()
+            if thisKey == 'tab':
+                self.onText('\t')
+            event._onPygletKey(evt, modifiers)
 
     def onText(self, evt):
         """Retrieve the character event(s?) for this window"""
-        currentEditable = self.win.currentEditable
-        if currentEditable:
-            currentEditable._onText(evt)
-        event._onPygletText(evt)  # duplicate the event to the psychopy.events lib
+        if evt is not None:
+            currentEditable = self.win.currentEditable
+            if currentEditable:
+                currentEditable._onText(evt)
+            event._onPygletText(evt)  # duplicate the event to the psychopy.events lib
 
     def onCursorKey(self, evt):
         """Processes the events from pyglet.window.on_text_motion


Test patch:
Repository: psychopy/psychopy

Issue:
AttributeError: 'list' object has no attribute 'contains' 
I know, that this error was discussed and closed already, but I can't solve it anyway. (@peircej)

> This error message came up during the workshop when a participant running PsychoPy 2021.1 tried to create a clickable button without using the button component (the old `method). (@mdcutone)

That's my error message:

`Traceback (most recent call last):
  File "C:\Users\Admin\Desktop\posner\test_lastrun.py", line 157, in <module>
    if obj.contains(mouse):
AttributeError: 'list' object has no attribute 'contains'
##### Experiment ended. #####`

In my case there is only one picture ("image") and one click ("mouse"), but the code still crushes right after first click at any part of  screen. I can't code at all and I dont know english good enough to search through pythons' forums so I'm asking for help. If it's possible, describe anything in easy words.

Thanks a lot. 


Discussion:

Resolving patch:
diff --git a/psychopy/experiment/components/mouse/__init__.py b/psychopy/experiment/components/mouse/__init__.py
--- a/psychopy/experiment/components/mouse/__init__.py
+++ b/psychopy/experiment/components/mouse/__init__.py
@@ -134,7 +134,7 @@ def _writeClickableObjectsCode(self, buff):
         code = (
             "# check if the mouse was inside our 'clickable' objects\n"
             "gotValidClick = False\n"
-            "for obj in [%(clickable)s]:\n"
+            "for obj in %(clickable)s:\n"
             "    if obj.contains(%(name)s):\n"
             "        gotValidClick = True\n")
         buff.writeIndentedLines(code % self.params)


Test patch:
Repository: psychopy/psychopy

Issue:
PsychoPy builder: scrolling right in the flow panel displaces context menu
Hey!

I'm using Windows 10, PsychoPy 2021.1.2. If I scroll to the right in the flow panel, then right click a loop or routine, the context menu appears shifted to the right. It seems that the amount the context menu moved to the right is about the same amount that I scrolled to the flow panel to the right. In the screenshot below, I right-clicked the "drawing" routine.

![image](https://user-images.githubusercontent.com/8987504/109798740-0b418c00-7c13-11eb-8281-6720e54c465f.png)



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
@@ -3015,8 +3015,8 @@ def OnMouse(self, event):
                 self.frame.routinePanel.setCurrentRoutine(comp)
                 try:
                     self._menuComponentID = icon
-                    xy = wx.Point(x + self.GetPosition()[0],
-                                  y + self.GetPosition()[1])
+                    xy = wx.Point(event.X + self.GetPosition()[0],
+                                  event.Y + self.GetPosition()[1])
                     self.showContextMenu(self._menuComponentID, xy=xy)
                 except UnboundLocalError:
                     # right click but not on an icon


Test patch:
Repository: psychopy/psychopy

Issue:
Unhandled internal error when checking for PsychoPy updates fails
If checking for PsychoPy updates fails, using the `Tools -> PsychoPy updates...` menu item, then there is an unhandled internal error because the `InstallUpdateDialog.latest` attribute is -1, and not a dictionary of version keys.
```
Traceback (most recent call last):
  File “/Applications/PsychoPy.app/Contents/Resources/lib/python3.6/psychopy/app/_psychopyApp.py”, line 640, in openUpdater
  File “/Applications/PsychoPy.app/Contents/Resources/lib/python3.6/psychopy/app/connections/updates.py”, line 327, in __init__
  File “/Applications/PsychoPy.app/Contents/Resources/lib/python3.6/psychopy/app/connections/updates.py”, line 364, in updateStatus
TypeError: ‘int’ object is not subscriptable
```


Discussion:

Resolving patch:
diff --git a/psychopy/app/connections/updates.py b/psychopy/app/connections/updates.py
--- a/psychopy/app/connections/updates.py
+++ b/psychopy/app/connections/updates.py
@@ -332,11 +332,14 @@ def updateStatus(self):
         """Check the current version and most recent version and update ctrls
         """
         if self.latest == -1:
+            # Set message and display, and return early if version could not be found
             msg = _translate(
                 "You are running PsychoPy v%s.\n ") % self.runningVersion
             msg += _translate("PsychoPy could not connect to the \n internet"
                               " to check for more recent versions.\n")
             msg += _translate("Check proxy settings in preferences.")
+            self.statusMessage.SetLabel(msg)
+            return
         elif (parse_version(self.latest['version'])
                   < parse_version(self.runningVersion)):
             msg = _translate(


Test patch:
Repository: psychopy/psychopy

Issue:
Duration field needs a "$" sign in new release
Previously it was necessary for users to add a $ sign at the start of the duration field to use custom code in that field, but in 2021.1.3 and 2021.1.4 this will throw an error. Need to add a $sign to the parameter fieldname in the dialog box.


Discussion:
@TEParsons maybe this is another case where the code has moved incorrectly to number and should be code (or similar)?
Spot on, yes, it needs changing back to `valType="code"`. Putting in a pull request now :) 

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
@@ -78,12 +78,12 @@ def __init__(self, exp, parentName, name='',
             label=_localized['stopType'])
 
         self.params['startVal'] = Param(startVal,
-            valType='num', inputType="single", categ='Basic',
+            valType='code', inputType="single", categ='Basic',
             hint=_translate("When does the component start?"), allowedTypes=[],
             label=_localized['startVal'])
 
         self.params['stopVal'] = Param(stopVal,
-            valType='num', inputType="single", categ='Basic',
+            valType='code', inputType="single", categ='Basic',
             updates='constant', allowedUpdates=[], allowedTypes=[],
             hint=_translate("When does the component end? (blank is endless)"),
             label=_localized['stopVal'])
@@ -91,14 +91,14 @@ def __init__(self, exp, parentName, name='',
         msg = _translate("(Optional) expected start (s), purely for "
                          "representing in the timeline")
         self.params['startEstim'] = Param(startEstim,
-            valType='num', inputType="single", categ='Basic',
+            valType='code', inputType="single", categ='Basic',
             hint=msg,allowedTypes=[],
             label=_localized['startEstim'])
 
         msg = _translate("(Optional) expected duration (s), purely for "
                          "representing in the timeline")
         self.params['durationEstim'] = Param(durationEstim,
-            valType='num', inputType="single", categ='Basic',
+            valType='code', inputType="single", categ='Basic',
             hint=msg, allowedTypes=[],
             label=_localized['durationEstim'])
 


Test patch:
Repository: psychopy/psychopy

Issue:
URLs in README files won't open
[This experiment](https://gitlab.pavlovia.org/tpronk/cep_2021_april7-9_assignment_stroop/) has a README file that displays upon opening the psyexp file via builder. There are a couple of URLs in there, pointing to gitlab repos. While the URLs are valid, when I click them, PsychoPy gives an error message. For example:

PsychoPy3 Error

Unable to open requested HTML document:
https://gitlab.pavlovia.org/tpronk/tutorial_js_syntax_error



Discussion:
I noticed that anchors to another location within a page also don't work. For example, in the README of the project below, I link to a section titled "prolific" as follows:
`[Prolific](#prolific)`
Clicking this link in gitlab takes me to the right sections, but in Builder I get "HTML anchor prolific does not exist"
https://gitlab.pavlovia.org/tpronk/demo_chaining



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
@@ -2436,6 +2436,10 @@ def __init__(self, parent):
         self.makeMenus()
         self.rawText = ""
         self.ctrl = HtmlWindow(self, wx.ID_ANY)
+        self.ctrl.Bind(wx.html.EVT_HTML_LINK_CLICKED, self.onUrl)
+
+    def onUrl(self, evt=None):
+        webbrowser.open(evt.LinkInfo.Href)
 
     def onClose(self, evt=None):
         """


Test patch:
Repository: psychopy/psychopy

Issue:
Feature request: Report the component name and routine of disabled components in Alert 4305
PsychoPy reports [an alert](https://psychopy.org/alerts/4305.html) when a component in the experiment is disabled. However, this alert doesn't tell you what component is disabled. It can be quite difficult to find the disabled component, aside from going through and manually checking every component. It would be a useful feature if this alert also included the name and routine of the disable component.


Discussion:

Resolving patch:
diff --git a/psychopy/alerts/alerttools.py b/psychopy/alerts/alerttools.py
--- a/psychopy/alerts/alerttools.py
+++ b/psychopy/alerts/alerttools.py
@@ -260,7 +260,7 @@ def testDisabled(component):
         return
 
     if component.params['disabled'].val:
-        alert(4305, component)
+        alert(4305, component, strFields={'name': component.params['name']})
 
 def testFont(component):
     """


Test patch:
diff --git a/psychopy/tests/test_alerts/test_alerttools.py b/psychopy/tests/test_alerts/test_alerttools.py
--- a/psychopy/tests/test_alerts/test_alerttools.py
+++ b/psychopy/tests/test_alerts/test_alerttools.py
@@ -78,7 +78,7 @@ def test_timing(self):
     def test_disabled(self):
         self.polygonComp.params['disabled'].val = True
         alerttools.testDisabled(self.polygonComp)
-        assert ('Your component is currently disabled' in self.error.alerts[0].msg)
+        assert (f"The component {self.polygonComp.params['name']} is currently disabled" in self.error.alerts[0].msg)
 
     def test_achievable_visual_stim_onset(self):
         self.polygonComp.params['startVal'].val = .001
Repository: psychopy/psychopy

Issue:
Image component: selecting Image via file picker doesn't translate well to PsychoJS
On my Windows 10 device, I selected an image via the file picker, and so the path `img\request_landscape.png` ended up in the Image field. In the generated JS, two different things happened with the backslash in this path:
- In `psychoJS.start`, as a resource the backslash got converted to a slash (`img/request_landscape.png`), so the resource got correctly downloaded
- However, in the `image` property of the `visual.ImageStim`, the backslash got converted into two backslashes instead of a slash (`img\\\\request_landscape.png`), so the experiment could not find the resource


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
@@ -24,6 +24,7 @@
 from builtins import object
 
 import re
+from pathlib import Path
 
 from psychopy import logging
 from . import utils
@@ -206,8 +207,8 @@ def __str__(self):
                             # but for other targets that will raise an annoying error
                             val = val[1:]
                     if self.valType in ['file', 'table']:
-                        # If param is a file of any kind, escape any \
-                        val = re.sub(r"\\", r"\\\\", val)
+                        # If param is a file of any kind, use Path to make sure it's valid
+                        val = str(Path(val))
                     val=re.sub("\n", "\\n", val) # Replace line breaks with escaped line break character
                     return repr(val)
             return repr(self.val)


Test patch:
Repository: psychopy/psychopy

Issue:
Textbox stretches out text in `norm` units
I you set the units of a Textbox to be `norm`, then the font is stretched out - haven't measured but I'd wager the amount it's stretched by is just the proportion of height/width of the screen.


Discussion:

Resolving patch:
diff --git a/psychopy/visual/textbox2/textbox2.py b/psychopy/visual/textbox2/textbox2.py
--- a/psychopy/visual/textbox2/textbox2.py
+++ b/psychopy/visual/textbox2/textbox2.py
@@ -137,9 +137,6 @@ def __init__(self, win, text, font,
         ColorMixin.foreColor.fset(self, color)  # Have to call the superclass directly on init as text has not been set
         self.onTextCallback = onTextCallback
 
-        if units=='norm':
-            raise NotImplementedError("TextBox2 doesn't support 'norm' units "
-                                 "at the moment. Use 'height' units instead")
         # first set params needed to create font (letter sizes etc)
         if letterHeight is None:
             self.letterHeight = defaultLetterHeight[self.units]
@@ -507,6 +504,13 @@ def getLineWidthFromPix(pixVal):
                     xBotR = xBotL + glyph.size[0] * alphaCorrection + fakeBold
                     xTopR = xTopL + glyph.size[0] * alphaCorrection + fakeBold
                     yBot = yTop - glyph.size[1]
+                    # Adjust for norm
+                    if self.units == 'norm':
+                        ratio = self.win.size[1]/self.win.size[0]
+                        xBotL *= ratio
+                        xTopL *= ratio
+                        xBotR *= ratio
+                        xTopR *= ratio
                     u0 = glyph.texcoords[0]
                     v0 = glyph.texcoords[1]
                     u1 = glyph.texcoords[2]


Test patch:
Repository: psychopy/psychopy

Issue:
BUG: Need tweak JS / CSS imports for next release



Discussion:

Resolving patch:
diff --git a/psychopy/experiment/components/settings/__init__.py b/psychopy/experiment/components/settings/__init__.py
--- a/psychopy/experiment/components/settings/__init__.py
+++ b/psychopy/experiment/components/settings/__init__.py
@@ -790,8 +790,8 @@ def writeInitCodeJS(self, buff, version, localDateTime, modular=True):
         # Write imports if modular
         if modular:
             code = (
-                    "import {{ core, data, sound, util, visual }} from './psycho-2021.2.0.js';\n"
-                    "const {{ PsychoJS }} = core;"
+                    "import {{ core, data, sound, util, visual }} from './lib/psychojs-2021.2.0.js';\n"
+                    "const {{ PsychoJS }} = core;\n"
                     "const {{ TrialHandler }} = data;\n"
                     "const {{ Scheduler }} = util;\n"
                     "//some handy aliases as in the psychopy scripts;\n"


Test patch:
Repository: psychopy/psychopy

Issue:
TextBox: Text in text field not presented if "set every repeat" 
If the text field of textbox contains placeholder text e.g. "type here" and that field is set to "set every repeat" the text in that field is not presented at the star of each trial. This differs from textbox's current functionality whereby that text is presented at the start of each trial, but can be deleted/edited. 

Minimal demo: https://pavlovia.org/lpxrh6/textbox_bug_placeholder_txt 


Discussion:

Resolving patch:
diff --git a/psychopy/experiment/components/roi/__init__.py b/psychopy/experiment/components/roi/__init__.py
--- a/psychopy/experiment/components/roi/__init__.py
+++ b/psychopy/experiment/components/roi/__init__.py
@@ -141,6 +141,9 @@ def writeInitCode(self, buff):
         buff.writeIndentedLines(code % inits)
         buff.setIndentLevel(-1, relative=True)
 
+    def writeInitCodeJS(self, buff):
+        pass
+
     def writeRoutineStartCode(self, buff):
         inits = getInitVals(self.params, 'PsychoPy')
         BaseVisualComponent.writeRoutineStartCode(self, buff)
@@ -237,7 +240,7 @@ def writeFrameCode(self, buff):
         buff.writeIndentedLines(code % inits)
         if self.params['endRoutineOn'].val == "look away":
             code = (
-                "if %(name)s.currentLookTime > %(lookDur)s/1000: # check if last look was long enough\n"
+                "if %(name)s.lastLookTime > %(lookDur)s/1000: # check if last look was long enough\n"
             )
             buff.writeIndentedLines(code % inits)
             buff.setIndentLevel(1, relative=True)
diff --git a/psychopy/experiment/components/textbox/__init__.py b/psychopy/experiment/components/textbox/__init__.py
--- a/psychopy/experiment/components/textbox/__init__.py
+++ b/psychopy/experiment/components/textbox/__init__.py
@@ -254,6 +254,7 @@ def writeRoutineStartCode(self, buff):
             "%(name)s.reset()"
         )
         buff.writeIndentedLines(code % self.params)
+        BaseVisualComponent.writeRoutineStartCode(self, buff)
 
     def writeRoutineStartCodeJS(self, buff):
         BaseVisualComponent.writeRoutineStartCode(self, buff)
diff --git a/psychopy/visual/roi.py b/psychopy/visual/roi.py
--- a/psychopy/visual/roi.py
+++ b/psychopy/visual/roi.py
@@ -108,6 +108,21 @@ def currentLookTime(self):
             # If not looked at, look time is 0
             return 0
 
+    @property
+    def lastLookTime(self):
+        if self.timesOn and self.timesOff and not self.isLookedIn:
+            # If not looked at, subtract most recent time from last time on
+            return self.timesOff[-1] - self.timesOn[-1]
+        elif len(self.timesOn) > 1 and len(self.timesOff) > 1:
+            # If looked at, return previous look time
+            return self.timesOff[-2] - self.timesOn[-2]
+        else:
+            # Otherwise, assume 0
+            return 0
+
+
+
+
     def reset(self):
         """Clear stored data"""
         self.timesOn = []


Test patch: