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

Issue:
Fix simple typo: whith -> with
There is a small typo in obspy/io/gcf/core.py.
Should read `with` rather than `whith`.




Discussion:

Resolving patch:
diff --git a/obspy/io/gcf/core.py b/obspy/io/gcf/core.py
--- a/obspy/io/gcf/core.py
+++ b/obspy/io/gcf/core.py
@@ -16,7 +16,7 @@ def merge_gcf_stream(st):
     Merges GCF stream (replacing Stream.merge(-1) for headonly=True)
 
     :type st: :class:`~obspy.core.stream.Stream`
-    :param st: GCF Stream object whith no data
+    :param st: GCF Stream object with no data
     :rtype: :class:`~obspy.core.stream.Stream`
     :returns: Stream object containing header and data.
     """


Test patch:
Repository: obspy/obspy

Issue:
Travis not building
I think it is a problem connected with changes introduced by me in #2619. In my project CI was building with that setup up to Friday, but crashed today. I fixed it with adding to pyproject.toml required by PEP517. I will do a PR to add this line here.





Quoting @megies:

Not sure whats wrong with Travis but looks like a clash between setuptools and numpy, so hopefully will go away eventually and we can just wait it out.

```
    File "/private/var/folders/nz/vv4_9tw56nv9k3tkvyszvwg80000gn/T/pip-build-env-dq61kdlp/overlay/lib/python3.7/site-packages/setuptools/build_meta.py", line 142, in run_setup

      exec(compile(code, __file__, 'exec'), locals())

    File "setup.py", line 47, in <module>

      from numpy.distutils.core import DistutilsSetupError, setup

  ImportError: cannot import name 'DistutilsSetupError' from 'numpy.distutils.core' (/private/var/folders/nz/vv4_9tw56nv9k3tkvyszvwg80000gn/T/pip-build-env-dq61kdlp/overlay/lib/python3.7/site-packages/numpy/distutils/core.py)
```

_Originally posted by @megies in https://github.com/obspy/obspy/pull/2626#issuecomment-648019872_


Discussion:
Okay, It's not my fault. Numpy released version 1.19 on 2020.06.20 on PyPi. As for now, neither documentation site nor the home site is updated and doesn't show that fact.

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -43,8 +43,9 @@
 import sys
 import platform
 from distutils.util import change_root
+from distutils.errors import DistutilsSetupError
 
-from numpy.distutils.core import DistutilsSetupError, setup
+from numpy.distutils.core import setup
 from numpy.distutils.ccompiler import get_default_compiler
 from numpy.distutils.command.build import build
 from numpy.distutils.command.install import install


Test patch:
Repository: obspy/obspy

Issue:
Scipy 2.0 deprecations
Scipy deprecated few methods and will removed them in 2.0. Now they are popping in CI as warnings
```
scipy.polyfit is deprecated and will be removed in SciPy 2.0.0, use numpy.polyfit instead
scipy.polyval is deprecated and will be removed in SciPy 2.0.0, use numpy.polyval instead

```


Discussion:
Do we know when scipy 2.0 will be out? Depending if sooner or later we might target 1.2.x instead.. dunno. Can always backport if needed though
To be honest, I could not find an exact timeline. They are following 6 months release cycle and they just released 1.5 (thus the new depracation warning I think). I could not find when they want to release 2.0, they do not have a milestones ahead of 1.6. 

I would say that we have quite a bit of time :)

Resolving patch:
diff --git a/obspy/signal/cross_correlation.py b/obspy/signal/cross_correlation.py
--- a/obspy/signal/cross_correlation.py
+++ b/obspy/signal/cross_correlation.py
@@ -669,7 +669,7 @@ def xcorr_pick_correction(pick1, trace1, pick2, trace2, t_before, t_after,
               "correlation: %s" % num_samples
         warnings.warn(msg)
     # quadratic fit for small subwindow
-    coeffs, residual = scipy.polyfit(
+    coeffs, residual = np.polyfit(
         cc_t[first_sample:last_sample + 1],
         cc[first_sample:last_sample + 1], deg=2, full=True)[:2]
     # check results of fit
@@ -718,7 +718,7 @@ def xcorr_pick_correction(pick1, trace1, pick2, trace2, t_before, t_after,
                      label="used for fitting")
             tmp_t = np.linspace(cc_t[first_sample], cc_t[last_sample],
                                 num_samples * 10)
-            ax2.plot(tmp_t, scipy.polyval(coeffs, tmp_t), "b", label="fit")
+            ax2.plot(tmp_t, np.polyval(coeffs, tmp_t), "b", label="fit")
             ax2.axvline(-dt, color="g", label="vertex")
             ax2.axhline(coeff, color="g")
             ax2.set_xlabel("%.2f at %.3f seconds correction" % (coeff, -dt))


Test patch:
Repository: obspy/obspy

Issue:
Ambiguity in xcorr_max()
The [documentation ](https://docs.obspy.org/packages/autogen/obspy.signal.cross_correlation.xcorr_max.html) for `xcorr_max()` has a boolean for `abs_max` to define whether to take the maximum cross correlation or not. My confusion lies since absolute in mathematics often defines a positive value. When `abs_max = True` it allows the maximum positive OR negative value. This is opposite to what I expected since "abs_max" should imply positive? Is there a way of adding clarification/changing the variable name?

Cheers!


Discussion:
@trichter that's your stuff no ? I agree it can be confusing :)
@Lewis-Khan Could you create a PR with a better doc string? I think returning the negative value for the case of a "negative absolute maximum" is preferable since it transmits more information.
@trichter Yes, I can give it a go. Just to make sure i'm along the right lines it should be:
```
if abs_max == True:
    Return the maximum positive correlation.
elif abs_max == False:
    Return the maximum correlation (positive or negative)
```
Should the default value for the function then be switched from abs_max = True to abs_max = False to switch the meaning? If so, this may change existing code.

Which branch should I submit a pull request on - master or maintenance?
I think it is not an option to change the behavior of the code. Better only clarify the doc string. `abs_max=False`(default) -> maximum (always positive) , `abs_max=True` -> absolute maximum (positive or negative).

Usually this would go into maintenance. But at the moment I'd prefer master, because maintenance still supports python2. We'll probably not see another `1.2.x` release. Later when maintenance is merged into master, it will land in master anyway, but the merging itself is another step and might result in more work when eliminating any merge conflicts.

Resolving patch:
diff --git a/obspy/signal/cross_correlation.py b/obspy/signal/cross_correlation.py
--- a/obspy/signal/cross_correlation.py
+++ b/obspy/signal/cross_correlation.py
@@ -387,7 +387,10 @@ def xcorr_max(fct, abs_max=True):
 
     :type fct: :class:`~numpy.ndarray`
     :param fct: Cross-correlation function e.g. returned by correlate.
-    :param bool abs_max: Determines if the absolute maximum should be used.
+    :param bool abs_max: Determines if the largest value of the correlation
+        function is returned, independent of it being positive (correlation) or
+        negative (anti-correlation). Defaults to `True`. If `False` the maximum
+        returned is positive only.
     :return: **shift, value** - Shift and value of maximum of
         cross-correlation.
 


Test patch:
Repository: obspy/obspy

Issue:
Inconsistent behaviour with st.merge(method=-1)
**Issue description:**
When merging with `method=-1` (i.e. `st._cleanup()`), `merge()` does not explicitly return the resulting `Stream` object, whereas for the other methods it does. This can desirable - e.g. cycling through a `Stream` and applying the merge operation individually for each id, such that if one amongst many doesn't pass the merge checks then they are not all rejected (see e.g. https://github.com/QuakeMigrate/QuakeMigrate/issues/137) . I would imagine doing this with:

```
ids = set([tr.id for tr in st])
st_merged = Stream()
for tr_id in ids:
    st_merged += st.select(id=tr_id).merge(method=-1)
```

This is currently possible, but only by using the internal `st._cleanup()` function, which does explicitly return the new `Stream` object.

**Suggested fix:**

Lines 2009-2011 of `obspy.core.stream`:
```
        self._cleanup(**kwargs)
        if method == -1:
-            return
+            return self
```

**Platform info:**
 - ObsPy version: 1.2.2
 - Python version: 3.8.4
 - Operating System: Ubuntu 16.04
 - Installed through anaconda


Discussion:
Hi Tom,

thanks for raising this issue. Sounds reasonable.
Could you provide a PR against master branch?

Resolving patch:
diff --git a/obspy/core/stream.py b/obspy/core/stream.py
--- a/obspy/core/stream.py
+++ b/obspy/core/stream.py
@@ -2008,7 +2008,7 @@ def listsort(order, current):
 
         self._cleanup(**kwargs)
         if method == -1:
-            return
+            return self
         # check sampling rates and dtypes
         self._merge_checks()
         # remember order of traces


Test patch:
Repository: obspy/obspy

Issue:
taup pierce for phase 2kmps raises error

"2kmps" is a fake phase name in TauP for a 2kmps surface wave. Pierce points for this are mostly not useful, just the start and ending points, but not raising an error in this case would be nice.


```
from obspy.taup import TauPyModel
taumodel = TauPyModel(model="prem" )
arrivals = taumodel.get_pierce_points(source_depth_in_km=origin.depth/1000,
                                   distance_in_degree=daz.getDistanceDeg(),
                                   phase_list=["2kmps"])
```
gives
```
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'origin' is not defined
>>> arrivals = taumodel.get_pierce_points(source_depth_in_km=10, distance_in_degree=30, phase_list=["2kmps"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/crotwell/opt/miniconda3/envs/obspy/lib/python3.7/site-packages/obspy/taup/tau.py", line 680, in get_pierce_points
    pp.run()
  File "/Users/crotwell/opt/miniconda3/envs/obspy/lib/python3.7/site-packages/obspy/taup/taup_time.py", line 39, in run
    self.calculate(self.degrees)
  File "/Users/crotwell/opt/miniconda3/envs/obspy/lib/python3.7/site-packages/obspy/taup/taup_pierce.py", line 73, in calculate
    self.calculate_pierce(degrees)
  File "/Users/crotwell/opt/miniconda3/envs/obspy/lib/python3.7/site-packages/obspy/taup/taup_pierce.py", line 82, in calculate_pierce
    self.arrivals += phase.calc_pierce(degrees)
  File "/Users/crotwell/opt/miniconda3/envs/obspy/lib/python3.7/site-packages/obspy/taup/seismic_phase.py", line 1047, in calc_pierce
    self.calc_pierce_from_arrival(arrival)
  File "/Users/crotwell/opt/miniconda3/envs/obspy/lib/python3.7/site-packages/obspy/taup/seismic_phase.py", line 1090, in calc_pierce_from_arrival
    len(self.down_going)
AssertionError

```

But in java version:
```
taup_pierce -h 10 -deg 30 -ph 2kmps
> 2kmps at  1667.92 seconds at    30.00 degrees for a     10.0 km deep source in the iasp91 model with rayParam   55.597 s/deg.
    0.00    10.0     0.0
   30.00     0.0  1667.9
> 2kmps at 18347.16 seconds at   330.00 degrees for a     10.0 km deep source in the iasp91 model with rayParam   55.597 s/deg.
    0.00    10.0     0.0
 -330.00     0.0 18347.2
```

```
Python 3.7.3 | packaged by conda-forge | (default, Jul  1 2019, 14:38:56) 
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin

obspy                     1.2.2            py37h10e2902_0    conda-forge
```


Discussion:

Resolving patch:
diff --git a/obspy/taup/seismic_phase.py b/obspy/taup/seismic_phase.py
--- a/obspy/taup/seismic_phase.py
+++ b/obspy/taup/seismic_phase.py
@@ -812,7 +812,6 @@ def sum_branches(self, tau_model):
 
             self.min_distance = 0
             self.max_distance = 2 * math.pi
-            self.down_going.append(True)
             return
 
         if self.max_ray_param < 0 or self.min_ray_param > self.max_ray_param:


Test patch:
Repository: obspy/obspy

Issue:
Clarify xcorr_3c docstring
### Documentation Link

https://docs.obspy.org/packages/autogen/obspy.signal.cross_correlation.xcorr_3c.html

### Problem

A new implementation of cross-correlation, i.e., `correlate`, is created in #1585 and `xcorr` is removed in  #1979. But the documentation for `xcorr_3c` still refers to `xcorr`:

https://github.com/obspy/obspy/blob/654442a26d7d1af213fc7a86831d655b79586031/obspy/signal/cross_correlation.py#L313

### Suggested improvement

I guess this line should replace `xcorr` with `correlate`, right?


Discussion:
@trichter should know better
> I guess this line should replace xcorr with correlate, right?

Yes, it just needs to be replaced.

Resolving patch:
diff --git a/obspy/signal/cross_correlation.py b/obspy/signal/cross_correlation.py
--- a/obspy/signal/cross_correlation.py
+++ b/obspy/signal/cross_correlation.py
@@ -310,7 +310,7 @@ def xcorr_3c(st1, st2, shift_len, components=["Z", "N", "E"],
     separately, stacks them together and estimates the maximum and shift of
     maximum on the stack.
 
-    Basically the same as `~obspy.signal.cross_correlation.xcorr` but
+    Basically the same as `~obspy.signal.cross_correlation.correlate` but
     for (normally) three components, please also take a look at the
     documentation of that function. Useful e.g. for estimation of waveform
     similarity on a three component seismogram.


Test patch:
Repository: obspy/obspy

Issue:
Event filtering always excludes magnitude 0 events
### Avoid duplicates

- [X] I searched existing issues

### Bug Summary

See title. I expect some kind of `if mag:` check at work.

### Code to Reproduce

```python
In [1]: evs = read_events()

In [2]: evs[0].magnitudes[0].mag = 0

In [3]: evs
Out[3]: 
3 Event(s) in Catalog:
2012-04-04T14:21:42.300000Z | +41.818,  +79.689 | 0.0  mb | manual
2012-04-04T14:18:37.000000Z | +39.342,  +41.044 | 4.3  ML | manual
2012-04-04T14:08:46.000000Z | +38.017,  +37.736 | 3.0  ML | manual

In [4]: evs.filter('magnitude < 3.5')
Out[4]: 
1 Event(s) in Catalog:
2012-04-04T14:08:46.000000Z | +38.017,  +37.736 | 3.0  ML | manual
```


### Error Traceback

_No response_

### ObsPy Version?

master

### Operating System?

_No response_

### Python Version?

_No response_

### Installation Method?

_No response_


Discussion:

Resolving patch:
diff --git a/obspy/core/event/catalog.py b/obspy/core/event/catalog.py
--- a/obspy/core/event/catalog.py
+++ b/obspy/core/event/catalog.py
@@ -365,7 +365,8 @@ def _is_greater_or_equal(value_1, value_2):
             if key == "magnitude":
                 temp_events = []
                 for event in events:
-                    if (event.magnitudes and event.magnitudes[0].mag and
+                    if (event.magnitudes and
+                        event.magnitudes[0].mag is not None and
                         operator_map[operator](
                             event.magnitudes[0].mag,
                             float(value))):


Test patch:
diff --git a/obspy/core/tests/test_event.py b/obspy/core/tests/test_event.py
--- a/obspy/core/tests/test_event.py
+++ b/obspy/core/tests/test_event.py
@@ -675,3 +675,9 @@ def test_setting_nans_or_inf_fails(self):
 
         with pytest.raises(ValueError, match='is not a finite'):
             o.latitude = float('-inf')
+
+    def test_issue3105(self):
+        evs = read_events()
+        evs[0].magnitudes[0].mag = 0
+        assert len(evs) == 3
+        assert len(evs.filter('magnitude < 3.5')) == 2
Repository: obspy/obspy

Issue:
set_flags_in_fixed_headers: wrong use of sampling rate
### Avoid duplicates

- [X] I searched existing issues

### Bug Summary

My code generates mseed files and calls the function `obspy.io.mseed.util.set_flags_in_fixed_headers`.
The flags to be set are of the 'DURATION' kind and I could observe in the resulting files that some records had the flags set when they should not wrt to their data dates.

I looked into the  code of this function and I think I found a buggy line. In obspy-1.3, it is in
obspy/io/mseed/util.py:1160-1163
```
                # date of the last sample is recstart+samp_rate*(nb_samples-1)
                # We assume here that a record with samples [0, 1, ..., n]
                # has a period [ date_0, date_n+1 [  AND NOT [ date_0, date_n ]
                realendtime = recstart + samp_rate * (nb_samples)
```
As far I understand it, it should be :
```
                # date of the last sample is recstart+(nb_samples-1)/samp_rate
                # We assume here that a record with samples [0, 1, ..., n]
                # has a period [ date_0, date_n+1 [  AND NOT [ date_0, date_n ]
                realendtime = recstart + nb_samples / samp_rate
```

What comforts me in this analysis is the line 814 of the same file, in the function `_get_record_information`:
```
        info['endtime'] = starttime + (npts - 1) / samp_rate
```


### Code to Reproduce

_No response_

### Error Traceback

_No response_

### ObsPy Version?

1.0.2 and 1.3 (and probably all intermediates)

### Operating System?

CentOS

### Python Version?

2.7

### Installation Method?

pip


Discussion:
Without looking at the details, looks like you're correct `sampling_rate * num_samples` as time increment doesn't make sense.

Resolving patch:
diff --git a/obspy/io/mseed/util.py b/obspy/io/mseed/util.py
--- a/obspy/io/mseed/util.py
+++ b/obspy/io/mseed/util.py
@@ -1160,7 +1160,7 @@ def __missing__(self, key):
                 # date of the last sample is recstart+samp_rate*(nb_samples-1)
                 # We assume here that a record with samples [0, 1, ..., n]
                 # has a period [ date_0, date_n+1 [  AND NOT [ date_0, date_n ]
-                realendtime = recstart + samp_rate * (nb_samples)
+                realendtime = recstart + nb_samples / samp_rate
 
                 # Convert flags to bytes : activity
                 if 'activity_flags' in flags_value:


Test patch:
Repository: obspy/obspy

Issue:
Seg2 read error for NOTE keyword
### Avoid duplicates

- [X] I searched existing issues

### Bug Summary

Hi, I am having problems reading seg2 files if the keyword 'NOTE' exists but has no contents behind :

Initial code (function "parse_free_form" near the end, around line 327 in file seg2.py:

```
       if key == 'NOTE':
            value = [cleanup_and_decode_string(line)
                     for line in value.split(self.line_terminator)
                     if line]
        else:
            value = cleanup_and_decode_string(value)
```
I suggest:
```
        if key == 'NOTE':
            try:
                value = [cleanup_and_decode_string(line)
                         for line in value.split(self.line_terminator)
                         if line]
            except:
                value = ''
        else:
            value = cleanup_and_decode_string(value)
```


[Rec_00001.zip](https://github.com/obspy/obspy/files/9765136/Rec_00001.zip)


### Code to Reproduce

```python
from obspy.io.seg2 import seg2
filename = "rec_00001.seg2"
st = seg2._read_seg2(filename)
```


### Error Traceback

```Python traceback
Traceback (most recent call last):

  File "C:\Users\Hermann\anaconda3\envs\pg\lib\site-packages\spyder_kernels\py3compat.py", line 356, in compat_exec
    exec(code, globals, locals)

  File "c:\sources_2010\python_programs\obspy_error.py", line 13, in <module>
    st = seg2._read_seg2(filename)

  File "C:\Users\Hermann\anaconda3\envs\pg\lib\site-packages\obspy\io\seg2\seg2.py", line 364, in _read_seg2
    st = seg2.read_file(filename)

  File "C:\Users\Hermann\anaconda3\envs\pg\lib\site-packages\obspy\io\seg2\seg2.py", line 83, in read_file
    self.read_file_descriptor_block()

  File "C:\Users\Hermann\anaconda3\envs\pg\lib\site-packages\obspy\io\seg2\seg2.py", line 167, in read_file_descriptor_block
    self.parse_free_form(

  File "C:\Users\Hermann\anaconda3\envs\pg\lib\site-packages\obspy\io\seg2\seg2.py", line 329, in parse_free_form
    for line in value.split(self.line_terminator)

TypeError: must be str or None, not bytes
```


### ObsPy Version?

1.3.0

### Operating System?

Windows

### Python Version?

3.8.13

### Installation Method?

conda


Discussion:

Resolving patch:
diff --git a/obspy/io/seg2/seg2.py b/obspy/io/seg2/seg2.py
--- a/obspy/io/seg2/seg2.py
+++ b/obspy/io/seg2/seg2.py
@@ -323,7 +323,7 @@ def is_good_char(c):
             try:
                 value = string[1]
             except IndexError:
-                value = ''
+                value = b''
             if key == 'NOTE':
                 value = [cleanup_and_decode_string(line)
                          for line in value.split(self.line_terminator)


Test patch:
Repository: obspy/obspy

Issue:
NCDEC fdsn goes HTTPS
### Avoid duplicates

- [X] I searched existing issues

### Bug Summary

Received by email:

> We (NCEDC) recently started using https (from http) for [FDSN webservice](https://service.ncedc.org/) and this would make an error when obspy users will use Client("NCEDC")  as shown at the bottom of the email.  A simple tentative solution to work around this issue is to overwrite URL_MAPPINGS:
> 
```
from obspy.clients.fdsn.header import URL_MAPPINGS
URL_MAPPINGS['NCEDC'] = "https://service.ncedc.org/"
```
> 
> We will post this at the front page of the NCEDC website so that users can get our data with obspy but eventually it would be great if obspy source code will use "https://service.ncedc.org/". Could you please pass this information to the obspy developer team?
> 
> Thank you so much again for providing obspy (and MSNoise indeed!) to the community. Please let me know if you have questions.
> 



### Code to Reproduce

```python
from obspy.clients.fdsn import Client
client1 = Client("NCEDC") # data from NCEDC
```


### Error Traceback

```Python traceback
client1 = Client("NCEDC") # data from NCEDC
---------------------------------------------------------------------------
FDSNException                             Traceback (most recent call last)
<ipython-input-113-75b7c9c20b1d> in <module>
      1 from obspy.clients.fdsn import Client
----> 2 client1 = Client("NCEDC") # data from NCEDC

~/opt/anaconda3/envs/netops/lib/python3.8/site-packages/obspy/clients/fdsn/client.py in __init__(self, base_url, major_versions, user, password, user_agent, debug, timeout, service_mappings, force_redirect, eida_token, _discover_services)
    261
    262         if _discover_services:
--> 263             self._discover_services()
    264         else:
    265             self.services = DEFAULT_SERVICES

~/opt/anaconda3/envs/netops/lib/python3.8/site-packages/obspy/clients/fdsn/client.py in _discover_services(self)
   1737                    "be due to a temporary service outage or an invalid FDSN "
   1738                    "service address." % self.base_url)
-> 1739             raise FDSNException(msg)
   1740
   1741         # Cache.

FDSNException: No FDSN services could be discovered at 'http://service.ncedc.org'. This could be due to a temporary service outage or an invalid FDSN service address.
```


### ObsPy Version?

all

### Operating System?

all

### Python Version?

all

### Installation Method?

_No response_


Discussion:

Resolving patch:
diff --git a/obspy/clients/fdsn/header.py b/obspy/clients/fdsn/header.py
--- a/obspy/clients/fdsn/header.py
+++ b/obspy/clients/fdsn/header.py
@@ -118,7 +118,7 @@ class FDSNNoServiceException(FDSNException):
     "KNMI": "http://rdsa.knmi.nl",
     "KOERI": "http://eida.koeri.boun.edu.tr",
     "LMU": "http://erde.geophysik.uni-muenchen.de",
-    "NCEDC": "http://service.ncedc.org",
+    "NCEDC": "https://service.ncedc.org",
     "NIEP": "http://eida-sc3.infp.ro",
     "NOA": "http://eida.gein.noa.gr",
     "ODC": "http://www.orfeus-eu.org",


Test patch: