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

Issue:
[BUG]:  The skills are unassigned from a topic, even when deletion fails
### Describe the bug

When we try to delete a skill containing questions, it fails (as it should) and throws an error. But even when the deletion fails, the skill is unassigned from the topic that it was previously assigned to.

Delete operation should be 'atomic', and should not leave any trace of the steps, if it fails. The skill, ideally should roll back to previous state, before attempted deletion of the skill.

### URL of the page where the issue is observed.

https://www.oppiatestserver.org/topics-and-skills-dashboard

### Steps To Reproduce

1. Goto: https://www.oppiatestserver.org/topics-and-skills-dashboard
2. Create a skill
3. Add one or more question to the skill
4. Assign it to a topic
5. Try to delete it

### Expected Behavior

When delete operation fails, the skill should be intact, as it was before (without being unassigned from the topic it was previously assigned to)

### Screenshots/Videos


https://github.com/oppia/oppia/assets/66303548/2bb05ad4-6e70-4682-8e27-81eda6e67157



### What device are you using?

Desktop

### Operating System

Windows

### What browsers are you seeing the problem on?

Chrome

### Browser version

_No response_

### Additional context

_No response_

### Tips for developers

Before addressing the bug, please identify which PR caused the issue (you can follow the steps [here](https://github.com/oppia/oppia/wiki/How-to-find-the-commit-which-introduced-a-bug)). If you identify the PR, comment on the issue with a link to it. If not, mention the commit hash of the oldest commit you saw the bug on (and the month and year it was made in).

Also, if this is your first issue, please make sure to follow https://github.com/oppia/oppia/wiki/Contributing-code-to-Oppia#choosing-a-good-first-issue and https://github.com/oppia/oppia/wiki/Contributing-code-to-Oppia#setting-things-up before claiming it. Thanks!



Discussion:
This issue is observed in 3.3.6 release as well.

Resolving patch:
diff --git a/core/controllers/skill_editor.py b/core/controllers/skill_editor.py
--- a/core/controllers/skill_editor.py
+++ b/core/controllers/skill_editor.py
@@ -315,13 +315,13 @@ def delete(self, skill_id: str) -> None:
             InvalidInputException. The skill still has associated questions.
         """
         assert self.user_id is not None
-        skill_services.remove_skill_from_all_topics(self.user_id, skill_id)
 
         if skill_services.skill_has_associated_questions(skill_id):
             raise self.InvalidInputException(
                 'Please delete all questions associated with this skill '
                 'first.')
 
+        skill_services.remove_skill_from_all_topics(self.user_id, skill_id)
         skill_services.delete_skill(self.user_id, skill_id)
 
         self.render_json(self.values)


Test patch:
Repository: ranaroussi/yfinance

Issue:
Usage with Anaconda/iPython?
Hi - thanks for the package, works great.

Question - is it possible to use this on iPython/Anaconda?

Thanks!


Discussion:
I use it with Anaconda and with Python2 and Python3.
The problem I am faced is, that approximately every third request 
returns an empty dataframe......
I really doubt, that this is a Yahoo error...  
A whole string of empty dataframes returned after the first few successful ones, then it starts working again
Hi, I have problem when try download another ticker, it will merge into one dataframe, how to separate dataframe per each session? 

my piece of codes
```

etf_a = ['spy','tlt']
etf_b = ['vwo','vti']

start = datetime(2001,1,1)
end    = datetime(2017,1,1)

data_a = pdr.get_data_yahoo(etf_a, start, end)['Adj Close']
data_b = pdr.get_data_yahoo(etf_b, start, end)['Adj Close']

print(len(data_a.columns)) # it will be 2 etf
print(len(data_b.columns))# should be 2, but it return 4, likely merge with previous downloaded data
```

any idea will be most appreciated, thanks!

Resolving patch:
diff --git a/fix_yahoo_finance/__init__.py b/fix_yahoo_finance/__init__.py
--- a/fix_yahoo_finance/__init__.py
+++ b/fix_yahoo_finance/__init__.py
@@ -221,6 +221,7 @@ def download(tickers, start=None, end=None, as_panel=True,
         print("\nThe following tickers failed to download:\n",
               ', '.join(_FAILED_))
 
+    _DFS_ = {}
     return data
 
 


Test patch:
Repository: ranaroussi/yfinance

Issue:
Deprecation warning due to invalid escape sequences
Deprecation warnings are raised due to invalid escape sequences. This can be fixed by using raw strings or escaping the literals. pyupgrade also helps in automatic conversion : https://github.com/asottile/pyupgrade/

```
find . -iname '*.py' | grep -Ev 'test.py' | xargs -P4 -I{} python3.8 -Wall -m py_compile {}
./yfinance/utils.py:67: DeprecationWarning: invalid escape sequence \g
  return [_re.sub("([a-z])([A-Z])", "\g<1> \g<2>", i).title() for i in o]
```


Discussion:

Resolving patch:
diff --git a/yfinance/utils.py b/yfinance/utils.py
--- a/yfinance/utils.py
+++ b/yfinance/utils.py
@@ -64,7 +64,7 @@ def get_json(url, proxy=None):
 
 
 def camel2title(o):
-    return [_re.sub("([a-z])([A-Z])", "\g<1> \g<2>", i).title() for i in o]
+    return [_re.sub("([a-z])([A-Z])", r"\g<1> \g<2>", i).title() for i in o]
 
 
 def auto_adjust(data):


Test patch:
Repository: ranaroussi/yfinance

Issue:
Please add Top Holdings for ETFs
For instance for [https://finance.yahoo.com/quote/QQQ/](https://finance.yahoo.com/quote/QQQ/):
```

Apple Inc | AAPL | 11.00%
Microsoft Corp | MSFT | 9.82%
Amazon.com Inc | AMZN | 8.35%
Facebook Inc A | FB | 4.01%
Facebook Inc Class A | FB | 4.01%
Tesla Inc | TSLA | 3.90%
Alphabet Inc Class C | GOOG | 3.90%
NVIDIA Corp | NVDA | 3.65%
Alphabet Inc A | GOOGL | 3.53%
Alphabet Inc Class A | GOOGL | 3.53%
```



Discussion:
Update: I'll add a pull request which does that - the data is already there, just need to update yfinance
I'm taking this one

Resolving patch:
diff --git a/yfinance/base.py b/yfinance/base.py
--- a/yfinance/base.py
+++ b/yfinance/base.py
@@ -371,12 +371,9 @@ def cleanup(data):
         except Exception:
             pass
 
-       # For ETFs, provide this valuable data: the top holdings of the ETF 
-        try:
-            if 'topHoldings' in data:
-                self._info.update(data['topHoldings'])
-        except Exception:
-            pass
+        # For ETFs, provide this valuable data: the top holdings of the ETF
+        if data.get('topHoldings'):
+            self._info.update(data['topHoldings'])
 
         if not isinstance(data.get('summaryDetail'), dict):
             # For some reason summaryDetail did not give any results. The price dict usually has most of the same info


Test patch:
Repository: ranaroussi/yfinance

Issue:
Please add Top Holdings for ETFs
For instance for [https://finance.yahoo.com/quote/QQQ/](https://finance.yahoo.com/quote/QQQ/):
```

Apple Inc | AAPL | 11.00%
Microsoft Corp | MSFT | 9.82%
Amazon.com Inc | AMZN | 8.35%
Facebook Inc A | FB | 4.01%
Facebook Inc Class A | FB | 4.01%
Tesla Inc | TSLA | 3.90%
Alphabet Inc Class C | GOOG | 3.90%
NVIDIA Corp | NVDA | 3.65%
Alphabet Inc A | GOOGL | 3.53%
Alphabet Inc Class A | GOOGL | 3.53%
```



Discussion:
Update: I'll add a pull request which does that - the data is already there, just need to update yfinance
I'm taking this one

Resolving patch:
diff --git a/yfinance/base.py b/yfinance/base.py
--- a/yfinance/base.py
+++ b/yfinance/base.py
@@ -370,6 +370,13 @@ def cleanup(data):
         except Exception:
             pass
 
+       # For ETFs, provide this valuable data: the top holdings of the ETF 
+        try:
+            if 'topHoldings' in data:
+                self._info.update(data['topHoldings'])
+        except Exception:
+            pass
+
         if not isinstance(data.get('summaryDetail'), dict):
             # For some reason summaryDetail did not give any results. The price dict usually has most of the same info
             self._info.update(data.get('price', {}))


Test patch:
Repository: ranaroussi/yfinance

Issue:
Timezone value passed on to the option_chain throws TypeError
ticker.option_chain(date='2021-11-26', tz="UTC")

TypeError : index is not a valid DatetimeIndex or PeriodIndex



Discussion:

Resolving patch:
diff --git a/yfinance/ticker.py b/yfinance/ticker.py
--- a/yfinance/ticker.py
+++ b/yfinance/ticker.py
@@ -84,9 +84,9 @@ def _options2df(self, opt, tz=None):
             'currency'])
 
         data['lastTradeDate'] = _pd.to_datetime(
-            data['lastTradeDate'], unit='s')
+            data['lastTradeDate'], unit='s', utc=True)
         if tz is not None:
-            data['lastTradeDate'] = data['lastTradeDate'].tz_localize(tz)
+            data['lastTradeDate'] = data['lastTradeDate'].dt.tz_convert(tz)
         return data
 
     def option_chain(self, date=None, proxy=None, tz=None):


Test patch:
Repository: ranaroussi/yfinance

Issue:
Ticker.history: history's index is not of type DateTimeIndex when dividend and split tables are empty
**Issue**:

Ticker.history (line 295):
>       df.index = df.index.tz_localize("UTC").tz_convert(data["chart"]["result"][0]["meta"]["exchangeTimezoneName"])
E       AttributeError: 'Index' object has no attribute 'tz_localize'

**Reason**: 

During the concatenation of a proper price table with empty dividend and split tables, the price table's index has changed from _pandas.DatetimeIndex_ to _pandas.Index_ because the empty tables had this index type.

**Proposed solution**: 

Modify _parse_actions_ (in utils.py) to initialise the dividend and split tables with : 
`dividends = _pd.DataFrame(columns=["Dividends"], index=_pd.DatetimeIndex([]))`
 `splits = _pd.DataFrame(columns=["Stock Splits"], index=_pd.DatetimeIndex([]))`


Local modules' versions:

finance : 0.1.69
pandas : 1.4.0
python : 3.10



Discussion:
I have found out that the issue occurs when upgrading pandas from 1.3.5 to 1.4.0. Staying with pandas 1.3.5 doesn't cause the issue shared above.
Thank you for identifying the issue is with numpy. pip install pandas==1.3.5 resolved the issue for me.

Here are the error messages I experienced when using yfinance in a virtual environment:

```
  File "/home/ubuntu/myproject/env/lib/python3.8/site-packages/yfinance/base.py", line 295, in history
    df.index = df.index.tz_localize("UTC").tz_convert(
AttributeError: 'Index' object has no attribute 'tz_localize'

```
This happens whenever I try to download ticker data with 'period'.

Resolving patch:
diff --git a/yfinance/utils.py b/yfinance/utils.py
--- a/yfinance/utils.py
+++ b/yfinance/utils.py
@@ -197,8 +197,8 @@ def parse_quotes(data, tz=None):
 
 
 def parse_actions(data, tz=None):
-    dividends = _pd.DataFrame(columns=["Dividends"])
-    splits = _pd.DataFrame(columns=["Stock Splits"])
+    dividends = _pd.DataFrame(columns=["Dividends"], index=_pd.DatetimeIndex([]))
+    splits = _pd.DataFrame(columns=["Stock Splits"], index=_pd.DatetimeIndex([]))
 
     if "events" in data:
         if "dividends" in data["events"]:


Test patch:
Repository: ranaroussi/yfinance

Issue:
Ticker.history: history's index is not of type DateTimeIndex when dividend and split tables are empty
**Issue**:

Ticker.history (line 295):
>       df.index = df.index.tz_localize("UTC").tz_convert(data["chart"]["result"][0]["meta"]["exchangeTimezoneName"])
E       AttributeError: 'Index' object has no attribute 'tz_localize'

**Reason**: 

During the concatenation of a proper price table with empty dividend and split tables, the price table's index has changed from _pandas.DatetimeIndex_ to _pandas.Index_ because the empty tables had this index type.

**Proposed solution**: 

Modify _parse_actions_ (in utils.py) to initialise the dividend and split tables with : 
`dividends = _pd.DataFrame(columns=["Dividends"], index=_pd.DatetimeIndex([]))`
 `splits = _pd.DataFrame(columns=["Stock Splits"], index=_pd.DatetimeIndex([]))`


Local modules' versions:

finance : 0.1.69
pandas : 1.4.0
python : 3.10



Discussion:
I have found out that the issue occurs when upgrading pandas from 1.3.5 to 1.4.0. Staying with pandas 1.3.5 doesn't cause the issue shared above.
Thank you for identifying the issue is with numpy. pip install pandas==1.3.5 resolved the issue for me.

Here are the error messages I experienced when using yfinance in a virtual environment:

```
  File "/home/ubuntu/myproject/env/lib/python3.8/site-packages/yfinance/base.py", line 295, in history
    df.index = df.index.tz_localize("UTC").tz_convert(
AttributeError: 'Index' object has no attribute 'tz_localize'

```
This happens whenever I try to download ticker data with 'period'.

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -61,7 +61,7 @@
     platforms=['any'],
     keywords='pandas, yahoo finance, pandas datareader',
     packages=find_packages(exclude=['contrib', 'docs', 'tests', 'examples']),
-    install_requires=['pandas>=0.24', 'numpy>=1.15',
+    install_requires=['pandas>=0.24.0,<=1.3.5', 'numpy>=1.15',
                       'requests>=2.26', 'multitasking>=0.0.7',
                       'lxml>=4.5.1'],
     entry_points={


Test patch:
Repository: ranaroussi/yfinance

Issue:
fix(sec): upgrade lxml to 4.9.1
### What happened？
There are 1 security vulnerabilities found in lxml 4.5.1
- [CVE-2022-2309](https://www.oscs1024.com/hd/CVE-2022-2309)


### What did I do？
Upgrade lxml from 4.5.1 to 4.9.1 for vulnerability fix

### What did you expect to happen？
Ideally, no insecure libs should be used.

### The specification of the pull request
[PR Specification](https://www.oscs1024.com/docs/pr-specification/) from OSCS


Discussion:
I had a look into automated solutions. Two exist - also Python modules - but neither can handle the `>=` in requirements.txt:
- safety
- pip-audit

`safety` developers claim to have a release imminent that will address. But until then, manual checks needed.
Actually, yfinance doesn't use lxml anymore. Will remove it.
Resolved by removing lxml - #1231

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -63,7 +63,7 @@
     packages=find_packages(exclude=['contrib', 'docs', 'tests', 'examples']),
     install_requires=['pandas>=1.3.0', 'numpy>=1.16.5',
                       'requests>=2.26', 'multitasking>=0.0.7',
-                      'appdirs>=1.4.4'],
+                      'lxml>=4.9.1', 'appdirs>=1.4.4'],
     entry_points={
         'console_scripts': [
             'sample=sample:main',


Test patch:
Repository: ranaroussi/yfinance

Issue:
Ticket data from different timezone are not aligned (bug introduced with #1085)
I am trying to find correlations between tickets in differnet timezone (one in the New York Stock exchange and the other in the London Stock Exchange). Due to changes to the timezone logic, the data in each row of `yfinance.download` are no longer the data of the Tickets at the same time. Using `ignore_tz=False` fixes this problem. This problem didn't exist with version `0.1.77` and previous. So I think by default `ignore_tz` should be set to `False` as that behaviour is consistent with the previous minor versions. 


Discussion:
But `ignore_tz=True` is default behaviour. Sounds like you copy-pasted from README without reading - post your code please.
I wrote my code with version `0.1.75`. I upgraded my packages the other day and found out my data analysis was completely off. Using `ignore_tz=False` brought back the old behaviour. See below for a minimal example
```
import yfinance as yf

tickets = yf.download(tickers=f"^FTSE ^DJI", period='7d', interval='1m', ignore_tz=True)
for index, row in tickets.iterrows():
    a = row['Close']['^FTSE']
    b = row['Close']['^DJI']
    # a and b are not data at the same time 

tickets = yf.download(tickers=f"^FTSE ^DJI", period='7d', interval='1m', ignore_tz=False)
for index, row in tickets.iterrows():
    a = row['Close']['^FTSE']
    b = row['Close']['^DJI']
    # a and b are data at the same time
```

I understand now, behaviour has changed since old version. Do you mind submitting a PR?
Sure. Is the PR just changing the default value to `ignore_tz=False`? 
Yes. I know it's trivial but I want community to be more involved in code.

Edit: update doc & README too, says default = True

Resolving patch:
diff --git a/yfinance/multi.py b/yfinance/multi.py
--- a/yfinance/multi.py
+++ b/yfinance/multi.py
@@ -29,7 +29,7 @@
 from . import shared
 
 
-def download(tickers, start=None, end=None, actions=False, threads=True, ignore_tz=True,
+def download(tickers, start=None, end=None, actions=False, threads=True, ignore_tz=False,
              group_by='column', auto_adjust=False, back_adjust=False, repair=False, keepna=False,
              progress=True, period="max", show_errors=True, interval="1d", prepost=False,
              proxy=None, rounding=False, timeout=10):
@@ -68,7 +68,7 @@ def download(tickers, start=None, end=None, actions=False, threads=True, ignore_
             How many threads to use for mass downloading. Default is True
         ignore_tz: bool
             When combining from different timezones, ignore that part of datetime.
-            Default is True
+            Default is False
         proxy: str
             Optional. Proxy server URL scheme. Default is None
         rounding: bool


Test patch:
Repository: ranaroussi/yfinance

Issue:
issues with getting price of EUR=X (Yahoo did not return share count in date range 2021-07-26 00:00:00+01:00 -> 2023-01-26 00:00:00+00:00.)
I have upgraded to 0.2.5 and updated the code to use the basic_info in stead of info for price values but for Ticker EUR=X I am getting the following:
EUR=X: Yahoo did not return share count in date range 2021-07-26 00:00:00+01:00 -> 2023-01-26 00:00:00+00:00.

File "yahoo.py", line 22, in
for key in sorted(tk.basic_info.keys()):
File "\AppData\Roaming\Python\Python310\site-packages\yfinance\base.py", line 85, in keys
attrs = utils.attributes(self)
File "\AppData\Roaming\Python\Python310\site-packages\yfinance\utils.py", line 59, in attributes
return {
File "\AppData\Roaming\Python\Python310\site-packages\yfinance\utils.py", line 61, in
if name[0] != '_' and name not in disallowed_names and hasattr(obj, name)}
File "\AppData\Roaming\Python\Python310\site-packages\yfinance\base.py", line 358, in market_cap
self._mcap = self.shares * self.last_price
File "\AppData\Roaming\Python\Python310\site-packages\yfinance\base.py", line 201, in shares
raise Exception(f"{self._tkr.ticker}: Cannot retrieve share count for calculating market cap")
Exception: EUR=X: Cannot retrieve share count for calculating market cap



Discussion:

Resolving patch:
diff --git a/yfinance/base.py b/yfinance/base.py
--- a/yfinance/base.py
+++ b/yfinance/base.py
@@ -82,8 +82,17 @@ def __init__(self, tickerBaseObject):
 
     # dict imitation:
     def keys(self):
-        attrs = utils.attributes(self)
-        return attrs.keys()
+        # attrs = utils.attributes(self)
+        # return attrs.keys()
+        # utils.attributes is calling each method, bad!
+        # Have to hardcode
+        keys = ["currency", "exchange", "timezone"]
+        keys += ["shares", "market_cap"]
+        keys += ["last_price", "previous_close", "open", "day_high", "day_low"]
+        keys += ["last_volume"]
+        keys += ["fifty_day_average", "two_hundred_day_average", "ten_day_average_volume", "three_month_average_volume"]
+        keys += ["year_high", "year_low", "year_change"]
+        return keys
     def items(self):
         return [(k,self[k]) for k in self.keys()]
     def __getitem__(self, k):
@@ -198,7 +207,7 @@ def shares(self):
             # Requesting 18 months failed, so fallback to shares which should include last year
             shares = self._tkr.get_shares()
         if shares is None:
-            raise Exception(f"{self._tkr.ticker}: Cannot retrieve share count for calculating market cap")
+            raise Exception(f"{self._tkr.ticker}: Cannot retrieve share count")
         if isinstance(shares, pd.DataFrame):
             shares = shares[shares.columns[0]]
         self._shares = shares.iloc[-1]


Test patch:
Repository: ranaroussi/yfinance

Issue:
Integrity Error when reading prices?
Hello - i create a simply test-program with output the prices for AAPL - 

```
from datetime import datetime, timedelta
import yfinance as yf
import time

tday = datetime.today()    
startDay = tday - timedelta(days=600)          
dfPrice = yf.download("AAPL", start=startDay, end=tday)   

print(dfPrice)
time.sleep(10)
```

Everything works fine - also when i bundle this to an exeduteable for windows.
But when i provide the exe-file to another user he gets on his computer this error:

```
[*********************100%***********************]  1 of 1 completed

1 Failed download:
- AAPL: IntegrityError('NOT NULL constraint failed: kv.key')
Empty DataFrame
Columns: [Open, High, Low, Close, Adj Close, Volume]
Index: []
```

It seems that this is an yfinance-error and has nothing to do with the pyinstaller-bundeling.
What does this error message mean?
Why is it only happening on one computer and i am not able to reproduce this on mine?








Discussion:

Resolving patch:
diff --git a/yfinance/utils.py b/yfinance/utils.py
--- a/yfinance/utils.py
+++ b/yfinance/utils.py
@@ -730,14 +730,21 @@ def close(self):
 
     def get(self, key: str) -> Union[str, None]:
         """Get value for key if it exists else returns None"""
-        item = self.conn.execute('select value from "kv" where key=?', (key,))
+        try:
+            item = self.conn.execute('select value from "kv" where key=?', (key,))
+        except _sqlite3.IntegrityError as e:
+            self.delete(key)
+            return None
         if item:
             return next(item, (None,))[0]
 
     def set(self, key: str, value: str) -> None:
-        with self._cache_mutex:
-            self.conn.execute('replace into "kv" (key, value) values (?,?)', (key, value))
-            self.conn.commit()
+        if value is None:
+            self.delete(key)
+        else:
+            with self._cache_mutex:
+                self.conn.execute('replace into "kv" (key, value) values (?,?)', (key, value))
+                self.conn.commit()
 
     def bulk_set(self, kvdata: Dict[str, str]):
         records = tuple(i for i in kvdata.items())
@@ -807,7 +814,15 @@ def _migrate_cache_tkr_tz(self):
         except _pd.errors.EmptyDataError:
             _os.remove(old_cache_file_path)
         else:
-            self.tz_db.bulk_set(df.to_dict()['Tz'])
+            df = df[~df["Tz"].isna().to_numpy()]
+            df = df[~(df["Tz"]=='').to_numpy()]
+            if not df.empty:
+                try:
+                    self.tz_db.bulk_set(df.to_dict()['Tz'])
+                except Exception as e:
+                    # Ignore
+                    pass
+
             _os.remove(old_cache_file_path)
 
 


Test patch:
Repository: ranaroussi/yfinance

Issue:
Falure when using single ISIN as a ticker (fix included)
Multiple tickers with ISINs mixed in do work, but a single ISIN fails. Here is the culprit (multi.py):

>     if len(tickers) == 1:
>        ticker = tickers[0]
>        return shared._DFS[shared._ISINS.get(ticker, ticker)]


The last line should be just

> return shared._DFS[ticker]

as at that point in time both _DFS and tickers refer to Yahoo ID instead of ISIN, and lookup by original ISIN in _DFS is failing. 

Testcase:

>import yfinance as yf
>yf.download("SE0000594111", period="7d", repair=True, progress=False, threads=False, timeout=30)

(corresponding Yahoo ID is '0P00000FYR.ST'.


Discussion:
Anyone can contribute code, just read #1084

Resolving patch:
diff --git a/yfinance/multi.py b/yfinance/multi.py
--- a/yfinance/multi.py
+++ b/yfinance/multi.py
@@ -207,7 +207,7 @@ def download(tickers, start=None, end=None, actions=False, threads=True, ignore_
 
     if len(tickers) == 1:
         ticker = tickers[0]
-        return shared._DFS[shared._ISINS.get(ticker, ticker)]
+        return shared._DFS[ticker]
 
     try:
         data = _pd.concat(shared._DFS.values(), axis=1, sort=True,


Test patch: