prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Add price to Turkey
  I am not sure which of the ticker [prices](https://www.epias.com.tr/en) to use but section 6.7.3 BLOCK ORDER BOOK in [this guide](https://www.epias.com.tr/wp-content/uploads/2017/06/INTRADAY_MARKET_USER_GUIDE_ENG_18.09.2017.pdf) may help.
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `parsers/TR.py`
  Content:
  ```
  1 #!/usr/bin/env python3
  2 
  3 import requests
  4 import re
  5 import json
  6 import arrow
  7 
  8 SEARCH_DATA = re.compile(r'var gunlukUretimEgrisiData = (?P<data>.*);')
  9 TIMEZONE = 'Europe/Istanbul'
  10 URL = 'https://ytbs.teias.gov.tr/ytbs/frm_login.jsf'
  11 EMPTY_DAY = -1
  12 
  13 MAP_GENERATION = {
  14     'akarsu': 'hydro',
  15     'barajli': 'hydro',
  16     'dogalgaz': 'gas',
  17     'lng': 'gas',
  18     'lpg': 'gas',
  19     'jeotermal': 'geothermal',
  20     'taskomur': 'coal',
  21     'asfaltitkomur': 'coal',
  22     'linyit': 'coal',
  23     'ithalkomur': 'coal',
  24     'ruzgar': 'wind',
  25     'fueloil': 'oil',
  26     'biyokutle': 'biomass',
  27     'nafta': 'oil',
  28     'gunes': 'solar',
  29     'nukleer': 'nuclear',
  30     'kojenerasyon': 'unknown',
  31     'motorin': 'oil',
  32 }
  33 
  34 
  35 def as_float(prod):
  36     """Convert json values to float and sum all production for a further use"""
  37     prod['total'] = 0.0
  38     if isinstance(prod, dict) and 'yuk' not in prod.keys():
  39         for prod_type, prod_val in prod.items():
  40             prod[prod_type] = float(prod_val)
  41             prod['total'] += prod[prod_type]
  42     return prod
  43 
  44 
  45 def get_last_data_idx(productions):
  46     """
  47     Find index of the last production
  48     :param productions: list of 24 production dict objects
  49     :return: (int) index of the newest data or -1 if no data (empty day)
  50     """
  51     for i in range(len(productions)):
  52         if productions[i]['total'] < 1000:
  53             return i - 1
  54     return len(productions) - 1  # full day
  55 
  56 
  57 def fetch_production(zone_key='TR', session=None, target_datetime=None, logger=None):
  58     """
  59     Requests the last known production mix (in MW) of a given country
  60     Arguments:
  61     zone_key (optional) -- used in case a parser is able to fetch multiple countries
  62     session (optional)      -- request session passed in order to re-use an existing session
  63     Return:
  64     A list of dictionaries in the form:
  65     {
  66       'zoneKey': 'FR',
  67       'datetime': '2017-01-01T00:00:00Z',
  68       'production': {
  69           'biomass': 0.0,
  70           'coal': 0.0,
  71           'gas': 0.0,
  72           'hydro': 0.0,
  73           'nuclear': null,
  74           'oil': 0.0,
  75           'solar': 0.0,
  76           'wind': 0.0,
  77           'geothermal': 0.0,
  78           'unknown': 0.0
  79       },
  80       'storage': {
  81           'hydro': -10.0,
  82       },
  83       'source': 'mysource.com'
  84     }
  85     """
  86     if target_datetime:
  87         raise NotImplementedError('This parser is not yet able to parse past dates')
  88 
  89     session = None  # Explicitely make a new session to avoid caching from their server...
  90     r = session or requests.session()
  91     tr_datetime = arrow.now().to('Europe/Istanbul').floor('day')
  92     response = r.get(URL, verify=False)
  93     str_data = re.search(SEARCH_DATA, response.text)
  94 
  95     production_by_hour = []
  96     if str_data:
  97         productions = json.loads(str_data.group('data'), object_hook=as_float)
  98         last_data_index = get_last_data_idx(productions)
  99         valid_production = productions[:last_data_index + 1]
  100         if last_data_index != EMPTY_DAY:
  101             for datapoint in valid_production:
  102                 data = {
  103                   'zoneKey': zone_key,
  104                   'production': {},
  105                   'storage': {},
  106                   'source': 'ytbs.teias.gov.tr',
  107                   'datetime': None
  108                 }
  109                 data['production'] = dict(zip(MAP_GENERATION.values(), [0] * len(MAP_GENERATION)))
  110                 for prod_type, prod_val in datapoint.items():
  111                     if prod_type in MAP_GENERATION.keys():
  112                         data['production'][MAP_GENERATION[prod_type]] += prod_val
  113                     elif prod_type not in ['total', 'uluslarasi', 'saat']:
  114                         logger.warning('Warning: %s (%d) is missing in mapping!' % (prod_type, prod_val))
  115 
  116                 try:
  117                     data['datetime'] = tr_datetime.replace(hour=int(datapoint['saat'])).datetime
  118                 except ValueError:
  119                     # 24 is not a valid hour!
  120                     data['datetime'] = tr_datetime.datetime
  121 
  122                 production_by_hour.append(data)
  123     else:
  124         raise Exception('Extracted data was None')
  125 
  126     return production_by_hour
  127 
  128 
  129 if __name__ == '__main__':
  130     """Main method, never used by the Electricity Map backend, but handy for testing."""
  131 
  132     print('fetch_production() ->')
  133     print(fetch_production())
  134
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/parsers/TR.py b/parsers/TR.py
  --- a/parsers/TR.py
  +++ b/parsers/TR.py
  @@ -4,12 +4,17 @@
   import re
   import json
   import arrow
  +from bs4 import BeautifulSoup
  +import datetime as dt
   
   SEARCH_DATA = re.compile(r'var gunlukUretimEgrisiData = (?P<data>.*);')
   TIMEZONE = 'Europe/Istanbul'
   URL = 'https://ytbs.teias.gov.tr/ytbs/frm_login.jsf'
   EMPTY_DAY = -1
   
  +PRICE_URL = 'https://seffaflik.epias.com.tr/transparency/piyasalar/' \
  +            'gop/ptf.xhtml'
  +
   MAP_GENERATION = {
       'akarsu': 'hydro',
       'barajli': 'hydro',
  @@ -54,6 +59,35 @@
       return len(productions) - 1  # full day
   
   
  +def fetch_price():
  +    soup = BeautifulSoup(requests.get(PRICE_URL).text, 'html.parser')
  +    cells = soup.select('.TexAlCenter')
  +
  +    # data is in td elements with class "TexAlCenter" and role "gridcell"
  +    data = list()
  +    for cell in cells:
  +        if cell.attrs.get('role', '') != 'gridcell':
  +            continue
  +        data.append(cell.text)
  +
  +    dates = [dt.datetime.strptime(val, '%d/%m/%Y').date()
  +             for i, val in enumerate(data) if i % 3 == 0]
  +    times = [dt.datetime.strptime(val, '%H:%M').time()
  +             for i, val in enumerate(data) if i % 3 == 1]
  +    prices = [float(val.replace(',', '.'))
  +              for i, val in enumerate(data) if i % 3 == 2]
  +
  +    datapoints = [{
  +        'zoneKey': 'TR',
  +        'currency': 'TRY',
  +        'datetime': arrow.get(
  +            dt.datetime.combine(date, time)).to('Europe/Istanbul').datetime,
  +        'price': price,
  +        'source': 'epias.com.tr'
  +    } for date, time, price in zip(dates, times, prices)]
  +    return datapoints
  +
  +
   def fetch_production(zone_key='TR', session=None, target_datetime=None, logger=None):
       """
       Requests the last known production mix (in MW) of a given country
  @@ -127,7 +161,10 @@
   
   
   if __name__ == '__main__':
  -    """Main method, never used by the Electricity Map backend, but handy for testing."""
  +    """Main method, never used by the Electricity Map backend, but handy for
  +    testing."""
   
       print('fetch_production() ->')
       print(fetch_production())
  +    print('fetch_price() ->')
  +    print(fetch_price())
  
verification_info: {"golden_diff": "diff --git a/parsers/TR.py b/parsers/TR.py\n--- a/parsers/TR.py\n+++ b/parsers/TR.py\n@@ -4,12 +4,17 @@\n import re\n import json\n import arrow\n+from bs4 import BeautifulSoup\n+import datetime as dt\n \n SEARCH_DATA = re.compile(r'var gunlukUretimEgrisiData = (?P<data>.*);')\n TIMEZONE = 'Europe/Istanbul'\n URL = 'https://ytbs.teias.gov.tr/ytbs/frm_login.jsf'\n EMPTY_DAY = -1\n \n+PRICE_URL = 'https://seffaflik.epias.com.tr/transparency/piyasalar/' \\\n+            'gop/ptf.xhtml'\n+\n MAP_GENERATION = {\n     'akarsu': 'hydro',\n     'barajli': 'hydro',\n@@ -54,6 +59,35 @@\n     return len(productions) - 1  # full day\n \n \n+def fetch_price():\n+    soup = BeautifulSoup(requests.get(PRICE_URL).text, 'html.parser')\n+    cells = soup.select('.TexAlCenter')\n+\n+    # data is in td elements with class \"TexAlCenter\" and role \"gridcell\"\n+    data = list()\n+    for cell in cells:\n+        if cell.attrs.get('role', '') != 'gridcell':\n+            continue\n+        data.append(cell.text)\n+\n+    dates = [dt.datetime.strptime(val, '%d/%m/%Y').date()\n+             for i, val in enumerate(data) if i % 3 == 0]\n+    times = [dt.datetime.strptime(val, '%H:%M').time()\n+             for i, val in enumerate(data) if i % 3 == 1]\n+    prices = [float(val.replace(',', '.'))\n+              for i, val in enumerate(data) if i % 3 == 2]\n+\n+    datapoints = [{\n+        'zoneKey': 'TR',\n+        'currency': 'TRY',\n+        'datetime': arrow.get(\n+            dt.datetime.combine(date, time)).to('Europe/Istanbul').datetime,\n+        'price': price,\n+        'source': 'epias.com.tr'\n+    } for date, time, price in zip(dates, times, prices)]\n+    return datapoints\n+\n+\n def fetch_production(zone_key='TR', session=None, target_datetime=None, logger=None):\n     \"\"\"\n     Requests the last known production mix (in MW) of a given country\n@@ -127,7 +161,10 @@\n \n \n if __name__ == '__main__':\n-    \"\"\"Main method, never used by the Electricity Map backend, but handy for testing.\"\"\"\n+    \"\"\"Main method, never used by the Electricity Map backend, but handy for\n+    testing.\"\"\"\n \n     print('fetch_production() ->')\n     print(fetch_production())\n+    print('fetch_price() ->')\n+    print(fetch_price())\n", "issue": "Add price to Turkey\nI am not sure which of the ticker [prices](https://www.epias.com.tr/en) to use but section 6.7.3 BLOCK ORDER BOOK in [this guide](https://www.epias.com.tr/wp-content/uploads/2017/06/INTRADAY_MARKET_USER_GUIDE_ENG_18.09.2017.pdf) may help.\n", "before_files": [{"content": "#!/usr/bin/env python3\n\nimport requests\nimport re\nimport json\nimport arrow\n\nSEARCH_DATA = re.compile(r'var gunlukUretimEgrisiData = (?P<data>.*);')\nTIMEZONE = 'Europe/Istanbul'\nURL = 'https://ytbs.teias.gov.tr/ytbs/frm_login.jsf'\nEMPTY_DAY = -1\n\nMAP_GENERATION = {\n    'akarsu': 'hydro',\n    'barajli': 'hydro',\n    'dogalgaz': 'gas',\n    'lng': 'gas',\n    'lpg': 'gas',\n    'jeotermal': 'geothermal',\n    'taskomur': 'coal',\n    'asfaltitkomur': 'coal',\n    'linyit': 'coal',\n    'ithalkomur': 'coal',\n    'ruzgar': 'wind',\n    'fueloil': 'oil',\n    'biyokutle': 'biomass',\n    'nafta': 'oil',\n    'gunes': 'solar',\n    'nukleer': 'nuclear',\n    'kojenerasyon': 'unknown',\n    'motorin': 'oil',\n}\n\n\ndef as_float(prod):\n    \"\"\"Convert json values to float and sum all production for a further use\"\"\"\n    prod['total'] = 0.0\n    if isinstance(prod, dict) and 'yuk' not in prod.keys():\n        for prod_type, prod_val in prod.items():\n            prod[prod_type] = float(prod_val)\n            prod['total'] += prod[prod_type]\n    return prod\n\n\ndef get_last_data_idx(productions):\n    \"\"\"\n    Find index of the last production\n    :param productions: list of 24 production dict objects\n    :return: (int) index of the newest data or -1 if no data (empty day)\n    \"\"\"\n    for i in range(len(productions)):\n        if productions[i]['total'] < 1000:\n            return i - 1\n    return len(productions) - 1  # full day\n\n\ndef fetch_production(zone_key='TR', session=None, target_datetime=None, logger=None):\n    \"\"\"\n    Requests the last known production mix (in MW) of a given country\n    Arguments:\n    zone_key (optional) -- used in case a parser is able to fetch multiple countries\n    session (optional)      -- request session passed in order to re-use an existing session\n    Return:\n    A list of dictionaries in the form:\n    {\n      'zoneKey': 'FR',\n      'datetime': '2017-01-01T00:00:00Z',\n      'production': {\n          'biomass': 0.0,\n          'coal': 0.0,\n          'gas': 0.0,\n          'hydro': 0.0,\n          'nuclear': null,\n          'oil': 0.0,\n          'solar': 0.0,\n          'wind': 0.0,\n          'geothermal': 0.0,\n          'unknown': 0.0\n      },\n      'storage': {\n          'hydro': -10.0,\n      },\n      'source': 'mysource.com'\n    }\n    \"\"\"\n    if target_datetime:\n        raise NotImplementedError('This parser is not yet able to parse past dates')\n\n    session = None  # Explicitely make a new session to avoid caching from their server...\n    r = session or requests.session()\n    tr_datetime = arrow.now().to('Europe/Istanbul').floor('day')\n    response = r.get(URL, verify=False)\n    str_data = re.search(SEARCH_DATA, response.text)\n\n    production_by_hour = []\n    if str_data:\n        productions = json.loads(str_data.group('data'), object_hook=as_float)\n        last_data_index = get_last_data_idx(productions)\n        valid_production = productions[:last_data_index + 1]\n        if last_data_index != EMPTY_DAY:\n            for datapoint in valid_production:\n                data = {\n                  'zoneKey': zone_key,\n                  'production': {},\n                  'storage': {},\n                  'source': 'ytbs.teias.gov.tr',\n                  'datetime': None\n                }\n                data['production'] = dict(zip(MAP_GENERATION.values(), [0] * len(MAP_GENERATION)))\n                for prod_type, prod_val in datapoint.items():\n                    if prod_type in MAP_GENERATION.keys():\n                        data['production'][MAP_GENERATION[prod_type]] += prod_val\n                    elif prod_type not in ['total', 'uluslarasi', 'saat']:\n                        logger.warning('Warning: %s (%d) is missing in mapping!' % (prod_type, prod_val))\n\n                try:\n                    data['datetime'] = tr_datetime.replace(hour=int(datapoint['saat'])).datetime\n                except ValueError:\n                    # 24 is not a valid hour!\n                    data['datetime'] = tr_datetime.datetime\n\n                production_by_hour.append(data)\n    else:\n        raise Exception('Extracted data was None')\n\n    return production_by_hour\n\n\nif __name__ == '__main__':\n    \"\"\"Main method, never used by the Electricity Map backend, but handy for testing.\"\"\"\n\n    print('fetch_production() ->')\n    print(fetch_production())\n", "path": "parsers/TR.py"}], "after_files": [{"content": "#!/usr/bin/env python3\n\nimport requests\nimport re\nimport json\nimport arrow\nfrom bs4 import BeautifulSoup\nimport datetime as dt\n\nSEARCH_DATA = re.compile(r'var gunlukUretimEgrisiData = (?P<data>.*);')\nTIMEZONE = 'Europe/Istanbul'\nURL = 'https://ytbs.teias.gov.tr/ytbs/frm_login.jsf'\nEMPTY_DAY = -1\n\nPRICE_URL = 'https://seffaflik.epias.com.tr/transparency/piyasalar/' \\\n            'gop/ptf.xhtml'\n\nMAP_GENERATION = {\n    'akarsu': 'hydro',\n    'barajli': 'hydro',\n    'dogalgaz': 'gas',\n    'lng': 'gas',\n    'lpg': 'gas',\n    'jeotermal': 'geothermal',\n    'taskomur': 'coal',\n    'asfaltitkomur': 'coal',\n    'linyit': 'coal',\n    'ithalkomur': 'coal',\n    'ruzgar': 'wind',\n    'fueloil': 'oil',\n    'biyokutle': 'biomass',\n    'nafta': 'oil',\n    'gunes': 'solar',\n    'nukleer': 'nuclear',\n    'kojenerasyon': 'unknown',\n    'motorin': 'oil',\n}\n\n\ndef as_float(prod):\n    \"\"\"Convert json values to float and sum all production for a further use\"\"\"\n    prod['total'] = 0.0\n    if isinstance(prod, dict) and 'yuk' not in prod.keys():\n        for prod_type, prod_val in prod.items():\n            prod[prod_type] = float(prod_val)\n            prod['total'] += prod[prod_type]\n    return prod\n\n\ndef get_last_data_idx(productions):\n    \"\"\"\n    Find index of the last production\n    :param productions: list of 24 production dict objects\n    :return: (int) index of the newest data or -1 if no data (empty day)\n    \"\"\"\n    for i in range(len(productions)):\n        if productions[i]['total'] < 1000:\n            return i - 1\n    return len(productions) - 1  # full day\n\n\ndef fetch_price():\n    soup = BeautifulSoup(requests.get(PRICE_URL).text, 'html.parser')\n    cells = soup.select('.TexAlCenter')\n\n    # data is in td elements with class \"TexAlCenter\" and role \"gridcell\"\n    data = list()\n    for cell in cells:\n        if cell.attrs.get('role', '') != 'gridcell':\n            continue\n        data.append(cell.text)\n\n    dates = [dt.datetime.strptime(val, '%d/%m/%Y').date()\n             for i, val in enumerate(data) if i % 3 == 0]\n    times = [dt.datetime.strptime(val, '%H:%M').time()\n             for i, val in enumerate(data) if i % 3 == 1]\n    prices = [float(val.replace(',', '.'))\n              for i, val in enumerate(data) if i % 3 == 2]\n\n    datapoints = [{\n        'zoneKey': 'TR',\n        'currency': 'TRY',\n        'datetime': arrow.get(\n            dt.datetime.combine(date, time)).to('Europe/Istanbul').datetime,\n        'price': price,\n        'source': 'epias.com.tr'\n    } for date, time, price in zip(dates, times, prices)]\n    return datapoints\n\n\ndef fetch_production(zone_key='TR', session=None, target_datetime=None, logger=None):\n    \"\"\"\n    Requests the last known production mix (in MW) of a given country\n    Arguments:\n    zone_key (optional) -- used in case a parser is able to fetch multiple countries\n    session (optional)      -- request session passed in order to re-use an existing session\n    Return:\n    A list of dictionaries in the form:\n    {\n      'zoneKey': 'FR',\n      'datetime': '2017-01-01T00:00:00Z',\n      'production': {\n          'biomass': 0.0,\n          'coal': 0.0,\n          'gas': 0.0,\n          'hydro': 0.0,\n          'nuclear': null,\n          'oil': 0.0,\n          'solar': 0.0,\n          'wind': 0.0,\n          'geothermal': 0.0,\n          'unknown': 0.0\n      },\n      'storage': {\n          'hydro': -10.0,\n      },\n      'source': 'mysource.com'\n    }\n    \"\"\"\n    if target_datetime:\n        raise NotImplementedError('This parser is not yet able to parse past dates')\n\n    session = None  # Explicitely make a new session to avoid caching from their server...\n    r = session or requests.session()\n    tr_datetime = arrow.now().to('Europe/Istanbul').floor('day')\n    response = r.get(URL, verify=False)\n    str_data = re.search(SEARCH_DATA, response.text)\n\n    production_by_hour = []\n    if str_data:\n        productions = json.loads(str_data.group('data'), object_hook=as_float)\n        last_data_index = get_last_data_idx(productions)\n        valid_production = productions[:last_data_index + 1]\n        if last_data_index != EMPTY_DAY:\n            for datapoint in valid_production:\n                data = {\n                  'zoneKey': zone_key,\n                  'production': {},\n                  'storage': {},\n                  'source': 'ytbs.teias.gov.tr',\n                  'datetime': None\n                }\n                data['production'] = dict(zip(MAP_GENERATION.values(), [0] * len(MAP_GENERATION)))\n                for prod_type, prod_val in datapoint.items():\n                    if prod_type in MAP_GENERATION.keys():\n                        data['production'][MAP_GENERATION[prod_type]] += prod_val\n                    elif prod_type not in ['total', 'uluslarasi', 'saat']:\n                        logger.warning('Warning: %s (%d) is missing in mapping!' % (prod_type, prod_val))\n\n                try:\n                    data['datetime'] = tr_datetime.replace(hour=int(datapoint['saat'])).datetime\n                except ValueError:\n                    # 24 is not a valid hour!\n                    data['datetime'] = tr_datetime.datetime\n\n                production_by_hour.append(data)\n    else:\n        raise Exception('Extracted data was None')\n\n    return production_by_hour\n\n\nif __name__ == '__main__':\n    \"\"\"Main method, never used by the Electricity Map backend, but handy for\n    testing.\"\"\"\n\n    print('fetch_production() ->')\n    print(fetch_production())\n    print('fetch_price() ->')\n    print(fetch_price())\n", "path": "parsers/TR.py"}]}