We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
The meta description is a knowl
**_1 Upvote**_ Hello,

This line:
`
<meta name="description" content="Welcome to the LMFDB, the database of L-functions, modular forms, and related objects. These pages are intended to be a modern handbook including tables, formulas, links, and references for L-functions and their underlying objects.">
`
common to all the webpages, comes from this knowl:

http://beta.lmfdb.org/knowledge/show/intro.description

see: https://github.com/LMFDB/lmfdb/blob/master/lmfdb/base.py#L203

Shouldn't this be hardcoded?

Best,
Edgar


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `lmfdb/base.py`
Content:
```
1 # -*- coding: utf8 -*-
2 # LMFDB - L-function and Modular Forms Database web-site - www.lmfdb.org
3 # Copyright (C) 2010-2012 by the LMFDB authors
4 #
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Library General Public
7 # License as published by the Free Software Foundation; either
8 # version 2 of the License, or (at your option) any later version.
9 
10 import sys
11 import logging
12 from time import sleep
13 from flask import Flask, session, g, render_template, url_for, request, redirect
14 from pymongo.cursor import Cursor
15 from pymongo.errors import AutoReconnect
16 from sage.all import *
17 from functools import wraps
18 from werkzeug.contrib.cache import SimpleCache
19 
20 # logfocus
21 logfocus = None
22 
23 def set_logfocus(lf):
24     global logfocus
25     logfocus = lf
26 
27 
28 def get_logfocus():
29     global logfocus
30     return logfocus
31 
32 # global db connection instance (will be set by the first call to
33 # getDBConnection() and should always be obtained from that)
34 _C = None
35 
36 DEFAULT_DB_PORT = 37010
37 #FIXME perhaps the global dbport removed
38 dbport = DEFAULT_DB_PORT
39 
40 
41 def getDBConnection():
42     return _C
43 
44 def makeDBConnection(port, **kwargs):
45     global _C
46     if not _C:
47         logging.info("establishing db connection at port %s ..." % port)
48         import pymongo
49         logging.info("using pymongo version %s" % pymongo.version)
50         if pymongo.version_tuple[0] >= 3 or kwargs.get("replicaset",None) is None:
51             from pymongo import MongoClient
52             _C = MongoClient(port = port,  **kwargs)
53         else:
54             from pymongo import MongoReplicaSetClient
55             _C = MongoReplicaSetClient(port = port,  **kwargs)
56         mongo_info = _C.server_info()
57         logging.info("mongodb version: %s" % mongo_info["version"])
58         logging.info("_C = %s", (_C,) )
59         #the reads are not necessarily from host/address
60         #those depend on the cursor, and can be checked with cursor.conn_id or cursor.address 
61         if pymongo.version_tuple[0] >= 3:
62             logging.info("_C.address = %s" % (_C.address,) )
63         else:
64             logging.info("_C.host = %s" % (_C.host,) )
65 
66         logging.info("_C.nodes = %s" %  (_C.nodes,) )
67         logging.info("_C.read_preference = %s" %  (_C.read_preference,) )
68 
69 
70 
71 # Global to track of many auto reconnect attempts for _db_reconnect
72 AUTO_RECONNECT_ATTEMPTS = 0
73 
74 def _db_reconnect(func):
75     """
76     Wrapper to automatically reconnect when mongodb throws a AutoReconnect exception.
77 
78     See
79       * http://stackoverflow.com/questions/5287621/occasional-connectionerror-cannot-connect-to-the-database-to-mongo
80       * http://paste.pocoo.org/show/224441/
81     and similar workarounds
82     """
83     # maximal number of auto reconnect attempts
84     AUTO_RECONNECT_MAX = 10
85     # delay between attempts
86     AUTO_RECONNECT_DELAY = 1
87 
88     def retry(*args, **kwargs):
89         global AUTO_RECONNECT_ATTEMPTS
90         while True:
91             try:
92                 return func(*args, **kwargs)
93             except AutoReconnect as e:
94                 AUTO_RECONNECT_ATTEMPTS += 1
95                 if AUTO_RECONNECT_ATTEMPTS > AUTO_RECONNECT_MAX:
96                     AUTO_RECONNECT_ATTEMPTS = 0
97                     import flask
98                     flask.flash("AutoReconnect failed to reconnect", "error")
99                     raise
100                 logging.warning(
101                     'AutoReconnect #%d - %s raised [%s]' % (AUTO_RECONNECT_ATTEMPTS, func.__name__, e))
102                 sleep(AUTO_RECONNECT_DELAY)
103     return retry
104 
105 # disabling this reconnect thing, doesn't really help anyways
106 # Cursor._Cursor__send_message = _db_reconnect(Cursor._Cursor__send_message)
107 # Connection._send_message = _db_reconnect(Connection._send_message)
108 # Connection._send_message_with_response =
109 # _db_reconnect(Connection._send_message_with_response)
110 
111 
112 def _init(port, **kwargs):
113     import pymongo
114     makeDBConnection(port = port, **kwargs)
115     C = getDBConnection()
116 
117     from os.path import dirname, join
118     pw_filename = join(dirname(dirname(__file__)), "password")
119     try:
120         username = "webserver"
121         password = open(pw_filename, "r").readlines()[0].strip()
122     except:
123         # file not found or any other problem
124         # this is read-only everywhere
125         logging.warning("authentication: no password -- fallback to read-only access")
126         username = "lmfdb"
127         password = "lmfdb"
128 
129     try:
130         C["admin"].authenticate(username, password)
131         if username == "webserver":
132             logging.info("authentication: partial read-write access enabled")
133     except pymongo.errors.PyMongoError as err:
134         logging.error("authentication: FAILED -- aborting")
135         raise err
136     #read something from the db    
137     #and check from where was it read
138     if pymongo.version_tuple[0] >= 3:
139         cursor = C.test.test.find().limit(-1)
140         list(cursor)
141         logging.info("MongoClient conection is reading from: %s" % (cursor.address,));
142     elif kwargs.get("replicaset",None) is not None:
143         cursor = C.test.test.find().limit(-1)
144         list(cursor)
145         logging.info("MongoReplicaSetClient connection is reading from: %s" % (cursor.conn_id,));
146     else:
147         logging.info("MongoClient conection is reading from: %s" % (C.host,));
148 
149 app = Flask(__name__)
150 
151 # If the debug toolbar is installed then use it
152 if app.debug:
153     try:
154         from flask_debugtoolbar import DebugToolbarExtension
155         app.config['SECRET_KEY'] = '''shh, it's a secret'''
156         toolbar = DebugToolbarExtension(app)
157     except ImportError:
158         pass
159 
160 # tell jinja to remove linebreaks
161 app.jinja_env.trim_blocks = True
162 
163 # enable break and continue in jinja loops
164 app.jinja_env.add_extension('jinja2.ext.loopcontrols')
165 app.jinja_env.add_extension('jinja2.ext.do')
166 
167 # the following context processor inserts
168 #  * empty info={} dict variable
169 #  * body_class = ''
170 #  * bread = [...] for the default bread crumb hierarch
171 #  * title = 'test string'
172 
173 
174 def is_debug_mode():
175     from flask import current_app
176     return current_app.debug
177 
178 branch = "prod"
179 if (os.getenv('BETA')=='1'):
180     branch = "beta"
181 
182 @app.before_request
183 def set_beta_state():
184     g.BETA = (os.getenv('BETA')=='1') or is_debug_mode()
185 
186 @app.context_processor
187 def ctx_proc_userdata():
188     # insert an empty info={} as default
189     # set the body class to some default, blueprints should
190     # overwrite it with their name, using @<blueprint_object>.context_processor
191     # see http://flask.pocoo.org/docs/api/?highlight=context_processor#flask.Blueprint.context_processor
192     vars = {'info': {}, 'body_class': ''}
193 
194     # insert the default bread crumb hierarchy
195     # overwrite this variable when you want to customize it
196     vars['bread'] = None  # [ ('Bread', '.'), ('Crumb', '.'), ('Hierarchy', '.')]
197 
198     # default title
199     vars['title'] = r'LMFDB'
200 
201     # meta_description appears in the meta tag "description"
202     import knowledge
203     vars['meta_description'] = knowledge.knowl.Knowl("intro.description").content
204     vars['shortthanks'] = r'This project is supported by <a href="%s">grants</a> from the US National Science Foundation and the UK Engineering and Physical Sciences Research Council.' % (url_for('acknowledgment') + "#sponsors")
205 #    vars['feedbackpage'] = url_for('contact')
206     vars['feedbackpage'] = r"https://docs.google.com/spreadsheet/viewform?formkey=dDJXYXBleU1BMTFERFFIdjVXVmJqdlE6MQ"
207     vars['LINK_EXT'] = lambda a, b: '<a href="%s" target="_blank">%s</a>' % (b, a)
208 
209     # debug mode?
210     vars['DEBUG'] = is_debug_mode()
211     vars['BETA'] = g.BETA
212 
213     return vars
214 
215 
216 # datetime format in jinja templates
217 # you can now pass in a datetime.datetime python object and via
218 # {{ <datetimeobject>|fmtdatetime }} you can format it right inside the template
219 # if you want to do more than just the default, use it for example this way:
220 # {{ <datetimeobject>|fmtdatetime('%H:%M:%S') }}
221 @app.template_filter("fmtdatetime")
222 def fmtdatetime(value, format='%Y-%m-%d %H:%M:%S'):
223     import datetime
224     if isinstance(value, datetime.datetime):
225         return value.strftime(format)
226     else:
227         return "-"
228 
229 
230 @app.template_filter("nl2br")
231 def nl2br(s):
232     return s.replace('\n', '<br>\n')
233 
234 
235 @app.template_filter('obfuscate_email')
236 def obfuscate_email(email):
237     """
238     obfuscating the email
239     TODO: doesn't work yet
240     """
241     return u"%s…@…%s" % (email[:2], email[-2:])
242 
243 
244 @app.template_filter('urlencode')
245 def urlencode(kwargs):
246     import urllib
247     return urllib.urlencode(kwargs)
248 
249 # start: link to google code at the bottom
250 
251 
252 def git_infos():
253     try:
254         from subprocess import Popen, PIPE
255         git_rev_cmd = '''git rev-parse HEAD'''
256         git_date_cmd = '''git show --format="%ci" -s HEAD'''
257         rev = Popen([git_rev_cmd], shell=True, stdout=PIPE).communicate()[0]
258         date = Popen([git_date_cmd], shell=True, stdout=PIPE).communicate()[0]
259         cmd_output = rev, date
260     except e:
261         cmd_output = '-', '-'
262     return cmd_output
263 
264 git_rev, git_date = git_infos()
265 from sage.env import SAGE_VERSION
266 
267 """
268 Creates link to the source code at the most recent commit.
269 """
270 _url_source = 'https://github.com/LMFDB/lmfdb/tree/'
271 _current_source = '<a href="%s%s">%s</a>' % (_url_source, git_rev, "Source")
272 """
273 Creates link to the list of revisions on the master, where the most recent commit is on top.
274 """
275 _url_changeset = 'https://github.com/LMFDB/lmfdb/commits/%s' % branch
276 _latest_changeset = '<a href="%s">%s</a>' % (_url_changeset, git_date)
277 
278 
279 @app.context_processor
280 def link_to_current_source():
281     return {'current_source': _current_source,
282             'latest_changeset': _latest_changeset,
283             'sage_version': 'SageMath version %s' % SAGE_VERSION}
284 
285 # end: google code links
286 
287 
288 # for testing.py ###
289 import unittest2
290 
291 
292 class DoctestExampleTest(object):
293 
294     """
295     This is a general purpose class with a doctest
296     """
297 
298     def __init__(self, k):
299         self.k = k
300 
301     def i_am_tested(self, n):
302         """
303         >>> det = DoctestExampleTest(5)
304         >>> det.i_am_tested(1)
305         47
306         """
307         return n * 42 + self.k
308 
309     def __str__(self):
310         """
311         >>> det = DoctestExampleTest(42)
312         >>> print(det)
313         I am 42
314         """
315         return "I am %d" % self.k
316 
317 
318 class LmfdbTest(unittest2.TestCase):
319 
320     def setUp(self):
321         app.config['TESTING'] = True
322         self.app = app
323         self.tc = app.test_client()
324         import lmfdb.website
325         self.C = getDBConnection()
326
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/lmfdb/base.py b/lmfdb/base.py
--- a/lmfdb/base.py
+++ b/lmfdb/base.py
@@ -33,8 +33,9 @@
 # getDBConnection() and should always be obtained from that)
 _C = None
 
+#FIXME perhaps the globals dbport and DEFAULT_DB_PORT should be removed?
+#we could had it a default argument to makeDBConnection
 DEFAULT_DB_PORT = 37010
-#FIXME perhaps the global dbport removed
 dbport = DEFAULT_DB_PORT
 
 
@@ -200,7 +201,7 @@
 
     # meta_description appears in the meta tag "description"
     import knowledge
-    vars['meta_description'] = knowledge.knowl.Knowl("intro.description").content
+    vars['meta_description'] = r'Welcome to the LMFDB, the database of L-functions, modular forms, and related objects. These pages are intended to be a modern handbook including tables, formulas, links, and references for L-functions and their underlying objects.'
     vars['shortthanks'] = r'This project is supported by <a href="%s">grants</a> from the US National Science Foundation and the UK Engineering and Physical Sciences Research Council.' % (url_for('acknowledgment') + "#sponsors")
 #    vars['feedbackpage'] = url_for('contact')
     vars['feedbackpage'] = r"https://docs.google.com/spreadsheet/viewform?formkey=dDJXYXBleU1BMTFERFFIdjVXVmJqdlE6MQ"

{"golden_diff": "diff --git a/lmfdb/base.py b/lmfdb/base.py\n--- a/lmfdb/base.py\n+++ b/lmfdb/base.py\n@@ -33,8 +33,9 @@\n # getDBConnection() and should always be obtained from that)\n _C = None\n \n+#FIXME perhaps the globals dbport and DEFAULT_DB_PORT should be removed?\n+#we could had it a default argument to makeDBConnection\n DEFAULT_DB_PORT = 37010\n-#FIXME perhaps the global dbport removed\n dbport = DEFAULT_DB_PORT\n \n \n@@ -200,7 +201,7 @@\n \n     # meta_description appears in the meta tag \"description\"\n     import knowledge\n-    vars['meta_description'] = knowledge.knowl.Knowl(\"intro.description\").content\n+    vars['meta_description'] = r'Welcome to the LMFDB, the database of L-functions, modular forms, and related objects. These pages are intended to be a modern handbook including tables, formulas, links, and references for L-functions and their underlying objects.'\n     vars['shortthanks'] = r'This project is supported by <a href=\"%s\">grants</a> from the US National Science Foundation and the UK Engineering and Physical Sciences Research Council.' % (url_for('acknowledgment') + \"#sponsors\")\n #    vars['feedbackpage'] = url_for('contact')\n     vars['feedbackpage'] = r\"https://docs.google.com/spreadsheet/viewform?formkey=dDJXYXBleU1BMTFERFFIdjVXVmJqdlE6MQ\"\n", "issue": "The meta description is a knowl\n**_1 Upvote**_ Hello,\n\nThis line:\n`\n<meta name=\"description\" content=\"Welcome to the LMFDB, the database of L-functions, modular forms, and related objects. These pages are intended to be a modern handbook including tables, formulas, links, and references for L-functions and their underlying objects.\">\n`\ncommon to all the webpages, comes from this knowl:\n\nhttp://beta.lmfdb.org/knowledge/show/intro.description\n\nsee: https://github.com/LMFDB/lmfdb/blob/master/lmfdb/base.py#L203\n\nShouldn't this be hardcoded?\n\nBest,\nEdgar\n\n", "before_files": [{"content": "# -*- coding: utf8 -*-\n# LMFDB - L-function and Modular Forms Database web-site - www.lmfdb.org\n# Copyright (C) 2010-2012 by the LMFDB authors\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; either\n# version 2 of the License, or (at your option) any later version.\n\nimport sys\nimport logging\nfrom time import sleep\nfrom flask import Flask, session, g, render_template, url_for, request, redirect\nfrom pymongo.cursor import Cursor\nfrom pymongo.errors import AutoReconnect\nfrom sage.all import *\nfrom functools import wraps\nfrom werkzeug.contrib.cache import SimpleCache\n\n# logfocus\nlogfocus = None\n\ndef set_logfocus(lf):\n    global logfocus\n    logfocus = lf\n\n\ndef get_logfocus():\n    global logfocus\n    return logfocus\n\n# global db connection instance (will be set by the first call to\n# getDBConnection() and should always be obtained from that)\n_C = None\n\nDEFAULT_DB_PORT = 37010\n#FIXME perhaps the global dbport removed\ndbport = DEFAULT_DB_PORT\n\n\ndef getDBConnection():\n    return _C\n\ndef makeDBConnection(port, **kwargs):\n    global _C\n    if not _C:\n        logging.info(\"establishing db connection at port %s ...\" % port)\n        import pymongo\n        logging.info(\"using pymongo version %s\" % pymongo.version)\n        if pymongo.version_tuple[0] >= 3 or kwargs.get(\"replicaset\",None) is None:\n            from pymongo import MongoClient\n            _C = MongoClient(port = port,  **kwargs)\n        else:\n            from pymongo import MongoReplicaSetClient\n            _C = MongoReplicaSetClient(port = port,  **kwargs)\n        mongo_info = _C.server_info()\n        logging.info(\"mongodb version: %s\" % mongo_info[\"version\"])\n        logging.info(\"_C = %s\", (_C,) )\n        #the reads are not necessarily from host/address\n        #those depend on the cursor, and can be checked with cursor.conn_id or cursor.address \n        if pymongo.version_tuple[0] >= 3:\n            logging.info(\"_C.address = %s\" % (_C.address,) )\n        else:\n            logging.info(\"_C.host = %s\" % (_C.host,) )\n\n        logging.info(\"_C.nodes = %s\" %  (_C.nodes,) )\n        logging.info(\"_C.read_preference = %s\" %  (_C.read_preference,) )\n\n\n\n# Global to track of many auto reconnect attempts for _db_reconnect\nAUTO_RECONNECT_ATTEMPTS = 0\n\ndef _db_reconnect(func):\n    \"\"\"\n    Wrapper to automatically reconnect when mongodb throws a AutoReconnect exception.\n\n    See\n      * http://stackoverflow.com/questions/5287621/occasional-connectionerror-cannot-connect-to-the-database-to-mongo\n      * http://paste.pocoo.org/show/224441/\n    and similar workarounds\n    \"\"\"\n    # maximal number of auto reconnect attempts\n    AUTO_RECONNECT_MAX = 10\n    # delay between attempts\n    AUTO_RECONNECT_DELAY = 1\n\n    def retry(*args, **kwargs):\n        global AUTO_RECONNECT_ATTEMPTS\n        while True:\n            try:\n                return func(*args, **kwargs)\n            except AutoReconnect as e:\n                AUTO_RECONNECT_ATTEMPTS += 1\n                if AUTO_RECONNECT_ATTEMPTS > AUTO_RECONNECT_MAX:\n                    AUTO_RECONNECT_ATTEMPTS = 0\n                    import flask\n                    flask.flash(\"AutoReconnect failed to reconnect\", \"error\")\n                    raise\n                logging.warning(\n                    'AutoReconnect #%d - %s raised [%s]' % (AUTO_RECONNECT_ATTEMPTS, func.__name__, e))\n                sleep(AUTO_RECONNECT_DELAY)\n    return retry\n\n# disabling this reconnect thing, doesn't really help anyways\n# Cursor._Cursor__send_message = _db_reconnect(Cursor._Cursor__send_message)\n# Connection._send_message = _db_reconnect(Connection._send_message)\n# Connection._send_message_with_response =\n# _db_reconnect(Connection._send_message_with_response)\n\n\ndef _init(port, **kwargs):\n    import pymongo\n    makeDBConnection(port = port, **kwargs)\n    C = getDBConnection()\n\n    from os.path import dirname, join\n    pw_filename = join(dirname(dirname(__file__)), \"password\")\n    try:\n        username = \"webserver\"\n        password = open(pw_filename, \"r\").readlines()[0].strip()\n    except:\n        # file not found or any other problem\n        # this is read-only everywhere\n        logging.warning(\"authentication: no password -- fallback to read-only access\")\n        username = \"lmfdb\"\n        password = \"lmfdb\"\n\n    try:\n        C[\"admin\"].authenticate(username, password)\n        if username == \"webserver\":\n            logging.info(\"authentication: partial read-write access enabled\")\n    except pymongo.errors.PyMongoError as err:\n        logging.error(\"authentication: FAILED -- aborting\")\n        raise err\n    #read something from the db    \n    #and check from where was it read\n    if pymongo.version_tuple[0] >= 3:\n        cursor = C.test.test.find().limit(-1)\n        list(cursor)\n        logging.info(\"MongoClient conection is reading from: %s\" % (cursor.address,));\n    elif kwargs.get(\"replicaset\",None) is not None:\n        cursor = C.test.test.find().limit(-1)\n        list(cursor)\n        logging.info(\"MongoReplicaSetClient connection is reading from: %s\" % (cursor.conn_id,));\n    else:\n        logging.info(\"MongoClient conection is reading from: %s\" % (C.host,));\n\napp = Flask(__name__)\n\n# If the debug toolbar is installed then use it\nif app.debug:\n    try:\n        from flask_debugtoolbar import DebugToolbarExtension\n        app.config['SECRET_KEY'] = '''shh, it's a secret'''\n        toolbar = DebugToolbarExtension(app)\n    except ImportError:\n        pass\n\n# tell jinja to remove linebreaks\napp.jinja_env.trim_blocks = True\n\n# enable break and continue in jinja loops\napp.jinja_env.add_extension('jinja2.ext.loopcontrols')\napp.jinja_env.add_extension('jinja2.ext.do')\n\n# the following context processor inserts\n#  * empty info={} dict variable\n#  * body_class = ''\n#  * bread = [...] for the default bread crumb hierarch\n#  * title = 'test string'\n\n\ndef is_debug_mode():\n    from flask import current_app\n    return current_app.debug\n\nbranch = \"prod\"\nif (os.getenv('BETA')=='1'):\n    branch = \"beta\"\n\n@app.before_request\ndef set_beta_state():\n    g.BETA = (os.getenv('BETA')=='1') or is_debug_mode()\n\n@app.context_processor\ndef ctx_proc_userdata():\n    # insert an empty info={} as default\n    # set the body class to some default, blueprints should\n    # overwrite it with their name, using @<blueprint_object>.context_processor\n    # see http://flask.pocoo.org/docs/api/?highlight=context_processor#flask.Blueprint.context_processor\n    vars = {'info': {}, 'body_class': ''}\n\n    # insert the default bread crumb hierarchy\n    # overwrite this variable when you want to customize it\n    vars['bread'] = None  # [ ('Bread', '.'), ('Crumb', '.'), ('Hierarchy', '.')]\n\n    # default title\n    vars['title'] = r'LMFDB'\n\n    # meta_description appears in the meta tag \"description\"\n    import knowledge\n    vars['meta_description'] = knowledge.knowl.Knowl(\"intro.description\").content\n    vars['shortthanks'] = r'This project is supported by <a href=\"%s\">grants</a> from the US National Science Foundation and the UK Engineering and Physical Sciences Research Council.' % (url_for('acknowledgment') + \"#sponsors\")\n#    vars['feedbackpage'] = url_for('contact')\n    vars['feedbackpage'] = r\"https://docs.google.com/spreadsheet/viewform?formkey=dDJXYXBleU1BMTFERFFIdjVXVmJqdlE6MQ\"\n    vars['LINK_EXT'] = lambda a, b: '<a href=\"%s\" target=\"_blank\">%s</a>' % (b, a)\n\n    # debug mode?\n    vars['DEBUG'] = is_debug_mode()\n    vars['BETA'] = g.BETA\n\n    return vars\n\n\n# datetime format in jinja templates\n# you can now pass in a datetime.datetime python object and via\n# {{ <datetimeobject>|fmtdatetime }} you can format it right inside the template\n# if you want to do more than just the default, use it for example this way:\n# {{ <datetimeobject>|fmtdatetime('%H:%M:%S') }}\n@app.template_filter(\"fmtdatetime\")\ndef fmtdatetime(value, format='%Y-%m-%d %H:%M:%S'):\n    import datetime\n    if isinstance(value, datetime.datetime):\n        return value.strftime(format)\n    else:\n        return \"-\"\n\n\n@app.template_filter(\"nl2br\")\ndef nl2br(s):\n    return s.replace('\\n', '<br>\\n')\n\n\n@app.template_filter('obfuscate_email')\ndef obfuscate_email(email):\n    \"\"\"\n    obfuscating the email\n    TODO: doesn't work yet\n    \"\"\"\n    return u\"%s\u2026@\u2026%s\" % (email[:2], email[-2:])\n\n\n@app.template_filter('urlencode')\ndef urlencode(kwargs):\n    import urllib\n    return urllib.urlencode(kwargs)\n\n# start: link to google code at the bottom\n\n\ndef git_infos():\n    try:\n        from subprocess import Popen, PIPE\n        git_rev_cmd = '''git rev-parse HEAD'''\n        git_date_cmd = '''git show --format=\"%ci\" -s HEAD'''\n        rev = Popen([git_rev_cmd], shell=True, stdout=PIPE).communicate()[0]\n        date = Popen([git_date_cmd], shell=True, stdout=PIPE).communicate()[0]\n        cmd_output = rev, date\n    except e:\n        cmd_output = '-', '-'\n    return cmd_output\n\ngit_rev, git_date = git_infos()\nfrom sage.env import SAGE_VERSION\n\n\"\"\"\nCreates link to the source code at the most recent commit.\n\"\"\"\n_url_source = 'https://github.com/LMFDB/lmfdb/tree/'\n_current_source = '<a href=\"%s%s\">%s</a>' % (_url_source, git_rev, \"Source\")\n\"\"\"\nCreates link to the list of revisions on the master, where the most recent commit is on top.\n\"\"\"\n_url_changeset = 'https://github.com/LMFDB/lmfdb/commits/%s' % branch\n_latest_changeset = '<a href=\"%s\">%s</a>' % (_url_changeset, git_date)\n\n\n@app.context_processor\ndef link_to_current_source():\n    return {'current_source': _current_source,\n            'latest_changeset': _latest_changeset,\n            'sage_version': 'SageMath version %s' % SAGE_VERSION}\n\n# end: google code links\n\n\n# for testing.py ###\nimport unittest2\n\n\nclass DoctestExampleTest(object):\n\n    \"\"\"\n    This is a general purpose class with a doctest\n    \"\"\"\n\n    def __init__(self, k):\n        self.k = k\n\n    def i_am_tested(self, n):\n        \"\"\"\n        >>> det = DoctestExampleTest(5)\n        >>> det.i_am_tested(1)\n        47\n        \"\"\"\n        return n * 42 + self.k\n\n    def __str__(self):\n        \"\"\"\n        >>> det = DoctestExampleTest(42)\n        >>> print(det)\n        I am 42\n        \"\"\"\n        return \"I am %d\" % self.k\n\n\nclass LmfdbTest(unittest2.TestCase):\n\n    def setUp(self):\n        app.config['TESTING'] = True\n        self.app = app\n        self.tc = app.test_client()\n        import lmfdb.website\n        self.C = getDBConnection()\n", "path": "lmfdb/base.py"}], "after_files": [{"content": "# -*- coding: utf8 -*-\n# LMFDB - L-function and Modular Forms Database web-site - www.lmfdb.org\n# Copyright (C) 2010-2012 by the LMFDB authors\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; either\n# version 2 of the License, or (at your option) any later version.\n\nimport sys\nimport logging\nfrom time import sleep\nfrom flask import Flask, session, g, render_template, url_for, request, redirect\nfrom pymongo.cursor import Cursor\nfrom pymongo.errors import AutoReconnect\nfrom sage.all import *\nfrom functools import wraps\nfrom werkzeug.contrib.cache import SimpleCache\n\n# logfocus\nlogfocus = None\n\ndef set_logfocus(lf):\n    global logfocus\n    logfocus = lf\n\n\ndef get_logfocus():\n    global logfocus\n    return logfocus\n\n# global db connection instance (will be set by the first call to\n# getDBConnection() and should always be obtained from that)\n_C = None\n\n#FIXME perhaps the globals dbport and DEFAULT_DB_PORT should be removed?\n#we could had it a default argument to makeDBConnection\nDEFAULT_DB_PORT = 37010\ndbport = DEFAULT_DB_PORT\n\n\ndef getDBConnection():\n    return _C\n\ndef makeDBConnection(port, **kwargs):\n    global _C\n    if not _C:\n        logging.info(\"establishing db connection at port %s ...\" % port)\n        import pymongo\n        logging.info(\"using pymongo version %s\" % pymongo.version)\n        if pymongo.version_tuple[0] >= 3 or kwargs.get(\"replicaset\",None) is None:\n            from pymongo import MongoClient\n            _C = MongoClient(port = port,  **kwargs)\n        else:\n            from pymongo import MongoReplicaSetClient\n            _C = MongoReplicaSetClient(port = port,  **kwargs)\n        mongo_info = _C.server_info()\n        logging.info(\"mongodb version: %s\" % mongo_info[\"version\"])\n        logging.info(\"_C = %s\", (_C,) )\n        #the reads are not necessarily from host/address\n        #those depend on the cursor, and can be checked with cursor.conn_id or cursor.address \n        if pymongo.version_tuple[0] >= 3:\n            logging.info(\"_C.address = %s\" % (_C.address,) )\n        else:\n            logging.info(\"_C.host = %s\" % (_C.host,) )\n\n        logging.info(\"_C.nodes = %s\" %  (_C.nodes,) )\n        logging.info(\"_C.read_preference = %s\" %  (_C.read_preference,) )\n\n\n\n# Global to track of many auto reconnect attempts for _db_reconnect\nAUTO_RECONNECT_ATTEMPTS = 0\n\ndef _db_reconnect(func):\n    \"\"\"\n    Wrapper to automatically reconnect when mongodb throws a AutoReconnect exception.\n\n    See\n      * http://stackoverflow.com/questions/5287621/occasional-connectionerror-cannot-connect-to-the-database-to-mongo\n      * http://paste.pocoo.org/show/224441/\n    and similar workarounds\n    \"\"\"\n    # maximal number of auto reconnect attempts\n    AUTO_RECONNECT_MAX = 10\n    # delay between attempts\n    AUTO_RECONNECT_DELAY = 1\n\n    def retry(*args, **kwargs):\n        global AUTO_RECONNECT_ATTEMPTS\n        while True:\n            try:\n                return func(*args, **kwargs)\n            except AutoReconnect as e:\n                AUTO_RECONNECT_ATTEMPTS += 1\n                if AUTO_RECONNECT_ATTEMPTS > AUTO_RECONNECT_MAX:\n                    AUTO_RECONNECT_ATTEMPTS = 0\n                    import flask\n                    flask.flash(\"AutoReconnect failed to reconnect\", \"error\")\n                    raise\n                logging.warning(\n                    'AutoReconnect #%d - %s raised [%s]' % (AUTO_RECONNECT_ATTEMPTS, func.__name__, e))\n                sleep(AUTO_RECONNECT_DELAY)\n    return retry\n\n# disabling this reconnect thing, doesn't really help anyways\n# Cursor._Cursor__send_message = _db_reconnect(Cursor._Cursor__send_message)\n# Connection._send_message = _db_reconnect(Connection._send_message)\n# Connection._send_message_with_response =\n# _db_reconnect(Connection._send_message_with_response)\n\n\ndef _init(port, **kwargs):\n    import pymongo\n    makeDBConnection(port = port, **kwargs)\n    C = getDBConnection()\n\n    from os.path import dirname, join\n    pw_filename = join(dirname(dirname(__file__)), \"password\")\n    try:\n        username = \"webserver\"\n        password = open(pw_filename, \"r\").readlines()[0].strip()\n    except:\n        # file not found or any other problem\n        # this is read-only everywhere\n        logging.warning(\"authentication: no password -- fallback to read-only access\")\n        username = \"lmfdb\"\n        password = \"lmfdb\"\n\n    try:\n        C[\"admin\"].authenticate(username, password)\n        if username == \"webserver\":\n            logging.info(\"authentication: partial read-write access enabled\")\n    except pymongo.errors.PyMongoError as err:\n        logging.error(\"authentication: FAILED -- aborting\")\n        raise err\n    #read something from the db    \n    #and check from where was it read\n    if pymongo.version_tuple[0] >= 3:\n        cursor = C.test.test.find().limit(-1)\n        list(cursor)\n        logging.info(\"MongoClient conection is reading from: %s\" % (cursor.address,));\n    elif kwargs.get(\"replicaset\",None) is not None:\n        cursor = C.test.test.find().limit(-1)\n        list(cursor)\n        logging.info(\"MongoReplicaSetClient connection is reading from: %s\" % (cursor.conn_id,));\n    else:\n        logging.info(\"MongoClient conection is reading from: %s\" % (C.host,));\n\napp = Flask(__name__)\n\n# If the debug toolbar is installed then use it\nif app.debug:\n    try:\n        from flask_debugtoolbar import DebugToolbarExtension\n        app.config['SECRET_KEY'] = '''shh, it's a secret'''\n        toolbar = DebugToolbarExtension(app)\n    except ImportError:\n        pass\n\n# tell jinja to remove linebreaks\napp.jinja_env.trim_blocks = True\n\n# enable break and continue in jinja loops\napp.jinja_env.add_extension('jinja2.ext.loopcontrols')\napp.jinja_env.add_extension('jinja2.ext.do')\n\n# the following context processor inserts\n#  * empty info={} dict variable\n#  * body_class = ''\n#  * bread = [...] for the default bread crumb hierarch\n#  * title = 'test string'\n\n\ndef is_debug_mode():\n    from flask import current_app\n    return current_app.debug\n\nbranch = \"prod\"\nif (os.getenv('BETA')=='1'):\n    branch = \"beta\"\n\n@app.before_request\ndef set_beta_state():\n    g.BETA = (os.getenv('BETA')=='1') or is_debug_mode()\n\n@app.context_processor\ndef ctx_proc_userdata():\n    # insert an empty info={} as default\n    # set the body class to some default, blueprints should\n    # overwrite it with their name, using @<blueprint_object>.context_processor\n    # see http://flask.pocoo.org/docs/api/?highlight=context_processor#flask.Blueprint.context_processor\n    vars = {'info': {}, 'body_class': ''}\n\n    # insert the default bread crumb hierarchy\n    # overwrite this variable when you want to customize it\n    vars['bread'] = None  # [ ('Bread', '.'), ('Crumb', '.'), ('Hierarchy', '.')]\n\n    # default title\n    vars['title'] = r'LMFDB'\n\n    # meta_description appears in the meta tag \"description\"\n    import knowledge\n    vars['meta_description'] = r'Welcome to the LMFDB, the database of L-functions, modular forms, and related objects. These pages are intended to be a modern handbook including tables, formulas, links, and references for L-functions and their underlying objects.'\n    vars['shortthanks'] = r'This project is supported by <a href=\"%s\">grants</a> from the US National Science Foundation and the UK Engineering and Physical Sciences Research Council.' % (url_for('acknowledgment') + \"#sponsors\")\n#    vars['feedbackpage'] = url_for('contact')\n    vars['feedbackpage'] = r\"https://docs.google.com/spreadsheet/viewform?formkey=dDJXYXBleU1BMTFERFFIdjVXVmJqdlE6MQ\"\n    vars['LINK_EXT'] = lambda a, b: '<a href=\"%s\" target=\"_blank\">%s</a>' % (b, a)\n\n    # debug mode?\n    vars['DEBUG'] = is_debug_mode()\n    vars['BETA'] = g.BETA\n\n    return vars\n\n\n# datetime format in jinja templates\n# you can now pass in a datetime.datetime python object and via\n# {{ <datetimeobject>|fmtdatetime }} you can format it right inside the template\n# if you want to do more than just the default, use it for example this way:\n# {{ <datetimeobject>|fmtdatetime('%H:%M:%S') }}\n@app.template_filter(\"fmtdatetime\")\ndef fmtdatetime(value, format='%Y-%m-%d %H:%M:%S'):\n    import datetime\n    if isinstance(value, datetime.datetime):\n        return value.strftime(format)\n    else:\n        return \"-\"\n\n\n@app.template_filter(\"nl2br\")\ndef nl2br(s):\n    return s.replace('\\n', '<br>\\n')\n\n\n@app.template_filter('obfuscate_email')\ndef obfuscate_email(email):\n    \"\"\"\n    obfuscating the email\n    TODO: doesn't work yet\n    \"\"\"\n    return u\"%s\u2026@\u2026%s\" % (email[:2], email[-2:])\n\n\n@app.template_filter('urlencode')\ndef urlencode(kwargs):\n    import urllib\n    return urllib.urlencode(kwargs)\n\n# start: link to google code at the bottom\n\n\ndef git_infos():\n    try:\n        from subprocess import Popen, PIPE\n        git_rev_cmd = '''git rev-parse HEAD'''\n        git_date_cmd = '''git show --format=\"%ci\" -s HEAD'''\n        rev = Popen([git_rev_cmd], shell=True, stdout=PIPE).communicate()[0]\n        date = Popen([git_date_cmd], shell=True, stdout=PIPE).communicate()[0]\n        cmd_output = rev, date\n    except e:\n        cmd_output = '-', '-'\n    return cmd_output\n\ngit_rev, git_date = git_infos()\nfrom sage.env import SAGE_VERSION\n\n\"\"\"\nCreates link to the source code at the most recent commit.\n\"\"\"\n_url_source = 'https://github.com/LMFDB/lmfdb/tree/'\n_current_source = '<a href=\"%s%s\">%s</a>' % (_url_source, git_rev, \"Source\")\n\"\"\"\nCreates link to the list of revisions on the master, where the most recent commit is on top.\n\"\"\"\n_url_changeset = 'https://github.com/LMFDB/lmfdb/commits/%s' % branch\n_latest_changeset = '<a href=\"%s\">%s</a>' % (_url_changeset, git_date)\n\n\n@app.context_processor\ndef link_to_current_source():\n    return {'current_source': _current_source,\n            'latest_changeset': _latest_changeset,\n            'sage_version': 'SageMath version %s' % SAGE_VERSION}\n\n# end: google code links\n\n\n# for testing.py ###\nimport unittest2\n\n\nclass DoctestExampleTest(object):\n\n    \"\"\"\n    This is a general purpose class with a doctest\n    \"\"\"\n\n    def __init__(self, k):\n        self.k = k\n\n    def i_am_tested(self, n):\n        \"\"\"\n        >>> det = DoctestExampleTest(5)\n        >>> det.i_am_tested(1)\n        47\n        \"\"\"\n        return n * 42 + self.k\n\n    def __str__(self):\n        \"\"\"\n        >>> det = DoctestExampleTest(42)\n        >>> print(det)\n        I am 42\n        \"\"\"\n        return \"I am %d\" % self.k\n\n\nclass LmfdbTest(unittest2.TestCase):\n\n    def setUp(self):\n        app.config['TESTING'] = True\n        self.app = app\n        self.tc = app.test_client()\n        import lmfdb.website\n        self.C = getDBConnection()\n", "path": "lmfdb/base.py"}]}