{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import dependencies\n",
    "from elasticsearch import Elasticsearch\n",
    "import wikipediaapi\n",
    "from slugify import slugify\n",
    "from pprint import pprint\n",
    "from bs4 import BeautifulSoup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "client = Elasticsearch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'pandemics': {'aliases': {}},\n",
       " 'american-science-fiction-television-series': {'aliases': {}},\n",
       " 'coronaviridae': {'aliases': {}},\n",
       " 'machine-learning': {'aliases': {}},\n",
       " 'science-fiction-television': {'aliases': {}},\n",
       " 'presidents-of-the-united-states': {'aliases': {}},\n",
       " 'american-comics-writers': {'aliases': {}},\n",
       " 'marvel-comics-editors-in-chief': {'aliases': {}},\n",
       " 'natural-language-processing': {'aliases': {}},\n",
       " 'marvel-comics': {'aliases': {}}}"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.indices.get_alias(\"\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "categories = ['Presidents of the United States', \n",
    "              'Marvel Comics', \n",
    "              'American comics writers',\n",
    "              'Marvel Comics editors-in-chief',\n",
    "              'Machine learning',\n",
    "              'Natural language processing',\n",
    "              'Coronaviridae',\n",
    "              '21st-century American comedians',\n",
    "              'Pandemics']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create a simple index called \"wikipedia-simple\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "client = Elasticsearch() # defaults to localhost:9200, but can be anything like networkname:9200"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "body = {\"title\": \"Natural language processing\",\n",
    "       \"source\": \"https://en.wikipedia.org/wiki/Natural_language_processing\",\n",
    "        \"page_id\": 21652,\n",
    "        \"text\": [{section1}, {section2}, {section3}, ...],\n",
    "        \"refernces\": [{section1}, {section2}, {section3}, ...]}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "mapping = {\n",
    "    \"properties\": {\n",
    "        \n",
    "            \"text\": {\n",
    "                \"type\": \"nested\",\n",
    "                \"properties\":{\n",
    "                    \"section_num\": {\"type\":\"integer\"},\n",
    "                    \"section_title\": {\"type\":\"text\"},\n",
    "                    \"section_content\": {\"type\":\"text\"}\n",
    "                }\n",
    "            },\n",
    "        \n",
    "            \"title\": {\n",
    "                \"type\": \"text\"\n",
    "            },\n",
    "        \n",
    "            \"source\": {\n",
    "                \"type\": \"text\"\n",
    "            },\n",
    "        \n",
    "            \"page_id\": {\n",
    "                \"type\": \"long\"\n",
    "            },\n",
    "            \n",
    "        }\n",
    "    }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'acknowledged': True,\n",
       " 'shards_acknowledged': True,\n",
       " 'index': 'wikipedia-nested'}"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.indices.create(index=\"wikipedia-nested\", body={\"mappings\": mapping})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "client.index(index=\"wikipedia-simple\", body=body)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Document:\n",
    "    \n",
    "    def __init__(self):\n",
    "        self.title = ''\n",
    "        self.page_id = None\n",
    "        self.source = ''\n",
    "        self.text = ''\n",
    "        \n",
    "    def __if_exists(self, page_id):\n",
    "        '''\n",
    "        A private method to check if the article already exists in the database\n",
    "        with a goal to avoid duplication\n",
    "        '''\n",
    "        \n",
    "        return client.search(index=self.index, \n",
    "                             body={\"query\": \n",
    "                                   {\"match\": \n",
    "                                    {\"page_id\": page_id}\n",
    "                                   }})['hits']['total']['value']\n",
    "        \n",
    "    def insert(self, title, page_id, url, text, index):\n",
    "        ''' Add a new document to the index'''\n",
    "        \n",
    "        self.index = index\n",
    "        self.title=title\n",
    "        self.page_id=page_id\n",
    "        self.source=url\n",
    "        self.text=text\n",
    "        self.body = {'title': self.title,\n",
    "            'page_id': self.page_id,\n",
    "            'source':self.source,\n",
    "            'text': self.text}\n",
    "        \n",
    "        if not self.__if_exists(page_id):\n",
    "        \n",
    "            try:\n",
    "                client.index(index=index, body=self.body)\n",
    "#                 print(f\"Sucess! The article {self.title} was added to index {index}\")\n",
    "            except error:\n",
    "                print(\"Something went wrong\", error)\n",
    "                \n",
    "        else:\n",
    "            print(f\"Article {self.title} is already in the database\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Article Los Bros Hernandez is already in the database\n",
      "Article C. B. Cebulski is already in the database\n",
      "Article Gerry Conway is already in the database\n",
      "Article Tom DeFalco is already in the database\n",
      "Article Stan Lee is already in the database\n",
      "Article Jim Shooter is already in the database\n",
      "Article Joe Simon is already in the database\n",
      "Article Roy Thomas is already in the database\n",
      "Article Len Wein is already in the database\n",
      "Article Marv Wolfman is already in the database\n",
      "Article Under-fitting is already in the database\n",
      "Article Underfitting is already in the database\n",
      "Article Validation set is already in the database\n",
      "Article Bag-of-words model is already in the database\n",
      "Article Deeplearning4j is already in the database\n",
      "Article Document classification is already in the database\n",
      "Article Documenting Hate is already in the database\n",
      "Article Grammar induction is already in the database\n",
      "Article Multimodal sentiment analysis is already in the database\n",
      "Article Native-language identification is already in the database\n",
      "Article Semantic folding is already in the database\n",
      "Article Coronavirinae is already in the database\n",
      "Article Sean Clements is already in the database\n",
      "Article Ernest Cline is already in the database\n",
      "Article Hayes Davenport is already in the database\n",
      "Article Adam Felber is already in the database\n",
      "Article Rashida Jones is already in the database\n",
      "Article Taran Killam is already in the database\n",
      "Article Steve Melcher is already in the database\n",
      "Article Patton Oswalt is already in the database\n",
      "Article Brian Posehn is already in the database\n",
      "Article Carlos Saldaña is already in the database\n",
      "Article Rob Schrab is already in the database\n",
      "Article Larry Siegel is already in the database\n",
      "Article Kevin Smith is already in the database\n",
      "Article Johns Hopkins Center for Health Security is already in the database\n"
     ]
    }
   ],
   "source": [
    "def simple_wiki_doc(category):\n",
    "    \n",
    "    if type(category) is not list: category = [ category ]\n",
    "\n",
    "    wiki_wiki = wikipediaapi.Wikipedia('en')\n",
    "    \n",
    "    for c in category:\n",
    "\n",
    "        cat = wiki_wiki.page(f\"Category:{c}\")\n",
    "\n",
    "        for key in cat.categorymembers.keys():\n",
    "            page = wiki_wiki.page(key)\n",
    "\n",
    "            if not \"Category:\" in page.title:\n",
    "                \n",
    "                doc = Document()\n",
    "                doc.insert(page.title, page.pageid, page.fullurl, page.text, index=\"wikipedia-simple\")\n",
    "                \n",
    "simple_wiki_doc(categories)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"AlphaGo\"\n",
    "\n",
    "# body = {\n",
    "#         \"query\": {\n",
    "#             \"bool\": {\n",
    "#                 \"should\": [{\n",
    "#                     \"match\": {\"title\": {'query': query, \"lenient\": 'true', \"boost\": 3}}}, {\n",
    "#                     \"nested\": {\n",
    "#                         \"path\": \"text\", \"query\": {\n",
    "#                             \"bool\": {\n",
    "#                                 \"should\": [{\n",
    "#                                     \"term\": {\"text.section_num\": 0}}, {\n",
    "#                                     \"match\": {\"text.section_content\": query}}\n",
    "#                                 ]\n",
    "#                             }\n",
    "#                         },\n",
    "#     \"inner_hits\": {\n",
    "#         \"highlight\": {\n",
    "#             \"fields\": {\n",
    "#                 \"text.section_content\": {\"number_of_fragments\": 3, 'order': \"score\"}}\n",
    "#         }\n",
    "#     }\n",
    "#                     }}\n",
    "#                 ]\n",
    "#             }\n",
    "#         }\n",
    "#     }\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'query': {'nested': {'path': 'text',\n",
      "                      'query': {'bool': {'should': [{'match': {'text.section_content': 'AlphaGo'}},\n",
      "                                                    {'match': {'text.section_title': 'Summary'}}]}}}}}\n"
     ]
    }
   ],
   "source": [
    "pprint(body)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "def search(index = '', text=\"coronavirus\"):  \n",
    "\n",
    "    # client = Elasticsearch(\"elasticsearch:9200\")\n",
    "    client = Elasticsearch(\"localhost:9200\")\n",
    "    \n",
    "#     body = {\n",
    "#     \"query\": {\n",
    "#         \"bool\": {\n",
    "#             \"should\": [\n",
    "#                 {\"match\": {\"title\": {\n",
    "#                     'query': text,\n",
    "#                     \"boost\":3\n",
    "#                 }}},\n",
    "#                 {\n",
    "#                     \"nested\": {\n",
    "#                         \"path\": \"text\",\n",
    "#                         \"query\": {\n",
    "#                             \"bool\": {\n",
    "#                                 \"should\": [\n",
    "#                                     {\"term\": { \"text.section_num\": 0 }},\n",
    "#                                     { \"match\": { \"text.section_content\":  text }}\n",
    "#                                 ]\n",
    "#                             }\n",
    "#                         },\n",
    "#                         \"inner_hits\":{\n",
    "#                             \"highlight\": {\n",
    "#                                 \"fields\": {\"text.section_content\": {\"number_of_fragments\" : 1, 'fragment_size':200, 'order': \"score\"}}\n",
    "#                             }\n",
    "#                         }\n",
    "#                     }\n",
    "#                 }\n",
    "\n",
    "#             ]\n",
    "#         }\n",
    "#     }\n",
    "#     }\n",
    "\n",
    "    body = {\n",
    "        \"query\": {\n",
    "            \"bool\": {\n",
    "                \"should\": [{\n",
    "                    \"match\": {\"title\": {'query': text, \"lenient\": 'true', \"boost\": 3}}}, {\n",
    "                    \"nested\": {\n",
    "                        \"path\": \"text\", \"query\": {\n",
    "                            \"bool\": {\n",
    "                                \"should\": [{\n",
    "                                    \"term\": {\"text.section_num\": 0}}, {\n",
    "                                    \"match\": {\"text.section_content\": text}}\n",
    "                                ]\n",
    "                            }\n",
    "                        },\n",
    "    \"inner_hits\": {\n",
    "        \"highlight\": {\n",
    "            \"fields\": {\n",
    "                \"text.section_content\": {\"number_of_fragments\": 3, \n",
    "                                         \"fragment_size\":250,\n",
    "                                         \"order\": \"score\"}}\n",
    "        }}}}\n",
    "                ]\n",
    "            }\n",
    "        }\n",
    "    }\n",
    "\n",
    "\n",
    "    \"\"\" Full text search within an ElasticSearch index (''=all indexes) for the indicated text \"\"\"\n",
    "    return client.search(index=index,\n",
    "                         body=body)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [],
   "source": [
    "def search(index = '', text=\"coronavirus\"):  \n",
    "\n",
    "    # client = Elasticsearch(\"elasticsearch:9200\")\n",
    "    client = Elasticsearch(\"localhost:9200\")\n",
    "    \n",
    "#     body = {\n",
    "#     \"query\": {\n",
    "#         \"bool\": {\n",
    "#             \"should\": [\n",
    "#                 {\"match\": {\"title\": {\n",
    "#                     'query': text,\n",
    "#                     \"boost\":3\n",
    "#                 }}},\n",
    "#                 {\n",
    "#                     \"nested\": {\n",
    "#                         \"path\": \"text\",\n",
    "#                         \"query\": {\n",
    "#                             \"bool\": {\n",
    "#                                 \"should\": [\n",
    "#                                     {\"term\": { \"text.section_num\": 0 }},\n",
    "#                                     { \"match\": { \"text.section_content\":  text }}\n",
    "#                                 ]\n",
    "#                             }\n",
    "#                         },\n",
    "#                         \"inner_hits\":{\n",
    "#                             \"highlight\": {\n",
    "#                                 \"fields\": {\"text.section_content\": {\"number_of_fragments\" : 1, 'fragment_size':200, 'order': \"score\"}}\n",
    "#                             }\n",
    "#                         }\n",
    "#                     }\n",
    "#                 }\n",
    "\n",
    "#             ]\n",
    "#         }\n",
    "#     }\n",
    "#     }\n",
    "\n",
    "    body = {\n",
    "        \"query\": {\n",
    "            \"bool\": {\n",
    "                \"should\": [{\n",
    "                    \"match\": {\"title\": {'query': text, \"lenient\": 'true', \"boost\": 3}}}, {\n",
    "                    \"nested\": {\n",
    "                        \"path\": \"text\", \"query\": {\n",
    "                            \"bool\": {\n",
    "                                \"should\": [{\n",
    "                                    \"term\": {\"text.section_num\": 0}}, {\n",
    "                                    \"match\": {\"text.section_content\": text}}\n",
    "                                ]\n",
    "                            }\n",
    "                        },\n",
    "    \"inner_hits\": {\n",
    "        \"highlight\": {\n",
    "            \"fields\": {\n",
    "                \"text.section_content\": {\"number_of_fragments\": 3, 'order': \"score\"}}\n",
    "        }\n",
    "    }\n",
    "                    }}\n",
    "                ]\n",
    "            }\n",
    "        }\n",
    "    }\n",
    "\n",
    "\n",
    "    \"\"\" Full text search within an ElasticSearch index (''=all indexes) for the indicated text \"\"\"\n",
    "    return client.search(index=index,\n",
    "                         body=body)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "def get_highlights(statement):\n",
    "    query = search(text=statement)\n",
    "    results = []\n",
    "\n",
    "    for doc in query['hits']['hits']:\n",
    "\n",
    "        for highlight in doc['inner_hits']['text']['hits']['hits']:\n",
    "\n",
    "            try:\n",
    "                snippet = ' '.join(highlight['highlight']['text.section_content']),\n",
    "                snippet_soup = BeautifulSoup(snippet[0])\n",
    "                mytuple = (doc['_source']['title'],\n",
    "                            doc['_score'],\n",
    "                            doc['_source']['source'],\n",
    "                            snippet_soup.get_text(),\n",
    "                            highlight['_source']['section_num'],\n",
    "                            highlight['_source']['section_title'],\n",
    "                            highlight['_score'],\n",
    "                            highlight['_source']['section_content'],\n",
    "                            doc['_source']['page_id'])\n",
    "\n",
    "                results.append(mytuple)\n",
    "\n",
    "            except:  # noqa\n",
    "                pass\n",
    "\n",
    "    return results\n",
    "\n",
    "hl = get_highlights(\"What is natural language processing?\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Natural language processing https://en.wikipedia.org/wiki/Natural_language_processing 21652\n",
      "Natural language processing https://en.wikipedia.org/wiki/Natural_language_processing 21652\n",
      "Natural language processing https://en.wikipedia.org/wiki/Natural_language_processing 21652\n",
      "Cognitive Natural Language Processing https://en.wikipedia.org/wiki/Cognitive_Natural_Language_Processing 63587118\n",
      "Cognitive Natural Language Processing https://en.wikipedia.org/wiki/Cognitive_Natural_Language_Processing 63587118\n",
      "Cognitive Natural Language Processing https://en.wikipedia.org/wiki/Cognitive_Natural_Language_Processing 63587118\n",
      "History of natural language processing https://en.wikipedia.org/wiki/History_of_natural_language_processing 27837170\n",
      "History of natural language processing https://en.wikipedia.org/wiki/History_of_natural_language_processing 27837170\n",
      "Studies in Natural Language Processing https://en.wikipedia.org/wiki/Studies_in_Natural_Language_Processing 6650456\n",
      "Outline of natural language processing https://en.wikipedia.org/wiki/Outline_of_natural_language_processing 37764426\n",
      "Outline of natural language processing https://en.wikipedia.org/wiki/Outline_of_natural_language_processing 37764426\n",
      "Outline of natural language processing https://en.wikipedia.org/wiki/Outline_of_natural_language_processing 37764426\n",
      "Data pre-processing https://en.wikipedia.org/wiki/Data_pre-processing 12386904\n",
      "Data pre-processing https://en.wikipedia.org/wiki/Data_pre-processing 12386904\n",
      "Data pre-processing https://en.wikipedia.org/wiki/Data_pre-processing 12386904\n",
      "Semantic decomposition (natural language processing) https://en.wikipedia.org/wiki/Semantic_decomposition_(natural_language_processing) 57932194\n",
      "Semantic decomposition (natural language processing) https://en.wikipedia.org/wiki/Semantic_decomposition_(natural_language_processing) 57932194\n",
      "Semantic decomposition (natural language processing) https://en.wikipedia.org/wiki/Semantic_decomposition_(natural_language_processing) 57932194\n",
      "Empirical Methods in Natural Language Processing https://en.wikipedia.org/wiki/Empirical_Methods_in_Natural_Language_Processing 43771647\n",
      "Native-language identification https://en.wikipedia.org/wiki/Native-language_identification 45627703\n",
      "Native-language identification https://en.wikipedia.org/wiki/Native-language_identification 45627703\n",
      "Native-language identification https://en.wikipedia.org/wiki/Native-language_identification 45627703\n",
      "Natural language https://en.wikipedia.org/wiki/Natural_language 21173\n",
      "Natural language https://en.wikipedia.org/wiki/Natural_language 21173\n",
      "Natural language https://en.wikipedia.org/wiki/Natural_language 21173\n"
     ]
    }
   ],
   "source": [
    "for h in hl:\n",
    "    print(h[0],h[2], h[8])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Obama was elected over Republican John McCain and was inaugurated on January 20, 2009. Nine months later, he was named the 2009 Nobel Peace Prize laureate.'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "soup.get_text()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def search(index = '', text=\"coronavirus\"):  \n",
    "\n",
    "    # client = Elasticsearch(\"elasticsearch:9200\")\n",
    "    client = Elasticsearch(\"localhost:9200\")\n",
    "\n",
    "body={\"query\":{\"bool\":{\"should\":[{\"match\":{\"title\":{'query':text,\"boost\":3}}},{\"nested\":{\"path\":\"text\",\"query\":{\"bool\":{\"should\":[{\"term\":{ \"text.section_num\":0}},{\"match\":{\"text.section_content\":text}}]}},\"inner_hits\":{\"highlight\":{\"fields\":{\"text.section_content\":{\"number_of_fragments\":1,'fragment_size':200,\"order\":\"score\"}}}}}}]}}}\n",
    "\n",
    "\n",
    "    \"\"\" Full text search within an ElasticSearch index (''=all indexes) for the indicated text \"\"\"\n",
    "    return client.search(index=index,\n",
    "                         body=body)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'took': 3,\n",
       " 'timed_out': False,\n",
       " '_shards': {'total': 10, 'successful': 10, 'skipped': 0, 'failed': 0},\n",
       " 'hits': {'total': {'value': 1, 'relation': 'eq'},\n",
       "  'max_score': 1.0,\n",
       "  'hits': [{'_index': 'presidents-of-the-united-states',\n",
       "    '_type': '_doc',\n",
       "    '_id': 'dHVyZ3EBC2bMrelm0kGo',\n",
       "    '_score': 1.0,\n",
       "    '_source': {'title': 'Barack Obama',\n",
       "     'page_id': 534366,\n",
       "     'source': 'https://en.wikipedia.org/wiki/Barack_Obama',\n",
       "     'text': [{'section_num': 0,\n",
       "       'section_title': 'Summary',\n",
       "       'section_content': 'Barack Hussein Obama II ( (listen); born August 4, 1961) is an American politician and attorney who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, he was the first African-American president of the United States. He previously served as a U.S. senator from Illinois from 2005 to 2008 and an Illinois state senator from 1997 to 2004.\\nObama was born in Honolulu, Hawaii. After graduating from Columbia University in 1983, he worked as a community organizer in Chicago. In 1988, he enrolled in Harvard Law School, where he was the first black person to head the Harvard Law Review. After graduating, he became a civil rights attorney and an academic, teaching constitutional law at the University of Chicago Law School from 1992 to 2004. Turning to elective politics, he represented the 13th district from 1997 until 2004 in the Illinois Senate, when he ran for the U.S. Senate. Obama received national attention in 2004 with his March Senate-primary win, his well-received July Democratic National Convention keynote address, and his landslide November election to the Senate. In 2008, he was nominated for president a year after his presidential campaign began, and after close primary campaigns against Hillary Clinton. Obama was elected over Republican John McCain and was inaugurated on January 20, 2009. Nine months later, he was named the 2009 Nobel Peace Prize laureate.\\nObama signed many landmark bills into law during his first two years in office. The main reforms that were passed include the Patient Protection and Affordable Care Act (commonly referred to as the \"Affordable Care Act\" or \"Obamacare\"), the Dodd–Frank Wall Street Reform and Consumer Protection Act, and the Don\\'t Ask, Don\\'t Tell Repeal Act of 2010. The American Recovery and Reinvestment Act of 2009 and Tax Relief, Unemployment Insurance Reauthorization, and Job Creation Act of 2010 served as economic stimulus amidst the Great Recession. After a lengthy debate over the national debt limit, he signed the Budget Control and the American Taxpayer Relief Acts. In foreign policy, he increased U.S. troop levels in Afghanistan, reduced nuclear weapons with the United States–Russia New START treaty, and ended military involvement in the Iraq War. He ordered military involvement in Libya, contributing to the overthrow of Muammar Gaddafi. He also ordered the military operations that resulted in the deaths of Osama bin Laden and suspected Yemeni Al-Qaeda operative Anwar al-Awlaki.\\nAfter winning re-election by defeating Republican opponent Mitt Romney, Obama was sworn in for a second term in 2013. During this term, he promoted inclusion for LGBT Americans. His administration filed briefs that urged the Supreme Court to strike down same-sex marriage bans as unconstitutional (United States v. Windsor and Obergefell v. Hodges); same-sex marriage was legalized nationwide in 2015 after the Court ruled so in Obergefell. He advocated for gun control in response to the Sandy Hook Elementary School shooting, indicating support for a ban on assault weapons, and issued wide-ranging executive actions concerning global warming and immigration. In foreign policy, he ordered military intervention in Iraq in response to gains made by ISIL after the 2011 withdrawal from Iraq, continued the process of ending U.S. combat operations in Afghanistan in 2016, promoted discussions that led to the 2015 Paris Agreement on global climate change, initiated sanctions against Russia following the invasion in Ukraine and again after Russian interference in the 2016 United States elections, brokered a nuclear deal with Iran, and normalized U.S. relations with Cuba. Obama nominated three justices to the Supreme Court: Sonia Sotomayor and Elena Kagan were confirmed as justices, while Merrick Garland faced partisan obstruction and was not confirmed. During his term in office, America\\'s reputation abroad significantly improved.Obama\\'s presidency has generally been regarded favorably, and evaluations of his presidency among historians, political scientists, and the general public place him among the upper tier of American presidents. Obama left office in January 2017 but continues to reside in Washington, D.C.'},\n",
       "      {'section_num': 8,\n",
       "       'section_title': 'Notes and references',\n",
       "       'section_content': '\\nNotes\\nReferences\\nFurther reading\\nExternal links\\nOfficial\\nOfficial website of The Obama Foundation\\nOfficial website of the Barack Obama Presidential Library\\nOfficial website of Organizing for Action\\nWhite House biography\\n\\nOther\\nColumn archive at The Huffington Post\\nBarack Obama at the Encyclopædia Britannica\\nObama B. \"United States Health Care Reform: Progress to Date and Next Steps\". JAMA. Published online July 11, 2016. doi:10.1001/jama.2016.9797.\\nTeague Beckwith, Ryan (March 23, 2017). \"Read Barack Obama\\'s Statement on the Anniversary of Obamacare\". Time magazine. Archived from the original on March 31, 2017. Retrieved March 31, 2017. See also: Taylor, Jessica (March 23, 2017). \"Obama: \\'America Is Stronger Because Of The Affordable Care Act\\'\". National Public Radio. Archived from the original on March 31, 2017. Retrieved March 31, 2017.\\nObama B. \"The President\\'s Role in Advancing Criminal Justice Reform\". Harvard Law Review. Published January 5, 2017.\\nBarack Obama at Curlie\\n\\nUnited States Congress. \"Barack Obama (id: O000167)\". Biographical Directory of the United States Congress.\\nAppearances on C-SPAN\\nBarack Obama articles in the archive of the Chicago Tribune\\nCollected news and commentary at the Tampa Bay Times\\'s PolitiFact.com\\nCollected news and commentary at The Washington Post\\'s Fact Checker blog\\n\"Barack Obama is officially one of the most consequential presidents in American history\" by Vox author Dylan Matthews on March 24, 2017. Archived from the original on March 24, 2017. Retrieved April 2, 2017. The article describes the successes and failures of Barack Obama\\'s domestic and foreign policy as well as provides articles for further reading in this context.\\nMaking Obama. Making. 2018. WBEZ. \"Former President Barack Obama—along with key advisers, mentors, and rivals—tells the story of his climb from Chicago to the national stage.\"\\nWorks by Barack Obama at Project Gutenberg\\nWorks by or about Barack Obama at Internet Archive\\nWorks by Barack Obama at LibriVox (public domain audiobooks) \\nBarack Obama on IMDb \\nBarack Obama at TV.com'},\n",
       "      {'section_num': 5,\n",
       "       'section_title': 'Legacy',\n",
       "       'section_content': '\\nObama\\'s most significant legacy is generally considered to be the Patient Protection and Affordable Care Act (PPACA), provisions of which went into effect from 2010 to 2020. Many attempts by Senate Republicans to repeal the PPACA, including a \"skinny repeal,\" have thus far failed. Together with the Health Care and Education Reconciliation Act amendment, it represents the U.S. healthcare system\\'s most significant regulatory overhaul and expansion of coverage since the passage of Medicare and Medicaid in 1965.Many commentators credit Obama with averting a threatened depression and pulling the economy back from the Great Recession. According to the U.S. Bureau of Labor Statistics, the Obama administration created 11.3 million jobs from the month after his first inauguration to the end of his term. In 2010, Obama signed into effect the Dodd–Frank Wall Street Reform and Consumer Protection Act. Passed as a response to the financial crisis of 2007–08, it brought the most significant changes to financial regulation in the United States since the regulatory reform that followed the Great Depression under Democratic President Franklin D. Roosevelt.In 2009, Obama signed into law the National Defense Authorization Act for Fiscal Year 2010, which contained in it the Matthew Shepard and James Byrd Jr. Hate Crimes Prevention Act, the first addition to existing federal hate crime law in the United States since Democratic President Bill Clinton signed into law the Church Arson Prevention Act of 1996. The Matthew Shepard and James Byrd Jr. Hate Crimes Prevention Act expanded existing federal hate crime laws in the United States to apply to crimes motivated by a victim\\'s actual or perceived gender, sexual orientation, gender identity, or disability, and dropped the prerequisite that the victim be engaging in a federally protected activity.\\nAs president, Obama advanced LGBT rights. In 2010, he signed the Don\\'t Ask, Don\\'t Tell Repeal Act, which brought an end to \"don\\'t ask, don\\'t tell\" policy in the U.S. armed forces that banned open service from LGB people; the law went into effect the following year. In 2016, his administration brought an end to the ban on transgender people serving openly in the U.S. armed forces. A Gallup poll, taken in the final days of Obama\\'s term, showed that 68% of Americans believed the U.S. had made progress in the situation for gays and lesbians during Obama\\'s eight years in office.Obama substantially escalated the use of drone strikes against suspected militants and terrorists associated with al-Qaeda and the Taliban. In 2016, the last year of his presidency, the US dropped 26,171 bombs on seven different countries. Obama left about 8,400 US troops in Afghanistan, 5,262 in Iraq, 503 in Syria, 133 in Pakistan, 106 in Somalia, seven in Yemen, and two in Libya at the end of his presidency.According to Pew Research Center and United States Bureau of Justice Statistics, from December 31, 2009, to December 31, 2015, inmates sentenced in US federal custody declined by five percent. This is the largest decline in sentenced inmates in US federal custody since Democratic President Jimmy Carter. By contrast, the federal prison population increased significantly under presidents Ronald Reagan, George H. W. Bush, Bill Clinton, and George W. Bush.Obama left office in January 2017 with a 60% approval rating. A 2018 survey of historians by the American Political Science Association ranked Obama the 8th-greatest American President. Obama gained 10 spots from the same survey in 2015 from the Brookings Institution that ranked Obama the 18th-greatest American President.\\n\\nPresidential library\\nThe Barack Obama Presidential Center is Obama\\'s planned presidential library. It will be hosted by the University of Chicago and located in Jackson Park on the South Side of Chicago.'},\n",
       "      {'section_num': 4,\n",
       "       'section_title': 'Post-presidency (2017–present)',\n",
       "       'section_content': '\\nObama\\'s presidency ended at noon on January 20, 2017, immediately following the inauguration of his Republican successor, Donald Trump. After the inauguration, Obama lifted off on Executive One, circled the White House, and flew to Joint Base Andrews. The family currently rents a house in Kalorama, Washington, D.C.On March 2, 2017, the John F. Kennedy Presidential Library and Museum awarded the annual Profile in Courage Award to Obama \"for his enduring commitment to democratic ideals and elevating the standard of political courage.\" In his first public appearance out of office, Obama appeared at a seminar at the University of Chicago on April 24. The seminar was aimed at the engagement with a new generation as well as an appeal for their participation in politics. On May 4, three days ahead of the French presidential election, Obama publicly endorsed Emmanuel Macron: \"He appeals to people\\'s hopes and not their fears, and I enjoyed speaking to Emmanuel recently to hear about his independent movement and his vision for the future of France.\" Macron went on to win the election.\\nWhile in Berlin on May 25, Obama made a joint public appearance with Chancellor Angela Merkel where he stressed inclusion and for leaders to question themselves, Obama having been formally invited to Berlin while still in office as part of an effort to boost Merkel\\'s re-election campaign. Obama traveled to Kensington Palace in England and met with Prince Harry on May 27, 2017; Obama tweeted afterward that the two discussed their foundations and offering condolences in the wake of the Manchester Arena bombing that occurred five days prior.After President Trump announced his withdrawal of the United States from the Paris Agreement on June 1, Obama released a statement disagreeing with the choice: \"But even in the absence of American leadership; even as this administration joins a small handful of nations that reject the future; I\\'m confident that our states, cities, and businesses will step up and do even more to lead the way, and help protect for future generations the one planet we\\'ve got.\"\\n\\nAfter Senate Republicans revealed the Better Care Reconciliation Act of 2017, their discussion draft of a health care bill to replace the Affordable Care Act, on June 22, Obama released a Facebook post calling the bill \"a massive transfer of wealth from middle-class and poor families to the richest people in America.\" On September 19, while delivering the keynote address at Goalkeepers, Obama admitted his frustration with Republicans backing \"a bill that will raise costs, reduce coverage, and roll back protections for older Americans and people with pre-existing conditions.\"After Attorney General Jeff Sessions announced the termination of the Deferred Action for Childhood Arrivals (DACA) program on September 5, Obama released a Facebook post criticizing the decision. Two days later, he partnered with former presidents Jimmy Carter, George H. W. Bush, Bill Clinton, and George W. Bush to work with One America Appeal to help the victims of Hurricane Harvey and Hurricane Irma in the Gulf Coast and Texas communities.Obama hosted the inaugural summit of the Obama Foundation in Chicago on October 31. Obama intends for the foundation to be the central focus of his post-presidency and part of his ambitions for his subsequent activities following his presidency to be more consequential than his time in office. Obama has also been working on a Presidential memoir, in a reported $65 million deal with Penguin Random House.Obama went on an international trip from November 28 to December 2, 2017, and visited China, India and France. In China, he delivered remarks at the Global Alliance of SMEs Summit in Shanghai and met with Chinese President Xi Jinping in Beijing. He then went to India, where he spoke at the Hindustan Times Leadership Summit before meeting with Indian Prime Minister Narendra Modi over lunch. In addition, he held a town hall for young leaders, organized by the Obama Foundation. He also met with the Dalai Lama while in New Delhi. He ended his five-day trip in France where he met with French President Emmanuel Macron, former President Francois Hollande and Paris Mayor Anne Hidalgo and then spoke at an invitation-only event, touching on climate issues.Barack and Michelle Obama signed a deal on May 22, 2018 to produce docu-series, documentaries and features for Netflix under the Obamas\\' newly formed production company, Higher Ground Productions. On the deal, Michelle said \"I have always believed in the power of storytelling to inspire us, to make us think differently about the world around us, and to help us open our minds and hearts to others.\" Higher Ground\\'s first film, American Factory, won the Best Documentary Oscar in 2020.A package that contained a pipe bomb was sent to Obama\\'s home in Washington, D.C, on October 24, 2018. The package was intercepted by the Secret Service during routine mail screenings. Similar packages were sent to several other Democratic leaders, mostly those who voiced strong objections to the policies of Donald Trump and to CNN. Debbie Wasserman Schultz was addressed as the sender of the package. On October 26, 2018, Cesar Sayoc was arrested and faces five federal charges in Manhattan carrying a combined maximum sentence of 48 years behind bars in relation to the pipe bombs.In 2019, Barack and Michelle Obama bought a home on Martha\\'s Vineyard from Wyc Grousbeck.'},\n",
       "      {'section_num': 3,\n",
       "       'section_title': 'Presidency (2009–2017)',\n",
       "       'section_content': '\\nFirst 100 days\\nThe inauguration of Barack Obama as the 44th President took place on January 20, 2009. In his first few days in office, Obama issued executive orders and presidential memoranda directing the U.S. military to develop plans to withdraw troops from Iraq. He ordered the closing of the Guantanamo Bay detention camp, but Congress prevented the closure by refusing to appropriate the required funds and preventing moving any Guantanamo detainee into the U.S. or to other countries. Obama reduced the secrecy given to presidential records. He also revoked President George W. Bush\\'s restoration of President Ronald Reagan\\'s Mexico City Policy prohibiting federal aid to international family planning organizations that perform or provide counseling about abortion.\\n\\nDomestic policy\\nThe first bill signed into law by Obama was the Lilly Ledbetter Fair Pay Act of 2009, relaxing the statute of limitations for equal-pay lawsuits. Five days later, he signed the reauthorization of the State Children\\'s Health Insurance Program (SCHIP) to cover an additional 4 million uninsured children. In March 2009, Obama reversed a Bush-era policy that had limited funding of embryonic stem cell research and pledged to develop \"strict guidelines\" on the research.\\n\\nObama appointed two women to serve on the Supreme Court in the first two years of his Presidency. He nominated Sonia Sotomayor on May 26, 2009 to replace retiring Associate Justice David Souter; she was confirmed on August 6, 2009, becoming the first Supreme Court Justice of Hispanic descent. Obama nominated Elena Kagan on May 10, 2010 to replace retiring Associate Justice John Paul Stevens. She was confirmed on August 5, 2010, bringing the number of women sitting simultaneously on the Court to three justices for the first time in American history.On March 30, 2010, Obama signed the Health Care and Education Reconciliation Act, a reconciliation bill that ended the process of the federal government giving subsidies to private banks to give out federally insured loans, increased the Pell Grant scholarship award, and made changes to the Patient Protection and Affordable Care Act.\\n\\nIn a major space policy speech in April 2010, Obama announced a planned change in direction at NASA, the U.S. space agency. He ended plans for a return of human spaceflight to the moon and development of the Ares I rocket, Ares V rocket and Constellation program, in favor of funding Earth science projects, a new rocket type, and research and development for an eventual manned mission to Mars, and ongoing missions to the International Space Station.President Obama\\'s 2011 State of the Union Address focused on themes of education and innovation, stressing the importance of innovation economics to make the United States more competitive globally. He spoke of a five-year freeze in domestic spending, eliminating tax breaks for oil companies and reversing tax cuts for the wealthiest Americans, banning congressional earmarks, and reducing healthcare costs. He promised the United States would have one million electric vehicles on the road by 2015 and be 80% reliant on \"clean\" electricity.\\n\\nLGBT rights\\nOn October 8, 2009, Obama signed the Matthew Shepard and James Byrd Jr. Hate Crimes Prevention Act, a measure that expanded the 1969 United States federal hate-crime law to include crimes motivated by a victim\\'s actual or perceived gender, sexual orientation, gender identity, or disability.On October 30, 2009, Obama lifted the ban on travel to the United States by those infected with HIV, which was celebrated by Immigration Equality.On December 22, 2010, Obama signed the Don\\'t Ask, Don\\'t Tell Repeal Act of 2010, which fulfilled a key promise made in the 2008 presidential campaign to end the Don\\'t ask, don\\'t tell policy of 1993 that had prevented gay and lesbian people from serving openly in the United States Armed Forces. In 2016, the Pentagon also ended the policy that barred transgender people from serving openly in the military.As a candidate for the Illinois state senate in 1996, Obama had said he favored legalizing same-sex marriage. By the time of his Senate run in 2004, he said he supported civil unions and domestic partnerships for same-sex partners but opposed same-sex marriages. In 2008, he reaffirmed this position by stating \"I believe marriage is between a man and a woman. I am not in favor of gay marriage.\" On May 9, 2012, shortly after the official launch of his campaign for re-election as president, Obama said his views had evolved, and he publicly affirmed his personal support for the legalization of same-sex marriage, becoming the first sitting U.S. president to do so.\\n\\nDuring his second inaugural address on January 21, 2013, Obama became the first U.S. President in office to call for full equality for gay Americans: \"Our journey is not complete until our gay brothers and sisters are treated like anyone else under the law—for if we are truly created equal, then surely the love we commit to one another must be equal as well.\" This was the first time that a president mentioned gay rights or the word \"gay\" in an inaugural address.In 2013, the Obama Administration filed briefs that urged the Supreme Court to rule in favor of same-sex couples in the cases of Hollingsworth v. Perry (regarding same-sex marriage) and United States v. Windsor (regarding the Defense of Marriage Act). Then, following the Supreme Court\\'s 2015 decision in Obergefell v. Hodges (ruling same-sex marriage to be a fundamental right), Obama asserted that, \"This decision affirms what millions of Americans already believe in their hearts: When all Americans are treated as equal we are all more free.\"On July 30, 2015, the White House Office of National AIDS Policy revised its strategy for addressing the disease, which included widespread testing and linkage to healthcare, which was celebrated by the Human Rights Campaign.\\n\\nWhite House advisory and oversight groups\\nOn March 11, 2009, Obama created the White House Council on Women and Girls, which formed part of the Office of Intergovernmental Affairs, having been established by Executive Order 13506 with a broad mandate to advise him on issues relating to the welfare of American women and girls. The Council was chaired by Senior Advisor to the President Valerie Jarrett. Obama also established the White House Task Force to Protect Students from Sexual Assault through a government memorandum on January 22, 2014, with a broad mandate to advise him on issues relating to sexual assault on college and university campuses throughout the United States. The co-chairs of the Task Force were Vice President Joe Biden and Jarrett. The Task Force was a development out of the White House Council on Women and Girls and Office of the Vice President of the United States, and prior to that the 1994 Violence Against Women Act first drafted by Biden.\\n\\nEconomic policy\\nOn February 17, 2009, Obama signed the American Recovery and Reinvestment Act of 2009, a $787 billion economic stimulus package aimed at helping the economy recover from the deepening worldwide recession. The act includes increased federal spending for health care, infrastructure, education, various tax breaks and incentives, and direct assistance to individuals.\\n\\nIn March, Obama\\'s Treasury Secretary, Timothy Geithner, took further steps to manage the financial crisis, including introducing the Public–Private Investment Program for Legacy Assets, which contains provisions for buying up to two trillion dollars in depreciated real estate assets.Obama intervened in the troubled automotive industry in March 2009, renewing loans for General Motors and Chrysler to continue operations while reorganizing. Over the following months the White House set terms for both firms\\' bankruptcies, including the sale of Chrysler to Italian automaker Fiat and a reorganization of GM giving the U.S. government a temporary 60% equity stake in the company, with the Canadian government taking a 12% stake. In June 2009, dissatisfied with the pace of economic stimulus, Obama called on his cabinet to accelerate the investment. He signed into law the Car Allowance Rebate System, known colloquially as \"Cash for Clunkers,\" which temporarily boosted the economy.The Bush and Obama administrations authorized spending and loan guarantees from the Federal Reserve and the Treasury Department. These guarantees totaled about $11.5 trillion, but only $3 trillion had been spent by the end of November 2009. Obama and the Congressional Budget Office predicted the 2010 budget deficit would be $1.5 trillion or 10.6% of the nation\\'s gross domestic product (GDP) compared to the 2009 deficit of $1.4 trillion or 9.9% of GDP. For 2011, the administration predicted the deficit would shrink to $1.34 trillion, and the 10-year deficit would increase to $8.53 trillion or 90% of GDP. The most recent increase in the U.S. debt ceiling to $17.2 trillion took effect in February 2014. On August 2, 2011, after a lengthy congressional debate over whether to raise the nation\\'s debt limit, Obama signed the bipartisan Budget Control Act of 2011. The legislation enforces limits on discretionary spending until 2021, establishes a procedure to increase the debt limit, creates a Congressional Joint Select Committee on Deficit Reduction to propose further deficit reduction with a stated goal of achieving at least $1.5 trillion in budgetary savings over 10 years, and establishes automatic procedures for reducing spending by as much as $1.2 trillion if legislation originating with the new joint select committee does not achieve such savings. By passing the legislation, Congress was able to prevent a U.S. government default on its obligations.\\n\\nAs it did throughout 2008, the unemployment rate rose in 2009, reaching a peak in October at 10.0% and averaging 10.0% in the fourth quarter. Following a decrease to 9.7% in the first quarter of 2010, the unemployment rate fell to 9.6% in the second quarter, where it remained for the rest of the year. Between February and December 2010, employment rose by 0.8%, which was less than the average of 1.9% experienced during comparable periods in the past four employment recoveries. By November 2012, the unemployment rate fell to 7.7%, decreasing to 6.7% in the last month of 2013. During 2014, the unemployment rate continued to decline, falling to 6.3% in the first quarter. GDP growth returned in the third quarter of 2009, expanding at a rate of 1.6%, followed by a 5.0% increase in the fourth quarter. Growth continued in 2010, posting an increase of 3.7% in the first quarter, with lesser gains throughout the rest of the year. In July 2010, the Federal Reserve noted that economic activity continued to increase, but its pace had slowed, and chairman Ben Bernanke said the economic outlook was \"unusually uncertain.\" Overall, the economy expanded at a rate of 2.9% in 2010.The Congressional Budget Office (CBO) and a broad range of economists credit Obama\\'s stimulus plan for economic growth. The CBO released a report stating that the stimulus bill increased employment by 1–2.1 million, while conceding that \"It is impossible to determine how many of the reported jobs would have existed in the absence of the stimulus package.\" Although an April 2010, survey of members of the National Association for Business Economics showed an increase in job creation (over a similar January survey) for the first time in two years, 73% of 68 respondents believed the stimulus bill has had no impact on employment. The economy of the United States has grown faster than the other original NATO members by a wider margin under President Obama than it has anytime since the end of World War II. The Organisation for Economic Co-operation and Development credits the much faster growth in the United States to the stimulus plan of the US and the austerity measures in the European Union.Within a month of the 2010 midterm elections, Obama announced a compromise deal with the Congressional Republican leadership that included a temporary, two-year extension of the 2001 and 2003 income tax rates, a one-year payroll tax reduction, continuation of unemployment benefits, and a new rate and exemption amount for estate taxes. The compromise overcame opposition from some in both parties, and the resulting $858 billion Tax Relief, Unemployment Insurance Reauthorization, and Job Creation Act of 2010 passed with bipartisan majorities in both houses of Congress before Obama signed it on December 17, 2010.In December 2013, Obama declared that growing income inequality is a \"defining challenge of our time\" and called on Congress to bolster the safety net and raise wages. This came on the heels of the nationwide strikes of fast-food workers and Pope Francis\\' criticism of inequality and trickle-down economics.Obama urged Congress to ratify a 12-nation free trade pact called the Trans-Pacific Partnership.\\n\\nEnvironmental policy\\nOn September 30, 2009, the Obama administration proposed new regulations on power plants, factories, and oil refineries in an attempt to limit greenhouse gas emissions and to curb global warming.On April 20, 2010, an explosion destroyed an offshore drilling rig at the Macondo Prospect in the Gulf of Mexico, causing a major sustained oil leak. Obama visited the Gulf, announced a federal investigation, and formed a bipartisan commission to recommend new safety standards, after a review by Secretary of the Interior Ken Salazar and concurrent Congressional hearings. He then announced a six-month moratorium on new deepwater drilling permits and leases, pending regulatory review. As multiple efforts by BP failed, some in the media and public expressed confusion and criticism over various aspects of the incident, and stated a desire for more involvement by Obama and the federal government.In July 2013, Obama expressed reservations and said he \"would reject the Keystone XL pipeline if it increased carbon pollution\" or \"greenhouse emissions.\" Obama\\'s advisers called for a halt to petroleum exploration in the Arctic in January 2013. On February 24, 2015, Obama vetoed a bill that would have authorized the pipeline. It was the third veto of Obama\\'s presidency and his first major veto.Obama emphasized the conservation of federal lands during his term in office. He used his power under the Antiquities Act to create 25 new national monuments during his presidency and expand four others, protecting a total of 553,000,000 acres (224,000,000 ha) of federal lands and waters, more than any other U.S. president.\\n\\nHealth care reform\\nObama called for Congress to pass legislation reforming health care in the United States, a key campaign promise and a top legislative goal. He proposed an expansion of health insurance coverage to cover the uninsured, to cap premium increases, and to allow people to retain their coverage when they leave or change jobs. His proposal was to spend $900 billion over 10 years and include a government insurance plan, also known as the public option, to compete with the corporate insurance sector as a main component to lowering costs and improving quality of health care. It would also make it illegal for insurers to drop sick people or deny them coverage for pre-existing conditions, and require every American to carry health coverage. The plan also includes medical spending cuts and taxes on insurance companies that offer expensive plans.\\n\\nOn July 14, 2009, House Democratic leaders introduced a 1,017-page plan for overhauling the U.S. health care system, which Obama wanted Congress to approve by the end of 2009. After much public debate during the Congressional summer recess of 2009, Obama delivered a speech to a joint session of Congress on September 9 where he addressed concerns over the proposals. In March 2009, Obama lifted a ban on using federal funds for stem cell research.On November 7, 2009, a health care bill featuring the public option was passed in the House. On December 24, 2009, the Senate passed its own bill—without a public option—on a party-line vote of 60–39. On March 21, 2010, the Patient Protection and Affordable Care Act (ACA) passed by the Senate in December was passed in the House by a vote of 219 to 212. Obama signed the bill into law on March 23, 2010.The ACA includes health-related provisions, most of which took effect in 2014, including expanding Medicaid eligibility for people making up to 133% of the federal poverty level (FPL) starting in 2014, subsidizing insurance premiums for people making up to 400% of the FPL ($88,000 for family of four in 2010) so their maximum \"out-of-pocket\" payment for annual premiums will be from 2% to 9.5% of income, providing incentives for businesses to provide health care benefits, prohibiting denial of coverage and denial of claims based on pre-existing conditions, establishing health insurance exchanges, prohibiting annual coverage caps, and support for medical research. According to White House and CBO figures, the maximum share of income that enrollees would have to pay would vary depending on their income relative to the federal poverty level.\\n\\nThe costs of these provisions are offset by taxes, fees, and cost-saving measures, such as new Medicare taxes for those in high-income brackets, taxes on indoor tanning, cuts to the Medicare Advantage program in favor of traditional Medicare, and fees on medical devices and pharmaceutical companies; there is also a tax penalty for those who do not obtain health insurance, unless they are exempt due to low income or other reasons. In March 2010, the CBO estimated that the net effect of both laws will be a reduction in the federal deficit by $143 billion over the first decade.The law faced several legal challenges, primarily based on the argument that an individual mandate requiring Americans to buy health insurance was unconstitutional. On June 28, 2012, the Supreme Court ruled by a 5–4 vote in National Federation of Independent Business v. Sebelius that the mandate was constitutional under the U.S. Congress\\'s taxing authority. In Burwell v. Hobby Lobby the Court ruled that \"closely-held\" for-profit corporations could be exempt on religious grounds under the Religious Freedom Restoration Act from regulations adopted under the ACA that would have required them to pay for insurance that covered certain contraceptives. In June 2015, the Court ruled 6–3 in King v. Burwell that subsidies to help individuals and families purchase health insurance were authorized for those doing so on both the federal exchange and state exchanges, not only those purchasing plans \"established by the State,\" as the statute reads.\\n\\nEnergy policy\\nPrior to June 2014, Obama offered substantial support for a broadly-based \"All of the above\" approach to domestic energy policy, which Obama has maintained since his first term and which he last confirmed at his State of the Union speech in January 2014 to a mixed reception by both parties. In June 2014, Obama made indications that his administration would consider a shift towards an energy policy more closely tuned to the manufacturing industry and its impact on the domestic economy. Obama\\'s approach of selectively combining regulation and incentive to various issues in the domestic energy policy, such as coal mining and oil fracking, has received mixed commentary for not being as responsive to the needs of the domestic manufacturing sector as needed, following claims that the domestic manufacturing sector utilizes as much as a third of the nation\\'s available energy resources.\\n\\nGun control\\nOn January 16, 2013, one month after the Sandy Hook Elementary School shooting, Obama signed 23 executive orders and outlined a series of sweeping proposals regarding gun control. He urged Congress to reintroduce an expired ban on military-style assault weapons, such as those used in several recent mass shootings, impose limits on ammunition magazines to 10 rounds, introduce background checks on all gun sales, pass a ban on possession and sale of armor-piercing bullets, introduce harsher penalties for gun-traffickers, especially unlicensed dealers who buy arms for criminals and approving the appointment of the head of the federal Bureau of Alcohol, Tobacco, Firearms and Explosives for the first time since 2006. On January 5, 2016, Obama announced new executive actions extending background check requirements to more gun sellers. In a 2016 editorial in the New York Times, Obama compared the struggle for what he termed \"common-sense gun reform\" to women\\'s suffrage and other civil rights movements in American history.\\n\\n2010 midterm elections\\nObama called the November 2, 2010 election, where the Democratic Party lost 63 seats in, and control of, the House of Representatives, \"humbling\" and a \"shellacking.\" He said that the results came because not enough Americans had felt the effects of the economic recovery.\\n\\nCybersecurity and Internet policy\\nOn November 10, 2014, President Obama recommended the Federal Communications Commission reclassify broadband Internet service as a telecommunications service in order to preserve net neutrality. On February 12, 2013, President Obama signed Executive Order 13636, \"Improving Critical Infrastructure Cybersecurity.\"\\n\\nGovernment mass surveillance\\nIn 2005 and 2006, Obama criticized certain aspects of the Patriot Act for infringing too much on civil liberties and sought as Senator to strengthen civil liberties protections. In 2006, he voted to reauthorize a revised version of the Patriot Act, saying the law was not ideal but that the revised version had strengthened civil liberties. In 2011, he signed a four-year renewal of the Patriot Act. Following the 2013 global surveillance disclosures by whistleblower Edward Snowden, Obama condemned the leak as unpatriotic, but called for increased restrictions on the NSA to address violations of privacy. The changes which Obama ordered have been described as \"modest\" however.\\n\\nForeign policy\\nIn February and March 2009, Vice President Joe Biden and Secretary of State Hillary Clinton made separate overseas trips to announce a \"new era\" in U.S. foreign relations with Russia and Europe, using the terms \"break\" and \"reset\" to signal major changes from the policies of the preceding administration. Obama attempted to reach out to Arab leaders by granting his first interview to an Arab satellite TV network, Al Arabiya.On March 19, Obama continued his outreach to the Muslim world, releasing a New Year\\'s video message to the people and government of Iran. In April, Obama gave a speech in Ankara, Turkey, which was well received by many Arab governments. On June 4, 2009, Obama delivered a speech at Cairo University in Egypt calling for \"A New Beginning\" in relations between the Islamic world and the United States and promoting Middle East peace.\\n\\nOn June 26, 2009, Obama responded to the Iranian government\\'s actions towards protesters following Iran\\'s 2009 presidential election by saying: \"The violence perpetrated against them is outrageous. We see it and we condemn it.\" While in Moscow on July 7, he responded to Vice President Biden\\'s comment on a possible Israeli military strike on Iran by saying: \"We have said directly to the Israelis that it is important to try and resolve this in an international setting in a way that does not create major conflict in the Middle East.\"On September 24, 2009, Obama became the first sitting U.S. President to preside over a meeting of the United Nations Security Council.In March 2010, Obama took a public stance against plans by the government of Israeli Prime Minister Benjamin Netanyahu to continue building Jewish housing projects in predominantly Arab neighborhoods of East Jerusalem. During the same month, an agreement was reached with the administration of Russian President Dmitry Medvedev to replace the 1991 Strategic Arms Reduction Treaty with a new pact reducing the number of long-range nuclear weapons in the arsenals of both countries by about a third. Obama and Medvedev signed the New START treaty in April 2010, and the U.S. Senate ratified it in December 2010.\\n\\nIn December 2011, Obama instructed agencies to consider LGBT rights when issuing financial aid to foreign countries. In August 2013, he criticized Russia\\'s law that discriminates against gays, but he stopped short of advocating a boycott of the upcoming 2014 Winter Olympics in Sochi, Russia.In December 2014, Obama announced that he intended to normalize relationships between Cuba and the United States. The countries\\' respective \"interests sections\" in one another\\'s capitals were upgraded to embassies on July 20, 2015.\\nIn March 2015, Obama declared that he had authorized U.S. forces to provide logistical and intelligence support to the Saudis in their military intervention in Yemen, establishing a \"Joint Planning Cell\" with Saudi Arabia. In 2016, the Obama administration proposed a series of arms deals with Saudi Arabia worth $115 billion. Obama halted the sale of guided munition technology to Saudi Arabia after Saudi warplanes targeted a funeral in Yemen\\'s capital Sanaa, killing more than 140 people.Before leaving office, Obama said German Chancellor Angela Merkel had been his \"closest international partner\" throughout his tenure as president.\\n\\nWar in Iraq\\nOn February 27, 2009, Obama announced that combat operations in Iraq would end within 18 months. His remarks were made to a group of Marines preparing for deployment to Afghanistan. Obama said, \"Let me say this as plainly as I can: by August 31, 2010, our combat mission in Iraq will end.\" The Obama administration scheduled the withdrawal of combat troops to be completed by August 2010, decreasing troop\\'s levels from 142,000 while leaving a transitional force of about 50,000 in Iraq until the end of 2011. On August 19, 2010, the last U.S. combat brigade exited Iraq. Remaining troops transitioned from combat operations to counter-terrorism and the training, equipping, and advising of Iraqi security forces. On August 31, 2010, Obama announced that the United States combat mission in Iraq was over. On October 21, 2011 President Obama announced that all U.S. troops would leave Iraq in time to be \"home for the holidays.\"\\n\\nIn June 2014, following the capture of Mosul by ISIS, Obama sent 275 troops to provide support and security for U.S. personnel and the U.S. Embassy in Baghdad. ISIS continued to gain ground and to commit widespread massacres and ethnic cleansing.In August 2014, during the Sinjar massacre, Obama ordered a campaign of U.S. airstrikes against ISIS.By the end of 2014, 3,100 American ground troops were committed to the conflict and 16,000 sorties were flown over the battlefield, primarily by U.S. Air Force and Navy pilots.In early 2015, with the addition of the \"Panther Brigade\" of the 82nd Airborne Division the number of U.S. ground troops in Iraq surged to 4,400, and by July American-led coalition air forces counted 44,000 sorties over the battlefield.\\n\\nWar in Afghanistan\\nEarly in his presidency, Obama moved to bolster U.S. troop strength in Afghanistan. He announced an increase in U.S. troop levels to 17,000 military personnel in February 2009 to \"stabilize a deteriorating situation in Afghanistan,\" an area he said had not received the \"strategic attention, direction and resources it urgently requires.\" He replaced the military commander in Afghanistan, General David D. McKiernan, with former Special Forces commander Lt. Gen. Stanley A. McChrystal in May 2009, indicating that McChrystal\\'s Special Forces experience would facilitate the use of counterinsurgency tactics in the war. On December 1, 2009, Obama announced the deployment of an additional 30,000 military personnel to Afghanistan and proposed to begin troop withdrawals 18 months from that date; this took place in July 2011. David Petraeus replaced McChrystal in June 2010, after McChrystal\\'s staff criticized White House personnel in a magazine article. In February 2013, Obama said the U.S. military would reduce the troop level in Afghanistan from 68,000 to 34,000 U.S. troops by February 2014.In October 2015, the White House announced a plan to keep U.S. Forces in Afghanistan indefinitely in light of the deteriorating security situation.\\n\\nIsrael\\nIn 2011, the United States vetoed a Security Council resolution condemning Israeli settlements, with the United States being the only nation to do so. Obama supports the two-state solution to the Arab–Israeli conflict based on the 1967 borders with land swaps.In June 2011, Obama said the bond between the United States and Israel is \"unbreakable.\" During the initial years of the Obama administration, the U.S. increased military cooperation with Israel, including increased military aid, re-establishment of the U.S.-Israeli Joint Political Military Group and the Defense Policy Advisory Group, and an increase in visits among high-level military officials of both countries. The Obama administration asked Congress to allocate money toward funding the Iron Dome program in response to the waves of Palestinian rocket attacks on Israel.In 2013, Jeffrey Goldberg reported that, in Obama\\'s view, \"with each new settlement announcement, Netanyahu is moving his country down a path toward near-total isolation.\" In 2014, Obama likened the Zionist movement to the Civil Rights Movement in the United States. He said both movements seek to bring justice and equal rights to historically persecuted peoples. He explained, \"To me, being pro-Israel and pro-Jewish is part and parcel with the values that I\\'ve been fighting for since I was politically conscious and started getting involved in politics.\" Obama expressed support for Israel\\'s right to defend itself during the 2014 Israel–Gaza conflict. In 2015, Obama was harshly criticized by Israel for advocating and signing the Iran Nuclear Deal; Israeli Prime Minister Benjamin Netanyahu, who had advocated the U.S. congress to oppose it, said the deal was \"dangerous\" and \"bad.\"On December 23, 2016, under the Obama Administration, the United States abstained from United Nations Security Council Resolution 2334, which condemned Israeli settlement building in the occupied Palestinian territories as a violation of international law, effectively allowing it to pass. Netanyahu strongly criticized the Obama Administration\\'s actions, and the Israeli government withdrew its annual dues from the organization, which totaled $6 million, on January 6, 2017. On January 5, 2017, the United States House of Representatives voted 342–80 to condemn the UN Resolution.\\n\\nLibya\\nIn February 2011, protests in Libya began against long-time dictator Muammar Gaddafi as part of the Arab Spring. They soon turned violent. In March, as forces loyal to Gaddafi advanced on rebels across Libya, calls for a no-fly zone came from around the world, including Europe, the Arab League, and a resolution passed unanimously by the U.S. Senate. In response to the unanimous passage of United Nations Security Council Resolution 1973 on March 17, Gaddafi—who had previously vowed to \"show no mercy\" to the rebels of Benghazi—announced an immediate cessation of military activities, yet reports came in that his forces continued shelling Misrata. The next day, on Obama\\'s orders, the U.S. military took part in air strikes to destroy the Libyan government\\'s air defense capabilities to protect civilians and enforce a no-fly-zone, including the use of Tomahawk missiles, B-2 Spirits, and fighter jets. Six days later, on March 25, by unanimous vote of all its 28 members, NATO took over leadership of the effort, dubbed Operation Unified Protector. Some Representatives questioned whether Obama had the constitutional authority to order military action in addition to questioning its cost, structure and aftermath.\\n\\nSyrian Civil War\\nOn August 18, 2011, several months after the start of the Syrian Civil War, Obama issued a written statement that said: \"The time has come for President Assad to step aside.\" This stance was reaffirmed in November 2015. In 2012, Obama authorized multiple programs run by the CIA and the Pentagon to train anti-Assad rebels. The Pentagon-run program was later found to have failed and was formally abandoned in October 2015.In the wake of a chemical weapons attack in Syria, formally blamed by the Obama administration on the Assad government, Obama chose not to enforce the \"red line\" he had pledged and, rather than authorize the promised military action against Assad, went along with the Russia-brokered deal that led to Assad giving up chemical weapons; however attacks with chlorine gas continued. In 2014, Obama authorized an air campaign aimed primarily at ISIL, but repeatedly promised the U.S. would not deploy ground troops in Syria.\\n\\nDeath of Osama bin Laden\\nStarting with information received from Central Intelligence Agency operatives in July 2010, the CIA developed intelligence over the next several months that determined what they believed to be the hideout of Osama bin Laden. He was living in seclusion in a large compound in Abbottabad, Pakistan, a suburban area 35 miles (56 km) from Islamabad. CIA head Leon Panetta reported this intelligence to President Obama in March 2011. Meeting with his national security advisers over the course of the next six weeks, Obama rejected a plan to bomb the compound, and authorized a \"surgical raid\" to be conducted by United States Navy SEALs. The operation took place on May 1, 2011, and resulted in the shooting death of bin Laden and the seizure of papers, computer drives and disks from the compound. DNA testing was one of five methods used to positively identify bin Laden\\'s corpse, which was buried at sea several hours later. Within minutes of the President\\'s announcement from Washington, DC, late in the evening on May 1, there were spontaneous celebrations around the country as crowds gathered outside the White House, and at New York City\\'s Ground Zero and Times Square. Reaction to the announcement was positive across party lines, including from former presidents Bill Clinton and George W. Bush.\\n\\nIran nuclear talks\\nOn October 1, 2009, the Obama administration went ahead with a Bush administration program increasing nuclear weapons production. The “Complex Modernization” initiative expanded two existing nuclear sites to produce new bomb parts. The administration built new plutonium pits at the Los Alamos lab in New Mexico and expanded enriched uranium processing at the Y-12 facility in Oak Ridge, Tennessee. In November 2013, the Obama administration opened negotiations with Iran to prevent it from acquiring nuclear weapons, which included an interim agreement. Negotiations took two years with numerous delays, with a deal being announced July 14, 2015. The deal, titled the \"Joint Comprehensive Plan of Action,\" saw the removal of sanctions in exchange for measures that would prevent Iran from producing nuclear weapons. While Obama hailed the agreement as being a step towards a more hopeful world, the deal drew strong criticism from Republican and conservative quarters, and from Israeli prime minister Benjamin Netanyahu. In addition, the transfer of $1.7 billion in cash to Iran shortly after the deal was announced was criticized by the republican party. The Obama administration said that the payment in cash was because of the \"effectiveness of U.S. and international sanctions.\" In order to advance the deal, the Obama administration shielded Hezbollah from the Drug Enforcement Administration\\'s Project Cassandra investigation regarding drug smuggling and from the Central Intelligence Agency.\\nOn a sidenote, the very same year, in December 2015, Obama started a $348 billion worth program to back the biggest U.S. buildup of nuclear arms since Ronald Reagan left the White House.\\n\\nRelations with Cuba\\nSince the spring of 2013, secret meetings were conducted between the United States and Cuba in the neutral locations of Canada and Vatican City. The Vatican first became involved in 2013 when Pope Francis advised the U.S. and Cuba to exchange prisoners as a gesture of goodwill. On December 10, 2013, Cuban President Raúl Castro, in a significant public moment, greeted and shook hands with Obama at the Nelson Mandela memorial service in Johannesburg.In December 2014, after the secret meetings, it was announced that Obama, with Pope Francis as an intermediary, had negotiated a restoration of relations with Cuba, after nearly sixty years of détente. Popularly dubbed the Cuban Thaw, The New Republic deemed the Cuban Thaw to be \"Obama\\'s finest foreign policy achievement.\" On July 1, 2015, President Barack Obama announced that formal diplomatic relations between Cuba and the United States would resume, and embassies would be opened in Washington and Havana. The countries\\' respective \"interests sections\" in one another\\'s capitals were upgraded to embassies on July 20 and August 13, 2015, respectively.Obama visited Havana, Cuba for two days in March 2016, becoming the first sitting U.S. President to arrive since Calvin Coolidge in 1928.\\n\\nAfrica\\nObama spoke in front of the African Union in Addis Ababa, Ethiopia, on July 29, 2015, the first sitting U.S. president to do so. He gave a speech encouraging the world to increase economic ties via investments and trade with the continent, and lauded the progress made in education, infrastructure, and economy. He also criticized the lack of democracy and leaders who refuse to step aside, discrimination against minorities (LGBT people, religious groups and ethnicities), and corruption. He suggested an intensified democratization and free trade, to significantly improve the quality of life for Africans. During his July 2015 trip, Obama also was the first U.S. president ever to visit Kenya, which is the homeland of his father.\\n\\nHiroshima speech\\nOn May 27, 2016, Obama became the first sitting American president to visit Hiroshima, Japan, 71 years after the U.S. atomic bombing of Hiroshima that ended World War II. Accompanied by Japanese Prime Minister Shinzō Abe, Obama paid tribute to the victims of the bombing at the Hiroshima Peace Memorial Museum.\\n\\nRussia\\nAfter Russia\\'s invasion of Crimea in 2014, military intervention in Syria in 2015, and the interference in the 2016 U.S. presidential election, Obama\\'s Russia policy was widely seen as a failure. George Robertson, a former UK defense secretary and NATO secretary-general, said Obama had \"allowed Putin to jump back on the world stage and test the resolve of the West,\" adding that the legacy of this disaster would last.\\n\\nCultural and political image\\nObama\\'s family history, upbringing, and Ivy League education differ markedly from those of African-American politicians who launched their careers in the 1960s through participation in the civil rights movement. Expressing puzzlement over questions about whether he is \"black enough,\" Obama told an August 2007 meeting of the National Association of Black Journalists that \"we\\'re still locked in this notion that if you appeal to white folks then there must be something wrong.\" Obama acknowledged his youthful image in an October 2007 campaign speech, saying: \"I wouldn\\'t be here if, time and again, the torch had not been passed to a new generation.\"Obama is frequently referred to as an exceptional orator. During his pre-inauguration transition period and continuing into his presidency, Obama delivered a series of weekly Internet video addresses. In his speeches as president, Obama did not make more overt references to race relations than his predecessors, but according to one study, he implemented stronger policy action on behalf of African-Americans than any president since the Nixon era.\\n\\nAccording to the Gallup Organization, Obama began his presidency with a 68% approval rating before gradually declining for the rest of the year, and eventually bottoming out at 41% in August 2010, a trend similar to Ronald Reagan\\'s and Bill Clinton\\'s first years in office. He experienced a small poll bounce shortly after the death of Osama bin Laden on May 2, 2011. This bounce lasted until around June 2011, when his approval numbers dropped back to where they were previously. His approval ratings rebounded around the same time as his reelection in 2012, with polls showing an average job approval of 52% shortly after his second inauguration. Despite approval ratings dropping to 39% in late-2013 due to the ACA roll-out, they climbed to 50% in January 2015 according to Gallup.Polls showed strong support for Obama in other countries both before and during his presidency. In a February 2009 poll conducted in Western Europe and the U.S. by Harris Interactive for France 24 and the International Herald Tribune, Obama was rated as the most respected world leader, as well as the most powerful. In a similar poll conducted by Harris in May 2009, Obama was rated as the most popular world leader, as well as the one figure most people would pin their hopes on for pulling the world out of the economic downturn.\\n\\nObama won Best Spoken Word Album Grammy Awards for abridged audiobook versions of Dreams from My Father in February 2006 and for The Audacity of Hope in February 2008. His concession speech after the New Hampshire primary was set to music by independent artists as the music video \"Yes We Can,\" which was viewed 10 million times on YouTube in its first month and received a Daytime Emmy Award. In December 2008 and in 2012, Time magazine named Obama as its Person of the Year. The 2008 awarding was for his historic candidacy and election, which Time described as \"the steady march of seemingly impossible accomplishments.\" On May 25, 2011, Obama became the first President of the United States to address both houses of the UK Parliament in Westminster Hall, London. This was only the fifth occurrence since the start of the 20th century of a head of state\\'s being extended this invitation, following Charles de Gaulle in 1960, Nelson Mandela in 1996, Queen Elizabeth II in 2002 and Pope Benedict XVI in 2010.On October 9, 2009, the Norwegian Nobel Committee announced that Obama had won the 2009 Nobel Peace Prize \"for his extraordinary efforts to strengthen international diplomacy and cooperation between peoples.\" Obama accepted this award in Oslo, Norway on December 10, 2009, with \"deep gratitude and great humility.\" The award drew a mixture of praise and criticism from world leaders and media figures. Obama\\'s peace prize was called a \"stunning surprise\" by The New York Times. He became the fourth U.S. president to be awarded the Nobel Peace Prize and the third to become a Nobel laureate while in office. Obama\\'s Nobel Prize has been viewed skeptically in subsequent years, especially after the director of the Nobel Institute, Geir Lundestad, said Obama\\'s Peace Prize did not have the desired effect.'},\n",
       "      {'section_num': 2,\n",
       "       'section_title': 'Presidential campaigns',\n",
       "       'section_content': '\\n2008\\nOn February 10, 2007, Obama announced his candidacy for President of the United States in front of the Old State Capitol building in Springfield, Illinois. The choice of the announcement site was viewed as symbolic because it was also where Abraham Lincoln delivered his historic \"House Divided\" speech in 1858. Obama emphasized issues of rapidly ending the Iraq War, increasing energy independence, and reforming the health care system, in a campaign that projected themes of hope and change.Numerous candidates entered the Democratic Party presidential primaries. The field narrowed to a duel between Obama and Senator Hillary Clinton after early contests, with the race remaining close throughout the primary process but with Obama gaining a steady lead in pledged delegates due to better long-range planning, superior fundraising, dominant organizing in caucus states, and better exploitation of delegate allocation rules. On June 7, 2008, Clinton ended her campaign and endorsed Obama.\\n\\nOn August 23, Obama announced his selection of Delaware Senator Joe Biden as his vice presidential running mate. Obama selected Biden from a field speculated to include former Indiana Governor and Senator Evan Bayh and Virginia Governor Tim Kaine. At the Democratic National Convention in Denver, Colorado, Hillary Clinton called for her supporters to endorse Obama, and she and Bill Clinton gave convention speeches in his support. Obama delivered his acceptance speech, not at the center where the Democratic National Convention was held, but at Invesco Field at Mile High to a crowd of approximately 84,000 people; the speech was viewed by over 38 million people worldwide.During both the primary process and the general election, Obama\\'s campaign set numerous fundraising records, particularly in the quantity of small donations. On June 19, 2008, Obama became the first major-party presidential candidate to turn down public financing in the general election since the system was created in 1976.John McCain was nominated as the Republican candidate, and he selected Sarah Palin as his running mate. The two candidates engaged in three presidential debates in September and October 2008. On November 4, Obama won the presidency with 365 electoral votes to 173 received by McCain. Obama won 52.9% of the popular vote to McCain\\'s 45.7%. He became the first African American to be elected president. Obama delivered his victory speech before hundreds of thousands of supporters in Chicago\\'s Grant Park.\\n\\n2012\\nOn April 4, 2011, Obama announced his reelection campaign for 2012 in a video titled \"It Begins with Us\" that he posted on his website and filed election papers with the Federal Election Commission. As the incumbent president he ran virtually unopposed in the Democratic Party presidential primaries, and on April 3, 2012, Obama had secured the 2778 convention delegates needed to win the Democratic nomination.At the Democratic National Convention in Charlotte, North Carolina, Obama and Joe Biden were formally nominated by former President Bill Clinton as the Democratic Party candidates for president and vice president in the general election. Their main opponents were Republicans Mitt Romney, the former governor of Massachusetts, and Representative Paul Ryan of Wisconsin.On November 6, 2012, Obama won 332 electoral votes, exceeding the 270 required for him to be reelected as president. With 51.1% of the popular vote, Obama became the first Democratic president since Franklin D. Roosevelt to win the majority of the popular vote twice. Obama addressed supporters and volunteers at Chicago\\'s McCormick Place after his reelection and said: \"Tonight you voted for action, not politics as usual. You elected us to focus on your jobs, not ours. And in the coming weeks and months, I am looking forward to reaching out and working with leaders of both parties.\"'},\n",
       "      {'section_num': 1,\n",
       "       'section_title': 'Early life and career',\n",
       "       'section_content': '\\nObama was born on August 4, 1961, at Kapiolani Medical Center for Women and Children in Honolulu, Hawaii at 7:24 pm. He is the only president born outside the contiguous 48 states. He was born to an American mother of European descent and an African father. His mother, Ann Dunham (1942–1995), was born in Wichita, Kansas; she was mostly of English descent, with some German, Irish, Scottish, Swiss, and Welsh ancestry. (In July 2012, Ancestry.com found a strong likelihood that Stanley Ann Dunham was descended from John Punch, an enslaved African man who lived in the Colony of Virginia during the seventeenth century.) His father, Barack Obama Sr. (1936–1982), was a married Luo Kenyan from Nyang\\'oma Kogelo. Obama\\'s parents met in 1960 in a Russian language class at the University of Hawaii at Manoa, where his father was a foreign student on a scholarship. The couple married in Wailuku, Hawaii, on February 2, 1961, six months before Obama was born.In late August 1961, a few weeks after he was born, Barack and his mother moved to the University of Washington in Seattle, where they lived for a year. During that time, the elder Obama completed his undergraduate degree in economics in Hawaii, graduating in June 1962. He left to attend graduate school on a scholarship at Harvard University, where he earned an M.A. in economics. Obama\\'s parents divorced in March 1964. Obama Sr. returned to Kenya in 1964, where he married for a third time and worked for the Kenyan government as the Senior Economic Analyst in the Ministry of Finance. He visited his son in Hawaii only once, at Christmas 1971, before he was killed in an automobile accident in 1982, when Obama was 21 years old. Recalling his early childhood, Obama said, \"That my father looked nothing like the people around me—that he was black as pitch, my mother white as milk—barely registered in my mind.\" He described his struggles as a young adult to reconcile social perceptions of his multiracial heritage.\\n\\nIn 1963, Dunham met Lolo Soetoro at the University of Hawaii; he was an Indonesian East–West Center graduate student in geography. The couple married on Molokai on March 15, 1965. After two one-year extensions of his J-1 visa, Lolo returned to Indonesia in 1966. His wife and stepson followed sixteen months later in 1967. The family initially lived in the Menteng Dalam neighborhood in the Tebet sub district of south Jakarta. From 1970, they lived in a wealthier neighborhood in the Menteng sub district of central Jakarta.\\n\\nEducation\\nObama started in St. Francis Pre-Education from age three to five. From age six to ten, he then attended local Indonesian-language schools: Sekolah Dasar Katolik Santo Fransiskus Asisi (St. Francis of Assisi Catholic Elementary School) for two years and Sekolah Dasar Negeri Menteng 01 (State Elementary School Menteng 01/Besuki school) for one and a half years, supplemented by English-language Calvert School homeschooling by his mother. As a result of those four years in Jakarta, he was able to speak Indonesian fluently as a child. During his time in Indonesia, Obama\\'s step-father taught him to be resilient and gave him \"a pretty hardheaded assessment of how the world works.\"In 1971, Obama returned to Honolulu to live with his maternal grandparents, Madelyn and Stanley Dunham. He attended Punahou School—a private college preparatory school—with the aid of a scholarship from fifth grade until he graduated from high school in 1979. In his youth, Obama went by the nickname \"Barry.\" Obama lived with his mother and half-sister, Maya Soetoro, in Hawaii for three years from 1972 to 1975 while his mother was a graduate student in anthropology at the University of Hawaii. Obama chose to stay in Hawaii with his grandparents for high school at Punahou when his mother and half-sister returned to Indonesia in 1975 so his mother could begin anthropology field work. His mother spent most of the next two decades in Indonesia, divorcing Lolo in 1980 and earning a PhD degree in 1992, before dying in 1995 in Hawaii following unsuccessful treatment for ovarian and uterine cancer.Obama later reflected on his years in Honolulu and wrote: \"The opportunity that Hawaii offered—to experience a variety of cultures in a climate of mutual respect—became an integral part of my world view, and a basis for the values that I hold most dear.\" Obama has also written and talked about using alcohol, marijuana, and cocaine during his teenage years to \"push questions of who I was out of my mind.\" Obama was also a member of the \"choom gang,\" a self-named group of friends who spent time together and occasionally smoked marijuana.After graduating from high school in 1979, Obama moved to Los Angeles to attend Occidental College on a full scholarship. In February 1981, Obama made his first public speech, calling for Occidental to participate in the disinvestment from South Africa in response to that nation\\'s policy of apartheid. In mid-1981, Obama traveled to Indonesia to visit his mother and half-sister Maya, and visited the families of college friends in Pakistan and India for three weeks. Later in 1981, he transferred as a junior to Columbia University in New York City, where he majored in political science with a specialty in international relations and in English literature and lived off-campus on West 109th Street. He graduated with a BA degree in 1983 and worked for about a year at the Business International Corporation, where he was a financial researcher and writer, then as a project coordinator for the New York Public Interest Research Group on the City College of New York campus for three months in 1985.\\n\\nFamily and personal life\\nIn a 2006 interview, Obama highlighted the diversity of his extended family: \"It\\'s like a little mini-United Nations,\" he said. \"I\\'ve got relatives who look like Bernie Mac, and I\\'ve got relatives who look like Margaret Thatcher.\" Obama has a half-sister with whom he was raised (Maya Soetoro-Ng) and seven other half-siblings from his Kenyan father\\'s family—six of them living. Obama\\'s mother was survived by her Kansas-born mother, Madelyn Dunham, until her death on November 2, 2008, two days before his election to the Presidency. Obama also has roots in Ireland; he met with his Irish cousins in Moneygall in May 2011. In Dreams from My Father, Obama ties his mother\\'s family history to possible Native American ancestors and distant relatives of Jefferson Davis, President of the Confederate States of America during the American Civil War. He also shares distant ancestors in common with George W. Bush and Dick Cheney, among others.Obama lived with anthropologist Sheila Miyoshi Jager while he was a community organizer in Chicago in the 1980s. He proposed to her twice, but both Jager and her parents turned him down. The relationship was not made public until May 2017, several months after his presidency had ended.\\n\\nIn June 1989, Obama met Michelle Robinson when he was employed as a summer associate at the Chicago law firm of Sidley Austin. Robinson was assigned for three months as Obama\\'s adviser at the firm, and she joined him at several group social functions but declined his initial requests to date. They began dating later that summer, became engaged in 1991, and were married on October 3, 1992. After suffering a miscarriage, Michelle underwent in vitro fertilisation to conceive their children. The couple\\'s first daughter, Malia Ann, was born in 1998, followed by a second daughter, Natasha (\"Sasha\"), in 2001. The Obama daughters attended the University of Chicago Laboratory Schools. When they moved to Washington, D.C., in January 2009, the girls started at the Sidwell Friends School. The Obamas have two Portuguese Water Dogs; the first, a male named Bo, was a gift from Senator Ted Kennedy. In 2013, Bo was joined by Sunny, a female.\\n\\nObama is a supporter of the Chicago White Sox, and he threw out the first pitch at the 2005 ALCS when he was still a senator. In 2009, he threw out the ceremonial first pitch at the All-Star Game while wearing a White Sox jacket. He is also primarily a Chicago Bears football fan in the NFL, but in his childhood and adolescence was a fan of the Pittsburgh Steelers, and rooted for them ahead of their victory in Super Bowl XLIII 12 days after he took office as president. In 2011, Obama invited the 1985 Chicago Bears to the White House; the team had not visited the White House after their Super Bowl win in 1986 due to the Space Shuttle Challenger disaster. He plays basketball, a sport he participated in as a member of his high school\\'s varsity team, and he is left-handed.In 2005, the Obama family applied the proceeds of a book deal and moved from a Hyde Park, Chicago condominium to a $1.6 million house (equivalent to $2.1 million in 2019) in neighboring Kenwood, Chicago. The purchase of an adjacent lot—and sale of part of it to Obama by the wife of developer, campaign donor and friend Tony Rezko—attracted media attention because of Rezko\\'s subsequent indictment and conviction on political corruption charges that were unrelated to Obama.In December 2007, Money Magazine estimated Obama\\'s net worth at $1.3 million (equivalent to $1.6 million in 2019) . Their 2009 tax return showed a household income of $5.5 million—up from about $4.2 million in 2007 and $1.6 million in 2005—mostly from sales of his books. On his 2010 income of $1.7 million, he gave 14% to non-profit organizations, including $131,000 to Fisher House Foundation, a charity assisting wounded veterans\\' families, allowing them to reside near where the veteran is receiving medical treatments. Per his 2012 financial disclosure, Obama may be worth as much as $10 million.In early 2010, Michelle spoke about her husband\\'s smoking habit and said Barack had quit smoking.On his 55th birthday, August 4, 2016, Obama penned an essay in Glamour, in which he described how his daughters and the presidency have made him a feminist.\\n\\nReligious views\\nObama is a Protestant Christian whose religious views developed in his adult life. He wrote in The Audacity of Hope that he \"was not raised in a religious household.\" He described his mother, raised by non-religious parents, as being detached from religion, yet \"in many ways the most spiritually awakened person ... I have ever known,\" and \"a lonely witness for secular humanism\". He described his father as a \"confirmed atheist\" by the time his parents met, and his stepfather as \"a man who saw religion as not particularly useful.\" Obama explained how, through working with black churches as a community organizer while in his twenties, he came to understand \"the power of the African-American religious tradition to spur social change.\"\\n\\nIn January 2008, Obama told Christianity Today: \"I am a Christian, and I am a devout Christian. I believe in the redemptive death and resurrection of Jesus Christ. I believe that faith gives me a path to be cleansed of sin and have eternal life.\" On September 27, 2010, Obama released a statement commenting on his religious views saying, \"I\\'m a Christian by choice. My family didn\\'t—frankly, they weren\\'t folks who went to church every week. And my mother was one of the most spiritual people I knew, but she didn\\'t raise me in the church. So I came to my Christian faith later in life, and it was because the precepts of Jesus Christ spoke to me in terms of the kind of life that I would want to lead—being my brothers\\' and sisters\\' keeper, treating others as they would treat me.\"Obama met Trinity United Church of Christ pastor Jeremiah Wright in October 1987 and became a member of Trinity in 1992. During Obama\\'s first presidential campaign in May 2008, he resigned from Trinity after some of Wright\\'s statements were criticized. Since moving to Washington, D.C., in 2009, the Obama family has attended several Protestant churches, including Shiloh Baptist Church and St. John\\'s Episcopal Church, as well as Evergreen Chapel at Camp David, but the members of the family do not attend church on a regular basis.\\n\\nLaw career\\nCommunity organizer and Harvard Law School\\nTwo years after graduating from Columbia, Obama moved from New York to Chicago when he was hired as director of the Developing Communities Project, a church-based community organization originally comprising eight Catholic parishes in Roseland, West Pullman, and Riverdale on Chicago\\'s South Side. He worked there as a community organizer from June 1985 to May 1988. He helped set up a job training program, a college preparatory tutoring program, and a tenants\\' rights organization in Altgeld Gardens. Obama also worked as a consultant and instructor for the Gamaliel Foundation, a community organizing institute. In mid-1988, he traveled for the first time in Europe for three weeks and then for five weeks in Kenya, where he met many of his paternal relatives for the first time.\\nDespite being offered a full scholarship to Northwestern University School of Law, Obama enrolled at Harvard Law School in the fall of 1988, living in nearby Somerville, Massachusetts. He was selected as an editor of the Harvard Law Review at the end of his first year, president of the journal in his second year, and research assistant to the constitutional scholar Laurence Tribe while at Harvard for two years. During his summers, he returned to Chicago, where he worked as a summer associate at the law firms of Sidley Austin in 1989 and Hopkins & Sutter in 1990. After graduating with a JD degree magna cum laude from Harvard in 1991, he returned to Chicago. Obama\\'s election as the first black president of the Harvard Law Review gained national media attention and led to a publishing contract and advance for a book about race relations, which evolved into a personal memoir. The manuscript was published in mid-1995 as Dreams from My Father.\\n\\nChicago Law School and civil rights attorney\\nIn 1991, Obama accepted a two-year position as Visiting Law and Government Fellow at the University of Chicago Law School to work on his first book. He then taught constitutional law at the University of Chicago Law School for twelve years, first as a lecturer from 1992 to 1996, and then as a senior lecturer from 1996 to 2004.From April to October 1992, Obama directed Illinois\\'s Project Vote, a voter registration campaign with ten staffers and seven hundred volunteer registrars; it achieved its goal of registering 150,000 of 400,000 unregistered African Americans in the state, leading Crain\\'s Chicago Business to name Obama to its 1993 list of \"40 under Forty\" powers to be.He joined Davis, Miner, Barnhill & Galland, a 13-attorney law firm specializing in civil rights litigation and neighborhood economic development, where he was an associate for three years from 1993 to 1996, then of counsel from 1996 to 2004. In 1994, he was listed as one of the lawyers in Buycks-Roberson v. Citibank Fed. Sav. Bank, 94 C 4094 (N.D. Ill.). This class action lawsuit was filed in 1994 with Selma Buycks-Roberson as lead plaintiff and alleged that Citibank Federal Savings Bank had engaged in practices forbidden under the Equal Credit Opportunity Act and the Fair Housing Act. The case was settled out of court. Final judgment was issued on May 13, 1998, with Citibank Federal Savings Bank agreeing to pay attorney fees. His law license became inactive in 2007.From 1994 to 2002, Obama served on the boards of directors of the Woods Fund of Chicago—which in 1985 had been the first foundation to fund the Developing Communities Project—and of the Joyce Foundation. He served on the board of directors of the Chicago Annenberg Challenge from 1995 to 2002, as founding president and chairman of the board of directors from 1995 to 1999.\\n\\nLegislative career\\nIllinois State Senator (1997–2004)\\nObama was elected to the Illinois Senate in 1996, succeeding Democratic State Senator Alice Palmer from Illinois\\'s 13th District, which, at that time, spanned Chicago South Side neighborhoods from Hyde Park–Kenwood south to South Shore and west to Chicago Lawn. Once elected, Obama gained bipartisan support for legislation that reformed ethics and health care laws. He sponsored a law that increased tax credits for low-income workers, negotiated welfare reform, and promoted increased subsidies for childcare. In 2001, as co-chairman of the bipartisan Joint Committee on Administrative Rules, Obama supported Republican Governor Ryan\\'s payday loan regulations and predatory mortgage lending regulations aimed at averting home foreclosures.He was reelected to the Illinois Senate in 1998, defeating Republican Yesse Yehudah in the general election, and was re-elected again in 2002. In 2000, he lost a Democratic primary race for Illinois\\'s 1st congressional district in the United States House of Representatives to four-term incumbent Bobby Rush by a margin of two to one.In January 2003, Obama became chairman of the Illinois Senate\\'s Health and Human Services Committee when Democrats, after a decade in the minority, regained a majority. He sponsored and led unanimous, bipartisan passage of legislation to monitor racial profiling by requiring police to record the race of drivers they detained, and legislation making Illinois the first state to mandate videotaping of homicide interrogations. During his 2004 general election campaign for the U.S. Senate, police representatives credited Obama for his active engagement with police organizations in enacting death penalty reforms. Obama resigned from the Illinois Senate in November 2004 following his election to the U.S. Senate.\\n\\n2004 U.S. Senate campaign\\nIn May 2002, Obama commissioned a poll to assess his prospects in a 2004 U.S. Senate race. He created a campaign committee, began raising funds, and lined up political media consultant David Axelrod by August 2002. Obama formally announced his candidacy in January 2003.Obama was an early opponent of the George W. Bush administration\\'s 2003 invasion of Iraq. On October 2, 2002, the day President Bush and Congress agreed on the joint resolution authorizing the Iraq War, Obama addressed the first high-profile Chicago anti-Iraq War rally, and spoke out against the war. He addressed another anti-war rally in March 2003 and told the crowd \"it\\'s not too late\" to stop the war.Decisions by Republican incumbent Peter Fitzgerald and his Democratic predecessor Carol Moseley Braun to not participate in the election resulted in wide-open Democratic and Republican primary contests involving 15 candidates. In the March 2004 primary election, Obama won in an unexpected landslide—which overnight made him a rising star within the national Democratic Party, started speculation about a presidential future, and led to the reissue of his memoir, Dreams from My Father. In July 2004, Obama delivered the keynote address at the 2004 Democratic National Convention, seen by nine million viewers. His speech was well received and elevated his status within the Democratic Party.Obama\\'s expected opponent in the general election, Republican primary winner Jack Ryan, withdrew from the race in June 2004. Six weeks later, Alan Keyes accepted the Republican nomination to replace Ryan. In the November 2004 general election, Obama won with 70% of the vote.\\n\\nU.S. Senator from Illinois (2005–08)\\nObama was sworn in as a senator on January 3, 2005, becoming the only Senate member of the Congressional Black Caucus. CQ Weekly characterized him as a \"loyal Democrat\" based on analysis of all Senate votes from 2005 to 2007. Obama announced on November 13, 2008, that he would resign his Senate seat on November 16, 2008, before the start of the lame-duck session, to focus on his transition period for the presidency.\\n\\nLegislation\\nObama cosponsored the Secure America and Orderly Immigration Act. He introduced two initiatives that bore his name: Lugar–Obama, which expanded the Nunn–Lugar Cooperative Threat Reduction concept to conventional weapons; and the Federal Funding Accountability and Transparency Act of 2006, which authorized the establishment of USAspending.gov, a web search engine on federal spending. On June 3, 2008, Senator Obama—along with Senators Tom Carper, Tom Coburn, and John McCain—introduced follow-up legislation: Strengthening Transparency and Accountability in Federal Spending Act of 2008.Obama sponsored legislation that would have required nuclear plant owners to notify state and local authorities of radioactive leaks, but the bill failed to pass in the full Senate after being heavily modified in committee. Regarding tort reform, Obama voted for the Class Action Fairness Act of 2005 and the FISA Amendments Act of 2008, which grants immunity from civil liability to telecommunications companies complicit with NSA warrantless wiretapping operations.\\n\\nIn December 2006, President Bush signed into law the Democratic Republic of the Congo Relief, Security, and Democracy Promotion Act, marking the first federal legislation to be enacted with Obama as its primary sponsor. In January 2007, Obama and Senator Feingold introduced a corporate jet provision to the Honest Leadership and Open Government Act, which was signed into law in September 2007. Obama also introduced two unsuccessful bills: the Deceptive Practices and Voter Intimidation Prevention Act to criminalize deceptive practices in federal elections, and the Iraq War De-Escalation Act of 2007.Later in 2007, Obama sponsored an amendment to the Defense Authorization Act to add safeguards for personality-disorder military discharges. This amendment passed the full Senate in the spring of 2008. He sponsored the Iran Sanctions Enabling Act supporting divestment of state pension funds from Iran\\'s oil and gas industry, which was never enacted but later incorporated in the Comprehensive Iran Sanctions, Accountability, and Divestment Act of 2010; and co-sponsored legislation to reduce risks of nuclear terrorism. Obama also sponsored a Senate amendment to the State Children\\'s Health Insurance Program, providing one year of job protection for family members caring for soldiers with combat-related injuries.\\n\\nCommittees\\nObama held assignments on the Senate Committees for Foreign Relations, Environment and Public Works and Veterans\\' Affairs through December 2006. In January 2007, he left the Environment and Public Works committee and took additional assignments with Health, Education, Labor and Pensions and Homeland Security and Governmental Affairs. He also became Chairman of the Senate\\'s subcommittee on European Affairs. As a member of the Senate Foreign Relations Committee, Obama made official trips to Eastern Europe, the Middle East, Central Asia and Africa. He met with Mahmoud Abbas before Abbas became President of the Palestinian National Authority, and gave a speech at the University of Nairobi in which he condemned corruption within the Kenyan government.'}],\n",
       "     'references': [{'section_num': 7,\n",
       "       'section_title': 'See also',\n",
       "       'section_content': '\\nPolitics\\nSocial policy of Barack Obama\\nDREAM Act\\nImmigration Reform and Control Act of 1986\\nList of international presidential trips made by Barack Obama\\nMiddle Class Tax Relief and Job Creation Act of 2012\\nFraud Enforcement and Recovery Act of 2009\\nNational Broadband Plan (United States)\\nOffice of Energy Efficiency and Renewable Energy\\nSPEECH Act\\nStay with It\\nWhite House Office of Energy and Climate Change Policy\\n\\nOther\\nSpeeches of Barack Obama\\nRoberts Court\\n\\nLists\\nAssassination threats against Barack Obama\\nList of people pardoned by Barack Obama\\nFederal political scandals, 2009–17\\nList of Barack Obama presidential campaign endorsements, 2008\\nList of Barack Obama presidential campaign endorsements, 2012\\nList of African-American United States Senators\\nList of things named after Barack Obama'},\n",
       "      {'section_num': 6,\n",
       "       'section_title': 'Bibliography',\n",
       "       'section_content': '\\nDreams from My Father, 1995\\nThe Audacity of Hope, 2006\\nOf Thee I Sing, 2010\\n\\nAudiobooks\\n2006: The Audacity of Hope: Thoughts on Reclaiming the American Dream (read by the author), Random House Audio, ISBN 978-0739366417'}]}}]}}"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.search(index=\"\", body={\"query\": \n",
    "                                   {\"match\": \n",
    "                                    {\"page_id\": 534366}\n",
    "                                   }})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:nbooks] *",
   "language": "python",
   "name": "conda-env-nbooks-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
