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

Issue:
Werkzeug built-in redirect for double slashes not working as expected (`/app//note`)
Small issue, but `raise RequestRedirect` is not caught, thus it becomes a **500** error :smile: 

```
Traceback (most recent call last):
  File "apps/frappe/frappe/website/serve.py", line 19, in get_response
    endpoint, renderer_instance = path_resolver.resolve()
                                  ^^^^^^^^^^^^^^^^^^^^^^^
  File "apps/frappe/frappe/website/path_resolver.py", line 45, in resolve
    endpoint = resolve_path(self.path)
               ^^^^^^^^^^^^^^^^^^^^^^^
  File "apps/frappe/frappe/website/path_resolver.py", line 162, in resolve_path
    path = resolve_from_map(path)
           ^^^^^^^^^^^^^^^^^^^^^^
  File "apps/frappe/frappe/website/path_resolver.py", line 173, in resolve_from_map
    return evaluate_dynamic_routes(rules, path) or path
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "apps/frappe/frappe/website/router.py", line 72, in evaluate_dynamic_routes
    endpoint, args = urls.match("/" + path)
                     ^^^^^^^^^^^^^^^^^^^^^^
  File "env/lib/python3.11/site-packages/werkzeug/routing/map.py", line 611, in match
    raise RequestRedirect(
werkzeug.routing.exceptions.RequestRedirect: 308 Permanent Redirect: http://localhost:8000/app/notification-log
```

See screenshot below (sorry it's in French).
![screenshot](https://github.com/frappe/frappe/assets/10946971/65d5af28-75b2-4837-8bd5-0333014f7f1d)



Discussion:

Resolving patch:
diff --git a/frappe/website/path_resolver.py b/frappe/website/path_resolver.py
--- a/frappe/website/path_resolver.py
+++ b/frappe/website/path_resolver.py
@@ -1,6 +1,7 @@
 import re
 
 import click
+import werkzeug.routing.exceptions
 from werkzeug.routing import Rule
 
 import frappe
@@ -42,7 +43,11 @@ def resolve(self):
 			for handler in frappe.get_hooks("website_path_resolver"):
 				endpoint = frappe.get_attr(handler)(self.path)
 		else:
-			endpoint = resolve_path(self.path)
+			try:
+				endpoint = resolve_path(self.path)
+			except werkzeug.routing.exceptions.RequestRedirect as e:
+				frappe.flags.redirect_location = e.new_url
+				return frappe.flags.redirect_location, RedirectPage(e.new_url, e.code)
 
 		# WARN: Hardcoded for better performance
 		if endpoint == "app":
diff --git a/frappe/website/router.py b/frappe/website/router.py
--- a/frappe/website/router.py
+++ b/frappe/website/router.py
@@ -1,7 +1,6 @@
 # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
 # License: MIT. See LICENSE
 
-import io
 import os
 import re
 
@@ -69,12 +68,10 @@ def evaluate_dynamic_routes(rules, path):
 		urls = route_map.bind_to_environ(frappe.local.request.environ)
 		try:
 			endpoint, args = urls.match("/" + path)
-			path = endpoint
 			if args:
 				# don't cache when there's a query string!
 				frappe.local.no_cache = 1
 				frappe.local.form_dict.update(args)
-
 		except NotFound:
 			pass
 


Test patch:
Repository: frappe/frappe

Issue:
(List View): In sidebar filter link field show Title of Field if set
**Is your feature request related to a problem? Please describe.**
In sidebar filter link field show field.name but not field.title

**Describe the solution you'd like**
if link field has title field - show title.
![image](https://github.com/frappe/frappe/assets/4525776/843f4b1c-daaf-4de9-958f-33dc57137c95)


Discussion:

Resolving patch:
diff --git a/frappe/desk/listview.py b/frappe/desk/listview.py
--- a/frappe/desk/listview.py
+++ b/frappe/desk/listview.py
@@ -60,10 +60,12 @@ def get_group_by_count(doctype: str, current_filters: str, field: str) -> list[d
 			.run(as_dict=True)
 		)
 
-	if not frappe.get_meta(doctype).has_field(field) and not is_default_field(field):
+	meta = frappe.get_meta(doctype)
+
+	if not meta.has_field(field) and not is_default_field(field):
 		raise ValueError("Field does not belong to doctype")
 
-	return frappe.get_list(
+	data = frappe.get_list(
 		doctype,
 		filters=current_filters,
 		group_by=f"`tab{doctype}`.{field}",
@@ -71,3 +73,13 @@ def get_group_by_count(doctype: str, current_filters: str, field: str) -> list[d
 		order_by="count desc",
 		limit=50,
 	)
+
+	# Add in title if it's a link field and `show_title_field_in_link` is set
+	if (field_meta := meta.get_field(field)) and field_meta.fieldtype == "Link":
+		link_meta = frappe.get_meta(field_meta.options)
+		if link_meta.show_title_field_in_link:
+			title_field = link_meta.get_title_field()
+			for item in data:
+				item.title = frappe.get_value(field_meta.options, item.name, title_field)
+
+	return data


Test patch:
Repository: apache/tvm

Issue:
[TEST][FLAKY] test_dlpack
Both #2749 and #2353 encountered seg fault error at test_dlpack.
http://ci.tvm.ai:8080/blue/organizations/jenkins/tvm/detail/PR-2749/2/pipeline
http://ci.tvm.ai:8080/blue/organizations/jenkins/tvm/detail/PR-2353/48/pipeline

cc @eqy , could you help look at this?


Discussion:
I will see if I can repro, otherwise we can thinking about disabling this test for now as it is not a critical part of the infrastructure.
@icemelon9 I am not able to reproduce the exact segfault on my machine, but I do see some tolerance errors (maybe every few hundred invocations). Bumping `rtol` down to `1e-5` seems to be enough on my end---should we submit a PR for that in the meantime?

Resolving patch:
diff --git a/python/tvm/_ffi/_ctypes/ndarray.py b/python/tvm/_ffi/_ctypes/ndarray.py
--- a/python/tvm/_ffi/_ctypes/ndarray.py
+++ b/python/tvm/_ffi/_ctypes/ndarray.py
@@ -24,6 +24,8 @@ def _from_dlpack(dltensor):
     dltensor = ctypes.py_object(dltensor)
     if ctypes.pythonapi.PyCapsule_IsValid(dltensor, _c_str_dltensor):
         ptr = ctypes.pythonapi.PyCapsule_GetPointer(dltensor, _c_str_dltensor)
+        # enforce type to make sure it works for all ctypes
+        ptr = ctypes.cast(ptr, ctypes.c_void_p)
         handle = TVMArrayHandle()
         check_call(_LIB.TVMArrayFromDLPack(ptr, ctypes.byref(handle)))
         ctypes.pythonapi.PyCapsule_SetName(dltensor, _c_str_used_dltensor)
@@ -36,6 +38,8 @@ def _dlpack_deleter(pycapsule):
     pycapsule = ctypes.cast(pycapsule, ctypes.py_object)
     if ctypes.pythonapi.PyCapsule_IsValid(pycapsule, _c_str_dltensor):
         ptr = ctypes.pythonapi.PyCapsule_GetPointer(pycapsule, _c_str_dltensor)
+        # enforce type to make sure it works for all ctypes
+        ptr = ctypes.cast(ctypes.c_void_p, ptr)
         _LIB.TVMDLManagedTensorCallDeleter(ptr)
         ctypes.pythonapi.PyCapsule_SetDestructor(dltensor, TVMPyCapsuleDestructor(0))
 


Test patch:
Repository: apache/tvm

Issue:
Operator Greater not implemented.
I successfully convert the pytorch model to the onnx. The converted model cannot be loaded in tvm (0.6_dev0), because the greater operator is not implemented. The greater operator is supported in the tvm relay. Any suggestion? 


Discussion:
It is probably a single missing line in the ONNX conversion code. cc @zhreshold 
If you are interested in contributing you just need to provide a converter here: https://github.com/dmlc/tvm/blob/master/python/tvm/relay/frontend/onnx.py#L781. 
listDiff operator in https://github.com/dmlc/tvm/tree/master/python/tvm/relay/frontend/tensorflow.py not implemented too.

Resolving patch:
diff --git a/python/tvm/relay/frontend/onnx.py b/python/tvm/relay/frontend/onnx.py
--- a/python/tvm/relay/frontend/onnx.py
+++ b/python/tvm/relay/frontend/onnx.py
@@ -605,6 +605,23 @@ def _impl_v1(cls, inputs, attr, params):
                        extras={'axis':axis})(inputs, {})
         #return _op.take(inputs[0], inputs[1], axis)
 
+
+class Greater(OnnxOpConverter):
+    """ Operator logical greater.
+    """
+    @classmethod
+    def _impl_v7(cls, inputs, attr, params):
+        return _op.greater(inputs[0], inputs[1])
+
+
+class Less(OnnxOpConverter):
+    """ Operator logical less than.
+    """
+    @classmethod
+    def _impl_v7(cls, inputs, attr, params):
+        return _op.less(inputs[0], inputs[1])
+
+
 class LRN(OnnxOpConverter):
     """ Operator converter for Local Response Normalization.
     """
@@ -819,6 +836,8 @@ def _get_convert_map(opset):
         'Selu': Selu.get_converter(opset),
         'Elu': Elu.get_converter(opset),
         'Exp': Renamer('exp'),
+        'Greater': Greater.get_converter(opset),
+        'Less': Less.get_converter(opset),
         'Log': Renamer('log'),
         'Tanh': Renamer('tanh'),
         'Pow': Renamer('power'),


Test patch:
diff --git a/tests/python/frontend/onnx/test_forward.py b/tests/python/frontend/onnx/test_forward.py
--- a/tests/python/frontend/onnx/test_forward.py
+++ b/tests/python/frontend/onnx/test_forward.py
@@ -932,6 +932,8 @@ def verify_binary_ops(op, x, y, out_np, broadcast=None):
     verify_binary_ops("Div", x, y, x / y, broadcast=None)
     verify_binary_ops("Div", x, z, x / z, broadcast=True)
     verify_binary_ops("Sum", x, y, x + y, broadcast=None)
+    verify_binary_ops("Greater", x, y, x > y, broadcast=True)
+    verify_binary_ops("Less", x, y, x < y, broadcast=True)
 
 def test_single_ops():
     in_shape = (1, 2, 3, 3)
Repository: apache/tvm

Issue:
OpenCL grouped convolutions "did you forget to bind"
It's possible that this is a usage question rather than a bug.

However, I have been trying to run grouped convolutions on OpenCL devices, using models imported from ONNX.

OpenCL models work when the number of `groups==1`, and when `groups==input_channels`, but get errors like `Direct host side access to device memory is detected in fused_nn_conv2d_9` for other values of groups.  

Interestingly, varying the optimisation level changes the error message slightly, but does not fix results.

[I have an MWE gist notebook that shows the problem here](https://gist.github.com/Wheest/abd48c08e7b0fef70f24c0a5b7c1c666).

Prior issues with grouped convolutions were dealt with in [#3070](https://github.com/dmlc/tvm/pull/3070).

Perhaps grouped convolutions in OpenCL require a specific data layout?  However I'm unsure how I would specify this for imported ONNX models.




Discussion:
group conv2d is not fully supported, we don't have schedule on CUDA/OpenCL. Currently only int8 group conv2d on CUDA is supported.
@vinx13 can we add a more specific exception for other cases for now?

Resolving patch:
diff --git a/topi/python/topi/cuda/group_conv2d_nchw.py b/topi/python/topi/cuda/group_conv2d_nchw.py
--- a/topi/python/topi/cuda/group_conv2d_nchw.py
+++ b/topi/python/topi/cuda/group_conv2d_nchw.py
@@ -346,6 +346,8 @@ def schedule_conv2d_nchw_cuda(cfg, outs):
     def _callback(op):
         if op.tag == "group_conv2d_NCHWc_int8":
             schedule_group_conv2d_NCHWc_int8(cfg, s, op.output(0))
+        if op.tag == "group_conv2d_nchw":
+            raise tvm.error.OpNotImplemented("group_conv2d_nchw not supported")
 
     traverse_inline(s, outs[0].op, _callback)
     return s


Test patch:
Repository: apache/tvm

Issue:
[potential bug?] SimulatedAnnealingOptimizer will find useless candidate?
When I read the code of  SimulatedAnnealingOptimize, I find the method `find_maximums` is implemented by heap, and insert some dummy elements first as following:
https://github.com/dmlc/tvm/blob/c0afc91884c1e664e19ab10f5f4898425975a756/python/tvm/autotvm/tuner/sa_model_optimizer.py#L78

But, in the code, there is no guarantee that the output list contains no dummy elements, so will it be a bug when we nearly run out the configs and can't find new points during the loop?


Discussion:
Please open a new thread on https://discuss.tvm.ai/ for general discussions :)
Good catch. Are you interested in sending a patch?
@merrymercy this problem should be at least partially covered by this heuristic right
https://github.com/dmlc/tvm/blob/4767554c580f5aa0521727629e51f04f5315f025/python/tvm/autotvm/tuner/model_based_tuner.py#L238
But it is still a bug in `find_maximums`..

Resolving patch:
diff --git a/python/tvm/autotvm/tuner/sa_model_optimizer.py b/python/tvm/autotvm/tuner/sa_model_optimizer.py
--- a/python/tvm/autotvm/tuner/sa_model_optimizer.py
+++ b/python/tvm/autotvm/tuner/sa_model_optimizer.py
@@ -75,10 +75,10 @@ def find_maximums(self, model, num, exclusive):
         scores = model.predict(points)
 
         # build heap and insert initial points
-        heap_items = [(float('-inf'), -i) for i in range(num)]
+        heap_items = [(float('-inf'), - 1 - i) for i in range(num)]
         heapq.heapify(heap_items)
         in_heap = set(exclusive)
-        in_heap.update([-i for i in range(num)])
+        in_heap.update([x for x in heap_items])
 
         for s, p in zip(scores, points):
             if s > heap_items[0][0] and p not in in_heap:
@@ -128,6 +128,7 @@ def find_maximums(self, model, num, exclusive):
                              time.time() - tic)
 
         heap_items.sort(key=lambda item: -item[0])
+        heap_items = [x for x in heap_items if x >= 0]
         logger.debug("SA iter: %d\tlast_update: %d\tmax-0: %.2f\tmax-1: %.2f\telapsed: %.2f",
                      k, k_last_modify, heap_items[-1][0], heap_items[0][0], time.time() - tic)
         logger.debug("SA Maximums: %s", heap_items)


Test patch:
Repository: apache/tvm

Issue:
[Bug][AutoTVM] Bug introduced by #3413
After #3413, elements in `in_heap` are tuples, no longer values. However, the subsequent code still pops value from `in_heap`, which causes key not found error.
https://github.com/dmlc/tvm/pull/3413/files#diff-1b305247d46fd804148ffbe2ceb5eb04R86.

Similarly, in the following code, `x` is also a tuple, cannot directly compare with 0. I'm not sure whether we should use `x[0]` or` x[1]` in this case.
https://github.com/dmlc/tvm/pull/3413/files#diff-1b305247d46fd804148ffbe2ceb5eb04R131

@merrymercy Could you take a look at this issue?


Discussion:

Resolving patch:
diff --git a/python/tvm/autotvm/tuner/sa_model_optimizer.py b/python/tvm/autotvm/tuner/sa_model_optimizer.py
--- a/python/tvm/autotvm/tuner/sa_model_optimizer.py
+++ b/python/tvm/autotvm/tuner/sa_model_optimizer.py
@@ -78,7 +78,7 @@ def find_maximums(self, model, num, exclusive):
         heap_items = [(float('-inf'), - 1 - i) for i in range(num)]
         heapq.heapify(heap_items)
         in_heap = set(exclusive)
-        in_heap.update([x for x in heap_items])
+        in_heap.update([x[1] for x in heap_items])
 
         for s, p in zip(scores, points):
             if s > heap_items[0][0] and p not in in_heap:
@@ -128,9 +128,9 @@ def find_maximums(self, model, num, exclusive):
                              time.time() - tic)
 
         heap_items.sort(key=lambda item: -item[0])
-        heap_items = [x for x in heap_items if x >= 0]
-        logger.debug("SA iter: %d\tlast_update: %d\tmax-0: %.2f\tmax-1: %.2f\telapsed: %.2f",
-                     k, k_last_modify, heap_items[-1][0], heap_items[0][0], time.time() - tic)
+        heap_items = [x for x in heap_items if x[0] >= 0]
+        logger.debug("SA iter: %d\tlast_update: %d\telapsed: %.2f",
+                     k, k_last_modify, time.time() - tic)
         logger.debug("SA Maximums: %s", heap_items)
 
         if self.persistent:


Test patch:
Repository: apache/tvm

Issue:
docker/build.sh demo_android -it bash fails
https://github.com/dmlc/tvm/blob/9e4f07b4695a8849590cdd46de662e3fa273d59b/docker/Dockerfile.demo_android#L70

Command fails with errors like:
```
CMake Error at cmake/util/FindLLVM.cmake:76 (string):
  string sub-command STRIP requires two arguments.
Call Stack (most recent call first):
  cmake/modules/LLVM.cmake:22 (find_llvm)
  CMakeLists.txt:240 (include)
```
And more generally it's hard to follow the tutorial to optimize for Android.
- On my Ubuntu 19.04 Java 11 is installed by default with which sources are not compatible
- docker/bash.sh tvmai/demo-android fails
- building image fails

So the only way to run the tutorial is to prepare custom docker image where all needed resources will be avilable


Discussion:
@junrushao1994 can you look into this? is it related to your recent change
The recent change is simply a single liner “separate_argument(LLVM_CONFIG)”
though...I will take a look!

On Mon, Sep 16, 2019 at 10:16 Tianqi Chen <notifications@github.com> wrote:

> @junrushao1994 <https://github.com/junrushao1994> can you look into this?
> is it related to your recent change
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/dmlc/tvm/issues/3958?email_source=notifications&email_token=AFLZBJJDKBEWOE6IBGN7HLDQJ65N5A5CNFSM4IXARMU2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD6Z3RRY#issuecomment-531871943>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/AFLZBJPP3S7YUA3P6TT3XL3QJ65N5ANCNFSM4IXARMUQ>
> .
>

@tqchen @herbakamil I looked into the docker container, but found that there is no llvm-config-6.0 at all...

I can confirm that build succeeded when Dockerfile uses llvm-config-8 instead.
Hmm, perhaps two take aways, we should fix the docker file, and ideally we should have nicer error messages when we cannot find llvm-config. @junrushao1994 can you help on that?
Thanks for looking into the problem!

Resolving patch:
diff --git a/tutorials/frontend/deploy_model_on_android.py b/tutorials/frontend/deploy_model_on_android.py
--- a/tutorials/frontend/deploy_model_on_android.py
+++ b/tutorials/frontend/deploy_model_on_android.py
@@ -66,7 +66,7 @@
 #
 #   mkdir build
 #   cd build
-#   cmake -DUSE_LLVM=llvm-config-6.0 \
+#   cmake -DUSE_LLVM=llvm-config-8 \
 #         -DUSE_RPC=ON \
 #         -DUSE_SORT=ON \
 #         -DUSE_VULKAN=ON \


Test patch:
Repository: apache/tvm

Issue:
 [BUG][TUTORIAL] Tutorial for quantization need update
Dear community,
I've noticed that the [stock tutorial for quantization](https://github.com/apache/incubator-tvm/blob/master/tutorials/frontend/deploy_quantized.py) fails if the following call is changed from local scales to global scales:

```
...
mod = quantize(mod, params, data_aware=True) # -> fails with data_aware=False 
...

ValueError: Unknown calibrate mode global
```

The fix is straight forward:

```
-         with relay.quantize.qconfig(calibrate_mode='global', global_scale=8.0):
---
+        with relay.quantize.qconfig(calibrate_mode='global_scale', global_scale=8.0):
```

I would like to kindly ask @vinx13 to update the tutorial. Thank you very much in advance & best regards!



Discussion:
feel free to send a PR to fix this
@tqchen I'm extremely ashamed to say this, but due to company policy I'm not allowed to contribute to anything other than company code bases. Especially shameful since it's only 1 string change... :( I'm really sorry.

Resolving patch:
diff --git a/tutorials/frontend/deploy_quantized.py b/tutorials/frontend/deploy_quantized.py
--- a/tutorials/frontend/deploy_quantized.py
+++ b/tutorials/frontend/deploy_quantized.py
@@ -132,7 +132,7 @@ def quantize(mod, params, data_aware):
         with relay.quantize.qconfig(calibrate_mode='kl_divergence', weight_scale='max'):
             mod = relay.quantize.quantize(mod, params, dataset=calibrate_dataset())
     else:
-        with relay.quantize.qconfig(calibrate_mode='global', global_scale=8.0):
+        with relay.quantize.qconfig(calibrate_mode='global_scale', global_scale=8.0):
             mod = relay.quantize.quantize(mod, params)
     return mod
 


Test patch:
Repository: apache/tvm

Issue:
[BACKPORT-0.6][BUGFIX] Fixed process termination routine in windows
#4844



Discussion:

Resolving patch:
diff --git a/python/tvm/rpc/server.py b/python/tvm/rpc/server.py
--- a/python/tvm/rpc/server.py
+++ b/python/tvm/rpc/server.py
@@ -39,6 +39,7 @@
 import time
 import sys
 import signal
+import platform
 
 from .._ffi.function import register_func
 from .._ffi.base import py_str


Test patch:
Repository: apache/tvm

Issue:
Some Windows and MSVC fixes
ref: https://github.com/apache/incubator-tvm/issues/4529


Discussion:
looks like VS2019 output utf-8 now...XD
But old versions should still use local encoding.

For windows `__FILE__` macro, full path is always used, it is safe to hardcoded here.
Can we run a test and set the function once for all? instead of doing the try catch inside every py_str call(which will be slow)?
I think we should keep it since it is not perforamce critical and different programs might use different encoding on windows.
Sorry I wasn't being clear, I agree that it is important to keep it, however, it might be better to implement it as follows(so condition is only executed once), I don't know if it is possible though

```python
if test_encode_utf8():
    py_str = lambda x: x.decode("utf-8")
else:
    py_str = lambda x: x.decode(oldencoding)

```
I assume that everytime the byte array we feed `py_str` comes from different program, which might have different encoding.

The most common encoding just happend to be `utf-8` and defalut local system encoding.

For an uncommon situation, a program compiled under Japanese Windows and being executed on Chinese Windows might not display correctly, if it uses non-ascii (e.g. Chinese or Japanese) character. 
In addition, for this case, the codec retrieved from `GetACP()`, which is  Chinese default encoding ( or `GBK`) cannot decode the string (encoded by `Shift-JIS`) either. The only thing we can do is to test what encoding it uses ~or ask the author to recompile the program with utf-8~.
OK this is merged. Thanks @kice 

Resolving patch:
diff --git a/python/tvm/_ffi/base.py b/python/tvm/_ffi/base.py
--- a/python/tvm/_ffi/base.py
+++ b/python/tvm/_ffi/base.py
@@ -35,8 +35,13 @@
     # this function is needed for python3
     # to convert ctypes.char_p .value back to python str
     if sys.platform == "win32":
-        encoding = 'cp' + str(ctypes.cdll.kernel32.GetACP())
-        py_str = lambda x: x.decode(encoding)
+        def _py_str(x):
+            try:
+                return x.decode('utf-8')
+            except UnicodeDecodeError:
+                encoding = 'cp' + str(ctypes.cdll.kernel32.GetACP())
+                return x.decode(encoding)
+        py_str = _py_str
     else:
         py_str = lambda x: x.decode('utf-8')
 else:


Test patch: