changeset 6335:9c6f717823e1

Merge stable
author Mads Kiilerich <madski@unity3d.com>
date Fri, 18 Nov 2016 01:11:13 +0100
parents 73654990ba75 (diff) cc21a2b86a30 (current diff)
children f9fefa7cb008
files docs/contributing.rst docs/index.rst docs/setup.rst docs/usage/troubleshooting.rst
diffstat 498 files changed, 42221 insertions(+), 65167 deletions(-) [+]
line wrap: on
line diff
--- a/.hgignore	Thu Nov 17 13:09:43 2016 +0800
+++ b/.hgignore	Fri Nov 18 01:11:13 2016 +0100
@@ -16,7 +16,6 @@
 ^docs/build/
 ^docs/_build/
 ^data$
-^kallithea/tests/data$
 ^sql_dumps/
 ^\.settings$
 ^\.project$
@@ -29,3 +28,4 @@
 ^fabfile.py
 ^\.idea$
 ^\.cache$
+/__pycache__$
--- a/CONTRIBUTORS	Thu Nov 17 13:09:43 2016 +0800
+++ b/CONTRIBUTORS	Fri Nov 18 01:11:13 2016 +0100
@@ -4,16 +4,26 @@
     Takumi IINO <trot.thunder@gmail.com> 2012-2016
     Unity Technologies 2012-2016
     Andrew Shadura <andrew@shadura.me> 2012 2014-2016
-    Dominik Ruf <dominikruf@gmail.com> 2012 2014 2016
+    Dominik Ruf <dominikruf@gmail.com> 2012 2014-2016
+    Thomas De Schampheleire <thomas.de.schampheleire@gmail.com> 2014-2016
+    Étienne Gilli <etienne.gilli@gmail.com> 2015-2016
+    Jan Heylen <heyleke@gmail.com> 2015-2016
+    Robert Martinez <ntttq@inboxen.org> 2015-2016
+    Robert Rauch <mail@robertrauch.de> 2015-2016
     Søren Løvborg <sorenl@unity3d.com> 2015-2016
+    Angel Ezquerra <angel.ezquerra@gmail.com> 2016
+    Asterios Dimitriou <steve@pci.gr> 2016
+    Kateryna Musina <kateryna@unity3d.com> 2016
     Konstantin Veretennicov <kveretennicov@gmail.com> 2016
+    Oscar Curero <oscar@naiandei.net> 2016
     Robert James Dennington <tinytimrob@googlemail.com> 2016
+    timeless@gmail.com 2016
+    YFdyh000 <yfdyh000@gmail.com> 2016
     Aras Pranckevičius <aras@unity3d.com> 2012-2013 2015
     Sean Farley <sean.michael.farley@gmail.com> 2013-2015
     Christian Oyarzun <oyarzun@gmail.com> 2014-2015
     Joseph Rivera <rivera.d.joseph@gmail.com> 2014-2015
     Michal Čihař <michal@cihar.com> 2014-2015
-    Thomas De Schampheleire <thomas.de.schampheleire@gmail.com> 2014-2015
     Anatoly Bubenkov <bubenkoff@gmail.com> 2015
     Andrew Bartlett <abartlet@catalyst.net.nz> 2015
     Balázs Úr <urbalazs@gmail.com> 2015
@@ -24,9 +34,8 @@
     Denis Blanchette <dblanchette@coveo.com> 2015
     duanhongyi <duanhongyi@doopai.com> 2015
     EriCSN Chang <ericsning@gmail.com> 2015
-    Étienne Gilli <etienne.gilli@gmail.com> 2015
     Grzegorz Krason <grzegorz.krason@gmail.com> 2015
-    Jan Heylen <heyleke@gmail.com> 2015
+    Jiří Suchan <yed@vanyli.net> 2015
     Kazunari Kobayashi <kobanari@nifty.com> 2015
     Kevin Bullock <kbullock@ringworld.org> 2015
     kobanari <kobanari@nifty.com> 2015
@@ -39,12 +48,11 @@
     Nick High <nick@silverchip.org> 2015
     Niemand Jedermann <predatorix@web.de> 2015
     Peter Vitt <petervitt@web.de> 2015
-    Robert Martinez <ntttq@inboxen.org> 2015
-    Robert Rauch <mail@robertrauch.de> 2015
     Ronny Pfannschmidt <opensource@ronnypfannschmidt.de> 2015
     Sam Jaques <sam.jaques@me.com> 2015
     Tuux <tuxa@galaxie.eu.org> 2015
     Viktar Palstsiuk <vipals@gmail.com> 2015
+    Ante Ilic <ante@unity3d.com> 2014
     Bradley M. Kuhn <bkuhn@sfconservancy.org> 2014
     Calinou <calinou@opmbx.org> 2014
     Daniel Anderson <daniel@dattrix.com> 2014
--- a/LICENSE.md	Thu Nov 17 13:09:43 2016 +0800
+++ b/LICENSE.md	Fri Nov 18 01:11:13 2016 +0100
@@ -22,20 +22,33 @@
 of Kallithea.
 
 
+Alembic
+-------
+
+Kallithea incorporates an [Alembic](http://alembic.zzzcomputing.com/en/latest/)
+"migration environment" in `kallithea/alembic`, portions of which is:
+
+Copyright &copy; 2009-2016 by Michael Bayer.
+Alembic is a trademark of Michael Bayer.
+
+and licensed under the MIT-permissive license, which is
+[included in this distribution](MIT-Permissive-License.txt).
+
 
 Bootstrap
 ---------
 
-Kallithea incorporates parts of the Javascript system called
+Kallithea incorporates the web framework called
 [Bootstrap](http://getbootstrap.com/), which is:
 
-Copyright &copy; 2012 Twitter, Inc.
+Copyright &copy; 2011-2016 Twitter, Inc.
+Copyright &copy; 2011-2016 The Bootstrap Authors
 
-and licensed under
-[the Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0.html).
-
-A copy of the Apache License 2.0 is also included in this distribution in its
-entirety in the file Apache-License-2.0.txt
+and licensed under the MIT-permissive license, which is
+[included in this distribution](MIT-Permissive-License.txt),
+which can be found together with its Corresponding Source in
+https://github.com/twbs/bootstrap at tag v3.3.7 (mirrored at
+https://kallithea-scm.org/repos/mirror/bootstrap/ ).
 
 
 
@@ -62,29 +75,27 @@
 ------
 
 Kallithea incorporates the Javascript system called
-[jQuery](http://jquery.org/),
-[herein](kallithea/public/js/jquery-1.11.1.min.js), and the Corresponding
-Source can be found in https://github.com/jquery/jquery at tag 1.11.1
-(mirrored at https://kallithea-scm.org/repos/mirror/jquery/files/1.11.1/ ).
+[jQuery](http://jquery.org/), [herein](kallithea/public/js/jquery.min.js),
+which can be found together with its Corresponding Source in
+https://github.com/jquery/jquery at tag 1.12.3 (mirrored at
+https://kallithea-scm.org/repos/mirror/jquery/files/1.12.3/ ).
 
 It is Copyright 2013 jQuery Foundation and other contributors http://jquery.com/ and is under an
 [MIT-permissive license](MIT-Permissive-License.txt).
 
 
 
-Mousetrap
----------
-
-Kallithea incorporates parts of the Javascript system called
-[Mousetrap](http://craig.is/killing/mice/), which is:
+DataTables
+----------
 
-   Copyright 2013 Craig Campbell
+Kallithea incorporates the Javascript system called
+[DataTables](http://www.datatables.net/) (jquery.dataTables.min.js and .css)
+which can be found together with their Corresponding Source in
+https://github.com/DataTables/DataTables at tag 1.10.11 (mirrored at
+https://kallithea-scm.org/repos/mirror/DataTables/files/1.10.11/ ).
 
-and licensed under
-[the Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0.html).
-
-A [copy of the Apache License 2.0](Apache-License-2.0.txt) is also included
-in this distribution.
+It is Copyright 2008-2015 SpryMedia Ltd. and is under an
+[MIT-permissive license](MIT-Permissive-License.txt).
 
 
 
@@ -213,9 +224,9 @@
     git checkout hudson-yui2-2800
     ln -sf JumpToPageDropDown.js src/paginator/js/JumpToPageDropdown.js # work around inconsistent casing
     rm -f tmp.js
-    for m in yahoo event dom connection animation dragdrop element datasource autocomplete container event-delegate json datatable paginator; do
-      rm -f build/\$m/\$m.js
-      ( cd src/\$m && ant build deploybuild ) && sed -e 's,@VERSION@,2.9.0,g' -e 's,@BUILD@,2800,g' build/\$m/\$m.js >> tmp.js
+    for m in yahoo event dom animation datasource autocomplete event-delegate; do
+      rm -f build/$m/$m.js
+      ( cd src/$m && ant build deploybuild ) && sed -e 's,@VERSION@,2.9.0,g' -e 's,@BUILD@,2800,g' build/$m/$m.js >> tmp.js
     done
     java -jar ../builder/componentbuild/lib/yuicompressor/yuicompressor-2.4.4.jar tmp.js -o yui.2.9.js
 
@@ -241,19 +252,6 @@
 
 
 
-Migrate
--------
-
-Kallithea incorporates in kallithea/lib/dbmigrate/migrate parts of the Python
-system called [Migrate or sqlalchemy-migrate](https://github.com/stackforge/sqlalchemy-migrate),
-which is:
-
-Copyright (c) 2009 Evan Rosson, Jan Dittberner, Domen Kožar
-
-and licensed under the MIT-permissive license, which is
-[included in this distribution](MIT-Permissive-License.txt).
-
-
 Icon fonts
 ----------
 
--- a/MANIFEST.in	Thu Nov 17 13:09:43 2016 +0800
+++ b/MANIFEST.in	Fri Nov 18 01:11:13 2016 +0100
@@ -8,11 +8,11 @@
 include           development.ini
 recursive-include docs *
 recursive-include init.d *
+recursive-include kallithea/alembic *
 include           kallithea/bin/ldap_sync.conf
 include           kallithea/bin/template.ini.mako
 include           kallithea/config/deployment.ini_tmpl
 recursive-include kallithea/i18n *
-recursive-include kallithea/lib/dbmigrate *.py_tmpl README migrate.cfg
 recursive-include kallithea/public *
 recursive-include kallithea/templates *
 recursive-include kallithea/tests/fixtures *
--- a/README.rst	Thu Nov 17 13:09:43 2016 +0800
+++ b/README.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -162,76 +162,14 @@
           install it via the command: ``pip install sphinx`` .
 
 
-Converting from RhodeCode
--------------------------
-
-Currently, you have two options for working with an existing RhodeCode
-database:
-
-- keep the database unconverted (intended for testing and evaluation)
-- convert the database in a one-time step
-
-Maintaining interoperability
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Interoperability with RhodeCode 2.2.X installations is provided so you don't
-have to immediately commit to switching to Kallithea. This option will most
-likely go away once the two projects have diverged significantly.
-
-To run Kallithea on a RhodeCode database, run::
-
-   echo "BRAND = 'rhodecode'" > kallithea/brand.py
-
-This location will depend on where you installed Kallithea. If you installed
-via::
-
-   python2 setup.py install
-
-then you will find this location at
-``$VIRTUAL_ENV/lib/python2.7/site-packages/Kallithea-0.1-py2.7.egg/kallithea``.
-
-One-time conversion
-~~~~~~~~~~~~~~~~~~~
+Migrating from RhodeCode
+------------------------
 
-Alternatively, if you would like to convert the database for good, you can use
-a helper script provided by Kallithea. This script will operate directly on the
-database, using the database string you can find in your ``production.ini`` (or
-``development.ini``) file. For example, if using SQLite::
-
-   cd /path/to/kallithea
-   cp /path/to/rhodecode/rhodecode.db kallithea.db
-   pip install sqlalchemy-migrate
-   python2 kallithea/bin/rebranddb.py sqlite:///kallithea.db
-
-.. Note::
-
-   If you started out using the branding interoperability approach mentioned
-   above, watch out for stray brand.pyc after removing brand.py.
-
-Git hooks
-~~~~~~~~~
-
-After switching to Kallithea, it will be necessary to update the Git_ hooks in
-your repositories. If not, the Git_ hooks from RhodeCode will still be called,
-which will cause ``git push`` to fail every time.
-
-If you do not have any custom Git_ hooks deployed, perform the following steps
-(this may take some time depending on the number and size of repositories you
-have):
-
-1. Log-in as an administrator.
-
-2. Open page *Admin > Settings > Remap and Rescan*.
-
-3. Turn on the option **Install Git Hooks**.
-
-4. Turn on the option **Overwrite existing Git hooks**.
-
-5. Click on the button **Rescan Repositories**.
-
-If you do have custom hooks, you will need to merge those changes manually. In
-order to get sample hooks from Kallithea, the easiest way is to create a new Git_
-repository, and have a look at the hooks deployed there.
+Kallithea 0.3.2 and earlier supports migrating from an existing RhodeCode
+installation. To migrate, install Kallithea 0.3.2 and follow the
+instructions in the 0.3.2 README to perform a one-time conversion of the
+database from RhodeCode to Kallithea, before upgrading to this version
+of Kallithea.
 
 
 .. _virtualenv: http://pypi.python.org/pypi/virtualenv
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/dev_requirements.txt	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,7 @@
+pytest>=2.7.0,<4.0
+pytest-runner
+pytest-sugar>=0.7.0
+pytest-catchlog
+WebTest<2 # this is also a Pylons dependency and pinned in setup.py to avoid version conflicts for WebOb
+mock
+sphinx
--- a/development.ini	Thu Nov 17 13:09:43 2016 +0800
+++ b/development.ini	Fri Nov 18 01:11:13 2016 +0100
@@ -55,32 +55,31 @@
 #error_email_from = paste_error@example.com
 
 ## SMTP server settings
-## Only smtp_server is mandatory. All other settings take the specified default
-## values.
+## If specifying credentials, make sure to use secure connections.
+## Default: Send unencrypted unauthenticated mails to the specified smtp_server.
+## For "SSL", use smtp_use_ssl = true and smtp_port = 465.
+## For "STARTTLS", use smtp_use_tls = true and smtp_port = 587.
 #smtp_server = smtp.example.com
 #smtp_username =
 #smtp_password =
 #smtp_port = 25
+#smtp_use_ssl = false
 #smtp_use_tls = false
-#smtp_use_ssl = false
-## SMTP authentication parameters to use (e.g. LOGIN PLAIN CRAM-MD5, etc.).
-## If empty, use any of the authentication parameters supported by the server.
-#smtp_auth =
 
 [server:main]
 ## PASTE ##
 #use = egg:Paste#http
 ## nr of worker threads to spawn
-#threadpool_workers = 5
+#threadpool_workers = 1
 ## max request before thread respawn
-#threadpool_max_requests = 10
+#threadpool_max_requests = 100
 ## option to use threads of process
 #use_threadpool = true
 
 ## WAITRESS ##
 use = egg:waitress#main
 ## number of worker threads
-threads = 5
+threads = 1
 ## MAX BODY SIZE 100GB
 max_request_body_size = 107374182400
 ## use poll instead of select, fixes fd limits, may not work on old
@@ -98,7 +97,7 @@
 ## recommended for bigger setup is using of of other than sync one
 #worker_class = sync
 #max_requests = 1000
-## ammount of time a worker can handle request before it gets killed and
+## amount of time a worker can handle request before it gets killed and
 ## restarted
 #timeout = 3600
 
@@ -163,6 +162,7 @@
 #cheaper-step = 1
 
 ## COMMON ##
+#host = 127.0.0.1
 host = 0.0.0.0
 port = 5000
 
@@ -198,9 +198,6 @@
 ## cut off limit for large diffs (size in bytes)
 cut_off_limit = 256000
 
-## use cache version of scm repo everywhere
-vcs_full_cache = true
-
 ## force https in Kallithea, fixes https redirects, assumes it's always https
 force_https = false
 
@@ -226,6 +223,11 @@
 show_sha_length = 12
 show_revision_number = false
 
+## Canonical URL to use when creating full URLs in UI and texts.
+## Useful when the site is available under different names or protocols.
+## Defaults to what is provided in the WSGI environment.
+#canonical_url = https://kallithea.example.com/repos
+
 ## gist URL alias, used to create nicer urls for gist. This should be an
 ## url that does rewrites to _admin/gists/<gistid>.
 ## example: http://gist.example.com/{gistid}. Empty means use the internal
@@ -245,7 +247,7 @@
 #    FilesController:archivefile
 
 ## default encoding used to convert from and to unicode
-## can be also a comma seperated list of encoding in case of mixed encodings
+## can be also a comma separated list of encoding in case of mixed encodings
 default_encoding = utf8
 
 ## issue tracker for Kallithea (leave blank to disable, absent for default)
@@ -280,12 +282,6 @@
 #issue_server_link_wiki = https://wiki.example.com/{id}
 #issue_prefix_wiki = WIKI-
 
-## instance-id prefix
-## a prefix key for this instance used for cache invalidation when running
-## multiple instances of kallithea, make sure it's globally unique for
-## all running kallithea instances. Leave empty if you don't use it
-instance_id =
-
 ## alternative return HTTP header for failed authentication. Default HTTP
 ## response is 401 HTTPUnauthorized. Currently Mercurial clients have trouble with
 ## handling that. Set this variable to 403 to return HTTPForbidden
@@ -301,19 +297,29 @@
 ## allows to setup custom hooks in settings page
 allow_custom_hooks_settings = True
 
+## extra extensions for indexing, space separated and without the leading '.'.
+# index.extensions =
+#    gemfile
+#    lock
+
+## extra filenames for indexing, space separated
+# index.filenames =
+#    .dockerignore
+#    .editorconfig
+#    INSTALL
+#    CHANGELOG
+
 ####################################
 ###        CELERY CONFIG        ####
 ####################################
 
 use_celery = false
-broker.host = localhost
-broker.vhost = rabbitmqhost
-broker.port = 5672
-broker.user = rabbitmq
-broker.password = qweqwe
+
+## Example: connect to the virtual host 'rabbitmqhost' on localhost as rabbitmq:
+broker.url = amqp://rabbitmq:qewqew@localhost:5672/rabbitmqhost
 
 celery.imports = kallithea.lib.celerylib.tasks
-
+celery.accept.content = pickle
 celery.result.backend = amqp
 celery.result.dburi = amqp://
 celery.result.serialier = json
@@ -322,11 +328,9 @@
 #celery.amqp.task.result.expires = 18000
 
 celeryd.concurrency = 2
-#celeryd.log.file = celeryd.log
-celeryd.log.level = DEBUG
 celeryd.max.tasks.per.child = 1
 
-## tasks will never be sent to the queue, but executed locally instead.
+## If true, tasks will never be sent to the queue, but executed locally instead.
 celery.always.eager = false
 
 ####################################
@@ -422,7 +426,7 @@
 ## (saves API quota for intensive logging)
 errormator.logging_on_error = false
 
-## list of additonal keywords that should be grabbed from environ object
+## list of additional keywords that should be grabbed from environ object
 ## can be string with comma separated list of words in lowercase
 ## (by default client will always send following info:
 ## 'REMOTE_USER', 'REMOTE_ADDR', 'SERVER_NAME', 'CONTENT_TYPE' + all keys that
@@ -480,19 +484,25 @@
 #########################################################
 
 # SQLITE [default]
-sqlalchemy.db1.url = sqlite:///%(here)s/kallithea.db?timeout=60
+sqlalchemy.url = sqlite:///%(here)s/kallithea.db?timeout=60
 
 # POSTGRESQL
-#sqlalchemy.db1.url = postgresql://user:pass@localhost/kallithea
+#sqlalchemy.url = postgresql://user:pass@localhost/kallithea
 
 # MySQL
-#sqlalchemy.db1.url = mysql://user:pass@localhost/kallithea
+#sqlalchemy.url = mysql://user:pass@localhost/kallithea?charset=utf8
 
 # see sqlalchemy docs for others
 
-sqlalchemy.db1.echo = false
-sqlalchemy.db1.pool_recycle = 3600
-sqlalchemy.db1.convert_unicode = true
+sqlalchemy.echo = false
+sqlalchemy.pool_recycle = 3600
+
+################################
+### ALEMBIC CONFIGURATION   ####
+################################
+
+[alembic]
+script_location = kallithea:alembic
 
 ################################
 ### LOGGING CONFIGURATION   ####
@@ -560,16 +570,16 @@
 class = StreamHandler
 args = (sys.stderr,)
 #level = INFO
+level = DEBUG
 #formatter = generic
-level = DEBUG
 formatter = color_formatter
 
 [handler_console_sql]
 class = StreamHandler
 args = (sys.stderr,)
 #level = WARN
+level = DEBUG
 #formatter = generic
-level = DEBUG
 formatter = color_formatter_sql
 
 ################
--- a/docs/api/api.rst	Thu Nov 17 13:09:43 2016 +0800
+++ b/docs/api/api.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -9,34 +9,8 @@
 ``<your_server>/_admin/api``.
 
 
-API access for web views
-++++++++++++++++++++++++
-
-API access can also be turned on for each web view in Kallithea that is
-decorated with the ``@LoginRequired`` decorator. Some views use
-``@LoginRequired(api_access=True)`` and are always available. By default only
-RSS/Atom feed views are enabled. Other views are
-only available if they have been whitelisted. Edit the
-``api_access_controllers_whitelist`` option in your .ini file and define views
-that should have API access enabled.
-
-For example, to enable API access to patch/diff, raw file and archive::
-
-    api_access_controllers_whitelist =
-        ChangesetController:changeset_patch,
-        ChangesetController:changeset_raw,
-        FilesController:raw,
-        FilesController:archivefile
-
-After this change, a Kallithea view can be accessed without login by adding a
-GET parameter ``?api_key=<api_key>`` to the URL.
-
-Exposing raw diffs is a good way to integrate with
-third-party services like code review, or build farms that can download archives.
-
-
 API access
-++++++++++
+----------
 
 Clients must send JSON encoded JSON-RPC requests::
 
@@ -76,7 +50,7 @@
 
 
 API client
-++++++++++
+----------
 
 Kallithea comes with a ``kallithea-api`` command line tool, providing a convenient
 way to call the JSON-RPC API.
@@ -110,11 +84,11 @@
 
 
 API methods
-+++++++++++
+-----------
 
 
 pull
-----
+^^^^
 
 Pull the given repo from remote location. Can be used to automatically keep
 remote repos up to date.
@@ -136,7 +110,7 @@
     error :  null
 
 rescan_repos
-------------
+^^^^^^^^^^^^
 
 Rescan repositories. If ``remove_obsolete`` is set,
 Kallithea will delete repos that are in the database but not in the filesystem.
@@ -159,7 +133,7 @@
     error :  null
 
 invalidate_cache
-----------------
+^^^^^^^^^^^^^^^^
 
 Invalidate the cache for a repository.
 This command can only be executed using the api_key of a user with admin rights,
@@ -181,7 +155,7 @@
     error :  null
 
 lock
-----
+^^^^
 
 Set the locking state on the given repository by the given user.
 If the param ``userid`` is skipped, it is set to the ID of the user who is calling this method.
@@ -212,7 +186,7 @@
     error :  null
 
 get_ip
-------
+^^^^^^
 
 Return IP address as seen from Kallithea server, together with all
 defined IP addresses for given user.
@@ -244,12 +218,12 @@
     error :  null
 
 get_user
---------
+^^^^^^^^
 
 Get a user by username or userid. The result is empty if user can't be found.
 If userid param is skipped, it is set to id of user who is calling this method.
 Any userid can be specified when the command is executed using the api_key of a user with admin rights.
-Regular users can only speicy their own userid.
+Regular users can only specify their own userid.
 
 INPUT::
 
@@ -288,7 +262,7 @@
     error:  null
 
 get_users
----------
+^^^^^^^^^
 
 List all existing users.
 This command can only be executed using the api_key of a user with admin rights.
@@ -325,7 +299,7 @@
 .. _create-user:
 
 create_user
------------
+^^^^^^^^^^^
 
 Create new user.
 This command can only be executed using the api_key of a user with admin rights.
@@ -371,7 +345,7 @@
     kallithea-api create_user username:bent email:bent@example.com firstname:Bent lastname:Bentsen extern_type:ldap extern_name:uid=bent,dc=example,dc=com
 
 update_user
------------
+^^^^^^^^^^^
 
 Update the given user if such user exists.
 This command can only be executed using the api_key of a user with admin rights.
@@ -415,7 +389,7 @@
     error:  null
 
 delete_user
------------
+^^^^^^^^^^^
 
 Delete the given user if such a user exists.
 This command can only be executed using the api_key of a user with admin rights.
@@ -439,7 +413,7 @@
     error:  null
 
 get_user_group
---------------
+^^^^^^^^^^^^^^
 
 Get an existing user group.
 This command can only be executed using the api_key of a user with admin rights.
@@ -481,7 +455,7 @@
     error : null
 
 get_user_groups
----------------
+^^^^^^^^^^^^^^^
 
 List all existing user groups.
 This command can only be executed using the api_key of a user with admin rights.
@@ -507,7 +481,7 @@
     error : null
 
 create_user_group
------------------
+^^^^^^^^^^^^^^^^^
 
 Create a new user group.
 This command can only be executed using the api_key of a user with admin rights.
@@ -537,7 +511,7 @@
     error:  null
 
 add_user_to_user_group
-----------------------
+^^^^^^^^^^^^^^^^^^^^^^
 
 Adds a user to a user group. If the user already is in that group, success will be
 ``false``.
@@ -564,7 +538,7 @@
     error:  null
 
 remove_user_from_user_group
----------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Remove a user from a user group. If the user isn't in the given group, success will
 be ``false``.
@@ -591,7 +565,7 @@
     error:  null
 
 get_repo
---------
+^^^^^^^^
 
 Get an existing repository by its name or repository_id. Members will contain
 either users_group or users associated to that repository.
@@ -680,7 +654,7 @@
     error:  null
 
 get_repos
----------
+^^^^^^^^^
 
 List all existing repositories.
 This command can only be executed using the api_key of a user with admin rights,
@@ -717,7 +691,7 @@
     error:  null
 
 get_repo_nodes
---------------
+^^^^^^^^^^^^^^
 
 Return a list of files and directories for a given path at the given revision.
 It is possible to specify ret_type to show only ``files`` or ``dirs``.
@@ -748,7 +722,7 @@
     error:  null
 
 create_repo
------------
+^^^^^^^^^^^
 
 Create a repository. If the repository name contains "/", all needed repository
 groups will be created. For example "foo/bar/baz" will create repository groups
@@ -800,7 +774,7 @@
     error:  null
 
 update_repo
------------
+^^^^^^^^^^^
 
 Update a repository.
 This command can only be executed using the api_key of a user with admin rights,
@@ -860,7 +834,7 @@
     error:  null
 
 fork_repo
----------
+^^^^^^^^^
 
 Create a fork of the given repo. If using Celery, this will
 return success message immediately and a fork will be created
@@ -896,7 +870,7 @@
     error:  null
 
 delete_repo
------------
+^^^^^^^^^^^
 
 Delete a repository.
 This command can only be executed using the api_key of a user with admin rights,
@@ -923,7 +897,7 @@
     error:  null
 
 grant_user_permission
----------------------
+^^^^^^^^^^^^^^^^^^^^^
 
 Grant permission for a user on the given repository, or update the existing one if found.
 This command can only be executed using the api_key of a user with admin rights.
@@ -949,7 +923,7 @@
     error:  null
 
 revoke_user_permission
-----------------------
+^^^^^^^^^^^^^^^^^^^^^^
 
 Revoke permission for a user on the given repository.
 This command can only be executed using the api_key of a user with admin rights.
@@ -974,7 +948,7 @@
     error:  null
 
 grant_user_group_permission
----------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Grant permission for a user group on the given repository, or update the
 existing one if found.
@@ -1001,7 +975,7 @@
     error:  null
 
 revoke_user_group_permission
-----------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Revoke permission for a user group on the given repository.
 This command can only be executed using the api_key of a user with admin rights.
@@ -1024,3 +998,29 @@
               "success": true
             }
     error:  null
+
+
+API access for web views
+------------------------
+
+API access can also be turned on for each web view in Kallithea that is
+decorated with the ``@LoginRequired`` decorator. Some views use
+``@LoginRequired(api_access=True)`` and are always available. By default only
+RSS/Atom feed views are enabled. Other views are
+only available if they have been whitelisted. Edit the
+``api_access_controllers_whitelist`` option in your .ini file and define views
+that should have API access enabled.
+
+For example, to enable API access to patch/diff, raw file and archive::
+
+    api_access_controllers_whitelist =
+        ChangesetController:changeset_patch,
+        ChangesetController:changeset_raw,
+        FilesController:raw,
+        FilesController:archivefile
+
+After this change, a Kallithea view can be accessed without login by adding a
+GET parameter ``?api_key=<api_key>`` to the URL.
+
+Exposing raw diffs is a good way to integrate with
+third-party services like code review, or build farms that can download archives.
--- a/docs/changelog.rst	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,10 +0,0 @@
-.. _changelog:
-
-=========
-Changelog
-=========
-
-Kallithea project doesn't keep its changelog here.  We refer you to our `Mercurial logs`__.
-
-
-.. __: https://kallithea-scm.org/repos/kallithea/changelog
--- a/docs/contributing.rst	Thu Nov 17 13:09:43 2016 +0800
+++ b/docs/contributing.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -48,9 +48,17 @@
 Running tests
 -------------
 
-After finishing your changes make sure all tests pass cleanly. You can run
-the testsuite running ``nosetests`` from the project root, or if you use tox
-run ``tox`` for Python 2.6--2.7 with multiple database test.
+After finishing your changes make sure all tests pass cleanly. Install the test
+dependencies, then run the testsuite by invoking ``py.test`` from the
+project root::
+
+    pip install -r dev_requirements.txt
+    py.test
+
+Note that testing on Python 2.6 also requires ``unittest2``.
+
+You can also use ``tox`` to run the tests with all supported Python versions
+(currently Python 2.6--2.7).
 
 When running tests, Kallithea uses `kallithea/tests/test.ini` and populates the
 SQLite database specified there.
@@ -59,31 +67,79 @@
 the tests, thus eliminating the initial delay. To achieve this, run the tests as::
 
     paster serve kallithea/tests/test.ini --pid-file=test.pid --daemon
-    KALLITHEA_WHOOSH_TEST_DISABLE=1 KALLITHEA_NO_TMP_PATH=1 nosetests
+    KALLITHEA_WHOOSH_TEST_DISABLE=1 KALLITHEA_NO_TMP_PATH=1 py.test
     kill -9 $(cat test.pid)
 
-You can run individual tests by specifying their path as argument to nosetests.
-nosetests also has many more options, see `nosetests -h`. Some useful options
+In these commands, the following variables are used::
+
+    KALLITHEA_WHOOSH_TEST_DISABLE=1 - skip whoosh index building and tests
+    KALLITHEA_NO_TMP_PATH=1 - disable new temp path for tests, used mostly for testing_vcs_operations
+
+You can run individual tests by specifying their path as argument to py.test.
+py.test also has many more options, see `py.test -h`. Some useful options
 are::
 
-    -x, --stop            Stop running tests after the first error or failure
-    -s, --nocapture       Don't capture stdout (any stdout output will be
-                          printed immediately) [NOSE_NOCAPTURE]
-    --failed              Run the tests that failed in the last test run.
+    -k EXPRESSION         only run tests which match the given substring
+                          expression. An expression is a python evaluable
+                          expression where all names are substring-matched
+                          against test names and their parent classes. Example:
+    -x, --exitfirst       exit instantly on first error or failed test.
+    --lf                  rerun only the tests that failed at the last run (or
+                          all if none failed)
+    --ff                  run all tests but run the last failures first. This
+                          may re-order tests and thus lead to repeated fixture
+                          setup/teardown
+    --pdb                 start the interactive Python debugger on errors.
+    -s, --capture=no      don't capture stdout (any stdout output will be
+                          printed immediately)
 
 
-Coding/contribution guidelines
-------------------------------
+Contribution guidelines
+-----------------------
 
 Kallithea is GPLv3 and we assume all contributions are made by the
 committer/contributor and under GPLv3 unless explicitly stated. We do care a
 lot about preservation of copyright and license information for existing code
 that is brought into the project.
 
+Contributions will be accepted in most formats -- such as pull requests on
+Bitbucket, something hosted on your own Kallithea instance, or patches sent by
+email to the `kallithea-general`_ mailing list.
+
+When contributing via Bitbucket, please make your fork of
+https://bitbucket.org/conservancy/kallithea/ `non-publishing`_ -- it is one of
+the settings on "Repository details" page. This ensures your commits are in
+"draft" phase and makes it easier for you to address feedback and for project
+maintainers to integrate your changes.
+
+.. _non-publishing: https://www.mercurial-scm.org/wiki/Phases#Publishing_Repository
+
+Make sure to test your changes both manually and with the automatic tests
+before posting.
+
+We care about quality and review and keeping a clean repository history. We
+might give feedback that requests polishing contributions until they are
+"perfect". We might also rebase and collapse and make minor adjustments to your
+changes when we apply them.
+
+We try to make sure we have consensus on the direction the project is taking.
+Everything non-sensitive should be discussed in public -- preferably on the
+mailing list.  We aim at having all non-trivial changes reviewed by at least
+one other core developer before pushing. Obvious non-controversial changes will
+be handled more casually.
+
+For now we just have one official branch ("default") and will keep it so stable
+that it can be (and is) used in production. Experimental changes should live
+elsewhere (for example in a pull request) until they are ready.
+
+
+Coding guidelines
+-----------------
+
 We don't have a formal coding/formatting standard. We are currently using a mix
 of Mercurial's (https://www.mercurial-scm.org/wiki/CodingStyle), pep8, and
-consistency with existing code. Run whitespacecleanup.sh to avoid stupid
-whitespace noise in your patches.
+consistency with existing code. Run ``scripts/run-all-cleanup`` before
+committing to ensure some basic code formatting consistency.
 
 We support both Python 2.6.x and 2.7.x and nothing else. For now we don't care
 about Python 3 compatibility.
@@ -112,30 +168,41 @@
 
 .. _English title case: https://en.wikipedia.org/wiki/Capitalization#Title_case
 
-Contributions will be accepted in most formats -- such as pull requests on
-bitbucket, something hosted on your own Kallithea instance, or patches sent by
-email to the `kallithea-general`_ mailing list.
+Template helpers (that is, everything in ``kallithea.lib.helpers``)
+should only be referenced from templates. If you need to call a
+helper from the Python code, consider moving the function somewhere
+else (e.g. to the model).
+
+Notes on the SQLAlchemy session
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-Make sure to test your changes both manually and with the automatic tests
-before posting.
+Each HTTP request runs inside an independent SQLAlchemy session (as well
+as in an independent database transaction). Database model objects
+(almost) always belong to a particular SQLAlchemy session, which means
+that SQLAlchemy will ensure that they're kept in sync with the database
+(but also means that they cannot be shared across requests).
 
-We care about quality and review and keeping a clean repository history. We
-might give feedback that requests polishing contributions until they are
-"perfect". We might also rebase and collapse and make minor adjustments to your
-changes when we apply them.
+Objects can be added to the session using ``Session().add``, but this is
+rarely needed:
 
-We try to make sure we have consensus on the direction the project is taking.
-Everything non-sensitive should be discussed in public -- preferably on the
-mailing list.  We aim at having all non-trivial changes reviewed by at least
-one other core developer before pushing. Obvious non-controversial changes will
-be handled more casually.
+* When creating a database object by calling the constructor directly,
+  it must explicitly be added to the session.
+
+* When creating an object using a factory function (like
+  ``create_repo``), the returned object has already (by convention)
+  been added to the session, and should not be added again.
 
-For now we just have one official branch ("default") and will keep it so stable
-that it can be (and is) used in production. Experimental changes should live
-elsewhere (for example in a pull request) until they are ready.
+* When getting an object from the session (via ``Session().query`` or
+  any of the utility functions that look up objects in the database),
+  it's already part of the session, and should not be added again.
+  SQLAlchemy monitors attribute modifications automatically for all
+  objects it knows about and syncs them to the database.
 
-.. _translations:
-.. include:: ./../kallithea/i18n/how_to
+SQLAlchemy also flushes changes to the database automatically; manually
+calling ``Session().flush`` is usually only necessary when the Python
+code needs the database to assign an "auto-increment" primary key ID to
+a freshly created model object (before flushing, the ID attribute will
+be ``None``).
 
 
 "Roadmap"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/docs/dev/dbmigrations.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,74 @@
+=======================
+Database schema changes
+=======================
+
+Kallithea uses Alembic for :ref:`database migrations <upgrade_db>`
+(upgrades and downgrades).
+
+If you are developing a Kallithea feature that requires database schema
+changes, you should make a matching Alembic database migration script:
+
+1. :ref:`Create a Kallithea configuration and database <setup>` for testing
+   the migration script, or use existing ``development.ini`` setup.
+
+   Ensure that this database is up to date with the latest database
+   schema *before* the changes you're currently developing. (Do not
+   create the database while your new schema changes are applied.)
+
+2. Create a separate throwaway configuration for iterating on the actual
+   database changes::
+
+    paster make-config Kallithea temp.ini
+
+   Edit the file to change database settings. SQLite is typically fine,
+   but make sure to change the path to e.g. ``temp.db``, to avoid
+   clobbering any existing database file.
+
+3. Make your code changes (including database schema changes in ``db.py``).
+
+4. After every database schema change, recreate the throwaway database
+   to test the changes::
+
+    rm temp.db
+    paster setup-db temp.ini --repos=/var/repos --user=doe --email doe@example.com --password=123456 --no-public-access --force-yes
+    paster repo-scan temp.ini
+
+5. Once satisfied with the schema changes, auto-generate a draft Alembic
+   script using the development database that has *not* been upgraded.
+   (The generated script will upgrade the database to match the code.)
+
+   ::
+
+    alembic -c development.ini revision -m "area: add cool feature" --autogenerate
+
+6. Edit the script to clean it up and fix any problems.
+
+   Note that for changes that simply add columns, it may be appropriate
+   to not remove them in the downgrade script (and instead do nothing),
+   to avoid the loss of data. Unknown columns will simply be ignored by
+   Kallithea versions predating your changes.
+
+7. Run ``alembic -c development.ini upgrade head`` to apply changes to
+   the (non-throwaway) database, and test the upgrade script. Also test
+   downgrades.
+
+   The included ``development.ini`` has full SQL logging enabled. If
+   you're using another configuration file, you may want to enable it
+   by setting ``level = DEBUG`` in section ``[handler_console_sql]``.
+
+The Alembic migration script should be committed in the same revision as
+the database schema (``db.py``) changes.
+
+See the `Alembic documentation`__ for more information, in particular
+the tutorial and the section about auto-generating migration scripts.
+
+.. __: http://alembic.zzzcomputing.com/en/latest/
+
+
+Troubleshooting
+---------------
+
+* If ``alembic --autogenerate`` responds "Target database is not up to
+  date", you need to either first use Alembic to upgrade the database
+  to the most recent version (before your changes), or recreate the
+  database from scratch (without your schema changes applied).
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/docs/dev/translation.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,2 @@
+.. _translations:
+.. include:: ./../../kallithea/i18n/how_to
--- a/docs/index.rst	Thu Nov 17 13:09:43 2016 +0800
+++ b/docs/index.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -23,6 +23,7 @@
    installation_iis
    setup
    installation_puppet
+   upgrade
 
 **Usage**
 
@@ -44,6 +45,7 @@
    usage/backup
    usage/debugging
    usage/troubleshooting
+   usage/customization
 
 **Development**
 
@@ -51,7 +53,8 @@
    :maxdepth: 1
 
    contributing
-   changelog
+   dev/translation
+   dev/dbmigrations
 
 **API**
 
@@ -59,11 +62,10 @@
    :maxdepth: 1
 
    api/api
-   api/models
 
 
 Other topics
-------------
+************
 
 * :ref:`genindex`
 * :ref:`search`
--- a/docs/installation.rst	Thu Nov 17 13:09:43 2016 +0800
+++ b/docs/installation.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -26,6 +26,22 @@
   have to remove its dependencies manually and make sure that they are not
   needed by other packages.
 
+Regardless of the installation method you may need to make sure you have
+appropriate development packages installed, as installation of some of the
+Kallithea dependencies requires a working C compiler and libffi library
+headers. Depending on your configuration, you may also need to install
+Git and development packages for the database of your choice.
+
+For Debian and Ubuntu, the following command will ensure that a reasonable
+set of dependencies is installed::
+
+    sudo apt-get install build-essential git python-pip python-virtualenv libffi-dev python-dev
+
+For Fedora and RHEL-derivatives, the following command will ensure that a
+reasonable set of dependencies is installed::
+
+    sudo yum install gcc git python-pip python-virtualenv libffi-devel python-devel
+
 .. _installation-source:
 
 
@@ -38,16 +54,13 @@
         hg clone https://kallithea-scm.org/repos/kallithea -u stable
         cd kallithea
         virtualenv ../kallithea-venv
-        source ../kallithea-venv/bin/activate
+        . ../kallithea-venv/bin/activate
         pip install --upgrade pip setuptools
         pip install -e .
         python2 setup.py compile_catalog   # for translation of the UI
 
 You can now proceed to :ref:`setup`.
 
-To upgrade, simply update the repository with ``hg pull -u`` and restart the
-server.
-
 .. _installation-virtualenv:
 
 
@@ -68,7 +81,7 @@
 - Activate the virtualenv_ in your current shell session and make sure the
   basic requirements are up-to-date by running::
 
-    source /srv/kallithea/venv/bin/activate
+    . /srv/kallithea/venv/bin/activate
     pip install --upgrade pip setuptools
 
 .. note:: You can't use UNIX ``sudo`` to source the ``virtualenv`` script; it
@@ -123,90 +136,5 @@
 You can now proceed to :ref:`setup`.
 
 
-Upgrading Kallithea from Python Package Index (PyPI)
-----------------------------------------------------
-
-.. note::
-   It is strongly recommended that you **always** perform a database and
-   configuration backup before doing an upgrade.
-
-   These directions will use '{version}' to note that this is the version of
-   Kallithea that these files were used with.  If backing up your Kallithea
-   instance from version 0.1 to 0.2, the ``my.ini`` file could be
-   backed up to ``my.ini.0-1``.
-
-If using a SQLite database, stop the Kallithea process/daemon/service, and
-then make a copy of the database file::
-
- service kallithea stop
- cp kallithea.db kallithea.db.{version}
-
-Back up your configuration file::
-
- cp my.ini my.ini.{version}
-
-Ensure that you are using the Python virtual environment that you originally
-installed Kallithea in by running::
-
- pip freeze
-
-This will list all packages installed in the current environment.  If
-Kallithea isn't listed, activate the correct virtual environment::
-
- source /srv/kallithea/venv/bin/activate
-
-Once you have verified the environment you can upgrade Kallithea with::
-
- pip install --upgrade kallithea
-
-Then run the following command from the installation directory::
-
- paster make-config Kallithea my.ini
-
-This will display any changes made by the new version of Kallithea to your
-current configuration. It will try to perform an automerge. It is recommended
-that you recheck the content after the automerge.
-
-.. note::
-   Please always make sure your .ini files are up to date. Errors can
-   often be caused by missing parameters added in new versions.
-
-It is also recommended that you rebuild the whoosh index after upgrading since
-the new whoosh version could introduce some incompatible index changes. Please
-read the changelog to see if there were any changes to whoosh.
-
-The final step is to upgrade the database. To do this simply run::
-
- paster upgrade-db my.ini
-
-This will upgrade the schema and update some of the defaults in the database,
-and will always recheck the settings of the application, if there are no new
-options that need to be set.
-
-.. note::
-   The DB schema upgrade library has some limitations and can sometimes fail if you try to
-   upgrade from older major releases. In such a case simply run upgrades sequentially, e.g.,
-   upgrading from 0.1.X to 0.3.X should be done like this: 0.1.X. > 0.2.X > 0.3.X
-   You can always specify what version of Kallithea you want to install for example in pip
-   `pip install Kallithea==0.2`
-
-You may find it helpful to clear out your log file so that new errors are
-readily apparent::
-
- echo > kallithea.log
-
-Once that is complete, you may now start your upgraded Kallithea Instance::
-
- service kallithea start
-
-Or::
-
- paster serve /srv/kallithea/my.ini
-
-.. note::
-   If you're using Celery, make sure you restart all instances of it after
-   upgrade.
-
-
 .. _virtualenv: http://pypi.python.org/pypi/virtualenv
 .. _pylons: http://www.pylonsproject.org/
--- a/docs/installation_iis.rst	Thu Nov 17 13:09:43 2016 +0800
+++ b/docs/installation_iis.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -39,7 +39,7 @@
 own virtual folder will be noted where appropriate.
 
 Application pool
-................
+^^^^^^^^^^^^^^^^
 
 Make sure that there is a unique application pool for the Kallithea application
 with an identity that has read access to the Kallithea distribution.
@@ -55,7 +55,7 @@
     as long as the Kallithea requirements are met by the existing pool.
 
 ISAPI handler
-.............
+^^^^^^^^^^^^^
 
 The ISAPI handler can be generated using::
 
@@ -79,7 +79,7 @@
 site will be processed through this logic henceforth.
 
 Authentication with Kallithea using IIS authentication modules
-..............................................................
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 The recommended way to handle authentication with Kallithea using IIS is to let
 IIS handle all the authentication and just pass it to Kallithea.
@@ -126,4 +126,4 @@
 traces, making it a lot easier to identify issues.
 
 
-.. _hgssoauthenticatio: https://bitbucket.org/domruf/hgssoauthentication
+.. _hgssoauthentication: https://bitbucket.org/domruf/hgssoauthentication
--- a/docs/installation_puppet.rst	Thu Nov 17 13:09:43 2016 +0800
+++ b/docs/installation_puppet.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -90,7 +90,7 @@
 parameter in the :ref:`example above <simple_manifest>`, but there are more.
 For example, you can specify the installation directory, the name of the user
 under which Kallithea gets installed, the initial admin password, etc.
-Notably, you can provide arbitrary modifications to Kallitheas configuration
+Notably, you can provide arbitrary modifications to Kallithea's configuration
 file by means of the ``config_hash`` parameter.
 
 Parameters, which have not been set explicitly, will be set to default values,
--- a/docs/installation_win.rst	Thu Nov 17 13:09:43 2016 +0800
+++ b/docs/installation_win.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -1,12 +1,12 @@
 .. _installation_win:
 
-================================================================
-Installation and upgrade on Windows (7/Server 2008 R2 and newer)
-================================================================
+====================================================
+Installation on Windows (7/Server 2008 R2 and newer)
+====================================================
 
 
 First time install
-::::::::::::::::::
+------------------
 
 Target OS: Windows 7 and newer or Windows Server 2008 R2 and newer
 
@@ -15,7 +15,7 @@
 To install on an older version of Windows, see `<installation_win_old.html>`_
 
 Step 1 -- Install Python
-------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^
 
 Install Python 2.x.y (x = 6 or 7). Latest version is recommended. If you need another version, they can run side by side.
 
@@ -31,7 +31,7 @@
 be needed in the next step. In this case, it is "2.7".
 
 Step 2 -- Python BIN
---------------------
+^^^^^^^^^^^^^^^^^^^^
 
 Add Python BIN folder to the path. This can be done manually (editing
 "PATH" environment variable) or by using Windows Support Tools that
@@ -45,7 +45,7 @@
 path. Typically this is ``C:\\Python27``.
 
 Step 3 -- Install pywin32 extensions
-------------------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Download pywin32 from:
 http://sourceforge.net/projects/pywin32/files/
@@ -61,7 +61,7 @@
   (Win32)
 
 Step 4 -- Install pip
----------------------
+^^^^^^^^^^^^^^^^^^^^^
 
 pip is a package management system for Python. You will need it to install Kallithea and its dependencies.
 
@@ -85,7 +85,7 @@
   SETX PATH "%PATH%;[your-python-path]\Scripts" /M
 
 Step 5 -- Kallithea folder structure
-------------------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Create a Kallithea folder structure.
 
@@ -102,7 +102,7 @@
   C:\Kallithea\Repos
 
 Step 6 -- Install virtualenv
-----------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 .. note::
    A python virtual environment will allow for isolation between the Python packages of your system and those used for Kallithea.
@@ -119,7 +119,7 @@
   virtualenv C:\Kallithea\Env
 
 Step 7 -- Install Kallithea
----------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 In order to install Kallithea, you need to be able to run "pip install kallithea". It will use pip to install the Kallithea Python package and its dependencies.
 Some Python packages use managed code and need to be compiled.
@@ -145,17 +145,19 @@
           complete. Some warnings will appear. Don't worry, they are
           normal.
 
-Step 8 -- Install git (optional)
---------------------------------
+Step 8 -- Install Git (optional)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Mercurial being a python package, was installed automatically when doing ``pip install kallithea``.
 
-Mercurial being a python package, it was installed automatically when doing "pip install kallithea".
-
-You need to install git manually if you want Kallithea to be able to host git repositories.
-
+You need to install Git manually if you want Kallithea to be able to host Git repositories.
 See http://git-scm.com/book/en/v2/Getting-Started-Installing-Git#Installing-on-Windows for instructions.
+The location of the Git binaries (like ``c:\path\to\git\bin``) must be
+added to the ``PATH`` environment variable so ``git.exe`` and other tools like
+``gzip.exe`` are available.
 
 Step 9 -- Configuring Kallithea
--------------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Steps taken from `<setup.html>`_
 
@@ -178,8 +180,8 @@
   paster setup-db production.ini
 
 .. warning:: This time a *new* database will be installed. You must
-             follow a different step to later *upgrade* to a newer
-             Kallithea version)
+             follow a different process to later :ref:`upgrade <upgrade>`
+             to a newer Kallithea version.
 
 The script will ask you for confirmation about creating a new database, answer yes (y)
 
@@ -191,10 +193,10 @@
 
 If you make a mistake and the script doesn't end, don't worry: start it again.
 
-If you decided not to install git, you will get errors about it that you can ignore.
+If you decided not to install Git, you will get errors about it that you can ignore.
 
 Step 10 -- Running Kallithea
-----------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 In the previous command prompt, being in the C:\\Kallithea\\Bin folder, type::
 
@@ -219,27 +221,3 @@
 - Using Apache. You can investigate here:
 
   - https://groups.google.com/group/rhodecode/msg/c433074e813ffdc4
-
-
-Upgrading
-:::::::::
-
-Stop running Kallithea
-Open a CommandPrompt like in Step 7 (cd to C:\Kallithea\Env\Scripts and activate) and type::
-
-  pip install kallithea --upgrade
-  cd \Kallithea\Bin
-
-Backup your production.ini file now.
-
-Then run::
-
-  paster make-config Kallithea production.ini
-
-Look for changes and update your production.ini accordingly.
-
-Next, update the database::
-
-  paster upgrade-db production.ini
-
-More details can be found in `<upgrade.html>`_.
--- a/docs/installation_win_old.rst	Thu Nov 17 13:09:43 2016 +0800
+++ b/docs/installation_win_old.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -1,12 +1,12 @@
 .. _installation_win_old:
 
-======================================================================
-Installation and upgrade on Windows (XP/Vista/Server 2003/Server 2008)
-======================================================================
+==========================================================
+Installation on Windows (XP/Vista/Server 2003/Server 2008)
+==========================================================
 
 
 First-time install
-::::::::::::::::::
+------------------
 
 Target OS: Windows XP SP3 32-bit English (Clean installation)
 + All Windows Updates until 24-may-2012
@@ -24,7 +24,7 @@
    - http://bugs.python.org/issue7511
 
 Step 1 -- Install Visual Studio 2008 Express
---------------------------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Optional: You can also install MinGW, but VS2008 installation is easier.
 
@@ -58,7 +58,7 @@
    Copy C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\vcvars64.bat to C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\amd64\vcvarsamd64.bat
 
 Step 2 -- Install Python
-------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^
 
 Install Python 2.x.y (x = 6 or 7) x86 version (32-bit). DO NOT USE A 3.x version.
 Download Python 2.x.y from:
@@ -74,7 +74,7 @@
    64-bit: Just download and install the 64-bit version of python.
 
 Step 3 -- Install Win32py extensions
-------------------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Download pywin32 from:
 http://sourceforge.net/projects/pywin32/files/
@@ -93,7 +93,7 @@
      http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/pywin32-218.win-amd64-py2.7.exe/download
 
 Step 4 -- Python BIN
---------------------
+^^^^^^^^^^^^^^^^^^^^
 
 Add Python BIN folder to the path
 
@@ -120,7 +120,7 @@
   Typically: C:\\Python27
 
 Step 5 -- Kallithea folder structure
-------------------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Create a Kallithea folder structure
 
@@ -137,7 +137,7 @@
   C:\Kallithea\Repos
 
 Step 6 -- Install virtualenv
-----------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Install Virtual Env for Python
 
@@ -157,7 +157,7 @@
 to include it)
 
 Step 7 -- Install Kallithea
----------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Finally, install Kallithea
 
@@ -195,7 +195,7 @@
 Some warnings will appear, don't worry as they are normal.
 
 Step 8 -- Configuring Kallithea
--------------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 steps taken from http://packages.python.org/Kallithea/setup.html
 
@@ -217,8 +217,9 @@
 
  paster setup-db production.ini
 
-(this time a NEW database will be installed, you must follow a different
-step to later UPGRADE to a newer Kallithea version)
+.. warning:: This time a *new* database will be installed. You must
+             follow a different process to later :ref:`upgrade <upgrade>`
+             to a newer Kallithea version.
 
 The script will ask you for confirmation about creating a NEW database,
 answer yes (y)
@@ -233,7 +234,7 @@
 it again.
 
 Step 9 -- Running Kallithea
----------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 In the previous command prompt, being in the C:\\Kallithea\\Bin folder,
 just type::
@@ -260,23 +261,3 @@
 - Using Apache. You can investigate here:
 
   - https://groups.google.com/group/rhodecode/msg/c433074e813ffdc4
-
-
-Upgrading
-:::::::::
-
-Stop running Kallithea
-Open a CommandPrompt like in Step7 (VS2008 path + activate) and type::
-
- easy_install -U kallithea
- cd \Kallithea\Bin
-
-{ backup your production.ini file now} ::
-
- paster make-config Kallithea production.ini
-
-(check changes and update your production.ini accordingly) ::
-
- paster upgrade-db production.ini (update database)
-
-Full steps in http://packages.python.org/Kallithea/upgrade.html
--- a/docs/setup.rst	Thu Nov 17 13:09:43 2016 +0800
+++ b/docs/setup.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -67,24 +67,6 @@
   repositories.
 
 
-Extensions
-----------
-
-Optionally one can create an ``rcextensions`` package that extends Kallithea
-functionality.
-To generate a skeleton extensions package, run::
-
-    paster make-rcext my.ini
-
-This will create an ``rcextensions`` package next to the specified ``ini`` file.
-With ``rcextensions`` it's possible to add additional mapping for whoosh,
-stats and add additional code into the push/pull/create/delete repo hooks,
-for example for sending signals to build-bots such as Jenkins.
-
-See the ``__init__.py`` file inside the generated ``rcextensions`` package
-for more details.
-
-
 Using Kallithea with SSH
 ------------------------
 
@@ -135,7 +117,7 @@
 
     paster make-index my.ini -f
 
-The ``--repo-location`` option allows the location of the repositories to be overriden;
+The ``--repo-location`` option allows the location of the repositories to be overridden;
 usually, the location is retrieved from the Kallithea database.
 
 The ``--index-only`` option can be used to limit the indexed repositories to a comma-separated list::
@@ -157,6 +139,7 @@
 
 .. _ldap-setup:
 
+
 Setting up LDAP support
 -----------------------
 
@@ -178,7 +161,6 @@
  Connection settings
  Enable LDAP          = checked
  Host                 = host.example.com
- Port                 = 389
  Account              = <account>
  Password             = <password>
  Connection Security  = LDAPS connection
@@ -215,8 +197,9 @@
 
 .. _Port:
 
-Port : required
-    389 for un-encrypted LDAP, 636 for SSL-encrypted LDAP.
+Port : optional
+    Defaults to 389 for PLAIN un-encrypted LDAP and START_TLS.
+    Defaults to 636 for LDAPS.
 
 .. _ldap_account:
 
@@ -236,26 +219,27 @@
 Connection Security : required
     Defines the connection to LDAP server
 
-    No encryption
-        Plain non encrypted connection
+    PLAIN
+        Plain unencrypted LDAP connection.
+        This will by default use `Port`_ 389.
 
-    LDAPS connection
-        Enable LDAPS connections. It will likely require `Port`_ to be set to
-        a different value (standard LDAPS port is 636). When LDAPS is enabled
-        then `Certificate Checks`_ is required.
+    LDAPS
+        Use secure LDAPS connections according to `Certificate
+        Checks`_ configuration.
+        This will by default use `Port`_ 636.
 
-    START_TLS on LDAP connection
-        START TLS connection
+    START_TLS
+        Use START TLS according to `Certificate Checks`_ configuration on an
+        apparently "plain" LDAP connection.
+        This will by default use `Port`_ 389.
 
 .. _Certificate Checks:
 
 Certificate Checks : optional
     How SSL certificates verification is handled -- this is only useful when
     `Enable LDAPS`_ is enabled.  Only DEMAND or HARD offer full SSL security
-    while the other options are susceptible to man-in-the-middle attacks.  SSL
-    certificates can be installed to /etc/openldap/cacerts so that the
-    DEMAND or HARD options can be used with self-signed certificates or
-    certificates that do not have traceable certificates of authority.
+    with mandatory certificate validation, while the other options are
+    susceptible to man-in-the-middle attacks.
 
     NEVER
         A serve certificate will never be requested or checked.
@@ -277,6 +261,16 @@
     HARD
         The same as DEMAND.
 
+.. _Custom CA Certificates:
+
+Custom CA Certificates : optional
+    Directory used by OpenSSL to find CAs for validating the LDAP server certificate.
+    Python 2.7.10 and later default to using the system certificate store, and
+    this should thus not be necessary when using certificates signed by a CA
+    trusted by the system.
+    It can be set to something like `/etc/openldap/cacerts` on older systems or
+    if using self-signed certificates.
+
 .. _Base DN:
 
 Base DN : required
@@ -347,7 +341,7 @@
 will be saved there.
 
 Active Directory
-''''''''''''''''
+^^^^^^^^^^^^^^^^
 
 Kallithea can use Microsoft Active Directory for user authentication.  This
 is done through an LDAP or LDAPS connection to Active Directory.  The
@@ -384,7 +378,7 @@
 permissions before the user logs in for the first time, using the :ref:`create-user` API.
 
 Container-based authentication
-''''''''''''''''''''''''''''''
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 In a container-based authentication setup, Kallithea reads the user name from
 the ``REMOTE_USER`` server variable provided by the WSGI container.
@@ -394,7 +388,7 @@
 Kallithea.
 
 Proxy pass-through authentication
-'''''''''''''''''''''''''''''''''
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 In a proxy pass-through authentication setup, Kallithea reads the user name
 from the ``X-Forwarded-User`` request header, which should be configured to be
@@ -428,6 +422,73 @@
       RequestHeader set X-Forwarded-User %{RU}e
     </Location>
 
+Setting metadata in container/reverse-proxy
+"""""""""""""""""""""""""""""""""""""""""""
+When a new user account is created on the first login, Kallithea has no information about
+the user's email and full name. So you can set some additional request headers like in the
+example below. In this example the user is authenticated via Kerberos and an Apache
+mod_python fixup handler is used to get the user information from a LDAP server. But you
+could set the request headers however you want.
+
+.. code-block:: apache
+
+    <Location /someprefix>
+      ProxyPass http://127.0.0.1:5000/someprefix
+      ProxyPassReverse http://127.0.0.1:5000/someprefix
+      SetEnvIf X-Url-Scheme https HTTPS=1
+
+      AuthName "Kerberos Login"
+      AuthType Kerberos
+      Krb5Keytab /etc/apache2/http.keytab
+      KrbMethodK5Passwd off
+      KrbVerifyKDC on
+      Require valid-user
+
+      PythonFixupHandler ldapmetadata
+
+      RequestHeader set X_REMOTE_USER %{X_REMOTE_USER}e
+      RequestHeader set X_REMOTE_EMAIL %{X_REMOTE_EMAIL}e
+      RequestHeader set X_REMOTE_FIRSTNAME %{X_REMOTE_FIRSTNAME}e
+      RequestHeader set X_REMOTE_LASTNAME %{X_REMOTE_LASTNAME}e
+    </Location>
+
+.. code-block:: python
+
+    from mod_python import apache
+    import ldap
+
+    LDAP_SERVER = "ldap://server.mydomain.com:389"
+    LDAP_USER = ""
+    LDAP_PASS = ""
+    LDAP_ROOT = "dc=mydomain,dc=com"
+    LDAP_FILTER = "sAMAccountName=%s"
+    LDAP_ATTR_LIST = ['sAMAccountName','givenname','sn','mail']
+
+    def fixuphandler(req):
+        if req.user is None:
+            # no user to search for
+            return apache.OK
+        else:
+            try:
+                if('\\' in req.user):
+                    username = req.user.split('\\')[1]
+                elif('@' in req.user):
+                    username = req.user.split('@')[0]
+                else:
+                    username = req.user
+                l = ldap.initialize(LDAP_SERVER)
+                l.simple_bind_s(LDAP_USER, LDAP_PASS)
+                r = l.search_s(LDAP_ROOT, ldap.SCOPE_SUBTREE, LDAP_FILTER % username, attrlist=LDAP_ATTR_LIST)
+
+                req.subprocess_env['X_REMOTE_USER'] = username
+                req.subprocess_env['X_REMOTE_EMAIL'] = r[0][1]['mail'][0].lower()
+                req.subprocess_env['X_REMOTE_FIRSTNAME'] = "%s" % r[0][1]['givenname'][0]
+                req.subprocess_env['X_REMOTE_LASTNAME'] = "%s" % r[0][1]['sn'][0]
+            except Exception, e:
+                apache.log_error("error getting data from ldap %s" % str(e), apache.APLOG_ERR)
+
+            return apache.OK
+
 .. note::
    If you enable proxy pass-through authentication, make sure your server is
    only accessible through the proxy. Otherwise, any client would be able to
@@ -606,7 +667,7 @@
 
        ## uncomment root directive if you want to serve static files by nginx
        ## requires static_files = false in .ini file
-       #root /path/to/installation/kallithea/public;
+       #root /srv/kallithea/kallithea/kallithea/public;
        include         /etc/nginx/proxy.conf;
        location / {
             try_files $uri @kallithea;
@@ -735,8 +796,7 @@
 
 .. code-block:: apache
 
-    WSGIDaemonProcess kallithea \
-        threads=4 \
+    WSGIDaemonProcess kallithea processes=5 threads=1 maximum-requests=100 \
         python-home=/srv/kallithea/venv
     WSGIProcessGroup kallithea
     WSGIScriptAlias / /srv/kallithea/dispatch.wsgi
@@ -746,7 +806,7 @@
 
 .. code-block:: apache
 
-    WSGIDaemonProcess kallithea threads=4
+    WSGIDaemonProcess kallithea processes=5 threads=1 maximum-requests=100
     WSGIProcessGroup kallithea
     WSGIScriptAlias / /srv/kallithea/dispatch.wsgi
     WSGIPassAuthorization On
@@ -756,11 +816,6 @@
 directory owned by a different user, use the user and group options to
 WSGIDaemonProcess to set the name of the user and group.
 
-.. note::
-   If running Kallithea in multiprocess mode,
-   make sure you set ``instance_id = *`` in the configuration so each process
-   gets it's own cache invalidation key.
-
 Example WSGI dispatch script:
 
 .. code-block:: python
@@ -769,7 +824,7 @@
     os.environ["HGENCODING"] = "UTF-8"
     os.environ['PYTHON_EGG_CACHE'] = '/srv/kallithea/.egg-cache'
 
-    # sometimes it's needed to set the curent dir
+    # sometimes it's needed to set the current dir
     os.chdir('/srv/kallithea/')
 
     import site
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/docs/upgrade.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,187 @@
+.. _upgrade:
+
+===================
+Upgrading Kallithea
+===================
+
+This describes the process for upgrading Kallithea, independently of the
+Kallithea installation method.
+
+.. note::
+    If you are upgrading from a RhodeCode installation, you must first
+    install Kallithea 0.3.2 and follow the instructions in the 0.3.2
+    README to perform a one-time conversion of the database from
+    RhodeCode to Kallithea, before upgrading to the latest version
+    of Kallithea.
+
+
+1. Stop the Kallithea web application
+-------------------------------------
+
+This step depends entirely on the web server software used to serve
+Kallithea, but in any case, Kallithea should not be running during
+the upgrade.
+
+.. note::
+    If you're using Celery, make sure you stop all instances during the
+    upgrade.
+
+
+2. Create a backup of both database and configuration
+-----------------------------------------------------
+
+You are of course strongly recommended to make backups regularly, but it
+is *especially* important to make a full database and configuration
+backup before performing a Kallithea upgrade.
+
+Back up your configuration
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Make a copy of your Kallithea configuration (``.ini``) file.
+
+If you are using :ref:`rcextensions <customization>`, you should also
+make a copy of the entire ``rcextensions`` directory.
+
+Back up your database
+^^^^^^^^^^^^^^^^^^^^^
+
+If using SQLite, simply make a copy of the Kallithea database (``.db``)
+file.
+
+If using PostgreSQL, please consult the documentation for the ``pg_dump``
+utility.
+
+If using MySQL, please consult the documentation for the ``mysqldump``
+utility.
+
+Look for ``sqlalchemy.url`` in your configuration file to determine
+database type, settings, location, etc.
+
+
+3. Activate the Kallithea virtual environment (if any)
+------------------------------------------------------
+
+Verify that you are using the Python environment that you originally
+installed Kallithea in by running::
+
+    pip freeze
+
+This will list all packages installed in the current environment. If
+Kallithea isn't listed, activate the correct virtual environment.
+See the appropriate installation page for details.
+
+
+4. Install new version of Kallithea
+-----------------------------------
+
+Please refer to the instructions for the installation method you
+originally used to install Kallithea.
+
+If you originally installed using pip, it is as simple as::
+
+    pip install --upgrade kallithea
+
+If you originally installed from version control, it is as simple as::
+
+    cd my-kallithea-clone
+    hg pull -u
+    pip install -e .
+
+
+5. Upgrade your configuration
+-----------------------------
+
+Run the following command to upgrade your configuration (``.ini``) file::
+
+    paster make-config Kallithea my.ini
+
+This will display any changes made by the new version of Kallithea to your
+current configuration, and attempt an automatic merge. It is recommended
+that you check the contents after the merge.
+
+.. note::
+    Please always make sure your ``.ini`` files are up to date. Errors
+    can often be caused by missing parameters added in new versions.
+
+.. _upgrade_db:
+
+
+6. Upgrade your database
+------------------------
+
+.. note::
+    If you are *downgrading* Kallithea, you should perform the database
+    migration step *before* installing the older version. (That is,
+    always perform migrations using the most recent of the two versions
+    you're migrating between.)
+
+First, run the following command to see your current database version::
+
+    alembic -c my.ini current
+
+Typical output will be something like "9358dc3d6828 (head)", which is
+the current Alembic database "revision ID". Write down the entire output
+for troubleshooting purposes.
+
+The output will be empty if you're upgrading from Kallithea 0.3.x or
+older. That's expected. If you get an error that the config file was not
+found or has no ``[alembic]`` section, see the next section.
+
+Next, if you are performing an *upgrade*: Run the following command to
+upgrade your database to the current Kallithea version::
+
+    alembic -c my.ini upgrade head
+
+If you are performing a *downgrade*: Run the following command to
+downgrade your database to the given version::
+
+    alembic -c my.ini downgrade 0.4
+
+Alembic will show the necessary migrations (if any) as it executes them.
+If no "ERROR" is displayed, the command was successful.
+
+Should an error occur, the database may be "stranded" half-way
+through the migration, and you should restore it from backup.
+
+Enabling old Kallithea config files for Alembic use
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Kallithea configuration files created before the introduction of Alembic
+(i.e. predating Kallithea 0.4) need to be updated for use with Alembic.
+Without this, Alembic will fail with an error like this::
+
+    FAILED: No config file 'my.ini' found, or file has no '[alembic]' section
+
+If Alembic complains specifically about a missing ``alembic.ini``, it is
+likely because you did not specify a config file using the ``-c`` option.
+On the other hand, if the mentioned config file actually exists, you
+need to append the following lines to it::
+
+    [alembic]
+    script_location = kallithea:alembic
+
+Your config file should now work with Alembic.
+
+
+7. Rebuild the Whoosh full-text index
+-------------------------------------
+
+It is recommended that you rebuild the Whoosh index after upgrading since
+new Whoosh versions can introduce incompatible index changes.
+
+
+8. Start the Kallithea web application
+--------------------------------------
+
+This step once again depends entirely on the web server software used to
+serve Kallithea.
+
+Before starting the new version of Kallithea, you may find it helpful to
+clear out your log file so that new errors are readily apparent.
+
+.. note::
+    If you're using Celery, make sure you restart all instances of it after
+    upgrade.
+
+
+.. _virtualenv: http://pypi.python.org/pypi/virtualenv
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/docs/usage/customization.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,50 @@
+.. _customization:
+
+=============
+Customization
+=============
+
+There are several ways to customize Kallithea to your needs depending on what
+you want to achieve.
+
+
+HTML/JavaScript/CSS customization
+---------------------------------
+
+To customize the look-and-feel of the web interface (for example to add a
+company banner or some JavaScript widget or to tweak the CSS style definitions)
+you can enter HTML code (possibly with JavaScript and/or CSS) directly via the
+*Admin > Settings > Global > HTML/JavaScript customization
+block*.
+
+
+Behavioral customization: rcextensions
+--------------------------------------
+
+Some behavioral customization can be done in Python using ``rcextensions``, a
+custom Python package that can extend Kallithea functionality.
+
+With ``rcextensions`` it's possible to add additional mappings for Whoosh
+indexing and statistics, to add additional code into the push/pull/create/delete
+repository hooks (for example to send signals to build bots such as Jenkins) and
+even to monkey-patch certain parts of the Kallithea source code (for example
+overwrite an entire function, change a global variable, ...).
+
+To generate a skeleton extensions package, run::
+
+    paster make-rcext my.ini
+
+This will create an ``rcextensions`` package next to the specified ``ini`` file.
+See the ``__init__.py`` file inside the generated ``rcextensions`` package
+for more details.
+
+
+Behavioral customization: code changes
+--------------------------------------
+
+As Kallithea is open-source software, you can make any changes you like directly
+in the source code.
+
+We encourage you to send generic improvements back to the
+community so that Kallithea can become better. See :ref:`contributing` for more
+details.
--- a/docs/usage/debugging.rst	Thu Nov 17 13:09:43 2016 +0800
+++ b/docs/usage/debugging.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -25,7 +25,7 @@
 
 To enable interactive debug mode simply comment out ``set debug = false`` in
 the .ini file. This will trigger an interactive debugger each time
-there is an error in the browser, or send a http link if an error occured in the backend. This
+there is an error in the browser, or send a http link if an error occurred in the backend. This
 is a great tool for fast debugging as you get a handy Python console right
 in the web view.
 
--- a/docs/usage/email.rst	Thu Nov 17 13:09:43 2016 +0800
+++ b/docs/usage/email.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -12,8 +12,17 @@
 Before any email can be sent, an SMTP server has to be configured using the
 configuration file setting ``smtp_server``. If required for that server, specify
 a username (``smtp_username``) and password (``smtp_password``), a non-standard
-port (``smtp_port``), encryption settings (``smtp_use_tls`` or ``smtp_use_ssl``)
-and/or specific authentication parameters (``smtp_auth``).
+port (``smtp_port``), whether to use "SSL" when connecting (``smtp_use_ssl``)
+or use STARTTLS (``smtp_use_tls``), and/or specify special ESMTP "auth" features
+(``smtp_auth``).
+
+For example, for sending through gmail, use::
+
+    smtp_server = smtp.gmail.com
+    smtp_username = username
+    smtp_password = password
+    smtp_port = 465
+    smtp_use_ssl = true
 
 
 Application emails
@@ -48,6 +57,19 @@
 The subject of these emails can optionally be prefixed with the value of
 ``email_prefix`` in the configuration file.
 
+A Kallithea-specific header indicating the email type will be added to each
+email. This header can be used for email filtering. The header is of the form:
+
+    X-Kallithea-Notification-Type: <type>
+
+where ``<type>`` is one of:
+
+- ``pull_request``: you are invited as reviewer in a pull request
+- ``pull_request_comment``: a comment was given on a pull request
+- ``cs_comment``: a comment was given on a changeset
+- ``registration``: a new user was registered
+- ``message``: another type of email
+
 
 Error emails
 ------------
--- a/docs/usage/general.rst	Thu Nov 17 13:09:43 2016 +0800
+++ b/docs/usage/general.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -151,7 +151,7 @@
 features that merit further explanation.
 
 Repository extra fields
-~~~~~~~~~~~~~~~~~~~~~~~
+^^^^^^^^^^^^^^^^^^^^^^^
 
 In the *Visual* tab, there is an option "Use repository extra
 fields", which allows to set custom fields for each repository in the system.
@@ -165,7 +165,7 @@
 Newly created fields are accessible via the API.
 
 Meta tagging
-~~~~~~~~~~~~
+^^^^^^^^^^^^
 
 In the *Visual* tab, option "Stylify recognised meta tags" will cause Kallithea
 to turn certain text fragments in repository and repository group
--- a/docs/usage/performance.rst	Thu Nov 17 13:09:43 2016 +0800
+++ b/docs/usage/performance.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -9,21 +9,17 @@
 amounts of data from version control systems, here are some tips on how to get
 the best performance.
 
-* Kallithea is often I/O bound, and hence a fast disk (SSD/SAN) is
-  usually more important than a fast CPU.
-
-* Sluggish loading of the front page can easily be fixed by grouping repositories or by
-  increasing cache size (see below). This includes using the lightweight dashboard
-  option and ``vcs_full_cache`` setting in .ini file.
-
 Follow these few steps to improve performance of Kallithea system.
 
-1. Increase cache
+1.  Kallithea is often I/O bound, and hence a fast disk (SSD/SAN) is
+    usually more important than a fast CPU.
+
+2. Increase cache
 
     Tweak beaker cache settings in the ini file. The actual effect of that
     is questionable.
 
-2. Switch from SQLite to PostgreSQL or MySQL
+3. Switch from SQLite to PostgreSQL or MySQL
 
     SQLite is a good option when having a small load on the system. But due to
     locking issues with SQLite, it is not recommended to use it for larger
@@ -31,26 +27,73 @@
     performance increase. A tool like SQLAlchemyGrate_ can be used for
     migrating to another database platform.
 
-3. Scale Kallithea horizontally
+4. Scale Kallithea horizontally
 
     Scaling horizontally can give huge performance benefits when dealing with
     large amounts of traffic (many users, CI servers, etc.). Kallithea can be
-    scaled horizontally on one (recommended) or multiple machines. In order
-    to scale horizontally you need to do the following:
+    scaled horizontally on one (recommended) or multiple machines.
+
+    It is generally possible to run WSGI applications multithreaded, so that
+    several HTTP requests are served from the same Python process at once. That
+    can in principle give better utilization of internal caches and less
+    process overhead.
+
+    One danger of running multithreaded is that program execution becomes much
+    more complex; programs must be written to consider all combinations of
+    events and problems might depend on timing and be impossible to reproduce.
 
-    - Each instance needs its own .ini file and unique ``instance_id`` set.
+    Kallithea can't promise to be thread-safe, just like the embedded Mercurial
+    backend doesn't make any strong promises when used as Kallithea uses it.
+    Instead, we recommend scaling by using multiple server processes.
+
+    Web servers with multiple worker processes (such as ``mod_wsgi`` with the
+    ``WSGIDaemonProcess`` ``processes`` parameter) will work out of the box.
+
+    In order to scale horizontally on multiple machines, you need to do the
+    following:
+
     - Each instance's ``data`` storage needs to be configured to be stored on a
       shared disk storage, preferably together with repositories. This ``data``
       dir contains template caches, sessions, whoosh index and is used for
       task locking (so it is safe across multiple instances). Set the
       ``cache_dir``, ``index_dir``, ``beaker.cache.data_dir``, ``beaker.cache.lock_dir``
       variables in each .ini file to a shared location across Kallithea instances
-    - If celery is used each instance should run a separate Celery instance, but
+    - If using several Celery instances,
       the message broker should be common to all of them (e.g.,  one
       shared RabbitMQ server)
     - Load balance using round robin or IP hash, recommended is writing LB rules
       that will separate regular user traffic from automated processes like CI
       servers or build bots.
 
+5. Serve static files directly from the web server
+
+With the default ``static_files`` ini setting, the Kallithea WSGI application
+will take care of serving the static files found in ``kallithea/public`` from
+the root of the application URL. While doing that, it will currently also
+apply buffering and compression of all the responses it is serving.
+
+The actual serving of the static files is unlikely to be a problem in a
+Kallithea setup. The buffering of responses is more likely to be a problem;
+large responses (clones or pulls) will have to be fully processed and spooled
+to disk or memory before the client will see any response.
+
+To serve static files from the web server, use something like this Apache config
+snippet::
+
+        Alias /images/ /srv/kallithea/kallithea/kallithea/public/images/
+        Alias /css/ /srv/kallithea/kallithea/kallithea/public/css/
+        Alias /js/ /srv/kallithea/kallithea/kallithea/public/js/
+        Alias /codemirror/ /srv/kallithea/kallithea/kallithea/public/codemirror/
+        Alias /fontello/ /srv/kallithea/kallithea/kallithea/public/fontello/
+
+Then disable serving of static files in the ``.ini`` ``app:main`` section::
+
+        static_files = false
+
+If using Kallithea installed as a package, you should be able to find the files
+under site-packages/kallithea, either in your Python installation or in your
+virtualenv. When upgrading, make sure to update the web server configuration
+too if necessary.
+
 
 .. _SQLAlchemyGrate: https://github.com/shazow/sqlalchemygrate
--- a/docs/usage/troubleshooting.rst	Thu Nov 17 13:09:43 2016 +0800
+++ b/docs/usage/troubleshooting.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -63,7 +63,7 @@
 |
 
 :Q: **Requests hanging on Windows**
-:A: Please try out with disabled Antivirus software, there are some known problems with Eset Anitivirus. Make sure
+:A: Please try out with disabled Antivirus software, there are some known problems with Eset Antivirus. Make sure
     you have installed the latest Windows patches (especially KB2789397).
 
 
--- a/docs/usage/vcs_support.rst	Thu Nov 17 13:09:43 2016 +0800
+++ b/docs/usage/vcs_support.rst	Fri Nov 18 01:11:13 2016 +0100
@@ -23,7 +23,7 @@
 
 
 Web server with chunked encoding
-````````````````````````````````
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Large Git pushes require an HTTP server with support for
 chunked encoding for POST. The Python web servers waitress_ and
@@ -51,7 +51,7 @@
 
 
 Working with Mercurial subrepositories
-``````````````````````````````````````
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 This section explains how to use Mercurial subrepositories_ in Kallithea.
 
--- a/kallithea/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/__init__.py	Fri Nov 18 01:11:13 2016 +0100
@@ -15,8 +15,9 @@
 kallithea
 ~~~~~~~~~
 
-Kallithea, a web based repository management based on pylons
-versioning implementation: http://www.python.org/dev/peps/pep-0386/
+Kallithea, a web based repository management system.
+
+Versioning implementation: http://www.python.org/dev/peps/pep-0386/
 
 This file was forked by the Kallithea project in July 2014.
 Original author and date, and relevant copyright and licensing information is below:
@@ -29,7 +30,7 @@
 import sys
 import platform
 
-VERSION = (0, 3, 2)
+VERSION = (0, 3, 99)
 BACKENDS = {
     'hg': 'Mercurial repository',
     'git': 'Git repository',
@@ -38,45 +39,20 @@
 CELERY_ON = False
 CELERY_EAGER = False
 
-# link to config for pylons
 CONFIG = {}
 
 # Linked module for extensions
 EXTENSIONS = {}
 
-# BRAND controls internal references in database and config to the products
-# own name.
-#
-# NOTE: If you want compatibility with a database that was originally created
-#  for use with the RhodeCode software product, change BRAND to "rhodecode",
-#  either by editing here or by creating a new file:
-#  echo "BRAND = 'rhodecode'" > kallithea/brand.py
-
-BRAND = "kallithea"
 try:
-    from kallithea.brand import BRAND
+    import kallithea.brand
 except ImportError:
     pass
-
-# Prefix for the ui and settings table names
-DB_PREFIX = (BRAND + "_") if BRAND != "kallithea" else ""
-
-# Users.extern_type and .extern_name value for local users
-EXTERN_TYPE_INTERNAL = BRAND if BRAND != 'kallithea' else 'internal'
-
-# db_migrate_version.repository_id value, same as kallithea/lib/dbmigrate/migrate.cfg
-DB_MIGRATIONS = BRAND + "_db_migrations"
+else:
+    assert False, 'Database rebranding is no longer supported; see README.'
 
-try:
-    from kallithea.lib import get_current_revision
-    _rev = get_current_revision(quiet=True)
-    if _rev and len(VERSION) > 3:
-        VERSION += (_rev[0],)
-except ImportError:
-    pass
 
-__version__ = ('.'.join((str(each) for each in VERSION[:3])))
-__dbversion__ = 31  # defines current db version for migrations
+__version__ = '.'.join(str(each) for each in VERSION)
 __platform__ = platform.system()
 __license__ = 'GPLv3'
 __py_version__ = sys.version_info
@@ -85,17 +61,3 @@
 
 is_windows = __platform__ in ['Windows']
 is_unix = not is_windows
-
-if len(VERSION) > 3:
-    __version__ += '.'+VERSION[3]
-
-    if len(VERSION) > 4:
-        __version__ += VERSION[4]
-    else:
-        __version__ += '0'
-
-# Hack for making the celery dependency kombu==1.5.1 compatible with Python
-# 2.7.11 which has https://hg.python.org/releases/2.7.11/rev/24bdc4940e81
-import uuid
-if not hasattr(uuid, '_uuid_generate_random'):
-    uuid._uuid_generate_random = None
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/alembic/env.py	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,105 @@
+# -*- coding: utf-8 -*-
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Alembic migration environment (configuration).
+
+import logging
+from logging.config import fileConfig
+
+from alembic import context
+from sqlalchemy import engine_from_config, pool
+
+from kallithea.model import db
+
+
+# The alembic.config.Config object, which wraps the current .ini file.
+config = context.config
+
+# Default to use the main Kallithea database string in [app:main].
+# For advanced uses, this can be overridden by specifying an explicit
+# [alembic] sqlalchemy.url.
+database_url = (
+    config.get_main_option('sqlalchemy.url') or
+    config.get_section_option('app:main', 'sqlalchemy.url')
+)
+
+# Configure default logging for Alembic. (This can be overriden by the
+# config file, but usually isn't.)
+logging.getLogger('alembic').setLevel(logging.INFO)
+
+# Setup Python loggers based on the config file provided to the alembic
+# command. If we're being invoked via the Alembic API (presumably for
+# stamping during "paster setup-db"), config_file_name is not available,
+# and loggers are assumed to already have been configured.
+if config.config_file_name:
+    fileConfig(config.config_file_name, disable_existing_loggers=False)
+
+
+def include_in_autogeneration(object, name, type, reflected, compare_to):
+    """Filter changes subject to autogeneration of migrations. """
+
+    # Don't include changes to sqlite_sequence.
+    if type == 'table' and name == 'sqlite_sequence':
+        return False
+
+    return True
+
+
+def run_migrations_offline():
+    """Run migrations in 'offline' (--sql) mode.
+
+    This produces an SQL script instead of directly applying the changes.
+    Some migrations may not run in offline mode.
+    """
+    context.configure(
+        url=database_url,
+        literal_binds=True,
+    )
+
+    with context.begin_transaction():
+        context.run_migrations()
+
+
+def run_migrations_online():
+    """Run migrations in 'online' mode.
+
+    Connects to the database and directly applies the necessary
+    migrations.
+    """
+    cfg = config.get_section(config.config_ini_section)
+    cfg['sqlalchemy.url'] = database_url
+    connectable = engine_from_config(
+        cfg,
+        prefix='sqlalchemy.',
+        poolclass=pool.NullPool)
+
+    with connectable.connect() as connection:
+        context.configure(
+            connection=connection,
+
+            # Support autogeneration of migration scripts based on "diff" between
+            # current database schema and kallithea.model.db schema.
+            target_metadata=db.Base.metadata,
+            include_object=include_in_autogeneration,
+            render_as_batch=True, # batch mode is needed for SQLite support
+        )
+
+        with context.begin_transaction():
+            context.run_migrations()
+
+
+if context.is_offline_mode():
+    run_migrations_offline()
+else:
+    run_migrations_online()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/alembic/script.py.mako	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,40 @@
+# -*- coding: utf-8 -*-
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+## Template for creating new Alembic migration scripts.
+"""${message}
+
+Revision ID: ${up_revision}
+Revises: ${down_revision | comma,n}
+Create Date: ${create_date}
+
+"""
+
+# The following opaque hexadecimal identifiers ("revisions") are used
+# by Alembic to track this migration script and its relations to others.
+revision = ${repr(up_revision)}
+down_revision = ${repr(down_revision)}
+branch_labels = ${repr(branch_labels)}
+depends_on = ${repr(depends_on)}
+
+from alembic import op
+import sqlalchemy as sa
+${imports if imports else ""}
+
+def upgrade():
+    ${upgrades if upgrades else "pass"}
+
+
+def downgrade():
+    ${downgrades if downgrades else "pass"}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/alembic/versions/9358dc3d6828_drop_sqlalchemy_migrate_support.py	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,37 @@
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+"""Drop SQLAlchemy Migrate support
+
+Revision ID: 9358dc3d6828
+Revises:
+Create Date: 2016-03-01 15:21:30.896585
+
+"""
+
+# The following opaque hexadecimal identifiers ("revisions") are used
+# by Alembic to track this migration script and its relations to others.
+revision = '9358dc3d6828'
+down_revision = None
+branch_labels = None
+depends_on = None
+
+from alembic import op
+
+
+def upgrade():
+    op.drop_table('db_migrate_version')
+
+
+def downgrade():
+    raise NotImplementedError('cannot revert to SQLAlchemy Migrate')
--- a/kallithea/bin/kallithea_backup.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/bin/kallithea_backup.py	Fri Nov 18 01:11:13 2016 +0100
@@ -28,11 +28,11 @@
 
 import os
 import sys
-
 import logging
 import tarfile
 import datetime
 import subprocess
+import tempfile
 
 logging.basicConfig(level=logging.DEBUG,
                     format="%(asctime)s %(levelname)-5.5s %(message)s")
@@ -47,7 +47,7 @@
         self.repos_path = self.get_repos_path(repos_location)
         self.backup_server = backup_server
 
-        self.backup_file_path = '/tmp'
+        self.backup_file_path = tempfile.gettempdir()
 
         logging.info('starting backup for %s', self.repos_path)
         logging.info('backup target %s', self.backup_file_path)
@@ -86,7 +86,7 @@
                '%(backup_server)s' % params]
 
         subprocess.call(cmd)
-        logging.info('Transfered file %s to %s', self.backup_file_name, cmd[4])
+        logging.info('Transferred file %s to %s', self.backup_file_name, cmd[4])
 
     def rm_file(self):
         logging.info('Removing file %s', self.backup_file_name)
--- a/kallithea/bin/kallithea_config.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/bin/kallithea_config.py	Fri Nov 18 01:11:13 2016 +0100
@@ -84,7 +84,7 @@
     # recurse because there may be more escaped separators
     endlist = _escape_split(after, sep)
 
-    # finish building the escaped value. we use endlist[0] becaue the first
+    # finish building the escaped value. we use endlist[0] because the first
     # part of the string sent in recursion is the rest of the escaped value.
     unfinished += sep + endlist[0]
 
--- a/kallithea/bin/rebranddb.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,173 +0,0 @@
-#!/usr/bin/env python2
-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-Script for rebranding of database to and from what Kallithea expects
-
-Works on databases from v1.7.2 to v2.2.5
-"""
-
-import sys
-from sqlalchemy import *
-import sqlalchemy.orm
-import sqlalchemy.ext.declarative
-import migrate.changeset # a part of sqlalchemy-migrate which is available on pypi
-
-def do_migrate(db, old, new):
-    print 'Migrating %s from %s to %s' % (db, old or '?', new)
-    metadata = MetaData()
-    metadata.bind = create_engine(db)
-    metadata.reflect()
-    assert metadata.tables, 'Cannot reflect table names from db'
-
-    if not old:
-        assert 'db_migrate_version' in metadata.tables, 'Cannot reflect db_migrate_version from db'
-        t = metadata.tables['db_migrate_version']
-        l = t.select().where(t.c.repository_path == 'versions').execute().fetchall()
-        assert len(l) == 1, 'Cannot find a single versions entry in db_migrate_version'
-        assert l[0].repository_id.endswith('_db_migrations')
-        old = l[0].repository_id[:-len('_db_migrations')]
-        print 'Detected migration from old name %s' % old
-        if new != old:
-            assert not t.select().where(t.c.repository_id == new + '_db_migrations').execute().fetchall(), 'db_migrate_version has entries for both old and new name'
-
-    def tablename(brand, s):
-        return s if brand == 'kallithea' else (brand + '_' + s)
-    new_ui_name = tablename(new, 'ui')
-    old_ui_name = tablename(old, 'ui')
-    new_settings_name = tablename(new, 'settings')
-    old_settings_name = tablename(old, 'settings')
-
-    # Table renames using sqlalchemy-migrate (available on pypi)
-    if new_ui_name == old_ui_name:
-        print 'No renaming of %s' % new_ui_name
-    else:
-        try:
-            t = metadata.tables[old_ui_name]
-            print 'Renaming', t, 'to', new_ui_name
-            migrate.changeset.rename_table(t, new_ui_name)
-        except KeyError as e:
-            print 'Not renaming ui:', e
-
-    if new_settings_name == old_settings_name:
-        print 'No renaming of %s' % new_settings_name
-    else:
-        try:
-            t = metadata.tables[old_settings_name]
-            print 'Renaming', t, 'to', new_settings_name
-            migrate.changeset.rename_table(t, new_settings_name)
-        except KeyError as e:
-            print 'Not renaming settings:', e
-
-    old_auth_name = 'internal' if old == 'kallithea' else old
-    new_auth_name = 'internal' if new == 'kallithea' else new
-
-    # using this API because ... dunno ... it is simple and works
-    conn = metadata.bind.connect()
-    trans = conn.begin()
-    t = metadata.tables['users']
-
-    print 'Bulk fixing of User extern_name'
-    try:
-        t.c.extern_name
-    except AttributeError:
-        print 'No extern_name to rename'
-    else:
-        t.update().where(t.c.extern_name == old_auth_name).values(extern_name=new_auth_name).execute()
-
-    print 'Bulk fixing of User extern_type'
-    try:
-        t.c.extern_type
-    except AttributeError:
-        print 'No extern_type to rename'
-    else:
-        t.update().where(t.c.extern_type == old_auth_name).values(extern_type=new_auth_name).execute()
-
-    trans.commit()
-
-    # For the following conversions, use ORM ... and create stub models that works for that purpose
-    Base = sqlalchemy.ext.declarative.declarative_base()
-
-    class Ui(Base):
-        __tablename__ = new_ui_name
-        ui_id = Column("ui_id", Integer(), primary_key=True)
-        ui_section = Column("ui_section", String())
-        ui_key = Column("ui_key", String())
-        ui_value = Column("ui_value", String())
-        ui_active = Column("ui_active", Boolean())
-
-    class Setting(Base):
-        __tablename__ = new_settings_name
-        app_settings_id = Column("app_settings_id", Integer(), primary_key=True)
-        app_settings_name = Column("app_settings_name", String())
-        app_settings_value = Column("app_settings_value", String())
-        #app_settings_type = Column("app_settings_type", String()) # not present in v1.7.2
-
-    class DbMigrateVersion(Base):
-        __tablename__ = 'db_migrate_version'
-        repository_id = Column('repository_id', String(), primary_key=True)
-        repository_path = Column('repository_path', Text)
-        version = Column('version', Integer)
-
-    Session = sqlalchemy.orm.sessionmaker(bind=metadata.bind)
-    session = Session()
-
-    print 'Fixing hook names'
-
-    oldhooks = u'python:%s.lib.hooks.' % old
-    newhooks = u'python:%s.lib.hooks.' % new
-    for u in session.query(Ui).filter(Ui.ui_section == 'hooks').all():
-        if u.ui_value.startswith(oldhooks):
-            print '- fixing %s' % u.ui_key
-            u.ui_value = newhooks + u.ui_value[len(oldhooks):]
-            session.add(u)
-    session.commit()
-
-    print 'Fixing auth module names'
-    for s in session.query(Setting).filter(Setting.app_settings_name == 'auth_plugins').all():
-        print '- fixing %s' % s.app_settings_name
-        s.app_settings_value = (s.app_settings_value
-                                .replace(old + '.lib.auth_modules.auth_', new + '.lib.auth_modules.auth_')
-                                .replace('.auth_modules.auth_' + old_auth_name, '.auth_modules.auth_' + new_auth_name))
-        session.add(s)
-    for s in session.query(Setting).filter(Setting.app_settings_name == 'auth_' + old_auth_name + '_enabled').all():
-        print '- fixing %s' % s.app_settings_name
-        s.app_settings_name = 'auth_' + new_auth_name + '_enabled'
-        session.add(s)
-    session.commit()
-
-    print 'Fixing db migration version number'
-    for s in session.query(DbMigrateVersion).filter(DbMigrateVersion.repository_id == old + '_db_migrations', DbMigrateVersion.repository_path == 'versions').all():
-        print '- fixing %s' % s.repository_id
-        s.repository_id = new + '_db_migrations'
-    session.commit()
-
-    print 'Done'
-
-def main(argv):
-    if len(argv) < 2 or argv[1] in ['-h', '--help']:
-        print 'usage: kallithea/bin/rebranddb.py DBSTRING [NEW] [OLD]'
-        print '  where DBSTRING is the value of sqlalchemy.db1.url from the .ini,'
-        print '  NEW defaults to "kallithea", OLD is by default detected from the db"'
-        raise SystemExit(0)
-    new = 'kallithea'
-    if len(argv) > 2:
-        new = argv[2]
-    old = None
-    if len(argv) > 3:
-        old = argv[3]
-    do_migrate(argv[1], old, new)
-
-if __name__ == '__main__':
-    main(sys.argv)
--- a/kallithea/bin/template.ini.mako	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/bin/template.ini.mako	Fri Nov 18 01:11:13 2016 +0100
@@ -49,26 +49,25 @@
 #error_email_from = paste_error@example.com
 
 <%text>## SMTP server settings</%text>
-<%text>## Only smtp_server is mandatory. All other settings take the specified default</%text>
-<%text>## values.</%text>
+<%text>## If specifying credentials, make sure to use secure connections.</%text>
+<%text>## Default: Send unencrypted unauthenticated mails to the specified smtp_server.</%text>
+<%text>## For "SSL", use smtp_use_ssl = true and smtp_port = 465.</%text>
+<%text>## For "STARTTLS", use smtp_use_tls = true and smtp_port = 587.</%text>
 #smtp_server = smtp.example.com
 #smtp_username =
 #smtp_password =
 #smtp_port = 25
+#smtp_use_ssl = false
 #smtp_use_tls = false
-#smtp_use_ssl = false
-<%text>## SMTP authentication parameters to use (e.g. LOGIN PLAIN CRAM-MD5, etc.).</%text>
-<%text>## If empty, use any of the authentication parameters supported by the server.</%text>
-#smtp_auth =
 
 [server:main]
 %if http_server == 'paste':
 <%text>## PASTE ##</%text>
 use = egg:Paste#http
 <%text>## nr of worker threads to spawn</%text>
-threadpool_workers = 5
+threadpool_workers = 1
 <%text>## max request before thread respawn</%text>
-threadpool_max_requests = 10
+threadpool_max_requests = 100
 <%text>## option to use threads of process</%text>
 use_threadpool = true
 
@@ -76,7 +75,7 @@
 <%text>## WAITRESS ##</%text>
 use = egg:waitress#main
 <%text>## number of worker threads</%text>
-threads = 5
+threads = 1
 <%text>## MAX BODY SIZE 100GB</%text>
 max_request_body_size = 107374182400
 <%text>## use poll instead of select, fixes fd limits, may not work on old</%text>
@@ -95,7 +94,7 @@
 <%text>## recommended for bigger setup is using of of other than sync one</%text>
 worker_class = sync
 max_requests = 1000
-<%text>## ammount of time a worker can handle request before it gets killed and</%text>
+<%text>## amount of time a worker can handle request before it gets killed and</%text>
 <%text>## restarted</%text>
 timeout = 3600
 
@@ -196,9 +195,6 @@
 <%text>## cut off limit for large diffs (size in bytes)</%text>
 cut_off_limit = 256000
 
-<%text>## use cache version of scm repo everywhere</%text>
-vcs_full_cache = true
-
 <%text>## force https in Kallithea, fixes https redirects, assumes it's always https</%text>
 force_https = false
 
@@ -224,6 +220,11 @@
 show_sha_length = 12
 show_revision_number = false
 
+<%text>## Canonical URL to use when creating full URLs in UI and texts.</%text>
+<%text>## Useful when the site is available under different names or protocols.</%text>
+<%text>## Defaults to what is provided in the WSGI environment.</%text>
+#canonical_url = https://kallithea.example.com/repos
+
 <%text>## gist URL alias, used to create nicer urls for gist. This should be an</%text>
 <%text>## url that does rewrites to _admin/gists/<gistid>.</%text>
 <%text>## example: http://gist.example.com/{gistid}. Empty means use the internal</%text>
@@ -243,7 +244,7 @@
 #    FilesController:archivefile
 
 <%text>## default encoding used to convert from and to unicode</%text>
-<%text>## can be also a comma seperated list of encoding in case of mixed encodings</%text>
+<%text>## can be also a comma separated list of encoding in case of mixed encodings</%text>
 default_encoding = utf8
 
 <%text>## issue tracker for Kallithea (leave blank to disable, absent for default)</%text>
@@ -278,12 +279,6 @@
 #issue_server_link_wiki = https://wiki.example.com/{id}
 #issue_prefix_wiki = WIKI-
 
-<%text>## instance-id prefix</%text>
-<%text>## a prefix key for this instance used for cache invalidation when running</%text>
-<%text>## multiple instances of kallithea, make sure it's globally unique for</%text>
-<%text>## all running kallithea instances. Leave empty if you don't use it</%text>
-instance_id =
-
 <%text>## alternative return HTTP header for failed authentication. Default HTTP</%text>
 <%text>## response is 401 HTTPUnauthorized. Currently Mercurial clients have trouble with</%text>
 <%text>## handling that. Set this variable to 403 to return HTTPForbidden</%text>
@@ -299,19 +294,29 @@
 <%text>## allows to setup custom hooks in settings page</%text>
 allow_custom_hooks_settings = True
 
+<%text>## extra extensions for indexing, space separated and without the leading '.'.</%text>
+# index.extensions =
+#    gemfile
+#    lock
+
+<%text>## extra filenames for indexing, space separated</%text>
+# index.filenames =
+#    .dockerignore
+#    .editorconfig
+#    INSTALL
+#    CHANGELOG
+
 <%text>####################################</%text>
 <%text>###        CELERY CONFIG        ####</%text>
 <%text>####################################</%text>
 
 use_celery = false
-broker.host = localhost
-broker.vhost = rabbitmqhost
-broker.port = 5672
-broker.user = rabbitmq
-broker.password = qweqwe
+
+<%text>## Example: connect to the virtual host 'rabbitmqhost' on localhost as rabbitmq:</%text>
+broker.url = amqp://rabbitmq:qewqew@localhost:5672/rabbitmqhost
 
 celery.imports = kallithea.lib.celerylib.tasks
-
+celery.accept.content = pickle
 celery.result.backend = amqp
 celery.result.dburi = amqp://
 celery.result.serialier = json
@@ -320,11 +325,9 @@
 #celery.amqp.task.result.expires = 18000
 
 celeryd.concurrency = 2
-#celeryd.log.file = celeryd.log
-celeryd.log.level = DEBUG
 celeryd.max.tasks.per.child = 1
 
-<%text>## tasks will never be sent to the queue, but executed locally instead.</%text>
+<%text>## If true, tasks will never be sent to the queue, but executed locally instead.</%text>
 celery.always.eager = false
 
 <%text>####################################</%text>
@@ -421,7 +424,7 @@
 <%text>## (saves API quota for intensive logging)</%text>
 errormator.logging_on_error = false
 
-<%text>## list of additonal keywords that should be grabbed from environ object</%text>
+<%text>## list of additional keywords that should be grabbed from environ object</%text>
 <%text>## can be string with comma separated list of words in lowercase</%text>
 <%text>## (by default client will always send following info:</%text>
 <%text>## 'REMOTE_USER', 'REMOTE_ADDR', 'SERVER_NAME', 'CONTENT_TYPE' + all keys that</%text>
@@ -481,22 +484,28 @@
 
 %if database_engine == 'sqlite':
 # SQLITE [default]
-sqlalchemy.db1.url = sqlite:///${here}/kallithea.db?timeout=60
+sqlalchemy.url = sqlite:///${here}/kallithea.db?timeout=60
 
 %elif database_engine == 'postgres':
 # POSTGRESQL
-sqlalchemy.db1.url = postgresql://user:pass@localhost/kallithea
+sqlalchemy.url = postgresql://user:pass@localhost/kallithea
 
 %elif database_engine == 'mysql':
 # MySQL
-sqlalchemy.db1.url = mysql://user:pass@localhost/kallithea
+sqlalchemy.url = mysql://user:pass@localhost/kallithea?charset=utf8
 
 %endif
 # see sqlalchemy docs for others
 
-sqlalchemy.db1.echo = false
-sqlalchemy.db1.pool_recycle = 3600
-sqlalchemy.db1.convert_unicode = true
+sqlalchemy.echo = false
+sqlalchemy.pool_recycle = 3600
+
+<%text>################################</%text>
+<%text>### ALEMBIC CONFIGURATION   ####</%text>
+<%text>################################</%text>
+
+[alembic]
+script_location = kallithea:alembic
 
 <%text>################################</%text>
 <%text>### LOGGING CONFIGURATION   ####</%text>
--- a/kallithea/config/conf.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/config/conf.py	Fri Nov 18 01:11:13 2016 +0100
@@ -25,19 +25,21 @@
 :license: GPLv3, see LICENSE.md for more details.
 """
 
-from kallithea.lib.utils2 import __get_lem
+from kallithea.lib import pygmentsutils
 
 
 # language map is also used by whoosh indexer, which for those specified
 # extensions will index it's content
-LANGUAGES_EXTENSIONS_MAP = __get_lem()
+LANGUAGES_EXTENSIONS_MAP = pygmentsutils.get_lem()
+
+# Whoosh index targets
 
-#==============================================================================
-# WHOOSH INDEX EXTENSIONS
-#==============================================================================
-# EXTENSIONS WE WANT TO INDEX CONTENT OFF USING WHOOSH
+# Extensions we want to index content of using whoosh
 INDEX_EXTENSIONS = LANGUAGES_EXTENSIONS_MAP.keys()
 
+# Filenames we want to index content of using whoosh
+INDEX_FILENAMES = pygmentsutils.get_index_filenames()
+
 # list of readme files to search in file tree and display in summary
 # attached weights defines the search  order lower is first
 ALL_READMES = [
@@ -65,7 +67,3 @@
 PLAIN_EXTS = [('.text', 2), ('.TEXT', 2)]
 
 ALL_EXTS = MARKDOWN_EXTS + RST_EXTS + PLAIN_EXTS
-
-DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
-
-DATE_FORMAT = "%Y-%m-%d"
--- a/kallithea/config/deployment.ini_tmpl	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/config/deployment.ini_tmpl	Fri Nov 18 01:11:13 2016 +0100
@@ -50,32 +50,31 @@
 #error_email_from = paste_error@example.com
 
 ## SMTP server settings
-## Only smtp_server is mandatory. All other settings take the specified default
-## values.
+## If specifying credentials, make sure to use secure connections.
+## Default: Send unencrypted unauthenticated mails to the specified smtp_server.
+## For "SSL", use smtp_use_ssl = true and smtp_port = 465.
+## For "STARTTLS", use smtp_use_tls = true and smtp_port = 587.
 #smtp_server = smtp.example.com
 #smtp_username =
 #smtp_password =
 #smtp_port = 25
+#smtp_use_ssl = false
 #smtp_use_tls = false
-#smtp_use_ssl = false
-## SMTP authentication parameters to use (e.g. LOGIN PLAIN CRAM-MD5, etc.).
-## If empty, use any of the authentication parameters supported by the server.
-#smtp_auth =
 
 [server:main]
 ## PASTE ##
 #use = egg:Paste#http
 ## nr of worker threads to spawn
-#threadpool_workers = 5
+#threadpool_workers = 1
 ## max request before thread respawn
-#threadpool_max_requests = 10
+#threadpool_max_requests = 100
 ## option to use threads of process
 #use_threadpool = true
 
 ## WAITRESS ##
 use = egg:waitress#main
 ## number of worker threads
-threads = 5
+threads = 1
 ## MAX BODY SIZE 100GB
 max_request_body_size = 107374182400
 ## use poll instead of select, fixes fd limits, may not work on old
@@ -93,7 +92,7 @@
 ## recommended for bigger setup is using of of other than sync one
 #worker_class = sync
 #max_requests = 1000
-## ammount of time a worker can handle request before it gets killed and
+## amount of time a worker can handle request before it gets killed and
 ## restarted
 #timeout = 3600
 
@@ -192,9 +191,6 @@
 ## cut off limit for large diffs (size in bytes)
 cut_off_limit = 256000
 
-## use cache version of scm repo everywhere
-vcs_full_cache = true
-
 ## force https in Kallithea, fixes https redirects, assumes it's always https
 force_https = false
 
@@ -220,6 +216,11 @@
 show_sha_length = 12
 show_revision_number = false
 
+## Canonical URL to use when creating full URLs in UI and texts.
+## Useful when the site is available under different names or protocols.
+## Defaults to what is provided in the WSGI environment.
+#canonical_url = https://kallithea.example.com/repos
+
 ## gist URL alias, used to create nicer urls for gist. This should be an
 ## url that does rewrites to _admin/gists/<gistid>.
 ## example: http://gist.example.com/{gistid}. Empty means use the internal
@@ -239,7 +240,7 @@
 #    FilesController:archivefile
 
 ## default encoding used to convert from and to unicode
-## can be also a comma seperated list of encoding in case of mixed encodings
+## can be also a comma separated list of encoding in case of mixed encodings
 default_encoding = utf8
 
 ## issue tracker for Kallithea (leave blank to disable, absent for default)
@@ -274,12 +275,6 @@
 #issue_server_link_wiki = https://wiki.example.com/{id}
 #issue_prefix_wiki = WIKI-
 
-## instance-id prefix
-## a prefix key for this instance used for cache invalidation when running
-## multiple instances of kallithea, make sure it's globally unique for
-## all running kallithea instances. Leave empty if you don't use it
-instance_id =
-
 ## alternative return HTTP header for failed authentication. Default HTTP
 ## response is 401 HTTPUnauthorized. Currently Mercurial clients have trouble with
 ## handling that. Set this variable to 403 to return HTTPForbidden
@@ -295,19 +290,29 @@
 ## allows to setup custom hooks in settings page
 allow_custom_hooks_settings = True
 
+## extra extensions for indexing, space separated and without the leading '.'.
+# index.extensions =
+#    gemfile
+#    lock
+
+## extra filenames for indexing, space separated
+# index.filenames =
+#    .dockerignore
+#    .editorconfig
+#    INSTALL
+#    CHANGELOG
+
 ####################################
 ###        CELERY CONFIG        ####
 ####################################
 
 use_celery = false
-broker.host = localhost
-broker.vhost = rabbitmqhost
-broker.port = 5672
-broker.user = rabbitmq
-broker.password = qweqwe
+
+## Example: connect to the virtual host 'rabbitmqhost' on localhost as rabbitmq:
+broker.url = amqp://rabbitmq:qewqew@localhost:5672/rabbitmqhost
 
 celery.imports = kallithea.lib.celerylib.tasks
-
+celery.accept.content = pickle
 celery.result.backend = amqp
 celery.result.dburi = amqp://
 celery.result.serialier = json
@@ -316,11 +321,9 @@
 #celery.amqp.task.result.expires = 18000
 
 celeryd.concurrency = 2
-#celeryd.log.file = celeryd.log
-celeryd.log.level = DEBUG
 celeryd.max.tasks.per.child = 1
 
-## tasks will never be sent to the queue, but executed locally instead.
+## If true, tasks will never be sent to the queue, but executed locally instead.
 celery.always.eager = false
 
 ####################################
@@ -416,7 +419,7 @@
 ## (saves API quota for intensive logging)
 errormator.logging_on_error = false
 
-## list of additonal keywords that should be grabbed from environ object
+## list of additional keywords that should be grabbed from environ object
 ## can be string with comma separated list of words in lowercase
 ## (by default client will always send following info:
 ## 'REMOTE_USER', 'REMOTE_ADDR', 'SERVER_NAME', 'CONTENT_TYPE' + all keys that
@@ -473,19 +476,25 @@
 #########################################################
 
 # SQLITE [default]
-sqlalchemy.db1.url = sqlite:///%(here)s/kallithea.db?timeout=60
+sqlalchemy.url = sqlite:///%(here)s/kallithea.db?timeout=60
 
 # POSTGRESQL
-#sqlalchemy.db1.url = postgresql://user:pass@localhost/kallithea
+#sqlalchemy.url = postgresql://user:pass@localhost/kallithea
 
 # MySQL
-#sqlalchemy.db1.url = mysql://user:pass@localhost/kallithea
+#sqlalchemy.url = mysql://user:pass@localhost/kallithea?charset=utf8
 
 # see sqlalchemy docs for others
 
-sqlalchemy.db1.echo = false
-sqlalchemy.db1.pool_recycle = 3600
-sqlalchemy.db1.convert_unicode = true
+sqlalchemy.echo = false
+sqlalchemy.pool_recycle = 3600
+
+################################
+### ALEMBIC CONFIGURATION   ####
+################################
+
+[alembic]
+script_location = kallithea:alembic
 
 ################################
 ### LOGGING CONFIGURATION   ####
--- a/kallithea/config/environment.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/config/environment.py	Fri Nov 18 01:11:13 2016 +0100
@@ -23,9 +23,7 @@
 import pylons
 import mako.lookup
 import beaker
-
-# don't remove this import it does magic for celery
-from kallithea.lib import celerypylons
+import formencode
 
 import kallithea.lib.app_globals as app_globals
 
@@ -33,17 +31,17 @@
 
 from kallithea.lib import helpers
 from kallithea.lib.auth import set_available_permissions
-from kallithea.lib.utils import repo2db_mapper, make_ui, set_app_settings,\
-    load_rcextensions, check_git_version, set_vcs_config
+from kallithea.lib.utils import repo2db_mapper, make_ui, set_app_settings, \
+    load_rcextensions, check_git_version, set_vcs_config, set_indexer_config
 from kallithea.lib.utils2 import engine_from_config, str2bool
 from kallithea.lib.db_manage import DbManage
-from kallithea.model import init_model
+from kallithea.model.base import init_model
 from kallithea.model.scm import ScmModel
 
 log = logging.getLogger(__name__)
 
 
-def load_environment(global_conf, app_conf, initial=False,
+def load_environment(global_conf, app_conf,
                      test_env=None, test_index=None):
     """
     Configure the Pylons environment via the ``pylons.config``
@@ -80,7 +78,7 @@
     # Create the Mako TemplateLookup, with the default auto-escaping
     config['pylons.app_globals'].mako_lookup = mako.lookup.TemplateLookup(
         directories=paths['templates'],
-        error_handler=pylons.error.handle_mako_error,
+        strict_undefined=True,
         module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
         input_encoding='utf-8', default_filters=['escape'],
         imports=['from webhelpers.html import escape'])
@@ -95,10 +93,10 @@
             test_index = not int(os.environ.get('KALLITHEA_WHOOSH_TEST_DISABLE', 0))
         if os.environ.get('TEST_DB'):
             # swap config if we pass enviroment variable
-            config['sqlalchemy.db1.url'] = os.environ.get('TEST_DB')
+            config['sqlalchemy.url'] = os.environ.get('TEST_DB')
 
         from kallithea.lib.utils import create_test_env, create_test_index
-        from kallithea.tests import TESTS_TMP_PATH
+        from kallithea.tests.base import TESTS_TMP_PATH
         #set KALLITHEA_NO_TMP_PATH=1 to disable re-creating the database and
         #test repos
         if test_env:
@@ -107,18 +105,17 @@
         if test_index:
             create_test_index(TESTS_TMP_PATH, config, True)
 
-    DbManage.check_waitress()
     # MULTIPLE DB configs
     # Setup the SQLAlchemy database engine
-    sa_engine_db1 = engine_from_config(config, 'sqlalchemy.db1.')
-    init_model(sa_engine_db1)
+    sa_engine = engine_from_config(config, 'sqlalchemy.')
+    init_model(sa_engine)
 
     set_available_permissions(config)
     repos_path = make_ui('db').configitems('paths')[0][1]
     config['base_path'] = repos_path
     set_app_settings(config)
 
-    instance_id = kallithea.CONFIG.get('instance_id')
+    instance_id = kallithea.CONFIG.get('instance_id', '*')
     if instance_id == '*':
         instance_id = '%s-%s' % (platform.uname()[1], os.getpid())
         kallithea.CONFIG['instance_id'] = instance_id
@@ -130,6 +127,7 @@
     # pylons
     kallithea.CONFIG.update(config)
     set_vcs_config(kallithea.CONFIG)
+    set_indexer_config(kallithea.CONFIG)
 
     #check git version
     check_git_version()
@@ -137,4 +135,5 @@
     if str2bool(config.get('initial_repo_scan', True)):
         repo2db_mapper(ScmModel().repo_scan(repos_path),
                        remove_obsolete=False, install_git_hooks=False)
+    formencode.api.set_stdtranslation(languages=[config.get('lang')])
     return config
--- a/kallithea/config/middleware.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/config/middleware.py	Fri Nov 18 01:11:13 2016 +0100
@@ -59,7 +59,7 @@
     app = PylonsApp(config=config)
 
     # Routing/Session/Cache Middleware
-    app = RoutesMiddleware(app, config['routes.map'])
+    app = RoutesMiddleware(app, config['routes.map'], use_method_override=False)
     app = SecureSessionMiddleware(app, config)
 
     # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
--- a/kallithea/config/post_receive_tmpl.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/config/post_receive_tmpl.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,26 +1,21 @@
-#!/usr/bin/env python2
 import os
 import sys
 
-try:
-    import kallithea
-    KALLITHEA_HOOK_VER = '_TMPL_'
-    os.environ['KALLITHEA_HOOK_VER'] = KALLITHEA_HOOK_VER
-    from kallithea.lib.hooks import handle_git_post_receive as _handler
-except ImportError:
-    if os.environ.get('RC_DEBUG_GIT_HOOK'):
-        import traceback
-        print traceback.format_exc()
-    kallithea = None
+# set output mode on windows to binary for stderr
+# this prevents python (or the windows console) from replacing \n with  \r\n
+# git doesn't display remote output lines that contain \r
+# and therefore without this modification git would displayes empty lines
+# instead of the exception output
+if sys.platform == "win32":
+    import msvcrt
+    msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
+
+KALLITHEA_HOOK_VER = '_TMPL_'
+os.environ['KALLITHEA_HOOK_VER'] = KALLITHEA_HOOK_VER
+from kallithea.lib.hooks import handle_git_post_receive as _handler
 
 
 def main():
-    if kallithea is None:
-        # exit with success if we cannot import kallithea !!
-        # this allows simply push to this repo even without
-        # kallithea
-        sys.exit(0)
-
     repo_path = os.path.abspath('.')
     push_data = sys.stdin.readlines()
     # os.environ is modified here by a subprocess call that
--- a/kallithea/config/pre_receive_tmpl.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/config/pre_receive_tmpl.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,26 +1,21 @@
-#!/usr/bin/env python2
 import os
 import sys
 
-try:
-    import kallithea
-    KALLITHEA_HOOK_VER = '_TMPL_'
-    os.environ['KALLITHEA_HOOK_VER'] = KALLITHEA_HOOK_VER
-    from kallithea.lib.hooks import handle_git_pre_receive as _handler
-except ImportError:
-    if os.environ.get('RC_DEBUG_GIT_HOOK'):
-        import traceback
-        print traceback.format_exc()
-    kallithea = None
+# set output mode on windows to binary for stderr
+# this prevents python (or the windows console) from replacing \n with  \r\n
+# git doesn't display remote output lines that contain \r
+# and therefore without this modification git would displayes empty lines
+# instead of the exception output
+if sys.platform == "win32":
+    import msvcrt
+    msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
+
+KALLITHEA_HOOK_VER = '_TMPL_'
+os.environ['KALLITHEA_HOOK_VER'] = KALLITHEA_HOOK_VER
+from kallithea.lib.hooks import handle_git_pre_receive as _handler
 
 
 def main():
-    if kallithea is None:
-        # exit with success if we cannot import kallithea !!
-        # this allows simply push to this repo even without
-        # kallithea
-        sys.exit(0)
-
     repo_path = os.path.abspath('.')
     push_data = sys.stdin.readlines()
     # os.environ is modified here by a subprocess call that
--- a/kallithea/config/rcextensions/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/config/rcextensions/__init__.py	Fri Nov 18 01:11:13 2016 +0100
@@ -41,7 +41,7 @@
      :param created_on:
      :param enable_downloads:
      :param repo_id:
-     :param user_id:
+     :param owner_id:
      :param enable_statistics:
      :param clone_uri:
      :param fork_id:
@@ -123,7 +123,7 @@
      :param created_on:
      :param enable_downloads:
      :param repo_id:
-     :param user_id:
+     :param owner_id:
      :param enable_statistics:
      :param clone_uri:
      :param fork_id:
--- a/kallithea/config/routing.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/config/routing.py	Fri Nov 18 01:11:13 2016 +0100
@@ -19,6 +19,7 @@
 refer to the routes manual at http://routes.groovie.org/docs/
 """
 
+from pylons import request
 from routes import Mapper
 
 # prefix for non repository related links needs to be prefixed with `/`
@@ -119,12 +120,11 @@
                   action="index", conditions=dict(method=["GET"]))
         m.connect("new_repo", "/create_repository",
                   action="create_repository", conditions=dict(method=["GET"]))
-        m.connect("put_repo", "/repos/{repo_name:.*?}",
-                  action="update", conditions=dict(method=["PUT"],
+        m.connect("update_repo", "/repos/{repo_name:.*?}",
+                  action="update", conditions=dict(method=["POST"],
                   function=check_repo))
-        m.connect("delete_repo", "/repos/{repo_name:.*?}",
-                  action="delete", conditions=dict(method=["DELETE"],
-                  ))
+        m.connect("delete_repo", "/repos/{repo_name:.*?}/delete",
+                  action="delete", conditions=dict(method=["POST"]))
 
     #ADMIN REPOSITORY GROUPS ROUTES
     with rmap.submapper(path_prefix=ADMIN_PREFIX,
@@ -136,7 +136,7 @@
         m.connect("new_repos_group", "/repo_groups/new",
                   action="new", conditions=dict(method=["GET"]))
         m.connect("update_repos_group", "/repo_groups/{group_name:.*?}",
-                  action="update", conditions=dict(method=["PUT"],
+                  action="update", conditions=dict(method=["POST"],
                                                    function=check_group))
 
         m.connect("repos_group", "/repo_groups/{group_name:.*?}",
@@ -147,36 +147,30 @@
         m.connect("edit_repo_group", "/repo_groups/{group_name:.*?}/edit",
                   action="edit",
                   conditions=dict(method=["GET"], function=check_group))
-        m.connect("edit_repo_group", "/repo_groups/{group_name:.*?}/edit",
-                  action="edit",
-                  conditions=dict(method=["PUT"], function=check_group))
 
         m.connect("edit_repo_group_advanced", "/repo_groups/{group_name:.*?}/edit/advanced",
                   action="edit_repo_group_advanced",
                   conditions=dict(method=["GET"], function=check_group))
-        m.connect("edit_repo_group_advanced", "/repo_groups/{group_name:.*?}/edit/advanced",
-                  action="edit_repo_group_advanced",
-                  conditions=dict(method=["PUT"], function=check_group))
 
         m.connect("edit_repo_group_perms", "/repo_groups/{group_name:.*?}/edit/permissions",
                   action="edit_repo_group_perms",
                   conditions=dict(method=["GET"], function=check_group))
-        m.connect("edit_repo_group_perms", "/repo_groups/{group_name:.*?}/edit/permissions",
+        m.connect("edit_repo_group_perms_update", "/repo_groups/{group_name:.*?}/edit/permissions",
                   action="update_perms",
-                  conditions=dict(method=["PUT"], function=check_group))
-        m.connect("edit_repo_group_perms", "/repo_groups/{group_name:.*?}/edit/permissions",
+                  conditions=dict(method=["POST"], function=check_group))
+        m.connect("edit_repo_group_perms_delete", "/repo_groups/{group_name:.*?}/edit/permissions/delete",
                   action="delete_perms",
-                  conditions=dict(method=["DELETE"], function=check_group))
+                  conditions=dict(method=["POST"], function=check_group))
 
-        m.connect("delete_repo_group", "/repo_groups/{group_name:.*?}",
-                  action="delete", conditions=dict(method=["DELETE"],
+        m.connect("delete_repo_group", "/repo_groups/{group_name:.*?}/delete",
+                  action="delete", conditions=dict(method=["POST"],
                                                    function=check_group_skip_path))
 
 
     #ADMIN USER ROUTES
     with rmap.submapper(path_prefix=ADMIN_PREFIX,
                         controller='admin/users') as m:
-        m.connect("users", "/users",
+        m.connect("new_user", "/users/new",
                   action="create", conditions=dict(method=["POST"]))
         m.connect("users", "/users",
                   action="index", conditions=dict(method=["GET"]))
@@ -185,45 +179,41 @@
         m.connect("new_user", "/users/new",
                   action="new", conditions=dict(method=["GET"]))
         m.connect("update_user", "/users/{id}",
-                  action="update", conditions=dict(method=["PUT"]))
-        m.connect("delete_user", "/users/{id}",
-                  action="delete", conditions=dict(method=["DELETE"]))
+                  action="update", conditions=dict(method=["POST"]))
+        m.connect("delete_user", "/users/{id}/delete",
+                  action="delete", conditions=dict(method=["POST"]))
         m.connect("edit_user", "/users/{id}/edit",
                   action="edit", conditions=dict(method=["GET"]))
-        m.connect("user", "/users/{id}",
-                  action="show", conditions=dict(method=["GET"]))
 
         #EXTRAS USER ROUTES
         m.connect("edit_user_advanced", "/users/{id}/edit/advanced",
                   action="edit_advanced", conditions=dict(method=["GET"]))
-        m.connect("edit_user_advanced", "/users/{id}/edit/advanced",
-                  action="update_advanced", conditions=dict(method=["PUT"]))
 
         m.connect("edit_user_api_keys", "/users/{id}/edit/api_keys",
                   action="edit_api_keys", conditions=dict(method=["GET"]))
-        m.connect("edit_user_api_keys", "/users/{id}/edit/api_keys",
+        m.connect("edit_user_api_keys_update", "/users/{id}/edit/api_keys",
                   action="add_api_key", conditions=dict(method=["POST"]))
-        m.connect("edit_user_api_keys", "/users/{id}/edit/api_keys",
-                  action="delete_api_key", conditions=dict(method=["DELETE"]))
+        m.connect("edit_user_api_keys_delete", "/users/{id}/edit/api_keys/delete",
+                  action="delete_api_key", conditions=dict(method=["POST"]))
 
         m.connect("edit_user_perms", "/users/{id}/edit/permissions",
                   action="edit_perms", conditions=dict(method=["GET"]))
-        m.connect("edit_user_perms", "/users/{id}/edit/permissions",
-                  action="update_perms", conditions=dict(method=["PUT"]))
+        m.connect("edit_user_perms_update", "/users/{id}/edit/permissions",
+                  action="update_perms", conditions=dict(method=["POST"]))
 
         m.connect("edit_user_emails", "/users/{id}/edit/emails",
                   action="edit_emails", conditions=dict(method=["GET"]))
-        m.connect("edit_user_emails", "/users/{id}/edit/emails",
-                  action="add_email", conditions=dict(method=["PUT"]))
-        m.connect("edit_user_emails", "/users/{id}/edit/emails",
-                  action="delete_email", conditions=dict(method=["DELETE"]))
+        m.connect("edit_user_emails_update", "/users/{id}/edit/emails",
+                  action="add_email", conditions=dict(method=["POST"]))
+        m.connect("edit_user_emails_delete", "/users/{id}/edit/emails/delete",
+                  action="delete_email", conditions=dict(method=["POST"]))
 
         m.connect("edit_user_ips", "/users/{id}/edit/ips",
                   action="edit_ips", conditions=dict(method=["GET"]))
-        m.connect("edit_user_ips", "/users/{id}/edit/ips",
-                  action="add_ip", conditions=dict(method=["PUT"]))
-        m.connect("edit_user_ips", "/users/{id}/edit/ips",
-                  action="delete_ip", conditions=dict(method=["DELETE"]))
+        m.connect("edit_user_ips_update", "/users/{id}/edit/ips",
+                  action="add_ip", conditions=dict(method=["POST"]))
+        m.connect("edit_user_ips_delete", "/users/{id}/edit/ips/delete",
+                  action="delete_ip", conditions=dict(method=["POST"]))
 
     #ADMIN USER GROUPS REST ROUTES
     with rmap.submapper(path_prefix=ADMIN_PREFIX,
@@ -235,28 +225,26 @@
         m.connect("new_users_group", "/user_groups/new",
                   action="new", conditions=dict(method=["GET"]))
         m.connect("update_users_group", "/user_groups/{id}",
-                  action="update", conditions=dict(method=["PUT"]))
-        m.connect("delete_users_group", "/user_groups/{id}",
-                  action="delete", conditions=dict(method=["DELETE"]))
+                  action="update", conditions=dict(method=["POST"]))
+        m.connect("delete_users_group", "/user_groups/{id}/delete",
+                  action="delete", conditions=dict(method=["POST"]))
         m.connect("edit_users_group", "/user_groups/{id}/edit",
                   action="edit", conditions=dict(method=["GET"]),
                   function=check_user_group)
-        m.connect("users_group", "/user_groups/{id}",
-                  action="show", conditions=dict(method=["GET"]))
 
         #EXTRAS USER GROUP ROUTES
         m.connect("edit_user_group_default_perms", "/user_groups/{id}/edit/default_perms",
                   action="edit_default_perms", conditions=dict(method=["GET"]))
-        m.connect("edit_user_group_default_perms", "/user_groups/{id}/edit/default_perms",
-                  action="update_default_perms", conditions=dict(method=["PUT"]))
+        m.connect("edit_user_group_default_perms_update", "/user_groups/{id}/edit/default_perms",
+                  action="update_default_perms", conditions=dict(method=["POST"]))
 
 
         m.connect("edit_user_group_perms", "/user_groups/{id}/edit/perms",
                   action="edit_perms", conditions=dict(method=["GET"]))
-        m.connect("edit_user_group_perms", "/user_groups/{id}/edit/perms",
-                  action="update_perms", conditions=dict(method=["PUT"]))
-        m.connect("edit_user_group_perms", "/user_groups/{id}/edit/perms",
-                  action="delete_perms", conditions=dict(method=["DELETE"]))
+        m.connect("edit_user_group_perms_update", "/user_groups/{id}/edit/perms",
+                  action="update_perms", conditions=dict(method=["POST"]))
+        m.connect("edit_user_group_perms_delete", "/user_groups/{id}/edit/perms/delete",
+                  action="delete_perms", conditions=dict(method=["POST"]))
 
         m.connect("edit_user_group_advanced", "/user_groups/{id}/edit/advanced",
                   action="edit_advanced", conditions=dict(method=["GET"]))
@@ -275,19 +263,19 @@
                   action="permission_globals", conditions=dict(method=["GET"]))
 
         m.connect("admin_permissions_ips", "/permissions/ips",
-                  action="permission_ips", conditions=dict(method=["POST"]))
-        m.connect("admin_permissions_ips", "/permissions/ips",
                   action="permission_ips", conditions=dict(method=["GET"]))
 
         m.connect("admin_permissions_perms", "/permissions/perms",
-                  action="permission_perms", conditions=dict(method=["POST"]))
-        m.connect("admin_permissions_perms", "/permissions/perms",
                   action="permission_perms", conditions=dict(method=["GET"]))
 
 
-    #ADMIN DEFAULTS REST ROUTES
-    rmap.resource('default', 'defaults',
-                  controller='admin/defaults', path_prefix=ADMIN_PREFIX)
+    #ADMIN DEFAULTS ROUTES
+    with rmap.submapper(path_prefix=ADMIN_PREFIX,
+                        controller='admin/defaults') as m:
+        m.connect('defaults', 'defaults',
+                  action="index")
+        m.connect('defaults_update', 'defaults/{id}/update',
+                  action="update", conditions=dict(method=["POST"]))
 
     #ADMIN AUTH SETTINGS
     rmap.connect('auth_settings', '%s/auth' % ADMIN_PREFIX,
@@ -326,8 +314,8 @@
 
         m.connect("admin_settings_hooks", "/settings/hooks",
                   action="settings_hooks", conditions=dict(method=["POST"]))
-        m.connect("admin_settings_hooks", "/settings/hooks",
-                  action="settings_hooks", conditions=dict(method=["DELETE"]))
+        m.connect("admin_settings_hooks_delete", "/settings/hooks/delete",
+                  action="settings_hooks", conditions=dict(method=["POST"]))
         m.connect("admin_settings_hooks", "/settings/hooks",
                   action="settings_hooks", conditions=dict(method=["GET"]))
 
@@ -370,40 +358,29 @@
                   action="my_account_emails", conditions=dict(method=["GET"]))
         m.connect("my_account_emails", "/my_account/emails",
                   action="my_account_emails_add", conditions=dict(method=["POST"]))
-        m.connect("my_account_emails", "/my_account/emails",
-                  action="my_account_emails_delete", conditions=dict(method=["DELETE"]))
+        m.connect("my_account_emails_delete", "/my_account/emails/delete",
+                  action="my_account_emails_delete", conditions=dict(method=["POST"]))
 
         m.connect("my_account_api_keys", "/my_account/api_keys",
                   action="my_account_api_keys", conditions=dict(method=["GET"]))
         m.connect("my_account_api_keys", "/my_account/api_keys",
                   action="my_account_api_keys_add", conditions=dict(method=["POST"]))
-        m.connect("my_account_api_keys", "/my_account/api_keys",
-                  action="my_account_api_keys_delete", conditions=dict(method=["DELETE"]))
+        m.connect("my_account_api_keys_delete", "/my_account/api_keys/delete",
+                  action="my_account_api_keys_delete", conditions=dict(method=["POST"]))
 
     #NOTIFICATION REST ROUTES
     with rmap.submapper(path_prefix=ADMIN_PREFIX,
                         controller='admin/notifications') as m:
         m.connect("notifications", "/notifications",
-                  action="create", conditions=dict(method=["POST"]))
-        m.connect("notifications", "/notifications",
                   action="index", conditions=dict(method=["GET"]))
         m.connect("notifications_mark_all_read", "/notifications/mark_all_read",
                   action="mark_all_read", conditions=dict(method=["GET"]))
         m.connect("formatted_notifications", "/notifications.{format}",
                   action="index", conditions=dict(method=["GET"]))
-        m.connect("new_notification", "/notifications/new",
-                  action="new", conditions=dict(method=["GET"]))
-        m.connect("formatted_new_notification", "/notifications/new.{format}",
-                  action="new", conditions=dict(method=["GET"]))
-        m.connect("/notifications/{notification_id}",
-                  action="update", conditions=dict(method=["PUT"]))
-        m.connect("/notifications/{notification_id}",
-                  action="delete", conditions=dict(method=["DELETE"]))
-        m.connect("edit_notification", "/notifications/{notification_id}/edit",
-                  action="edit", conditions=dict(method=["GET"]))
-        m.connect("formatted_edit_notification",
-                  "/notifications/{notification_id}.{format}/edit",
-                  action="edit", conditions=dict(method=["GET"]))
+        m.connect("notification_update", "/notifications/{notification_id}/update",
+                  action="update", conditions=dict(method=["POST"]))
+        m.connect("notification_delete", "/notifications/{notification_id}/delete",
+                  action="delete", conditions=dict(method=["POST"]))
         m.connect("notification", "/notifications/{notification_id}",
                   action="show", conditions=dict(method=["GET"]))
         m.connect("formatted_notification", "/notifications/{notification_id}.{format}",
@@ -420,10 +397,8 @@
                   action="new", conditions=dict(method=["GET"]))
 
 
-        m.connect("/gists/{gist_id}",
-                  action="update", conditions=dict(method=["PUT"]))
-        m.connect("/gists/{gist_id}",
-                  action="delete", conditions=dict(method=["DELETE"]))
+        m.connect("gist_delete", "/gists/{gist_id}/delete",
+                  action="delete", conditions=dict(method=["POST"]))
         m.connect("edit_gist", "/gists/{gist_id}/edit",
                   action="edit", conditions=dict(method=["GET", "POST"]))
         m.connect("edit_gist_check_revision", "/gists/{gist_id}/edit/check_revision",
@@ -543,8 +518,6 @@
                 controller='summary', action='repo_size',
                 conditions=dict(function=check_repo))
 
-    rmap.connect('branch_tag_switcher', '/{repo_name:.*?}/branches-tags',
-                 controller='home', action='branch_tag_switcher')
     rmap.connect('repo_refs_data', '/{repo_name:.*?}/refs-data',
                  controller='home', action='repo_refs_data')
 
@@ -568,20 +541,20 @@
                  conditions=dict(method=["GET"], function=check_repo))
     rmap.connect("edit_repo_perms_update", "/{repo_name:.*?}/settings/permissions",
                  controller='admin/repos', action="edit_permissions_update",
-                 conditions=dict(method=["PUT"], function=check_repo))
-    rmap.connect("edit_repo_perms_revoke", "/{repo_name:.*?}/settings/permissions",
+                 conditions=dict(method=["POST"], function=check_repo))
+    rmap.connect("edit_repo_perms_revoke", "/{repo_name:.*?}/settings/permissions/delete",
                  controller='admin/repos', action="edit_permissions_revoke",
-                 conditions=dict(method=["DELETE"], function=check_repo))
+                 conditions=dict(method=["POST"], function=check_repo))
 
     rmap.connect("edit_repo_fields", "/{repo_name:.*?}/settings/fields",
                  controller='admin/repos', action="edit_fields",
                  conditions=dict(method=["GET"], function=check_repo))
     rmap.connect('create_repo_fields', "/{repo_name:.*?}/settings/fields/new",
                  controller='admin/repos', action="create_repo_field",
-                 conditions=dict(method=["PUT"], function=check_repo))
-    rmap.connect('delete_repo_fields', "/{repo_name:.*?}/settings/fields/{field_id}",
+                 conditions=dict(method=["POST"], function=check_repo))
+    rmap.connect('delete_repo_fields', "/{repo_name:.*?}/settings/fields/{field_id}/delete",
                  controller='admin/repos', action="delete_repo_field",
-                 conditions=dict(method=["DELETE"], function=check_repo))
+                 conditions=dict(method=["POST"], function=check_repo))
 
 
     rmap.connect("edit_repo_advanced", "/{repo_name:.*?}/settings/advanced",
@@ -590,41 +563,41 @@
 
     rmap.connect("edit_repo_advanced_locking", "/{repo_name:.*?}/settings/advanced/locking",
                  controller='admin/repos', action="edit_advanced_locking",
-                 conditions=dict(method=["PUT"], function=check_repo))
+                 conditions=dict(method=["POST"], function=check_repo))
     rmap.connect('toggle_locking', "/{repo_name:.*?}/settings/advanced/locking_toggle",
                  controller='admin/repos', action="toggle_locking",
                  conditions=dict(method=["GET"], function=check_repo))
 
     rmap.connect("edit_repo_advanced_journal", "/{repo_name:.*?}/settings/advanced/journal",
                  controller='admin/repos', action="edit_advanced_journal",
-                 conditions=dict(method=["PUT"], function=check_repo))
+                 conditions=dict(method=["POST"], function=check_repo))
 
     rmap.connect("edit_repo_advanced_fork", "/{repo_name:.*?}/settings/advanced/fork",
                  controller='admin/repos', action="edit_advanced_fork",
-                 conditions=dict(method=["PUT"], function=check_repo))
+                 conditions=dict(method=["POST"], function=check_repo))
 
 
     rmap.connect("edit_repo_caches", "/{repo_name:.*?}/settings/caches",
                  controller='admin/repos', action="edit_caches",
                  conditions=dict(method=["GET"], function=check_repo))
-    rmap.connect("edit_repo_caches", "/{repo_name:.*?}/settings/caches",
+    rmap.connect("update_repo_caches", "/{repo_name:.*?}/settings/caches",
                  controller='admin/repos', action="edit_caches",
-                 conditions=dict(method=["PUT"], function=check_repo))
+                 conditions=dict(method=["POST"], function=check_repo))
 
 
     rmap.connect("edit_repo_remote", "/{repo_name:.*?}/settings/remote",
                  controller='admin/repos', action="edit_remote",
                  conditions=dict(method=["GET"], function=check_repo))
-    rmap.connect("edit_repo_remote", "/{repo_name:.*?}/settings/remote",
+    rmap.connect("edit_repo_remote_update", "/{repo_name:.*?}/settings/remote",
                  controller='admin/repos', action="edit_remote",
-                 conditions=dict(method=["PUT"], function=check_repo))
+                 conditions=dict(method=["POST"], function=check_repo))
 
     rmap.connect("edit_repo_statistics", "/{repo_name:.*?}/settings/statistics",
                  controller='admin/repos', action="edit_statistics",
                  conditions=dict(method=["GET"], function=check_repo))
-    rmap.connect("edit_repo_statistics", "/{repo_name:.*?}/settings/statistics",
+    rmap.connect("edit_repo_statistics_update", "/{repo_name:.*?}/settings/statistics",
                  controller='admin/repos', action="edit_statistics",
-                 conditions=dict(method=["PUT"], function=check_repo))
+                 conditions=dict(method=["POST"], function=check_repo))
 
     #still working url for backward compat.
     rmap.connect('raw_changeset_home_depraced',
@@ -653,16 +626,11 @@
                 controller='changeset', revision='tip', action='comment',
                 conditions=dict(function=check_repo))
 
-    rmap.connect('changeset_comment_preview',
-                 '/{repo_name:.*?}/changeset-comment-preview',
-                controller='changeset', action='preview_comment',
+    rmap.connect('changeset_comment_delete',
+                 '/{repo_name:.*?}/changeset-comment/{comment_id}/delete',
+                controller='changeset', action='delete_comment',
                 conditions=dict(function=check_repo, method=["POST"]))
 
-    rmap.connect('changeset_comment_delete',
-                 '/{repo_name:.*?}/changeset-comment-delete/{comment_id}',
-                controller='changeset', action='delete_comment',
-                conditions=dict(function=check_repo, method=["DELETE"]))
-
     rmap.connect('changeset_info', '/changeset_info/{repo_name:.*?}/{revision}',
                  controller='changeset', action='changeset_info')
 
@@ -706,10 +674,10 @@
                  action='post', conditions=dict(function=check_repo,
                                                 method=["POST"]))
     rmap.connect('pullrequest_delete',
-                 '/{repo_name:.*?}/pull-request/{pull_request_id}',
+                 '/{repo_name:.*?}/pull-request/{pull_request_id}/delete',
                  controller='pullrequests',
                  action='delete', conditions=dict(function=check_repo,
-                                                method=["DELETE"]))
+                                                  method=["POST"]))
 
     rmap.connect('pullrequest_show_all',
                  '/{repo_name:.*?}/pull-request',
@@ -731,20 +699,11 @@
     rmap.connect('pullrequest_comment_delete',
                  '/{repo_name:.*?}/pull-request-comment/{comment_id}/delete',
                 controller='pullrequests', action='delete_comment',
-                conditions=dict(function=check_repo, method=["DELETE"]))
+                conditions=dict(function=check_repo, method=["POST"]))
 
     rmap.connect('summary_home_summary', '/{repo_name:.*?}/summary',
                 controller='summary', conditions=dict(function=check_repo))
 
-    rmap.connect('branches_home', '/{repo_name:.*?}/branches',
-                controller='branches', conditions=dict(function=check_repo))
-
-    rmap.connect('tags_home', '/{repo_name:.*?}/tags',
-                controller='tags', conditions=dict(function=check_repo))
-
-    rmap.connect('bookmarks_home', '/{repo_name:.*?}/bookmarks',
-                controller='bookmarks', conditions=dict(function=check_repo))
-
     rmap.connect('changelog_home', '/{repo_name:.*?}/changelog',
                 controller='changelog', conditions=dict(function=check_repo))
 
@@ -842,3 +801,27 @@
                  conditions=dict(function=check_repo))
 
     return rmap
+
+
+class UrlGenerator(object):
+    """Emulate pylons.url in providing a wrapper around routes.url
+
+    This code was added during migration from Pylons to Turbogears2. Pylons
+    already provided a wrapper like this, but Turbogears2 does not.
+
+    When the routing of Kallithea is changed to use less Routes and more
+    Turbogears2-style routing, this class may disappear or change.
+
+    url() (the __call__ method) returns the URL based on a route name and
+    arguments.
+    url.current() returns the URL of the current page with arguments applied.
+
+    Refer to documentation of Routes for details:
+    https://routes.readthedocs.io/en/latest/generating.html#generation
+    """
+    def __call__(self, *args, **kwargs):
+        return request.environ['routes.url'](*args, **kwargs)
+    def current(self, *args, **kwargs):
+        return request.environ['routes.url'].current(*args, **kwargs)
+
+url = UrlGenerator()
--- a/kallithea/controllers/admin/admin.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/admin/admin.py	Fri Nov 18 01:11:13 2016 +0100
@@ -28,19 +28,20 @@
 
 import logging
 
-from pylons import request, tmpl_context as c, url
+from pylons import request, tmpl_context as c
 from sqlalchemy.orm import joinedload
 from whoosh.qparser.default import QueryParser
 from whoosh.qparser.dateparse import DateParserPlugin
 from whoosh import query
 from sqlalchemy.sql.expression import or_, and_, func
 
+from kallithea.config.routing import url
 from kallithea.model.db import UserLog
-from kallithea.lib.auth import LoginRequired, HasPermissionAllDecorator
+from kallithea.lib.auth import LoginRequired, HasPermissionAnyDecorator
 from kallithea.lib.base import BaseController, render
 from kallithea.lib.utils2 import safe_int, remove_prefix, remove_suffix
 from kallithea.lib.indexers import JOURNAL_SCHEMA
-from kallithea.lib.helpers import Page
+from kallithea.lib.page import Page
 
 
 log = logging.getLogger(__name__)
@@ -123,10 +124,10 @@
     def __before__(self):
         super(AdminController, self).__before__()
 
-    @HasPermissionAllDecorator('hg.admin')
+    @HasPermissionAnyDecorator('hg.admin')
     def index(self):
-        users_log = UserLog.query()\
-                .options(joinedload(UserLog.user))\
+        users_log = UserLog.query() \
+                .options(joinedload(UserLog.user)) \
                 .options(joinedload(UserLog.repository))
 
         #FILTERING
@@ -135,7 +136,7 @@
 
         users_log = users_log.order_by(UserLog.action_date.desc())
 
-        p = safe_int(request.GET.get('page', 1), 1)
+        p = safe_int(request.GET.get('page'), 1)
 
         def url_generator(**kw):
             return url.current(filter=c.search_term, **kw)
--- a/kallithea/controllers/admin/auth_settings.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/admin/auth_settings.py	Fri Nov 18 01:11:13 2016 +0100
@@ -27,14 +27,15 @@
 import formencode.htmlfill
 import traceback
 
-from pylons import request, tmpl_context as c, url
-from pylons.controllers.util import redirect
+from pylons import request, tmpl_context as c
 from pylons.i18n.translation import _
+from webob.exc import HTTPFound
 
+from kallithea.config.routing import url
 from kallithea.lib import helpers as h
 from kallithea.lib.compat import formatted_json
 from kallithea.lib.base import BaseController, render
-from kallithea.lib.auth import LoginRequired, HasPermissionAllDecorator
+from kallithea.lib.auth import LoginRequired, HasPermissionAnyDecorator
 from kallithea.lib import auth_modules
 from kallithea.model.forms import AuthSettingsForm
 from kallithea.model.db import Setting
@@ -46,7 +47,7 @@
 class AuthSettingsController(BaseController):
 
     @LoginRequired()
-    @HasPermissionAllDecorator('hg.admin')
+    @HasPermissionAnyDecorator('hg.admin')
     def __before__(self):
         super(AuthSettingsController, self).__before__()
 
@@ -130,7 +131,6 @@
                     v = ','.join(v)
                 log.debug("%s = %s", k, str(v))
                 setting = Setting.create_or_update(k, v)
-                Session().add(setting)
             Session().commit()
             h.flash(_('Auth settings updated successfully'),
                        category='success')
@@ -146,4 +146,4 @@
             h.flash(_('error occurred during update of auth settings'),
                     category='error')
 
-        return redirect(url('auth_home'))
+        raise HTTPFound(location=url('auth_home'))
--- a/kallithea/controllers/admin/defaults.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/admin/defaults.py	Fri Nov 18 01:11:13 2016 +0100
@@ -30,12 +30,13 @@
 import formencode
 from formencode import htmlfill
 
-from pylons import request, tmpl_context as c, url
-from pylons.controllers.util import redirect
+from pylons import request, tmpl_context as c
 from pylons.i18n.translation import _
+from webob.exc import HTTPFound
 
+from kallithea.config.routing import url
 from kallithea.lib import helpers as h
-from kallithea.lib.auth import LoginRequired, HasPermissionAllDecorator
+from kallithea.lib.auth import LoginRequired, HasPermissionAnyDecorator
 from kallithea.lib.base import BaseController, render
 from kallithea.model.forms import DefaultsForm
 from kallithea.model.meta import Session
@@ -46,19 +47,13 @@
 
 
 class DefaultsController(BaseController):
-    """REST Controller styled on the Atom Publishing Protocol"""
-    # To properly map this controller, ensure your config/routing.py
-    # file has a resource setup:
-    #     map.resource('default', 'defaults')
 
     @LoginRequired()
-    @HasPermissionAllDecorator('hg.admin')
+    @HasPermissionAnyDecorator('hg.admin')
     def __before__(self):
         super(DefaultsController, self).__before__()
 
     def index(self, format='html'):
-        """GET /defaults: All items in the collection"""
-        # url('defaults')
         c.backends = BACKENDS.keys()
         defaults = Setting.get_default_repo_settings()
 
@@ -69,30 +64,13 @@
             force_defaults=False
         )
 
-    def create(self):
-        """POST /defaults: Create a new item"""
-        # url('defaults')
-
-    def new(self, format='html'):
-        """GET /defaults/new: Form to create a new item"""
-        # url('new_default')
-
     def update(self, id):
-        """PUT /defaults/id: Update an existing item"""
-        # Forms posted to this method should contain a hidden field:
-        #    <input type="hidden" name="_method" value="PUT" />
-        # Or using helpers:
-        #    h.form(url('default', id=ID),
-        #           method='put')
-        # url('default', id=ID)
-
         _form = DefaultsForm()()
 
         try:
             form_result = _form.to_python(dict(request.POST))
             for k, v in form_result.iteritems():
                 setting = Setting.create_or_update(k, v)
-                Session().add(setting)
             Session().commit()
             h.flash(_('Default settings updated successfully'),
                     category='success')
@@ -112,21 +90,4 @@
             h.flash(_('Error occurred during update of defaults'),
                     category='error')
 
-        return redirect(url('defaults'))
-
-    def delete(self, id):
-        """DELETE /defaults/id: Delete an existing item"""
-        # Forms posted to this method should contain a hidden field:
-        #    <input type="hidden" name="_method" value="DELETE" />
-        # Or using helpers:
-        #    h.form(url('default', id=ID),
-        #           method='delete')
-        # url('default', id=ID)
-
-    def show(self, id, format='html'):
-        """GET /defaults/id: Show a specific item"""
-        # url('default', id=ID)
-
-    def edit(self, id, format='html'):
-        """GET /defaults/id/edit: Form to edit an existing item"""
-        # url('edit_default', id=ID)
+        raise HTTPFound(location=url('defaults'))
--- a/kallithea/controllers/admin/gists.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/admin/gists.py	Fri Nov 18 01:11:13 2016 +0100
@@ -30,10 +30,11 @@
 import traceback
 import formencode.htmlfill
 
-from pylons import request, response, tmpl_context as c, url
-from pylons.controllers.util import redirect
+from pylons import request, response, tmpl_context as c
 from pylons.i18n.translation import _
+from webob.exc import HTTPFound, HTTPNotFound, HTTPForbidden
 
+from kallithea.config.routing import url
 from kallithea.model.forms import GistForm
 from kallithea.model.gist import GistModel
 from kallithea.model.meta import Session
@@ -43,8 +44,7 @@
 from kallithea.lib.auth import LoginRequired, NotAnonymous
 from kallithea.lib.utils import jsonify
 from kallithea.lib.utils2 import safe_int, safe_unicode, time_to_datetime
-from kallithea.lib.helpers import Page
-from webob.exc import HTTPNotFound, HTTPForbidden
+from kallithea.lib.page import Page
 from sqlalchemy.sql.expression import or_
 from kallithea.lib.vcs.exceptions import VCSError, NodeNotChangedError
 
@@ -68,45 +68,41 @@
 
     @LoginRequired()
     def index(self):
-        """GET /admin/gists: All items in the collection"""
-        # url('gists')
-        not_default_user = c.authuser.username != User.DEFAULT_USER
+        not_default_user = not c.authuser.is_default_user
         c.show_private = request.GET.get('private') and not_default_user
         c.show_public = request.GET.get('public') and not_default_user
 
-        gists = Gist().query()\
-            .filter(or_(Gist.gist_expires == -1, Gist.gist_expires >= time.time()))\
+        gists = Gist().query() \
+            .filter(or_(Gist.gist_expires == -1, Gist.gist_expires >= time.time())) \
             .order_by(Gist.created_on.desc())
 
         # MY private
         if c.show_private and not c.show_public:
-            gists = gists.filter(Gist.gist_type == Gist.GIST_PRIVATE)\
-                             .filter(Gist.gist_owner == c.authuser.user_id)
+            gists = gists.filter(Gist.gist_type == Gist.GIST_PRIVATE) \
+                             .filter(Gist.owner_id == c.authuser.user_id)
         # MY public
         elif c.show_public and not c.show_private:
-            gists = gists.filter(Gist.gist_type == Gist.GIST_PUBLIC)\
-                             .filter(Gist.gist_owner == c.authuser.user_id)
+            gists = gists.filter(Gist.gist_type == Gist.GIST_PUBLIC) \
+                             .filter(Gist.owner_id == c.authuser.user_id)
 
         # MY public+private
         elif c.show_private and c.show_public:
             gists = gists.filter(or_(Gist.gist_type == Gist.GIST_PUBLIC,
-                                     Gist.gist_type == Gist.GIST_PRIVATE))\
-                             .filter(Gist.gist_owner == c.authuser.user_id)
+                                     Gist.gist_type == Gist.GIST_PRIVATE)) \
+                             .filter(Gist.owner_id == c.authuser.user_id)
 
         # default show ALL public gists
         if not c.show_public and not c.show_private:
             gists = gists.filter(Gist.gist_type == Gist.GIST_PUBLIC)
 
         c.gists = gists
-        p = safe_int(request.GET.get('page', 1), 1)
+        p = safe_int(request.GET.get('page'), 1)
         c.gists_pager = Page(c.gists, page=p, items_per_page=10)
         return render('admin/gists/index.html')
 
     @LoginRequired()
     @NotAnonymous()
     def create(self):
-        """POST /admin/gists: Create a new item"""
-        # url('gists')
         self.__load_defaults()
         gist_form = GistForm([x[0] for x in c.lifetime_values])()
         try:
@@ -144,40 +140,20 @@
         except Exception as e:
             log.error(traceback.format_exc())
             h.flash(_('Error occurred during gist creation'), category='error')
-            return redirect(url('new_gist'))
-        return redirect(url('gist', gist_id=new_gist_id))
+            raise HTTPFound(location=url('new_gist'))
+        raise HTTPFound(location=url('gist', gist_id=new_gist_id))
 
     @LoginRequired()
     @NotAnonymous()
     def new(self, format='html'):
-        """GET /admin/gists/new: Form to create a new item"""
-        # url('new_gist')
         self.__load_defaults()
         return render('admin/gists/new.html')
 
     @LoginRequired()
     @NotAnonymous()
-    def update(self, gist_id):
-        """PUT /admin/gists/gist_id: Update an existing item"""
-        # Forms posted to this method should contain a hidden field:
-        #    <input type="hidden" name="_method" value="PUT" />
-        # Or using helpers:
-        #    h.form(url('gist', gist_id=ID),
-        #           method='put')
-        # url('gist', gist_id=ID)
-
-    @LoginRequired()
-    @NotAnonymous()
     def delete(self, gist_id):
-        """DELETE /admin/gists/gist_id: Delete an existing item"""
-        # Forms posted to this method should contain a hidden field:
-        #    <input type="hidden" name="_method" value="DELETE" />
-        # Or using helpers:
-        #    h.form(url('gist', gist_id=ID),
-        #           method='delete')
-        # url('gist', gist_id=ID)
         gist = GistModel().get_gist(gist_id)
-        owner = gist.gist_owner == c.authuser.user_id
+        owner = gist.owner_id == c.authuser.user_id
         if h.HasPermissionAny('hg.admin')() or owner:
             GistModel().delete(gist)
             Session().commit()
@@ -185,12 +161,10 @@
         else:
             raise HTTPForbidden()
 
-        return redirect(url('gists'))
+        raise HTTPFound(location=url('gists'))
 
     @LoginRequired()
     def show(self, gist_id, revision='tip', format='html', f_path=None):
-        """GET /admin/gists/gist_id: Show a specific item"""
-        # url('gist', gist_id=ID)
         c.gist = Gist.get_or_404(gist_id)
 
         #check if this gist is not expired
@@ -214,8 +188,6 @@
     @LoginRequired()
     @NotAnonymous()
     def edit(self, gist_id, format='html'):
-        """GET /admin/gists/gist_id/edit: Form to edit an existing item"""
-        # url('edit_gist', gist_id=ID)
         c.gist = Gist.get_or_404(gist_id)
 
         #check if this gist is not expired
@@ -270,7 +242,7 @@
                 h.flash(_('Error occurred during update of gist %s') % gist_id,
                         category='error')
 
-            return redirect(url('gist', gist_id=gist_id))
+            raise HTTPFound(location=url('gist', gist_id=gist_id))
 
         return rendered
 
--- a/kallithea/controllers/admin/my_account.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/admin/my_account.py	Fri Nov 18 01:11:13 2016 +0100
@@ -31,11 +31,11 @@
 
 from sqlalchemy import func
 from formencode import htmlfill
-from pylons import request, tmpl_context as c, url
-from pylons.controllers.util import redirect
+from pylons import request, tmpl_context as c
 from pylons.i18n.translation import _
+from webob.exc import HTTPFound
 
-from kallithea import EXTERN_TYPE_INTERNAL
+from kallithea.config.routing import url
 from kallithea.lib import helpers as h
 from kallithea.lib import auth_modules
 from kallithea.lib.auth import LoginRequired, NotAnonymous, AuthUser
@@ -69,22 +69,20 @@
         if c.user.username == User.DEFAULT_USER:
             h.flash(_("You can't edit this user since it's"
                       " crucial for entire application"), category='warning')
-            return redirect(url('users'))
-        c.EXTERN_TYPE_INTERNAL = EXTERN_TYPE_INTERNAL
+            raise HTTPFound(location=url('users'))
 
     def _load_my_repos_data(self, watched=False):
         if watched:
             admin = False
-            repos_list = [x.follows_repository for x in
-                          Session().query(UserFollowing).filter(
-                              UserFollowing.user_id ==
-                              self.authuser.user_id).all()]
+            repos_list = Session().query(Repository) \
+                         .join(UserFollowing) \
+                         .filter(UserFollowing.user_id ==
+                                 self.authuser.user_id).all()
         else:
             admin = True
-            repos_list = Session().query(Repository)\
-                         .filter(Repository.user_id ==
-                                 self.authuser.user_id)\
-                         .order_by(func.lower(Repository.repo_name)).all()
+            repos_list = Session().query(Repository) \
+                         .filter(Repository.owner_id ==
+                                 self.authuser.user_id).all()
 
         repos_data = RepoModel().get_repos_as_dict(repos_list=repos_list,
                                                    admin=admin)
@@ -92,10 +90,6 @@
         return json.dumps(repos_data)
 
     def my_account(self):
-        """
-        GET /_admin/my_account Displays info about my account
-        """
-        # url('my_account')
         c.active = 'profile'
         self.__load_data()
         c.perm_user = AuthUser(user_id=self.authuser.user_id)
@@ -144,7 +138,7 @@
                 h.flash(_('Error occurred during update of user %s') \
                         % form_result.get('username'), category='error')
         if update:
-            return redirect('my_account')
+            raise HTTPFound(location='my_account')
         return htmlfill.render(
             render('admin/my_account/my_account.html'),
             defaults=defaults,
@@ -207,7 +201,7 @@
         c.active = 'emails'
         self.__load_data()
 
-        c.user_email_map = UserEmailMap.query()\
+        c.user_email_map = UserEmailMap.query() \
             .filter(UserEmailMap.user == c.user).all()
         return render('admin/my_account/my_account.html')
 
@@ -225,7 +219,7 @@
             log.error(traceback.format_exc())
             h.flash(_('An error occurred during email saving'),
                     category='error')
-        return redirect(url('my_account_emails'))
+        raise HTTPFound(location=url('my_account_emails'))
 
     def my_account_emails_delete(self):
         email_id = request.POST.get('del_email_id')
@@ -233,7 +227,7 @@
         user_model.delete_extra_email(self.authuser.user_id, email_id)
         Session().commit()
         h.flash(_("Removed email from user"), category='success')
-        return redirect(url('my_account_emails'))
+        raise HTTPFound(location=url('my_account_emails'))
 
     def my_account_api_keys(self):
         c.active = 'api_keys'
@@ -257,21 +251,18 @@
         ApiKeyModel().create(self.authuser.user_id, description, lifetime)
         Session().commit()
         h.flash(_("API key successfully created"), category='success')
-        return redirect(url('my_account_api_keys'))
+        raise HTTPFound(location=url('my_account_api_keys'))
 
     def my_account_api_keys_delete(self):
         api_key = request.POST.get('del_api_key')
-        user_id = self.authuser.user_id
         if request.POST.get('del_api_key_builtin'):
-            user = User.get(user_id)
-            if user is not None:
-                user.api_key = generate_api_key()
-                Session().add(user)
-                Session().commit()
-                h.flash(_("API key successfully reset"), category='success')
+            user = User.get(self.authuser.user_id)
+            user.api_key = generate_api_key()
+            Session().commit()
+            h.flash(_("API key successfully reset"), category='success')
         elif api_key:
             ApiKeyModel().delete(api_key, self.authuser.user_id)
             Session().commit()
             h.flash(_("API key successfully deleted"), category='success')
 
-        return redirect(url('my_account_api_keys'))
+        raise HTTPFound(location=url('my_account_api_keys'))
--- a/kallithea/controllers/admin/notifications.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/admin/notifications.py	Fri Nov 18 01:11:13 2016 +0100
@@ -30,8 +30,7 @@
 
 from pylons import request
 from pylons import tmpl_context as c
-from pylons.controllers.util import abort
-from webob.exc import HTTPBadRequest
+from webob.exc import HTTPBadRequest, HTTPForbidden
 
 from kallithea.model.db import Notification
 from kallithea.model.notification import NotificationModel
@@ -39,7 +38,7 @@
 from kallithea.lib.auth import LoginRequired, NotAnonymous
 from kallithea.lib.base import BaseController, render
 from kallithea.lib import helpers as h
-from kallithea.lib.helpers import Page
+from kallithea.lib.page import Page
 from kallithea.lib.utils2 import safe_int
 
 
@@ -59,13 +58,11 @@
         super(NotificationsController, self).__before__()
 
     def index(self, format='html'):
-        """GET /_admin/notifications: All items in the collection"""
-        # url('notifications')
         c.user = self.authuser
-        notif = NotificationModel().get_for_user(self.authuser.user_id,
+        notif = NotificationModel().query_for_user(self.authuser.user_id,
                                             filter_=request.GET.getall('type'))
 
-        p = safe_int(request.GET.get('page', 1), 1)
+        p = safe_int(request.GET.get('page'), 1)
         c.notifications = Page(notif, page=p, items_per_page=10)
         c.pull_request_type = Notification.TYPE_PULL_REQUEST
         c.comment_type = [Notification.TYPE_CHANGESET_COMMENT,
@@ -88,30 +85,15 @@
                                       filter_=request.GET.getall('type'))
             Session().commit()
             c.user = self.authuser
-            notif = nm.get_for_user(self.authuser.user_id,
-                                    filter_=request.GET.getall('type'))
+            notif = nm.query_for_user(self.authuser.user_id,
+                                      filter_=request.GET.getall('type'))
             c.notifications = Page(notif, page=1, items_per_page=10)
             return render('admin/notifications/notifications_data.html')
 
-    def create(self):
-        """POST /_admin/notifications: Create a new item"""
-        # url('notifications')
-
-    def new(self, format='html'):
-        """GET /_admin/notifications/new: Form to create a new item"""
-        # url('new_notification')
-
     def update(self, notification_id):
-        """PUT /_admin/notifications/id: Update an existing item"""
-        # Forms posted to this method should contain a hidden field:
-        #    <input type="hidden" name="_method" value="PUT" />
-        # Or using helpers:
-        #    h.form(url('notification', notification_id=ID),
-        #           method='put')
-        # url('notification', notification_id=ID)
         try:
             no = Notification.get(notification_id)
-            owner = all(un.user.user_id == c.authuser.user_id
+            owner = all(un.user_id == c.authuser.user_id
                         for un in no.notifications_to_users)
             if h.HasPermissionAny('hg.admin')() or owner:
                 # deletes only notification2user
@@ -124,16 +106,9 @@
         raise HTTPBadRequest()
 
     def delete(self, notification_id):
-        """DELETE /_admin/notifications/id: Delete an existing item"""
-        # Forms posted to this method should contain a hidden field:
-        #    <input type="hidden" name="_method" value="DELETE" />
-        # Or using helpers:
-        #    h.form(url('notification', notification_id=ID),
-        #           method='delete')
-        # url('notification', notification_id=ID)
         try:
             no = Notification.get(notification_id)
-            owner = any(un.user.user_id == c.authuser.user_id
+            owner = any(un.user_id == c.authuser.user_id
                         for un in no.notifications_to_users)
             if h.HasPermissionAny('hg.admin')() or owner:
                 # deletes only notification2user
@@ -146,30 +121,20 @@
         raise HTTPBadRequest()
 
     def show(self, notification_id, format='html'):
-        """GET /_admin/notifications/id: Show a specific item"""
-        # url('notification', notification_id=ID)
-        c.user = self.authuser
-        no = Notification.get(notification_id)
+        notification = Notification.get_or_404(notification_id)
 
-        owner = any(un.user.user_id == c.authuser.user_id
-                    for un in no.notifications_to_users)
-        repo_admin = h.HasRepoPermissionAny('repository.admin')
-        if no and (h.HasPermissionAny('hg.admin')() or repo_admin or owner):
-            unotification = NotificationModel()\
-                            .get_user_notification(c.user.user_id, no)
+        unotification = NotificationModel() \
+            .get_user_notification(self.authuser.user_id, notification)
 
-            # if this association to user is not valid, we don't want to show
-            # this message
-            if unotification is not None:
-                if not unotification.read:
-                    unotification.mark_as_read()
-                    Session().commit()
-                c.notification = no
+        # if this association to user is not valid, we don't want to show
+        # this message
+        if unotification is None:
+            raise HTTPForbidden()
 
-                return render('admin/notifications/show_notification.html')
-
-        return abort(403)
+        if not unotification.read:
+            unotification.mark_as_read()
+            Session().commit()
 
-    def edit(self, notification_id, format='html'):
-        """GET /_admin/notifications/id/edit: Form to edit an existing item"""
-        # url('edit_notification', notification_id=ID)
+        c.notification = notification
+        c.user = self.authuser
+        return render('admin/notifications/show_notification.html')
--- a/kallithea/controllers/admin/permissions.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/admin/permissions.py	Fri Nov 18 01:11:13 2016 +0100
@@ -31,12 +31,13 @@
 import formencode
 from formencode import htmlfill
 
-from pylons import request, tmpl_context as c, url
-from pylons.controllers.util import redirect
+from pylons import request, tmpl_context as c
 from pylons.i18n.translation import _
+from webob.exc import HTTPFound
 
+from kallithea.config.routing import url
 from kallithea.lib import helpers as h
-from kallithea.lib.auth import LoginRequired, HasPermissionAllDecorator
+from kallithea.lib.auth import LoginRequired, HasPermissionAnyDecorator
 from kallithea.lib.base import BaseController, render
 from kallithea.model.forms import DefaultPermissionsForm
 from kallithea.model.permission import PermissionModel
@@ -53,7 +54,7 @@
     #     map.resource('permission', 'permissions')
 
     @LoginRequired()
-    @HasPermissionAllDecorator('hg.admin')
+    @HasPermissionAnyDecorator('hg.admin')
     def __before__(self):
         super(PermissionsController, self).__before__()
 
@@ -139,7 +140,7 @@
                 h.flash(_('Error occurred during update of permissions'),
                         category='error')
 
-            return redirect(url('admin_permissions'))
+            raise HTTPFound(location=url('admin_permissions'))
 
         c.user = User.get_default_user()
         defaults = {'anonymous': c.user.active}
@@ -184,7 +185,7 @@
     def permission_ips(self):
         c.active = 'ips'
         c.user = User.get_default_user()
-        c.user_ip_map = UserIpMap.query()\
+        c.user_ip_map = UserIpMap.query() \
                         .filter(UserIpMap.user == c.user).all()
 
         return render('admin/permissions/permissions.html')
--- a/kallithea/controllers/admin/repo_groups.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/admin/repo_groups.py	Fri Nov 18 01:11:13 2016 +0100
@@ -32,16 +32,17 @@
 
 from formencode import htmlfill
 
-from pylons import request, tmpl_context as c, url
-from pylons.controllers.util import abort, redirect
+from pylons import request, tmpl_context as c
 from pylons.i18n.translation import _, ungettext
+from webob.exc import HTTPFound, HTTPForbidden, HTTPNotFound, HTTPInternalServerError
 
 import kallithea
+from kallithea.config.routing import url
 from kallithea.lib import helpers as h
 from kallithea.lib.compat import json
 from kallithea.lib.auth import LoginRequired, \
-    HasRepoGroupPermissionAnyDecorator, HasRepoGroupPermissionAll, \
-    HasPermissionAll
+    HasRepoGroupPermissionAnyDecorator, HasRepoGroupPermissionAny, \
+    HasPermissionAny
 from kallithea.lib.base import BaseController, render
 from kallithea.model.db import RepoGroup, Repository
 from kallithea.model.scm import RepoGroupList, AvailableRepoGroupChoices
@@ -49,7 +50,6 @@
 from kallithea.model.forms import RepoGroupForm, RepoGroupPermsForm
 from kallithea.model.meta import Session
 from kallithea.model.repo import RepoModel
-from webob.exc import HTTPInternalServerError, HTTPNotFound
 from kallithea.lib.utils2 import safe_int
 from sqlalchemy.sql.expression import func
 
@@ -109,11 +109,7 @@
         return False
 
     def index(self, format='html'):
-        """GET /repo_groups: All items in the collection"""
-        # url('repos_groups')
-        _list = RepoGroup.query()\
-                    .order_by(func.lower(RepoGroup.group_name))\
-                    .all()
+        _list = RepoGroup.query(sorted=True).all()
         group_iter = RepoGroupList(_list, perm_set=['group.admin'])
         repo_groups_data = []
         total_records = len(group_iter)
@@ -140,7 +136,7 @@
                 "group_name": repo_group_name(repo_gr.group_name, children_groups),
                 "desc": h.escape(repo_gr.group_description),
                 "repos": repo_count,
-                "owner": h.person(repo_gr.user),
+                "owner": h.person(repo_gr.owner),
                 "action": repo_group_actions(repo_gr.group_id, repo_gr.group_name,
                                              repo_count)
             })
@@ -156,9 +152,6 @@
         return render('admin/repo_groups/repo_groups.html')
 
     def create(self):
-        """POST /repo_groups: Create a new item"""
-        # url('repos_groups')
-
         self.__load_defaults()
 
         # permissions for can create group based on parent_id are checked
@@ -169,7 +162,7 @@
             gr = RepoGroupModel().create(
                 group_name=form_result['group_name'],
                 group_description=form_result['group_description'],
-                parent=form_result['group_parent_id'],
+                parent=form_result['parent_group_id'],
                 owner=self.authuser.user_id, # TODO: make editable
                 copy_permissions=form_result['group_copy_permissions']
             )
@@ -187,17 +180,15 @@
             log.error(traceback.format_exc())
             h.flash(_('Error occurred during creation of repository group %s') \
                     % request.POST.get('group_name'), category='error')
-            parent_group_id = form_result['group_parent_id']
+            parent_group_id = form_result['parent_group_id']
             #TODO: maybe we should get back to the main view, not the admin one
-            return redirect(url('repos_groups', parent_group=parent_group_id))
+            raise HTTPFound(location=url('repos_groups', parent_group=parent_group_id))
         h.flash(_('Created repository group %s') % gr.group_name,
                 category='success')
-        return redirect(url('repos_group_home', group_name=gr.group_name))
+        raise HTTPFound(location=url('repos_group_home', group_name=gr.group_name))
 
     def new(self):
-        """GET /repo_groups/new: Form to create a new item"""
-        # url('new_repos_group')
-        if HasPermissionAll('hg.admin')('group create'):
+        if HasPermissionAny('hg.admin')('group create'):
             #we're global admin, we're ok and we can create TOP level groups
             pass
         else:
@@ -206,30 +197,22 @@
             group_id = safe_int(request.GET.get('parent_group'))
             group = RepoGroup.get(group_id) if group_id else None
             group_name = group.group_name if group else None
-            if HasRepoGroupPermissionAll('group.admin')(group_name, 'group create'):
+            if HasRepoGroupPermissionAny('group.admin')(group_name, 'group create'):
                 pass
             else:
-                return abort(403)
+                raise HTTPForbidden()
 
         self.__load_defaults()
         return render('admin/repo_groups/repo_group_add.html')
 
     @HasRepoGroupPermissionAnyDecorator('group.admin')
     def update(self, group_name):
-        """PUT /repo_groups/group_name: Update an existing item"""
-        # Forms posted to this method should contain a hidden field:
-        #    <input type="hidden" name="_method" value="PUT" />
-        # Or using helpers:
-        #    h.form(url('repos_group', group_name=GROUP_NAME),
-        #           method='put')
-        # url('repos_group', group_name=GROUP_NAME)
-
         c.repo_group = RepoGroupModel()._get_repo_group(group_name)
         self.__load_defaults(extras=[c.repo_group.parent_group],
                              exclude=[c.repo_group])
 
         # TODO: kill allow_empty_group - it is only used for redundant form validation!
-        if HasPermissionAll('hg.admin')('group edit'):
+        if HasPermissionAny('hg.admin')('group edit'):
             #we're global admin, we're ok and we can create TOP level groups
             allow_empty_group = True
         elif not c.repo_group.parent_group:
@@ -253,7 +236,7 @@
             group_name = new_gr.group_name
             #TODO: in future action_logger(, '', '', '', self.sa)
         except formencode.Invalid as errors:
-
+            c.active = 'settings'
             return htmlfill.render(
                 render('admin/repo_groups/repo_group_edit.html'),
                 defaults=errors.value,
@@ -266,30 +249,22 @@
             h.flash(_('Error occurred during update of repository group %s') \
                     % request.POST.get('group_name'), category='error')
 
-        return redirect(url('edit_repo_group', group_name=group_name))
+        raise HTTPFound(location=url('edit_repo_group', group_name=group_name))
 
     @HasRepoGroupPermissionAnyDecorator('group.admin')
     def delete(self, group_name):
-        """DELETE /repo_groups/group_name: Delete an existing item"""
-        # Forms posted to this method should contain a hidden field:
-        #    <input type="hidden" name="_method" value="DELETE" />
-        # Or using helpers:
-        #    h.form(url('repos_group', group_name=GROUP_NAME),
-        #           method='delete')
-        # url('repos_group', group_name=GROUP_NAME)
-
         gr = c.repo_group = RepoGroupModel()._get_repo_group(group_name)
         repos = gr.repositories.all()
         if repos:
             h.flash(_('This group contains %s repositories and cannot be '
                       'deleted') % len(repos), category='warning')
-            return redirect(url('repos_groups'))
+            raise HTTPFound(location=url('repos_groups'))
 
         children = gr.children.all()
         if children:
             h.flash(_('This group contains %s subgroups and cannot be deleted'
                       % (len(children))), category='warning')
-            return redirect(url('repos_groups'))
+            raise HTTPFound(location=url('repos_groups'))
 
         try:
             RepoGroupModel().delete(group_name)
@@ -303,8 +278,8 @@
                     % group_name, category='error')
 
         if gr.parent_group:
-            return redirect(url('repos_group_home', group_name=gr.parent_group.group_name))
-        return redirect(url('repos_groups'))
+            raise HTTPFound(location=url('repos_group_home', group_name=gr.parent_group.group_name))
+        raise HTTPFound(location=url('repos_groups'))
 
     def show_by_name(self, group_name):
         """
@@ -320,27 +295,16 @@
     @HasRepoGroupPermissionAnyDecorator('group.read', 'group.write',
                                          'group.admin')
     def show(self, group_name):
-        """GET /repo_groups/group_name: Show a specific item"""
-        # url('repos_group', group_name=GROUP_NAME)
         c.active = 'settings'
 
         c.group = c.repo_group = RepoGroupModel()._get_repo_group(group_name)
-        c.group_repos = c.group.repositories.all()
 
-        #overwrite our cached list with current filter
-        c.repo_cnt = 0
-
-        groups = RepoGroup.query().order_by(RepoGroup.group_name)\
-            .filter(RepoGroup.group_parent_id == c.group.group_id).all()
+        groups = RepoGroup.query(sorted=True).filter_by(parent_group=c.group).all()
         c.groups = self.scm_model.get_repo_groups(groups)
 
-        c.repos_list = Repository.query()\
-                        .filter(Repository.group_id == c.group.group_id)\
-                        .order_by(func.lower(Repository.repo_name))\
-                        .all()
-
-        repos_data = RepoModel().get_repos_as_dict(repos_list=c.repos_list,
-                                                   admin=False)
+        repos_list = Repository.query(sorted=True).filter_by(group=c.group).all()
+        repos_data = RepoModel().get_repos_as_dict(repos_list=repos_list,
+                                                   admin=False, short_name=True)
         #json used to render the grid
         c.data = json.dumps(repos_data)
 
@@ -348,8 +312,6 @@
 
     @HasRepoGroupPermissionAnyDecorator('group.admin')
     def edit(self, group_name):
-        """GET /repo_groups/group_name/edit: Form to edit an existing item"""
-        # url('edit_repo_group', group_name=GROUP_NAME)
         c.active = 'settings'
 
         c.repo_group = RepoGroupModel()._get_repo_group(group_name)
@@ -366,8 +328,6 @@
 
     @HasRepoGroupPermissionAnyDecorator('group.admin')
     def edit_repo_group_advanced(self, group_name):
-        """GET /repo_groups/group_name/edit: Form to edit an existing item"""
-        # url('edit_repo_group', group_name=GROUP_NAME)
         c.active = 'advanced'
         c.repo_group = RepoGroupModel()._get_repo_group(group_name)
 
@@ -375,8 +335,6 @@
 
     @HasRepoGroupPermissionAnyDecorator('group.admin')
     def edit_repo_group_perms(self, group_name):
-        """GET /repo_groups/group_name/edit: Form to edit an existing item"""
-        # url('edit_repo_group', group_name=GROUP_NAME)
         c.active = 'perms'
         c.repo_group = RepoGroupModel()._get_repo_group(group_name)
         self.__load_defaults()
@@ -404,7 +362,7 @@
             if self._revoke_perms_on_yourself(form_result):
                 msg = _('Cannot revoke permission for yourself as admin')
                 h.flash(msg, category='warning')
-                return redirect(url('edit_repo_group_perms', group_name=group_name))
+                raise HTTPFound(location=url('edit_repo_group_perms', group_name=group_name))
         recursive = form_result['recursive']
         # iterate over all members(if in recursive mode) of this groups and
         # set the permissions !
@@ -418,15 +376,10 @@
         #              repo_name, self.ip_addr, self.sa)
         Session().commit()
         h.flash(_('Repository group permissions updated'), category='success')
-        return redirect(url('edit_repo_group_perms', group_name=group_name))
+        raise HTTPFound(location=url('edit_repo_group_perms', group_name=group_name))
 
     @HasRepoGroupPermissionAnyDecorator('group.admin')
     def delete_perms(self, group_name):
-        """
-        DELETE an existing repository group permission user
-
-        :param group_name:
-        """
         try:
             obj_type = request.POST.get('obj_type')
             obj_id = None
--- a/kallithea/controllers/admin/repos.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/admin/repos.py	Fri Nov 18 01:11:13 2016 +0100
@@ -29,21 +29,20 @@
 import traceback
 import formencode
 from formencode import htmlfill
-from webob.exc import HTTPInternalServerError, HTTPForbidden, HTTPNotFound
-from pylons import request, tmpl_context as c, url
-from pylons.controllers.util import redirect
+from pylons import request, tmpl_context as c
 from pylons.i18n.translation import _
 from sqlalchemy.sql.expression import func
+from webob.exc import HTTPFound, HTTPInternalServerError, HTTPForbidden, HTTPNotFound
 
+from kallithea.config.routing import url
 from kallithea.lib import helpers as h
 from kallithea.lib.auth import LoginRequired, \
-    HasRepoPermissionAllDecorator, NotAnonymous, HasPermissionAny, \
-    HasRepoPermissionAnyDecorator
+    HasRepoPermissionAnyDecorator, NotAnonymous, HasPermissionAny
 from kallithea.lib.base import BaseRepoController, render
 from kallithea.lib.utils import action_logger, jsonify
 from kallithea.lib.vcs import RepositoryError
 from kallithea.model.meta import Session
-from kallithea.model.db import User, Repository, UserFollowing, RepoGroup,\
+from kallithea.model.db import User, Repository, UserFollowing, RepoGroup, \
     Setting, RepositoryField
 from kallithea.model.forms import RepoForm, RepoFieldForm, RepoPermsForm
 from kallithea.model.scm import ScmModel, AvailableRepoGroupChoices, RepoList
@@ -66,12 +65,12 @@
     def __before__(self):
         super(ReposController, self).__before__()
 
-    def _load_repo(self, repo_name):
-        repo_obj = Repository.get_by_repo_name(repo_name)
+    def _load_repo(self):
+        repo_obj = c.db_repo
 
         if repo_obj is None:
-            h.not_mapped_error(repo_name)
-            return redirect(url('repos'))
+            h.not_mapped_error(c.repo_name)
+            raise HTTPFound(location=url('repos'))
 
         return repo_obj
 
@@ -86,26 +85,20 @@
 
         c.landing_revs_choices, c.landing_revs = ScmModel().get_repo_landing_revs(repo)
 
-    def __load_data(self, repo_name=None):
+    def __load_data(self):
         """
         Load defaults settings for edit, and update
-
-        :param repo_name:
         """
-        c.repo_info = self._load_repo(repo_name)
+        c.repo_info = self._load_repo()
         self.__load_defaults(c.repo_info)
 
-        defaults = RepoModel()._get_defaults(repo_name)
+        defaults = RepoModel()._get_defaults(c.repo_name)
         defaults['clone_uri'] = c.repo_info.clone_uri_hidden # don't show password
 
         return defaults
 
     def index(self, format='html'):
-        """GET /repos: All items in the collection"""
-        # url('repos')
-        _list = Repository.query()\
-                        .order_by(func.lower(Repository.repo_name))\
-                        .all()
+        _list = Repository.query(sorted=True).all()
 
         c.repos_list = RepoList(_list, perm_set=['repository.admin'])
         repos_data = RepoModel().get_repos_as_dict(repos_list=c.repos_list,
@@ -118,25 +111,18 @@
 
     @NotAnonymous()
     def create(self):
-        """
-        POST /repos: Create a new item"""
-        # url('repos')
-
         self.__load_defaults()
         form_result = {}
-        task_id = None
         try:
             # CanWriteGroup validators checks permissions of this POST
             form_result = RepoForm(repo_groups=c.repo_groups,
-                                   landing_revs=c.landing_revs_choices)()\
+                                   landing_revs=c.landing_revs_choices)() \
                             .to_python(dict(request.POST))
 
             # create is done sometimes async on celery, db transaction
             # management is handled there.
             task = RepoModel().create(form_result, self.authuser.user_id)
-            from celery.result import BaseAsyncResult
-            if isinstance(task, BaseAsyncResult):
-                task_id = task.task_id
+            task_id = task.task_id
         except formencode.Invalid as errors:
             log.info(errors)
             return htmlfill.render(
@@ -152,15 +138,14 @@
             msg = (_('Error creating repository %s')
                    % form_result.get('repo_name'))
             h.flash(msg, category='error')
-            return redirect(url('home'))
+            raise HTTPFound(location=url('home'))
 
-        return redirect(h.url('repo_creating_home',
+        raise HTTPFound(location=h.url('repo_creating_home',
                               repo_name=form_result['repo_name_full'],
                               task_id=task_id))
 
     @NotAnonymous()
     def create_repository(self):
-        """GET /_admin/create_repository: Form to create a new item"""
         self.__load_defaults()
         if not c.repo_groups:
             raise HTTPForbidden
@@ -201,9 +186,9 @@
 
         if task_id and task_id not in ['None']:
             from kallithea import CELERY_ON
-            from celery.result import AsyncResult
+            from kallithea.lib import celerypylons
             if CELERY_ON:
-                task = AsyncResult(task_id)
+                task = celerypylons.result.AsyncResult(task_id)
                 if task.failed():
                     raise HTTPInternalServerError(task.traceback)
 
@@ -227,20 +212,12 @@
             return {'result': True}
         return {'result': False}
 
-    @HasRepoPermissionAllDecorator('repository.admin')
+    @HasRepoPermissionAnyDecorator('repository.admin')
     def update(self, repo_name):
-        """
-        PUT /repos/repo_name: Update an existing item"""
-        # Forms posted to this method should contain a hidden field:
-        #    <input type="hidden" name="_method" value="PUT" />
-        # Or using helpers:
-        #    h.form(url('put_repo', repo_name=ID),
-        #           method='put')
-        # url('put_repo', repo_name=ID)
-        c.repo_info = self._load_repo(repo_name)
+        c.repo_info = self._load_repo()
         self.__load_defaults(c.repo_info)
         c.active = 'settings'
-        c.repo_fields = RepositoryField.query()\
+        c.repo_fields = RepositoryField.query() \
             .filter(RepositoryField.repository == c.repo_info).all()
 
         repo_model = RepoModel()
@@ -267,7 +244,7 @@
             Session().commit()
         except formencode.Invalid as errors:
             log.info(errors)
-            defaults = self.__load_data(repo_name)
+            defaults = self.__load_data()
             defaults.update(errors.value)
             c.users_array = repo_model.get_users_js()
             return htmlfill.render(
@@ -282,24 +259,15 @@
             log.error(traceback.format_exc())
             h.flash(_('Error occurred during update of repository %s') \
                     % repo_name, category='error')
-        return redirect(url('edit_repo', repo_name=changed_name))
+        raise HTTPFound(location=url('edit_repo', repo_name=changed_name))
 
-    @HasRepoPermissionAllDecorator('repository.admin')
+    @HasRepoPermissionAnyDecorator('repository.admin')
     def delete(self, repo_name):
-        """
-        DELETE /repos/repo_name: Delete an existing item"""
-        # Forms posted to this method should contain a hidden field:
-        #    <input type="hidden" name="_method" value="DELETE" />
-        # Or using helpers:
-        #    h.form(url('delete_repo', repo_name=ID),
-        #           method='delete')
-        # url('delete_repo', repo_name=ID)
-
         repo_model = RepoModel()
         repo = repo_model.get_by_repo_name(repo_name)
         if not repo:
             h.not_mapped_error(repo_name)
-            return redirect(url('repos'))
+            raise HTTPFound(location=url('repos'))
         try:
             _forks = repo.forks.count()
             handle_forks = None
@@ -327,15 +295,13 @@
                     category='error')
 
         if repo.group:
-            return redirect(url('repos_group_home', group_name=repo.group.group_name))
-        return redirect(url('repos'))
+            raise HTTPFound(location=url('repos_group_home', group_name=repo.group.group_name))
+        raise HTTPFound(location=url('repos'))
 
-    @HasRepoPermissionAllDecorator('repository.admin')
+    @HasRepoPermissionAnyDecorator('repository.admin')
     def edit(self, repo_name):
-        """GET /repo_name/settings: Form to edit an existing item"""
-        # url('edit_repo', repo_name=ID)
-        defaults = self.__load_data(repo_name)
-        c.repo_fields = RepositoryField.query()\
+        defaults = self.__load_data()
+        c.repo_fields = RepositoryField.query() \
             .filter(RepositoryField.repository == c.repo_info).all()
         repo_model = RepoModel()
         c.users_array = repo_model.get_users_js()
@@ -346,11 +312,9 @@
             encoding="UTF-8",
             force_defaults=False)
 
-    @HasRepoPermissionAllDecorator('repository.admin')
+    @HasRepoPermissionAnyDecorator('repository.admin')
     def edit_permissions(self, repo_name):
-        """GET /repo_name/settings: Form to edit an existing item"""
-        # url('edit_repo', repo_name=ID)
-        c.repo_info = self._load_repo(repo_name)
+        c.repo_info = self._load_repo()
         repo_model = RepoModel()
         c.users_array = repo_model.get_users_js()
         c.user_groups_array = repo_model.get_user_groups_js()
@@ -372,7 +336,7 @@
         #              repo_name, self.ip_addr, self.sa)
         Session().commit()
         h.flash(_('Repository permissions updated'), category='success')
-        return redirect(url('edit_repo_perms', repo_name=repo_name))
+        raise HTTPFound(location=url('edit_repo_perms', repo_name=repo_name))
 
     def edit_permissions_revoke(self, repo_name):
         try:
@@ -399,20 +363,18 @@
                     category='error')
             raise HTTPInternalServerError()
 
-    @HasRepoPermissionAllDecorator('repository.admin')
+    @HasRepoPermissionAnyDecorator('repository.admin')
     def edit_fields(self, repo_name):
-        """GET /repo_name/settings: Form to edit an existing item"""
-        # url('edit_repo', repo_name=ID)
-        c.repo_info = self._load_repo(repo_name)
-        c.repo_fields = RepositoryField.query()\
+        c.repo_info = self._load_repo()
+        c.repo_fields = RepositoryField.query() \
             .filter(RepositoryField.repository == c.repo_info).all()
         c.active = 'fields'
         if request.POST:
 
-            return redirect(url('repo_edit_fields'))
+            raise HTTPFound(location=url('repo_edit_fields'))
         return render('admin/repos/repo_edit.html')
 
-    @HasRepoPermissionAllDecorator('repository.admin')
+    @HasRepoPermissionAnyDecorator('repository.admin')
     def create_repo_field(self, repo_name):
         try:
             form_result = RepoFieldForm()().to_python(dict(request.POST))
@@ -431,9 +393,9 @@
             if isinstance(e, formencode.Invalid):
                 msg += ". " + e.msg
             h.flash(msg, category='error')
-        return redirect(url('edit_repo_fields', repo_name=repo_name))
+        raise HTTPFound(location=url('edit_repo_fields', repo_name=repo_name))
 
-    @HasRepoPermissionAllDecorator('repository.admin')
+    @HasRepoPermissionAnyDecorator('repository.admin')
     def delete_repo_field(self, repo_name, field_id):
         field = RepositoryField.get_or_404(field_id)
         try:
@@ -443,19 +405,17 @@
             log.error(traceback.format_exc())
             msg = _('An error occurred during removal of field')
             h.flash(msg, category='error')
-        return redirect(url('edit_repo_fields', repo_name=repo_name))
+        raise HTTPFound(location=url('edit_repo_fields', repo_name=repo_name))
 
-    @HasRepoPermissionAllDecorator('repository.admin')
+    @HasRepoPermissionAnyDecorator('repository.admin')
     def edit_advanced(self, repo_name):
-        """GET /repo_name/settings: Form to edit an existing item"""
-        # url('edit_repo', repo_name=ID)
-        c.repo_info = self._load_repo(repo_name)
+        c.repo_info = self._load_repo()
         c.default_user_id = User.get_default_user().user_id
-        c.in_public_journal = UserFollowing.query()\
-            .filter(UserFollowing.user_id == c.default_user_id)\
+        c.in_public_journal = UserFollowing.query() \
+            .filter(UserFollowing.user_id == c.default_user_id) \
             .filter(UserFollowing.follows_repository == c.repo_info).scalar()
 
-        _repos = Repository.query().order_by(Repository.repo_name).all()
+        _repos = Repository.query(sorted=True).all()
         read_access_repos = RepoList(_repos)
         c.repos_list = [(None, _('-- Not a fork --'))]
         c.repos_list += [(x.repo_id, x.repo_name)
@@ -463,19 +423,19 @@
                          if x.repo_id != c.repo_info.repo_id]
 
         defaults = {
-            'id_fork_of': c.repo_info.fork.repo_id if c.repo_info.fork else ''
+            'id_fork_of': c.repo_info.fork_id if c.repo_info.fork_id else ''
         }
 
         c.active = 'advanced'
         if request.POST:
-            return redirect(url('repo_edit_advanced'))
+            raise HTTPFound(location=url('repo_edit_advanced'))
         return htmlfill.render(
             render('admin/repos/repo_edit.html'),
             defaults=defaults,
             encoding="UTF-8",
             force_defaults=False)
 
-    @HasRepoPermissionAllDecorator('repository.admin')
+    @HasRepoPermissionAnyDecorator('repository.admin')
     def edit_advanced_journal(self, repo_name):
         """
         Sets this repository to be visible in public journal,
@@ -495,10 +455,10 @@
             h.flash(_('An error occurred during setting this'
                       ' repository in public journal'),
                     category='error')
-        return redirect(url('edit_repo_advanced', repo_name=repo_name))
+        raise HTTPFound(location=url('edit_repo_advanced', repo_name=repo_name))
 
 
-    @HasRepoPermissionAllDecorator('repository.admin')
+    @HasRepoPermissionAnyDecorator('repository.admin')
     def edit_advanced_fork(self, repo_name):
         """
         Mark given repository as a fork of another
@@ -521,9 +481,9 @@
             h.flash(_('An error occurred during this operation'),
                     category='error')
 
-        return redirect(url('edit_repo_advanced', repo_name=repo_name))
+        raise HTTPFound(location=url('edit_repo_advanced', repo_name=repo_name))
 
-    @HasRepoPermissionAllDecorator('repository.admin')
+    @HasRepoPermissionAnyDecorator('repository.admin')
     def edit_advanced_locking(self, repo_name):
         """
         Unlock repository when it is locked !
@@ -542,16 +502,10 @@
             log.error(traceback.format_exc())
             h.flash(_('An error occurred during unlocking'),
                     category='error')
-        return redirect(url('edit_repo_advanced', repo_name=repo_name))
+        raise HTTPFound(location=url('edit_repo_advanced', repo_name=repo_name))
 
     @HasRepoPermissionAnyDecorator('repository.write', 'repository.admin')
     def toggle_locking(self, repo_name):
-        """
-        Toggle locking of repository by simple GET call to url
-
-        :param repo_name:
-        """
-
         try:
             repo = Repository.get_by_repo_name(repo_name)
 
@@ -567,17 +521,15 @@
             log.error(traceback.format_exc())
             h.flash(_('An error occurred during unlocking'),
                     category='error')
-        return redirect(url('summary_home', repo_name=repo_name))
+        raise HTTPFound(location=url('summary_home', repo_name=repo_name))
 
-    @HasRepoPermissionAllDecorator('repository.admin')
+    @HasRepoPermissionAnyDecorator('repository.admin')
     def edit_caches(self, repo_name):
-        """GET /repo_name/settings: Form to edit an existing item"""
-        # url('edit_repo', repo_name=ID)
-        c.repo_info = self._load_repo(repo_name)
+        c.repo_info = self._load_repo()
         c.active = 'caches'
         if request.POST:
             try:
-                ScmModel().mark_for_invalidation(repo_name, delete=True)
+                ScmModel().mark_for_invalidation(repo_name)
                 Session().commit()
                 h.flash(_('Cache invalidation successful'),
                         category='success')
@@ -586,14 +538,12 @@
                 h.flash(_('An error occurred during cache invalidation'),
                         category='error')
 
-            return redirect(url('edit_repo_caches', repo_name=c.repo_name))
+            raise HTTPFound(location=url('edit_repo_caches', repo_name=c.repo_name))
         return render('admin/repos/repo_edit.html')
 
-    @HasRepoPermissionAllDecorator('repository.admin')
+    @HasRepoPermissionAnyDecorator('repository.admin')
     def edit_remote(self, repo_name):
-        """GET /repo_name/settings: Form to edit an existing item"""
-        # url('edit_repo', repo_name=ID)
-        c.repo_info = self._load_repo(repo_name)
+        c.repo_info = self._load_repo()
         c.active = 'remote'
         if request.POST:
             try:
@@ -603,14 +553,12 @@
                 log.error(traceback.format_exc())
                 h.flash(_('An error occurred during pull from remote location'),
                         category='error')
-            return redirect(url('edit_repo_remote', repo_name=c.repo_name))
+            raise HTTPFound(location=url('edit_repo_remote', repo_name=c.repo_name))
         return render('admin/repos/repo_edit.html')
 
-    @HasRepoPermissionAllDecorator('repository.admin')
+    @HasRepoPermissionAnyDecorator('repository.admin')
     def edit_statistics(self, repo_name):
-        """GET /repo_name/settings: Form to edit an existing item"""
-        # url('edit_repo', repo_name=ID)
-        c.repo_info = self._load_repo(repo_name)
+        c.repo_info = self._load_repo()
         repo = c.repo_info.scm_instance
 
         if c.repo_info.stats:
@@ -636,6 +584,6 @@
                 log.error(traceback.format_exc())
                 h.flash(_('An error occurred during deletion of repository stats'),
                         category='error')
-            return redirect(url('edit_repo_statistics', repo_name=c.repo_name))
+            raise HTTPFound(location=url('edit_repo_statistics', repo_name=c.repo_name))
 
         return render('admin/repos/repo_edit.html')
--- a/kallithea/controllers/admin/settings.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/admin/settings.py	Fri Nov 18 01:11:13 2016 +0100
@@ -30,14 +30,15 @@
 import formencode
 
 from formencode import htmlfill
-from pylons import request, tmpl_context as c, url, config
-from pylons.controllers.util import redirect
+from pylons import request, tmpl_context as c, config
 from pylons.i18n.translation import _
+from webob.exc import HTTPFound
 
+from kallithea.config.routing import url
 from kallithea.lib import helpers as h
-from kallithea.lib.auth import LoginRequired, HasPermissionAllDecorator
+from kallithea.lib.auth import LoginRequired, HasPermissionAnyDecorator
 from kallithea.lib.base import BaseController, render
-from kallithea.lib.celerylib import tasks, run_task
+from kallithea.lib.celerylib import tasks
 from kallithea.lib.exceptions import HgsubversionImportError
 from kallithea.lib.utils import repo2db_mapper, set_app_settings
 from kallithea.model.db import Ui, Repository, Setting
@@ -64,31 +65,23 @@
     def _get_hg_ui_settings(self):
         ret = Ui.query().all()
 
-        if not ret:
-            raise Exception('Could not get application ui settings !')
         settings = {}
         for each in ret:
-            k = each.ui_key
+            k = each.ui_section + '_' + each.ui_key
             v = each.ui_value
-            if k == '/':
-                k = 'root_path'
+            if k == 'paths_/':
+                k = 'paths_root_path'
 
-            if k == 'push_ssl':
-                v = str2bool(v)
-
-            if k.find('.') != -1:
-                k = k.replace('.', '_')
+            k = k.replace('.', '_')
 
             if each.ui_section in ['hooks', 'extensions']:
                 v = each.ui_active
 
-            settings[each.ui_section + '_' + k] = v
+            settings[k] = v
         return settings
 
-    @HasPermissionAllDecorator('hg.admin')
+    @HasPermissionAnyDecorator('hg.admin')
     def settings_vcs(self):
-        """GET /admin/settings: All items in the collection"""
-        # url('admin_settings')
         c.active = 'vcs'
         if request.POST:
             application_form = ApplicationUiSettingsForm()()
@@ -104,66 +97,37 @@
                      force_defaults=False)
 
             try:
-                sett = Ui.get_by_key('push_ssl')
-                sett.ui_value = form_result['web_push_ssl']
-                Session().add(sett)
                 if c.visual.allow_repo_location_change:
-                    sett = Ui.get_by_key('/')
+                    sett = Ui.get_by_key('paths', '/')
                     sett.ui_value = form_result['paths_root_path']
-                    Session().add(sett)
 
                 #HOOKS
-                sett = Ui.get_by_key(Ui.HOOK_UPDATE)
+                sett = Ui.get_by_key('hooks', Ui.HOOK_UPDATE)
                 sett.ui_active = form_result['hooks_changegroup_update']
-                Session().add(sett)
 
-                sett = Ui.get_by_key(Ui.HOOK_REPO_SIZE)
+                sett = Ui.get_by_key('hooks', Ui.HOOK_REPO_SIZE)
                 sett.ui_active = form_result['hooks_changegroup_repo_size']
-                Session().add(sett)
 
-                sett = Ui.get_by_key(Ui.HOOK_PUSH)
+                sett = Ui.get_by_key('hooks', Ui.HOOK_PUSH)
                 sett.ui_active = form_result['hooks_changegroup_push_logger']
-                Session().add(sett)
 
-                sett = Ui.get_by_key(Ui.HOOK_PULL)
+                sett = Ui.get_by_key('hooks', Ui.HOOK_PULL)
                 sett.ui_active = form_result['hooks_outgoing_pull_logger']
 
-                Session().add(sett)
-
                 ## EXTENSIONS
-                sett = Ui.get_by_key('largefiles')
-                if not sett:
-                    #make one if it's not there !
-                    sett = Ui()
-                    sett.ui_key = 'largefiles'
-                    sett.ui_section = 'extensions'
+                sett = Ui.get_or_create('extensions', 'largefiles')
                 sett.ui_active = form_result['extensions_largefiles']
-                Session().add(sett)
 
-                sett = Ui.get_by_key('hgsubversion')
-                if not sett:
-                    #make one if it's not there !
-                    sett = Ui()
-                    sett.ui_key = 'hgsubversion'
-                    sett.ui_section = 'extensions'
-
+                sett = Ui.get_or_create('extensions', 'hgsubversion')
                 sett.ui_active = form_result['extensions_hgsubversion']
                 if sett.ui_active:
                     try:
                         import hgsubversion  # pragma: no cover
                     except ImportError:
                         raise HgsubversionImportError
-                Session().add(sett)
 
-#                sett = Ui.get_by_key('hggit')
-#                if not sett:
-#                    #make one if it's not there !
-#                    sett = Ui()
-#                    sett.ui_key = 'hggit'
-#                    sett.ui_section = 'extensions'
-#
+#                sett = Ui.get_or_create('extensions', 'hggit')
 #                sett.ui_active = form_result['extensions_hggit']
-#                Session().add(sett)
 
                 Session().commit()
 
@@ -189,10 +153,8 @@
             encoding="UTF-8",
             force_defaults=False)
 
-    @HasPermissionAllDecorator('hg.admin')
+    @HasPermissionAnyDecorator('hg.admin')
     def settings_mapping(self):
-        """GET /admin/settings/mapping: All items in the collection"""
-        # url('admin_settings_mapping')
         c.active = 'mapping'
         if request.POST:
             rm_obsolete = request.POST.get('destroy', False)
@@ -205,8 +167,8 @@
 
             if invalidate_cache:
                 log.debug('invalidating all repositories cache')
-                for repo in Repository.get_all():
-                    ScmModel().mark_for_invalidation(repo.repo_name, delete=True)
+                for repo in Repository.query():
+                    ScmModel().mark_for_invalidation(repo.repo_name)
 
             filesystem_repos = ScmModel().repo_scan()
             added, removed = repo2db_mapper(filesystem_repos, rm_obsolete,
@@ -218,7 +180,7 @@
                  for repo_name in added) or '-',
                  ', '.join(h.escape(safe_unicode(repo_name)) for repo_name in removed) or '-')),
                 category='success')
-            return redirect(url('admin_settings_mapping'))
+            raise HTTPFound(location=url('admin_settings_mapping'))
 
         defaults = Setting.get_app_settings()
         defaults.update(self._get_hg_ui_settings())
@@ -229,10 +191,8 @@
             encoding="UTF-8",
             force_defaults=False)
 
-    @HasPermissionAllDecorator('hg.admin')
+    @HasPermissionAnyDecorator('hg.admin')
     def settings_global(self):
-        """GET /admin/settings/global: All items in the collection"""
-        # url('admin_settings_global')
         c.active = 'global'
         if request.POST:
             application_form = ApplicationSettingsForm()()
@@ -248,25 +208,14 @@
                     force_defaults=False)
 
             try:
-                sett1 = Setting.create_or_update('title',
-                                            form_result['title'])
-                Session().add(sett1)
-
-                sett2 = Setting.create_or_update('realm',
-                                            form_result['realm'])
-                Session().add(sett2)
-
-                sett3 = Setting.create_or_update('ga_code',
-                                            form_result['ga_code'])
-                Session().add(sett3)
-
-                sett4 = Setting.create_or_update('captcha_public_key',
-                                    form_result['captcha_public_key'])
-                Session().add(sett4)
-
-                sett5 = Setting.create_or_update('captcha_private_key',
-                                    form_result['captcha_private_key'])
-                Session().add(sett5)
+                for setting in (
+                    'title',
+                    'realm',
+                    'ga_code',
+                    'captcha_public_key',
+                    'captcha_private_key',
+                ):
+                    Setting.create_or_update(setting, form_result[setting])
 
                 Session().commit()
                 set_app_settings(config)
@@ -278,7 +227,7 @@
                           'application settings'),
                           category='error')
 
-            return redirect(url('admin_settings_global'))
+            raise HTTPFound(location=url('admin_settings_global'))
 
         defaults = Setting.get_app_settings()
         defaults.update(self._get_hg_ui_settings())
@@ -289,10 +238,8 @@
             encoding="UTF-8",
             force_defaults=False)
 
-    @HasPermissionAllDecorator('hg.admin')
+    @HasPermissionAnyDecorator('hg.admin')
     def settings_visual(self):
-        """GET /admin/settings/visual: All items in the collection"""
-        # url('admin_settings_visual')
         c.active = 'visual'
         if request.POST:
             application_form = ApplicationVisualisationForm()()
@@ -313,7 +260,7 @@
                     ('show_private_icon', 'show_private_icon', 'bool'),
                     ('stylify_metatags', 'stylify_metatags', 'bool'),
                     ('repository_fields', 'repository_fields', 'bool'),
-                    ('dashboard_items', 'dashboard_items', 'int'),
+                    ('dashboard_items', 'page_size', 'int'),
                     ('admin_grid_items', 'admin_grid_items', 'int'),
                     ('show_version', 'show_version', 'bool'),
                     ('use_gravatar', 'use_gravatar', 'bool'),
@@ -321,9 +268,7 @@
                     ('clone_uri_tmpl', 'clone_uri_tmpl', 'unicode'),
                 ]
                 for setting, form_key, type_ in settings:
-                    sett = Setting.create_or_update(setting,
-                                        form_result[form_key], type_)
-                    Session().add(sett)
+                    Setting.create_or_update(setting, form_result[form_key], type_)
 
                 Session().commit()
                 set_app_settings(config)
@@ -336,7 +281,7 @@
                           'visualisation settings'),
                         category='error')
 
-            return redirect(url('admin_settings_visual'))
+            raise HTTPFound(location=url('admin_settings_visual'))
 
         defaults = Setting.get_app_settings()
         defaults.update(self._get_hg_ui_settings())
@@ -347,10 +292,8 @@
             encoding="UTF-8",
             force_defaults=False)
 
-    @HasPermissionAllDecorator('hg.admin')
+    @HasPermissionAnyDecorator('hg.admin')
     def settings_email(self):
-        """GET /admin/settings/email: All items in the collection"""
-        # url('admin_settings_email')
         c.active = 'email'
         if request.POST:
             test_email = request.POST.get('test_email')
@@ -359,22 +302,22 @@
                                'Kallithea version: %s' % c.kallithea_version)
             if not test_email:
                 h.flash(_('Please enter email address'), category='error')
-                return redirect(url('admin_settings_email'))
+                raise HTTPFound(location=url('admin_settings_email'))
 
-            test_email_txt_body = EmailNotificationModel()\
+            test_email_txt_body = EmailNotificationModel() \
                 .get_email_tmpl(EmailNotificationModel.TYPE_DEFAULT,
                                 'txt', body=test_body)
-            test_email_html_body = EmailNotificationModel()\
+            test_email_html_body = EmailNotificationModel() \
                 .get_email_tmpl(EmailNotificationModel.TYPE_DEFAULT,
                                 'html', body=test_body)
 
             recipients = [test_email] if test_email else None
 
-            run_task(tasks.send_email, recipients, test_email_subj,
-                     test_email_txt_body, test_email_html_body)
+            tasks.send_email(recipients, test_email_subj,
+                             test_email_txt_body, test_email_html_body)
 
             h.flash(_('Send email task created'), category='success')
-            return redirect(url('admin_settings_email'))
+            raise HTTPFound(location=url('admin_settings_email'))
 
         defaults = Setting.get_app_settings()
         defaults.update(self._get_hg_ui_settings())
@@ -388,10 +331,8 @@
             encoding="UTF-8",
             force_defaults=False)
 
-    @HasPermissionAllDecorator('hg.admin')
+    @HasPermissionAnyDecorator('hg.admin')
     def settings_hooks(self):
-        """GET /admin/settings/hooks: All items in the collection"""
-        # url('admin_settings_hooks')
         c.active = 'hooks'
         if request.POST:
             if c.visual.allow_custom_hooks_settings:
@@ -425,7 +366,7 @@
                     h.flash(_('Error occurred during hook creation'),
                             category='error')
 
-                return redirect(url('admin_settings_hooks'))
+                raise HTTPFound(location=url('admin_settings_hooks'))
 
         defaults = Setting.get_app_settings()
         defaults.update(self._get_hg_ui_settings())
@@ -439,17 +380,15 @@
             encoding="UTF-8",
             force_defaults=False)
 
-    @HasPermissionAllDecorator('hg.admin')
+    @HasPermissionAnyDecorator('hg.admin')
     def settings_search(self):
-        """GET /admin/settings/search: All items in the collection"""
-        # url('admin_settings_search')
         c.active = 'search'
         if request.POST:
             repo_location = self._get_hg_ui_settings()['paths_root_path']
             full_index = request.POST.get('full_index', False)
-            run_task(tasks.whoosh_index, repo_location, full_index)
+            tasks.whoosh_index(repo_location, full_index)
             h.flash(_('Whoosh reindex task scheduled'), category='success')
-            return redirect(url('admin_settings_search'))
+            raise HTTPFound(location=url('admin_settings_search'))
 
         defaults = Setting.get_app_settings()
         defaults.update(self._get_hg_ui_settings())
@@ -460,10 +399,8 @@
             encoding="UTF-8",
             force_defaults=False)
 
-    @HasPermissionAllDecorator('hg.admin')
+    @HasPermissionAnyDecorator('hg.admin')
     def settings_system(self):
-        """GET /admin/settings/system: All items in the collection"""
-        # url('admin_settings_system')
         c.active = 'system'
 
         defaults = Setting.get_app_settings()
@@ -482,10 +419,8 @@
             encoding="UTF-8",
             force_defaults=False)
 
-    @HasPermissionAllDecorator('hg.admin')
+    @HasPermissionAnyDecorator('hg.admin')
     def settings_system_update(self):
-        """GET /admin/settings/system/updates: All items in the collection"""
-        # url('admin_settings_system_update')
         import json
         import urllib2
         from kallithea.lib.verlib import NormalizedVersion
@@ -496,7 +431,7 @@
         _update_url = defaults.get('update_url', '')
         _update_url = "" # FIXME: disabled
 
-        _err = lambda s: '<div style="color:#ff8888; padding:4px 0px">%s</div>' % (s)
+        _err = lambda s: '<div class="alert alert-danger">%s</div>' % (s)
         try:
             import kallithea
             ver = kallithea.__version__
--- a/kallithea/controllers/admin/user_groups.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/admin/user_groups.py	Fri Nov 18 01:11:13 2016 +0100
@@ -15,7 +15,7 @@
 kallithea.controllers.admin.user_groups
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
-User Groups crud controller for pylons
+User Groups crud controller
 
 This file was forked by the Kallithea project in July 2014.
 Original author and date, and relevant copyright and licensing information is below:
@@ -30,15 +30,16 @@
 import formencode
 
 from formencode import htmlfill
-from pylons import request, tmpl_context as c, url, config
-from pylons.controllers.util import redirect
+from pylons import request, tmpl_context as c, config
 from pylons.i18n.translation import _
+from webob.exc import HTTPFound
 
 from sqlalchemy.orm import joinedload
 from sqlalchemy.sql.expression import func
 from webob.exc import HTTPInternalServerError
 
 import kallithea
+from kallithea.config.routing import url
 from kallithea.lib import helpers as h
 from kallithea.lib.exceptions import UserGroupsAssignedException, \
     RepoGroupAssignmentError
@@ -88,10 +89,8 @@
         return data
 
     def index(self, format='html'):
-        """GET /users_groups: All items in the collection"""
-        # url('users_groups')
-        _list = UserGroup.query()\
-                        .order_by(func.lower(UserGroup.users_group_name))\
+        _list = UserGroup.query() \
+                        .order_by(func.lower(UserGroup.users_group_name)) \
                         .all()
         group_iter = UserGroupList(_list, perm_set=['usergroup.admin'])
         user_groups_data = []
@@ -116,7 +115,7 @@
                 "desc": h.escape(user_gr.user_group_description),
                 "members": len(user_gr.members),
                 "active": h.boolicon(user_gr.users_group_active),
-                "owner": h.person(user_gr.user.username),
+                "owner": h.person(user_gr.owner.username),
                 "action": user_group_actions(user_gr.users_group_id, user_gr.users_group_name)
             })
 
@@ -132,9 +131,6 @@
 
     @HasPermissionAnyDecorator('hg.admin', 'hg.usergroup.create.true')
     def create(self):
-        """POST /users_groups: Create a new item"""
-        # url('users_groups')
-
         users_group_form = UserGroupForm()()
         try:
             form_result = users_group_form.to_python(dict(request.POST))
@@ -163,24 +159,14 @@
             h.flash(_('Error occurred during creation of user group %s') \
                     % request.POST.get('users_group_name'), category='error')
 
-        return redirect(url('users_groups'))
+        raise HTTPFound(location=url('users_groups'))
 
     @HasPermissionAnyDecorator('hg.admin', 'hg.usergroup.create.true')
     def new(self, format='html'):
-        """GET /user_groups/new: Form to create a new item"""
-        # url('new_users_group')
         return render('admin/user_groups/user_group_add.html')
 
     @HasUserGroupPermissionAnyDecorator('usergroup.admin')
     def update(self, id):
-        """PUT /user_groups/id: Update an existing item"""
-        # Forms posted to this method should contain a hidden field:
-        #    <input type="hidden" name="_method" value="PUT" />
-        # Or using helpers:
-        #    h.form(url('users_group', id=ID),
-        #           method='put')
-        # url('users_group', id=ID)
-
         c.user_group = UserGroup.get_or_404(id)
         c.active = 'settings'
         self.__load_data(id)
@@ -209,7 +195,6 @@
                                                       'hg.create.repository'),
                 'fork_repo_perm': ug_model.has_perm(id,
                                                     'hg.fork.repository'),
-                '_method': 'put'
             })
 
             return htmlfill.render(
@@ -224,17 +209,10 @@
             h.flash(_('Error occurred during update of user group %s') \
                     % request.POST.get('users_group_name'), category='error')
 
-        return redirect(url('edit_users_group', id=id))
+        raise HTTPFound(location=url('edit_users_group', id=id))
 
     @HasUserGroupPermissionAnyDecorator('usergroup.admin')
     def delete(self, id):
-        """DELETE /user_groups/id: Delete an existing item"""
-        # Forms posted to this method should contain a hidden field:
-        #    <input type="hidden" name="_method" value="DELETE" />
-        # Or using helpers:
-        #    h.form(url('users_group', id=ID),
-        #           method='delete')
-        # url('users_group', id=ID)
         usr_gr = UserGroup.get_or_404(id)
         try:
             UserGroupModel().delete(usr_gr)
@@ -246,17 +224,10 @@
             log.error(traceback.format_exc())
             h.flash(_('An error occurred during deletion of user group'),
                     category='error')
-        return redirect(url('users_groups'))
-
-    def show(self, id, format='html'):
-        """GET /user_groups/id: Show a specific item"""
-        # url('users_group', id=ID)
+        raise HTTPFound(location=url('users_groups'))
 
     @HasUserGroupPermissionAnyDecorator('usergroup.admin')
     def edit(self, id, format='html'):
-        """GET /user_groups/id/edit: Form to edit an existing item"""
-        # url('edit_users_group', id=ID)
-
         c.user_group = UserGroup.get_or_404(id)
         c.active = 'settings'
         self.__load_data(id)
@@ -312,21 +283,16 @@
                                                  form['perms_updates'])
         except RepoGroupAssignmentError:
             h.flash(_('Target group cannot be the same'), category='error')
-            return redirect(url('edit_user_group_perms', id=id))
+            raise HTTPFound(location=url('edit_user_group_perms', id=id))
         #TODO: implement this
         #action_logger(self.authuser, 'admin_changed_repo_permissions',
         #              repo_name, self.ip_addr, self.sa)
         Session().commit()
         h.flash(_('User group permissions updated'), category='success')
-        return redirect(url('edit_user_group_perms', id=id))
+        raise HTTPFound(location=url('edit_user_group_perms', id=id))
 
     @HasUserGroupPermissionAnyDecorator('usergroup.admin')
     def delete_perms(self, id):
-        """
-        DELETE an existing repository group permission user
-
-        :param group_name:
-        """
         try:
             obj_type = request.POST.get('obj_type')
             obj_id = None
@@ -362,20 +328,20 @@
             'repositories': {},
             'repositories_groups': {}
         }
-        ugroup_repo_perms = UserGroupRepoToPerm.query()\
-            .options(joinedload(UserGroupRepoToPerm.permission))\
-            .options(joinedload(UserGroupRepoToPerm.repository))\
-            .filter(UserGroupRepoToPerm.users_group_id == id)\
+        ugroup_repo_perms = UserGroupRepoToPerm.query() \
+            .options(joinedload(UserGroupRepoToPerm.permission)) \
+            .options(joinedload(UserGroupRepoToPerm.repository)) \
+            .filter(UserGroupRepoToPerm.users_group_id == id) \
             .all()
 
         for gr in ugroup_repo_perms:
             permissions['repositories'][gr.repository.repo_name]  \
                 = gr.permission.permission_name
 
-        ugroup_group_perms = UserGroupRepoGroupToPerm.query()\
-            .options(joinedload(UserGroupRepoGroupToPerm.permission))\
-            .options(joinedload(UserGroupRepoGroupToPerm.group))\
-            .filter(UserGroupRepoGroupToPerm.users_group_id == id)\
+        ugroup_group_perms = UserGroupRepoGroupToPerm.query() \
+            .options(joinedload(UserGroupRepoGroupToPerm.permission)) \
+            .options(joinedload(UserGroupRepoGroupToPerm.group)) \
+            .filter(UserGroupRepoGroupToPerm.users_group_id == id) \
             .all()
 
         for gr in ugroup_group_perms:
@@ -404,9 +370,6 @@
 
     @HasUserGroupPermissionAnyDecorator('usergroup.admin')
     def update_default_perms(self, id):
-        """PUT /users_perm/id: Update an existing item"""
-        # url('users_group_perm', id=ID, method='put')
-
         user_group = UserGroup.get_or_404(id)
 
         try:
@@ -415,11 +378,10 @@
 
             inherit_perms = form_result['inherit_default_permissions']
             user_group.inherit_default_permissions = inherit_perms
-            Session().add(user_group)
             usergroup_model = UserGroupModel()
 
-            defs = UserGroupToPerm.query()\
-                .filter(UserGroupToPerm.users_group == user_group)\
+            defs = UserGroupToPerm.query() \
+                .filter(UserGroupToPerm.users_group == user_group) \
                 .all()
             for ug in defs:
                 Session().delete(ug)
@@ -444,7 +406,7 @@
             h.flash(_('An error occurred during permissions saving'),
                     category='error')
 
-        return redirect(url('edit_user_group_default_perms', id=id))
+        raise HTTPFound(location=url('edit_user_group_default_perms', id=id))
 
     @HasUserGroupPermissionAnyDecorator('usergroup.admin')
     def edit_advanced(self, id):
--- a/kallithea/controllers/admin/users.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/admin/users.py	Fri Nov 18 01:11:13 2016 +0100
@@ -15,7 +15,7 @@
 kallithea.controllers.admin.users
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
-Users crud controller for pylons
+Users crud controller
 
 This file was forked by the Kallithea project in July 2014.
 Original author and date, and relevant copyright and licensing information is below:
@@ -30,20 +30,19 @@
 import formencode
 
 from formencode import htmlfill
-from pylons import request, tmpl_context as c, url, config
-from pylons.controllers.util import redirect
+from pylons import request, tmpl_context as c, config
 from pylons.i18n.translation import _
 from sqlalchemy.sql.expression import func
-from webob.exc import HTTPNotFound
+from webob.exc import HTTPFound, HTTPNotFound
 
 import kallithea
+from kallithea.config.routing import url
 from kallithea.lib.exceptions import DefaultUserException, \
     UserOwnsReposException, UserCreationError
 from kallithea.lib import helpers as h
-from kallithea.lib.auth import LoginRequired, HasPermissionAllDecorator, \
+from kallithea.lib.auth import LoginRequired, HasPermissionAnyDecorator, \
     AuthUser
 from kallithea.lib import auth_modules
-from kallithea.lib.auth_modules import auth_internal
 from kallithea.lib.base import BaseController, render
 from kallithea.model.api_key import ApiKeyModel
 
@@ -62,19 +61,15 @@
     """REST Controller styled on the Atom Publishing Protocol"""
 
     @LoginRequired()
-    @HasPermissionAllDecorator('hg.admin')
+    @HasPermissionAnyDecorator('hg.admin')
     def __before__(self):
         super(UsersController, self).__before__()
         c.available_permissions = config['available_permissions']
-        c.EXTERN_TYPE_INTERNAL = kallithea.EXTERN_TYPE_INTERNAL
 
     def index(self, format='html'):
-        """GET /users: All items in the collection"""
-        # url('users')
-
-        c.users_list = User.query().order_by(User.username)\
-                        .filter(User.username != User.DEFAULT_USER)\
-                        .order_by(func.lower(User.username))\
+        c.users_list = User.query().order_by(User.username) \
+                        .filter(User.username != User.DEFAULT_USER) \
+                        .order_by(func.lower(User.username)) \
                         .all()
 
         users_data = []
@@ -119,19 +114,16 @@
         return render('admin/users/users.html')
 
     def create(self):
-        """POST /users: Create a new item"""
-        # url('users')
-        c.default_extern_type = auth_internal.KallitheaAuthPlugin.name
-        c.default_extern_name = auth_internal.KallitheaAuthPlugin.name
+        c.default_extern_type = User.DEFAULT_AUTH_TYPE
+        c.default_extern_name = ''
         user_model = UserModel()
         user_form = UserForm()()
         try:
             form_result = user_form.to_python(dict(request.POST))
             user = user_model.create(form_result)
-            usr = form_result['username']
-            action_logger(self.authuser, 'admin_created_user:%s' % usr,
+            action_logger(self.authuser, 'admin_created_user:%s' % user.username,
                           None, self.ip_addr, self.sa)
-            h.flash(h.literal(_('Created user %s') % h.link_to(h.escape(usr), url('edit_user', id=user.user_id))),
+            h.flash(_('Created user %s') % user.username,
                     category='success')
             Session().commit()
         except formencode.Invalid as errors:
@@ -148,23 +140,14 @@
             log.error(traceback.format_exc())
             h.flash(_('Error occurred during creation of user %s') \
                     % request.POST.get('username'), category='error')
-        return redirect(url('users'))
+        raise HTTPFound(location=url('edit_user', id=user.user_id))
 
     def new(self, format='html'):
-        """GET /users/new: Form to create a new item"""
-        # url('new_user')
-        c.default_extern_type = auth_internal.KallitheaAuthPlugin.name
-        c.default_extern_name = auth_internal.KallitheaAuthPlugin.name
+        c.default_extern_type = User.DEFAULT_AUTH_TYPE
+        c.default_extern_name = ''
         return render('admin/users/user_add.html')
 
     def update(self, id):
-        """PUT /users/id: Update an existing item"""
-        # Forms posted to this method should contain a hidden field:
-        #    <input type="hidden" name="_method" value="PUT" />
-        # Or using helpers:
-        #    h.form(url('update_user', id=ID),
-        #           method='put')
-        # url('user', id=ID)
         user_model = UserModel()
         user = user_model.get(id)
         _form = UserForm(edit=True, old_data={'user_id': id,
@@ -188,7 +171,6 @@
                 'create_repo_perm': user_model.has_perm(id,
                                                         'hg.create.repository'),
                 'fork_repo_perm': user_model.has_perm(id, 'hg.fork.repository'),
-                '_method': 'put'
             })
             return htmlfill.render(
                 self._render_edit_profile(user),
@@ -201,16 +183,9 @@
             log.error(traceback.format_exc())
             h.flash(_('Error occurred during update of user %s') \
                     % form_result.get('username'), category='error')
-        return redirect(url('edit_user', id=id))
+        raise HTTPFound(location=url('edit_user', id=id))
 
     def delete(self, id):
-        """DELETE /users/id: Delete an existing item"""
-        # Forms posted to this method should contain a hidden field:
-        #    <input type="hidden" name="_method" value="DELETE" />
-        # Or using helpers:
-        #    h.form(url('delete_user', id=ID),
-        #           method='delete')
-        # url('user', id=ID)
         usr = User.get_or_404(id)
         try:
             UserModel().delete(usr)
@@ -222,12 +197,7 @@
             log.error(traceback.format_exc())
             h.flash(_('An error occurred during deletion of user'),
                     category='error')
-        return redirect(url('users'))
-
-    def show(self, id, format='html'):
-        """GET /users/id: Show a specific item"""
-        # url('user', id=ID)
-        User.get_or_404(-1)
+        raise HTTPFound(location=url('users'))
 
     def _get_user_or_raise_if_default(self, id):
         try:
@@ -246,8 +216,6 @@
         return render('admin/users/user_edit.html')
 
     def edit(self, id, format='html'):
-        """GET /users/id/edit: Form to edit an existing item"""
-        # url('edit_user', id=ID)
         user = self._get_user_or_raise_if_default(id)
         defaults = user.get_dict()
 
@@ -260,7 +228,7 @@
     def edit_advanced(self, id):
         c.user = self._get_user_or_raise_if_default(id)
         c.active = 'advanced'
-        c.perm_user = AuthUser(user_id=id)
+        c.perm_user = AuthUser(dbuser=c.user)
         c.ip_addr = self.ip_addr
 
         umodel = UserModel()
@@ -306,25 +274,22 @@
         ApiKeyModel().create(c.user.user_id, description, lifetime)
         Session().commit()
         h.flash(_("API key successfully created"), category='success')
-        return redirect(url('edit_user_api_keys', id=c.user.user_id))
+        raise HTTPFound(location=url('edit_user_api_keys', id=c.user.user_id))
 
     def delete_api_key(self, id):
         c.user = self._get_user_or_raise_if_default(id)
 
         api_key = request.POST.get('del_api_key')
         if request.POST.get('del_api_key_builtin'):
-            user = User.get(c.user.user_id)
-            if user is not None:
-                user.api_key = generate_api_key()
-                Session().add(user)
-                Session().commit()
-                h.flash(_("API key successfully reset"), category='success')
+            c.user.api_key = generate_api_key()
+            Session().commit()
+            h.flash(_("API key successfully reset"), category='success')
         elif api_key:
             ApiKeyModel().delete(api_key, c.user.user_id)
             Session().commit()
             h.flash(_("API key successfully deleted"), category='success')
 
-        return redirect(url('edit_user_api_keys', id=c.user.user_id))
+        raise HTTPFound(location=url('edit_user_api_keys', id=c.user.user_id))
 
     def update_account(self, id):
         pass
@@ -332,7 +297,7 @@
     def edit_perms(self, id):
         c.user = self._get_user_or_raise_if_default(id)
         c.active = 'perms'
-        c.perm_user = AuthUser(user_id=id)
+        c.perm_user = AuthUser(dbuser=c.user)
         c.ip_addr = self.ip_addr
 
         umodel = UserModel()
@@ -350,8 +315,6 @@
             force_defaults=False)
 
     def update_perms(self, id):
-        """PUT /users_perm/id: Update an existing item"""
-        # url('user_perm', id=ID, method='put')
         user = self._get_user_or_raise_if_default(id)
 
         try:
@@ -360,11 +323,10 @@
 
             inherit_perms = form_result['inherit_default_permissions']
             user.inherit_default_permissions = inherit_perms
-            Session().add(user)
             user_model = UserModel()
 
-            defs = UserToPerm.query()\
-                .filter(UserToPerm.user == user)\
+            defs = UserToPerm.query() \
+                .filter(UserToPerm.user == user) \
                 .all()
             for ug in defs:
                 Session().delete(ug)
@@ -387,12 +349,12 @@
             log.error(traceback.format_exc())
             h.flash(_('An error occurred during permissions saving'),
                     category='error')
-        return redirect(url('edit_user_perms', id=id))
+        raise HTTPFound(location=url('edit_user_perms', id=id))
 
     def edit_emails(self, id):
         c.user = self._get_user_or_raise_if_default(id)
         c.active = 'emails'
-        c.user_email_map = UserEmailMap.query()\
+        c.user_email_map = UserEmailMap.query() \
             .filter(UserEmailMap.user == c.user).all()
 
         defaults = c.user.get_dict()
@@ -403,8 +365,6 @@
             force_defaults=False)
 
     def add_email(self, id):
-        """POST /user_emails:Add an existing item"""
-        # url('user_emails', id=ID, method='put')
         user = self._get_user_or_raise_if_default(id)
         email = request.POST.get('new_email')
         user_model = UserModel()
@@ -420,27 +380,25 @@
             log.error(traceback.format_exc())
             h.flash(_('An error occurred during email saving'),
                     category='error')
-        return redirect(url('edit_user_emails', id=id))
+        raise HTTPFound(location=url('edit_user_emails', id=id))
 
     def delete_email(self, id):
-        """DELETE /user_emails_delete/id: Delete an existing item"""
-        # url('user_emails_delete', id=ID, method='delete')
         user = self._get_user_or_raise_if_default(id)
         email_id = request.POST.get('del_email_id')
         user_model = UserModel()
         user_model.delete_extra_email(id, email_id)
         Session().commit()
         h.flash(_("Removed email from user"), category='success')
-        return redirect(url('edit_user_emails', id=id))
+        raise HTTPFound(location=url('edit_user_emails', id=id))
 
     def edit_ips(self, id):
         c.user = self._get_user_or_raise_if_default(id)
         c.active = 'ips'
-        c.user_ip_map = UserIpMap.query()\
+        c.user_ip_map = UserIpMap.query() \
             .filter(UserIpMap.user == c.user).all()
 
         c.inherit_default_ips = c.user.inherit_default_permissions
-        c.default_user_ip_map = UserIpMap.query()\
+        c.default_user_ip_map = UserIpMap.query() \
             .filter(UserIpMap.user == User.get_default_user()).all()
 
         defaults = c.user.get_dict()
@@ -451,9 +409,6 @@
             force_defaults=False)
 
     def add_ip(self, id):
-        """POST /user_ips:Add an existing item"""
-        # url('user_ips', id=ID, method='put')
-
         ip = request.POST.get('new_ip')
         user_model = UserModel()
 
@@ -470,12 +425,10 @@
                     category='error')
 
         if 'default_user' in request.POST:
-            return redirect(url('admin_permissions_ips'))
-        return redirect(url('edit_user_ips', id=id))
+            raise HTTPFound(location=url('admin_permissions_ips'))
+        raise HTTPFound(location=url('edit_user_ips', id=id))
 
     def delete_ip(self, id):
-        """DELETE /user_ips_delete/id: Delete an existing item"""
-        # url('user_ips_delete', id=ID, method='delete')
         ip_id = request.POST.get('del_ip_id')
         user_model = UserModel()
         user_model.delete_extra_ip(id, ip_id)
@@ -483,5 +436,5 @@
         h.flash(_("Removed IP address from user whitelist"), category='success')
 
         if 'default_user' in request.POST:
-            return redirect(url('admin_permissions_ips'))
-        return redirect(url('edit_user_ips', id=id))
+            raise HTTPFound(location=url('admin_permissions_ips'))
+        raise HTTPFound(location=url('edit_user_ips', id=id))
--- a/kallithea/controllers/api/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/api/__init__.py	Fri Nov 18 01:11:13 2016 +0100
@@ -30,15 +30,17 @@
 import types
 import traceback
 import time
+import itertools
 
 from paste.response import replace_header
 from pylons.controllers import WSGIController
+from pylons import request
 
 from webob.exc import HTTPError
 
 from kallithea.model.db import User
 from kallithea.model import meta
-from kallithea.lib.compat import izip_longest, json
+from kallithea.lib.compat import json
 from kallithea.lib.auth import AuthUser
 from kallithea.lib.base import _get_ip_addr as _get_ip, _get_access_path
 from kallithea.lib.utils2 import safe_unicode, safe_str
@@ -183,26 +185,18 @@
         default_empty = types.NotImplementedType
 
         # kw arguments required by this method
-        func_kwargs = dict(izip_longest(reversed(arglist), reversed(defaults),
-                                        fillvalue=default_empty))
+        func_kwargs = dict(itertools.izip_longest(reversed(arglist), reversed(defaults),
+                                                  fillvalue=default_empty))
 
         # this is little trick to inject logged in user for
         # perms decorators to work they expect the controller class to have
         # authuser attribute set
-        self.authuser = auth_u
+        self.authuser = request.user = auth_u
 
         # This attribute will need to be first param of a method that uses
         # api_key, which is translated to instance of user at that name
         USER_SESSION_ATTR = 'apiuser'
 
-        if USER_SESSION_ATTR not in arglist:
-            return jsonrpc_error(
-                retid=self._req_id,
-                message='This method [%s] does not support '
-                         'authentication (missing %s param)' % (
-                                    self._func.__name__, USER_SESSION_ATTR)
-            )
-
         # get our arglist and check if we provided them as args
         for arg, default in func_kwargs.iteritems():
             if arg == USER_SESSION_ATTR:
@@ -220,7 +214,15 @@
                     )
                 )
 
-        self._rpc_args = {USER_SESSION_ATTR: u}
+        extra = set(self._request_params).difference(func_kwargs)
+        if extra:
+                return jsonrpc_error(
+                    retid=self._req_id,
+                    message=('Unknown %s arg in JSON DATA' %
+                             ', '.join('`%s`' % arg for arg in extra)),
+                )
+
+        self._rpc_args = {}
 
         self._rpc_args.update(self._request_params)
 
--- a/kallithea/controllers/api/api.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/api/api.py	Fri Nov 18 01:11:13 2016 +0100
@@ -25,18 +25,16 @@
 :license: GPLv3, see LICENSE.md for more details.
 """
 
-
 import time
 import traceback
 import logging
 from sqlalchemy import or_
 
-from kallithea import EXTERN_TYPE_INTERNAL
 from kallithea.controllers.api import JSONRPCController, JSONRPCError
 from kallithea.lib.auth import (
-    PasswordGenerator, AuthUser, HasPermissionAllDecorator,
-    HasPermissionAnyDecorator, HasPermissionAnyApi, HasRepoPermissionAnyApi,
-    HasRepoGroupPermissionAnyApi, HasUserGroupPermissionAny)
+    PasswordGenerator, AuthUser, HasPermissionAnyDecorator,
+    HasPermissionAnyDecorator, HasPermissionAny, HasRepoPermissionAny,
+    HasRepoGroupPermissionAny, HasUserGroupPermissionAny)
 from kallithea.lib.utils import map_groups, repo2db_mapper
 from kallithea.lib.utils2 import (
     str2bool, time_to_datetime, safe_int, Optional, OAttr)
@@ -49,7 +47,7 @@
 from kallithea.model.gist import GistModel
 from kallithea.model.db import (
     Repository, Setting, UserIpMap, Permission, User, Gist,
-    RepoGroup)
+    RepoGroup, UserGroup)
 from kallithea.lib.compat import json
 from kallithea.lib.exceptions import (
     DefaultUserException, UserGroupsAssignedException)
@@ -147,32 +145,28 @@
     """
     API Controller
 
-    Each method takes USER as first argument. This is then, based on given
-    API_KEY propagated as instance of user object who's making the call.
+    The authenticated user can be found as self.authuser.
 
-    example function::
+    Example function::
 
-        def func(apiuser,arg1, arg2,...):
+        def func(arg1, arg2,...):
             pass
 
     Each function should also **raise** JSONRPCError for any
     errors that happens.
-
     """
 
-    @HasPermissionAllDecorator('hg.admin')
-    def test(self, apiuser, args):
+    @HasPermissionAnyDecorator('hg.admin')
+    def test(self, args):
         return args
 
-    @HasPermissionAllDecorator('hg.admin')
-    def pull(self, apiuser, repoid):
+    @HasPermissionAnyDecorator('hg.admin')
+    def pull(self, repoid):
         """
         Triggers a pull from remote location on given repo. Can be used to
         automatically keep remote repos up to date. This command can be executed
         only using api_key belonging to user with admin rights
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repoid: repository name or repository id
         :type repoid: str or int
 
@@ -210,16 +204,14 @@
                 'Unable to pull changes from `%s`' % repo.repo_name
             )
 
-    @HasPermissionAllDecorator('hg.admin')
-    def rescan_repos(self, apiuser, remove_obsolete=Optional(False)):
+    @HasPermissionAnyDecorator('hg.admin')
+    def rescan_repos(self, remove_obsolete=Optional(False)):
         """
         Triggers rescan repositories action. If remove_obsolete is set
         than also delete repos that are in database but not in the filesystem.
         aka "clean zombies". This command can be executed only using api_key
         belonging to user with admin rights.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param remove_obsolete: deletes repositories from
             database that are not found on the filesystem
         :type remove_obsolete: Optional(bool)
@@ -254,14 +246,12 @@
                 'Error occurred during rescan repositories action'
             )
 
-    def invalidate_cache(self, apiuser, repoid):
+    def invalidate_cache(self, repoid):
         """
         Invalidate cache for repository.
         This command can be executed only using api_key belonging to user with admin
         rights or regular user that have write or admin or write access to repository.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repoid: repository name or repository id
         :type repoid: str or int
 
@@ -284,11 +274,11 @@
 
         """
         repo = get_repo_or_error(repoid)
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # check if we have admin permission for this repo !
-            if not HasRepoPermissionAnyApi('repository.admin',
-                                           'repository.write')(
-                    user=apiuser, repo_name=repo.repo_name):
+            if not HasRepoPermissionAny('repository.admin',
+                                        'repository.write')(
+                    repo_name=repo.repo_name):
                 raise JSONRPCError('repository `%s` does not exist' % (repoid,))
 
         try:
@@ -304,7 +294,7 @@
             )
 
     # permission check inside
-    def lock(self, apiuser, repoid, locked=Optional(None),
+    def lock(self, repoid, locked=Optional(None),
              userid=Optional(OAttr('apiuser'))):
         """
         Set locking state on given repository by given user. If userid param
@@ -314,8 +304,6 @@
         to user with admin rights or regular user that have admin or write
         access to repository.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repoid: repository name or repository id
         :type repoid: str or int
         :param locked: lock state to be set
@@ -350,14 +338,13 @@
 
         """
         repo = get_repo_or_error(repoid)
-        if HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if HasPermissionAny('hg.admin')():
             pass
-        elif HasRepoPermissionAnyApi('repository.admin',
-                                     'repository.write')(user=apiuser,
-                                                         repo_name=repo.repo_name):
+        elif HasRepoPermissionAny('repository.admin',
+                                  'repository.write')(repo_name=repo.repo_name):
             # make sure normal user does not pass someone else userid,
             # he is not allowed to do that
-            if not isinstance(userid, Optional) and userid != apiuser.user_id:
+            if not isinstance(userid, Optional) and userid != self.authuser.user_id:
                 raise JSONRPCError(
                     'userid is not the same as your user'
                 )
@@ -365,7 +352,7 @@
             raise JSONRPCError('repository `%s` does not exist' % (repoid,))
 
         if isinstance(userid, Optional):
-            userid = apiuser.user_id
+            userid = self.authuser.user_id
 
         user = get_user_or_error(userid)
 
@@ -423,14 +410,12 @@
                     'Error occurred locking repository `%s`' % repo.repo_name
                 )
 
-    def get_locks(self, apiuser, userid=Optional(OAttr('apiuser'))):
+    def get_locks(self, userid=Optional(OAttr('apiuser'))):
         """
         Get all repositories with locks for given userid, if
         this command is run by non-admin account userid is set to user
         who is calling this method, thus returning locks for himself.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param userid: User to get locks for
         :type userid: Optional(str or int)
 
@@ -443,10 +428,10 @@
           error :  null
         """
 
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # make sure normal user does not pass someone else userid,
             # he is not allowed to do that
-            if not isinstance(userid, Optional) and userid != apiuser.user_id:
+            if not isinstance(userid, Optional) and userid != self.authuser.user_id:
                 raise JSONRPCError(
                     'userid is not the same as your user'
                 )
@@ -458,7 +443,7 @@
             user = get_user_or_error(userid)
 
         # show all locks
-        for r in Repository.getAll():
+        for r in Repository.query():
             userid, time_ = r.locked
             if time_:
                 _api_data = r.get_api_data()
@@ -471,8 +456,8 @@
 
         return ret
 
-    @HasPermissionAllDecorator('hg.admin')
-    def get_ip(self, apiuser, userid=Optional(OAttr('apiuser'))):
+    @HasPermissionAnyDecorator('hg.admin')
+    def get_ip(self, userid=Optional(OAttr('apiuser'))):
         """
         Shows IP address as seen from Kallithea server, together with all
         defined IP addresses for given user. If userid is not passed data is
@@ -480,8 +465,6 @@
         This command can be executed only using api_key belonging to user with
         admin rights.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param userid: username to show ips for
         :type userid: Optional(str or int)
 
@@ -501,7 +484,7 @@
 
         """
         if isinstance(userid, Optional):
-            userid = apiuser.user_id
+            userid = self.authuser.user_id
         user = get_user_or_error(userid)
         ips = UserIpMap.query().filter(UserIpMap.user == user).all()
         return dict(
@@ -512,13 +495,11 @@
     # alias for old
     show_ip = get_ip
 
-    @HasPermissionAllDecorator('hg.admin')
-    def get_server_info(self, apiuser):
+    @HasPermissionAnyDecorator('hg.admin')
+    def get_server_info(self):
         """
         return server info, including Kallithea version and installed packages
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
 
         OUTPUT::
 
@@ -533,7 +514,7 @@
         """
         return Setting.get_server_info()
 
-    def get_user(self, apiuser, userid=Optional(OAttr('apiuser'))):
+    def get_user(self, userid=Optional(OAttr('apiuser'))):
         """
         Gets a user by username or user_id, Returns empty result if user is
         not found. If userid param is skipped it is set to id of user who is
@@ -541,8 +522,6 @@
         belonging to user with admin rights, or regular users that cannot
         specify different userid than theirs
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param userid: user to get data for
         :type userid: Optional(str or int)
 
@@ -577,30 +556,28 @@
             error:  null
 
         """
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # make sure normal user does not pass someone else userid,
             # he is not allowed to do that
-            if not isinstance(userid, Optional) and userid != apiuser.user_id:
+            if not isinstance(userid, Optional) and userid != self.authuser.user_id:
                 raise JSONRPCError(
                     'userid is not the same as your user'
                 )
 
         if isinstance(userid, Optional):
-            userid = apiuser.user_id
+            userid = self.authuser.user_id
 
         user = get_user_or_error(userid)
         data = user.get_api_data()
         data['permissions'] = AuthUser(user_id=user.user_id).permissions
         return data
 
-    @HasPermissionAllDecorator('hg.admin')
-    def get_users(self, apiuser):
+    @HasPermissionAnyDecorator('hg.admin')
+    def get_users(self):
         """
         Lists all existing users. This command can be executed only using api_key
         belonging to user with admin rights.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
 
         OUTPUT::
 
@@ -617,18 +594,16 @@
             result.append(user.get_api_data())
         return result
 
-    @HasPermissionAllDecorator('hg.admin')
-    def create_user(self, apiuser, username, email, password=Optional(''),
+    @HasPermissionAnyDecorator('hg.admin')
+    def create_user(self, username, email, password=Optional(''),
                     firstname=Optional(''), lastname=Optional(''),
                     active=Optional(True), admin=Optional(False),
-                    extern_name=Optional(EXTERN_TYPE_INTERNAL),
-                    extern_type=Optional(EXTERN_TYPE_INTERNAL)):
+                    extern_type=Optional(User.DEFAULT_AUTH_TYPE),
+                    extern_name=Optional('')):
         """
         Creates new user. Returns new user object. This command can
         be executed only using api_key belonging to user with admin rights.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param username: new username
         :type username: str or int
         :param email: email
@@ -675,13 +650,9 @@
         if User.get_by_username(username):
             raise JSONRPCError("user `%s` already exist" % (username,))
 
-        if User.get_by_email(email, case_insensitive=True):
+        if User.get_by_email(email):
             raise JSONRPCError("email `%s` already exist" % (email,))
 
-        if Optional.extract(extern_name):
-            # generate temporary password if user is external
-            password = PasswordGenerator().gen_password(length=8)
-
         try:
             user = UserModel().create_or_update(
                 username=Optional.extract(username),
@@ -703,18 +674,16 @@
             log.error(traceback.format_exc())
             raise JSONRPCError('failed to create user `%s`' % (username,))
 
-    @HasPermissionAllDecorator('hg.admin')
-    def update_user(self, apiuser, userid, username=Optional(None),
-                    email=Optional(None),password=Optional(None),
+    @HasPermissionAnyDecorator('hg.admin')
+    def update_user(self, userid, username=Optional(None),
+                    email=Optional(None), password=Optional(None),
                     firstname=Optional(None), lastname=Optional(None),
                     active=Optional(None), admin=Optional(None),
-                    extern_type=Optional(None), extern_name=Optional(None),):
+                    extern_type=Optional(None), extern_name=Optional(None)):
         """
         updates given user if such user exists. This command can
         be executed only using api_key belonging to user with admin rights.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param userid: userid to update
         :type userid: str or int
         :param username: new username
@@ -786,14 +755,12 @@
             log.error(traceback.format_exc())
             raise JSONRPCError('failed to update user `%s`' % (userid,))
 
-    @HasPermissionAllDecorator('hg.admin')
-    def delete_user(self, apiuser, userid):
+    @HasPermissionAnyDecorator('hg.admin')
+    def delete_user(self, userid):
         """
         deletes given user if such user exists. This command can
         be executed only using api_key belonging to user with admin rights.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param userid: user to delete
         :type userid: str or int
 
@@ -831,14 +798,12 @@
                                % (user.user_id, user.username))
 
     # permission check inside
-    def get_user_group(self, apiuser, usergroupid):
+    def get_user_group(self, usergroupid):
         """
         Gets an existing user group. This command can be executed only using api_key
         belonging to user with admin rights or user who has at least
         read access to user group.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param usergroupid: id of user_group to edit
         :type usergroupid: str or int
 
@@ -856,25 +821,23 @@
 
         """
         user_group = get_user_group_or_error(usergroupid)
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # check if we have at least read permission for this user group !
             _perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin',)
             if not HasUserGroupPermissionAny(*_perms)(
-                    user=apiuser, user_group_name=user_group.users_group_name):
+                    user_group_name=user_group.users_group_name):
                 raise JSONRPCError('user group `%s` does not exist' % (usergroupid,))
 
         data = user_group.get_api_data()
         return data
 
     # permission check inside
-    def get_user_groups(self, apiuser):
+    def get_user_groups(self):
         """
         Lists all existing user groups. This command can be executed only using
         api_key belonging to user with admin rights or user who has at least
         read access to user group.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
 
         OUTPUT::
 
@@ -885,22 +848,19 @@
 
         result = []
         _perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin',)
-        extras = {'user': apiuser}
-        for user_group in UserGroupList(UserGroupModel().get_all(),
-                                        perm_set=_perms, extra_kwargs=extras):
+        for user_group in UserGroupList(UserGroup.query().all(),
+                                        perm_set=_perms):
             result.append(user_group.get_api_data())
         return result
 
     @HasPermissionAnyDecorator('hg.admin', 'hg.usergroup.create.true')
-    def create_user_group(self, apiuser, group_name, description=Optional(''),
+    def create_user_group(self, group_name, description=Optional(''),
                           owner=Optional(OAttr('apiuser')), active=Optional(True)):
         """
         Creates new user group. This command can be executed only using api_key
         belonging to user with admin rights or an user who has create user group
         permission
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param group_name: name of new user group
         :type group_name: str
         :param description: group description
@@ -936,7 +896,7 @@
 
         try:
             if isinstance(owner, Optional):
-                owner = apiuser.user_id
+                owner = self.authuser.user_id
 
             owner = get_user_or_error(owner)
             active = Optional.extract(active)
@@ -953,15 +913,13 @@
             raise JSONRPCError('failed to create group `%s`' % (group_name,))
 
     # permission check inside
-    def update_user_group(self, apiuser, usergroupid, group_name=Optional(''),
+    def update_user_group(self, usergroupid, group_name=Optional(''),
                           description=Optional(''), owner=Optional(None),
                           active=Optional(True)):
         """
         Updates given usergroup.  This command can be executed only using api_key
         belonging to user with admin rights or an admin of given user group
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param usergroupid: id of user group to update
         :type usergroupid: str or int
         :param group_name: name of new user group
@@ -992,11 +950,11 @@
 
         """
         user_group = get_user_group_or_error(usergroupid)
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # check if we have admin permission for this user group !
             _perms = ('usergroup.admin',)
             if not HasUserGroupPermissionAny(*_perms)(
-                    user=apiuser, user_group_name=user_group.users_group_name):
+                    user_group_name=user_group.users_group_name):
                 raise JSONRPCError('user group `%s` does not exist' % (usergroupid,))
 
         if not isinstance(owner, Optional):
@@ -1005,7 +963,7 @@
         updates = {}
         store_update(updates, group_name, 'users_group_name')
         store_update(updates, description, 'user_group_description')
-        store_update(updates, owner, 'user')
+        store_update(updates, owner, 'owner')
         store_update(updates, active, 'users_group_active')
         try:
             UserGroupModel().update(user_group, updates)
@@ -1020,14 +978,12 @@
             raise JSONRPCError('failed to update user group `%s`' % (usergroupid,))
 
     # permission check inside
-    def delete_user_group(self, apiuser, usergroupid):
+    def delete_user_group(self, usergroupid):
         """
         Delete given user group by user group id or name.
         This command can be executed only using api_key
         belonging to user with admin rights or an admin of given user group
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param usergroupid:
         :type usergroupid: int
 
@@ -1051,11 +1007,11 @@
 
         """
         user_group = get_user_group_or_error(usergroupid)
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # check if we have admin permission for this user group !
             _perms = ('usergroup.admin',)
             if not HasUserGroupPermissionAny(*_perms)(
-                    user=apiuser, user_group_name=user_group.users_group_name):
+                    user_group_name=user_group.users_group_name):
                 raise JSONRPCError('user group `%s` does not exist' % (usergroupid,))
 
         try:
@@ -1074,17 +1030,15 @@
             raise JSONRPCError('failed to delete user group ID:%s %s' %
                                (user_group.users_group_id,
                                 user_group.users_group_name)
-            )
+                               )
 
     # permission check inside
-    def add_user_to_user_group(self, apiuser, usergroupid, userid):
+    def add_user_to_user_group(self, usergroupid, userid):
         """
         Adds a user to a user group. If user exists in that group success will be
         `false`. This command can be executed only using api_key
         belonging to user with admin rights  or an admin of given user group
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param usergroupid:
         :type usergroupid: int
         :param userid:
@@ -1112,11 +1066,11 @@
         """
         user = get_user_or_error(userid)
         user_group = get_user_group_or_error(usergroupid)
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # check if we have admin permission for this user group !
             _perms = ('usergroup.admin',)
             if not HasUserGroupPermissionAny(*_perms)(
-                    user=apiuser, user_group_name=user_group.users_group_name):
+                    user_group_name=user_group.users_group_name):
                 raise JSONRPCError('user group `%s` does not exist' % (usergroupid,))
 
         try:
@@ -1141,14 +1095,12 @@
             )
 
     # permission check inside
-    def remove_user_from_user_group(self, apiuser, usergroupid, userid):
+    def remove_user_from_user_group(self, usergroupid, userid):
         """
         Removes a user from a user group. If user is not in given group success will
         be `false`. This command can be executed only
         using api_key belonging to user with admin rights or an admin of given user group
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param usergroupid:
         :param userid:
 
@@ -1166,11 +1118,11 @@
         """
         user = get_user_or_error(userid)
         user_group = get_user_group_or_error(usergroupid)
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # check if we have admin permission for this user group !
             _perms = ('usergroup.admin',)
             if not HasUserGroupPermissionAny(*_perms)(
-                    user=apiuser, user_group_name=user_group.users_group_name):
+                    user_group_name=user_group.users_group_name):
                 raise JSONRPCError('user group `%s` does not exist' % (usergroupid,))
 
         try:
@@ -1190,15 +1142,13 @@
             )
 
     # permission check inside
-    def get_repo(self, apiuser, repoid):
+    def get_repo(self, repoid):
         """
         Gets an existing repository by it's name or repository_id. Members will return
         either users_group or user associated to that repository. This command can be
         executed only using api_key belonging to user with admin
         rights or regular user that have at least read access to repository.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repoid: repository name or repository id
         :type repoid: str or int
 
@@ -1251,10 +1201,10 @@
         """
         repo = get_repo_or_error(repoid)
 
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # check if we have admin permission for this repo !
             perms = ('repository.admin', 'repository.write', 'repository.read')
-            if not HasRepoPermissionAnyApi(*perms)(user=apiuser, repo_name=repo.repo_name):
+            if not HasRepoPermissionAny(*perms)(repo_name=repo.repo_name):
                 raise JSONRPCError('repository `%s` does not exist' % (repoid,))
 
         members = []
@@ -1288,14 +1238,12 @@
         return data
 
     # permission check inside
-    def get_repos(self, apiuser):
+    def get_repos(self):
         """
         Lists all existing repositories. This command can be executed only using
         api_key belonging to user with admin rights or regular user that have
         admin, write or read access to repository.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
 
         OUTPUT::
 
@@ -1321,17 +1269,17 @@
             error:  null
         """
         result = []
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
-            repos = RepoModel().get_all_user_repos(user=apiuser)
+        if not HasPermissionAny('hg.admin')():
+            repos = RepoModel().get_all_user_repos(user=self.authuser.user_id)
         else:
-            repos = RepoModel().get_all()
+            repos = Repository.query()
 
         for repo in repos:
             result.append(repo.get_api_data())
         return result
 
     # permission check inside
-    def get_repo_nodes(self, apiuser, repoid, revision, root_path,
+    def get_repo_nodes(self, repoid, revision, root_path,
                        ret_type=Optional('all')):
         """
         returns a list of nodes and it's children in a flat list for a given path
@@ -1339,8 +1287,6 @@
         `dirs`.  This command can be executed only using api_key belonging to
         user with admin rights or regular user that have at least read access to repository.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repoid: repository name or repository id
         :type repoid: str or int
         :param revision: revision for which listing should be done
@@ -1365,10 +1311,10 @@
         """
         repo = get_repo_or_error(repoid)
 
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # check if we have admin permission for this repo !
             perms = ('repository.admin', 'repository.write', 'repository.read')
-            if not HasRepoPermissionAnyApi(*perms)(user=apiuser, repo_name=repo.repo_name):
+            if not HasRepoPermissionAny(*perms)(repo_name=repo.repo_name):
                 raise JSONRPCError('repository `%s` does not exist' % (repoid,))
 
         ret_type = Optional.extract(ret_type)
@@ -1392,7 +1338,7 @@
             )
 
     @HasPermissionAnyDecorator('hg.admin', 'hg.create.repository')
-    def create_repo(self, apiuser, repo_name, owner=Optional(OAttr('apiuser')),
+    def create_repo(self, repo_name, owner=Optional(OAttr('apiuser')),
                     repo_type=Optional('hg'), description=Optional(''),
                     private=Optional(False), clone_uri=Optional(None),
                     landing_rev=Optional('rev:tip'),
@@ -1408,8 +1354,6 @@
         belonging to user with admin rights or regular user that have create
         repository permission. Regular users cannot specify owner parameter
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repo_name: repository name
         :type repo_name: str
         :param owner: user_id or username
@@ -1453,14 +1397,14 @@
           }
 
         """
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             if not isinstance(owner, Optional):
-                #forbid setting owner for non-admins
+                # forbid setting owner for non-admins
                 raise JSONRPCError(
                     'Only Kallithea admin can specify `owner` param'
                 )
         if isinstance(owner, Optional):
-            owner = apiuser.user_id
+            owner = self.authuser.user_id
 
         owner = get_user_or_error(owner)
 
@@ -1505,10 +1449,7 @@
             )
 
             task = RepoModel().create(form_data=data, cur_user=owner)
-            from celery.result import BaseAsyncResult
-            task_id = None
-            if isinstance(task, BaseAsyncResult):
-                task_id = task.task_id
+            task_id = task.task_id
             # no commit, it's done in RepoModel, or async via celery
             return dict(
                 msg="Created new repository `%s`" % (repo_name,),
@@ -1522,7 +1463,7 @@
                 'failed to create repository `%s`' % (repo_name,))
 
     # permission check inside
-    def update_repo(self, apiuser, repoid, name=Optional(None),
+    def update_repo(self, repoid, name=Optional(None),
                     owner=Optional(OAttr('apiuser')),
                     group=Optional(None),
                     description=Optional(''), private=Optional(False),
@@ -1534,8 +1475,6 @@
         """
         Updates repo
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repoid: repository name or repository id
         :type repoid: str or int
         :param name:
@@ -1550,19 +1489,18 @@
         :param enable_downloads:
         """
         repo = get_repo_or_error(repoid)
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # check if we have admin permission for this repo !
-            if not HasRepoPermissionAnyApi('repository.admin')(user=apiuser,
-                                                               repo_name=repo.repo_name):
+            if not HasRepoPermissionAny('repository.admin')(repo_name=repo.repo_name):
                 raise JSONRPCError('repository `%s` does not exist' % (repoid,))
 
             if (name != repo.repo_name and
-                not HasPermissionAnyApi('hg.create.repository')(user=apiuser)
+                not HasPermissionAny('hg.create.repository')()
                 ):
                 raise JSONRPCError('no permission to create (or move) repositories')
 
             if not isinstance(owner, Optional):
-                #forbid setting owner for non-admins
+                # forbid setting owner for non-admins
                 raise JSONRPCError(
                     'Only Kallithea admin can specify `owner` param'
                 )
@@ -1575,7 +1513,7 @@
         try:
             store_update(updates, name, 'repo_name')
             store_update(updates, repo_group, 'repo_group')
-            store_update(updates, owner, 'user')
+            store_update(updates, owner, 'owner')
             store_update(updates, description, 'repo_description')
             store_update(updates, private, 'repo_private')
             store_update(updates, clone_uri, 'clone_uri')
@@ -1595,7 +1533,7 @@
             raise JSONRPCError('failed to update repo `%s`' % repoid)
 
     @HasPermissionAnyDecorator('hg.admin', 'hg.fork.repository')
-    def fork_repo(self, apiuser, repoid, fork_name,
+    def fork_repo(self, repoid, fork_name,
                   owner=Optional(OAttr('apiuser')),
                   description=Optional(''), copy_permissions=Optional(False),
                   private=Optional(False), landing_rev=Optional('rev:tip')):
@@ -1606,8 +1544,6 @@
         user with admin rights or regular user that have fork permission, and at least
         read access to forking repository. Regular users cannot specify owner parameter.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repoid: repository name or repository id
         :type repoid: str or int
         :param fork_name:
@@ -1650,25 +1586,24 @@
             type_ = 'fork' if _repo.fork else 'repo'
             raise JSONRPCError("%s `%s` already exist" % (type_, fork_name))
 
-        if HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if HasPermissionAny('hg.admin')():
             pass
-        elif HasRepoPermissionAnyApi('repository.admin',
-                                     'repository.write',
-                                     'repository.read')(user=apiuser,
-                                                        repo_name=repo.repo_name):
+        elif HasRepoPermissionAny('repository.admin',
+                                  'repository.write',
+                                  'repository.read')(repo_name=repo.repo_name):
             if not isinstance(owner, Optional):
-                #forbid setting owner for non-admins
+                # forbid setting owner for non-admins
                 raise JSONRPCError(
                     'Only Kallithea admin can specify `owner` param'
                 )
 
-            if not HasPermissionAnyApi('hg.create.repository')(user=apiuser):
+            if not HasPermissionAny('hg.create.repository')():
                 raise JSONRPCError('no permission to create repositories')
         else:
             raise JSONRPCError('repository `%s` does not exist' % (repoid,))
 
         if isinstance(owner, Optional):
-            owner = apiuser.user_id
+            owner = self.authuser.user_id
 
         owner = get_user_or_error(owner)
 
@@ -1691,10 +1626,7 @@
             )
             task = RepoModel().create_fork(form_data, cur_user=owner)
             # no commit, it's done in RepoModel, or async via celery
-            from celery.result import BaseAsyncResult
-            task_id = None
-            if isinstance(task, BaseAsyncResult):
-                task_id = task.task_id
+            task_id = task.task_id
             return dict(
                 msg='Created fork of `%s` as `%s`' % (repo.repo_name,
                                                       fork_name),
@@ -1710,15 +1642,13 @@
             )
 
     # permission check inside
-    def delete_repo(self, apiuser, repoid, forks=Optional('')):
+    def delete_repo(self, repoid, forks=Optional('')):
         """
         Deletes a repository. This command can be executed only using api_key belonging
         to user with admin rights or regular user that have admin access to repository.
         When `forks` param is set it's possible to detach or delete forks of deleting
         repository
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repoid: repository name or repository id
         :type repoid: str or int
         :param forks: `detach` or `delete`, what do do with attached forks for repo
@@ -1736,10 +1666,9 @@
         """
         repo = get_repo_or_error(repoid)
 
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # check if we have admin permission for this repo !
-            if not HasRepoPermissionAnyApi('repository.admin')(user=apiuser,
-                                                           repo_name=repo.repo_name):
+            if not HasRepoPermissionAny('repository.admin')(repo_name=repo.repo_name):
                 raise JSONRPCError('repository `%s` does not exist' % (repoid,))
 
         try:
@@ -1768,15 +1697,13 @@
                 'failed to delete repository `%s`' % (repo.repo_name,)
             )
 
-    @HasPermissionAllDecorator('hg.admin')
-    def grant_user_permission(self, apiuser, repoid, userid, perm):
+    @HasPermissionAnyDecorator('hg.admin')
+    def grant_user_permission(self, repoid, userid, perm):
         """
         Grant permission for user on given repository, or update existing one
         if found. This command can be executed only using api_key belonging to user
         with admin rights.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repoid: repository name or repository id
         :type repoid: str or int
         :param userid:
@@ -1815,14 +1742,12 @@
                 )
             )
 
-    @HasPermissionAllDecorator('hg.admin')
-    def revoke_user_permission(self, apiuser, repoid, userid):
+    @HasPermissionAnyDecorator('hg.admin')
+    def revoke_user_permission(self, repoid, userid):
         """
         Revoke permission for user on given repository. This command can be executed
         only using api_key belonging to user with admin rights.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repoid: repository name or repository id
         :type repoid: str or int
         :param userid:
@@ -1858,14 +1783,12 @@
             )
 
     # permission check inside
-    def grant_user_group_permission(self, apiuser, repoid, usergroupid, perm):
+    def grant_user_group_permission(self, repoid, usergroupid, perm):
         """
         Grant permission for user group on given repository, or update
         existing one if found. This command can be executed only using
         api_key belonging to user with admin rights.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repoid: repository name or repository id
         :type repoid: str or int
         :param usergroupid: id of usergroup
@@ -1895,17 +1818,17 @@
         repo = get_repo_or_error(repoid)
         perm = get_perm_or_error(perm)
         user_group = get_user_group_or_error(usergroupid)
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # check if we have admin permission for this repo !
             _perms = ('repository.admin',)
-            if not HasRepoPermissionAnyApi(*_perms)(
-                    user=apiuser, repo_name=repo.repo_name):
+            if not HasRepoPermissionAny(*_perms)(
+                    repo_name=repo.repo_name):
                 raise JSONRPCError('repository `%s` does not exist' % (repoid,))
 
             # check if we have at least read permission for this user group !
             _perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin',)
             if not HasUserGroupPermissionAny(*_perms)(
-                    user=apiuser, user_group_name=user_group.users_group_name):
+                    user_group_name=user_group.users_group_name):
                 raise JSONRPCError('user group `%s` does not exist' % (usergroupid,))
 
         try:
@@ -1931,13 +1854,11 @@
             )
 
     # permission check inside
-    def revoke_user_group_permission(self, apiuser, repoid, usergroupid):
+    def revoke_user_group_permission(self, repoid, usergroupid):
         """
         Revoke permission for user group on given repository. This command can be
         executed only using api_key belonging to user with admin rights.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repoid: repository name or repository id
         :type repoid: str or int
         :param usergroupid:
@@ -1953,17 +1874,17 @@
         """
         repo = get_repo_or_error(repoid)
         user_group = get_user_group_or_error(usergroupid)
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # check if we have admin permission for this repo !
             _perms = ('repository.admin',)
-            if not HasRepoPermissionAnyApi(*_perms)(
-                    user=apiuser, repo_name=repo.repo_name):
+            if not HasRepoPermissionAny(*_perms)(
+                    repo_name=repo.repo_name):
                 raise JSONRPCError('repository `%s` does not exist' % (repoid,))
 
             # check if we have at least read permission for this user group !
             _perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin',)
             if not HasUserGroupPermissionAny(*_perms)(
-                    user=apiuser, user_group_name=user_group.users_group_name):
+                    user_group_name=user_group.users_group_name):
                 raise JSONRPCError('user group `%s` does not exist' % (usergroupid,))
 
         try:
@@ -1986,14 +1907,12 @@
                 )
             )
 
-    @HasPermissionAllDecorator('hg.admin')
-    def get_repo_group(self, apiuser, repogroupid):
+    @HasPermissionAnyDecorator('hg.admin')
+    def get_repo_group(self, repogroupid):
         """
         Returns given repo group together with permissions, and repositories
         inside the group
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repogroupid: id/name of repository group
         :type repogroupid: str or int
         """
@@ -2024,21 +1943,19 @@
         data["members"] = members
         return data
 
-    @HasPermissionAllDecorator('hg.admin')
-    def get_repo_groups(self, apiuser):
+    @HasPermissionAnyDecorator('hg.admin')
+    def get_repo_groups(self):
         """
         Returns all repository groups
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         """
         result = []
-        for repo_group in RepoGroupModel().get_all():
+        for repo_group in RepoGroup.query():
             result.append(repo_group.get_api_data())
         return result
 
-    @HasPermissionAllDecorator('hg.admin')
-    def create_repo_group(self, apiuser, group_name, description=Optional(''),
+    @HasPermissionAnyDecorator('hg.admin')
+    def create_repo_group(self, group_name, description=Optional(''),
                           owner=Optional(OAttr('apiuser')),
                           parent=Optional(None),
                           copy_permissions=Optional(False)):
@@ -2046,8 +1963,6 @@
         Creates a repository group. This command can be executed only using
         api_key belonging to user with admin rights.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param group_name:
         :type group_name:
         :param description:
@@ -2081,7 +1996,7 @@
             raise JSONRPCError("repo group `%s` already exist" % (group_name,))
 
         if isinstance(owner, Optional):
-            owner = apiuser.user_id
+            owner = self.authuser.user_id
         group_description = Optional.extract(description)
         parent_group = Optional.extract(parent)
         if not isinstance(parent, Optional):
@@ -2106,8 +2021,8 @@
             log.error(traceback.format_exc())
             raise JSONRPCError('failed to create repo group `%s`' % (group_name,))
 
-    @HasPermissionAllDecorator('hg.admin')
-    def update_repo_group(self, apiuser, repogroupid, group_name=Optional(''),
+    @HasPermissionAnyDecorator('hg.admin')
+    def update_repo_group(self, repogroupid, group_name=Optional(''),
                           description=Optional(''),
                           owner=Optional(OAttr('apiuser')),
                           parent=Optional(None), enable_locking=Optional(False)):
@@ -2132,12 +2047,10 @@
             raise JSONRPCError('failed to update repository group `%s`'
                                % (repogroupid,))
 
-    @HasPermissionAllDecorator('hg.admin')
-    def delete_repo_group(self, apiuser, repogroupid):
+    @HasPermissionAnyDecorator('hg.admin')
+    def delete_repo_group(self, repogroupid):
         """
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repogroupid: name or id of repository group
         :type repogroupid: str or int
 
@@ -2173,10 +2086,10 @@
             log.error(traceback.format_exc())
             raise JSONRPCError('failed to delete repo group ID:%s %s' %
                                (repo_group.group_id, repo_group.group_name)
-            )
+                               )
 
     # permission check inside
-    def grant_user_permission_to_repo_group(self, apiuser, repogroupid, userid,
+    def grant_user_permission_to_repo_group(self, repogroupid, userid,
                                             perm, apply_to_children=Optional('none')):
         """
         Grant permission for user on given repository group, or update existing
@@ -2184,8 +2097,6 @@
         to user with admin rights, or user who has admin right to given repository
         group.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repogroupid: name or id of repository group
         :type repogroupid: str or int
         :param userid:
@@ -2215,10 +2126,9 @@
 
         repo_group = get_repo_group_or_error(repogroupid)
 
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # check if we have admin permission for this repo group !
-            if not HasRepoGroupPermissionAnyApi('group.admin')(user=apiuser,
-                                                               group_name=repo_group.group_name):
+            if not HasRepoGroupPermissionAny('group.admin')(group_name=repo_group.group_name):
                 raise JSONRPCError('repository group `%s` does not exist' % (repogroupid,))
 
         user = get_user_or_error(userid)
@@ -2245,15 +2155,13 @@
                     userid, repo_group.name))
 
     # permission check inside
-    def revoke_user_permission_from_repo_group(self, apiuser, repogroupid, userid,
+    def revoke_user_permission_from_repo_group(self, repogroupid, userid,
                                                apply_to_children=Optional('none')):
         """
         Revoke permission for user on given repository group. This command can
         be executed only using api_key belonging to user with admin rights, or
         user who has admin right to given repository group.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repogroupid: name or id of repository group
         :type repogroupid: str or int
         :param userid:
@@ -2282,10 +2190,9 @@
 
         repo_group = get_repo_group_or_error(repogroupid)
 
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # check if we have admin permission for this repo group !
-            if not HasRepoGroupPermissionAnyApi('group.admin')(user=apiuser,
-                                                               group_name=repo_group.group_name):
+            if not HasRepoGroupPermissionAny('group.admin')(group_name=repo_group.group_name):
                 raise JSONRPCError('repository group `%s` does not exist' % (repogroupid,))
 
         user = get_user_or_error(userid)
@@ -2312,16 +2219,14 @@
 
     # permission check inside
     def grant_user_group_permission_to_repo_group(
-            self, apiuser, repogroupid, usergroupid, perm,
-            apply_to_children=Optional('none'),):
+            self, repogroupid, usergroupid, perm,
+            apply_to_children=Optional('none')):
         """
         Grant permission for user group on given repository group, or update
         existing one if found. This command can be executed only using
         api_key belonging to user with admin rights, or user who has admin
         right to given repository group.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repogroupid: name or id of repository group
         :type repogroupid: str or int
         :param usergroupid: id of usergroup
@@ -2353,18 +2258,18 @@
         repo_group = get_repo_group_or_error(repogroupid)
         perm = get_perm_or_error(perm, prefix='group.')
         user_group = get_user_group_or_error(usergroupid)
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # check if we have admin permission for this repo group !
             _perms = ('group.admin',)
-            if not HasRepoGroupPermissionAnyApi(*_perms)(
-                    user=apiuser, group_name=repo_group.group_name):
+            if not HasRepoGroupPermissionAny(*_perms)(
+                    group_name=repo_group.group_name):
                 raise JSONRPCError(
                     'repository group `%s` does not exist' % (repogroupid,))
 
             # check if we have at least read permission for this user group !
             _perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin',)
             if not HasUserGroupPermissionAny(*_perms)(
-                    user=apiuser, user_group_name=user_group.users_group_name):
+                    user_group_name=user_group.users_group_name):
                 raise JSONRPCError(
                     'user group `%s` does not exist' % (usergroupid,))
 
@@ -2379,9 +2284,9 @@
             Session().commit()
             return dict(
                 msg='Granted perm: `%s` (recursive:%s) for user group: `%s` in repo group: `%s`' % (
-                        perm.permission_name, apply_to_children,
-                        user_group.users_group_name, repo_group.name
-                    ),
+                    perm.permission_name, apply_to_children,
+                    user_group.users_group_name, repo_group.name
+                ),
                 success=True
             )
         except Exception:
@@ -2395,15 +2300,13 @@
 
     # permission check inside
     def revoke_user_group_permission_from_repo_group(
-            self, apiuser, repogroupid, usergroupid,
+            self, repogroupid, usergroupid,
             apply_to_children=Optional('none')):
         """
         Revoke permission for user group on given repository. This command can be
         executed only using api_key belonging to user with admin rights, or
         user who has admin right to given repository group.
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param repogroupid: name or id of repository group
         :type repogroupid: str or int
         :param usergroupid:
@@ -2431,18 +2334,18 @@
         """
         repo_group = get_repo_group_or_error(repogroupid)
         user_group = get_user_group_or_error(usergroupid)
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # check if we have admin permission for this repo group !
             _perms = ('group.admin',)
-            if not HasRepoGroupPermissionAnyApi(*_perms)(
-                    user=apiuser, group_name=repo_group.group_name):
+            if not HasRepoGroupPermissionAny(*_perms)(
+                    group_name=repo_group.group_name):
                 raise JSONRPCError(
                     'repository group `%s` does not exist' % (repogroupid,))
 
             # check if we have at least read permission for this user group !
             _perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin',)
             if not HasUserGroupPermissionAny(*_perms)(
-                    user=apiuser, user_group_name=user_group.users_group_name):
+                    user_group_name=user_group.users_group_name):
                 raise JSONRPCError(
                     'user group `%s` does not exist' % (usergroupid,))
 
@@ -2468,62 +2371,56 @@
                 )
             )
 
-    def get_gist(self, apiuser, gistid):
+    def get_gist(self, gistid):
         """
         Get given gist by id
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param gistid: id of private or public gist
         :type gistid: str
         """
         gist = get_gist_or_error(gistid)
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
-            if gist.gist_owner != apiuser.user_id:
+        if not HasPermissionAny('hg.admin')():
+            if gist.owner_id != self.authuser.user_id:
                 raise JSONRPCError('gist `%s` does not exist' % (gistid,))
         return gist.get_api_data()
 
-    def get_gists(self, apiuser, userid=Optional(OAttr('apiuser'))):
+    def get_gists(self, userid=Optional(OAttr('apiuser'))):
         """
         Get all gists for given user. If userid is empty returned gists
         are for user who called the api
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param userid: user to get gists for
         :type userid: Optional(str or int)
         """
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
+        if not HasPermissionAny('hg.admin')():
             # make sure normal user does not pass someone else userid,
             # he is not allowed to do that
-            if not isinstance(userid, Optional) and userid != apiuser.user_id:
+            if not isinstance(userid, Optional) and userid != self.authuser.user_id:
                 raise JSONRPCError(
                     'userid is not the same as your user'
                 )
 
         if isinstance(userid, Optional):
-            user_id = apiuser.user_id
+            user_id = self.authuser.user_id
         else:
             user_id = get_user_or_error(userid).user_id
 
         gists = []
-        _gists = Gist().query()\
-            .filter(or_(Gist.gist_expires == -1, Gist.gist_expires >= time.time()))\
-            .filter(Gist.gist_owner == user_id)\
+        _gists = Gist().query() \
+            .filter(or_(Gist.gist_expires == -1, Gist.gist_expires >= time.time())) \
+            .filter(Gist.owner_id == user_id) \
             .order_by(Gist.created_on.desc())
         for gist in _gists:
             gists.append(gist.get_api_data())
         return gists
 
-    def create_gist(self, apiuser, files, owner=Optional(OAttr('apiuser')),
+    def create_gist(self, files, owner=Optional(OAttr('apiuser')),
                     gist_type=Optional(Gist.GIST_PUBLIC), lifetime=Optional(-1),
                     description=Optional('')):
 
         """
         Creates new Gist
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param files: files to be added to gist
             {'filename': {'content':'...', 'lexer': null},
              'filename2': {'content':'...', 'lexer': null}}
@@ -2557,7 +2454,7 @@
         """
         try:
             if isinstance(owner, Optional):
-                owner = apiuser.user_id
+                owner = self.authuser.user_id
 
             owner = get_user_or_error(owner)
             description = Optional.extract(description)
@@ -2578,19 +2475,17 @@
             log.error(traceback.format_exc())
             raise JSONRPCError('failed to create gist')
 
-    # def update_gist(self, apiuser, gistid, files, owner=Optional(OAttr('apiuser')),
+    # def update_gist(self, gistid, files, owner=Optional(OAttr('apiuser')),
     #                 gist_type=Optional(Gist.GIST_PUBLIC),
     #                 gist_lifetime=Optional(-1), gist_description=Optional('')):
     #     gist = get_gist_or_error(gistid)
     #     updates = {}
 
     # permission check inside
-    def delete_gist(self, apiuser, gistid):
+    def delete_gist(self, gistid):
         """
         Deletes existing gist
 
-        :param apiuser: filled automatically from apikey
-        :type apiuser: AuthUser
         :param gistid: id of gist to delete
         :type gistid: str
 
@@ -2613,8 +2508,8 @@
 
         """
         gist = get_gist_or_error(gistid)
-        if not HasPermissionAnyApi('hg.admin')(user=apiuser):
-            if gist.gist_owner != apiuser.user_id:
+        if not HasPermissionAny('hg.admin')():
+            if gist.owner_id != self.authuser.user_id:
                 raise JSONRPCError('gist `%s` does not exist' % (gistid,))
 
         try:
--- a/kallithea/controllers/bookmarks.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,60 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.controllers.bookmarks
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Bookmarks controller for Kallithea
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Dec 1, 2011
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-import logging
-
-from pylons import tmpl_context as c
-
-from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
-from kallithea.lib.base import BaseRepoController, render
-from kallithea.lib.compat import OrderedDict
-from webob.exc import HTTPNotFound
-
-log = logging.getLogger(__name__)
-
-
-class BookmarksController(BaseRepoController):
-
-    def __before__(self):
-        super(BookmarksController, self).__before__()
-
-    @LoginRequired()
-    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
-                                   'repository.admin')
-    def index(self):
-        if c.db_repo_scm_instance.alias != 'hg':
-            raise HTTPNotFound()
-
-        c.repo_bookmarks = OrderedDict()
-
-        bookmarks = [(name, c.db_repo_scm_instance.get_changeset(hash_)) for \
-                 name, hash_ in c.db_repo_scm_instance._repo._bookmarks.items()]
-        ordered_tags = sorted(bookmarks, key=lambda x: x[1].date, reverse=True)
-        for name, cs_book in ordered_tags:
-            c.repo_bookmarks[name] = cs_book
-
-        return render('bookmarks/bookmarks.html')
--- a/kallithea/controllers/branches.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,77 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.controllers.branches
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-branches controller for Kallithea
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Apr 21, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-import logging
-import binascii
-
-from pylons import tmpl_context as c
-
-from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
-from kallithea.lib.base import BaseRepoController, render
-from kallithea.lib.compat import OrderedDict
-from kallithea.lib.utils2 import safe_unicode
-
-log = logging.getLogger(__name__)
-
-
-class BranchesController(BaseRepoController):
-
-    def __before__(self):
-        super(BranchesController, self).__before__()
-
-    @LoginRequired()
-    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
-                                   'repository.admin')
-    def index(self):
-
-        def _branchtags(localrepo):
-            bt_closed = {}
-            for bn, heads in localrepo.branchmap().iteritems():
-                tip = heads[-1]
-                if 'close' in localrepo.changelog.read(tip)[5]:
-                    bt_closed[bn] = tip
-            return bt_closed
-
-        cs_g = c.db_repo_scm_instance.get_changeset
-
-        c.repo_closed_branches = {}
-        if c.db_repo.repo_type == 'hg':
-            bt_closed = _branchtags(c.db_repo_scm_instance._repo)
-            _closed_branches = [(safe_unicode(n), cs_g(binascii.hexlify(h)),)
-                                for n, h in bt_closed.items()]
-
-            c.repo_closed_branches = OrderedDict(sorted(_closed_branches,
-                                                    key=lambda ctx: ctx[0],
-                                                    reverse=False))
-
-        _branches = [(safe_unicode(n), cs_g(h))
-                     for n, h in c.db_repo_scm_instance.branches.items()]
-        c.repo_branches = OrderedDict(sorted(_branches,
-                                             key=lambda ctx: ctx[0],
-                                             reverse=False))
-
-        return render('branches/branches.html')
--- a/kallithea/controllers/changelog.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/changelog.py	Fri Nov 18 01:11:13 2016 +0100
@@ -28,18 +28,18 @@
 import logging
 import traceback
 
-from pylons import request, url, session, tmpl_context as c
-from pylons.controllers.util import redirect
+from pylons import request, session, tmpl_context as c
 from pylons.i18n.translation import _
-from webob.exc import HTTPNotFound, HTTPBadRequest
+from webob.exc import HTTPFound, HTTPNotFound, HTTPBadRequest
 
 import kallithea.lib.helpers as h
+from kallithea.config.routing import url
 from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
 from kallithea.lib.base import BaseRepoController, render
-from kallithea.lib.helpers import RepoPage
 from kallithea.lib.compat import json
 from kallithea.lib.graphmod import graph_data
-from kallithea.lib.vcs.exceptions import RepositoryError, ChangesetDoesNotExistError,\
+from kallithea.lib.page import RepoPage
+from kallithea.lib.vcs.exceptions import RepositoryError, ChangesetDoesNotExistError, \
     ChangesetError, NodeDoesNotExistError, EmptyRepositoryError
 from kallithea.lib.utils2 import safe_int, safe_str
 
@@ -48,6 +48,7 @@
 
 
 def _load_changelog_summary():
+    # also used from summary ...
     p = safe_int(request.GET.get('page'), 1)
     size = safe_int(request.GET.get('size'), 10)
 
@@ -99,8 +100,8 @@
         if request.GET.get('set'):
             request.GET.pop('set', None)
             if revision is None:
-                return redirect(url('changelog_home', repo_name=repo_name, **request.GET))
-            return redirect(url('changelog_file_home', repo_name=repo_name, revision=revision, f_path=f_path, **request.GET))
+                raise HTTPFound(location=url('changelog_home', repo_name=repo_name, **request.GET))
+            raise HTTPFound(location=url('changelog_file_home', repo_name=repo_name, revision=revision, f_path=f_path, **request.GET))
 
         limit = 2000
         default = 100
@@ -112,13 +113,13 @@
             c.size = int(session.get('changelog_size', default))
         # min size must be 1
         c.size = max(c.size, 1)
-        p = safe_int(request.GET.get('page', 1), 1)
+        p = safe_int(request.GET.get('page'), 1)
         branch_name = request.GET.get('branch', None)
         if (branch_name and
             branch_name not in c.db_repo_scm_instance.branches and
             branch_name not in c.db_repo_scm_instance.closed_branches and
             not revision):
-            return redirect(url('changelog_file_home', repo_name=c.repo_name,
+            raise HTTPFound(location=url('changelog_file_home', repo_name=c.repo_name,
                                     revision=branch_name, f_path=f_path or ''))
 
         if revision == 'tip':
@@ -140,7 +141,7 @@
                         collection = cs.get_file_history(f_path)
                     except RepositoryError as e:
                         h.flash(safe_str(e), category='warning')
-                        redirect(h.url('changelog_home', repo_name=repo_name))
+                        raise HTTPFound(location=h.url('changelog_home', repo_name=repo_name))
                 collection = list(reversed(collection))
             else:
                 collection = c.db_repo_scm_instance.get_changesets(start=0, end=revision,
@@ -155,11 +156,11 @@
             c.statuses = c.db_repo.statuses(page_revisions)
         except EmptyRepositoryError as e:
             h.flash(safe_str(e), category='warning')
-            return redirect(url('summary_home', repo_name=c.repo_name))
+            raise HTTPFound(location=url('summary_home', repo_name=c.repo_name))
         except (RepositoryError, ChangesetDoesNotExistError, Exception) as e:
             log.error(traceback.format_exc())
             h.flash(safe_str(e), category='error')
-            return redirect(url('changelog_home', repo_name=c.repo_name))
+            raise HTTPFound(location=url('changelog_home', repo_name=c.repo_name))
 
         c.branch_name = branch_name
         c.branch_filters = [('', _('None'))] + \
--- a/kallithea/controllers/changeset.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/changeset.py	Fri Nov 18 01:11:13 2016 +0100
@@ -15,8 +15,7 @@
 kallithea.controllers.changeset
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
-changeset controller for pylons showing changes between
-revisions
+changeset controller showing changes between revisions
 
 This file was forked by the Kallithea project in July 2014.
 Original author and date, and relevant copyright and licensing information is below:
@@ -29,19 +28,18 @@
 import logging
 import traceback
 from collections import defaultdict
-from webob.exc import HTTPForbidden, HTTPBadRequest, HTTPNotFound
 
 from pylons import tmpl_context as c, request, response
 from pylons.i18n.translation import _
-from pylons.controllers.util import redirect
-from kallithea.lib.utils import jsonify
+from webob.exc import HTTPFound, HTTPForbidden, HTTPBadRequest, HTTPNotFound
 
+from kallithea.lib.utils import jsonify
 from kallithea.lib.vcs.exceptions import RepositoryError, \
-    ChangesetDoesNotExistError
+    ChangesetDoesNotExistError, EmptyRepositoryError
 
 from kallithea.lib.compat import json
 import kallithea.lib.helpers as h
-from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator,\
+from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator, \
     NotAnonymous
 from kallithea.lib.base import BaseRepoController, render
 from kallithea.lib.utils import action_logger
@@ -173,6 +171,27 @@
     return h.link_to(icon, h.url.current(**params), title=lbl, class_='tooltip')
 
 
+# Could perhaps be nice to have in the model but is too high level ...
+def create_comment(text, status, f_path, line_no, revision=None, pull_request_id=None, closing_pr=None):
+    """Comment functionality shared between changesets and pullrequests"""
+    f_path = f_path or None
+    line_no = line_no or None
+
+    comment = ChangesetCommentsModel().create(
+        text=text,
+        repo=c.db_repo.repo_id,
+        author=c.authuser.user_id,
+        revision=revision,
+        pull_request=pull_request_id,
+        f_path=f_path,
+        line_no=line_no,
+        status_change=ChangesetStatus.get_status_lbl(status) if status else None,
+        closing_pr=closing_pr,
+    )
+
+    return comment
+
+
 class ChangesetController(BaseRepoController):
 
     def __before__(self):
@@ -185,6 +204,7 @@
         c.user_groups_array = repo_model.get_user_groups_js()
 
     def _index(self, revision, method):
+        c.pull_request = None
         c.anchor_url = anchor_url
         c.ignorews_url = _ignorews_url
         c.context_url = _context_url
@@ -207,7 +227,7 @@
             if not c.cs_ranges:
                 raise RepositoryError('Changeset range returned empty result')
 
-        except(ChangesetDoesNotExistError,), e:
+        except (ChangesetDoesNotExistError, EmptyRepositoryError):
             log.debug(traceback.format_exc())
             msg = _('Such revision does not exist for this repository')
             h.flash(msg, category='error')
@@ -226,7 +246,6 @@
 
         # Iterate over ranges (default changeset view is always one changeset)
         for changeset in c.cs_ranges:
-            inlines = []
             if method == 'show':
                 c.statuses.extend([ChangesetStatusModel().get_status(
                             c.db_repo.repo_id, changeset.raw_id)])
@@ -238,23 +257,21 @@
                                               revision=changeset.raw_id))
 
                 # Status change comments - mostly from pull requests
-                comments.update((st.changeset_comment_id, st.comment)
+                comments.update((st.comment_id, st.comment)
                                 for st in ChangesetStatusModel()
                                 .get_statuses(c.db_repo.repo_id,
                                               changeset.raw_id, with_revisions=True)
-                                if st.changeset_comment_id is not None)
+                                if st.comment_id is not None)
 
-                inlines = ChangesetCommentsModel()\
+                inlines = ChangesetCommentsModel() \
                             .get_inline_comments(c.db_repo.repo_id,
                                                  revision=changeset.raw_id)
                 c.inline_comments.extend(inlines)
 
-            c.changes[changeset.raw_id] = []
-
             cs2 = changeset.raw_id
             cs1 = changeset.parents[0].raw_id if changeset.parents else EmptyChangeset().raw_id
             context_lcl = get_line_ctx('', request.GET)
-            ign_whitespace_lcl = ign_whitespace_lcl = get_ignore_ws('', request.GET)
+            ign_whitespace_lcl = get_ignore_ws('', request.GET)
 
             _diff = c.db_repo_scm_instance.get_diff(cs1, cs2,
                 ignore_whitespace=ign_whitespace_lcl, context=context_lcl)
@@ -263,7 +280,7 @@
                                                  vcs=c.db_repo_scm_instance.alias,
                                                  format='gitdiff',
                                                  diff_limit=diff_limit)
-            cs_changes = OrderedDict()
+            file_diff_data = []
             if method == 'show':
                 _parsed = diff_processor.prepare()
                 c.limited_diff = False
@@ -273,16 +290,17 @@
                     st = f['stats']
                     c.lines_added += st['added']
                     c.lines_deleted += st['deleted']
-                    fid = h.FID(changeset.raw_id, f['filename'])
+                    filename = f['filename']
+                    fid = h.FID(changeset.raw_id, filename)
+                    url_fid = h.FID('', filename)
                     diff = diff_processor.as_html(enable_comments=enable_comments,
                                                   parsed_lines=[f])
-                    cs_changes[fid] = [cs1, cs2, f['operation'], f['filename'],
-                                       diff, st]
+                    file_diff_data.append((fid, url_fid, f['operation'], f['old_filename'], filename, diff, st))
             else:
                 # downloads/raw we only need RAW diff nothing else
                 diff = diff_processor.as_raw()
-                cs_changes[''] = [None, None, None, None, diff, None]
-            c.changes[changeset.raw_id] = cs_changes
+                file_diff_data.append(('', None, None, None, diff, None))
+            c.changes[changeset.raw_id] = (cs1, cs2, file_diff_data)
 
         #sort comments in creation order
         c.comments = [com for com_id, com in sorted(comments.items())]
@@ -349,57 +367,47 @@
                                    'repository.admin')
     @jsonify
     def comment(self, repo_name, revision):
+        assert request.environ.get('HTTP_X_PARTIAL_XHR')
+
         status = request.POST.get('changeset_status')
         text = request.POST.get('text', '').strip()
 
-        c.comment = comment = ChangesetCommentsModel().create(
-            text=text,
-            repo=c.db_repo.repo_id,
-            user=c.authuser.user_id,
+        c.comment = create_comment(
+            text,
+            status,
             revision=revision,
             f_path=request.POST.get('f_path'),
             line_no=request.POST.get('line'),
-            status_change=(ChangesetStatus.get_status_lbl(status)
-                           if status else None)
         )
 
         # get status if set !
         if status:
             # if latest status was from pull request and it's closed
-            # disallow changing status !
-            # dont_allow_on_closed_pull_request = True !
-
+            # disallow changing status ! RLY?
             try:
                 ChangesetStatusModel().set_status(
                     c.db_repo.repo_id,
                     status,
                     c.authuser.user_id,
-                    comment,
+                    c.comment,
                     revision=revision,
-                    dont_allow_on_closed_pull_request=True
+                    dont_allow_on_closed_pull_request=True,
                 )
             except StatusChangeOnClosedPullRequestError:
-                log.debug(traceback.format_exc())
-                msg = _('Changing status on a changeset associated with '
-                        'a closed pull request is not allowed')
-                h.flash(msg, category='warning')
-                return redirect(h.url('changeset_home', repo_name=repo_name,
-                                      revision=revision))
+                log.debug('cannot change status on %s with closed pull request', revision)
+                raise HTTPBadRequest()
+
         action_logger(self.authuser,
                       'user_commented_revision:%s' % revision,
                       c.db_repo, self.ip_addr, self.sa)
 
         Session().commit()
 
-        if not request.environ.get('HTTP_X_PARTIAL_XHR'):
-            return redirect(h.url('changeset_home', repo_name=repo_name,
-                                  revision=revision))
-        #only ajax below
         data = {
            'target_id': h.safeid(h.safe_unicode(request.POST.get('f_path'))),
         }
-        if comment is not None:
-            data.update(comment.get_dict())
+        if c.comment is not None:
+            data.update(c.comment.get_dict())
             data.update({'rendered_text':
                          render('changeset/changeset_comment_block.html')})
 
@@ -409,24 +417,12 @@
     @NotAnonymous()
     @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
                                    'repository.admin')
-    def preview_comment(self):
-        if not request.environ.get('HTTP_X_PARTIAL_XHR'):
-            raise HTTPBadRequest()
-        text = request.POST.get('text')
-        if text:
-            return h.rst_w_mentions(text)
-        return ''
-
-    @LoginRequired()
-    @NotAnonymous()
-    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
-                                   'repository.admin')
     @jsonify
     def delete_comment(self, repo_name, comment_id):
         co = ChangesetComment.get_or_404(comment_id)
         if co.repo.repo_name != repo_name:
             raise HTTPNotFound()
-        owner = co.author.user_id == c.authuser.user_id
+        owner = co.author_id == c.authuser.user_id
         repo_admin = h.HasRepoPermissionAny('repository.admin')(repo_name)
         if h.HasPermissionAny('hg.admin')() or repo_admin or owner:
             ChangesetCommentsModel().delete(comment=co)
--- a/kallithea/controllers/compare.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/compare.py	Fri Nov 18 01:11:13 2016 +0100
@@ -15,7 +15,7 @@
 kallithea.controllers.compare
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
-compare controller for pylons showing differences between two
+compare controller showing differences between two
 repos, branches, bookmarks or tips
 
 This file was forked by the Kallithea project in July 2014.
@@ -30,11 +30,12 @@
 import logging
 import re
 
-from webob.exc import HTTPBadRequest
-from pylons import request, tmpl_context as c, url
-from pylons.controllers.util import redirect
+from pylons import request, tmpl_context as c
 from pylons.i18n.translation import _
+from webob.exc import HTTPFound, HTTPBadRequest, HTTPNotFound
 
+from kallithea.config.routing import url
+from kallithea.lib.utils2 import safe_str, safe_int
 from kallithea.lib.vcs.utils.hgcompat import unionrepo
 from kallithea.lib import helpers as h
 from kallithea.lib.base import BaseRepoController, render
@@ -44,7 +45,7 @@
 from kallithea.lib.diffs import LimitedDiffContainer
 from kallithea.controllers.changeset import _ignorews_url, _context_url
 from kallithea.lib.graphmod import graph_data
-from kallithea.lib.compat import json
+from kallithea.lib.compat import json, OrderedDict
 
 log = logging.getLogger(__name__)
 
@@ -54,13 +55,33 @@
     def __before__(self):
         super(CompareController, self).__before__()
 
+        # The base repository has already been retrieved.
+        c.a_repo = c.db_repo
+
+        # Retrieve the "changeset" repository (default: same as base).
+        other_repo = request.GET.get('other_repo', None)
+        if other_repo is None:
+            c.cs_repo = c.a_repo
+        else:
+            c.cs_repo = Repository.get_by_repo_name(other_repo)
+            if c.cs_repo is None:
+                msg = _('Could not find other repository %s') % other_repo
+                h.flash(msg, category='error')
+                raise HTTPFound(location=url('compare_home', repo_name=c.a_repo.repo_name))
+
+        # Verify that it's even possible to compare these two repositories.
+        if c.a_repo.scm_instance.alias != c.cs_repo.scm_instance.alias:
+            msg = _('Cannot compare repositories of different types')
+            h.flash(msg, category='error')
+            raise HTTPFound(location=url('compare_home', repo_name=c.a_repo.repo_name))
+
     @staticmethod
     def _get_changesets(alias, org_repo, org_rev, other_repo, other_rev):
         """
         Returns lists of changesets that can be merged from org_repo@org_rev
         to other_repo@other_rev
         ... and the other way
-        ... and the ancestor that would be used for merge
+        ... and the ancestors that would be used for merge
 
         :param org_repo: repo object, that is most likely the original repo we forked from
         :param org_rev: the revision we want our compare to be made
@@ -68,11 +89,10 @@
             all changesets that we need to obtain
         :param other_rev: revision we want out compare to be made on other_repo
         """
-        ancestor = None
+        ancestors = None
         if org_rev == other_rev:
             org_changesets = []
             other_changesets = []
-            ancestor = org_rev
 
         elif alias == 'hg':
             #case two independent repos
@@ -87,25 +107,20 @@
             else:
                 hgrepo = other_repo._repo
 
-            if org_repo.EMPTY_CHANGESET in (org_rev, other_rev):
-                # work around unexpected behaviour in Mercurial < 3.4
-                ancestor = org_repo.EMPTY_CHANGESET
+            ancestors = [hgrepo[ancestor].hex() for ancestor in
+                         hgrepo.revs("id(%s) & ::id(%s)", other_rev, org_rev)]
+            if ancestors:
+                log.debug("shortcut found: %s is already an ancestor of %s", other_rev, org_rev)
             else:
-                ancestors = hgrepo.revs("ancestor(id(%s), id(%s))", org_rev, other_rev)
-                if ancestors:
-                    # FIXME: picks arbitrary ancestor - but there is usually only one
-                    try:
-                        ancestor = hgrepo[ancestors.first()].hex()
-                    except AttributeError:
-                        # removed in hg 3.2
-                        ancestor = hgrepo[ancestors[0]].hex()
+                log.debug("no shortcut found: %s is not an ancestor of %s", other_rev, org_rev)
+                ancestors = [hgrepo[ancestor].hex() for ancestor in
+                             hgrepo.revs("heads(::id(%s) & ::id(%s))", org_rev, other_rev)] # FIXME: expensive!
 
             other_revs = hgrepo.revs("ancestors(id(%s)) and not ancestors(id(%s)) and not id(%s)",
                                      other_rev, org_rev, org_rev)
             other_changesets = [other_repo.get_changeset(rev) for rev in other_revs]
             org_revs = hgrepo.revs("ancestors(id(%s)) and not ancestors(id(%s)) and not id(%s)",
                                    org_rev, other_rev, other_rev)
-
             org_changesets = [org_repo.get_changeset(hgrepo[rev].hex()) for rev in org_revs]
 
         elif alias == 'git':
@@ -114,10 +129,10 @@
                 from dulwich.client import SubprocessGitClient
 
                 gitrepo = Repo(org_repo.path)
-                SubprocessGitClient(thin_packs=False).fetch(other_repo.path, gitrepo)
+                SubprocessGitClient(thin_packs=False).fetch(safe_str(other_repo.path), gitrepo)
 
                 gitrepo_remote = Repo(other_repo.path)
-                SubprocessGitClient(thin_packs=False).fetch(org_repo.path, gitrepo_remote)
+                SubprocessGitClient(thin_packs=False).fetch(safe_str(org_repo.path), gitrepo_remote)
 
                 revs = []
                 for x in gitrepo_remote.get_walker(include=[other_rev],
@@ -126,10 +141,14 @@
 
                 other_changesets = [other_repo.get_changeset(rev) for rev in reversed(revs)]
                 if other_changesets:
-                    ancestor = other_changesets[0].parents[0].raw_id
+                    ancestors = [other_changesets[0].parents[0].raw_id]
                 else:
                     # no changesets from other repo, ancestor is the other_rev
-                    ancestor = other_rev
+                    ancestors = [other_rev]
+
+                # dulwich 0.9.9 doesn't have a Repo.close() so we have to mess with internals:
+                gitrepo.object_store.close()
+                gitrepo_remote.object_store.close()
 
             else:
                 so, se = org_repo.run_git_command(
@@ -141,23 +160,19 @@
                 so, se = org_repo.run_git_command(
                     ['merge-base', org_rev, other_rev]
                 )
-                ancestor = re.findall(r'[0-9a-fA-F]{40}', so)[0]
+                ancestors = [re.findall(r'[0-9a-fA-F]{40}', so)[0]]
             org_changesets = []
 
         else:
             raise Exception('Bad alias only git and hg is allowed')
 
-        return other_changesets, org_changesets, ancestor
+        return other_changesets, org_changesets, ancestors
 
     @LoginRequired()
     @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
                                    'repository.admin')
     def index(self, repo_name):
         c.compare_home = True
-        org_repo = c.db_repo.repo_name
-        other_repo = request.GET.get('other_repo', org_repo)
-        c.a_repo = Repository.get_by_repo_name(org_repo)
-        c.cs_repo = Repository.get_by_repo_name(other_repo)
         c.a_ref_name = c.cs_ref_name = _('Select changeset')
         return render('compare/compare_diff.html')
 
@@ -168,8 +183,6 @@
         org_ref_name = org_ref_name.strip()
         other_ref_name = other_ref_name.strip()
 
-        org_repo = c.db_repo.repo_name
-        other_repo = request.GET.get('other_repo', org_repo)
         # If merge is True:
         #   Show what org would get if merged with other:
         #   List changesets that are ancestors of other but not of org.
@@ -187,9 +200,9 @@
         c.as_form = partial and request.GET.get('as_form')
         # swap url for compare_diff page - never partial and never as_form
         c.swap_url = h.url('compare_url',
-            repo_name=other_repo,
+            repo_name=c.cs_repo.repo_name,
             org_ref_type=other_ref_type, org_ref_name=other_ref_name,
-            other_repo=org_repo,
+            other_repo=c.a_repo.repo_name,
             other_ref_type=org_ref_type, other_ref_name=org_ref_name,
             merge=merge or '')
 
@@ -197,64 +210,56 @@
         c.ignorews_url = _ignorews_url
         c.context_url = _context_url
         ignore_whitespace = request.GET.get('ignorews') == '1'
-        line_context = request.GET.get('context', 3)
-
-        org_repo = Repository.get_by_repo_name(org_repo)
-        other_repo = Repository.get_by_repo_name(other_repo)
-
-        if org_repo is None:
-            msg = 'Could not find org repo %s' % org_repo
-            log.error(msg)
-            h.flash(msg, category='error')
-            return redirect(url('compare_home', repo_name=c.repo_name))
+        line_context = safe_int(request.GET.get('context'), 3)
 
-        if other_repo is None:
-            msg = 'Could not find other repo %s' % other_repo
-            log.error(msg)
-            h.flash(msg, category='error')
-            return redirect(url('compare_home', repo_name=c.repo_name))
-
-        if org_repo.scm_instance.alias != other_repo.scm_instance.alias:
-            msg = 'compare of two different kind of remote repos not available'
-            log.error(msg)
-            h.flash(msg, category='error')
-            return redirect(url('compare_home', repo_name=c.repo_name))
-
-        c.a_rev = self._get_ref_rev(org_repo, org_ref_type, org_ref_name,
+        c.a_rev = self._get_ref_rev(c.a_repo, org_ref_type, org_ref_name,
             returnempty=True)
-        c.cs_rev = self._get_ref_rev(other_repo, other_ref_type, other_ref_name)
+        c.cs_rev = self._get_ref_rev(c.cs_repo, other_ref_type, other_ref_name)
 
         c.compare_home = False
-        c.a_repo = org_repo
         c.a_ref_name = org_ref_name
         c.a_ref_type = org_ref_type
-        c.cs_repo = other_repo
         c.cs_ref_name = other_ref_name
         c.cs_ref_type = other_ref_type
 
-        c.cs_ranges, c.cs_ranges_org, c.ancestor = self._get_changesets(
-            org_repo.scm_instance.alias, org_repo.scm_instance, c.a_rev,
-            other_repo.scm_instance, c.cs_rev)
+        c.cs_ranges, c.cs_ranges_org, c.ancestors = self._get_changesets(
+            c.a_repo.scm_instance.alias, c.a_repo.scm_instance, c.a_rev,
+            c.cs_repo.scm_instance, c.cs_rev)
         raw_ids = [x.raw_id for x in c.cs_ranges]
-        c.cs_comments = other_repo.get_comments(raw_ids)
-        c.statuses = other_repo.statuses(raw_ids)
+        c.cs_comments = c.cs_repo.get_comments(raw_ids)
+        c.statuses = c.cs_repo.statuses(raw_ids)
 
         revs = [ctx.revision for ctx in reversed(c.cs_ranges)]
         c.jsdata = json.dumps(graph_data(c.cs_repo.scm_instance, revs))
 
         if partial:
             return render('compare/compare_cs.html')
-        if merge and c.ancestor:
+
+        org_repo = c.a_repo
+        other_repo = c.cs_repo
+
+        if merge:
+            rev1 = msg = None
+            if not c.cs_ranges:
+                msg = _('Cannot show empty diff')
+            elif not c.ancestors:
+                msg = _('No ancestor found for merge diff')
+            elif len(c.ancestors) == 1:
+                rev1 = c.ancestors[0]
+            else:
+                msg = _('Multiple merge ancestors found for merge compare')
+            if rev1 is None:
+                h.flash(msg, category='error')
+                log.error(msg)
+                raise HTTPNotFound
+
             # case we want a simple diff without incoming changesets,
             # previewing what will be merged.
             # Make the diff on the other repo (which is known to have other_rev)
             log.debug('Using ancestor %s as rev1 instead of %s',
-                      c.ancestor, c.a_rev)
-            rev1 = c.ancestor
+                      rev1, c.a_rev)
             org_repo = other_repo
         else: # comparing tips, not necessarily linearly related
-            if merge:
-                log.error('Unable to find ancestor revision')
             if org_repo != other_repo:
                 # TODO: we could do this by using hg unionrepo
                 log.error('cannot compare across repos %s and %s', org_repo, other_repo)
@@ -278,18 +283,17 @@
         if isinstance(_parsed, LimitedDiffContainer):
             c.limited_diff = True
 
-        c.files = []
-        c.changes = {}
+        c.file_diff_data = []
         c.lines_added = 0
         c.lines_deleted = 0
         for f in _parsed:
             st = f['stats']
-            if not st['binary']:
-                c.lines_added += st['added']
-                c.lines_deleted += st['deleted']
-            fid = h.FID('', f['filename'])
-            c.files.append([fid, f['operation'], f['filename'], f['stats']])
-            htmldiff = diff_processor.as_html(enable_comments=False, parsed_lines=[f])
-            c.changes[fid] = [f['operation'], f['filename'], htmldiff]
+            c.lines_added += st['added']
+            c.lines_deleted += st['deleted']
+            filename = f['filename']
+            fid = h.FID('', filename)
+            diff = diff_processor.as_html(enable_comments=False,
+                                          parsed_lines=[f])
+            c.file_diff_data.append((fid, None, f['operation'], f['old_filename'], filename, diff, st))
 
         return render('compare/compare_diff.html')
--- a/kallithea/controllers/feed.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/feed.py	Fri Nov 18 01:11:13 2016 +0100
@@ -117,7 +117,7 @@
     def atom(self, repo_name):
         """Produce an atom-1.0 feed via feedgenerator module"""
 
-        @cache_region('long_term')
+        @cache_region('long_term', '_get_feed_from_cache')
         def _get_feed_from_cache(key, kind):
             feed = Atom1Feed(
                  title=self.title % repo_name,
@@ -142,13 +142,13 @@
         kind = 'ATOM'
         valid = CacheInvalidation.test_and_set_valid(repo_name, kind)
         if not valid:
-            region_invalidate(_get_feed_from_cache, None, repo_name, kind)
+            region_invalidate(_get_feed_from_cache, None, '_get_feed_from_cache', repo_name, kind)
         return _get_feed_from_cache(repo_name, kind)
 
     def rss(self, repo_name):
         """Produce an rss2 feed via feedgenerator module"""
 
-        @cache_region('long_term')
+        @cache_region('long_term', '_get_feed_from_cache')
         def _get_feed_from_cache(key, kind):
             feed = Rss201rev2Feed(
                 title=self.title % repo_name,
@@ -173,5 +173,5 @@
         kind = 'RSS'
         valid = CacheInvalidation.test_and_set_valid(repo_name, kind)
         if not valid:
-            region_invalidate(_get_feed_from_cache, None, repo_name, kind)
+            region_invalidate(_get_feed_from_cache, None, '_get_feed_from_cache', repo_name, kind)
         return _get_feed_from_cache(repo_name, kind)
--- a/kallithea/controllers/files.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/files.py	Fri Nov 18 01:11:13 2016 +0100
@@ -26,29 +26,31 @@
 """
 
 import os
+import posixpath
 import logging
 import traceback
 import tempfile
 import shutil
 
-from pylons import request, response, tmpl_context as c, url
+from pylons import request, response, tmpl_context as c
 from pylons.i18n.translation import _
-from pylons.controllers.util import redirect
+from webob.exc import HTTPFound
+
+from kallithea.config.routing import url
 from kallithea.lib.utils import jsonify, action_logger
-
 from kallithea.lib import diffs
 from kallithea.lib import helpers as h
 
 from kallithea.lib.compat import OrderedDict
-from kallithea.lib.utils2 import convert_line_endings, detect_mode, safe_str,\
-    str2bool
+from kallithea.lib.utils2 import convert_line_endings, detect_mode, safe_str, \
+    str2bool, safe_int
 from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
 from kallithea.lib.base import BaseRepoController, render
 from kallithea.lib.vcs.backends.base import EmptyChangeset
 from kallithea.lib.vcs.conf import settings
 from kallithea.lib.vcs.exceptions import RepositoryError, \
     ChangesetDoesNotExistError, EmptyRepositoryError, \
-    ImproperArchiveTypeError, VCSError, NodeAlreadyExistsError,\
+    ImproperArchiveTypeError, VCSError, NodeAlreadyExistsError, \
     NodeDoesNotExistError, ChangesetError, NodeError
 from kallithea.lib.vcs.nodes import FileNode
 
@@ -56,7 +58,7 @@
 from kallithea.model.scm import ScmModel
 from kallithea.model.db import Repository
 
-from kallithea.controllers.changeset import anchor_url, _ignorews_url,\
+from kallithea.controllers.changeset import anchor_url, _ignorews_url, \
     _context_url, get_line_ctx, get_ignore_ws
 from webob.exc import HTTPNotFound
 from kallithea.lib.exceptions import NonRelativePathError
@@ -92,7 +94,7 @@
             h.flash(h.literal(_('There are no files yet. %s') % add_new),
                     category='warning')
             raise HTTPNotFound()
-        except(ChangesetDoesNotExistError, LookupError), e:
+        except (ChangesetDoesNotExistError, LookupError):
             msg = _('Such revision does not exist for this repository')
             h.flash(msg, category='error')
             raise HTTPNotFound()
@@ -112,7 +114,7 @@
             file_node = cs.get_node(path)
             if file_node.is_dir():
                 raise RepositoryError('given path is a directory')
-        except(ChangesetDoesNotExistError,), e:
+        except ChangesetDoesNotExistError:
             msg = _('Such revision does not exist for this repository')
             h.flash(msg, category='error')
             raise HTTPNotFound()
@@ -137,6 +139,7 @@
         c.f_path = f_path
         c.annotate = annotate
         cur_rev = c.changeset.revision
+        c.fulldiff = request.GET.get('fulldiff')
 
         # prev link
         try:
@@ -164,10 +167,6 @@
 
             if c.file.is_file():
                 c.load_full_history = False
-                file_last_cs = c.file.last_changeset
-                c.file_changeset = (c.changeset
-                                    if c.changeset.revision < file_last_cs.revision
-                                    else file_last_cs)
                 #determine if we're on branch head
                 _branches = c.db_repo_scm_instance.branches
                 c.on_branch_head = revision in _branches.keys() + _branches.values()
@@ -306,7 +305,7 @@
                 % (h.person_by_id(repo.locked[0]),
                    h.fmt_date(h.time_to_datetime(repo.locked[1]))),
                 'warning')
-            return redirect(h.url('files_home',
+            raise HTTPFound(location=h.url('files_home',
                                   repo_name=repo_name, revision='tip'))
 
         # check if revision is a branch identifier- basically we cannot
@@ -316,7 +315,7 @@
         if revision not in _branches.keys() + _branches.values():
             h.flash(_('You can only delete files with revision '
                       'being a valid branch'), category='warning')
-            return redirect(h.url('files_home',
+            raise HTTPFound(location=h.url('files_home',
                                   repo_name=repo_name, revision='tip',
                                   f_path=f_path))
 
@@ -352,7 +351,7 @@
             except Exception:
                 log.error(traceback.format_exc())
                 h.flash(_('Error occurred during commit'), category='error')
-            return redirect(url('changeset_home',
+            raise HTTPFound(location=url('changeset_home',
                                 repo_name=c.repo_name, revision='tip'))
 
         return render('files/files_delete.html')
@@ -366,7 +365,7 @@
                 % (h.person_by_id(repo.locked[0]),
                    h.fmt_date(h.time_to_datetime(repo.locked[1]))),
                 'warning')
-            return redirect(h.url('files_home',
+            raise HTTPFound(location=h.url('files_home',
                                   repo_name=repo_name, revision='tip'))
 
         # check if revision is a branch identifier- basically we cannot
@@ -376,7 +375,7 @@
         if revision not in _branches.keys() + _branches.values():
             h.flash(_('You can only edit files with revision '
                       'being a valid branch'), category='warning')
-            return redirect(h.url('files_home',
+            raise HTTPFound(location=h.url('files_home',
                                   repo_name=repo_name, revision='tip',
                                   f_path=f_path))
 
@@ -386,7 +385,7 @@
         c.file = self.__get_filenode(c.cs, f_path)
 
         if c.file.is_binary:
-            return redirect(url('files_home', repo_name=c.repo_name,
+            raise HTTPFound(location=url('files_home', repo_name=c.repo_name,
                             revision=c.cs.raw_id, f_path=f_path))
         c.default_message = _('Edited file %s via Kallithea') % (f_path)
         c.f_path = f_path
@@ -405,7 +404,7 @@
 
             if content == old_content:
                 h.flash(_('No changes'), category='warning')
-                return redirect(url('changeset_home', repo_name=c.repo_name,
+                raise HTTPFound(location=url('changeset_home', repo_name=c.repo_name,
                                     revision='tip'))
             try:
                 self.scm_model.commit_change(repo=c.db_repo_scm_instance,
@@ -418,7 +417,7 @@
             except Exception:
                 log.error(traceback.format_exc())
                 h.flash(_('Error occurred during commit'), category='error')
-            return redirect(url('changeset_home',
+            raise HTTPFound(location=url('changeset_home',
                                 repo_name=c.repo_name, revision='tip'))
 
         return render('files/files_edit.html')
@@ -427,13 +426,13 @@
     @HasRepoPermissionAnyDecorator('repository.write', 'repository.admin')
     def add(self, repo_name, revision, f_path):
 
-        repo = Repository.get_by_repo_name(repo_name)
+        repo = c.db_repo
         if repo.enable_locking and repo.locked[0]:
             h.flash(_('This repository has been locked by %s on %s')
                 % (h.person_by_id(repo.locked[0]),
                    h.fmt_date(h.time_to_datetime(repo.locked[1]))),
                   'warning')
-            return redirect(h.url('files_home',
+            raise HTTPFound(location=h.url('files_home',
                                   repo_name=repo_name, revision='tip'))
 
         r_post = request.POST
@@ -462,15 +461,15 @@
 
             if not content:
                 h.flash(_('No content'), category='warning')
-                return redirect(url('changeset_home', repo_name=c.repo_name,
+                raise HTTPFound(location=url('changeset_home', repo_name=c.repo_name,
                                     revision='tip'))
             if not filename:
                 h.flash(_('No filename'), category='warning')
-                return redirect(url('changeset_home', repo_name=c.repo_name,
+                raise HTTPFound(location=url('changeset_home', repo_name=c.repo_name,
                                     revision='tip'))
             #strip all crap out of file, just leave the basename
             filename = os.path.basename(filename)
-            node_path = os.path.join(location, filename)
+            node_path = posixpath.join(location, filename)
             author = self.authuser.full_contact
 
             try:
@@ -492,14 +491,14 @@
             except NonRelativePathError as e:
                 h.flash(_('Location must be relative path and must not '
                           'contain .. in path'), category='warning')
-                return redirect(url('changeset_home', repo_name=c.repo_name,
+                raise HTTPFound(location=url('changeset_home', repo_name=c.repo_name,
                                     revision='tip'))
             except (NodeError, NodeAlreadyExistsError) as e:
                 h.flash(_(e), category='error')
             except Exception:
                 log.error(traceback.format_exc())
                 h.flash(_('Error occurred during commit'), category='error')
-            return redirect(url('changeset_home',
+            raise HTTPFound(location=url('changeset_home',
                                 repo_name=c.repo_name, revision='tip'))
 
         return render('files/files_add.html')
@@ -548,7 +547,7 @@
         archive_path = None
         cached_archive_path = None
         archive_cache_dir = CONFIG.get('archive_cache_dir')
-        if archive_cache_dir and not subrepos: # TOOD: subrepo caching?
+        if archive_cache_dir and not subrepos: # TODO: subrepo caching?
             if not os.path.isdir(archive_cache_dir):
                 os.makedirs(archive_cache_dir)
             cached_archive_path = os.path.join(archive_cache_dir, archive_name)
@@ -596,7 +595,7 @@
                                    'repository.admin')
     def diff(self, repo_name, f_path):
         ignore_whitespace = request.GET.get('ignorews') == '1'
-        line_context = request.GET.get('context', 3)
+        line_context = safe_int(request.GET.get('context'), 3)
         diff2 = request.GET.get('diff2', '')
         diff1 = request.GET.get('diff1', '') or diff2
         c.action = request.GET.get('diff')
@@ -620,7 +619,7 @@
                 _url = url('files_home', repo_name=c.repo_name,
                            revision=diff1, f_path=c.f_path)
 
-            return redirect(_url)
+            raise HTTPFound(location=_url)
         try:
             if diff1 not in ['', None, 'None', '0' * 12, '0' * 40]:
                 c.changeset_1 = c.db_repo_scm_instance.get_changeset(diff1)
@@ -655,7 +654,7 @@
                 node2 = FileNode(f_path, '', changeset=c.changeset_2)
         except (RepositoryError, NodeError):
             log.error(traceback.format_exc())
-            return redirect(url('files_home', repo_name=c.repo_name,
+            raise HTTPFound(location=url('files_home', repo_name=c.repo_name,
                                 f_path=f_path))
 
         if c.action == 'download':
@@ -685,20 +684,15 @@
             ign_whitespace_lcl = get_ignore_ws(fid, request.GET)
 
             lim = request.GET.get('fulldiff') or self.cut_off_limit
-            _, cs1, cs2, diff, st = diffs.wrapped_diff(filenode_old=node1,
+            c.a_rev, c.cs_rev, a_path, diff, st, op = diffs.wrapped_diff(filenode_old=node1,
                                          filenode_new=node2,
                                          cut_off_limit=lim,
                                          ignore_whitespace=ign_whitespace_lcl,
                                          line_context=line_context_lcl,
                                          enable_comments=False)
-            op = ''
-            filename = node1.path
-            cs_changes = {
-                'fid': [cs1, cs2, op, filename, diff, st]
-            }
-            c.changes = cs_changes
+            c.file_diff_data = [(fid, fid, op, a_path, node2.path, diff, st)]
 
-        return render('files/file_diff.html')
+            return render('files/file_diff.html')
 
     @LoginRequired()
     @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
--- a/kallithea/controllers/followers.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/followers.py	Fri Nov 18 01:11:13 2016 +0100
@@ -29,11 +29,11 @@
 
 from pylons import tmpl_context as c, request
 
-from kallithea.lib.helpers import Page
 from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
 from kallithea.lib.base import BaseRepoController, render
+from kallithea.lib.page import Page
+from kallithea.lib.utils2 import safe_int
 from kallithea.model.db import UserFollowing
-from kallithea.lib.utils2 import safe_int
 
 log = logging.getLogger(__name__)
 
@@ -47,9 +47,9 @@
     @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
                                    'repository.admin')
     def followers(self, repo_name):
-        p = safe_int(request.GET.get('page', 1), 1)
+        p = safe_int(request.GET.get('page'), 1)
         repo_id = c.db_repo.repo_id
-        d = UserFollowing.get_repo_followers(repo_id)\
+        d = UserFollowing.get_repo_followers(repo_id) \
             .order_by(UserFollowing.follows_from)
         c.followers_pager = Page(d, page=p, items_per_page=20)
 
--- a/kallithea/controllers/forks.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/forks.py	Fri Nov 18 01:11:13 2016 +0100
@@ -30,21 +30,22 @@
 import traceback
 from formencode import htmlfill
 
-from pylons import tmpl_context as c, request, url
-from pylons.controllers.util import redirect
+from pylons import tmpl_context as c, request
 from pylons.i18n.translation import _
+from webob.exc import HTTPFound
 
 import kallithea.lib.helpers as h
 
-from kallithea.lib.helpers import Page
+from kallithea.config.routing import url
 from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator, \
     NotAnonymous, HasRepoPermissionAny, HasPermissionAnyDecorator, HasPermissionAny
 from kallithea.lib.base import BaseRepoController, render
+from kallithea.lib.page import Page
+from kallithea.lib.utils2 import safe_int
 from kallithea.model.db import Repository, UserFollowing, User, Ui
 from kallithea.model.repo import RepoModel
 from kallithea.model.forms import RepoForkForm
 from kallithea.model.scm import ScmModel, AvailableRepoGroupChoices
-from kallithea.lib.utils2 import safe_int
 
 log = logging.getLogger(__name__)
 
@@ -62,26 +63,24 @@
 
         c.landing_revs_choices, c.landing_revs = ScmModel().get_repo_landing_revs()
 
-        c.can_update = Ui.get_by_key(Ui.HOOK_UPDATE).ui_active
+        c.can_update = Ui.get_by_key('hooks', Ui.HOOK_UPDATE).ui_active
 
-    def __load_data(self, repo_name=None):
+    def __load_data(self):
         """
         Load defaults settings for edit, and update
-
-        :param repo_name:
         """
         self.__load_defaults()
 
-        c.repo_info = db_repo = Repository.get_by_repo_name(repo_name)
-        repo = db_repo.scm_instance
+        c.repo_info = c.db_repo
+        repo = c.db_repo.scm_instance
 
         if c.repo_info is None:
-            h.not_mapped_error(repo_name)
-            return redirect(url('repos'))
+            h.not_mapped_error(c.repo_name)
+            raise HTTPFound(location=url('repos'))
 
         c.default_user_id = User.get_default_user().user_id
-        c.in_public_journal = UserFollowing.query()\
-            .filter(UserFollowing.user_id == c.default_user_id)\
+        c.in_public_journal = UserFollowing.query() \
+            .filter(UserFollowing.user_id == c.default_user_id) \
             .filter(UserFollowing.follows_repository == c.repo_info).scalar()
 
         if c.repo_info.stats:
@@ -98,7 +97,7 @@
             c.stats_percentage = '%.2f' % ((float((last_rev)) /
                                             c.repo_last_rev) * 100)
 
-        defaults = RepoModel()._get_defaults(repo_name)
+        defaults = RepoModel()._get_defaults(c.repo_name)
         # alter the description to indicate a fork
         defaults['description'] = ('fork of repository: %s \n%s'
                                    % (defaults['repo_name'],
@@ -112,7 +111,7 @@
     @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
                                    'repository.admin')
     def forks(self, repo_name):
-        p = safe_int(request.GET.get('page', 1), 1)
+        p = safe_int(request.GET.get('page'), 1)
         repo_id = c.db_repo.repo_id
         d = []
         for r in Repository.get_repo_forks(repo_id):
@@ -137,9 +136,9 @@
         c.repo_info = Repository.get_by_repo_name(repo_name)
         if not c.repo_info:
             h.not_mapped_error(repo_name)
-            return redirect(url('home'))
+            raise HTTPFound(location=url('home'))
 
-        defaults = self.__load_data(repo_name)
+        defaults = self.__load_data()
 
         return htmlfill.render(
             render('forks/fork.html'),
@@ -164,15 +163,13 @@
             form_result = _form.to_python(dict(request.POST))
 
             # an approximation that is better than nothing
-            if not Ui.get_by_key(Ui.HOOK_UPDATE).ui_active:
+            if not Ui.get_by_key('hooks', Ui.HOOK_UPDATE).ui_active:
                 form_result['update_after_clone'] = False
 
             # create fork is done sometimes async on celery, db transaction
             # management is handled there.
             task = RepoModel().create_fork(form_result, self.authuser.user_id)
-            from celery.result import BaseAsyncResult
-            if isinstance(task, BaseAsyncResult):
-                task_id = task.task_id
+            task_id = task.task_id
         except formencode.Invalid as errors:
             return htmlfill.render(
                 render('forks/fork.html'),
@@ -186,6 +183,6 @@
             h.flash(_('An error occurred during repository forking %s') %
                     repo_name, category='error')
 
-        return redirect(h.url('repo_creating_home',
+        raise HTTPFound(location=h.url('repo_creating_home',
                               repo_name=form_result['repo_name_full'],
                               task_id=task_id))
--- a/kallithea/controllers/home.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/home.py	Fri Nov 18 01:11:13 2016 +0100
@@ -57,13 +57,10 @@
         c.groups = self.scm_model.get_repo_groups()
         c.group = None
 
-        c.repos_list = Repository.query()\
-                        .filter(Repository.group_id == None)\
-                        .order_by(func.lower(Repository.repo_name))\
-                        .all()
+        repos_list = Repository.query(sorted=True).filter_by(group=None).all()
 
-        repos_data = RepoModel().get_repos_as_dict(repos_list=c.repos_list,
-                                                   admin=False)
+        repos_data = RepoModel().get_repos_as_dict(repos_list=repos_list,
+                                                   admin=False, short_name=True)
         #json used to render the grid
         c.data = json.dumps(repos_data)
 
@@ -75,26 +72,35 @@
         #wrapper for conditional cache
         def _c():
             log.debug('generating switcher repo/groups list')
-            all_repos = Repository.query().order_by(Repository.repo_name).all()
-            repo_iter = self.scm_model.get_repos(all_repos, simple=True)
-            all_groups = RepoGroup.query().order_by(RepoGroup.group_name).all()
+            all_repos = Repository.query(sorted=True).all()
+            repo_iter = self.scm_model.get_repos(all_repos)
+            all_groups = RepoGroup.query(sorted=True).all()
             repo_groups_iter = self.scm_model.get_repo_groups(all_groups)
 
             res = [{
                     'text': _('Groups'),
                     'children': [
-                       {'id': obj.group_name, 'text': obj.group_name,
-                        'type': 'group', 'obj': {}} for obj in repo_groups_iter]
-                   }, {
+                       {'id': obj.group_name,
+                        'text': obj.group_name,
+                        'type': 'group',
+                        'obj': {}}
+                       for obj in repo_groups_iter
+                    ],
+                   },
+                   {
                     'text': _('Repositories'),
                     'children': [
-                       {'id': obj['name'], 'text': obj['name'],
-                        'type': 'repo', 'obj': obj['dbrepo']} for obj in repo_iter]
+                       {'id': obj.repo_name,
+                        'text': obj.repo_name,
+                        'type': 'repo',
+                        'obj': obj.get_dict()}
+                       for obj in repo_iter
+                    ],
                    }]
 
             data = {
                 'more': False,
-                'results': res
+                'results': res,
             }
             return data
 
@@ -109,17 +115,6 @@
     @LoginRequired()
     @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
                                    'repository.admin')
-    def branch_tag_switcher(self, repo_name):
-        if request.is_xhr:
-            c.db_repo = Repository.get_by_repo_name(repo_name)
-            if c.db_repo:
-                c.db_repo_scm_instance = c.db_repo.scm_instance
-                return render('/switch_to_list.html')
-        raise HTTPBadRequest()
-
-    @LoginRequired()
-    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
-                                   'repository.admin')
     @jsonify
     def repo_refs_data(self, repo_name):
         repo = Repository.get_by_repo_name(repo_name).scm_instance
@@ -130,6 +125,12 @@
                 'text': _('Branch'),
                 'children': [{'id': rev, 'text': name, 'type': 'branch'} for name, rev in _branches]
             })
+        _closed_branches = repo.closed_branches.items()
+        if _closed_branches:
+            res.append({
+                'text': _('Closed Branches'),
+                'children': [{'id': rev, 'text': name, 'type': 'closed-branch'} for name, rev in _closed_branches]
+            })
         _tags = repo.tags.items()
         if _tags:
             res.append({
--- a/kallithea/controllers/journal.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/journal.py	Fri Nov 18 01:11:13 2016 +0100
@@ -15,7 +15,7 @@
 kallithea.controllers.journal
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
-Journal controller for pylons
+Journal controller
 
 This file was forked by the Kallithea project in July 2014.
 Original author and date, and relevant copyright and licensing information is below:
@@ -37,19 +37,20 @@
 from webhelpers.feedgenerator import Atom1Feed, Rss201rev2Feed
 
 from webob.exc import HTTPBadRequest
-from pylons import request, tmpl_context as c, response, url
+from pylons import request, tmpl_context as c, response
 from pylons.i18n.translation import _
 
+from kallithea.config.routing import url
 from kallithea.controllers.admin.admin import _journal_filter
 from kallithea.model.db import UserLog, UserFollowing, Repository, User
 from kallithea.model.meta import Session
 from kallithea.model.repo import RepoModel
 import kallithea.lib.helpers as h
-from kallithea.lib.helpers import Page
 from kallithea.lib.auth import LoginRequired, NotAnonymous
 from kallithea.lib.base import BaseController, render
+from kallithea.lib.compat import json
+from kallithea.lib.page import Page
 from kallithea.lib.utils2 import safe_int, AttributeDict
-from kallithea.lib.compat import json
 
 log = logging.getLogger(__name__)
 
@@ -77,10 +78,10 @@
         return groups
 
     def _get_journal_data(self, following_repos):
-        repo_ids = [x.follows_repository.repo_id for x in following_repos
-                    if x.follows_repository is not None]
-        user_ids = [x.follows_user.user_id for x in following_repos
-                    if x.follows_user is not None]
+        repo_ids = [x.follows_repository_id for x in following_repos
+                    if x.follows_repository_id is not None]
+        user_ids = [x.follows_user_id for x in following_repos
+                    if x.follows_user_id is not None]
 
         filtering_criterion = None
 
@@ -92,12 +93,12 @@
         if not repo_ids and user_ids:
             filtering_criterion = UserLog.user_id.in_(user_ids)
         if filtering_criterion is not None:
-            journal = self.sa.query(UserLog)\
-                .options(joinedload(UserLog.user))\
+            journal = self.sa.query(UserLog) \
+                .options(joinedload(UserLog.user)) \
                 .options(joinedload(UserLog.repository))
             #filter
             journal = _journal_filter(journal, c.search_term)
-            journal = journal.filter(filtering_criterion)\
+            journal = journal.filter(filtering_criterion) \
                         .order_by(UserLog.action_date.desc())
         else:
             journal = []
@@ -192,11 +193,11 @@
     @NotAnonymous()
     def index(self):
         # Return a rendered template
-        p = safe_int(request.GET.get('page', 1), 1)
+        p = safe_int(request.GET.get('page'), 1)
         c.user = User.get(self.authuser.user_id)
-        c.following = self.sa.query(UserFollowing)\
-            .filter(UserFollowing.user_id == self.authuser.user_id)\
-            .options(joinedload(UserFollowing.follows_repository))\
+        c.following = self.sa.query(UserFollowing) \
+            .filter(UserFollowing.user_id == self.authuser.user_id) \
+            .options(joinedload(UserFollowing.follows_repository)) \
             .all()
 
         journal = self._get_journal_data(c.following)
@@ -205,15 +206,13 @@
             return url.current(filter=c.search_term, **kw)
 
         c.journal_pager = Page(journal, page=p, items_per_page=20, url=url_generator)
-        c.journal_day_aggreagate = self._get_daily_aggregate(c.journal_pager)
+        c.journal_day_aggregate = self._get_daily_aggregate(c.journal_pager)
 
         if request.environ.get('HTTP_X_PARTIAL_XHR'):
             return render('journal/journal_data.html')
 
-        repos_list = Session().query(Repository)\
-                     .filter(Repository.user_id ==
-                             self.authuser.user_id)\
-                     .order_by(func.lower(Repository.repo_name)).all()
+        repos_list = Repository.query(sorted=True) \
+            .filter_by(owner_id=self.authuser.user_id).all()
 
         repos_data = RepoModel().get_repos_as_dict(repos_list=repos_list,
                                                    admin=True)
@@ -255,7 +254,7 @@
             cs_cache = repo.changeset_cache
             row = {
                 "menu": quick_menu(repo.repo_name),
-                "raw_name": repo.repo_name.lower(),
+                "raw_name": repo.repo_name,
                 "name": repo_lnk(repo.repo_name, repo.repo_type,
                                  repo.repo_state, repo.private, repo.fork),
                 "last_changeset": last_rev(repo.repo_name, cs_cache),
@@ -280,9 +279,9 @@
         """
         Produce an atom-1.0 feed via feedgenerator module
         """
-        following = self.sa.query(UserFollowing)\
-            .filter(UserFollowing.user_id == self.authuser.user_id)\
-            .options(joinedload(UserFollowing.follows_repository))\
+        following = self.sa.query(UserFollowing) \
+            .filter(UserFollowing.user_id == self.authuser.user_id) \
+            .options(joinedload(UserFollowing.follows_repository)) \
             .all()
         return self._atom_feed(following, public=False)
 
@@ -292,9 +291,9 @@
         """
         Produce an rss feed via feedgenerator module
         """
-        following = self.sa.query(UserFollowing)\
-            .filter(UserFollowing.user_id == self.authuser.user_id)\
-            .options(joinedload(UserFollowing.follows_repository))\
+        following = self.sa.query(UserFollowing) \
+            .filter(UserFollowing.user_id == self.authuser.user_id) \
+            .options(joinedload(UserFollowing.follows_repository)) \
             .all()
         return self._rss_feed(following, public=False)
 
@@ -312,7 +311,7 @@
                 log.error(traceback.format_exc())
                 raise HTTPBadRequest()
 
-        repo_id = request.POST.get('follows_repo_id')
+        repo_id = request.POST.get('follows_repository_id')
         if repo_id:
             try:
                 self.scm_model.toggle_following_repo(repo_id,
@@ -328,18 +327,18 @@
     @LoginRequired()
     def public_journal(self):
         # Return a rendered template
-        p = safe_int(request.GET.get('page', 1), 1)
+        p = safe_int(request.GET.get('page'), 1)
 
-        c.following = self.sa.query(UserFollowing)\
-            .filter(UserFollowing.user_id == self.authuser.user_id)\
-            .options(joinedload(UserFollowing.follows_repository))\
+        c.following = self.sa.query(UserFollowing) \
+            .filter(UserFollowing.user_id == self.authuser.user_id) \
+            .options(joinedload(UserFollowing.follows_repository)) \
             .all()
 
         journal = self._get_journal_data(c.following)
 
         c.journal_pager = Page(journal, page=p, items_per_page=20)
 
-        c.journal_day_aggreagate = self._get_daily_aggregate(c.journal_pager)
+        c.journal_day_aggregate = self._get_daily_aggregate(c.journal_pager)
 
         if request.environ.get('HTTP_X_PARTIAL_XHR'):
             return render('journal/journal_data.html')
@@ -351,9 +350,9 @@
         """
         Produce an atom-1.0 feed via feedgenerator module
         """
-        c.following = self.sa.query(UserFollowing)\
-            .filter(UserFollowing.user_id == self.authuser.user_id)\
-            .options(joinedload(UserFollowing.follows_repository))\
+        c.following = self.sa.query(UserFollowing) \
+            .filter(UserFollowing.user_id == self.authuser.user_id) \
+            .options(joinedload(UserFollowing.follows_repository)) \
             .all()
 
         return self._atom_feed(c.following)
@@ -363,9 +362,9 @@
         """
         Produce an rss2 feed via feedgenerator module
         """
-        c.following = self.sa.query(UserFollowing)\
-            .filter(UserFollowing.user_id == self.authuser.user_id)\
-            .options(joinedload(UserFollowing.follows_repository))\
+        c.following = self.sa.query(UserFollowing) \
+            .filter(UserFollowing.user_id == self.authuser.user_id) \
+            .options(joinedload(UserFollowing.follows_repository)) \
             .all()
 
         return self._rss_feed(c.following)
--- a/kallithea/controllers/login.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/login.py	Fri Nov 18 01:11:13 2016 +0100
@@ -31,12 +31,12 @@
 import formencode
 
 from formencode import htmlfill
+from pylons.i18n.translation import _
+from pylons import request, session, tmpl_context as c
 from webob.exc import HTTPFound, HTTPBadRequest
-from pylons.i18n.translation import _
-from pylons.controllers.util import redirect
-from pylons import request, session, tmpl_context as c, url
 
 import kallithea.lib.helpers as h
+from kallithea.config.routing import url
 from kallithea.lib.auth import AuthUser, HasPermissionAnyDecorator
 from kallithea.lib.base import BaseController, log_in_user, render
 from kallithea.lib.exceptions import UserCreationError
@@ -79,11 +79,10 @@
         else:
             c.came_from = url('home')
 
-        not_default = self.authuser.username != User.DEFAULT_USER
         ip_allowed = AuthUser.check_ip_allowed(self.authuser, self.ip_addr)
 
         # redirect if already logged in
-        if self.authuser.is_authenticated and not_default and ip_allowed:
+        if self.authuser.is_authenticated and ip_allowed:
             raise HTTPFound(location=c.came_from)
 
         if request.POST:
@@ -93,11 +92,11 @@
                 c.form_result = login_form.to_python(dict(request.POST))
                 # form checks for username/password, now we're authenticated
                 username = c.form_result['username']
-                user = User.get_by_username(username, case_insensitive=True)
+                user = User.get_by_username_or_email(username, case_insensitive=True)
             except formencode.Invalid as errors:
                 defaults = errors.value
                 # remove password from filling in form again
-                del defaults['password']
+                defaults.pop('password', None)
                 return htmlfill.render(
                     render('/login.html'),
                     defaults=errors.value,
@@ -121,7 +120,7 @@
     @HasPermissionAnyDecorator('hg.admin', 'hg.register.auto_activate',
                                'hg.register.manual_activate')
     def register(self):
-        c.auto_active = 'hg.register.auto_activate' in User.get_default_user()\
+        c.auto_active = 'hg.register.auto_activate' in User.get_default_user() \
             .AuthUser.permissions['global']
 
         settings = Setting.get_app_settings()
@@ -149,10 +148,10 @@
                                                  error_dict=error_dict)
 
                 UserModel().create_registration(form_result)
-                h.flash(_('You have successfully registered into Kallithea'),
+                h.flash(_('You have successfully registered with %s') % (c.site_name or 'Kallithea'),
                         category='success')
                 Session().commit()
-                return redirect(url('login_home'))
+                raise HTTPFound(location=url('login_home'))
 
             except formencode.Invalid as errors:
                 return htmlfill.render(
@@ -196,7 +195,7 @@
                 redirect_link = UserModel().send_reset_password_email(form_result)
                 h.flash(_('A password reset confirmation code has been sent'),
                             category='success')
-                return redirect(redirect_link)
+                raise HTTPFound(location=redirect_link)
 
             except formencode.Invalid as errors:
                 return htmlfill.render(
@@ -249,12 +248,12 @@
 
         UserModel().reset_password(form_result['email'], form_result['password'])
         h.flash(_('Successfully updated password'), category='success')
-        return redirect(url('login_home'))
+        raise HTTPFound(location=url('login_home'))
 
     def logout(self):
         session.delete()
         log.info('Logging out and deleting session for user')
-        redirect(url('home'))
+        raise HTTPFound(location=url('home'))
 
     def authentication_token(self):
         """Return the CSRF protection token for the session - just like it
--- a/kallithea/controllers/pullrequests.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/pullrequests.py	Fri Nov 18 01:11:13 2016 +0100
@@ -30,27 +30,26 @@
 import formencode
 import re
 
-from webob.exc import HTTPNotFound, HTTPForbidden, HTTPBadRequest
-
-from pylons import request, tmpl_context as c, url
-from pylons.controllers.util import redirect
+from pylons import request, tmpl_context as c
 from pylons.i18n.translation import _
+from webob.exc import HTTPFound, HTTPNotFound, HTTPForbidden, HTTPBadRequest
 
-from kallithea.lib.vcs.utils.hgcompat import unionrepo
-from kallithea.lib.compat import json
-from kallithea.lib.base import BaseRepoController, render
-from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator,\
-    NotAnonymous
-from kallithea.lib.helpers import Page
+from kallithea.config.routing import url
 from kallithea.lib import helpers as h
 from kallithea.lib import diffs
+from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator, \
+    NotAnonymous
+from kallithea.lib.base import BaseRepoController, render
+from kallithea.lib.compat import json, OrderedDict
+from kallithea.lib.diffs import LimitedDiffContainer
 from kallithea.lib.exceptions import UserInvalidException
+from kallithea.lib.page import Page
 from kallithea.lib.utils import action_logger, jsonify
+from kallithea.lib.vcs.exceptions import EmptyRepositoryError, ChangesetDoesNotExistError
 from kallithea.lib.vcs.utils import safe_str
-from kallithea.lib.vcs.exceptions import EmptyRepositoryError
-from kallithea.lib.diffs import LimitedDiffContainer
-from kallithea.model.db import PullRequest, ChangesetStatus, ChangesetComment,\
-    PullRequestReviewers, User
+from kallithea.lib.vcs.utils.hgcompat import unionrepo
+from kallithea.model.db import PullRequest, ChangesetStatus, ChangesetComment, \
+    PullRequestReviewer, User
 from kallithea.model.pull_request import PullRequestModel
 from kallithea.model.meta import Session
 from kallithea.model.repo import RepoModel
@@ -58,7 +57,8 @@
 from kallithea.model.changeset_status import ChangesetStatusModel
 from kallithea.model.forms import PullRequestForm, PullRequestPostForm
 from kallithea.lib.utils2 import safe_int
-from kallithea.controllers.changeset import _ignorews_url, _context_url
+from kallithea.controllers.changeset import _ignorews_url, _context_url, \
+    create_comment
 from kallithea.controllers.compare import CompareController
 from kallithea.lib.graphmod import graph_data
 
@@ -140,8 +140,7 @@
                 continue
             n = 'tag:%s:%s' % (tag, tagrev)
             tags.append((n, tag))
-            if rev == tagrev:
-                selected = n
+            # note: even if rev == tagrev, don't select the static tag - it must be chosen explicitly
 
         # prio 1: rev was selected as existing entry above
 
@@ -182,9 +181,12 @@
         if pull_request.is_closed():
             return False
 
-        owner = self.authuser.user_id == pull_request.user_id
-        reviewer = self.authuser.user_id in [x.user_id for x in
-                                                   pull_request.reviewers]
+        owner = self.authuser.user_id == pull_request.owner_id
+        reviewer = PullRequestReviewer.query() \
+            .filter(PullRequestReviewer.pull_request == pull_request) \
+            .filter(PullRequestReviewer.user_id == self.authuser.user_id) \
+            .count() != 0
+
         return self.authuser.admin or owner or reviewer
 
     @LoginRequired()
@@ -193,9 +195,14 @@
     def show_all(self, repo_name):
         c.from_ = request.GET.get('from_') or ''
         c.closed = request.GET.get('closed') or ''
-        c.pull_requests = PullRequestModel().get_all(repo_name, from_=c.from_, closed=c.closed)
-        c.repo_name = repo_name
-        p = safe_int(request.GET.get('page', 1), 1)
+        p = safe_int(request.GET.get('page'), 1)
+
+        q = PullRequest.query(include_closed=c.closed, sorted=True)
+        if c.from_:
+            q = q.filter_by(org_repo=c.db_repo)
+        else:
+            q = q.filter_by(other_repo=c.db_repo)
+        c.pull_requests = q.all()
 
         c.pullrequests_pager = Page(c.pull_requests, page=p, items_per_page=100)
 
@@ -206,22 +213,24 @@
     def show_my(self):
         c.closed = request.GET.get('closed') or ''
 
-        def _filter(pr):
-            s = sorted(pr, key=lambda o: o.created_on, reverse=True)
-            if not c.closed:
-                s = filter(lambda p: p.status != PullRequest.STATUS_CLOSED, s)
-            return s
+        c.my_pull_requests = PullRequest.query(
+            include_closed=c.closed,
+            sorted=True,
+        ).filter_by(owner_id=self.authuser.user_id).all()
 
-        c.my_pull_requests = _filter(PullRequest.query()\
-                                .filter(PullRequest.user_id ==
-                                        self.authuser.user_id)\
-                                .all())
-
-        c.participate_in_pull_requests = _filter(PullRequest.query()\
-                                .join(PullRequestReviewers)\
-                                .filter(PullRequestReviewers.user_id ==
-                                        self.authuser.user_id)\
-                                                 )
+        c.participate_in_pull_requests = []
+        c.participate_in_pull_requests_todo = []
+        done_status = set([ChangesetStatus.STATUS_APPROVED, ChangesetStatus.STATUS_REJECTED])
+        for pr in PullRequest.query(
+            include_closed=c.closed,
+            reviewer_id=self.authuser.user_id,
+            sorted=True,
+        ):
+            status = pr.user_review_status(c.authuser.user_id) # very inefficient!!!
+            if status in done_status:
+                c.participate_in_pull_requests.append(pr)
+            else:
+                c.participate_in_pull_requests_todo.append(pr)
 
         return render('/pullrequests/pullrequest_show_my.html')
 
@@ -237,7 +246,7 @@
         except EmptyRepositoryError as e:
             h.flash(h.literal(_('There are no changesets yet')),
                     category='warning')
-            redirect(url('summary_home', repo_name=org_repo.repo_name))
+            raise HTTPFound(location=url('summary_home', repo_name=org_repo.repo_name))
 
         org_rev = request.GET.get('rev_end')
         # rev_start is not directly useful - its parent could however be used
@@ -288,7 +297,7 @@
                                    'repository.admin')
     @jsonify
     def repo_info(self, repo_name):
-        repo = RepoModel()._get_repo(repo_name)
+        repo = c.db_repo
         refs, selected_ref = self._get_repo_refs(repo.scm_instance)
         return {
             'description': repo.description.split('\n', 1)[0],
@@ -301,7 +310,7 @@
     @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
                                    'repository.admin')
     def create(self, repo_name):
-        repo = RepoModel()._get_repo(repo_name)
+        repo = c.db_repo
         try:
             _form = PullRequestForm(repo.repo_id)().to_python(request.POST)
         except formencode.Invalid as errors:
@@ -319,9 +328,8 @@
          org_ref_name,
          org_rev) = org_ref.split(':')
         if org_ref_type == 'rev':
-            org_ref_type = 'branch'
             cs = org_repo.scm_instance.get_changeset(org_rev)
-            org_ref = '%s:%s:%s' % (org_ref_type, cs.branch, cs.raw_id)
+            org_ref = 'branch:%s:%s' % (cs.branch, cs.raw_id)
 
         other_repo_name = _form['other_repo']
         other_ref = _form['other_ref'] # will have symbolic name and head revision
@@ -329,21 +337,38 @@
         (other_ref_type,
          other_ref_name,
          other_rev) = other_ref.split(':')
+        if other_ref_type == 'rev':
+            cs = other_repo.scm_instance.get_changeset(other_rev)
+            other_ref_name = cs.raw_id[:12]
+            other_ref = '%s:%s:%s' % (other_ref_type, other_ref_name, cs.raw_id)
 
-        cs_ranges, _cs_ranges_not, ancestor_rev = \
+        cs_ranges, _cs_ranges_not, ancestor_revs = \
             CompareController._get_changesets(org_repo.scm_instance.alias,
                                               other_repo.scm_instance, other_rev, # org and other "swapped"
                                               org_repo.scm_instance, org_rev,
                                               )
+        ancestor_rev = msg = None
+        if not cs_ranges:
+            msg = _('Cannot create empty pull request')
+        elif not ancestor_revs:
+            ancestor_rev = org_repo.scm_instance.EMPTY_CHANGESET
+        elif len(ancestor_revs) == 1:
+            ancestor_rev = ancestor_revs[0]
+        else:
+            msg = _('Cannot create pull request - criss cross merge detected, please merge a later %s revision to %s'
+                    ) % (other_ref_name, org_ref_name)
         if ancestor_rev is None:
-            ancestor_rev = org_repo.scm_instance.EMPTY_CHANGESET
+            h.flash(msg, category='error')
+            log.error(msg)
+            raise HTTPNotFound
+
         revisions = [cs_.raw_id for cs_ in cs_ranges]
 
         # hack: ancestor_rev is not an other_rev but we want to show the
         # requested destination and have the exact ancestor
         other_ref = '%s:%s:%s' % (other_ref_type, other_ref_name, ancestor_rev)
 
-        reviewers = _form['review_members']
+        reviewer_ids = []
 
         title = _form['pullrequest_title']
         if not title:
@@ -355,10 +380,10 @@
                                             other_repo_name, h.short_ref(other_ref_type, other_ref_name))
         description = _form['pullrequest_desc'].strip() or _('No description')
         try:
+            created_by = User.get(self.authuser.user_id)
             pull_request = PullRequestModel().create(
-                self.authuser.user_id, org_repo_name, org_ref, other_repo_name,
-                other_ref, revisions, reviewers, title, description
-            )
+                created_by, org_repo, org_ref, other_repo, other_ref, revisions,
+                title, description, reviewer_ids)
             Session().commit()
             h.flash(_('Successfully opened new pull request'),
                     category='success')
@@ -369,59 +394,73 @@
             h.flash(_('Error occurred while creating pull request'),
                     category='error')
             log.error(traceback.format_exc())
-            return redirect(url('pullrequest_home', repo_name=repo_name))
+            raise HTTPFound(location=url('pullrequest_home', repo_name=repo_name))
 
-        return redirect(pull_request.url())
+        raise HTTPFound(location=pull_request.url())
 
-    def create_update(self, old_pull_request, updaterev, title, description, reviewers_ids):
-        org_repo = RepoModel()._get_repo(old_pull_request.org_repo.repo_name)
+    def create_new_iteration(self, old_pull_request, new_rev, title, description, reviewer_ids):
+        org_repo = old_pull_request.org_repo
         org_ref_type, org_ref_name, org_rev = old_pull_request.org_ref.split(':')
-        new_org_rev = self._get_ref_rev(org_repo, 'rev', updaterev)
+        new_org_rev = self._get_ref_rev(org_repo, 'rev', new_rev)
 
-        other_repo = RepoModel()._get_repo(old_pull_request.other_repo.repo_name)
+        other_repo = old_pull_request.other_repo
         other_ref_type, other_ref_name, other_rev = old_pull_request.other_ref.split(':') # other_rev is ancestor
         #assert other_ref_type == 'branch', other_ref_type # TODO: what if not?
         new_other_rev = self._get_ref_rev(other_repo, other_ref_type, other_ref_name)
 
-        cs_ranges, _cs_ranges_not, ancestor_rev = CompareController._get_changesets(org_repo.scm_instance.alias,
+        cs_ranges, _cs_ranges_not, ancestor_revs = CompareController._get_changesets(org_repo.scm_instance.alias,
             other_repo.scm_instance, new_other_rev, # org and other "swapped"
             org_repo.scm_instance, new_org_rev)
+        ancestor_rev = msg = None
+        if not cs_ranges:
+            msg = _('Cannot create empty pull request update') # cannot happen!
+        elif not ancestor_revs:
+            msg = _('Cannot create pull request update - no common ancestor found') # cannot happen
+        elif len(ancestor_revs) == 1:
+            ancestor_rev = ancestor_revs[0]
+        else:
+            msg = _('Cannot create pull request update - criss cross merge detected, please merge a later %s revision to %s'
+                    ) % (other_ref_name, org_ref_name)
+        if ancestor_rev is None:
+            h.flash(msg, category='error')
+            log.error(msg)
+            raise HTTPNotFound
 
         old_revisions = set(old_pull_request.revisions)
         revisions = [cs.raw_id for cs in cs_ranges]
         new_revisions = [r for r in revisions if r not in old_revisions]
         lost = old_revisions.difference(revisions)
 
-        infos = ['This is an update of %s "%s".' %
+        infos = ['This is a new iteration of %s "%s".' %
                  (h.canonical_url('pullrequest_show', repo_name=old_pull_request.other_repo.repo_name,
                       pull_request_id=old_pull_request.pull_request_id),
                   old_pull_request.title)]
 
         if lost:
-            infos.append(_('Missing changesets since the previous pull request:'))
+            infos.append(_('Missing changesets since the previous iteration:'))
             for r in old_pull_request.revisions:
                 if r in lost:
                     rev_desc = org_repo.get_changeset(r).message.split('\n')[0]
-                    infos.append('  %s "%s"' % (h.short_id(r), rev_desc))
+                    infos.append('  %s %s' % (h.short_id(r), rev_desc))
 
         if new_revisions:
-            infos.append(_('New changesets on %s %s since the previous pull request:') % (org_ref_type, org_ref_name))
+            infos.append(_('New changesets on %s %s since the previous iteration:') % (org_ref_type, org_ref_name))
             for r in reversed(revisions):
                 if r in new_revisions:
                     rev_desc = org_repo.get_changeset(r).message.split('\n')[0]
                     infos.append('  %s %s' % (h.short_id(r), h.shorter(rev_desc, 80)))
 
             if ancestor_rev == other_rev:
-                infos.append(_("Ancestor didn't change - show diff since previous version:"))
+                infos.append(_("Ancestor didn't change - diff since previous iteration:"))
                 infos.append(h.canonical_url('compare_url',
                                  repo_name=org_repo.repo_name, # other_repo is always same as repo_name
                                  org_ref_type='rev', org_ref_name=h.short_id(org_rev), # use old org_rev as base
                                  other_ref_type='rev', other_ref_name=h.short_id(new_org_rev),
                                  )) # note: linear diff, merge or not doesn't matter
             else:
-                infos.append(_('This pull request is based on another %s revision and there is no simple diff.') % other_ref_name)
+                infos.append(_('This iteration is based on another %s revision and there is no simple diff.') % other_ref_name)
         else:
-           infos.append(_('No changes found on %s %s since previous version.') % (org_ref_type, org_ref_name))
+           infos.append(_('No changes found on %s %s since previous iteration.') % (org_ref_type, org_ref_name))
            # TODO: fail?
 
         # hack: ancestor_rev is not an other_ref but we want to show the
@@ -436,19 +475,17 @@
             v = 2
         title = '%s (v%s)' % (title.strip(), v)
 
-        # using a mail-like separator, insert new update info at the top of the list
+        # using a mail-like separator, insert new iteration info in description with latest first
         descriptions = description.replace('\r\n', '\n').split('\n-- \n', 1)
         description = descriptions[0].strip() + '\n\n-- \n' + '\n'.join(infos)
         if len(descriptions) > 1:
             description += '\n\n' + descriptions[1].strip()
 
         try:
+            created_by = User.get(self.authuser.user_id)
             pull_request = PullRequestModel().create(
-                self.authuser.user_id,
-                old_pull_request.org_repo.repo_name, new_org_ref,
-                old_pull_request.other_repo.repo_name, new_other_ref,
-                revisions, reviewers_ids, title, description
-            )
+                created_by, org_repo, new_org_ref, other_repo, new_other_ref, revisions,
+                title, description, reviewer_ids)
         except UserInvalidException as u:
             h.flash(_('Invalid reviewer "%s" specified') % u, category='error')
             raise HTTPBadRequest()
@@ -456,21 +493,21 @@
             h.flash(_('Error occurred while creating pull request'),
                     category='error')
             log.error(traceback.format_exc())
-            return redirect(old_pull_request.url())
+            raise HTTPFound(location=old_pull_request.url())
 
         ChangesetCommentsModel().create(
-            text=_('Closed, replaced by %s .') % pull_request.url(canonical=True),
-            repo=old_pull_request.other_repo.repo_id,
-            user=c.authuser.user_id,
+            text=_('Closed, next iteration: %s .') % pull_request.url(canonical=True),
+            repo=old_pull_request.other_repo_id,
+            author=c.authuser.user_id,
             pull_request=old_pull_request.pull_request_id,
             closing_pr=True)
         PullRequestModel().close_pull_request(old_pull_request.pull_request_id)
 
         Session().commit()
-        h.flash(_('Pull request update created'),
+        h.flash(_('New pull request iteration created'),
                 category='success')
 
-        return redirect(pull_request.url())
+        raise HTTPFound(location=pull_request.url())
 
     # pullrequest_post for PR editing
     @LoginRequired()
@@ -483,29 +520,45 @@
             raise HTTPForbidden()
         assert pull_request.other_repo.repo_name == repo_name
         #only owner or admin can update it
-        owner = pull_request.owner.user_id == c.authuser.user_id
+        owner = pull_request.owner_id == c.authuser.user_id
         repo_admin = h.HasRepoPermissionAny('repository.admin')(c.repo_name)
         if not (h.HasPermissionAny('hg.admin')() or repo_admin or owner):
             raise HTTPForbidden()
 
         _form = PullRequestPostForm()().to_python(request.POST)
-        reviewers_ids = [int(s) for s in _form['review_members']]
+        reviewer_ids = set(int(s) for s in _form['review_members'])
+
+        org_reviewer_ids = set(int(s) for s in _form['org_review_members'])
+        current_reviewer_ids = set(prr.user_id for prr in pull_request.reviewers)
+        other_added = [User.get(u) for u in current_reviewer_ids - org_reviewer_ids]
+        other_removed = [User.get(u) for u in org_reviewer_ids - current_reviewer_ids]
+        if other_added:
+            h.flash(_('Meanwhile, the following reviewers have been added: %s') %
+                    (', '.join(u.username for u in other_added)),
+                    category='warning')
+        if other_removed:
+            h.flash(_('Meanwhile, the following reviewers have been removed: %s') %
+                    (', '.join(u.username for u in other_removed)),
+                    category='warning')
 
         if _form['updaterev']:
-            return self.create_update(pull_request,
+            return self.create_new_iteration(pull_request,
                                       _form['updaterev'],
                                       _form['pullrequest_title'],
                                       _form['pullrequest_desc'],
-                                      reviewers_ids)
+                                      reviewer_ids)
 
         old_description = pull_request.description
         pull_request.title = _form['pullrequest_title']
         pull_request.description = _form['pullrequest_desc'].strip() or _('No description')
         pull_request.owner = User.get_by_username(_form['owner'])
         user = User.get(c.authuser.user_id)
+        add_reviewer_ids = reviewer_ids - org_reviewer_ids - current_reviewer_ids
+        remove_reviewer_ids = (org_reviewer_ids - reviewer_ids) & current_reviewer_ids
         try:
             PullRequestModel().mention_from_description(user, pull_request, old_description)
-            PullRequestModel().update_reviewers(user, pull_request_id, reviewers_ids)
+            PullRequestModel().add_reviewers(user, pull_request, add_reviewer_ids)
+            PullRequestModel().remove_reviewers(user, pull_request, remove_reviewer_ids)
         except UserInvalidException as u:
             h.flash(_('Invalid reviewer "%s" specified') % u, category='error')
             raise HTTPBadRequest()
@@ -513,7 +566,7 @@
         Session().commit()
         h.flash(_('Pull request updated'), category='success')
 
-        return redirect(pull_request.url())
+        raise HTTPFound(location=pull_request.url())
 
     @LoginRequired()
     @NotAnonymous()
@@ -523,12 +576,12 @@
     def delete(self, repo_name, pull_request_id):
         pull_request = PullRequest.get_or_404(pull_request_id)
         #only owner can delete it !
-        if pull_request.owner.user_id == c.authuser.user_id:
+        if pull_request.owner_id == c.authuser.user_id:
             PullRequestModel().delete(pull_request)
             Session().commit()
             h.flash(_('Successfully deleted pull request'),
                     category='success')
-            return redirect(url('my_pullrequests'))
+            raise HTTPFound(location=url('my_pullrequests'))
         raise HTTPForbidden()
 
     @LoginRequired()
@@ -557,80 +610,98 @@
         c.a_repo = c.pull_request.other_repo
         (c.a_ref_type,
          c.a_ref_name,
-         c.a_rev) = c.pull_request.other_ref.split(':') # other_rev is ancestor
+         c.a_rev) = c.pull_request.other_ref.split(':') # a_rev is ancestor
 
         org_scm_instance = c.cs_repo.scm_instance # property with expensive cache invalidation check!!!
         c.cs_repo = c.cs_repo
-        c.cs_ranges = [org_scm_instance.get_changeset(x) for x in c.pull_request.revisions]
+        try:
+            c.cs_ranges = [org_scm_instance.get_changeset(x)
+                           for x in c.pull_request.revisions]
+        except ChangesetDoesNotExistError:
+            c.cs_ranges = []
+            h.flash(_('Revision %s not found in %s') % (x, c.cs_repo.repo_name),
+                'error')
         c.cs_ranges_org = None # not stored and not important and moving target - could be calculated ...
         revs = [ctx.revision for ctx in reversed(c.cs_ranges)]
         c.jsdata = json.dumps(graph_data(org_scm_instance, revs))
 
         c.is_range = False
-        if c.a_ref_type == 'rev': # this looks like a free range where target is ancestor
-            cs_a = org_scm_instance.get_changeset(c.a_rev)
-            root_parents = c.cs_ranges[0].parents
-            c.is_range = cs_a in root_parents
-            #c.merge_root = len(root_parents) > 1 # a range starting with a merge might deserve a warning
+        try:
+            if c.a_ref_type == 'rev': # this looks like a free range where target is ancestor
+                cs_a = org_scm_instance.get_changeset(c.a_rev)
+                root_parents = c.cs_ranges[0].parents
+                c.is_range = cs_a in root_parents
+                #c.merge_root = len(root_parents) > 1 # a range starting with a merge might deserve a warning
+        except ChangesetDoesNotExistError: # probably because c.a_rev not found
+            pass
+        except IndexError: # probably because c.cs_ranges is empty, probably because revisions are missing
+            pass
 
         avail_revs = set()
         avail_show = []
         c.cs_branch_name = c.cs_ref_name
+        c.a_branch_name = None
         other_scm_instance = c.a_repo.scm_instance
         c.update_msg = ""
         c.update_msg_other = ""
-        if org_scm_instance.alias == 'hg' and c.a_ref_name != 'ancestor':
-            if c.cs_ref_type != 'branch':
-                c.cs_branch_name = org_scm_instance.get_changeset(c.cs_ref_name).branch # use ref_type ?
-            c.a_branch_name = c.a_ref_name
-            if c.a_ref_type != 'branch':
-                try:
-                    c.a_branch_name = other_scm_instance.get_changeset(c.a_ref_name).branch # use ref_type ?
-                except EmptyRepositoryError:
-                    c.a_branch_name = 'null' # not a branch name ... but close enough
-            # candidates: descendants of old head that are on the right branch
-            #             and not are the old head itself ...
-            #             and nothing at all if old head is a descendant of target ref name
-            if not c.is_range and other_scm_instance._repo.revs('present(%s)::&%s', c.cs_ranges[-1].raw_id, c.a_branch_name):
-                c.update_msg = _('This pull request has already been merged to %s.') % c.a_branch_name
-            elif c.pull_request.is_closed():
-                c.update_msg = _('This pull request has been closed and can not be updated.')
-            else: # look for descendants of PR head on source branch in org repo
-                avail_revs = org_scm_instance._repo.revs('%s:: & branch(%s)',
-                                                         revs[0], c.cs_branch_name)
-                if len(avail_revs) > 1: # more than just revs[0]
-                    # also show changesets that not are descendants but would be merged in
-                    targethead = other_scm_instance.get_changeset(c.a_branch_name).raw_id
-                    if org_scm_instance.path != other_scm_instance.path:
-                        # Note: org_scm_instance.path must come first so all
-                        # valid revision numbers are 100% org_scm compatible
-                        # - both for avail_revs and for revset results
-                        hgrepo = unionrepo.unionrepository(org_scm_instance.baseui,
-                                                           org_scm_instance.path,
-                                                           other_scm_instance.path)
+        try:
+            if not c.cs_ranges:
+                c.update_msg = _('Error: changesets not found when displaying pull request from %s.') % c.cs_rev
+            elif org_scm_instance.alias == 'hg' and c.a_ref_name != 'ancestor':
+                if c.cs_ref_type != 'branch':
+                    c.cs_branch_name = org_scm_instance.get_changeset(c.cs_ref_name).branch # use ref_type ?
+                c.a_branch_name = c.a_ref_name
+                if c.a_ref_type != 'branch':
+                    try:
+                        c.a_branch_name = other_scm_instance.get_changeset(c.a_ref_name).branch # use ref_type ?
+                    except EmptyRepositoryError:
+                        c.a_branch_name = 'null' # not a branch name ... but close enough
+                # candidates: descendants of old head that are on the right branch
+                #             and not are the old head itself ...
+                #             and nothing at all if old head is a descendant of target ref name
+                if not c.is_range and other_scm_instance._repo.revs('present(%s)::&%s', c.cs_ranges[-1].raw_id, c.a_branch_name):
+                    c.update_msg = _('This pull request has already been merged to %s.') % c.a_branch_name
+                elif c.pull_request.is_closed():
+                    c.update_msg = _('This pull request has been closed and can not be updated.')
+                else: # look for descendants of PR head on source branch in org repo
+                    avail_revs = org_scm_instance._repo.revs('%s:: & branch(%s)',
+                                                             revs[0], c.cs_branch_name)
+                    if len(avail_revs) > 1: # more than just revs[0]
+                        # also show changesets that not are descendants but would be merged in
+                        targethead = other_scm_instance.get_changeset(c.a_branch_name).raw_id
+                        if org_scm_instance.path != other_scm_instance.path:
+                            # Note: org_scm_instance.path must come first so all
+                            # valid revision numbers are 100% org_scm compatible
+                            # - both for avail_revs and for revset results
+                            hgrepo = unionrepo.unionrepository(org_scm_instance.baseui,
+                                                               org_scm_instance.path,
+                                                               other_scm_instance.path)
+                        else:
+                            hgrepo = org_scm_instance._repo
+                        show = set(hgrepo.revs('::%ld & !::parents(%s) & !::%s',
+                                               avail_revs, revs[0], targethead))
+                        c.update_msg = _('The following additional changes are available on %s:') % c.cs_branch_name
                     else:
-                        hgrepo = org_scm_instance._repo
-                    show = set(hgrepo.revs('::%ld & !::%s & !::%s',
-                                           avail_revs, revs[0], targethead))
-                    c.update_msg = _('This pull request can be updated with changes on %s:') % c.cs_branch_name
-                else:
-                    show = set()
-                    avail_revs = set() # drop revs[0]
-                    c.update_msg = _('No changesets found for updating this pull request.')
+                        show = set()
+                        avail_revs = set() # drop revs[0]
+                        c.update_msg = _('No additional changesets found for iterating on this pull request.')
 
-                # TODO: handle branch heads that not are tip-most
-                brevs = org_scm_instance._repo.revs('%s - %ld - %s', c.cs_branch_name, avail_revs, revs[0])
-                if brevs:
-                    # also show changesets that are on branch but neither ancestors nor descendants
-                    show.update(org_scm_instance._repo.revs('::%ld - ::%ld - ::%s', brevs, avail_revs, c.a_branch_name))
-                    show.add(revs[0]) # make sure graph shows this so we can see how they relate
-                    c.update_msg_other = _('Note: Branch %s has another head: %s.') % (c.cs_branch_name,
-                        h.short_id(org_scm_instance.get_changeset((max(brevs))).raw_id))
+                    # TODO: handle branch heads that not are tip-most
+                    brevs = org_scm_instance._repo.revs('%s - %ld - %s', c.cs_branch_name, avail_revs, revs[0])
+                    if brevs:
+                        # also show changesets that are on branch but neither ancestors nor descendants
+                        show.update(org_scm_instance._repo.revs('::%ld - ::%ld - ::%s', brevs, avail_revs, c.a_branch_name))
+                        show.add(revs[0]) # make sure graph shows this so we can see how they relate
+                        c.update_msg_other = _('Note: Branch %s has another head: %s.') % (c.cs_branch_name,
+                            h.short_id(org_scm_instance.get_changeset((max(brevs))).raw_id))
 
-                avail_show = sorted(show, reverse=True)
+                    avail_show = sorted(show, reverse=True)
 
-        elif org_scm_instance.alias == 'git':
-            c.update_msg = _("Git pull requests don't support updates yet.")
+            elif org_scm_instance.alias == 'git':
+                c.cs_repo.scm_instance.get_changeset(c.cs_rev) # check it exists - raise ChangesetDoesNotExistError if not
+                c.update_msg = _("Git pull requests don't support iterating yet.")
+        except ChangesetDoesNotExistError:
+            c.update_msg = _('Error: some changesets not found when displaying pull request from %s.') % c.cs_rev
 
         c.avail_revs = avail_revs
         c.avail_cs = [org_scm_instance.get_changeset(r) for r in avail_show]
@@ -641,7 +712,7 @@
         c.statuses = c.cs_repo.statuses(raw_ids)
 
         ignore_whitespace = request.GET.get('ignorews') == '1'
-        line_context = request.GET.get('context', 3)
+        line_context = safe_int(request.GET.get('context'), 3)
         c.ignorews_url = _ignorews_url
         c.context_url = _context_url
         c.fulldiff = request.GET.get('fulldiff')
@@ -650,10 +721,12 @@
         # we swap org/other ref since we run a simple diff on one repo
         log.debug('running diff between %s and %s in %s',
                   c.a_rev, c.cs_rev, org_scm_instance.path)
-        txtdiff = org_scm_instance.get_diff(rev1=safe_str(c.a_rev), rev2=safe_str(c.cs_rev),
-                                      ignore_whitespace=ignore_whitespace,
-                                      context=line_context)
-
+        try:
+            txtdiff = org_scm_instance.get_diff(rev1=safe_str(c.a_rev), rev2=safe_str(c.cs_rev),
+                                                ignore_whitespace=ignore_whitespace,
+                                                context=line_context)
+        except ChangesetDoesNotExistError:
+            txtdiff =  _("The diff can't be shown - the PR revisions could not be found.")
         diff_processor = diffs.DiffProcessor(txtdiff or '', format='gitdiff',
                                              diff_limit=diff_limit)
         _parsed = diff_processor.prepare()
@@ -662,8 +735,7 @@
         if isinstance(_parsed, LimitedDiffContainer):
             c.limited_diff = True
 
-        c.files = []
-        c.changes = {}
+        c.file_diff_data = []
         c.lines_added = 0
         c.lines_deleted = 0
 
@@ -671,11 +743,11 @@
             st = f['stats']
             c.lines_added += st['added']
             c.lines_deleted += st['deleted']
-            fid = h.FID('', f['filename'])
-            c.files.append([fid, f['operation'], f['filename'], f['stats']])
-            htmldiff = diff_processor.as_html(enable_comments=True,
-                                              parsed_lines=[f])
-            c.changes[fid] = [f['operation'], f['filename'], htmldiff]
+            filename = f['filename']
+            fid = h.FID('', filename)
+            diff = diff_processor.as_html(enable_comments=True,
+                                          parsed_lines=[f])
+            c.file_diff_data.append((fid, None, f['operation'], f['old_filename'], filename, diff, st))
 
         # inline comments
         c.inline_cnt = 0
@@ -698,7 +770,7 @@
         c.changeset_statuses = ChangesetStatus.STATUSES
 
         c.as_form = False
-        c.ancestor = None # there is one - but right here we don't know which
+        c.ancestors = None # [c.a_rev] ... but that is shown in an other way
         return render('/pullrequests/pullrequest_show.html')
 
     @LoginRequired()
@@ -711,10 +783,11 @@
 
         status = request.POST.get('changeset_status')
         close_pr = request.POST.get('save_close')
+        delete = request.POST.get('save_delete')
         f_path = request.POST.get('f_path')
         line_no = request.POST.get('line')
 
-        if (status or close_pr) and (f_path or line_no):
+        if (status or close_pr or delete) and (f_path or line_no):
             # status votes and closing is only possible in general comments
             raise HTTPBadRequest()
 
@@ -724,20 +797,31 @@
                 h.flash(_('No permission to change pull request status'), 'error')
                 raise HTTPForbidden()
 
-        text = request.POST.get('text', '').strip()
-        if close_pr:
-            text = _('Closing.') + '\n' + text
+        if delete == "delete":
+            if (pull_request.owner_id == c.authuser.user_id or
+                h.HasPermissionAny('hg.admin')() or
+                h.HasRepoPermissionAny('repository.admin')(pull_request.org_repo.repo_name) or
+                h.HasRepoPermissionAny('repository.admin')(pull_request.other_repo.repo_name)
+                ) and not pull_request.is_closed():
+                PullRequestModel().delete(pull_request)
+                Session().commit()
+                h.flash(_('Successfully deleted pull request %s') % pull_request_id,
+                        category='success')
+                return {
+                   'location': url('my_pullrequests'), # or repo pr list?
+                }
+                raise HTTPFound(location=url('my_pullrequests')) # or repo pr list?
+            raise HTTPForbidden()
 
-        comment = ChangesetCommentsModel().create(
-            text=text,
-            repo=c.db_repo.repo_id,
-            user=c.authuser.user_id,
-            pull_request=pull_request_id,
+        text = request.POST.get('text', '').strip()
+
+        comment = create_comment(
+            text,
+            status,
+            pull_request_id=pull_request_id,
             f_path=f_path,
             line_no=line_no,
-            status_change=(ChangesetStatus.get_status_lbl(status)
-                           if status and allowed_to_change_status else None),
-            closing_pr=close_pr
+            closing_pr=close_pr,
         )
 
         action_logger(self.authuser,
@@ -762,7 +846,7 @@
         Session().commit()
 
         if not request.environ.get('HTTP_X_PARTIAL_XHR'):
-            return redirect(pull_request.url())
+            raise HTTPFound(location=pull_request.url())
 
         data = {
            'target_id': h.safeid(h.safe_unicode(request.POST.get('f_path'))),
@@ -786,7 +870,7 @@
             #don't allow deleting comments on closed pull request
             raise HTTPForbidden()
 
-        owner = co.author.user_id == c.authuser.user_id
+        owner = co.author_id == c.authuser.user_id
         repo_admin = h.HasRepoPermissionAny('repository.admin')(c.repo_name)
         if h.HasPermissionAny('hg.admin')() or repo_admin or owner:
             ChangesetCommentsModel().delete(comment=co)
--- a/kallithea/controllers/search.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/search.py	Fri Nov 18 01:11:13 2016 +0100
@@ -40,9 +40,9 @@
 from kallithea.lib.base import BaseRepoController, render
 from kallithea.lib.indexers import CHGSETS_SCHEMA, SCHEMA, CHGSET_IDX_NAME, \
     IDX_NAME, WhooshResultWrapper
-from kallithea.model.repo import RepoModel
+from kallithea.lib.page import Page
 from kallithea.lib.utils2 import safe_str, safe_int
-from kallithea.lib.helpers import Page
+from kallithea.model.repo import RepoModel
 
 log = logging.getLogger(__name__)
 
@@ -85,7 +85,7 @@
             log.debug(cur_query)
 
         if c.cur_query:
-            p = safe_int(request.GET.get('page', 1), 1)
+            p = safe_int(request.GET.get('page'), 1)
             highlight_items = set()
             try:
                 idx = open_dir(config['app_conf']['index_dir'],
@@ -139,7 +139,7 @@
                 log.error('Empty Index data')
                 c.runtime = _('There is no index to search in. '
                               'Please run whoosh indexer')
-            except (Exception):
+            except Exception:
                 log.error(traceback.format_exc())
                 c.runtime = _('An error occurred during search operation.')
 
--- a/kallithea/controllers/summary.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/controllers/summary.py	Fri Nov 18 01:11:13 2016 +0100
@@ -28,6 +28,7 @@
 import traceback
 import calendar
 import logging
+import itertools
 from time import mktime
 from datetime import timedelta, date
 
@@ -37,19 +38,17 @@
 
 from beaker.cache import cache_region, region_invalidate
 
-from kallithea.lib.compat import product
 from kallithea.lib.vcs.exceptions import ChangesetError, EmptyRepositoryError, \
     NodeDoesNotExistError
 from kallithea.config.conf import ALL_READMES, ALL_EXTS, LANGUAGES_EXTENSIONS_MAP
 from kallithea.model.db import Statistics, CacheInvalidation, User
 from kallithea.lib.utils import jsonify
 from kallithea.lib.utils2 import safe_str
-from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator,\
+from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator, \
     NotAnonymous
 from kallithea.lib.base import BaseRepoController, render
 from kallithea.lib.vcs.backends.base import EmptyChangeset
 from kallithea.lib.markup_renderer import MarkupRenderer
-from kallithea.lib.celerylib import run_task
 from kallithea.lib.celerylib.tasks import get_commits_stats
 from kallithea.lib.compat import json
 from kallithea.lib.vcs.nodes import FileNode
@@ -58,7 +57,7 @@
 log = logging.getLogger(__name__)
 
 README_FILES = [''.join([x[0][0], x[1][0]]) for x in
-                    sorted(list(product(ALL_READMES, ALL_EXTS)),
+                    sorted(list(itertools.product(ALL_READMES, ALL_EXTS)),
                            key=lambda y:y[0][1] + y[1][1])]
 
 
@@ -71,7 +70,7 @@
         repo_name = db_repo.repo_name
         log.debug('Looking for README file')
 
-        @cache_region('long_term')
+        @cache_region('long_term', '_get_readme_from_cache')
         def _get_readme_from_cache(key, kind):
             readme_data = None
             readme_file = None
@@ -105,7 +104,7 @@
         kind = 'README'
         valid = CacheInvalidation.test_and_set_valid(repo_name, kind)
         if not valid:
-            region_invalidate(_get_readme_from_cache, None, repo_name, kind)
+            region_invalidate(_get_readme_from_cache, None, '_get_readme_from_cache', repo_name, kind)
         return _get_readme_from_cache(repo_name, kind)
 
     @LoginRequired()
@@ -114,8 +113,9 @@
     def index(self, repo_name):
         _load_changelog_summary()
 
-        username = ''
-        if self.authuser.username != User.DEFAULT_USER:
+        if self.authuser.is_default_user:
+            username = ''
+        else:
             username = safe_str(self.authuser.username)
 
         _def_clone_uri = _def_clone_uri_by_id = c.clone_uri_tmpl
@@ -134,8 +134,8 @@
         else:
             c.show_stats = False
 
-        stats = self.sa.query(Statistics)\
-            .filter(Statistics.repository == c.db_repo)\
+        stats = self.sa.query(Statistics) \
+            .filter(Statistics.repository == c.db_repo) \
             .scalar()
 
         c.stats_percentage = 0
@@ -192,8 +192,8 @@
         c.ts_min = ts_min_m
         c.ts_max = ts_max_y
 
-        stats = self.sa.query(Statistics)\
-            .filter(Statistics.repository == c.db_repo)\
+        stats = self.sa.query(Statistics) \
+            .filter(Statistics.repository == c.db_repo) \
             .scalar()
         c.stats_percentage = 0
         if stats and stats.languages:
@@ -210,7 +210,7 @@
                 sorted(lang_stats, reverse=True, key=lambda k: k[1])[:10]
             )
             last_rev = stats.stat_on_revision + 1
-            c.repo_last_rev = c.db_repo_scm_instance.count()\
+            c.repo_last_rev = c.db_repo_scm_instance.count() \
                 if c.db_repo_scm_instance.revisions else 0
             if last_rev == 0 or c.repo_last_rev == 0:
                 pass
@@ -224,6 +224,5 @@
             c.no_data = True
 
         recurse_limit = 500  # don't recurse more than 500 times when parsing
-        run_task(get_commits_stats, c.db_repo.repo_name, ts_min_y,
-                 ts_max_y, recurse_limit)
+        get_commits_stats(c.db_repo.repo_name, ts_min_y, ts_max_y, recurse_limit)
         return render('summary/statistics.html')
--- a/kallithea/controllers/tags.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,57 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.controllers.tags
-~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Tags controller for Kallithea
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Apr 21, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-
-"""
-
-import logging
-
-from pylons import tmpl_context as c
-
-from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
-from kallithea.lib.base import BaseRepoController, render
-from kallithea.lib.compat import OrderedDict
-
-log = logging.getLogger(__name__)
-
-
-class TagsController(BaseRepoController):
-
-    def __before__(self):
-        super(TagsController, self).__before__()
-
-    @LoginRequired()
-    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
-                                   'repository.admin')
-    def index(self):
-        c.repo_tags = OrderedDict()
-
-        tags = [(name, c.db_repo_scm_instance.get_changeset(hash_)) for \
-                 name, hash_ in c.db_repo_scm_instance.tags.items()]
-        ordered_tags = sorted(tags, key=lambda x: x[1].date, reverse=True)
-        for name, cs_tag in ordered_tags:
-            c.repo_tags[name] = cs_tag
-
-        return render('tags/tags.html')
--- a/kallithea/i18n/be/LC_MESSAGES/kallithea.po	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/i18n/be/LC_MESSAGES/kallithea.po	Fri Nov 18 01:11:13 2016 +0100
@@ -1,14 +1,14 @@
 # Belarusian translations for Kallithea.
-# Copyright (C) 2015 Various authors, licensing as GPLv3
+# Copyright (C) 2016 Various authors, licensing as GPLv3
 # This file is distributed under the same license as the Kallithea project.
-# Automatically generated, 2015.
+# Automatically generated, 2016.
 # #, fuzzy
 msgid ""
 msgstr ""
 "Project-Id-Version: Kallithea 0.3\n"
 "Report-Msgid-Bugs-To: translations@kallithea-scm.org\n"
-"POT-Creation-Date: 2015-09-08 10:34+0200\n"
-"PO-Revision-Date: 2015-08-08 12:03+0300\n"
+"POT-Creation-Date: 2016-03-14 16:51+0100\n"
+"PO-Revision-Date: 2016-02-24 16:36+0100\n"
 "Last-Translator: Andrew Shadura <andrew@shadura.me>\n"
 "Language-Team: Belarusian "
 "<https://hosted.weblate.org/projects/kallithea/kallithea/be/>\n"
@@ -18,14 +18,14 @@
 "Content-Transfer-Encoding: 8bit\n"
 "Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<="
 "4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
-"X-Generator: Weblate 2.4-dev\n"
-
-#: kallithea/controllers/changelog.py:86
-#: kallithea/controllers/pullrequests.py:238 kallithea/lib/base.py:512
+"X-Generator: Weblate 2.5-dev\n"
+
+#: kallithea/controllers/changelog.py:85
+#: kallithea/controllers/pullrequests.py:240 kallithea/lib/base.py:515
 msgid "There are no changesets yet"
 msgstr "Яшчэ не было змен"
 
-#: kallithea/controllers/changelog.py:166
+#: kallithea/controllers/changelog.py:164
 #: kallithea/controllers/admin/permissions.py:61
 #: kallithea/controllers/admin/permissions.py:65
 #: kallithea/controllers/admin/permissions.py:69
@@ -37,35 +37,29 @@
 msgid "None"
 msgstr "Нічога"
 
-#: kallithea/controllers/changelog.py:169 kallithea/controllers/files.py:196
+#: kallithea/controllers/changelog.py:167 kallithea/controllers/files.py:198
 msgid "(closed)"
 msgstr "(зачынена)"
 
-#: kallithea/controllers/changeset.py:89
+#: kallithea/controllers/changeset.py:88
 msgid "Show whitespace"
-msgstr "Адлюстроўваць прабелы"
-
-#: kallithea/controllers/changeset.py:96 kallithea/controllers/changeset.py:103
+msgstr "Паказваць прабелы"
+
+#: kallithea/controllers/changeset.py:95 kallithea/controllers/changeset.py:102
 #: kallithea/templates/files/diff_2way.html:55
 msgid "Ignore whitespace"
 msgstr "Ігнараваць прабелы"
 
-#: kallithea/controllers/changeset.py:169
+#: kallithea/controllers/changeset.py:168
 #, python-format
 msgid "Increase diff context to %(num)s lines"
 msgstr "Павялічыць кантэкст да %(num)s радкоў"
 
-#: kallithea/controllers/changeset.py:212 kallithea/controllers/files.py:96
-#: kallithea/controllers/files.py:116 kallithea/controllers/files.py:742
+#: kallithea/controllers/changeset.py:233 kallithea/controllers/files.py:97
+#: kallithea/controllers/files.py:117 kallithea/controllers/files.py:744
 msgid "Such revision does not exist for this repository"
 msgstr "Няма такой рэвізіі ў гэтым рэпазітары"
 
-#: kallithea/controllers/changeset.py:383
-msgid ""
-"Changing status on a changeset associated with a closed pull request is "
-"not allowed"
-msgstr "Нельга рэдагаваць статус змен, злучаных з зачыненымі pull-request'ами"
-
 #: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:41
 msgid "Select changeset"
 msgstr "Выбраць набор змен"
@@ -119,125 +113,127 @@
 #: kallithea/controllers/feed.py:87
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Changeset was too big and was cut off..."
-msgstr "Змены апынуліся занадта вялікімі і былі выразаныя..."
+msgstr "Змены апынуліся занадта вялікімі і былі скарочаныя..."
 
 #: kallithea/controllers/feed.py:91
 #, python-format
 msgid "%s committed on %s"
 msgstr "%s выканаў каміт у %s"
 
-#: kallithea/controllers/files.py:91
+#: kallithea/controllers/files.py:92
 msgid "Click here to add new file"
 msgstr "Націсніце каб дадаць новы файл"
 
-#: kallithea/controllers/files.py:92
+#: kallithea/controllers/files.py:93
 #, python-format
 msgid "There are no files yet. %s"
 msgstr "Няма файлаў. %s"
 
-#: kallithea/controllers/files.py:193
+#: kallithea/controllers/files.py:195
 #, python-format
 msgid "%s at %s"
 msgstr "%s (%s)"
 
-#: kallithea/controllers/files.py:305 kallithea/controllers/files.py:365
-#: kallithea/controllers/files.py:432
+#: kallithea/controllers/files.py:307 kallithea/controllers/files.py:367
+#: kallithea/controllers/files.py:434
 #, python-format
 msgid "This repository has been locked by %s on %s"
 msgstr "Рэпазітар заблакаваў %s у %s"
 
-#: kallithea/controllers/files.py:317
-msgid "You can only delete files with revision being a valid branch "
-msgstr "Вы можаце выдаляць файлы толькі ў рэвізіі, злучанай з існай галінкай "
-
-#: kallithea/controllers/files.py:328
+#: kallithea/controllers/files.py:319
+#, fuzzy
+msgid "You can only delete files with revision being a valid branch"
+msgstr "Вы можаце выдаляць файлы толькі ў рэвізіі, злучанай з існай галінай "
+
+#: kallithea/controllers/files.py:330
 #, python-format
 msgid "Deleted file %s via Kallithea"
 msgstr "Файл %s выдалены з дапамогай Kallithea"
 
-#: kallithea/controllers/files.py:350
+#: kallithea/controllers/files.py:352
 #, python-format
 msgid "Successfully deleted file %s"
 msgstr "Файл %s выдалены"
 
-#: kallithea/controllers/files.py:354 kallithea/controllers/files.py:420
-#: kallithea/controllers/files.py:501
+#: kallithea/controllers/files.py:356 kallithea/controllers/files.py:422
+#: kallithea/controllers/files.py:503
 msgid "Error occurred during commit"
 msgstr "Падчас каміта адбылася памылка"
 
-#: kallithea/controllers/files.py:377
-msgid "You can only edit files with revision being a valid branch "
-msgstr "Вы можаце рэдагаваць файлы толькі ў рэвізіі, злучанай з існай галінкай "
-
-#: kallithea/controllers/files.py:391
+#: kallithea/controllers/files.py:379
+#, fuzzy
+msgid "You can only edit files with revision being a valid branch"
+msgstr "Вы можаце рэдагаваць файлы толькі ў рэвізіі, злучанай з існай галінай "
+
+#: kallithea/controllers/files.py:393
 #, python-format
 msgid "Edited file %s via Kallithea"
 msgstr "Файл %s адрэдагаваны з дапамогай Kallithea"
 
-#: kallithea/controllers/files.py:407
+#: kallithea/controllers/files.py:409
 msgid "No changes"
 msgstr "Без змен"
 
-#: kallithea/controllers/files.py:416 kallithea/controllers/files.py:490
+#: kallithea/controllers/files.py:418 kallithea/controllers/files.py:492
 #, python-format
 msgid "Successfully committed to %s"
-msgstr "Змены ўжыты ў %s"
-
-#: kallithea/controllers/files.py:443
+msgstr "Змены захаваныя ў %s"
+
+#: kallithea/controllers/files.py:445
 msgid "Added file via Kallithea"
 msgstr "Файл дададзены з дапамогай Kallithea"
 
-#: kallithea/controllers/files.py:464
+#: kallithea/controllers/files.py:466
 msgid "No content"
 msgstr "Пуста"
 
-#: kallithea/controllers/files.py:468
+#: kallithea/controllers/files.py:470
 msgid "No filename"
 msgstr "Безназоўны"
 
-#: kallithea/controllers/files.py:493
+#: kallithea/controllers/files.py:495
 msgid "Location must be relative path and must not contain .. in path"
 msgstr ""
 "Размяшчэнне павінна быць адносным шляхам, і не можа ўтрымліваць \"..\" у "
 "шляхі"
 
-#: kallithea/controllers/files.py:526
+#: kallithea/controllers/files.py:528
 msgid "Downloads disabled"
-msgstr "Магчымасць спампоўваць адключана"
-
-#: kallithea/controllers/files.py:537
+msgstr "Магчымасць спампоўваць адключаная"
+
+#: kallithea/controllers/files.py:539
 #, python-format
 msgid "Unknown revision %s"
 msgstr "Невядомая рэвізія %s"
 
-#: kallithea/controllers/files.py:539
+#: kallithea/controllers/files.py:541
 msgid "Empty repository"
 msgstr "Пусты рэпазітар"
 
-#: kallithea/controllers/files.py:541
+#: kallithea/controllers/files.py:543
 msgid "Unknown archive type"
 msgstr "Невядомы тып архіва"
 
-#: kallithea/controllers/files.py:771
+#: kallithea/controllers/files.py:773
 #: kallithea/templates/changeset/changeset_range.html:9
 #: kallithea/templates/email_templates/pull_request.html:15
 #: kallithea/templates/pullrequests/pullrequest.html:97
 msgid "Changesets"
 msgstr "Набор змен"
 
-#: kallithea/controllers/files.py:772 kallithea/controllers/pullrequests.py:176
-#: kallithea/model/scm.py:820 kallithea/templates/switch_to_list.html:3
+#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:175
+#: kallithea/model/scm.py:716 kallithea/templates/switch_to_list.html:3
 #: kallithea/templates/branches/branches.html:10
 msgid "Branches"
-msgstr "Галінкі"
-
-#: kallithea/controllers/files.py:773 kallithea/controllers/pullrequests.py:177
-#: kallithea/model/scm.py:831 kallithea/templates/switch_to_list.html:25
+msgstr "Галіны"
+
+#: kallithea/controllers/files.py:775 kallithea/controllers/pullrequests.py:176
+#: kallithea/model/scm.py:727 kallithea/templates/switch_to_list.html:25
 #: kallithea/templates/tags/tags.html:10
 msgid "Tags"
 msgstr "Тэгі"
@@ -245,13 +241,13 @@
 #: kallithea/controllers/forks.py:186
 #, python-format
 msgid "An error occurred during repository forking %s"
-msgstr "Адбылася памылка падчас стварэння форка рэпазітара %s"
+msgstr "Памылка падчас стварэння форка рэпазітара %s"
 
 #: kallithea/controllers/home.py:84
 msgid "Groups"
 msgstr "Групы"
 
-#: kallithea/controllers/home.py:89
+#: kallithea/controllers/home.py:94
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:106
 #: kallithea/templates/admin/repos/repo_add.html:12
 #: kallithea/templates/admin/repos/repo_add.html:16
@@ -259,23 +255,27 @@
 #: kallithea/templates/admin/users/user_edit_advanced.html:6
 #: kallithea/templates/base/base.html:60 kallithea/templates/base/base.html:77
 #: kallithea/templates/base/base.html:124
-#: kallithea/templates/base/base.html:390
-#: kallithea/templates/base/base.html:562
+#: kallithea/templates/base/base.html:479
+#: kallithea/templates/base/base.html:653
 msgid "Repositories"
 msgstr "Рэпазітары"
 
-#: kallithea/controllers/home.py:130
+#: kallithea/controllers/home.py:139
 #: kallithea/templates/files/files_add.html:32
 #: kallithea/templates/files/files_delete.html:23
 #: kallithea/templates/files/files_edit.html:32
 msgid "Branch"
-msgstr "Галінка"
-
-#: kallithea/controllers/home.py:136
+msgstr "Галіна"
+
+#: kallithea/controllers/home.py:145 kallithea/templates/switch_to_list.html:16
+msgid "Closed Branches"
+msgstr "Зачыненыя галіны"
+
+#: kallithea/controllers/home.py:151
 msgid "Tag"
 msgstr "Тэгі"
 
-#: kallithea/controllers/home.py:142
+#: kallithea/controllers/home.py:157
 msgid "Bookmark"
 msgstr "Закладкі"
 
@@ -283,165 +283,166 @@
 #: kallithea/templates/journal/public_journal.html:4
 #: kallithea/templates/journal/public_journal.html:21
 msgid "Public Journal"
-msgstr "Публічны часопіс"
+msgstr "Публічны журнал"
 
 #: kallithea/controllers/journal.py:115 kallithea/controllers/journal.py:157
-#: kallithea/templates/base/base.html:222
+#: kallithea/templates/base/base.html:306
 #: kallithea/templates/journal/journal.html:4
 #: kallithea/templates/journal/journal.html:12
 msgid "Journal"
-msgstr "Часопіс"
-
-#: kallithea/controllers/login.py:151 kallithea/controllers/login.py:197
+msgstr "Журнал"
+
+#: kallithea/controllers/login.py:144 kallithea/controllers/login.py:190
 msgid "Bad captcha"
 msgstr "Няслушная капча"
 
-#: kallithea/controllers/login.py:157
-msgid "You have successfully registered into Kallithea"
-msgstr "Рэгістрацыя ў Kallithea прайшла паспяхова"
-
-#: kallithea/controllers/login.py:202
-#, fuzzy
-#| msgid "Your password reset link was sent"
+#: kallithea/controllers/login.py:150
+msgid "You have successfully registered with %s"
+msgstr "Рэгістрацыя ў %s прайшла паспяхова"
+
+#: kallithea/controllers/login.py:195
 msgid "A password reset confirmation code has been sent"
-msgstr "Спасылка для скідання пароля адпраўлена"
-
-#: kallithea/controllers/login.py:251
-#, fuzzy
-#| msgid "Password reset link"
+msgstr "Код для скідання пароля адпраўлены"
+
+#: kallithea/controllers/login.py:244
 msgid "Invalid password reset token"
-msgstr "Спасылка скіду пароля"
-
-#: kallithea/controllers/login.py:256
+msgstr "Няслушны код скідання пароля"
+
+#: kallithea/controllers/login.py:249
 #: kallithea/controllers/admin/my_account.py:167
 msgid "Successfully updated password"
 msgstr "Пароль абноўлены"
 
-#: kallithea/controllers/pullrequests.py:124
+#: kallithea/controllers/pullrequests.py:123
 #, python-format
 msgid "%s (closed)"
 msgstr "%s (зачынена)"
 
-#: kallithea/controllers/pullrequests.py:152
+#: kallithea/controllers/pullrequests.py:151
 #: kallithea/templates/changeset/changeset.html:12
 #: kallithea/templates/email_templates/changeset_comment.html:17
 msgid "Changeset"
 msgstr "Змены"
 
-#: kallithea/controllers/pullrequests.py:173
+#: kallithea/controllers/pullrequests.py:172
 msgid "Special"
 msgstr "Адмысловы"
 
-#: kallithea/controllers/pullrequests.py:174
+#: kallithea/controllers/pullrequests.py:173
 msgid "Peer branches"
-msgstr "Галінкі ўдзельніка"
-
-#: kallithea/controllers/pullrequests.py:175 kallithea/model/scm.py:826
+msgstr "Галіны ўдзельніка"
+
+#: kallithea/controllers/pullrequests.py:174 kallithea/model/scm.py:722
 #: kallithea/templates/switch_to_list.html:38
 #: kallithea/templates/bookmarks/bookmarks.html:10
 msgid "Bookmarks"
 msgstr "Закладкі"
 
-#: kallithea/controllers/pullrequests.py:310
+#: kallithea/controllers/pullrequests.py:312
 #, python-format
 msgid "Error creating pull request: %s"
 msgstr "Памылка пры стварэнні pull-запыту: %s"
 
-#: kallithea/controllers/pullrequests.py:356
-#: kallithea/controllers/pullrequests.py:503
+#: kallithea/controllers/pullrequests.py:358
+#: kallithea/controllers/pullrequests.py:505
 msgid "No description"
 msgstr "Няма апісання"
 
-#: kallithea/controllers/pullrequests.py:363
+#: kallithea/controllers/pullrequests.py:365
 msgid "Successfully opened new pull request"
 msgstr "Pull-запыт створаны паспяхова"
 
-#: kallithea/controllers/pullrequests.py:366
-#: kallithea/controllers/pullrequests.py:453
-#: kallithea/controllers/pullrequests.py:509
+#: kallithea/controllers/pullrequests.py:368
+#: kallithea/controllers/pullrequests.py:455
+#: kallithea/controllers/pullrequests.py:512
 #, python-format
 msgid "Invalid reviewer \"%s\" specified"
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:369
-#: kallithea/controllers/pullrequests.py:456
+msgstr "Няслушны рэцэнзент \"%s\""
+
+#: kallithea/controllers/pullrequests.py:371
+#: kallithea/controllers/pullrequests.py:458
 msgid "Error occurred while creating pull request"
 msgstr "Адбылася памылка пры стварэнні pull-запыту"
 
-#: kallithea/controllers/pullrequests.py:401
+#: kallithea/controllers/pullrequests.py:403
 msgid "Missing changesets since the previous pull request:"
 msgstr "Адсутныя рэвізіі адносна папярэдняга pull-запыту:"
 
-#: kallithea/controllers/pullrequests.py:408
+#: kallithea/controllers/pullrequests.py:410
 #, python-format
 msgid "New changesets on %s %s since the previous pull request:"
 msgstr "Новыя рэвізіі на %s %s адносна папярэдняга pull-запыту:"
 
-#: kallithea/controllers/pullrequests.py:415
+#: kallithea/controllers/pullrequests.py:417
 msgid "Ancestor didn't change - show diff since previous version:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:422
+#: kallithea/controllers/pullrequests.py:424
 #, python-format
 msgid ""
 "This pull request is based on another %s revision and there is no simple "
 "diff."
 msgstr "Гэты pull-запыт заснаваны на іншай рэвізіі %s, просты diff немагчымы."
 
-#: kallithea/controllers/pullrequests.py:424
+#: kallithea/controllers/pullrequests.py:426
 #, python-format
 msgid "No changes found on %s %s since previous version."
 msgstr "Няма змен на %s %s адносна папярэдняй версіі."
 
-#: kallithea/controllers/pullrequests.py:462
+#: kallithea/controllers/pullrequests.py:464
 #, python-format
 msgid "Closed, replaced by %s ."
-msgstr "Зачынены, замешчаны %s."
-
-#: kallithea/controllers/pullrequests.py:470
+msgstr "Зачынены, заменены %s."
+
+#: kallithea/controllers/pullrequests.py:472
 msgid "Pull request update created"
 msgstr "Абнаўленне для pull-запыту створана"
 
-#: kallithea/controllers/pullrequests.py:513
+#: kallithea/controllers/pullrequests.py:516
 msgid "Pull request updated"
 msgstr "Pull-запыт абноўлены"
 
-#: kallithea/controllers/pullrequests.py:528
+#: kallithea/controllers/pullrequests.py:531
 msgid "Successfully deleted pull request"
 msgstr "Pull-запыт паспяхова выдалены"
 
-#: kallithea/controllers/pullrequests.py:594
+#: kallithea/controllers/pullrequests.py:597
 #, python-format
 msgid "This pull request has already been merged to %s."
-msgstr "Гэты pull-запыт ужо прыняты на галінку %s."
-
-#: kallithea/controllers/pullrequests.py:596
+msgstr "Гэты pull-запыт ужо прыняты на галіну %s."
+
+#: kallithea/controllers/pullrequests.py:599
 msgid "This pull request has been closed and can not be updated."
 msgstr "Гэты pull-запыт быў зачынены і не можа быць абноўлены."
 
-#: kallithea/controllers/pullrequests.py:614
-#, python-format
-msgid "This pull request can be updated with changes on %s:"
-msgstr "Гэты pull-запыт можа быць абноўлены з %s:"
-
 #: kallithea/controllers/pullrequests.py:617
+#, python-format
+msgid "The following changes are available on %s:"
+msgstr "Гэтыя змены даступныя на %s:"
+
+#: kallithea/controllers/pullrequests.py:621
 msgid "No changesets found for updating this pull request."
 msgstr "Няма змен для абнаўлення гэтага pull-запыту."
 
-#: kallithea/controllers/pullrequests.py:625
+#: kallithea/controllers/pullrequests.py:629
 #, python-format
 msgid "Note: Branch %s has another head: %s."
-msgstr "Увага: Галінка %s мае яшчэ адну верхавіну: %s."
-
-#: kallithea/controllers/pullrequests.py:631
+msgstr "Увага: Галіна %s мае яшчэ адну верхавіну: %s."
+
+#: kallithea/controllers/pullrequests.py:635
 msgid "Git pull requests don't support updates yet."
-msgstr "Абнаўленне pull-запытаў git не падтрымліваецца."
-
-#: kallithea/controllers/pullrequests.py:722
+msgstr "Абнаўленне pull-запытаў git яшчэ не падтрымліваецца."
+
+#: kallithea/controllers/pullrequests.py:727
 msgid "No permission to change pull request status"
 msgstr "Няма правоў змяняць статус pull-запыту"
 
-#: kallithea/controllers/pullrequests.py:727
+#: kallithea/controllers/pullrequests.py:738
+#, python-format
+msgid "Successfully deleted pull request %s"
+msgstr "Pull-запыт %s паспяхова выдалены"
+
+#: kallithea/controllers/pullrequests.py:748
 msgid "Closing."
 msgstr "Зачынены."
 
@@ -455,14 +456,14 @@
 
 #: kallithea/controllers/search.py:144
 msgid "An error occurred during search operation."
-msgstr "Адбылася памылка пры выкананні гэтага пошуку."
-
-#: kallithea/controllers/summary.py:180
+msgstr "Памылка пры выкананні гэтага пошуку."
+
+#: kallithea/controllers/summary.py:181
 #: kallithea/templates/summary/summary.html:384
 msgid "No data ready yet"
 msgstr "Няма дадзеных"
 
-#: kallithea/controllers/summary.py:183
+#: kallithea/controllers/summary.py:184
 #: kallithea/templates/summary/summary.html:98
 msgid "Statistics are disabled for this repository"
 msgstr "Статыстычныя дадзеныя адключаны для гэтага рэпазітара"
@@ -473,7 +474,7 @@
 
 #: kallithea/controllers/admin/auth_settings.py:146
 msgid "error occurred during update of auth settings"
-msgstr "адбылася памылка пры абнаўленні налад аўтарызацыі"
+msgstr "памылка пры абнаўленні налад аўтарызацыі"
 
 #: kallithea/controllers/admin/defaults.py:97
 msgid "Default settings updated successfully"
@@ -481,119 +482,119 @@
 
 #: kallithea/controllers/admin/defaults.py:112
 msgid "Error occurred during update of defaults"
-msgstr "Адбылася памылка пры абнаўленні стандартных налад"
+msgstr "Памылка пры абнаўленні стандартных налад"
+
+#: kallithea/controllers/admin/gists.py:58
+#: kallithea/controllers/admin/my_account.py:243
+#: kallithea/controllers/admin/users.py:284
+msgid "Forever"
+msgstr "Назаўжды"
 
 #: kallithea/controllers/admin/gists.py:59
-#: kallithea/controllers/admin/my_account.py:243
+#: kallithea/controllers/admin/my_account.py:244
 #: kallithea/controllers/admin/users.py:285
-msgid "Forever"
-msgstr "Назаўжды"
+msgid "5 minutes"
+msgstr "5 хвілін"
 
 #: kallithea/controllers/admin/gists.py:60
-#: kallithea/controllers/admin/my_account.py:244
+#: kallithea/controllers/admin/my_account.py:245
 #: kallithea/controllers/admin/users.py:286
-msgid "5 minutes"
-msgstr "5 хвілін"
+msgid "1 hour"
+msgstr "1 гадзіна"
 
 #: kallithea/controllers/admin/gists.py:61
-#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/my_account.py:246
 #: kallithea/controllers/admin/users.py:287
-msgid "1 hour"
-msgstr "1 гадзіна"
+msgid "1 day"
+msgstr "1 дзень"
 
 #: kallithea/controllers/admin/gists.py:62
-#: kallithea/controllers/admin/my_account.py:246
+#: kallithea/controllers/admin/my_account.py:247
 #: kallithea/controllers/admin/users.py:288
-msgid "1 day"
-msgstr "1 дзень"
-
-#: kallithea/controllers/admin/gists.py:63
-#: kallithea/controllers/admin/my_account.py:247
-#: kallithea/controllers/admin/users.py:289
 msgid "1 month"
 msgstr "1 месяц"
 
-#: kallithea/controllers/admin/gists.py:67
+#: kallithea/controllers/admin/gists.py:66
 #: kallithea/controllers/admin/my_account.py:249
-#: kallithea/controllers/admin/users.py:291
+#: kallithea/controllers/admin/users.py:290
 msgid "Lifetime"
 msgstr "Тэрмін"
 
-#: kallithea/controllers/admin/gists.py:146
+#: kallithea/controllers/admin/gists.py:145
 msgid "Error occurred during gist creation"
 msgstr "Адбылася памылка падчас стварэння gist-запіса"
 
-#: kallithea/controllers/admin/gists.py:184
+#: kallithea/controllers/admin/gists.py:183
 #, python-format
 msgid "Deleted gist %s"
 msgstr "Gist-запіс %s выдалены"
 
-#: kallithea/controllers/admin/gists.py:233
+#: kallithea/controllers/admin/gists.py:232
 msgid "Unmodified"
 msgstr "Без змен"
 
-#: kallithea/controllers/admin/gists.py:262
+#: kallithea/controllers/admin/gists.py:261
 msgid "Successfully updated gist content"
-msgstr ""
-
-#: kallithea/controllers/admin/gists.py:267
+msgstr "Gist-запіс абноўлены"
+
+#: kallithea/controllers/admin/gists.py:266
 msgid "Successfully updated gist data"
-msgstr "Дадзеныя gist-запісы абноўлены"
-
-#: kallithea/controllers/admin/gists.py:270
+msgstr "Gist-запіс абноўлены"
+
+#: kallithea/controllers/admin/gists.py:269
 #, python-format
 msgid "Error occurred during update of gist %s"
-msgstr "Адбылася памылка пры абнаўленні gist-запісы %s"
+msgstr "Памылка пры абнаўленні gist-запісу %s"
 
 #: kallithea/controllers/admin/my_account.py:70 kallithea/model/user.py:215
 #: kallithea/model/user.py:237
 msgid "You can't edit this user since it's crucial for entire application"
 msgstr ""
-"Вы не можаце змяніць дадзеныя гэтага карыстача, паколькі ён важны для "
-"працы ўсяго прыкладання"
+"Вы не можаце змяніць дадзеныя гэтага карыстальніка, паколькі ён важны для"
+" працы ўсёй праграмы"
 
 #: kallithea/controllers/admin/my_account.py:129
 msgid "Your account was updated successfully"
 msgstr "Ваш уліковы запіс паспяхова абноўлены"
 
 #: kallithea/controllers/admin/my_account.py:144
-#: kallithea/controllers/admin/users.py:202
+#: kallithea/controllers/admin/users.py:201
 #, python-format
 msgid "Error occurred during update of user %s"
-msgstr "Адбылася памылка пры абнаўленні карыстача %s"
+msgstr "Памылка пры абнаўленні карыстальніка %s"
 
 #: kallithea/controllers/admin/my_account.py:178
 msgid "Error occurred during update of user password"
 msgstr "Памылка пры абнаўленні пароля"
 
 #: kallithea/controllers/admin/my_account.py:220
-#: kallithea/controllers/admin/users.py:415
+#: kallithea/controllers/admin/users.py:414
 #, python-format
 msgid "Added email %s to user"
-msgstr "Карыстачу дададзены e-mail %s"
+msgstr "Карыстальніку дададзены e-mail %s"
 
 #: kallithea/controllers/admin/my_account.py:226
-#: kallithea/controllers/admin/users.py:421
+#: kallithea/controllers/admin/users.py:420
 msgid "An error occurred during email saving"
-msgstr "Адбылася памылка пры захаванні e-mail"
+msgstr "Памылка пры захаванні e-mail"
 
 #: kallithea/controllers/admin/my_account.py:235
-#: kallithea/controllers/admin/users.py:433
+#: kallithea/controllers/admin/users.py:432
 msgid "Removed email from user"
-msgstr "E-mail карыстача выдалены"
+msgstr "E-mail карыстальніка выдалены"
 
 #: kallithea/controllers/admin/my_account.py:259
-#: kallithea/controllers/admin/users.py:308
+#: kallithea/controllers/admin/users.py:307
 msgid "API key successfully created"
 msgstr "API-ключ паспяхова створаны"
 
 #: kallithea/controllers/admin/my_account.py:271
-#: kallithea/controllers/admin/users.py:321
+#: kallithea/controllers/admin/users.py:320
 msgid "API key successfully reset"
 msgstr "API-ключ паспяхова скінуты"
 
 #: kallithea/controllers/admin/my_account.py:275
-#: kallithea/controllers/admin/users.py:325
+#: kallithea/controllers/admin/users.py:324
 msgid "API key successfully deleted"
 msgstr "API-ключ паспяхова выдалены"
 
@@ -643,10 +644,10 @@
 #: kallithea/templates/admin/users/user_edit_profile.html:105
 #: kallithea/templates/admin/users/users.html:10
 #: kallithea/templates/admin/users/users.html:55
-#: kallithea/templates/base/base.html:252
-#: kallithea/templates/base/base.html:253
-#: kallithea/templates/base/base.html:259
-#: kallithea/templates/base/base.html:260
+#: kallithea/templates/base/base.html:336
+#: kallithea/templates/base/base.html:337
+#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:344
 #: kallithea/templates/base/perms_summary.html:17
 msgid "Admin"
 msgstr "Адміністратар"
@@ -677,7 +678,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1564
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1603
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1655
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1701
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1705
 msgid "Manual activation of external account"
 msgstr "Ручная актывацыя вонкавага ўліковага запісу"
 
@@ -689,7 +690,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1565
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1604
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1656
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1702
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1706
 msgid "Automatic activation of external account"
 msgstr "Аўтаматычная актывацыя вонкавага ўліковага запісу"
 
@@ -704,360 +705,364 @@
 
 #: kallithea/controllers/admin/permissions.py:124
 msgid "Global permissions updated successfully"
-msgstr "Глабальныя прывілеі паспяхова абноўлены"
+msgstr "Глабальныя прывілеі паспяхова абноўленыя"
 
 #: kallithea/controllers/admin/permissions.py:139
 msgid "Error occurred during update of permissions"
 msgstr "Адбылася памылка падчас абнаўлення прывілеяў"
 
-#: kallithea/controllers/admin/repo_groups.py:188
+#: kallithea/controllers/admin/repo_groups.py:187
 #, python-format
 msgid "Error occurred during creation of repository group %s"
 msgstr "Адбылася памылка пры стварэнні групы рэпазітароў %s"
 
-#: kallithea/controllers/admin/repo_groups.py:193
+#: kallithea/controllers/admin/repo_groups.py:192
 #, python-format
 msgid "Created repository group %s"
-msgstr "Створана новая група рэпазітароў %s"
-
-#: kallithea/controllers/admin/repo_groups.py:250
+msgstr "Створаная новая група рэпазітароў %s"
+
+#: kallithea/controllers/admin/repo_groups.py:249
 #, python-format
 msgid "Updated repository group %s"
-msgstr "Група рэпазітароў %s абноўлена"
-
-#: kallithea/controllers/admin/repo_groups.py:266
+msgstr "Група рэпазітароў %s абноўленая"
+
+#: kallithea/controllers/admin/repo_groups.py:265
 #, python-format
 msgid "Error occurred during update of repository group %s"
 msgstr "Адбылася памылка пры абнаўленні групы рэпазітароў %s"
 
-#: kallithea/controllers/admin/repo_groups.py:284
+#: kallithea/controllers/admin/repo_groups.py:283
 #, python-format
 msgid "This group contains %s repositories and cannot be deleted"
-msgstr "Дадзеная група ўтрымоўвае %s рэпазітароў і не можа быць выдалена"
-
-#: kallithea/controllers/admin/repo_groups.py:291
+msgstr "Група ўтрымлівае %s рэпазітароў і не можа быць выдаленая"
+
+#: kallithea/controllers/admin/repo_groups.py:290
 #, python-format
 msgid "This group contains %s subgroups and cannot be deleted"
-msgstr "Група ўтрымоўвае ў сабе %s падгруп і не можа быць выдалены"
-
-#: kallithea/controllers/admin/repo_groups.py:297
+msgstr "Група ўтрымлівае ў сабе %s падгруп і не можа быць выдаленая"
+
+#: kallithea/controllers/admin/repo_groups.py:296
 #, python-format
 msgid "Removed repository group %s"
-msgstr "Група рэпазітароў %s выдалена"
-
-#: kallithea/controllers/admin/repo_groups.py:302
+msgstr "Група рэпазітароў %s выдаленая"
+
+#: kallithea/controllers/admin/repo_groups.py:301
 #, python-format
 msgid "Error occurred during deletion of repository group %s"
-msgstr "Адбылася памылка пры выдаленні групы рэпазітароў %s"
-
-#: kallithea/controllers/admin/repo_groups.py:405
-#: kallithea/controllers/admin/repo_groups.py:440
+msgstr "Памылка пры выдаленні групы рэпазітароў %s"
+
+#: kallithea/controllers/admin/repo_groups.py:404
+#: kallithea/controllers/admin/repo_groups.py:439
 #: kallithea/controllers/admin/user_groups.py:340
 msgid "Cannot revoke permission for yourself as admin"
 msgstr "Адміністратар не можа адклікаць свае прывелеі"
 
-#: kallithea/controllers/admin/repo_groups.py:420
+#: kallithea/controllers/admin/repo_groups.py:419
 msgid "Repository group permissions updated"
-msgstr "Прывілеі групы рэпазітароў абноўлены"
-
-#: kallithea/controllers/admin/repo_groups.py:457
-#: kallithea/controllers/admin/repos.py:398
+msgstr "Прывілеі групы рэпазітароў абноўленыя"
+
+#: kallithea/controllers/admin/repo_groups.py:456
+#: kallithea/controllers/admin/repos.py:397
 #: kallithea/controllers/admin/user_groups.py:352
 msgid "An error occurred during revoking of permission"
-msgstr "Адбылася памылка пры водгуку прывелеі"
-
-#: kallithea/controllers/admin/repos.py:152
+msgstr "Памылка пры водгуку прывелея"
+
+#: kallithea/controllers/admin/repos.py:151
 #, python-format
 msgid "Error creating repository %s"
-msgstr "Адбылася памылка пры стварэнні рэпазітара %s"
-
-#: kallithea/controllers/admin/repos.py:213
+msgstr "Памылка пры стварэнні рэпазітара %s"
+
+#: kallithea/controllers/admin/repos.py:212
 #, python-format
 msgid "Created repository %s from %s"
 msgstr "Рэпазітар %s створаны з %s"
 
-#: kallithea/controllers/admin/repos.py:222
+#: kallithea/controllers/admin/repos.py:221
 #, python-format
 msgid "Forked repository %s as %s"
-msgstr "Зроблены форк(копія) рэпазітара %s на %s"
-
-#: kallithea/controllers/admin/repos.py:225
+msgstr "Зроблены форк рэпазітара %s на %s"
+
+#: kallithea/controllers/admin/repos.py:224
 #, python-format
 msgid "Created repository %s"
 msgstr "Рэпазітар %s створаны"
 
-#: kallithea/controllers/admin/repos.py:262
+#: kallithea/controllers/admin/repos.py:261
 #, python-format
 msgid "Repository %s updated successfully"
 msgstr "Рэпазітар %s паспяхова абноўлены"
 
-#: kallithea/controllers/admin/repos.py:283
+#: kallithea/controllers/admin/repos.py:282
 #, python-format
 msgid "Error occurred during update of repository %s"
-msgstr "Адбылася памылка падчас абнаўлення рэпазітара %s"
-
-#: kallithea/controllers/admin/repos.py:310
+msgstr "Памылка падчас абнаўлення рэпазітара %s"
+
+#: kallithea/controllers/admin/repos.py:309
 #, python-format
 msgid "Detached %s forks"
-msgstr "Форки %s адлучаны"
-
-#: kallithea/controllers/admin/repos.py:313
+msgstr "Форкі %s адлучаныя"
+
+#: kallithea/controllers/admin/repos.py:312
 #, python-format
 msgid "Deleted %s forks"
-msgstr "Выдалены форки рэпазітара %s"
-
-#: kallithea/controllers/admin/repos.py:318
+msgstr "Выдаленыя форки рэпазітара %s"
+
+#: kallithea/controllers/admin/repos.py:317
 #, python-format
 msgid "Deleted repository %s"
 msgstr "Рэпазітар %s выдалены"
 
-#: kallithea/controllers/admin/repos.py:321
+#: kallithea/controllers/admin/repos.py:320
 #, python-format
 msgid "Cannot delete repository %s which still has forks"
 msgstr "Немагчыма выдаліць %s, ён усё яшчэ мае форкі"
 
-#: kallithea/controllers/admin/repos.py:326
+#: kallithea/controllers/admin/repos.py:325
 #, python-format
 msgid "An error occurred during deletion of %s"
-msgstr "Адбылася памылка падчас выдалення %s"
-
-#: kallithea/controllers/admin/repos.py:374
+msgstr "Памылка падчас выдалення %s"
+
+#: kallithea/controllers/admin/repos.py:373
 msgid "Repository permissions updated"
-msgstr "Прывілеі рэпазітара абноўлены"
-
-#: kallithea/controllers/admin/repos.py:430
+msgstr "Прывілеі рэпазітара абноўленыя"
+
+#: kallithea/controllers/admin/repos.py:429
 msgid "An error occurred during creation of field"
-msgstr "Адбылася памылка пры стварэнні поля"
-
-#: kallithea/controllers/admin/repos.py:444
+msgstr "Памылка пры стварэнні поля"
+
+#: kallithea/controllers/admin/repos.py:443
 msgid "An error occurred during removal of field"
-msgstr "Адбылася памылка пры выдаленні поля"
-
-#: kallithea/controllers/admin/repos.py:460
+msgstr "Памылка пры выдаленні поля"
+
+#: kallithea/controllers/admin/repos.py:459
 msgid "-- Not a fork --"
 msgstr "-- Не форк --"
 
-#: kallithea/controllers/admin/repos.py:491
+#: kallithea/controllers/admin/repos.py:490
 msgid "Updated repository visibility in public journal"
 msgstr "Бачнасць рэпазітара ў публічным часопісе абноўлена"
 
-#: kallithea/controllers/admin/repos.py:495
+#: kallithea/controllers/admin/repos.py:494
 msgid "An error occurred during setting this repository in public journal"
-msgstr "Адбылася памылка пры ўсталёўцы рэпазітара ў агульнадаступны часопіс"
-
-#: kallithea/controllers/admin/repos.py:512
+msgstr "Памылка пры даданні рэпазітара ў агульнадаступны часопіс"
+
+#: kallithea/controllers/admin/repos.py:511
 msgid "Nothing"
 msgstr "Нічога"
 
-#: kallithea/controllers/admin/repos.py:514
+#: kallithea/controllers/admin/repos.py:513
 #, python-format
 msgid "Marked repository %s as fork of %s"
 msgstr "Рэпазітар %s адзначаны як форк %s"
 
-#: kallithea/controllers/admin/repos.py:521
+#: kallithea/controllers/admin/repos.py:520
 msgid "An error occurred during this operation"
-msgstr "Адбылася памылка пры выкананні аперацыі"
-
-#: kallithea/controllers/admin/repos.py:537
-#: kallithea/controllers/admin/repos.py:564
+msgstr "Памылка пры выкананні аперацыі"
+
+#: kallithea/controllers/admin/repos.py:536
+#: kallithea/controllers/admin/repos.py:563
 msgid "Repository has been locked"
 msgstr "Рэпазітар заблакаваны"
 
-#: kallithea/controllers/admin/repos.py:540
-#: kallithea/controllers/admin/repos.py:561
+#: kallithea/controllers/admin/repos.py:539
+#: kallithea/controllers/admin/repos.py:560
 msgid "Repository has been unlocked"
-msgstr "Рэпазітар адблакаваны"
-
-#: kallithea/controllers/admin/repos.py:543
-#: kallithea/controllers/admin/repos.py:568
+msgstr "Рэпазітар разблакаваны"
+
+#: kallithea/controllers/admin/repos.py:542
+#: kallithea/controllers/admin/repos.py:567
 msgid "An error occurred during unlocking"
-msgstr "Адбылася памылка падчас разблакавання"
-
-#: kallithea/controllers/admin/repos.py:582
+msgstr "Памылка падчас разблакавання"
+
+#: kallithea/controllers/admin/repos.py:581
 msgid "Cache invalidation successful"
 msgstr "Кэш скінуты"
 
-#: kallithea/controllers/admin/repos.py:586
+#: kallithea/controllers/admin/repos.py:585
 msgid "An error occurred during cache invalidation"
-msgstr "Адбылася памылка пры ачыстцы кэша"
-
-#: kallithea/controllers/admin/repos.py:601
+msgstr "Памылка пры скіданні кэша"
+
+#: kallithea/controllers/admin/repos.py:600
 msgid "Pulled from remote location"
-msgstr "Занесены змены з выдаленага рэпазітара"
-
-#: kallithea/controllers/admin/repos.py:604
+msgstr "Занесеныя змены з аддаленага рэпазітара"
+
+#: kallithea/controllers/admin/repos.py:603
 msgid "An error occurred during pull from remote location"
-msgstr "Адбылася памылка пры занясенні змен з выдаленага рэпазітара"
-
-#: kallithea/controllers/admin/repos.py:637
+msgstr "Памылка пры занясенні змен з аддаленага рэпазітара"
+
+#: kallithea/controllers/admin/repos.py:636
 msgid "An error occurred during deletion of repository stats"
 msgstr "Адбылася памылка пры выдаленні статыстыкі рэпазітара"
 
-#: kallithea/controllers/admin/settings.py:170
+#: kallithea/controllers/admin/settings.py:141
 msgid "Updated VCS settings"
 msgstr "Абноўлены налады VCS"
 
-#: kallithea/controllers/admin/settings.py:174
+#: kallithea/controllers/admin/settings.py:145
 msgid ""
 "Unable to activate hgsubversion support. The \"hgsubversion\" library is "
 "missing"
 msgstr ""
-"Немагчыма ўключыць падтрымку hgsubversion. Бібліятэка «hgsubversion» "
+"Немагчыма ўключыць падтрымку hgsubversion. Бібліятэка hgsubversion "
 "адсутнічае"
 
-#: kallithea/controllers/admin/settings.py:180
-#: kallithea/controllers/admin/settings.py:277
+#: kallithea/controllers/admin/settings.py:151
+#: kallithea/controllers/admin/settings.py:248
 msgid "Error occurred while updating application settings"
-msgstr "Адбылася памылка пры абнаўленні налад прыкладання"
-
-#: kallithea/controllers/admin/settings.py:216
+msgstr "Памылка пры абнаўленні наладаў праграмы"
+
+#: kallithea/controllers/admin/settings.py:187
 #, python-format
 msgid "Repositories successfully rescanned. Added: %s. Removed: %s."
-msgstr "Рэпазітары паспяхова перасканіраваны, дададзена: %s, выдалена: %s."
-
-#: kallithea/controllers/admin/settings.py:273
+msgstr "Рэпазітары паспяхова перасканаваныя, дададзена: %s, выдалена: %s."
+
+#: kallithea/controllers/admin/settings.py:244
 msgid "Updated application settings"
-msgstr "Абноўленыя параметры налады прыкладання"
-
-#: kallithea/controllers/admin/settings.py:330
+msgstr "Абноўленыя налады праграмы"
+
+#: kallithea/controllers/admin/settings.py:301
 msgid "Updated visualisation settings"
 msgstr "Налады візуалізацыі абноўленыя"
 
-#: kallithea/controllers/admin/settings.py:335
+#: kallithea/controllers/admin/settings.py:306
 msgid "Error occurred during updating visualisation settings"
-msgstr "Адбылася памылка пры абнаўленні налад візуалізацыі"
-
-#: kallithea/controllers/admin/settings.py:361
+msgstr "Адбылася памылка пры абнаўленні наладаў візуалізацыі"
+
+#: kallithea/controllers/admin/settings.py:332
 msgid "Please enter email address"
-msgstr "Калі ласка, увядзіце email-адрас"
-
-#: kallithea/controllers/admin/settings.py:376
+msgstr "Калі ласка, увядзіце e-mail-адрас"
+
+#: kallithea/controllers/admin/settings.py:347
 msgid "Send email task created"
 msgstr "Задача адпраўкі e-mail створаная"
 
-#: kallithea/controllers/admin/settings.py:407
+#: kallithea/controllers/admin/settings.py:378
 msgid "Added new hook"
 msgstr "Дададзены новы хук"
 
-#: kallithea/controllers/admin/settings.py:421
+#: kallithea/controllers/admin/settings.py:392
 msgid "Updated hooks"
 msgstr "Абноўленыя хукі"
 
-#: kallithea/controllers/admin/settings.py:425
+#: kallithea/controllers/admin/settings.py:396
 msgid "Error occurred during hook creation"
-msgstr "адбылася памылка пры стварэнні хука"
-
-#: kallithea/controllers/admin/settings.py:451
+msgstr "Памылка пры стварэнні хука"
+
+#: kallithea/controllers/admin/settings.py:422
 msgid "Whoosh reindex task scheduled"
-msgstr "Запланавана пераіндэксаванне базы Whoosh"
+msgstr "Запланаванае пераіндэксаванне базы Whoosh"
 
 #: kallithea/controllers/admin/user_groups.py:150
 #, python-format
 msgid "Created user group %s"
-msgstr "Створана група карыстачоў %s"
+msgstr "Створана група карыстальнікаў %s"
 
 #: kallithea/controllers/admin/user_groups.py:163
 #, python-format
 msgid "Error occurred during creation of user group %s"
-msgstr "Адбылася памылка пры стварэнні групы карыстачоў %s"
+msgstr "Памылка пры стварэнні групы карыстальнікаў %s"
 
 #: kallithea/controllers/admin/user_groups.py:201
 #, python-format
 msgid "Updated user group %s"
-msgstr "Група карыстачоў %s абноўлена"
+msgstr "Група карыстальнікаў %s абноўленая"
 
 #: kallithea/controllers/admin/user_groups.py:224
 #, python-format
 msgid "Error occurred during update of user group %s"
-msgstr "Адбылася памылка пры абнаўленні групы карыстачоў %s"
+msgstr "Памылка пры абнаўленні групы карыстальнікаў %s"
 
 #: kallithea/controllers/admin/user_groups.py:242
 msgid "Successfully deleted user group"
-msgstr "Група карыстачоў паспяхова выдалена"
+msgstr "Група карыстальнікаў паспяхова выдаленая"
 
 #: kallithea/controllers/admin/user_groups.py:247
 msgid "An error occurred during deletion of user group"
-msgstr "Адбылася памылка пры выдаленні групы карыстачоў"
+msgstr "Памылка пры выдаленні групы карыстальнікаў"
 
 #: kallithea/controllers/admin/user_groups.py:314
 msgid "Target group cannot be the same"
-msgstr "Мэтавая група не можа быць такі ж"
+msgstr "Мэтавая група не можа быць той жа самай"
 
 #: kallithea/controllers/admin/user_groups.py:320
 msgid "User group permissions updated"
-msgstr "Прывілеі групы карыстачоў абноўлены"
+msgstr "Прывілеі групы карыстальнікаў абноўленыя"
 
 #: kallithea/controllers/admin/user_groups.py:440
-#: kallithea/controllers/admin/users.py:384
+#: kallithea/controllers/admin/users.py:383
 msgid "Updated permissions"
-msgstr "Абноўлены прывілеі"
+msgstr "Абноўленыя прывілеі"
 
 #: kallithea/controllers/admin/user_groups.py:444
-#: kallithea/controllers/admin/users.py:388
+#: kallithea/controllers/admin/users.py:387
 msgid "An error occurred during permissions saving"
-msgstr "Адбылася памылка пры захаванні прывілеяў"
-
-#: kallithea/controllers/admin/users.py:134
+msgstr "Памылка пры захаванні прывілеяў"
+
+#: kallithea/controllers/admin/users.py:133
 #, python-format
 msgid "Created user %s"
-msgstr "Карыстач %s створаны"
-
-#: kallithea/controllers/admin/users.py:149
+msgstr "Карыстальнік %s створаны"
+
+#: kallithea/controllers/admin/users.py:148
 #, python-format
 msgid "Error occurred during creation of user %s"
-msgstr "Адбылася памылка пры стварэнні карыстача %s"
-
-#: kallithea/controllers/admin/users.py:182
+msgstr "Памылка пры стварэнні карыстальніка %s"
+
+#: kallithea/controllers/admin/users.py:181
 msgid "User updated successfully"
-msgstr "Карыстач паспяхова абноўлены"
-
-#: kallithea/controllers/admin/users.py:218
+msgstr "Карыстальнік паспяхова абноўлены"
+
+#: kallithea/controllers/admin/users.py:217
 msgid "Successfully deleted user"
-msgstr "Карыстач паспяхова выдалены"
-
-#: kallithea/controllers/admin/users.py:223
+msgstr "Карыстальнік паспяхова выдалены"
+
+#: kallithea/controllers/admin/users.py:222
 msgid "An error occurred during deletion of user"
-msgstr "Адбылася памылка пры выдаленні карыстача"
-
-#: kallithea/controllers/admin/users.py:236
+msgstr "Памылка пры выдаленні карыстальніка"
+
+#: kallithea/controllers/admin/users.py:235
 msgid "The default user cannot be edited"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:463
+#: kallithea/controllers/admin/users.py:462
 #, python-format
 msgid "Added IP address %s to user whitelist"
-msgstr "Дададзены IP %s у белы спіс карыстача"
-
-#: kallithea/controllers/admin/users.py:469
+msgstr "Дададзены IP %s у белы спіс карыстальніка"
+
+#: kallithea/controllers/admin/users.py:468
 msgid "An error occurred while adding IP address"
 msgstr "Адбылася памылка пры захаванні IP"
 
-#: kallithea/controllers/admin/users.py:483
+#: kallithea/controllers/admin/users.py:482
 msgid "Removed IP address from user whitelist"
-msgstr "Выдалены IP %s з белага спісу карыстача"
-
-#: kallithea/lib/auth.py:743
+msgstr "Выдалены IP %s з белага спісу карыстальніка"
+
+#: kallithea/lib/auth.py:737
 #, python-format
 msgid "IP %s not allowed"
 msgstr "IP %s заблакаваны"
 
-#: kallithea/lib/auth.py:756
+#: kallithea/lib/auth.py:750
 msgid "Invalid API key"
 msgstr "Няслушны API-ключ"
 
-#: kallithea/lib/auth.py:812
+#: kallithea/lib/auth.py:768
+msgid "CSRF token leak has been detected - all form tokens have been expired"
+msgstr ""
+
+#: kallithea/lib/auth.py:813
 msgid "You need to be a registered user to perform this action"
-msgstr "Вы павінны быць зарэгістраваным карыстачом, каб выканаць гэта дзеянне"
-
-#: kallithea/lib/auth.py:844
+msgstr "Вы павінны быць зарэгістраваным карыстальнікам, каб выканаць гэта дзеянне"
+
+#: kallithea/lib/auth.py:843
 msgid "You need to be signed in to view this page"
-msgstr "Старонка даступная толькі аўтарызаваным карыстачам"
-
-#: kallithea/lib/base.py:490
+msgstr "Старонка даступная толькі аўтарызаваным карыстальнікам"
+
+#: kallithea/lib/base.py:493
 msgid "Repository not found in the filesystem"
 msgstr "Рэпазітар не знойдзены на файлавай сістэме"
 
-#: kallithea/lib/base.py:516 kallithea/lib/helpers.py:622
+#: kallithea/lib/base.py:519 kallithea/lib/helpers.py:623
 msgid "Changeset not found"
 msgstr "Набор змен не знойдзены"
 
@@ -1075,126 +1080,125 @@
 msgid "No changes detected"
 msgstr "Змен не выяўлена"
 
-#: kallithea/lib/helpers.py:609
+#: kallithea/lib/helpers.py:610
 #, python-format
 msgid "Deleted branch: %s"
-msgstr "Выдалена галінка: %s"
-
-#: kallithea/lib/helpers.py:611
+msgstr "Выдаленая галіна: %s"
+
+#: kallithea/lib/helpers.py:612
 #, python-format
 msgid "Created tag: %s"
 msgstr "Створаны тэг: %s"
 
-#: kallithea/lib/helpers.py:671
+#: kallithea/lib/helpers.py:672
 #, python-format
 msgid "Show all combined changesets %s->%s"
 msgstr "Паказаць адрозненні разам %s->%s"
 
-#: kallithea/lib/helpers.py:677
-#, fuzzy
+#: kallithea/lib/helpers.py:678
 msgid "Compare view"
-msgstr "параўнанне"
-
-#: kallithea/lib/helpers.py:696
+msgstr "Параўнанне"
+
+#: kallithea/lib/helpers.py:697
 msgid "and"
 msgstr "і"
 
-#: kallithea/lib/helpers.py:697
+#: kallithea/lib/helpers.py:698
 #, python-format
 msgid "%s more"
 msgstr "на %s больш"
 
-#: kallithea/lib/helpers.py:698 kallithea/templates/changelog/changelog.html:44
+#: kallithea/lib/helpers.py:699 kallithea/templates/changelog/changelog.html:44
 msgid "revisions"
 msgstr "версіі"
 
-#: kallithea/lib/helpers.py:722
+#: kallithea/lib/helpers.py:723
 #, python-format
 msgid "Fork name %s"
 msgstr "Імя форка %s"
 
-#: kallithea/lib/helpers.py:742
+#: kallithea/lib/helpers.py:743
 #, python-format
 msgid "Pull request %s"
 msgstr "Pull-запыт %s"
 
-#: kallithea/lib/helpers.py:752
+#: kallithea/lib/helpers.py:753
 msgid "[deleted] repository"
 msgstr "[выдалены] рэпазітар"
 
-#: kallithea/lib/helpers.py:754 kallithea/lib/helpers.py:766
+#: kallithea/lib/helpers.py:755 kallithea/lib/helpers.py:767
 msgid "[created] repository"
 msgstr "[створаны] рэпазітар"
 
-#: kallithea/lib/helpers.py:756
+#: kallithea/lib/helpers.py:757
 msgid "[created] repository as fork"
 msgstr "[створаны] рэпазітар як форк"
 
-#: kallithea/lib/helpers.py:758 kallithea/lib/helpers.py:768
+#: kallithea/lib/helpers.py:759 kallithea/lib/helpers.py:769
 msgid "[forked] repository"
 msgstr "[форкнуты] рэпазітар"
 
-#: kallithea/lib/helpers.py:760 kallithea/lib/helpers.py:770
+#: kallithea/lib/helpers.py:761 kallithea/lib/helpers.py:771
 msgid "[updated] repository"
 msgstr "[абноўлены] рэпазітар"
 
-#: kallithea/lib/helpers.py:762
+#: kallithea/lib/helpers.py:763
 msgid "[downloaded] archive from repository"
 msgstr "[загружаны] архіў з рэпазітара"
 
-#: kallithea/lib/helpers.py:764
+#: kallithea/lib/helpers.py:765
 msgid "[delete] repository"
 msgstr "[выдалены] рэпазітар"
 
-#: kallithea/lib/helpers.py:772
+#: kallithea/lib/helpers.py:773
 msgid "[created] user"
-msgstr "[створаны] карыстач"
-
-#: kallithea/lib/helpers.py:774
+msgstr "[створаны] карыстальнік"
+
+#: kallithea/lib/helpers.py:775
 msgid "[updated] user"
-msgstr "[абноўлены] карыстач"
-
-#: kallithea/lib/helpers.py:776
+msgstr "[абноўлены] карыстальнік"
+
+#: kallithea/lib/helpers.py:777
 msgid "[created] user group"
-msgstr "[створана] група карыстачоў"
-
-#: kallithea/lib/helpers.py:778
+msgstr "[створана] група карыстальнікаў"
+
+#: kallithea/lib/helpers.py:779
 msgid "[updated] user group"
-msgstr "[абноўлена] група карыстачоў"
-
-#: kallithea/lib/helpers.py:780
+msgstr "[абноўлена] група карыстальнікаў"
+
+#: kallithea/lib/helpers.py:781
 msgid "[commented] on revision in repository"
 msgstr "[каментар] да рэвізіі ў рэпазітары"
 
-#: kallithea/lib/helpers.py:782
+#: kallithea/lib/helpers.py:783
 msgid "[commented] on pull request for"
-msgstr "[пракаменціравана] у запыце на занясенне змен для"
-
-#: kallithea/lib/helpers.py:784
+msgstr "[каментар] у pull-запыце для"
+
+#: kallithea/lib/helpers.py:785
 msgid "[closed] pull request for"
-msgstr "[зачынены] Pull-запыт для"
-
-#: kallithea/lib/helpers.py:786
+msgstr "[зачынены] pull-запыт для"
+
+#: kallithea/lib/helpers.py:787
 msgid "[pushed] into"
 msgstr "[адпраўлена] у"
 
-#: kallithea/lib/helpers.py:788
+#: kallithea/lib/helpers.py:789
 msgid "[committed via Kallithea] into repository"
-msgstr "[занесены змены з дапамогай Kallithea] у рэпазітары"
-
-#: kallithea/lib/helpers.py:790
+msgstr "[каміт праз Kallithea] у рэпазітары"
+
+#: kallithea/lib/helpers.py:791
 msgid "[pulled from remote] into repository"
-msgstr "[занесены змены з выдаленага рэпазітара] у рэпазітар"
-
-#: kallithea/lib/helpers.py:792
+msgstr "[занесены з аддаленага рэпазітара] у рэпазітар"
+
+#: kallithea/lib/helpers.py:793
 msgid "[pulled] from"
-msgstr "[занесены змены] з"
-
-#: kallithea/lib/helpers.py:794
+msgstr "[занесены] з"
+
+#: kallithea/lib/helpers.py:795
 msgid "[started following] repository"
 msgstr "[дададзены ў назіранні] рэпазітар"
 
-#: kallithea/lib/helpers.py:796
+#: kallithea/lib/helpers.py:797
 msgid "[stopped following] repository"
 msgstr "[выдалены з назірання] рэпазітар"
 
@@ -1204,8 +1208,8 @@
 msgstr " і на %s больш"
 
 #: kallithea/lib/helpers.py:1128
-#: kallithea/templates/compare/compare_diff.html:65
-#: kallithea/templates/pullrequests/pullrequest_show.html:326
+#: kallithea/templates/compare/compare_diff.html:71
+#: kallithea/templates/pullrequests/pullrequest_show.html:337
 msgid "No files"
 msgstr "Няма файлаў"
 
@@ -1229,7 +1233,7 @@
 msgid "chmod"
 msgstr "chmod"
 
-#: kallithea/lib/helpers.py:1444
+#: kallithea/lib/helpers.py:1469
 #, python-format
 msgid ""
 "%s repository is not mapped to db perhaps it was created or renamed from "
@@ -1240,39 +1244,39 @@
 "пераназваны з файлавай сістэмы. Калі ласка, перазапусціце прыкладанне для"
 " сканавання рэпазітароў"
 
-#: kallithea/lib/utils2.py:415
+#: kallithea/lib/utils2.py:434
 #, python-format
 msgid "%d year"
 msgid_plural "%d years"
 msgstr[0] "%d год"
-msgstr[1] "%d гадоў"
-msgstr[2] "%d гады"
-
-#: kallithea/lib/utils2.py:416
+msgstr[1] "%d гады"
+msgstr[2] "%d гадоў"
+
+#: kallithea/lib/utils2.py:435
 #, python-format
 msgid "%d month"
 msgid_plural "%d months"
 msgstr[0] "%d месяц"
-msgstr[1] "%d месяца"
+msgstr[1] "%d месяцы"
 msgstr[2] "%d месяцаў"
 
-#: kallithea/lib/utils2.py:417
+#: kallithea/lib/utils2.py:436
 #, python-format
 msgid "%d day"
 msgid_plural "%d days"
 msgstr[0] "%d дзень"
-msgstr[1] "%d дня"
+msgstr[1] "%d дні"
 msgstr[2] "%d дзён"
 
-#: kallithea/lib/utils2.py:418
+#: kallithea/lib/utils2.py:437
 #, python-format
 msgid "%d hour"
 msgid_plural "%d hours"
 msgstr[0] "%d гадзіна"
-msgstr[1] "%d гадзін"
-msgstr[2] "%d гадзіны"
-
-#: kallithea/lib/utils2.py:419
+msgstr[1] "%d гадзіны"
+msgstr[2] "%d гадзін"
+
+#: kallithea/lib/utils2.py:438
 #, python-format
 msgid "%d minute"
 msgid_plural "%d minutes"
@@ -1280,37 +1284,37 @@
 msgstr[1] "%d хвіліны"
 msgstr[2] "%d хвілін"
 
-#: kallithea/lib/utils2.py:420
+#: kallithea/lib/utils2.py:439
 #, python-format
 msgid "%d second"
 msgid_plural "%d seconds"
-msgstr[0] "%d секунды"
+msgstr[0] "%d секунда"
 msgstr[1] "%d секунды"
-msgstr[2] "%d секунды"
-
-#: kallithea/lib/utils2.py:436
+msgstr[2] "%d секунд"
+
+#: kallithea/lib/utils2.py:455
 #, python-format
 msgid "in %s"
 msgstr "у %s"
 
-#: kallithea/lib/utils2.py:438
+#: kallithea/lib/utils2.py:457
 #, python-format
 msgid "%s ago"
 msgstr "%s назад"
 
-#: kallithea/lib/utils2.py:440
+#: kallithea/lib/utils2.py:459
 #, python-format
 msgid "in %s and %s"
 msgstr "у %s і %s"
 
-#: kallithea/lib/utils2.py:443
+#: kallithea/lib/utils2.py:462
 #, python-format
 msgid "%s and %s ago"
 msgstr "%s і %s назад"
 
-#: kallithea/lib/utils2.py:446
+#: kallithea/lib/utils2.py:465
 msgid "just now"
-msgstr "прама цяпер"
+msgstr "цяпер"
 
 #: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1163
 #: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1182
@@ -1407,7 +1411,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1531
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1570
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1620
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1665
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1669
 msgid "Kallithea Administrator"
 msgstr "Адміністратар Kallithea"
 
@@ -1424,7 +1428,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1643
 #: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1670
 msgid "Repository creation disabled"
-msgstr "Стварэнне рэпазітароў адключана"
+msgstr "Стварэнне рэпазітароў адключанае"
 
 #: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1175
 #: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1194
@@ -1439,7 +1443,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1644
 #: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1671
 msgid "Repository creation enabled"
-msgstr "Стварэнне рэпазітароў уключана"
+msgstr "Стварэнне рэпазітароў уключанае"
 
 #: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1176
 #: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1195
@@ -1454,7 +1458,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1648
 #: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1675
 msgid "Repository forking disabled"
-msgstr "Магчымасць ствараць форк рэпазітара адключана"
+msgstr "Магчымасць ствараць форк рэпазітара адключаная"
 
 #: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1177
 #: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1196
@@ -1469,28 +1473,28 @@
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1649
 #: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1676
 msgid "Repository forking enabled"
-msgstr "Магчымасць ствараць форк рэпазітара ўключана"
+msgstr "Магчымасць ствараць форк рэпазітара ўключаная"
 
 #: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1178
 #: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1197
 #: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1318
 #: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1403
 msgid "Register disabled"
-msgstr "Рэгістрацыя адключана"
+msgstr "Рэгістрацыя адключаная"
 
 #: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1179
 #: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1198
 #: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1319
 #: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1404
 msgid "Register new user with Kallithea with manual activation"
-msgstr "Рэгістрацыя новага карыстача ў Kallithea з ручной актывацыяй"
+msgstr "Рэгістрацыя новага карыстальніка ў Kallithea з ручной актывацыяй"
 
 #: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1182
 #: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1201
 #: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1322
 #: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1407
 msgid "Register new user with Kallithea with auto activation"
-msgstr "Рэгістрацыя новага карыстача ў Kallithea з аўтаматычнай актывацыяй"
+msgstr "Рэгістрацыя новага карыстальніка ў Kallithea з аўтаматычнай актывацыяй"
 
 #: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1623
 #: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1650
@@ -1518,7 +1522,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2063
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2102
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2155
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2229
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2237
 msgid "Approved"
 msgstr "Ухвалена"
 
@@ -1533,7 +1537,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2064
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2103
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2156
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2230
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2238
 msgid "Rejected"
 msgstr "Адхілена"
 
@@ -1560,7 +1564,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1379
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1418
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1471
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1518
 msgid "top level"
 msgstr "верхні ўзровень"
 
@@ -1621,7 +1625,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1632
 #: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1659
 msgid "User group no access"
-msgstr "Група карыстачоў - няма доступу"
+msgstr "Група карыстальнікаў - няма доступу"
 
 #: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1419
 #: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1465
@@ -1632,7 +1636,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1633
 #: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1660
 msgid "User group read access"
-msgstr "Група карыстачоў - доступ на чытанне"
+msgstr "Група карыстальнікаў - доступ на чытанне"
 
 #: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1420
 #: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1466
@@ -1643,7 +1647,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1634
 #: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1661
 msgid "User group write access"
-msgstr "Група карыстачоў - доступ на запіс"
+msgstr "Група карыстальнікаў - доступ на запіс"
 
 #: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1421
 #: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1467
@@ -1654,7 +1658,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1635
 #: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1662
 msgid "User group admin access"
-msgstr "Група карыстачоў - адміністраванне"
+msgstr "Група карыстальнікаў - адміністраванне"
 
 #: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1423
 #: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1469
@@ -1665,7 +1669,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1637
 #: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1664
 msgid "Repository Group creation disabled"
-msgstr "Стварэнне груп рэпазітароў адключана"
+msgstr "Стварэнне груп рэпазітароў адключанае"
 
 #: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1424
 #: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1470
@@ -1676,7 +1680,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1638
 #: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1665
 msgid "Repository Group creation enabled"
-msgstr "Стварэнне груп рэпазітароў уключана"
+msgstr "Стварэнне груп рэпазітароў уключанае"
 
 #: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1426
 #: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1472
@@ -1687,7 +1691,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1640
 #: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1667
 msgid "User Group creation disabled"
-msgstr "Стварэнне груп карыстачоў адключана"
+msgstr "Стварэнне груп карыстальнікаў адключанае"
 
 #: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1427
 #: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1473
@@ -1698,7 +1702,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1641
 #: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1668
 msgid "User Group creation enabled"
-msgstr "Стварэнне груп карыстачоў уключана"
+msgstr "Стварэнне груп карыстальнікаў уключанае"
 
 #: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1435
 #: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1481
@@ -1707,9 +1711,9 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1560
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1599
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1651
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1697
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1701
 msgid "Registration disabled"
-msgstr "Рэгістрацыя адключана"
+msgstr "Рэгістрацыя адключаная"
 
 #: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1436
 #: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1482
@@ -1720,7 +1724,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1652
 #: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1679
 msgid "User Registration with manual account activation"
-msgstr "Рэгістрацыя карыстача з ручной актывацыяй уліковага запісу"
+msgstr "Рэгістрацыя карыстальніка з ручной актывацыяй уліковага запісу"
 
 #: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1437
 #: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1483
@@ -1731,15 +1735,15 @@
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1653
 #: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1680
 msgid "User Registration with automatic account activation"
-msgstr "Рэгістрацыя карыстача з аўтаматычнай актывацыяй"
+msgstr "Рэгістрацыя карыстальніка з аўтаматычнай актывацыяй"
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1645
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1691
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1695
 msgid "Repository creation enabled with write permission to a repository group"
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1646
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1692
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1696
 msgid "Repository creation disabled with write permission to a repository group"
 msgstr ""
 
@@ -1748,117 +1752,103 @@
 msgid "on line %s"
 msgstr "на радку %s"
 
-#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:169
+#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:170
 msgid "[Mention]"
 msgstr "[Згадванне]"
 
-#: kallithea/model/db.py:1667
+#: kallithea/model/db.py:1671
 msgid "Default user has no access to new repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1668
-#, fuzzy
-msgid "Default user has read access to new repositories"
-msgstr "Несанкцыянаваны доступ да рэсурсу"
-
-#: kallithea/model/db.py:1669
-#, fuzzy
-msgid "Default user has write access to new repositories"
-msgstr "Несанкцыянаваны доступ да рэсурсу"
-
-#: kallithea/model/db.py:1670
-msgid "Default user has admin access to new repositories"
-msgstr ""
-
 #: kallithea/model/db.py:1672
-msgid "Default user has no access to new repository groups"
+msgid "Default user has read access to new repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1673
-msgid "Default user has read access to new repository groups"
+msgid "Default user has write access to new repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1674
-msgid "Default user has write access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1675
-msgid "Default user has admin access to new repository groups"
+msgid "Default user has admin access to new repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1676
+msgid "Default user has no access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1677
-msgid "Default user has no access to new user groups"
+msgid "Default user has read access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1678
-msgid "Default user has read access to new user groups"
+msgid "Default user has write access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1679
-msgid "Default user has write access to new user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1680
-msgid "Default user has admin access to new user groups"
+msgid "Default user has admin access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1681
+msgid "Default user has no access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1682
-#, fuzzy
-msgid "Only admins can create repository groups"
-msgstr "Створана новая група рэпазітароў %s"
+msgid "Default user has read access to new user groups"
+msgstr ""
 
 #: kallithea/model/db.py:1683
-#, fuzzy
-msgid "Non-admins can create repository groups"
-msgstr "Створана новая група рэпазітароў %s"
-
-#: kallithea/model/db.py:1685
-#, fuzzy
-msgid "Only admins can create user groups"
-msgstr "Ствараць групы карыстачоў"
+msgid "Default user has write access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1684
+msgid "Default user has admin access to new user groups"
+msgstr ""
 
 #: kallithea/model/db.py:1686
-#, fuzzy
-msgid "Non-admins can create user groups"
-msgstr "Ствараць групы карыстачоў"
-
-#: kallithea/model/db.py:1688
-#, fuzzy
-msgid "Only admins can create top level repositories"
-msgstr "Рэпазітары верхняга ўзроўню"
+msgid "Only admins can create repository groups"
+msgstr "Толькі адміністратары могуць ствараць групы репазітароў"
+
+#: kallithea/model/db.py:1687
+msgid "Non-admins can create repository groups"
+msgstr "Неадміністратары могуць ствараць групы репазітароў"
 
 #: kallithea/model/db.py:1689
-#, fuzzy
+msgid "Only admins can create user groups"
+msgstr "Толькі адміністратары могуць ствараць групы карыстальнікаў"
+
+#: kallithea/model/db.py:1690
+msgid "Non-admins can create user groups"
+msgstr "Неадміністратары могуць ствараць групы карыстальнікаў"
+
+#: kallithea/model/db.py:1692
+msgid "Only admins can create top level repositories"
+msgstr "Толькі адміністратары могуць ствараць рэпазітары верхняга ўзроўню"
+
+#: kallithea/model/db.py:1693
 msgid "Non-admins can create top level repositories"
-msgstr "Рэпазітары верхняга ўзроўню"
-
-#: kallithea/model/db.py:1694
-#, fuzzy
-msgid "Only admins can fork repositories"
-msgstr "Месцазнаходжанне рэпазітароў"
-
-#: kallithea/model/db.py:1695
-#, fuzzy
-msgid "Non-admins can can fork repositories"
-msgstr "Скінуць кэш для ўсіх рэпазітароў"
+msgstr "Неадміністратары могуць ствараць рэпазітары верхняга ўзроўню"
 
 #: kallithea/model/db.py:1698
-#, fuzzy
-msgid "User registration with manual account activation"
-msgstr "Рэгістрацыя карыстача з ручной актывацыяй уліковага запісу"
+msgid "Only admins can fork repositories"
+msgstr "Месцазнаходжанне рэпазітароў"
 
 #: kallithea/model/db.py:1699
-#, fuzzy
+msgid "Non-admins can fork repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1702
+msgid "User registration with manual account activation"
+msgstr "Рэгістрацыя карыстальніка з ручной актывацыяй уліковага запісу"
+
+#: kallithea/model/db.py:1703
 msgid "User registration with automatic account activation"
-msgstr "Рэгістрацыя карыстача з аўтаматычнай актывацыяй"
-
-#: kallithea/model/db.py:2228
-#, fuzzy
+msgstr "Рэгістрацыя карыстальніка з аўтаматычнай актывацыяй"
+
+#: kallithea/model/db.py:2236
 msgid "Not reviewed"
 msgstr "Не прагледжана"
 
-#: kallithea/model/db.py:2231
-#, fuzzy
+#: kallithea/model/db.py:2239
 msgid "Under review"
 msgstr "На разглядзе"
 
@@ -1880,7 +1870,7 @@
 msgid "Enter %(min)i characters or more"
 msgstr "Увядзіце не меней %(min)i знакаў"
 
-#: kallithea/model/forms.py:160
+#: kallithea/model/forms.py:165
 msgid "Name must not contain only digits"
 msgstr "Імя не можа ўтрымліваць толькі лічбы"
 
@@ -1952,20 +1942,17 @@
 #: kallithea/model/notification.py:305
 #, python-format
 msgid "New user %(new_username)s registered"
-msgstr "Новы карыстач \"%(new_username)s\" зарэгістраваны"
+msgstr "Новы карыстальнік \"%(new_username)s\" зарэгістраваны"
 
 #: kallithea/model/notification.py:307
 #, fuzzy, python-format
-#| msgid "%(user)s wants you to review pull request %(pr_nice_id)s:
-#| %(pr_title)s"
 msgid "[Added] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
 msgstr "%(user)s просіць вас разгледзець pull request %(pr_nice_id)s: %(pr_title)s"
 
 #: kallithea/model/notification.py:308
 #, fuzzy, python-format
-#| msgid "[commented] on pull request for"
 msgid "[Comment] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
-msgstr "[пракаменціравана] у запыце на занясенне змен для"
+msgstr "[пракаментавана] у запыце на занясенне змен для"
 
 #: kallithea/model/notification.py:321
 msgid "Closing"
@@ -1976,19 +1963,19 @@
 msgid "%(user)s wants you to review pull request %(pr_nice_id)s: %(pr_title)s"
 msgstr "%(user)s просіць вас разгледзець pull request %(pr_nice_id)s: %(pr_title)s"
 
-#: kallithea/model/scm.py:812
+#: kallithea/model/scm.py:708
 msgid "latest tip"
 msgstr "апошняя версія"
 
 #: kallithea/model/user.py:192
 msgid "New user registration"
-msgstr "Рэгістрацыя новага карыстача"
+msgstr "Рэгістрацыя новага карыстальніка"
 
 #: kallithea/model/user.py:256
 msgid "You can't remove this user since it is crucial for the entire application"
 msgstr ""
-"Вы не можаце выдаліць карыстача, паколькі гэта крытычна для працы ўсяго "
-"прыкладання"
+"Вы не можаце выдаліць карыстальніка, паколькі гэта крытычна для працы "
+"ўсёй праграмы"
 
 #: kallithea/model/user.py:261
 #, python-format
@@ -1996,8 +1983,9 @@
 "User \"%s\" still owns %s repositories and cannot be removed. Switch "
 "owners or remove those repositories: %s"
 msgstr ""
-"Карыстач \"%s\" усё яшчэ з'яўляецца ўладальнікам %s рэпазітароў і таму не"
-" можа быць выдалены. Зменіце ўладальніка ці выдаліце гэтыя рэпазітары: %s"
+"Карыстальнік \"%s\" усё яшчэ з'яўляецца ўладальнікам %s рэпазітароў і "
+"таму не можа быць выдалены. Змяніце ўладальніка ці выдаліце гэтыя "
+"рэпазітары: %s"
 
 #: kallithea/model/user.py:266
 #, python-format
@@ -2005,8 +1993,8 @@
 "User \"%s\" still owns %s repository groups and cannot be removed. Switch"
 " owners or remove those repository groups: %s"
 msgstr ""
-"Карыстач \"%s\" усё яшчэ з'яўляецца ўладальнікам %s груп рэпазітароў і "
-"таму не можа быць выдалены. Зменіце ўладальніка ці выдаліце дадзеныя "
+"Карыстальнік \"%s\" усё яшчэ з'яўляецца ўладальнікам %s груп рэпазітароў "
+"і таму не можа быць выдалены. Змяніце ўладальніка ці выдаліце гэтая "
 "групы: %s"
 
 #: kallithea/model/user.py:273
@@ -2015,21 +2003,19 @@
 "User \"%s\" still owns %s user groups and cannot be removed. Switch "
 "owners or remove those user groups: %s"
 msgstr ""
-"Карыстач \"%s\" усё яшчэ з'яўляецца ўладальнікам %s груп карыстачоў і "
-"таму не можа быць выдалены. Зменіце ўладальніка ці выдаліце дадзеныя "
-"групы: %s"
-
-#: kallithea/model/user.py:360
+"Карыстальнік \"%s\" усё яшчэ з'яўляецца ўладальнікам %s груп "
+"карыстальнікаў і таму не можа быць выдалены. Змяніце ўладальніка ці "
+"выдаліце гэтыя групы: %s"
+
+#: kallithea/model/user.py:368
 msgid "Password reset link"
 msgstr "Спасылка скіду пароля"
 
-#: kallithea/model/user.py:408
-#, fuzzy
-#| msgid "Password reset link"
+#: kallithea/model/user.py:418
 msgid "Password reset notification"
-msgstr "Спасылка скіду пароля"
-
-#: kallithea/model/user.py:409
+msgstr "Паведамленне пра скіданне пароля"
+
+#: kallithea/model/user.py:419
 #, python-format
 msgid ""
 "The password to your account %s has been changed using password reset "
@@ -2040,112 +2026,111 @@
 msgid "Value cannot be an empty list"
 msgstr "Значэнне не можа быць пустым спісам"
 
-#: kallithea/model/validators.py:95
+#: kallithea/model/validators.py:96
 #, python-format
 msgid "Username \"%(username)s\" already exists"
-msgstr "Карыстач з імем \"%(username)s\" ужо існуе"
-
-#: kallithea/model/validators.py:97
+msgstr "Карыстальнік з імем \"%(username)s\" ужо існуе"
+
+#: kallithea/model/validators.py:98
 #, python-format
 msgid "Username \"%(username)s\" cannot be used"
 msgstr "Імя \"%(username)s\" недапушчальнае"
 
-#: kallithea/model/validators.py:99
+#: kallithea/model/validators.py:100
 msgid ""
 "Username may only contain alphanumeric characters underscores, periods or"
 " dashes and must begin with an alphanumeric character or underscore"
 msgstr ""
-"Імя карыстача можа ўтрымоўваць толькі літары, лічбы, знакі падкрэслення, "
-"кропкі і працяжнік; а гэтак жа павінна пачынацца з літары, лічбы або са "
-"знака падкрэслення"
-
-#: kallithea/model/validators.py:126
+"Імя карыстальніка можа ўтрымоўваць толькі літары, лічбы, знакі "
+"падкрэслення, кропкі і працяжнік; а гэтак жа павінна пачынацца з літары, "
+"лічбы або са знака падкрэслення"
+
+#: kallithea/model/validators.py:127
 msgid "The input is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:133
+#: kallithea/model/validators.py:134
 #, python-format
 msgid "Username %(username)s is not valid"
-msgstr "Імя \"%(username)s\" недапушчальна"
-
-#: kallithea/model/validators.py:152
+msgstr "Імя \"%(username)s\" недапушчальнае"
+
+#: kallithea/model/validators.py:154
 msgid "Invalid user group name"
-msgstr "Няслушнае імя групы карыстачоў"
-
-#: kallithea/model/validators.py:153
+msgstr "Няслушнае імя групы карыстальнікаў"
+
+#: kallithea/model/validators.py:155
 #, python-format
 msgid "User group \"%(usergroup)s\" already exists"
-msgstr "Група карыстачоў \"%(usergroup)s\" ужо існуе"
-
-#: kallithea/model/validators.py:155
+msgstr "Група карыстальнікаў \"%(usergroup)s\" ужо існуе"
+
+#: kallithea/model/validators.py:157
 msgid ""
 "user group name may only contain alphanumeric characters underscores, "
 "periods or dashes and must begin with alphanumeric character"
 msgstr ""
-"імя групы карыстачоў можа ўтрымоўваць толькі літары, лічбы, знакі "
+"імя групы карыстальнікаў можа ўтрымоўваць толькі літары, лічбы, знакі "
 "падкрэслення, кропкі і працяжнік; а гэтак жа павінна пачынацца з літары "
 "ці лічбы"
 
-#: kallithea/model/validators.py:193
+#: kallithea/model/validators.py:197
 msgid "Cannot assign this group as parent"
 msgstr "Немагчыма выкарыстоўваць гэту групу як бацькоўскую"
 
-#: kallithea/model/validators.py:194
+#: kallithea/model/validators.py:198
 #, python-format
 msgid "Group \"%(group_name)s\" already exists"
 msgstr "Група \"%(group_name)s\" ужо існуе"
 
-#: kallithea/model/validators.py:196
+#: kallithea/model/validators.py:200
 #, python-format
 msgid "Repository with name \"%(group_name)s\" already exists"
 msgstr "Рэпазітар з  імем \"%(group_name)s\" ужо існуе"
 
-#: kallithea/model/validators.py:254
+#: kallithea/model/validators.py:258
 msgid "Invalid characters (non-ascii) in password"
 msgstr "Недапушчальныя знакі (не ascii) у паролі"
 
-#: kallithea/model/validators.py:269
+#: kallithea/model/validators.py:273
 msgid "Invalid old password"
 msgstr "Няслушна зададзены стары пароль"
 
-#: kallithea/model/validators.py:285
+#: kallithea/model/validators.py:289
 msgid "Passwords do not match"
 msgstr "Паролі не супадаюць"
 
-#: kallithea/model/validators.py:300
+#: kallithea/model/validators.py:304
 msgid "Invalid username or password"
 msgstr "Няслушнае імя ці пароль"
 
-#: kallithea/model/validators.py:331
+#: kallithea/model/validators.py:335
 msgid "Token mismatch"
 msgstr "Несупадзенне токенаў"
 
-#: kallithea/model/validators.py:345
+#: kallithea/model/validators.py:351
 #, python-format
 msgid "Repository name %(repo)s is not allowed"
 msgstr "Імя рэпазітара %(repo)s забароненае"
 
-#: kallithea/model/validators.py:347
+#: kallithea/model/validators.py:353
 #, python-format
 msgid "Repository named %(repo)s already exists"
 msgstr "Рэпазітар %(repo)s ужо існуе"
 
-#: kallithea/model/validators.py:348
+#: kallithea/model/validators.py:354
 #, python-format
 msgid "Repository \"%(repo)s\" already exists in group \"%(group)s\""
 msgstr "Рэпазітар \"%(repo)s\" ужо існуе ў групе \"%(group)s\""
 
-#: kallithea/model/validators.py:350
+#: kallithea/model/validators.py:356
 #, python-format
 msgid "Repository group with name \"%(repo)s\" already exists"
 msgstr "Група рэпазітароў \"%(repo)s\" ужо існуе"
 
-#: kallithea/model/validators.py:465
+#: kallithea/model/validators.py:470
 msgid "Invalid repository URL"
 msgstr "Няслушны URL рэпазітара"
 
-#: kallithea/model/validators.py:466
-#, fuzzy
+#: kallithea/model/validators.py:471
 msgid ""
 "Invalid repository URL. It must be a valid http, https, ssh, svn+http or "
 "svn+https URL"
@@ -2153,69 +2138,69 @@
 "Няслушны URL рэпазітара. Ён мусіць быць карэктным URL http, https, ssh, "
 "svn+http ці svn+https"
 
-#: kallithea/model/validators.py:489
+#: kallithea/model/validators.py:496
 msgid "Fork has to be the same type as parent"
 msgstr "Тып форка будзе супадаць з бацькоўскім"
 
-#: kallithea/model/validators.py:504
+#: kallithea/model/validators.py:511
 msgid "You don't have permissions to create repository in this group"
-msgstr "У вас недастаткова мае рацыю для стварэння рэпазітароў у гэтай групе"
-
-#: kallithea/model/validators.py:506
+msgstr "У вас недастаткова правоў для стварэння рэпазітароў у гэтай групе"
+
+#: kallithea/model/validators.py:513
 msgid "no permission to create repository in root location"
-msgstr "недастаткова мае рацыю для стварэння рэпазітара ў каранёвым каталогу"
-
-#: kallithea/model/validators.py:556
+msgstr "недастаткова правоў для стварэння рэпазітара ў каранёвым каталогу"
+
+#: kallithea/model/validators.py:563
 msgid "You don't have permissions to create a group in this location"
 msgstr "У Вас недастаткова прывілеяў для стварэння групы ў гэтым месцы"
 
-#: kallithea/model/validators.py:597
+#: kallithea/model/validators.py:604
 msgid "This username or user group name is not valid"
-msgstr "Дадзенае імя карыстача ці групы карыстачоў недапушчальна"
-
-#: kallithea/model/validators.py:690
+msgstr "Дадзенае імя карыстальніка ці групы карыстальнікаў недапушчальна"
+
+#: kallithea/model/validators.py:697
 msgid "This is not a valid path"
 msgstr "Гэты шлях хібны"
 
-#: kallithea/model/validators.py:705
+#: kallithea/model/validators.py:714
 msgid "This email address is already in use"
-msgstr "Гэты E-mail ужо заняты"
-
-#: kallithea/model/validators.py:725
-#, fuzzy, python-format
+msgstr "Гэты e-mail ужо ўжываецца"
+
+#: kallithea/model/validators.py:734
+#, python-format
 msgid "Email address \"%(email)s\" not found"
-msgstr "\"%(email)s\" не існуе."
-
-#: kallithea/model/validators.py:762
+msgstr "e-mail \"%(email)s\" не існуе."
+
+#: kallithea/model/validators.py:771
 msgid ""
 "The LDAP Login attribute of the CN must be specified - this is the name "
 "of the attribute that is equivalent to \"username\""
 msgstr ""
 "Для ўваходу па LDAP павінна быць паказана значэнне атрыбута CN - гэта "
-"эквівалент імя карыстача"
-
-#: kallithea/model/validators.py:774
+"эквівалент імя карыстальніка"
+
+#: kallithea/model/validators.py:783
 msgid "Please enter a valid IPv4 or IPv6 address"
 msgstr "Калі ласка, увядзіце існы IPv4 ці IPv6 адрас"
 
-#: kallithea/model/validators.py:775
+#: kallithea/model/validators.py:784
 #, python-format
 msgid "The network size (bits) must be within the range of 0-32 (not %(bits)r)"
 msgstr ""
 "Значэнне маскі падсеткі павінна быць у межах ад 0 да 32 (%(bits)r - "
 "няслушна)"
 
-#: kallithea/model/validators.py:808
+#: kallithea/model/validators.py:817
 msgid "Key name can only consist of letters, underscore, dash or numbers"
 msgstr ""
 "Ключавое імя можа толькі складацца з літар, знака падкрэслення, працяжнік"
 " ці лікаў"
 
-#: kallithea/model/validators.py:822
+#: kallithea/model/validators.py:831
 msgid "Filename cannot be inside a directory"
 msgstr "Файла няма ў каталогу"
 
-#: kallithea/model/validators.py:838
+#: kallithea/model/validators.py:847
 #, python-format
 msgid "Plugins %(loaded)s and %(next_to_load)s both export the same name"
 msgstr ""
@@ -2331,7 +2316,7 @@
 #: kallithea/templates/journal/journal.html:189
 #: kallithea/templates/journal/journal.html:280
 msgid "Tip"
-msgstr "Стан"
+msgstr ""
 
 #: kallithea/templates/index_base.html:132
 #: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:10
@@ -2342,7 +2327,7 @@
 #: kallithea/templates/admin/user_groups/user_groups.html:50
 #: kallithea/templates/pullrequests/pullrequest_data.html:16
 #: kallithea/templates/pullrequests/pullrequest_show.html:156
-#: kallithea/templates/pullrequests/pullrequest_show.html:233
+#: kallithea/templates/pullrequests/pullrequest_show.html:244
 #: kallithea/templates/summary/summary.html:134
 msgid "Owner"
 msgstr "Уладальнік"
@@ -2373,7 +2358,7 @@
 
 #: kallithea/templates/index_base.html:142
 msgid "No repositories found."
-msgstr "Рэпазітары не знойдзены."
+msgstr "Рэпазітары не знойдзеныя."
 
 #: kallithea/templates/index_base.html:143
 #: kallithea/templates/admin/my_account/my_account_repos.html:60
@@ -2390,7 +2375,7 @@
 #: kallithea/templates/index_base.html:144
 #: kallithea/templates/admin/my_account/my_account_repos.html:61
 #: kallithea/templates/admin/my_account/my_account_watched.html:61
-#: kallithea/templates/base/base.html:140 kallithea/templates/base/root.html:47
+#: kallithea/templates/base/root.html:47
 #: kallithea/templates/bookmarks/bookmarks.html:83
 #: kallithea/templates/branches/branches.html:83
 #: kallithea/templates/journal/journal.html:202
@@ -2400,7 +2385,7 @@
 msgstr "Загрузка..."
 
 #: kallithea/templates/login.html:5 kallithea/templates/login.html:15
-#: kallithea/templates/base/base.html:326
+#: kallithea/templates/base/base.html:414
 msgid "Log In"
 msgstr "Увайсці"
 
@@ -2415,15 +2400,15 @@
 #: kallithea/templates/admin/users/user_add.html:32
 #: kallithea/templates/admin/users/user_edit_profile.html:24
 #: kallithea/templates/admin/users/users.html:50
-#: kallithea/templates/base/base.html:302
+#: kallithea/templates/base/base.html:390
 #: kallithea/templates/pullrequests/pullrequest_show.html:166
 msgid "Username"
-msgstr "Імя карыстача"
+msgstr "Імя карыстальніка"
 
 #: kallithea/templates/login.html:33 kallithea/templates/register.html:33
 #: kallithea/templates/admin/my_account/my_account.html:37
 #: kallithea/templates/admin/users/user_add.html:41
-#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:399
 msgid "Password"
 msgstr "Пароль"
 
@@ -2433,9 +2418,9 @@
 
 #: kallithea/templates/login.html:53
 msgid "Forgot your password ?"
-msgstr "Забыліся пароль?"
-
-#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:322
+msgstr "Забыліся на пароль?"
+
+#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:410
 msgid "Don't have an account ?"
 msgstr "Няма акаўнта?"
 
@@ -2445,13 +2430,13 @@
 
 #: kallithea/templates/password_reset.html:5
 msgid "Password Reset"
-msgstr "Скід пароля"
+msgstr "Скінуць пароль"
 
 #: kallithea/templates/password_reset.html:12
 #: kallithea/templates/password_reset_confirmation.html:12
 #, python-format
 msgid "Reset Your Password to %s"
-msgstr "Забыліся пароль для %s?"
+msgstr "Забыліся на пароль для %s?"
 
 #: kallithea/templates/password_reset.html:14
 #: kallithea/templates/password_reset_confirmation.html:5
@@ -2470,16 +2455,14 @@
 
 #: kallithea/templates/password_reset.html:46
 msgid "Send Password Reset Email"
-msgstr "Паслаць спасылку скіду пароля"
+msgstr "Паслаць спасылку для скідання пароля"
 
 #: kallithea/templates/password_reset.html:47
 #, fuzzy
-#| msgid "" "Password reset link will be sent to the email address matching
-#| your " "username."
 msgid ""
 "A password reset link will be sent to the specified email address if it "
 "is registered in the system."
-msgstr "Спасылка для скіду пароля была адпраўлена на адпаведны e-mail."
+msgstr "Спасылка для скіду пароля будзе адпраўленая на адпаведны e-mail."
 
 #: kallithea/templates/password_reset_confirmation.html:19
 #, python-format
@@ -2497,14 +2480,10 @@
 msgstr ""
 
 #: kallithea/templates/password_reset_confirmation.html:39
-#, fuzzy
-#| msgid "New password"
 msgid "New Password"
 msgstr "Новы пароль"
 
 #: kallithea/templates/password_reset_confirmation.html:48
-#, fuzzy
-#| msgid "Confirm new password"
 msgid "Confirm New Password"
 msgstr "Пацвердзіце новы пароль"
 
@@ -2520,11 +2499,11 @@
 #: kallithea/templates/register.html:12
 #, python-format
 msgid "Sign Up to %s"
-msgstr "Рэгістра на %s"
+msgstr "Рэгістрацыя на %s"
 
 #: kallithea/templates/register.html:42
 msgid "Re-enter password"
-msgstr "Паўторыце пароль"
+msgstr "Паўтарыце пароль"
 
 #: kallithea/templates/register.html:51
 #: kallithea/templates/admin/my_account/my_account_profile.html:34
@@ -2561,11 +2540,7 @@
 #: kallithea/templates/switch_to_list.html:10
 #: kallithea/templates/branches/branches_data.html:69
 msgid "There are no branches yet"
-msgstr "Галінкі яшчэ не створаны"
-
-#: kallithea/templates/switch_to_list.html:16
-msgid "Closed Branches"
-msgstr "Зачыненыя галінкі"
+msgstr "Галіны яшчэ не створаныя"
 
 #: kallithea/templates/switch_to_list.html:32
 #: kallithea/templates/tags/tags_data.html:44
@@ -2581,11 +2556,11 @@
 #: kallithea/templates/admin/admin.html:13
 #: kallithea/templates/base/base.html:59
 msgid "Admin Journal"
-msgstr "Часопіс адміністратара"
+msgstr "Журнал адміністратара"
 
 #: kallithea/templates/admin/admin.html:10
 msgid "journal filter..."
-msgstr "Фільтр часопіса..."
+msgstr "Фільтр журнала..."
 
 #: kallithea/templates/admin/admin.html:12
 #: kallithea/templates/journal/journal.html:11
@@ -2635,7 +2610,7 @@
 
 #: kallithea/templates/admin/admin_log.html:63
 msgid "No actions yet"
-msgstr "Дзеянні яшчэ не вырабляліся"
+msgstr "Няма інфармацыі"
 
 #: kallithea/templates/admin/auth/auth_settings.html:5
 msgid "Authentication Settings"
@@ -2648,11 +2623,11 @@
 
 #: kallithea/templates/admin/auth/auth_settings.html:28
 msgid "Authentication Plugins"
-msgstr "Убудовы аўтэнтыфікацыі"
+msgstr "Плагіны аўтэнтыфікацыі"
 
 #: kallithea/templates/admin/auth/auth_settings.html:31
 msgid "Enabled Plugins"
-msgstr "Уключаныя ўбудовы"
+msgstr "Уключаныя плагіны"
 
 #: kallithea/templates/admin/auth/auth_settings.html:33
 #, fuzzy
@@ -2660,16 +2635,16 @@
 "Comma-separated list of plugins; Kallithea will try user authentication "
 "in plugin order"
 msgstr ""
-"Спіс убудоў, падзеленых коскі. Kallithea будзе спрабаваць аўтэнтыфікаваць"
-" карыстача ў парадку ўказання ўбудоў"
+"Спіс плагінаў, падзеленых коскамі. Kallithea будзе спрабаваць "
+"аўтэнтыфікаваць карыстальніка ў парадку ўказання плагінаў"
 
 #: kallithea/templates/admin/auth/auth_settings.html:34
 msgid "Available built-in plugins"
-msgstr "Даступныя ўбудаваныя ўбудовы"
+msgstr "Даступныя ўбудаваныя плагіны"
 
 #: kallithea/templates/admin/auth/auth_settings.html:51
 msgid "Plugin"
-msgstr "Убудова"
+msgstr "Плагін"
 
 #: kallithea/templates/admin/auth/auth_settings.html:101
 #: kallithea/templates/admin/defaults/defaults.html:82
@@ -2695,7 +2670,7 @@
 #: kallithea/templates/admin/defaults/defaults.html:11
 #: kallithea/templates/base/base.html:66
 msgid "Repository Defaults"
-msgstr "Значэнні па змаўчанні"
+msgstr "Значэнні па змоўчанні"
 
 #: kallithea/templates/admin/defaults/defaults.html:33
 #: kallithea/templates/admin/repos/repo_add_base.html:55
@@ -2748,12 +2723,12 @@
 #: kallithea/templates/admin/defaults/defaults.html:77
 #: kallithea/templates/admin/repos/repo_edit_settings.html:106
 msgid "Enable lock-by-pulling on repository."
-msgstr "Уключыць аўтаблакоўку для рэпазітара."
+msgstr "Уключыць аўтаблакаванне для рэпазітара."
 
 #: kallithea/templates/admin/gists/edit.html:5
 #: kallithea/templates/admin/gists/edit.html:18
 msgid "Edit Gist"
-msgstr "Праўка gist-запісы"
+msgstr "Правіць gist-запіс"
 
 #: kallithea/templates/admin/gists/edit.html:36
 #, python-format
@@ -2785,7 +2760,7 @@
 #: kallithea/templates/admin/users/user_edit_api_keys.html:27
 #: kallithea/templates/admin/users/user_edit_api_keys.html:32
 msgid "Expires"
-msgstr "Мінае"
+msgstr ""
 
 #: kallithea/templates/admin/gists/edit.html:61
 #: kallithea/templates/admin/gists/index.html:57
@@ -2794,16 +2769,15 @@
 #: kallithea/templates/admin/my_account/my_account_api_keys.html:27
 #: kallithea/templates/admin/users/user_edit_api_keys.html:8
 #: kallithea/templates/admin/users/user_edit_api_keys.html:27
-#, fuzzy
 msgid "Never"
-msgstr "ніколі"
-
-#: kallithea/templates/admin/gists/edit.html:145
+msgstr "Ніколі"
+
+#: kallithea/templates/admin/gists/edit.html:146
 msgid "Update Gist"
 msgstr "Абнавіць"
 
-#: kallithea/templates/admin/gists/edit.html:146
-#: kallithea/templates/changeset/changeset_file_comment.html:81
+#: kallithea/templates/admin/gists/edit.html:147
+#: kallithea/templates/changeset/changeset_file_comment.html:105
 msgid "Cancel"
 msgstr "Адмена"
 
@@ -2811,13 +2785,13 @@
 #: kallithea/templates/admin/gists/index.html:16
 #, python-format
 msgid "Private Gists for User %s"
-msgstr "Прыватная gist-запіс для карыстача %s"
+msgstr "Прыватны gist-запіс для карыстальніка %s"
 
 #: kallithea/templates/admin/gists/index.html:8
 #: kallithea/templates/admin/gists/index.html:18
 #, python-format
 msgid "Public Gists for User %s"
-msgstr "Публічная gist-запіс для карыстача %s"
+msgstr "Публічны gist-запіс для карыстальніка %s"
 
 #: kallithea/templates/admin/gists/index.html:10
 #: kallithea/templates/admin/gists/index.html:20
@@ -2826,14 +2800,14 @@
 
 #: kallithea/templates/admin/gists/index.html:37
 #: kallithea/templates/admin/gists/show.html:25
-#: kallithea/templates/base/base.html:237
+#: kallithea/templates/base/base.html:321
 msgid "Create New Gist"
-msgstr "Стварыць новую gist-запіс"
+msgstr "Стварыць новы gist-запіс"
 
 #: kallithea/templates/admin/gists/index.html:54
 #: kallithea/templates/data_table/_dt_elements.html:141
 msgid "Created"
-msgstr "Створана"
+msgstr "Створаны"
 
 #: kallithea/templates/admin/gists/index.html:74
 msgid "There are no gists yet"
@@ -2842,7 +2816,7 @@
 #: kallithea/templates/admin/gists/new.html:5
 #: kallithea/templates/admin/gists/new.html:18
 msgid "New Gist"
-msgstr ""
+msgstr "Новы gist-запіс"
 
 #: kallithea/templates/admin/gists/new.html:47
 msgid "name this file..."
@@ -2884,7 +2858,7 @@
 #: kallithea/templates/files/files_edit.html:68
 #: kallithea/templates/pullrequests/pullrequest.html:89
 msgid "Reset"
-msgstr "Скід"
+msgstr "Скінуць"
 
 #: kallithea/templates/admin/gists/show.html:5
 #: kallithea/templates/admin/gists/show.html:9
@@ -2914,7 +2888,8 @@
 #: kallithea/templates/admin/settings/settings_hooks.html:36
 #: kallithea/templates/admin/users/user_edit_emails.html:19
 #: kallithea/templates/admin/users/user_edit_ips.html:22
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+#: kallithea/templates/changeset/changeset_file_comment.html:95
 #: kallithea/templates/data_table/_dt_elements.html:129
 #: kallithea/templates/data_table/_dt_elements.html:157
 #: kallithea/templates/data_table/_dt_elements.html:173
@@ -2928,14 +2903,12 @@
 
 #: kallithea/templates/admin/gists/show.html:56
 msgid "Confirm to delete this Gist"
-msgstr "Пацвердзіце выдаленне гэтай gist-запісы"
+msgstr "Пацвердзіце выдаленне гэтага gist-запісу"
 
 #: kallithea/templates/admin/gists/show.html:63
 #: kallithea/templates/base/perms_summary.html:43
 #: kallithea/templates/base/perms_summary.html:79
 #: kallithea/templates/base/perms_summary.html:81
-#: kallithea/templates/changeset/changeset_file_comment.html:83
-#: kallithea/templates/changeset/changeset_file_comment.html:192
 #: kallithea/templates/data_table/_dt_elements.html:122
 #: kallithea/templates/data_table/_dt_elements.html:123
 #: kallithea/templates/data_table/_dt_elements.html:150
@@ -2962,13 +2935,12 @@
 msgstr "створана"
 
 #: kallithea/templates/admin/gists/show.html:86
-#: kallithea/templates/files/files_source.html:73
 msgid "Show as raw"
 msgstr "Паказаць толькі тэкст"
 
 #: kallithea/templates/admin/my_account/my_account.html:5
 #: kallithea/templates/admin/my_account/my_account.html:9
-#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:431
 msgid "My Account"
 msgstr "Мой Акаўнт"
 
@@ -2978,9 +2950,8 @@
 msgstr "Профіль"
 
 #: kallithea/templates/admin/my_account/my_account.html:36
-#, fuzzy
 msgid "Email Addresses"
-msgstr "Новы E-mail"
+msgstr "E-mail адрэсы"
 
 #: kallithea/templates/admin/my_account/my_account.html:38
 #: kallithea/templates/admin/users/user_edit.html:31
@@ -2988,9 +2959,8 @@
 msgstr "API-ключы"
 
 #: kallithea/templates/admin/my_account/my_account.html:39
-#, fuzzy
 msgid "Owned Repositories"
-msgstr "рэпазітары"
+msgstr "Мае рэпазітары"
 
 #: kallithea/templates/admin/my_account/my_account.html:40
 #: kallithea/templates/journal/journal.html:53
@@ -3002,9 +2972,8 @@
 #: kallithea/templates/admin/permissions/permissions.html:30
 #: kallithea/templates/admin/user_groups/user_group_edit.html:32
 #: kallithea/templates/admin/users/user_edit.html:34
-#, fuzzy
 msgid "Show Permissions"
-msgstr "Скапіяваць прывілеі"
+msgstr "Паказаць прывілеі"
 
 #: kallithea/templates/admin/my_account/my_account_api_keys.html:6
 #: kallithea/templates/admin/users/user_edit_api_keys.html:6
@@ -3015,7 +2984,7 @@
 #: kallithea/templates/admin/users/user_edit_api_keys.html:14
 #, fuzzy, python-format
 msgid "Confirm to reset this API key: %s"
-msgstr "Пацвердзіце скід гэтага API-ключа: %s"
+msgstr "Пацвердзіце скіданне гэтага API-ключа: %s"
 
 #: kallithea/templates/admin/my_account/my_account_api_keys.html:30
 #: kallithea/templates/admin/users/user_edit_api_keys.html:30
@@ -3025,15 +2994,14 @@
 
 #: kallithea/templates/admin/my_account/my_account_api_keys.html:40
 #: kallithea/templates/admin/users/user_edit_api_keys.html:40
-#, fuzzy, python-format
+#, python-format
 msgid "Confirm to remove this API key: %s"
 msgstr "Пацвердзіце выдаленне гэтага API-ключа: %s"
 
 #: kallithea/templates/admin/my_account/my_account_api_keys.html:42
 #: kallithea/templates/admin/users/user_edit_api_keys.html:42
-#, fuzzy
 msgid "Remove"
-msgstr "выдаліць"
+msgstr "Выдаліць"
 
 #: kallithea/templates/admin/my_account/my_account_api_keys.html:49
 #: kallithea/templates/admin/users/user_edit_api_keys.html:49
@@ -3043,9 +3011,8 @@
 
 #: kallithea/templates/admin/my_account/my_account_api_keys.html:61
 #: kallithea/templates/admin/users/user_edit_api_keys.html:61
-#, fuzzy
 msgid "New API key"
-msgstr "Ключ"
+msgstr "Новы API-ключ"
 
 #: kallithea/templates/admin/my_account/my_account_api_keys.html:69
 #: kallithea/templates/admin/my_account/my_account_emails.html:45
@@ -3067,7 +3034,7 @@
 #: kallithea/templates/admin/users/user_edit_emails.html:20
 #, python-format
 msgid "Confirm to delete this email: %s"
-msgstr "Пацвердзіце выдаленне E-mail: %s"
+msgstr "Пацвердзіце выдаленне e-mail: %s"
 
 #: kallithea/templates/admin/my_account/my_account_emails.html:26
 #: kallithea/templates/admin/users/user_edit_emails.html:26
@@ -3077,7 +3044,7 @@
 #: kallithea/templates/admin/my_account/my_account_emails.html:38
 #: kallithea/templates/admin/users/user_edit_emails.html:38
 msgid "New email address"
-msgstr "Новы E-mail"
+msgstr "Новы e-mail"
 
 #: kallithea/templates/admin/my_account/my_account_password.html:1
 msgid "Change Your Account Password"
@@ -3085,7 +3052,7 @@
 
 #: kallithea/templates/admin/my_account/my_account_password.html:10
 msgid "Current password"
-msgstr "Бягучы пароль"
+msgstr "Цяперашні пароль"
 
 #: kallithea/templates/admin/my_account/my_account_password.html:19
 #: kallithea/templates/admin/users/user_edit_profile.html:60
@@ -3103,7 +3070,7 @@
 
 #: kallithea/templates/admin/my_account/my_account_profile.html:11
 msgid "Change your avatar at"
-msgstr "Зменіце аватар праз сайт"
+msgstr "Змяніць аватар можна праз"
 
 #: kallithea/templates/admin/my_account/my_account_profile.html:12
 #: kallithea/templates/admin/users/user_edit_profile.html:9
@@ -3113,17 +3080,16 @@
 #: kallithea/templates/admin/my_account/my_account_profile.html:14
 #: kallithea/templates/admin/users/user_edit_profile.html:11
 msgid "Avatars are disabled"
-msgstr "Аватары адключаны"
+msgstr "Аватары адключаныя"
 
 #: kallithea/templates/admin/my_account/my_account_profile.html:15
 msgid "Missing email, please update your user email address."
-msgstr "Не паказаны email. Калі ласка, абновіце ваш email."
+msgstr "Няма email адрэсы, калі ласка, абнавіце ваш email."
 
 #: kallithea/templates/admin/my_account/my_account_profile.html:16
 #: kallithea/templates/admin/users/user_edit_profile.html:15
-#, fuzzy
 msgid "Current IP"
-msgstr "бягучы IP-адрас"
+msgstr "Цяперашні IP-адрас"
 
 #: kallithea/templates/admin/my_account/my_account_repos.html:1
 msgid "Repositories You Own"
@@ -3138,7 +3104,7 @@
 #: kallithea/templates/journal/journal.html:291
 #: kallithea/templates/tags/tags.html:81
 msgid "No records found."
-msgstr "Запісы не знойдзены."
+msgstr "Запісы не знойдзеныя."
 
 #: kallithea/templates/admin/my_account/my_account_watched.html:1
 msgid "Repositories You are Watching"
@@ -3151,20 +3117,20 @@
 
 #: kallithea/templates/admin/notifications/notifications.html:24
 msgid "All"
-msgstr "Усё"
+msgstr "Усе"
 
 #: kallithea/templates/admin/notifications/notifications.html:25
 msgid "Comments"
 msgstr "Каментары"
 
 #: kallithea/templates/admin/notifications/notifications.html:26
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 msgid "Pull Requests"
 msgstr "Pull-запыты"
 
 #: kallithea/templates/admin/notifications/notifications.html:30
 msgid "Mark All Read"
-msgstr "Адзначыць усё як прачытаныя"
+msgstr "Адзначыць усе як прачытаныя"
 
 #: kallithea/templates/admin/notifications/notifications_data.html:40
 msgid "No notifications here yet"
@@ -3176,7 +3142,7 @@
 msgstr "Паказаць апавяшчэнне"
 
 #: kallithea/templates/admin/notifications/show_notification.html:9
-#: kallithea/templates/base/base.html:342
+#: kallithea/templates/base/base.html:430
 msgid "Notifications"
 msgstr "Апавяшчэнні"
 
@@ -3213,13 +3179,12 @@
 "permission, note that all custom default permission on repositories will "
 "be lost"
 msgstr ""
-"Абраныя прывілеі будуць усталяваны па змаўчанні для кожнага рэпазітара. "
-"Улічыце, што раней усталяваныя прывілеі па змаўчанні будуць скінуты"
+"Выбраныя прывілеі будуць усталяваныя па змоўчанні для кожнага рэпазітара."
+" Улічыце, што раней усталяваныя прывілеі па змоўчанні будуць скінутыя"
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:26
-#, fuzzy
 msgid "Apply to all existing repositories"
-msgstr "Імпартаваць існы рэпазітар?"
+msgstr ""
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:27
 msgid "Permissions for the Default user on new repositories."
@@ -3239,14 +3204,13 @@
 "permission, note that all custom default permission on repository groups "
 "will be lost"
 msgstr ""
-"Абраныя прывілеі будуць усталяваны па змаўчанні для кожнай групы "
-"рэпазітароў. Улічыце, што раней усталяваныя прывілеі па змаўчанні для "
-"груп рэпазітароў будуць скінуты"
+"Выбраныя прывілеі будуць усталяваныя па змоўчанні для кожнай групы "
+"рэпазітароў. Улічыце, што раней усталяваныя прывілеі па змоўчанні для "
+"груп рэпазітароў будуць скінутыя"
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:40
-#, fuzzy
 msgid "Apply to all existing repository groups"
-msgstr "Імпартаваць існы рэпазітар?"
+msgstr ""
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:41
 msgid "Permissions for the Default user on new repository groups."
@@ -3255,18 +3219,17 @@
 #: kallithea/templates/admin/permissions/permissions_globals.html:46
 #: kallithea/templates/data_table/_dt_elements.html:209
 msgid "User group"
-msgstr "Група карыстачоў"
+msgstr "Група карыстальнікаў"
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:53
-#, fuzzy
 msgid ""
 "All default permissions on each user group will be reset to chosen "
 "permission, note that all custom default permission on user groups will "
 "be lost"
 msgstr ""
-"Абраныя прывілеі будуць усталяваны па змаўчанні для кожнай групы "
-"карыстачоў. Улічыце, што раней усталяваныя прывілеі па змаўчанні для груп"
-" карыстачоў будуць скінуты"
+"Выбраныя прывілеі будуць усталяваныя па змоўчанні для кожнай групы "
+"карыстальнікаў. Улічыце, што раней усталяваныя прывілеі па змоўчанні для "
+"груп карыстальнікаў будуць скінутыя"
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:54
 msgid "Apply to all existing user groups"
@@ -3277,9 +3240,8 @@
 msgstr ""
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:60
-#, fuzzy
 msgid "Top level repository creation"
-msgstr "Стварэнне рэпазітара"
+msgstr ""
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:64
 msgid "Enable this to allow non-admins to create repositories at the top level."
@@ -3304,7 +3266,7 @@
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:79
 msgid "User group creation"
-msgstr "Стварэнне груп карыстачоў"
+msgstr "Стварэнне груп карыстальнікаў"
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:83
 msgid "Enable this to allow non-admins to create user groups."
@@ -3328,7 +3290,7 @@
 
 #: kallithea/templates/admin/permissions/permissions_ips.html:13
 #: kallithea/templates/admin/users/user_edit_ips.html:23
-#, fuzzy, python-format
+#, python-format
 msgid "Confirm to delete this IP address: %s"
 msgstr "Пацвердзіце выдаленне IP %s"
 
@@ -3386,7 +3348,7 @@
 #: kallithea/templates/admin/repos/repo_edit.html:40
 #: kallithea/templates/admin/settings/settings.html:11
 #: kallithea/templates/admin/user_groups/user_group_edit.html:29
-#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:151
+#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:148
 #: kallithea/templates/data_table/_dt_elements.html:45
 #: kallithea/templates/data_table/_dt_elements.html:49
 msgid "Settings"
@@ -3445,9 +3407,8 @@
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:11
 #: kallithea/templates/admin/repos/repo_edit_permissions.html:12
 #: kallithea/templates/admin/user_groups/user_group_edit_perms.html:11
-#, fuzzy
 msgid "User/User Group"
-msgstr "групы карыстальнікаў"
+msgstr "Карыстальнік/група карыстальнікаў"
 
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:28
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:45
@@ -3455,9 +3416,8 @@
 #: kallithea/templates/admin/repos/repo_edit_permissions.html:37
 #: kallithea/templates/admin/user_groups/user_group_edit_perms.html:28
 #: kallithea/templates/admin/user_groups/user_group_edit_perms.html:45
-#, fuzzy
 msgid "Default"
-msgstr "па змаўчанні"
+msgstr "Па змоўчанні"
 
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:34
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:71
@@ -3465,9 +3425,8 @@
 #: kallithea/templates/admin/repos/repo_edit_permissions.html:68
 #: kallithea/templates/admin/user_groups/user_group_edit_perms.html:34
 #: kallithea/templates/admin/user_groups/user_group_edit_perms.html:71
-#, fuzzy
 msgid "Revoke"
-msgstr "адклікаць"
+msgstr "Адклікаць"
 
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:97
 #: kallithea/templates/admin/repos/repo_edit_permissions.html:94
@@ -3476,9 +3435,8 @@
 msgstr "Дадаць новы"
 
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:103
-#, fuzzy
 msgid "Apply to children"
-msgstr "дастасаваць да даччыным"
+msgstr ""
 
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:107
 msgid "Both"
@@ -3504,7 +3462,7 @@
 
 #: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:53
 msgid "Confirm to delete this group"
-msgstr "Пацвердзіце выдаленне гэтай групы карыстачоў"
+msgstr "Пацвердзіце выдаленне гэтай групы карыстальнікаў"
 
 #: kallithea/templates/admin/repo_groups/repo_group_show.html:4
 #, python-format
@@ -3513,7 +3471,7 @@
 
 #: kallithea/templates/admin/repo_groups/repo_group_show.html:9
 msgid "Home"
-msgstr "Дахаты"
+msgstr "Дамоў"
 
 #: kallithea/templates/admin/repo_groups/repo_group_show.html:13
 msgid "with"
@@ -3528,9 +3486,8 @@
 msgstr "Лік рэпазітароў верхняга ўзроўня"
 
 #: kallithea/templates/admin/repos/repo_add_base.html:17
-#, fuzzy
 msgid "Clone remote repository"
-msgstr "[створаны] рэпазітар"
+msgstr ""
 
 #: kallithea/templates/admin/repos/repo_add_base.html:22
 msgid ""
@@ -3626,19 +3583,19 @@
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:8
 #: kallithea/templates/admin/repos/repo_edit_fork.html:9
 msgid "Manually set this repository as a fork of another from the list."
-msgstr "Уручную зрабіць гэты рэпазітар форкам абранага са спісу."
+msgstr "Уручную зрабіць гэты рэпазітар форкам выбранага са спісу."
 
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:22
 msgid "Public Journal Visibility"
-msgstr "Доступ да публічнага часопіса"
+msgstr "Доступ да публічнага журналу"
 
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:29
 msgid "Remove from public journal"
-msgstr "Выдаліць з агульнадаступнага часопіса"
+msgstr "Выдаліць з агульнадаступнага журналу"
 
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:34
 msgid "Add to Public Journal"
-msgstr "Дадаць у публічны часопіс"
+msgstr "Дадаць у публічны журнал"
 
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:40
 msgid ""
@@ -3646,7 +3603,7 @@
 "public journal."
 msgstr ""
 "Усе выконваемыя з гэтым рэпазітаром дзеянні будуць адлюстроўвацца ў "
-"публічным часопісе."
+"публічным журнал."
 
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:46
 msgid "Change Locking"
@@ -3654,12 +3611,17 @@
 
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:52
 msgid "Confirm to unlock repository."
-msgstr "Пацвердзіце здыманне блакавання з рэпазітара."
+msgstr "Пацвердзіце разблакаванне рэпазітара."
 
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:54
 msgid "Unlock Repository"
 msgstr "Разблакаваць рэпазітар"
 
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:56
+#, python-format
+msgid "Locked by %s on %s"
+msgstr "Заблакавана %s %s"
+
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:60
 msgid "Confirm to lock repository."
 msgstr "Пацвердзіце блакаванне рэпазітара."
@@ -3696,15 +3658,15 @@
 msgid_plural "This repository has %s forks"
 msgstr[0] "Дадзены рэпазітар мае %s копію"
 msgstr[1] "Дадзены рэпазітар мае %s копіі"
-msgstr[2] "Дадзены рэпазітар мае %s дзід"
+msgstr[2] "Дадзены рэпазітар мае %s копій"
 
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:85
 msgid "Detach forks"
-msgstr "Адлучыць fork'і"
+msgstr "Адлучыць форкі"
 
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:86
 msgid "Delete forks"
-msgstr "Выдаліць fork'і"
+msgstr "Выдаліць форкі"
 
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:90
 msgid ""
@@ -3717,15 +3679,11 @@
 msgid "Invalidate Repository Cache"
 msgstr "Скінуць кэш рэпазітара"
 
-#: kallithea/templates/admin/repos/repo_edit_caches.html:4
-msgid "Confirm to invalidate repository cache."
-msgstr "Пацвердзіце скід кэша."
-
 #: kallithea/templates/admin/repos/repo_edit_caches.html:7
 msgid ""
 "Manually invalidate cache for this repository. On first access, the "
 "repository will be cached again."
-msgstr "Ручны скід кэша рэпазітара. Пры першым доступе кэш адновіцца."
+msgstr "Ручное скіданне кэша рэпазітара. Пры першым доступе кэш адновіцца."
 
 #: kallithea/templates/admin/repos/repo_edit_caches.html:12
 msgid "List of Cached Values"
@@ -3781,36 +3739,31 @@
 
 #: kallithea/templates/admin/repos/repo_edit_fields.html:66
 msgid "Extra fields are disabled."
-msgstr "Дадатковыя палі адключаны."
+msgstr "Дадатковыя палі адключаныя."
 
 #: kallithea/templates/admin/repos/repo_edit_permissions.html:21
-#, fuzzy
 msgid "Private Repository"
-msgstr "прыватны рэпазітар"
+msgstr "Прыватны рэпазітар"
 
 #: kallithea/templates/admin/repos/repo_edit_remote.html:3
-#, fuzzy
 msgid "Remote repository URL"
-msgstr "Рэпазітар %s створаны"
+msgstr "URL аддаленага рэпазітара"
 
 #: kallithea/templates/admin/repos/repo_edit_remote.html:9
-#, fuzzy
 msgid "Pull Changes from Remote Repository"
-msgstr "[занесены змены з выдаленага рэпазітара] у рэпазітар"
+msgstr "Занесці змены з аддаленага рэпазітара"
 
 #: kallithea/templates/admin/repos/repo_edit_remote.html:11
-#, fuzzy
 msgid "Confirm to pull changes from remote repository."
-msgstr "Пацвердзіце спампоўку змен."
+msgstr "Пацвердзіце спампоўку змен з аддаленага рэпазітара."
 
 #: kallithea/templates/admin/repos/repo_edit_remote.html:17
 msgid "This repository does not have a remote repository URL."
 msgstr ""
 
 #: kallithea/templates/admin/repos/repo_edit_settings.html:11
-#, fuzzy
 msgid "Permanent Repository ID"
-msgstr "прыватны рэпазітар"
+msgstr "Пастаяннае ШВ рэпазітара"
 
 #: kallithea/templates/admin/repos/repo_edit_settings.html:11
 msgid "What is that?"
@@ -3831,14 +3784,12 @@
 msgstr ""
 
 #: kallithea/templates/admin/repos/repo_edit_settings.html:21
-#, fuzzy
 msgid "Remote repository"
-msgstr "[створаны] рэпазітар"
+msgstr "Аддалены рэпазітар"
 
 #: kallithea/templates/admin/repos/repo_edit_settings.html:25
-#, fuzzy
 msgid "Repository URL"
-msgstr "Рэпазітар"
+msgstr "URL рэпазітара"
 
 #: kallithea/templates/admin/repos/repo_edit_settings.html:29
 msgid ""
@@ -3848,9 +3799,7 @@
 
 #: kallithea/templates/admin/repos/repo_edit_settings.html:48
 msgid "Default revision for files page, downloads, whoosh and readme"
-msgstr ""
-"Рэвізія па змаўчанні, з якой будзе вырабляцца выгрузка файлаў пры "
-"спампоўцы"
+msgstr "Рэвізія па змоўчанні, з якой будзе рабіцца выгрузка файлаў пры спампоўцы"
 
 #: kallithea/templates/admin/repos/repo_edit_settings.html:58
 msgid "Change owner of this repository."
@@ -3870,7 +3819,7 @@
 
 #: kallithea/templates/admin/repos/repo_edit_statistics.html:10
 msgid "Confirm to remove current statistics."
-msgstr "Пацвердзіце скід статыстыкі."
+msgstr "Пацвердзіце скіданне статыстыкі."
 
 #: kallithea/templates/admin/repos/repos.html:5
 msgid "Repositories Administration"
@@ -3975,7 +3924,7 @@
 
 #: kallithea/templates/admin/settings/settings_hooks.html:19
 msgid "Custom Hooks"
-msgstr "Карыстацкія хуки"
+msgstr "Карыстальніцкія хукі"
 
 #: kallithea/templates/admin/settings/settings_hooks.html:67
 msgid "Failed to remove hook"
@@ -3986,9 +3935,8 @@
 msgstr "Опцыі перасканіравання"
 
 #: kallithea/templates/admin/settings/settings_mapping.html:11
-#, fuzzy
 msgid "Delete records of missing repositories"
-msgstr "Пошук па рэпазітарах"
+msgstr "Сцерці запісы пра выдаленыя рэпазітары"
 
 #: kallithea/templates/admin/settings/settings_mapping.html:13
 msgid ""
@@ -4049,12 +3997,11 @@
 
 #: kallithea/templates/admin/settings/settings_system.html:4
 msgid "Kallithea version"
-msgstr ""
+msgstr "Версія Kallithea"
 
 #: kallithea/templates/admin/settings/settings_system.html:4
-#, fuzzy
 msgid "Check for updates"
-msgstr "праверыць наяўнасць абнаўленняў"
+msgstr "Праверыць наяўнасць абнаўленняў"
 
 #: kallithea/templates/admin/settings/settings_system.html:5
 msgid "Kallithea configuration file"
@@ -4112,11 +4059,11 @@
 
 #: kallithea/templates/admin/settings/settings_vcs.html:28
 msgid "Log user push commands"
-msgstr "Лагіраваць карыстацкія каманды адпраўкі"
+msgstr "Лагаваць карыстацкія каманды адпраўкі"
 
 #: kallithea/templates/admin/settings/settings_vcs.html:32
 msgid "Log user pull commands"
-msgstr "Лагіраваць карыстацкія каманды атрымання"
+msgstr "Лагаваць карыстацкія каманды атрымання"
 
 #: kallithea/templates/admin/settings/settings_vcs.html:36
 msgid "Update repository after push (hg update)"
@@ -4256,9 +4203,8 @@
 msgstr "Паказваць абразкі публічных рэпазітароў."
 
 #: kallithea/templates/admin/settings/settings_visual.html:92
-#, fuzzy
 msgid "Meta Tagging"
-msgstr "Метатэгіраванне"
+msgstr "Метатэгаванне"
 
 #: kallithea/templates/admin/settings/settings_visual.html:97
 msgid "Stylify recognised meta tags:"
@@ -4272,7 +4218,7 @@
 
 #: kallithea/templates/admin/user_groups/user_group_add.html:5
 msgid "Add user group"
-msgstr "Дадаць групу карыстачоў"
+msgstr "Дадаць групу карыстальнікаў"
 
 #: kallithea/templates/admin/user_groups/user_group_add.html:10
 #: kallithea/templates/admin/user_groups/user_group_edit.html:11
@@ -4297,9 +4243,8 @@
 msgstr ""
 
 #: kallithea/templates/admin/user_groups/user_group_edit.html:33
-#, fuzzy
 msgid "Show Members"
-msgstr "удзельнікі"
+msgstr "Паказаць удзельнікаў"
 
 #: kallithea/templates/admin/user_groups/user_group_edit_advanced.html:1
 #, python-format
@@ -4316,7 +4261,7 @@
 #: kallithea/templates/data_table/_dt_elements.html:174
 #, python-format
 msgid "Confirm to delete this user group: %s"
-msgstr "Пацвердзіце выдаленне наступнай групы карыстачоў: %s"
+msgstr "Пацвердзіце выдаленне наступнай групы карыстальнікаў: %s"
 
 #: kallithea/templates/admin/user_groups/user_group_edit_advanced.html:21
 msgid "Delete this user group"
@@ -4336,23 +4281,23 @@
 
 #: kallithea/templates/admin/user_groups/user_groups.html:5
 msgid "User Groups Administration"
-msgstr "Адміністраванне груп карыстачоў"
+msgstr "Адміністраванне груп карыстальнікаў"
 
 #: kallithea/templates/admin/users/user_add.html:5
 msgid "Add user"
-msgstr "Дадаць карыстача"
+msgstr "Дадаць карыстальніка"
 
 #: kallithea/templates/admin/users/user_add.html:10
 #: kallithea/templates/admin/users/user_edit.html:11
 #: kallithea/templates/admin/users/users.html:10
 #: kallithea/templates/base/base.html:62
 msgid "Users"
-msgstr "Карыстачы"
+msgstr "Карыстальнікі"
 
 #: kallithea/templates/admin/users/user_add.html:12
 #: kallithea/templates/admin/users/users.html:24
 msgid "Add User"
-msgstr "Дадаць карыстача"
+msgstr "Дадаць карыстальніка"
 
 #: kallithea/templates/admin/users/user_add.html:50
 msgid "Password confirmation"
@@ -4390,7 +4335,7 @@
 #: kallithea/templates/data_table/_dt_elements.html:158
 #, python-format
 msgid "Confirm to delete this user: %s"
-msgstr "Пацвердзіце выдаленне карыстача %s"
+msgstr "Пацвердзіце выдаленне карыстальніка %s"
 
 #: kallithea/templates/admin/users/user_edit_advanced.html:23
 msgid "Delete this user"
@@ -4419,7 +4364,7 @@
 
 #: kallithea/templates/admin/users/users.html:5
 msgid "Users Administration"
-msgstr "Адміністраванне карыстачоў"
+msgstr "Адміністраванне карыстальнікаў"
 
 #: kallithea/templates/admin/users/users.html:56
 msgid "Auth Type"
@@ -4468,21 +4413,17 @@
 msgid "Files"
 msgstr "Файлы"
 
-#: kallithea/templates/base/base.html:138
-msgid "Switch To"
-msgstr "Пераключыцца на"
-
-#: kallithea/templates/base/base.html:145
-#: kallithea/templates/base/base.html:147
+#: kallithea/templates/base/base.html:142
+#: kallithea/templates/base/base.html:144
 msgid "Options"
 msgstr "Опцыі"
 
-#: kallithea/templates/base/base.html:155
+#: kallithea/templates/base/base.html:152
 #: kallithea/templates/forks/forks_data.html:21
 msgid "Compare Fork"
 msgstr "Параўнаць форк"
 
-#: kallithea/templates/base/base.html:157
+#: kallithea/templates/base/base.html:154
 #: kallithea/templates/bookmarks/bookmarks.html:56
 #: kallithea/templates/bookmarks/bookmarks_data.html:13
 #: kallithea/templates/branches/branches.html:56
@@ -4492,118 +4433,122 @@
 msgid "Compare"
 msgstr "Параўнаць"
 
-#: kallithea/templates/base/base.html:159
-#: kallithea/templates/base/base.html:247
+#: kallithea/templates/base/base.html:156
+#: kallithea/templates/base/base.html:331
 #: kallithea/templates/search/search.html:14
 #: kallithea/templates/search/search.html:54
 msgid "Search"
 msgstr "Пошук"
 
-#: kallithea/templates/base/base.html:163
+#: kallithea/templates/base/base.html:160
 msgid "Unlock"
 msgstr "Разблакаваць"
 
-#: kallithea/templates/base/base.html:165
+#: kallithea/templates/base/base.html:162
 msgid "Lock"
 msgstr "Заблакаваць"
 
-#: kallithea/templates/base/base.html:173
+#: kallithea/templates/base/base.html:170
 msgid "Follow"
 msgstr "Назіраць"
 
+#: kallithea/templates/base/base.html:171
+msgid "Unfollow"
+msgstr "Не назіраць"
+
 #: kallithea/templates/base/base.html:174
-msgid "Unfollow"
-msgstr "Не назіраць"
-
-#: kallithea/templates/base/base.html:177
 #: kallithea/templates/data_table/_dt_elements.html:37
 #: kallithea/templates/data_table/_dt_elements.html:41
 #: kallithea/templates/forks/fork.html:9
 msgid "Fork"
 msgstr "Форк"
 
-#: kallithea/templates/base/base.html:178
+#: kallithea/templates/base/base.html:175
 #: kallithea/templates/pullrequests/pullrequest.html:88
 msgid "Create Pull Request"
-msgstr "Стварыць Pull запыт"
-
-#: kallithea/templates/base/base.html:183
+msgstr "Стварыць pull-запыт"
+
+#: kallithea/templates/base/base.html:180
 #, python-format
 msgid "Show Pull Requests for %s"
 msgstr "Паказаць pull-запыты для %s"
 
-#: kallithea/templates/base/base.html:221
+#: kallithea/templates/base/base.html:193
+msgid "Switch To"
+msgstr "Пераключыцца на"
+
+#: kallithea/templates/base/base.html:203
+#: kallithea/templates/base/base.html:485
+msgid "No matches found"
+msgstr "Супадзенняў не знойдзена"
+
+#: kallithea/templates/base/base.html:305
 msgid "Show recent activity"
 msgstr "Паказаць апошнюю актыўнасць"
 
-#: kallithea/templates/base/base.html:227
-#: kallithea/templates/base/base.html:228
+#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:312
 msgid "Public journal"
-msgstr "Агульнадаступны часопіс"
-
-#: kallithea/templates/base/base.html:233
+msgstr "Агульнадаступны журнал"
+
+#: kallithea/templates/base/base.html:317
 msgid "Show public gists"
 msgstr "Паказаць публічныя запісы"
 
-#: kallithea/templates/base/base.html:234
+#: kallithea/templates/base/base.html:318
 msgid "Gists"
 msgstr "Gist"
 
-#: kallithea/templates/base/base.html:238
+#: kallithea/templates/base/base.html:322
 msgid "All Public Gists"
 msgstr "Усе публічныя Gist-запісы"
 
-#: kallithea/templates/base/base.html:240
+#: kallithea/templates/base/base.html:324
 msgid "My Public Gists"
 msgstr "Мае публічныя Gist-запісы"
 
-#: kallithea/templates/base/base.html:241
+#: kallithea/templates/base/base.html:325
 msgid "My Private Gists"
 msgstr "Мае прыватныя Gist-запісы"
 
-#: kallithea/templates/base/base.html:246
+#: kallithea/templates/base/base.html:330
 msgid "Search in repositories"
 msgstr "Пошук па рэпазітарах"
 
-#: kallithea/templates/base/base.html:269
-#: kallithea/templates/base/base.html:270
+#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:354
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:6
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:10
 msgid "My Pull Requests"
-msgstr "Мае Pull-запыты"
-
-#: kallithea/templates/base/base.html:289
+msgstr "Мае pull-запыты"
+
+#: kallithea/templates/base/base.html:377
 msgid "Not Logged In"
 msgstr "Не аўтарызаваны"
 
-#: kallithea/templates/base/base.html:296
+#: kallithea/templates/base/base.html:384
 msgid "Login to Your Account"
 msgstr "Аўтарызавацца"
 
-#: kallithea/templates/base/base.html:319
+#: kallithea/templates/base/base.html:407
 msgid "Forgot password ?"
-msgstr "Забыліся пароль?"
-
-#: kallithea/templates/base/base.html:346
+msgstr "Забыліся на пароль?"
+
+#: kallithea/templates/base/base.html:434
 msgid "Log Out"
-msgstr "Выйсце"
-
-#: kallithea/templates/base/base.html:395
-msgid "No matches found"
-msgstr "Супадзенняў не знойдзена"
-
-#: kallithea/templates/base/base.html:524
+msgstr "Выйсці"
+
+#: kallithea/templates/base/base.html:615
 msgid "Keyboard shortcuts"
 msgstr "Гарачыя клавішы"
 
-#: kallithea/templates/base/base.html:533
+#: kallithea/templates/base/base.html:624
 msgid "Site-wide shortcuts"
 msgstr ""
 
 #: kallithea/templates/base/default_perms_box.html:14
-#, fuzzy
 msgid "Inherit defaults"
-msgstr "Значэнні па змаўчанні"
+msgstr "Ужываць значэнні па змоўчанні"
 
 #: kallithea/templates/base/default_perms_box.html:19
 #, python-format
@@ -4618,15 +4563,15 @@
 
 #: kallithea/templates/base/default_perms_box.html:33
 msgid "Select this option to allow repository creation for this user"
-msgstr "Опцыя дазваляе карыстачу ствараць рэпазітары"
+msgstr "Опцыя дазваляе карыстальніку ствараць рэпазітары"
 
 #: kallithea/templates/base/default_perms_box.html:40
 msgid "Create user groups"
-msgstr "Ствараць групы карыстачоў"
+msgstr "Ствараць групы карыстальнікаў"
 
 #: kallithea/templates/base/default_perms_box.html:45
 msgid "Select this option to allow user group creation for this user"
-msgstr "Опцыя дазваляе карыстачу ствараць групы карыстачоў"
+msgstr "Опцыя дазваляе карыстальніку ствараць групы карыстальнікаў"
 
 #: kallithea/templates/base/default_perms_box.html:52
 msgid "Fork repositories"
@@ -4635,7 +4580,7 @@
 #: kallithea/templates/base/default_perms_box.html:57
 msgid "Select this option to allow repository forking for this user"
 msgstr ""
-"Абярыце гэту опцыю каб дазволіць дадзенаму карыстачу ствараць fork'і "
+"Абярыце гэту опцыю каб дазволіць дадзенаму карыстальніку ствараць форкі "
 "рэпазітароў"
 
 #: kallithea/templates/base/perms_summary.html:13
@@ -4645,7 +4590,7 @@
 
 #: kallithea/templates/base/perms_summary.html:22
 msgid "No permissions defined yet"
-msgstr "Прывілеі яшчэ не прызначаны"
+msgstr "Прывілеі яшчэ не прызначаныя"
 
 #: kallithea/templates/base/perms_summary.html:30
 #: kallithea/templates/base/perms_summary.html:54
@@ -4699,20 +4644,16 @@
 msgstr "Няма супадзенняў"
 
 #: kallithea/templates/base/root.html:31
-#, fuzzy
-#| msgid "on pull request"
 msgid "Open New Pull Request from {0}"
-msgstr "Каментар у pull-запыце"
+msgstr "Стварыць новы pull-запыт з {0}"
 
 #: kallithea/templates/base/root.html:32
 msgid "Open New Pull Request for {0} &rarr; {1}"
-msgstr ""
+msgstr "Стварыць новы pull-запыт для {0} &rarr; {1}"
 
 #: kallithea/templates/base/root.html:33
-#, fuzzy
-#| msgid "Show Selected Changesets __S &rarr; __E"
 msgid "Show Selected Changesets {0} &rarr; {1}"
-msgstr "Паказаць абраныя наборы змен: __S &rarr; __E"
+msgstr "Паказаць выбраныя наборы змен: {0} &rarr; {1}"
 
 #: kallithea/templates/base/root.html:34
 msgid "Selection Link"
@@ -4720,12 +4661,13 @@
 
 #: kallithea/templates/base/root.html:35
 #: kallithea/templates/changeset/diff_block.html:8
+#: kallithea/templates/changeset/diff_block.html:21
 msgid "Collapse Diff"
 msgstr "Згарнуць параўнанне"
 
 #: kallithea/templates/base/root.html:36
 msgid "Expand Diff"
-msgstr "Расчыніць параўнанне"
+msgstr "Разгарнуць параўнанне"
 
 #: kallithea/templates/base/root.html:37
 msgid "Failed to revoke permission"
@@ -4745,7 +4687,7 @@
 
 #: kallithea/templates/base/root.html:42
 msgid "Specify changeset"
-msgstr "Абраць набор змен"
+msgstr "Выбраць набор змен"
 
 #: kallithea/templates/bookmarks/bookmarks.html:5
 #, python-format
@@ -4754,7 +4696,7 @@
 
 #: kallithea/templates/bookmarks/bookmarks.html:26
 msgid "Compare Bookmarks"
-msgstr ""
+msgstr "Параўнаць закладкі"
 
 #: kallithea/templates/bookmarks/bookmarks.html:53
 #: kallithea/templates/bookmarks/bookmarks_data.html:10
@@ -4782,11 +4724,11 @@
 #: kallithea/templates/branches/branches.html:5
 #, python-format
 msgid "%s Branches"
-msgstr "Галінкі %s"
+msgstr "%s Галіны"
 
 #: kallithea/templates/branches/branches.html:26
 msgid "Compare Branches"
-msgstr ""
+msgstr "Параўнаць галіны"
 
 #: kallithea/templates/changelog/changelog.html:6
 #, python-format
@@ -4823,59 +4765,61 @@
 #: kallithea/templates/changelog/changelog.html:66
 #: kallithea/templates/files/files.html:29
 msgid "Branch filter:"
-msgstr "Адфільтраваць галінку:"
+msgstr "Адфільтраваць галіну:"
 
 #: kallithea/templates/changelog/changelog.html:92
 #: kallithea/templates/changelog/changelog_summary_data.html:20
 #, fuzzy, python-format
 msgid ""
-"Changeset status: %s\n"
+"Changeset status: %s by %s\n"
 "Click to open associated pull request %s"
 msgstr ""
-"Статут набору змен: %s?\n"
-"Клікніце, каб перайсці да адпаведнага pull-request'у #%s"
+"Статус набору змен: %s?\n"
+"Клікніце, каб перайсці да адпаведнага pull-запыту %s"
 
 #: kallithea/templates/changelog/changelog.html:96
-#: kallithea/templates/compare/compare_cs.html:24
-#, python-format
-msgid "Changeset status: %s"
-msgstr "Статут набору змен: %s"
-
-#: kallithea/templates/changelog/changelog.html:115
+#: kallithea/templates/changelog/changelog_summary_data.html:24
+#, fuzzy, python-format
+msgid "Changeset status: %s by %s"
+msgstr "Статус набору змен: %s"
+
+#: kallithea/templates/changelog/changelog.html:116
 #: kallithea/templates/compare/compare_cs.html:63
 msgid "Expand commit message"
-msgstr ""
-
-#: kallithea/templates/changelog/changelog.html:124
+msgstr "Разгарнуць паведамленне"
+
+#: kallithea/templates/changelog/changelog.html:125
 #: kallithea/templates/compare/compare_cs.html:30
 msgid "Changeset has comments"
 msgstr "Каментары адсутнічаюць"
 
-#: kallithea/templates/changelog/changelog.html:134
-#: kallithea/templates/changelog/changelog_summary_data.html:54
+#: kallithea/templates/changelog/changelog.html:135
+#: kallithea/templates/changelog/changelog_summary_data.html:57
 #: kallithea/templates/changeset/changeset.html:94
 #: kallithea/templates/changeset/changeset_range.html:92
 #, python-format
 msgid "Bookmark %s"
 msgstr "Закладка %s"
 
-#: kallithea/templates/changelog/changelog.html:140
-#: kallithea/templates/changelog/changelog_summary_data.html:60
+#: kallithea/templates/changelog/changelog.html:141
+#: kallithea/templates/changelog/changelog_summary_data.html:63
 #: kallithea/templates/changeset/changeset.html:101
 #: kallithea/templates/changeset/changeset_range.html:98
+#: kallithea/templates/compare/compare_cs.html:69
+#: kallithea/templates/pullrequests/pullrequest_show.html:203
 #, python-format
 msgid "Tag %s"
-msgstr "Пазнака %s"
-
-#: kallithea/templates/changelog/changelog.html:145
-#: kallithea/templates/changelog/changelog_summary_data.html:65
+msgstr "Тэг %s"
+
+#: kallithea/templates/changelog/changelog.html:146
+#: kallithea/templates/changelog/changelog_summary_data.html:68
 #: kallithea/templates/changeset/changeset.html:106
 #: kallithea/templates/changeset/changeset_range.html:102
 #, python-format
 msgid "Branch %s"
-msgstr "Галінка %s"
-
-#: kallithea/templates/changelog/changelog.html:310
+msgstr "Галіна %s"
+
+#: kallithea/templates/changelog/changelog.html:311
 msgid "There are no changes yet"
 msgstr "Змен яшчэ няма"
 
@@ -4891,7 +4835,7 @@
 
 #: kallithea/templates/changelog/changelog_details.html:6
 #: kallithea/templates/changeset/changeset.html:79
-#: kallithea/templates/changeset/diff_block.html:79
+#: kallithea/templates/changeset/diff_block.html:47
 msgid "Added"
 msgstr "Дададзена"
 
@@ -4921,22 +4865,21 @@
 msgid "Refs"
 msgstr "Спасылкі"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:81
+#: kallithea/templates/changelog/changelog_summary_data.html:84
 msgid "Add or upload files directly via Kallithea"
 msgstr "Дадаць ці загрузіць файлы праз Kallithea"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:84
+#: kallithea/templates/changelog/changelog_summary_data.html:87
 #: kallithea/templates/files/files_add.html:21
 #: kallithea/templates/files/files_ypjax.html:9
 msgid "Add New File"
 msgstr "Дадаць новы файл"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:90
-#, fuzzy
+#: kallithea/templates/changelog/changelog_summary_data.html:93
 msgid "Push new repository"
 msgstr "Адправіць новы рэпазітар"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:98
+#: kallithea/templates/changelog/changelog_summary_data.html:101
 msgid "Existing repository?"
 msgstr "Існы рэпазітар?"
 
@@ -4954,32 +4897,31 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:50
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #: kallithea/templates/changeset/changeset_range.html:48
 msgid "Changeset status"
-msgstr "Статут змен"
+msgstr "Статус змен"
 
 #: kallithea/templates/changeset/changeset.html:54
-#: kallithea/templates/changeset/diff_block.html:27
+#: kallithea/templates/changeset/diff_block.html:72
 #: kallithea/templates/files/diff_2way.html:49
 msgid "Raw diff"
 msgstr "Адлюстраваць у фармаце diff"
 
 #: kallithea/templates/changeset/changeset.html:57
 msgid "Patch diff"
-msgstr "Ужыць рознаснае выпраўленне (Patch diff)"
+msgstr "Patch diff"
 
 #: kallithea/templates/changeset/changeset.html:60
-#: kallithea/templates/changeset/diff_block.html:30
+#: kallithea/templates/changeset/diff_block.html:75
 #: kallithea/templates/files/diff_2way.html:52
 msgid "Download diff"
-msgstr "Запампаваць diff"
+msgstr "Спампаваць diff"
 
 #: kallithea/templates/changeset/changeset.html:89
 #: kallithea/templates/changeset/changeset_range.html:88
-#, fuzzy
 msgid "Merge"
-msgstr "звесці"
+msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:123
 msgid "Grafted from:"
@@ -4990,135 +4932,136 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:135
-#, fuzzy
 msgid "Replaced by:"
-msgstr "Створана"
+msgstr "Заменена:"
 
 #: kallithea/templates/changeset/changeset.html:149
-#, fuzzy
 msgid "Preceded by:"
-msgstr "Створана"
+msgstr "Замяняе:"
 
 #: kallithea/templates/changeset/changeset.html:166
-#: kallithea/templates/compare/compare_diff.html:54
-#: kallithea/templates/pullrequests/pullrequest_show.html:318
+#: kallithea/templates/compare/compare_diff.html:60
+#: kallithea/templates/pullrequests/pullrequest_show.html:329
 #, python-format
 msgid "%s file changed"
 msgid_plural "%s files changed"
 msgstr[0] "%s файл зменены"
-msgstr[1] "%s файлаў зменена"
-msgstr[2] "%s файла зменена"
+msgstr[1] "%s файлы зменена"
+msgstr[2] "%s файлаў зменена"
 
 #: kallithea/templates/changeset/changeset.html:168
-#: kallithea/templates/compare/compare_diff.html:56
-#: kallithea/templates/pullrequests/pullrequest_show.html:320
+#: kallithea/templates/compare/compare_diff.html:62
+#: kallithea/templates/pullrequests/pullrequest_show.html:331
 #, python-format
 msgid "%s file changed with %s insertions and %s deletions"
 msgid_plural "%s files changed with %s insertions and %s deletions"
 msgstr[0] "%s файл зменены: %s даданне, %s выдаленне"
-msgstr[1] "%s файла зменена: %s даданні, %s выдаленні"
+msgstr[1] "%s файлы зменена: %s даданні, %s выдаленні"
 msgstr[2] "%s файлаў зменена: %s даданняў, %s выдаленняў"
 
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Show full diff anyway"
 msgstr "Паказаць поўны diff"
 
-#: kallithea/templates/changeset/changeset.html:247
-#: kallithea/templates/changeset/changeset.html:284
-#, fuzzy
+#: kallithea/templates/changeset/changeset.html:231
+#: kallithea/templates/changeset/changeset.html:268
 msgid "No revisions"
-msgstr "няма рэвізій"
+msgstr "Няма рэвізій"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:21
-#, fuzzy
 msgid "on pull request"
-msgstr "Каментар у pull-запыце"
+msgstr "у pull-запыце"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:22
 msgid "No title"
 msgstr "Няма загалоўка"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:24
-#, fuzzy
 msgid "on this changeset"
-msgstr "Няма змен"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+msgstr "на змене"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:31
 msgid "Delete comment?"
 msgstr "Выдаліць каментар?"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:37
-#, fuzzy
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 msgid "Status change"
-msgstr "Апошнія змены"
+msgstr "Змена статусу"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:59
-msgid "Commenting on line {1}."
-msgstr "Каментар да радка {1}."
+msgid "Commenting on line."
+msgstr "Каментар да радка."
 
 #: kallithea/templates/changeset/changeset_file_comment.html:60
-#: kallithea/templates/changeset/changeset_file_comment.html:148
-#, python-format
-msgid "Comments parsed using %s syntax with %s support."
-msgstr "Парсінг каментароў выкананы з выкарыстаннем сінтаксісу %s з падтрымкай %s."
-
-#: kallithea/templates/changeset/changeset_file_comment.html:62
-msgid "Use @username inside this text to notify another user"
-msgstr ""
-"Выкарыстоўвайце @імя_карыстача ў тэксце, каб адправіць абвестку пэўнаму "
-"карыстачу"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:72
-#: kallithea/templates/changeset/changeset_file_comment.html:184
-msgid "Comment preview"
-msgstr "Папярэдні прагляд каментара"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:77
+#, fuzzy
+msgid ""
+"Comments are in plain text. Use @username inside this text to notify "
+"another user."
+msgstr ""
+"Выкарыстоўвайце @імя_карыстальніка ў тэксце, каб адправіць паведамленне "
+"пэўнаму карыстальніку"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:67
+msgid "Set changeset status"
+msgstr "Змяніць статус рэвізіі"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:69
+msgid "Vote for pull request status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:75
+msgid "No change"
+msgstr "Без змен"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:88
+#, fuzzy
+msgid "Finish pull request"
+msgstr "Каментар у pull-запыце"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:91
+msgid "Close"
+msgstr "Закрыць"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:103
 msgid "Submitting ..."
-msgstr "Ужыванне..."
-
-#: kallithea/templates/changeset/changeset_file_comment.html:80
-#: kallithea/templates/changeset/changeset_file_comment.html:190
+msgstr "Адпраўка..."
+
+#: kallithea/templates/changeset/changeset_file_comment.html:104
 msgid "Comment"
 msgstr "Каментаваць"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:82
-#: kallithea/templates/changeset/changeset_file_comment.html:191
-msgid "Preview"
-msgstr "Прадпрагляд"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "You need to be logged in to comment."
 msgstr "Вам неабходна аўтарызавацца, каб пакідаць каментары."
 
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "Login now"
-msgstr "Аўтарызавацца цяпер"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:94
+msgstr "Аўтарызавацца зараз"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:116
 msgid "Hide"
 msgstr "Схаваць"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:106
+#: kallithea/templates/changeset/changeset_file_comment.html:128
 #, python-format
 msgid "%d comment"
 msgid_plural "%d comments"
 msgstr[0] "%d каментар"
-msgstr[1] "%d каментара"
+msgstr[1] "%d каментары"
 msgstr[2] "%d каментароў"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:107
+#: kallithea/templates/changeset/changeset_file_comment.html:129
 #, python-format
 msgid "%d inline"
 msgid_plural "%d inline"
-msgstr[0] "%d да радка"
-msgstr[1] "%d да радкоў"
-msgstr[2] "%d да радкоў"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:108
+msgstr[0] ""
+msgstr[1] ""
+msgstr[2] ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:130
 #, python-format
 msgid "%d general"
 msgid_plural "%d general"
@@ -5126,29 +5069,6 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:150
-#, fuzzy
-msgid "Use @username inside this text to notify another user."
-msgstr ""
-"Выкарыстоўвайце @імя_карыстача ў тэксце, каб адправіць абвестку пэўнаму "
-"карыстачу"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:157
-msgid "Vote for pull request status"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:159
-msgid "Set changeset status"
-msgstr "Змяніць статус рэвізіі"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:163
-msgid "No change"
-msgstr "Без змен"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:176
-msgid "Close"
-msgstr "Зачыніць"
-
 #: kallithea/templates/changeset/changeset_range.html:5
 #, python-format
 msgid "%s Changesets"
@@ -5158,29 +5078,28 @@
 msgid "Files affected"
 msgstr "Закранутыя файлы"
 
-#: kallithea/templates/changeset/diff_block.html:21
+#: kallithea/templates/changeset/diff_block.html:54
+msgid "Deleted"
+msgstr "Выдалены"
+
+#: kallithea/templates/changeset/diff_block.html:57
+msgid "Renamed"
+msgstr "Пераназваны"
+
+#: kallithea/templates/changeset/diff_block.html:66
 #: kallithea/templates/files/diff_2way.html:43
 msgid "Show full diff for this file"
 msgstr "Паказаць поўны diff для гэтага файла"
 
-#: kallithea/templates/changeset/diff_block.html:24
-#: kallithea/templates/changeset/diff_block.html:98
+#: kallithea/templates/changeset/diff_block.html:69
 #: kallithea/templates/files/diff_2way.html:46
 msgid "Show full side-by-side diff for this file"
 msgstr "Паказаць поўны diff для гэтага файла"
 
-#: kallithea/templates/changeset/diff_block.html:38
+#: kallithea/templates/changeset/diff_block.html:83
 msgid "Show inline comments"
 msgstr "Паказаць каментары ў радках"
 
-#: kallithea/templates/changeset/diff_block.html:86
-msgid "Deleted"
-msgstr "Выдалены"
-
-#: kallithea/templates/changeset/diff_block.html:89
-msgid "Renamed"
-msgstr "Пераназваны"
-
 #: kallithea/templates/compare/compare_cs.html:4
 msgid "No changesets"
 msgstr "Няма змен"
@@ -5189,6 +5108,11 @@
 msgid "Ancestor"
 msgstr "Продак"
 
+#: kallithea/templates/compare/compare_cs.html:24
+#, python-format
+msgid "Changeset status: %s"
+msgstr "Статус набору змен: %s"
+
 #: kallithea/templates/compare/compare_cs.html:44
 msgid "First (oldest) changeset in this list"
 msgstr ""
@@ -5201,29 +5125,29 @@
 msgid "Position in this list of changesets"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:76
+#: kallithea/templates/compare/compare_cs.html:85
 msgid "Show merge diff"
 msgstr "Паказаць merge diff"
 
-#: kallithea/templates/compare/compare_cs.html:86
-#: kallithea/templates/pullrequests/pullrequest_show.html:310
+#: kallithea/templates/compare/compare_cs.html:95
+#: kallithea/templates/pullrequests/pullrequest_show.html:321
 msgid "Common ancestor"
 msgstr "Агульны продак"
 
-#: kallithea/templates/compare/compare_cs.html:90
+#: kallithea/templates/compare/compare_cs.html:99
 msgid "No common ancestor found - repositories are unrelated"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:98
+#: kallithea/templates/compare/compare_cs.html:107
 msgid "is"
 msgstr "адстае на"
 
-#: kallithea/templates/compare/compare_cs.html:99
+#: kallithea/templates/compare/compare_cs.html:108
 #, python-format
 msgid "%s changesets"
 msgstr "%s змен"
 
-#: kallithea/templates/compare/compare_cs.html:100
+#: kallithea/templates/compare/compare_cs.html:109
 msgid "behind"
 msgstr "ад"
 
@@ -5234,29 +5158,29 @@
 msgstr "%s Параўнаць"
 
 #: kallithea/templates/compare/compare_diff.html:13
-#: kallithea/templates/compare/compare_diff.html:35
+#: kallithea/templates/compare/compare_diff.html:41
 msgid "Compare Revisions"
 msgstr "Параўнаць рэвізіі"
 
-#: kallithea/templates/compare/compare_diff.html:33
+#: kallithea/templates/compare/compare_diff.html:39
 msgid "Swap"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:42
+#: kallithea/templates/compare/compare_diff.html:48
 msgid "Compare revisions, branches, bookmarks, or tags."
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:47
-#: kallithea/templates/pullrequests/pullrequest_show.html:305
+#: kallithea/templates/compare/compare_diff.html:53
+#: kallithea/templates/pullrequests/pullrequest_show.html:316
 #, python-format
 msgid "Showing %s commit"
 msgid_plural "Showing %s commits"
 msgstr[0] "Паказаць %s commit"
-msgstr[1] "Паказаць %s commit'а"
+msgstr[1] "Паказаць %s commit'ы"
 msgstr[2] "Паказаць %s commit'аў"
 
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
 msgid "Show full diff"
 msgstr "Паказаць поўны diff"
 
@@ -5300,7 +5224,7 @@
 
 #: kallithea/templates/email_templates/changeset_comment.html:12
 msgid "The changeset status was changed to"
-msgstr "Стан набору змен зменены на"
+msgstr "Статус набору змен зменены на"
 
 #: kallithea/templates/email_templates/main.html:6
 msgid "This is an automatic notification. Don't reply to this mail."
@@ -5312,22 +5236,26 @@
 msgstr "Добры дзень, %s"
 
 #: kallithea/templates/email_templates/password_reset.html:6
-#, fuzzy
-#| msgid "We received a request to create a new password for your account."
 msgid "We have received a request to reset the password for your account."
-msgstr "Мы атрымалі запыт на стварэнне новага пароля для вашага акаўнта."
-
-#: kallithea/templates/email_templates/password_reset.html:7
-msgid "To set a new password, click the following link"
+msgstr "Мы атрымалі запыт на скіданне пароля для вашага акаўнта."
+
+#: kallithea/templates/email_templates/password_reset.html:8
+msgid ""
+"This account is however managed outside this system and the password "
+"cannot be changed here."
 msgstr ""
 
 #: kallithea/templates/email_templates/password_reset.html:10
+msgid "To set a new password, click the following link"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:13
 msgid ""
 "Should you not be able to use the link above, please type the following "
 "code into the password reset form"
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:12
+#: kallithea/templates/email_templates/password_reset.html:16
 msgid ""
 "If it weren't you who requested the password reset, just disregard this "
 "message."
@@ -5358,7 +5286,7 @@
 
 #: kallithea/templates/email_templates/registration.html:6
 msgid "View this user here"
-msgstr "Падрабязней пра карыстача"
+msgstr "Падрабязней пра карыстальніка"
 
 #: kallithea/templates/files/diff_2way.html:15
 #, python-format
@@ -5410,14 +5338,15 @@
 msgstr "Стварыць новы файл"
 
 #: kallithea/templates/files/files_add.html:53
-msgid "New file mode"
-msgstr "Рэжым новага файла"
+#, fuzzy
+msgid "New file type"
+msgstr "Тып новага файла"
 
 #: kallithea/templates/files/files_add.html:64
 #: kallithea/templates/files/files_delete.html:43
 #: kallithea/templates/files/files_edit.html:67
 msgid "Commit Changes"
-msgstr "Ужыць змены"
+msgstr "Захаваць змены"
 
 #: kallithea/templates/files/files_browser.html:33
 msgid "Previous revision"
@@ -5429,7 +5358,7 @@
 
 #: kallithea/templates/files/files_browser.html:41
 msgid "Follow current branch"
-msgstr "Адсочваць дадзеную галінку"
+msgstr "Адсочваць дадзеную галіну"
 
 #: kallithea/templates/files/files_browser.html:44
 msgid "Search File List"
@@ -5527,11 +5456,11 @@
 
 #: kallithea/templates/files/files_source.html:41
 msgid "Editing binary files not allowed"
-msgstr "Рэдагаванне бінарных файлаў забаронена"
+msgstr "Рэдагаванне бінарных файлаў забароненае"
 
 #: kallithea/templates/files/files_source.html:44
 msgid "Editing files allowed only when on branch head revision"
-msgstr "Рэдагаванне файлаў дазволена толькі ў HEAD-рэвізіі дадзенай галінкі"
+msgstr "Рэдагаванне файлаў дазволенае толькі ў HEAD-рэвізіі дадзенай галіны"
 
 #: kallithea/templates/files/files_source.html:45
 msgid "Deleting files allowed only when on branch head revision"
@@ -5542,9 +5471,20 @@
 msgid "Binary file (%s)"
 msgstr "Бінарны файл (%s)"
 
-#: kallithea/templates/files/files_source.html:73
-msgid "File is too big to display"
-msgstr "Файл занадта вялікай для адлюстравання"
+#: kallithea/templates/files/files_source.html:74
+#, fuzzy
+msgid "File is too big to display."
+msgstr "Файл занадта вялікі для адлюстравання"
+
+#: kallithea/templates/files/files_source.html:76
+#, fuzzy
+msgid "Show full annotation anyway."
+msgstr "Паказаць поўны diff"
+
+#: kallithea/templates/files/files_source.html:78
+#, fuzzy
+msgid "Show as raw."
+msgstr "Паказаць толькі тэкст"
 
 #: kallithea/templates/files/files_ypjax.html:5
 msgid "annotation"
@@ -5629,11 +5569,11 @@
 
 #: kallithea/templates/forks/forks_data.html:30
 msgid "There are no forks yet"
-msgstr "Форкі яшчэ не створаны"
+msgstr "Форкі яшчэ не створаныя"
 
 #: kallithea/templates/journal/journal.html:21
 msgid "ATOM journal feed"
-msgstr "Стужка часопіса ATOM"
+msgstr "Стужка часопіса Atom"
 
 #: kallithea/templates/journal/journal.html:22
 msgid "RSS journal feed"
@@ -5649,7 +5589,7 @@
 
 #: kallithea/templates/journal/public_journal.html:13
 msgid "ATOM public journal feed"
-msgstr "Агульная стужка часопіса ATOM"
+msgstr "Агульная стужка часопіса Atom"
 
 #: kallithea/templates/journal/public_journal.html:14
 msgid "RSS public journal feed"
@@ -5693,9 +5633,8 @@
 msgstr "Запісы отсуствуют"
 
 #: kallithea/templates/pullrequests/pullrequest_data.html:14
-#, fuzzy
 msgid "Vote"
-msgstr "адклікаць"
+msgstr "Галасаваць"
 
 #: kallithea/templates/pullrequests/pullrequest_data.html:18
 msgid "From"
@@ -5733,19 +5672,19 @@
 msgstr "Пацвердзіце выдаленне гэтага pull-request'а"
 
 #: kallithea/templates/pullrequests/pullrequest_data.html:70
-#, fuzzy, python-format
+#, python-format
 msgid "Confirm again to delete this pull request with %s comments"
-msgstr "Пацвердзіце выдаленне гэтага pull-request'а"
+msgstr "Пацвердзіце выдаленне гэтага pull-запыту з %s каментарамі"
 
 #: kallithea/templates/pullrequests/pullrequest_show.html:6
-#, fuzzy, python-format
+#, python-format
 msgid "%s Pull Request %s"
-msgstr "%s Pull-запыт #%s"
+msgstr "%s зull-запыт %s"
 
 #: kallithea/templates/pullrequests/pullrequest_show.html:10
-#, fuzzy, python-format
+#, python-format
 msgid "Pull request %s from %s#%s"
-msgstr "Pull-запыты №%s ад %s#%s"
+msgstr "Pull-запыт %s ад %s#%s"
 
 #: kallithea/templates/pullrequests/pullrequest_show.html:57
 msgid "Summarize the changes"
@@ -5769,7 +5708,7 @@
 msgid "%d reviewer"
 msgid_plural "%d reviewers"
 msgstr[0] "%d рэцэнзент"
-msgstr[1] "%d рэцэнзента"
+msgstr[1] "%d рэцэнзенты"
 msgstr[2] "%d рэцэнзентаў"
 
 #: kallithea/templates/pullrequests/pullrequest_show.html:99
@@ -5810,56 +5749,63 @@
 msgid "Current revision - no change"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:213
+#: kallithea/templates/pullrequests/pullrequest_show.html:215
+msgid ""
+"Pull requests do not change once created. Select a revision and save to "
+"replace this pull request with a new one."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:224
 msgid "Pull Request Reviewers"
 msgstr "Рэцэнзенты pull-запытаў"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:238
+#: kallithea/templates/pullrequests/pullrequest_show.html:249
 msgid "Remove reviewer"
 msgstr "Выдаліць рэцэнзента"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:250
-msgid "Type name of reviewer to add"
-msgstr ""
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:258
-msgid "Potential Reviewers"
-msgstr "Патэнцыйныя рэцэнзенты"
-
 #: kallithea/templates/pullrequests/pullrequest_show.html:261
+msgid "Type name of reviewer to add"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:269
+msgid "Potential Reviewers"
+msgstr "Патэнцыйныя рэцэнзенты"
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:272
 msgid "Click to add the repository owner as reviewer:"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:284
+#: kallithea/templates/pullrequests/pullrequest_show.html:295
 msgid "Save Changes"
 msgstr "Захаваць змены"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:285
-msgid "Save as New Pull Request"
-msgstr ""
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:286
+#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#, fuzzy
+msgid "Save Updates as New Pull Request"
+msgstr "Pull-запыт створаны паспяхова"
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:297
 msgid "Cancel Changes"
 msgstr "Адмяніць змены"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#: kallithea/templates/pullrequests/pullrequest_show.html:307
 msgid "Pull Request Content"
 msgstr ""
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:6
 #, python-format
 msgid "%s Pull Requests"
-msgstr "%s Запыты на занясенне змен"
+msgstr "%s pull-запыты"
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:11
 #, python-format
-msgid "Pull Requests from %s'"
-msgstr "Pull-запыты ад %s"
+msgid "Pull Requests from '%s'"
+msgstr "Pull-запыты ад '%s'"
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:13
 #, python-format
 msgid "Pull Requests to '%s'"
-msgstr "Pull-запыты для %s"
+msgstr "Pull-запыты да '%s'"
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:32
 msgid "Open New Pull Request"
@@ -5913,7 +5859,7 @@
 
 #: kallithea/templates/search/search.html:65
 msgid "File contents"
-msgstr "Змесціва файлаў"
+msgstr "Змест файлаў"
 
 #: kallithea/templates/search/search.html:66
 msgid "Commit messages"
@@ -5927,7 +5873,7 @@
 #: kallithea/templates/search/search_content.html:21
 #: kallithea/templates/search/search_path.html:15
 msgid "Permission denied"
-msgstr "Недастаткова мае рацыю"
+msgstr "Недастаткова правоў"
 
 #: kallithea/templates/summary/statistics.html:4
 #, python-format
@@ -5938,7 +5884,7 @@
 #: kallithea/templates/summary/summary.html:39
 #, python-format
 msgid "%s ATOM feed"
-msgstr "ATOM стужка рэпазітара %s"
+msgstr "Atom стужка рэпазітара %s"
 
 #: kallithea/templates/summary/statistics.html:17
 #: kallithea/templates/summary/summary.html:40
@@ -6022,15 +5968,15 @@
 
 #: kallithea/templates/summary/summary.html:72
 msgid "Clone URL"
-msgstr "Спасылка для кланавання"
+msgstr "URL для кланавання"
 
 #: kallithea/templates/summary/summary.html:78
 msgid "Show by Name"
-msgstr "Паказаць па імі"
+msgstr "Паводле імя"
 
 #: kallithea/templates/summary/summary.html:79
 msgid "Show by ID"
-msgstr "Паказаць па ID"
+msgstr "Паводле ID"
 
 #: kallithea/templates/summary/summary.html:92
 msgid "Trending files"
@@ -6038,7 +5984,7 @@
 
 #: kallithea/templates/summary/summary.html:108
 msgid "Download"
-msgstr "Запампаваць"
+msgstr "Спампаваць"
 
 #: kallithea/templates/summary/summary.html:112
 msgid "There are no downloads yet"
@@ -6046,20 +5992,19 @@
 
 #: kallithea/templates/summary/summary.html:114
 msgid "Downloads are disabled for this repository"
-msgstr "Спампоўка адключана ў гэтым рэпазітары"
+msgstr "Спампоўванне адключанае ў гэтым рэпазітары"
 
 #: kallithea/templates/summary/summary.html:120
 msgid "Download as zip"
-msgstr "Запампаваць у zip"
+msgstr "Спампаваць у zip"
 
 #: kallithea/templates/summary/summary.html:125
 msgid "Check this to download archive with subrepos"
 msgstr "Адзначце для спампоўкі архіва з даччынымі рэпазітарамі"
 
 #: kallithea/templates/summary/summary.html:125
-#, fuzzy
 msgid "With subrepos"
-msgstr "з даччынымі рэпазітарамі"
+msgstr "З даччынымі рэпазітарамі"
 
 #: kallithea/templates/summary/summary.html:156
 msgid "Repository Size"
@@ -6086,12 +6031,12 @@
 #: kallithea/templates/summary/summary.html:293
 #, python-format
 msgid "Download %s as %s"
-msgstr "Запампаваць %s як %s"
+msgstr "Спампаваць %s як %s"
 
 #: kallithea/templates/tags/tags.html:5
 #, python-format
 msgid "%s Tags"
-msgstr "%s Пазнак"
+msgstr "%s Тэгаў"
 
 #: kallithea/templates/tags/tags.html:26
 msgid "Compare Tags"
@@ -6122,19 +6067,16 @@
 #~ msgstr "Рэпазітар %s"
 
 #~ msgid "You can't edit this user"
-#~ msgstr "Вы не можаце рэдагаваць дадзенага карыстача"
+#~ msgstr "Вы не можаце рэдагаваць дадзенага карыстальніка"
 
 #~ msgid "No Files"
 #~ msgstr "Файлаў няма"
 
-#~ msgid ""
-#~ msgstr ""
-
 #~ msgid "Username \"%(username)s\" is forbidden"
 #~ msgstr "Імя \"%(username)s\" адхілена"
 
 #~ msgid "invalid user name"
-#~ msgstr "няслушнае імя карыстача"
+#~ msgstr "няслушнае імя карыстальніка"
 
 #~ msgid "Your account is disabled"
 #~ msgstr "Ваш акаўнт выключаны"
@@ -6185,10 +6127,10 @@
 #~ msgstr "Перазапісаць існыя налады"
 
 #~ msgid "Default IP Whitelist for All Users"
-#~ msgstr "Белы спіс IP для ўсіх карыстачоў"
+#~ msgstr "Белы спіс IP для ўсіх карыстальнікаў"
 
 #~ msgid "Default User Permissions Overview"
-#~ msgstr "Агляд мае рацыю карыстачоў па змаўчанні"
+#~ msgstr "Агляд мае рацыю карыстальнікаў па змаўчанні"
 
 #~ msgid "none"
 #~ msgstr "нічога"
@@ -6313,27 +6255,6 @@
 #~ msgid "reviewer"
 #~ msgstr "рэцэнзент"
 
-#~ msgid ""
-#~ "Your password reset was successful, new"
-#~ " password has been sent to your "
-#~ "email"
-#~ msgstr "Пароль скінуты паспяхова, новы пароль быў адпраўлены на ваш email"
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " changeset %(short_id)s on %(branch)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Added by %(pr_username)s] %(repo_name)s pull"
-#~ " request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " pull request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
 #~ msgid "Your new password"
 #~ msgstr "Ваш новы пароль"
 
@@ -6351,10 +6272,31 @@
 
 #~ msgid "Please ignore this email if you did not request a new password ."
 #~ msgstr ""
-#~ "Калі ласка, праігнаруйце дадзенае "
-#~ "паведамленне, калі вы не запытвалі новы"
-#~ " пароль."
 
 #~ msgid "Created by"
 #~ msgstr "Створана"
 
+#~ msgid "This pull request can be updated with changes on %s:"
+#~ msgstr "Гэты pull-запыт можа быць абноўлены з %s:"
+
+#~ msgid "Confirm to invalidate repository cache."
+#~ msgstr "Пацвердзіце скід кэша."
+
+#~ msgid "Comments parsed using %s syntax with %s support."
+#~ msgstr ""
+
+#~ msgid "Use @username inside this text to notify another user"
+#~ msgstr ""
+
+#~ msgid "Comment preview"
+#~ msgstr "Папярэдні прагляд каментара"
+
+#~ msgid "Preview"
+#~ msgstr "Прадпрагляд"
+
+#~ msgid "New file mode"
+#~ msgstr "Рэжым новага файла"
+
+#~ msgid "Save as New Pull Request"
+#~ msgstr ""
+
--- a/kallithea/i18n/cs/LC_MESSAGES/kallithea.po	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/i18n/cs/LC_MESSAGES/kallithea.po	Fri Nov 18 01:11:13 2016 +0100
@@ -7,11 +7,11 @@
 msgstr ""
 "Project-Id-Version: Kallithea 0.3\n"
 "Report-Msgid-Bugs-To: translations@kallithea-scm.org\n"
-"POT-Creation-Date: 2015-09-08 10:34+0200\n"
+"POT-Creation-Date: 2016-03-14 16:51+0100\n"
 "PO-Revision-Date: 2015-11-12 08:51+0000\n"
 "Last-Translator: Michal Čihař <michal@cihar.com>\n"
 "Language-Team: Czech "
-"<https://hosted.weblate.org/projects/kallithea/stable/cs/>\n"
+"<https://hosted.weblate.org/projects/kallithea/kallithea/cs/>\n"
 "Language: cs\n"
 "MIME-Version: 1.0\n"
 "Content-Type: text/plain; charset=UTF-8\n"
@@ -19,12 +19,12 @@
 "Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;\n"
 "X-Generator: Weblate 2.5-dev\n"
 
-#: kallithea/controllers/changelog.py:86
-#: kallithea/controllers/pullrequests.py:238 kallithea/lib/base.py:512
+#: kallithea/controllers/changelog.py:85
+#: kallithea/controllers/pullrequests.py:240 kallithea/lib/base.py:515
 msgid "There are no changesets yet"
 msgstr ""
 
-#: kallithea/controllers/changelog.py:166
+#: kallithea/controllers/changelog.py:164
 #: kallithea/controllers/admin/permissions.py:61
 #: kallithea/controllers/admin/permissions.py:65
 #: kallithea/controllers/admin/permissions.py:69
@@ -36,35 +36,29 @@
 msgid "None"
 msgstr ""
 
-#: kallithea/controllers/changelog.py:169 kallithea/controllers/files.py:196
+#: kallithea/controllers/changelog.py:167 kallithea/controllers/files.py:198
 msgid "(closed)"
 msgstr "(zavřeno)"
 
-#: kallithea/controllers/changeset.py:89
+#: kallithea/controllers/changeset.py:88
 msgid "Show whitespace"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:96 kallithea/controllers/changeset.py:103
+#: kallithea/controllers/changeset.py:95 kallithea/controllers/changeset.py:102
 #: kallithea/templates/files/diff_2way.html:55
 msgid "Ignore whitespace"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:169
+#: kallithea/controllers/changeset.py:168
 #, python-format
 msgid "Increase diff context to %(num)s lines"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:212 kallithea/controllers/files.py:96
-#: kallithea/controllers/files.py:116 kallithea/controllers/files.py:742
+#: kallithea/controllers/changeset.py:233 kallithea/controllers/files.py:97
+#: kallithea/controllers/files.py:117 kallithea/controllers/files.py:744
 msgid "Such revision does not exist for this repository"
 msgstr "Taková revize neexistuje"
 
-#: kallithea/controllers/changeset.py:383
-msgid ""
-"Changing status on a changeset associated with a closed pull request is "
-"not allowed"
-msgstr ""
-
 #: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:41
 msgid "Select changeset"
 msgstr ""
@@ -117,10 +111,10 @@
 #: kallithea/controllers/feed.py:87
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Changeset was too big and was cut off..."
 msgstr ""
 
@@ -129,111 +123,111 @@
 msgid "%s committed on %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:91
+#: kallithea/controllers/files.py:92
 msgid "Click here to add new file"
 msgstr "Klikněte pro přidání nového souboru"
 
-#: kallithea/controllers/files.py:92
+#: kallithea/controllers/files.py:93
 #, python-format
 msgid "There are no files yet. %s"
 msgstr "Zatím nejsou žádné soubory. %s"
 
-#: kallithea/controllers/files.py:193
+#: kallithea/controllers/files.py:195
 #, python-format
 msgid "%s at %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:305 kallithea/controllers/files.py:365
-#: kallithea/controllers/files.py:432
+#: kallithea/controllers/files.py:307 kallithea/controllers/files.py:367
+#: kallithea/controllers/files.py:434
 #, python-format
 msgid "This repository has been locked by %s on %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:317
-msgid "You can only delete files with revision being a valid branch "
-msgstr ""
-
-#: kallithea/controllers/files.py:328
+#: kallithea/controllers/files.py:319
+msgid "You can only delete files with revision being a valid branch"
+msgstr ""
+
+#: kallithea/controllers/files.py:330
 #, python-format
 msgid "Deleted file %s via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:350
+#: kallithea/controllers/files.py:352
 #, python-format
 msgid "Successfully deleted file %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:354 kallithea/controllers/files.py:420
-#: kallithea/controllers/files.py:501
+#: kallithea/controllers/files.py:356 kallithea/controllers/files.py:422
+#: kallithea/controllers/files.py:503
 msgid "Error occurred during commit"
 msgstr ""
 
-#: kallithea/controllers/files.py:377
-msgid "You can only edit files with revision being a valid branch "
-msgstr ""
-
-#: kallithea/controllers/files.py:391
+#: kallithea/controllers/files.py:379
+msgid "You can only edit files with revision being a valid branch"
+msgstr ""
+
+#: kallithea/controllers/files.py:393
 #, python-format
 msgid "Edited file %s via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:407
+#: kallithea/controllers/files.py:409
 msgid "No changes"
 msgstr "Žádné změny"
 
-#: kallithea/controllers/files.py:416 kallithea/controllers/files.py:490
+#: kallithea/controllers/files.py:418 kallithea/controllers/files.py:492
 #, python-format
 msgid "Successfully committed to %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:443
+#: kallithea/controllers/files.py:445
 msgid "Added file via Kallithea"
 msgstr "Přidaný soubor přes Kallithea"
 
-#: kallithea/controllers/files.py:464
+#: kallithea/controllers/files.py:466
 msgid "No content"
 msgstr "Žádný obsah"
 
-#: kallithea/controllers/files.py:468
+#: kallithea/controllers/files.py:470
 msgid "No filename"
 msgstr ""
 
-#: kallithea/controllers/files.py:493
+#: kallithea/controllers/files.py:495
 msgid "Location must be relative path and must not contain .. in path"
 msgstr ""
 
-#: kallithea/controllers/files.py:526
+#: kallithea/controllers/files.py:528
 msgid "Downloads disabled"
 msgstr "Stahování vypnuto"
 
-#: kallithea/controllers/files.py:537
+#: kallithea/controllers/files.py:539
 #, python-format
 msgid "Unknown revision %s"
 msgstr "Neznámá revize %s"
 
-#: kallithea/controllers/files.py:539
+#: kallithea/controllers/files.py:541
 msgid "Empty repository"
 msgstr "Prázdný repozitář"
 
-#: kallithea/controllers/files.py:541
+#: kallithea/controllers/files.py:543
 msgid "Unknown archive type"
 msgstr ""
 
-#: kallithea/controllers/files.py:771
+#: kallithea/controllers/files.py:773
 #: kallithea/templates/changeset/changeset_range.html:9
 #: kallithea/templates/email_templates/pull_request.html:15
 #: kallithea/templates/pullrequests/pullrequest.html:97
 msgid "Changesets"
 msgstr "Změny"
 
-#: kallithea/controllers/files.py:772 kallithea/controllers/pullrequests.py:176
-#: kallithea/model/scm.py:820 kallithea/templates/switch_to_list.html:3
+#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:175
+#: kallithea/model/scm.py:716 kallithea/templates/switch_to_list.html:3
 #: kallithea/templates/branches/branches.html:10
 msgid "Branches"
 msgstr "Větve"
 
-#: kallithea/controllers/files.py:773 kallithea/controllers/pullrequests.py:177
-#: kallithea/model/scm.py:831 kallithea/templates/switch_to_list.html:25
+#: kallithea/controllers/files.py:775 kallithea/controllers/pullrequests.py:176
+#: kallithea/model/scm.py:727 kallithea/templates/switch_to_list.html:25
 #: kallithea/templates/tags/tags.html:10
 msgid "Tags"
 msgstr "Tagy"
@@ -247,7 +241,7 @@
 msgid "Groups"
 msgstr "Skupiny"
 
-#: kallithea/controllers/home.py:89
+#: kallithea/controllers/home.py:94
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:106
 #: kallithea/templates/admin/repos/repo_add.html:12
 #: kallithea/templates/admin/repos/repo_add.html:16
@@ -255,23 +249,27 @@
 #: kallithea/templates/admin/users/user_edit_advanced.html:6
 #: kallithea/templates/base/base.html:60 kallithea/templates/base/base.html:77
 #: kallithea/templates/base/base.html:124
-#: kallithea/templates/base/base.html:390
-#: kallithea/templates/base/base.html:562
+#: kallithea/templates/base/base.html:479
+#: kallithea/templates/base/base.html:653
 msgid "Repositories"
 msgstr "Repozitáře"
 
-#: kallithea/controllers/home.py:130
+#: kallithea/controllers/home.py:139
 #: kallithea/templates/files/files_add.html:32
 #: kallithea/templates/files/files_delete.html:23
 #: kallithea/templates/files/files_edit.html:32
 msgid "Branch"
 msgstr "Větev"
 
-#: kallithea/controllers/home.py:136
+#: kallithea/controllers/home.py:145 kallithea/templates/switch_to_list.html:16
+msgid "Closed Branches"
+msgstr ""
+
+#: kallithea/controllers/home.py:151
 msgid "Tag"
 msgstr "Tag"
 
-#: kallithea/controllers/home.py:142
+#: kallithea/controllers/home.py:157
 msgid "Bookmark"
 msgstr "Záložka"
 
@@ -282,158 +280,163 @@
 msgstr ""
 
 #: kallithea/controllers/journal.py:115 kallithea/controllers/journal.py:157
-#: kallithea/templates/base/base.html:222
+#: kallithea/templates/base/base.html:306
 #: kallithea/templates/journal/journal.html:4
 #: kallithea/templates/journal/journal.html:12
 msgid "Journal"
 msgstr ""
 
-#: kallithea/controllers/login.py:151 kallithea/controllers/login.py:197
+#: kallithea/controllers/login.py:144 kallithea/controllers/login.py:190
 msgid "Bad captcha"
 msgstr "Špatná captcha"
 
-#: kallithea/controllers/login.py:157
-msgid "You have successfully registered into Kallithea"
-msgstr ""
-
-#: kallithea/controllers/login.py:202
+#: kallithea/controllers/login.py:150
+msgid "You have successfully registered with %s"
+msgstr ""
+
+#: kallithea/controllers/login.py:195
 msgid "A password reset confirmation code has been sent"
 msgstr ""
 
-#: kallithea/controllers/login.py:251
+#: kallithea/controllers/login.py:244
 msgid "Invalid password reset token"
 msgstr ""
 
-#: kallithea/controllers/login.py:256
+#: kallithea/controllers/login.py:249
 #: kallithea/controllers/admin/my_account.py:167
 msgid "Successfully updated password"
 msgstr "Úspěšně aktualizované heslo"
 
-#: kallithea/controllers/pullrequests.py:124
+#: kallithea/controllers/pullrequests.py:123
 #, python-format
 msgid "%s (closed)"
 msgstr "%s (zavřené)"
 
-#: kallithea/controllers/pullrequests.py:152
+#: kallithea/controllers/pullrequests.py:151
 #: kallithea/templates/changeset/changeset.html:12
 #: kallithea/templates/email_templates/changeset_comment.html:17
 msgid "Changeset"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:173
+#: kallithea/controllers/pullrequests.py:172
 msgid "Special"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:174
+#: kallithea/controllers/pullrequests.py:173
 msgid "Peer branches"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:175 kallithea/model/scm.py:826
+#: kallithea/controllers/pullrequests.py:174 kallithea/model/scm.py:722
 #: kallithea/templates/switch_to_list.html:38
 #: kallithea/templates/bookmarks/bookmarks.html:10
 msgid "Bookmarks"
 msgstr "Záložky"
 
-#: kallithea/controllers/pullrequests.py:310
+#: kallithea/controllers/pullrequests.py:312
 #, python-format
 msgid "Error creating pull request: %s"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:356
-#: kallithea/controllers/pullrequests.py:503
+#: kallithea/controllers/pullrequests.py:358
+#: kallithea/controllers/pullrequests.py:505
 msgid "No description"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:363
+#: kallithea/controllers/pullrequests.py:365
 msgid "Successfully opened new pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:366
-#: kallithea/controllers/pullrequests.py:453
-#: kallithea/controllers/pullrequests.py:509
+#: kallithea/controllers/pullrequests.py:368
+#: kallithea/controllers/pullrequests.py:455
+#: kallithea/controllers/pullrequests.py:512
 #, python-format
 msgid "Invalid reviewer \"%s\" specified"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:369
-#: kallithea/controllers/pullrequests.py:456
+#: kallithea/controllers/pullrequests.py:371
+#: kallithea/controllers/pullrequests.py:458
 msgid "Error occurred while creating pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:401
+#: kallithea/controllers/pullrequests.py:403
 msgid "Missing changesets since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:408
+#: kallithea/controllers/pullrequests.py:410
 #, python-format
 msgid "New changesets on %s %s since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:415
+#: kallithea/controllers/pullrequests.py:417
 msgid "Ancestor didn't change - show diff since previous version:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:422
+#: kallithea/controllers/pullrequests.py:424
 #, python-format
 msgid ""
 "This pull request is based on another %s revision and there is no simple "
 "diff."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:424
+#: kallithea/controllers/pullrequests.py:426
 #, python-format
 msgid "No changes found on %s %s since previous version."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:462
+#: kallithea/controllers/pullrequests.py:464
 #, python-format
 msgid "Closed, replaced by %s ."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:470
+#: kallithea/controllers/pullrequests.py:472
 msgid "Pull request update created"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:513
+#: kallithea/controllers/pullrequests.py:516
 msgid "Pull request updated"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:528
+#: kallithea/controllers/pullrequests.py:531
 msgid "Successfully deleted pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:594
+#: kallithea/controllers/pullrequests.py:597
 #, python-format
 msgid "This pull request has already been merged to %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:596
+#: kallithea/controllers/pullrequests.py:599
 msgid "This pull request has been closed and can not be updated."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:614
-#, python-format
-msgid "This pull request can be updated with changes on %s:"
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:617
+#, python-format
+msgid "The following changes are available on %s:"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:621
 msgid "No changesets found for updating this pull request."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:625
+#: kallithea/controllers/pullrequests.py:629
 #, python-format
 msgid "Note: Branch %s has another head: %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:631
+#: kallithea/controllers/pullrequests.py:635
 msgid "Git pull requests don't support updates yet."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:722
-msgid "No permission to change pull request status"
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:727
+msgid "No permission to change pull request status"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:738
+#, fuzzy, python-format
+msgid "Successfully deleted pull request %s"
+msgstr "Úspěšně aktualizované heslo"
+
+#: kallithea/controllers/pullrequests.py:748
 msgid "Closing."
 msgstr ""
 
@@ -449,12 +452,12 @@
 msgid "An error occurred during search operation."
 msgstr "Došlo k chybě při vyhledávání."
 
-#: kallithea/controllers/summary.py:180
+#: kallithea/controllers/summary.py:181
 #: kallithea/templates/summary/summary.html:384
 msgid "No data ready yet"
 msgstr ""
 
-#: kallithea/controllers/summary.py:183
+#: kallithea/controllers/summary.py:184
 #: kallithea/templates/summary/summary.html:98
 msgid "Statistics are disabled for this repository"
 msgstr ""
@@ -475,64 +478,64 @@
 msgid "Error occurred during update of defaults"
 msgstr ""
 
+#: kallithea/controllers/admin/gists.py:58
+#: kallithea/controllers/admin/my_account.py:243
+#: kallithea/controllers/admin/users.py:284
+msgid "Forever"
+msgstr ""
+
 #: kallithea/controllers/admin/gists.py:59
-#: kallithea/controllers/admin/my_account.py:243
+#: kallithea/controllers/admin/my_account.py:244
 #: kallithea/controllers/admin/users.py:285
-msgid "Forever"
-msgstr ""
+msgid "5 minutes"
+msgstr "5 minut"
 
 #: kallithea/controllers/admin/gists.py:60
-#: kallithea/controllers/admin/my_account.py:244
+#: kallithea/controllers/admin/my_account.py:245
 #: kallithea/controllers/admin/users.py:286
-msgid "5 minutes"
-msgstr "5 minut"
+msgid "1 hour"
+msgstr "1 hodina"
 
 #: kallithea/controllers/admin/gists.py:61
-#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/my_account.py:246
 #: kallithea/controllers/admin/users.py:287
-msgid "1 hour"
-msgstr "1 hodina"
+msgid "1 day"
+msgstr "1 den"
 
 #: kallithea/controllers/admin/gists.py:62
-#: kallithea/controllers/admin/my_account.py:246
+#: kallithea/controllers/admin/my_account.py:247
 #: kallithea/controllers/admin/users.py:288
-msgid "1 day"
-msgstr "1 den"
-
-#: kallithea/controllers/admin/gists.py:63
-#: kallithea/controllers/admin/my_account.py:247
-#: kallithea/controllers/admin/users.py:289
 msgid "1 month"
 msgstr "1 měsíc"
 
-#: kallithea/controllers/admin/gists.py:67
+#: kallithea/controllers/admin/gists.py:66
 #: kallithea/controllers/admin/my_account.py:249
-#: kallithea/controllers/admin/users.py:291
+#: kallithea/controllers/admin/users.py:290
 msgid "Lifetime"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:146
+#: kallithea/controllers/admin/gists.py:145
 msgid "Error occurred during gist creation"
 msgstr "Došlo k chybě při vytváření gist"
 
-#: kallithea/controllers/admin/gists.py:184
+#: kallithea/controllers/admin/gists.py:183
 #, python-format
 msgid "Deleted gist %s"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:233
+#: kallithea/controllers/admin/gists.py:232
 msgid "Unmodified"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:262
+#: kallithea/controllers/admin/gists.py:261
 msgid "Successfully updated gist content"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:267
+#: kallithea/controllers/admin/gists.py:266
 msgid "Successfully updated gist data"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:270
+#: kallithea/controllers/admin/gists.py:269
 #, python-format
 msgid "Error occurred during update of gist %s"
 msgstr ""
@@ -547,7 +550,7 @@
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:144
-#: kallithea/controllers/admin/users.py:202
+#: kallithea/controllers/admin/users.py:201
 #, python-format
 msgid "Error occurred during update of user %s"
 msgstr ""
@@ -557,33 +560,33 @@
 msgstr "Došlo k chybě při aktualizaci hesla uživatele"
 
 #: kallithea/controllers/admin/my_account.py:220
-#: kallithea/controllers/admin/users.py:415
+#: kallithea/controllers/admin/users.py:414
 #, python-format
 msgid "Added email %s to user"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:226
-#: kallithea/controllers/admin/users.py:421
+#: kallithea/controllers/admin/users.py:420
 msgid "An error occurred during email saving"
 msgstr "Došlo k chybě při ukládání e-mailové adresy"
 
 #: kallithea/controllers/admin/my_account.py:235
-#: kallithea/controllers/admin/users.py:433
+#: kallithea/controllers/admin/users.py:432
 msgid "Removed email from user"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:259
-#: kallithea/controllers/admin/users.py:308
+#: kallithea/controllers/admin/users.py:307
 msgid "API key successfully created"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:271
-#: kallithea/controllers/admin/users.py:321
+#: kallithea/controllers/admin/users.py:320
 msgid "API key successfully reset"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:275
-#: kallithea/controllers/admin/users.py:325
+#: kallithea/controllers/admin/users.py:324
 msgid "API key successfully deleted"
 msgstr ""
 
@@ -633,10 +636,10 @@
 #: kallithea/templates/admin/users/user_edit_profile.html:105
 #: kallithea/templates/admin/users/users.html:10
 #: kallithea/templates/admin/users/users.html:55
-#: kallithea/templates/base/base.html:252
-#: kallithea/templates/base/base.html:253
-#: kallithea/templates/base/base.html:259
-#: kallithea/templates/base/base.html:260
+#: kallithea/templates/base/base.html:336
+#: kallithea/templates/base/base.html:337
+#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:344
 #: kallithea/templates/base/perms_summary.html:17
 msgid "Admin"
 msgstr ""
@@ -667,7 +670,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1564
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1603
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1655
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1701
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1705
 msgid "Manual activation of external account"
 msgstr ""
 
@@ -679,7 +682,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1565
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1604
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1656
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1702
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1706
 msgid "Automatic activation of external account"
 msgstr ""
 
@@ -700,242 +703,242 @@
 msgid "Error occurred during update of permissions"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:188
+#: kallithea/controllers/admin/repo_groups.py:187
 #, python-format
 msgid "Error occurred during creation of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:193
+#: kallithea/controllers/admin/repo_groups.py:192
 #, python-format
 msgid "Created repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:250
+#: kallithea/controllers/admin/repo_groups.py:249
 #, python-format
 msgid "Updated repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:266
+#: kallithea/controllers/admin/repo_groups.py:265
 #, python-format
 msgid "Error occurred during update of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:284
+#: kallithea/controllers/admin/repo_groups.py:283
 #, python-format
 msgid "This group contains %s repositories and cannot be deleted"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:291
+#: kallithea/controllers/admin/repo_groups.py:290
 #, python-format
 msgid "This group contains %s subgroups and cannot be deleted"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:297
+#: kallithea/controllers/admin/repo_groups.py:296
 #, python-format
 msgid "Removed repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:302
+#: kallithea/controllers/admin/repo_groups.py:301
 #, python-format
 msgid "Error occurred during deletion of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:405
-#: kallithea/controllers/admin/repo_groups.py:440
+#: kallithea/controllers/admin/repo_groups.py:404
+#: kallithea/controllers/admin/repo_groups.py:439
 #: kallithea/controllers/admin/user_groups.py:340
 msgid "Cannot revoke permission for yourself as admin"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:420
+#: kallithea/controllers/admin/repo_groups.py:419
 msgid "Repository group permissions updated"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:457
-#: kallithea/controllers/admin/repos.py:398
+#: kallithea/controllers/admin/repo_groups.py:456
+#: kallithea/controllers/admin/repos.py:397
 #: kallithea/controllers/admin/user_groups.py:352
 msgid "An error occurred during revoking of permission"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:152
+#: kallithea/controllers/admin/repos.py:151
 #, python-format
 msgid "Error creating repository %s"
 msgstr "Chyba při vytváření repozitáře %s"
 
-#: kallithea/controllers/admin/repos.py:213
+#: kallithea/controllers/admin/repos.py:212
 #, python-format
 msgid "Created repository %s from %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:222
+#: kallithea/controllers/admin/repos.py:221
 #, python-format
 msgid "Forked repository %s as %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:225
+#: kallithea/controllers/admin/repos.py:224
 #, python-format
 msgid "Created repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:262
+#: kallithea/controllers/admin/repos.py:261
 #, python-format
 msgid "Repository %s updated successfully"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:283
+#: kallithea/controllers/admin/repos.py:282
 #, python-format
 msgid "Error occurred during update of repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:310
+#: kallithea/controllers/admin/repos.py:309
 #, python-format
 msgid "Detached %s forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:313
+#: kallithea/controllers/admin/repos.py:312
 #, python-format
 msgid "Deleted %s forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:318
+#: kallithea/controllers/admin/repos.py:317
 #, python-format
 msgid "Deleted repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:321
+#: kallithea/controllers/admin/repos.py:320
 #, python-format
 msgid "Cannot delete repository %s which still has forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:326
+#: kallithea/controllers/admin/repos.py:325
 #, python-format
 msgid "An error occurred during deletion of %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:374
+#: kallithea/controllers/admin/repos.py:373
 msgid "Repository permissions updated"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:430
+#: kallithea/controllers/admin/repos.py:429
 msgid "An error occurred during creation of field"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:444
+#: kallithea/controllers/admin/repos.py:443
 msgid "An error occurred during removal of field"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:460
+#: kallithea/controllers/admin/repos.py:459
 msgid "-- Not a fork --"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:491
+#: kallithea/controllers/admin/repos.py:490
 msgid "Updated repository visibility in public journal"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:495
+#: kallithea/controllers/admin/repos.py:494
 msgid "An error occurred during setting this repository in public journal"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:512
+#: kallithea/controllers/admin/repos.py:511
 msgid "Nothing"
 msgstr "Nic"
 
-#: kallithea/controllers/admin/repos.py:514
+#: kallithea/controllers/admin/repos.py:513
 #, python-format
 msgid "Marked repository %s as fork of %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:521
+#: kallithea/controllers/admin/repos.py:520
 msgid "An error occurred during this operation"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:537
-#: kallithea/controllers/admin/repos.py:564
+#: kallithea/controllers/admin/repos.py:536
+#: kallithea/controllers/admin/repos.py:563
 msgid "Repository has been locked"
 msgstr "Repozitář byl uzamčen"
 
-#: kallithea/controllers/admin/repos.py:540
-#: kallithea/controllers/admin/repos.py:561
+#: kallithea/controllers/admin/repos.py:539
+#: kallithea/controllers/admin/repos.py:560
 msgid "Repository has been unlocked"
 msgstr "Repozitář byl odemčen"
 
-#: kallithea/controllers/admin/repos.py:543
-#: kallithea/controllers/admin/repos.py:568
+#: kallithea/controllers/admin/repos.py:542
+#: kallithea/controllers/admin/repos.py:567
 msgid "An error occurred during unlocking"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:582
+#: kallithea/controllers/admin/repos.py:581
 msgid "Cache invalidation successful"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:586
+#: kallithea/controllers/admin/repos.py:585
 msgid "An error occurred during cache invalidation"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:601
+#: kallithea/controllers/admin/repos.py:600
 msgid "Pulled from remote location"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:604
+#: kallithea/controllers/admin/repos.py:603
 msgid "An error occurred during pull from remote location"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:637
+#: kallithea/controllers/admin/repos.py:636
 msgid "An error occurred during deletion of repository stats"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:170
+#: kallithea/controllers/admin/settings.py:141
 msgid "Updated VCS settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:174
+#: kallithea/controllers/admin/settings.py:145
 msgid ""
 "Unable to activate hgsubversion support. The \"hgsubversion\" library is "
 "missing"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:180
-#: kallithea/controllers/admin/settings.py:277
+#: kallithea/controllers/admin/settings.py:151
+#: kallithea/controllers/admin/settings.py:248
 msgid "Error occurred while updating application settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:216
+#: kallithea/controllers/admin/settings.py:187
 #, python-format
 msgid "Repositories successfully rescanned. Added: %s. Removed: %s."
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:273
+#: kallithea/controllers/admin/settings.py:244
 msgid "Updated application settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:330
+#: kallithea/controllers/admin/settings.py:301
 msgid "Updated visualisation settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:335
+#: kallithea/controllers/admin/settings.py:306
 msgid "Error occurred during updating visualisation settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:361
+#: kallithea/controllers/admin/settings.py:332
 msgid "Please enter email address"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:376
+#: kallithea/controllers/admin/settings.py:347
 msgid "Send email task created"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:407
+#: kallithea/controllers/admin/settings.py:378
 msgid "Added new hook"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:421
+#: kallithea/controllers/admin/settings.py:392
 msgid "Updated hooks"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:425
+#: kallithea/controllers/admin/settings.py:396
 msgid "Error occurred during hook creation"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:451
+#: kallithea/controllers/admin/settings.py:422
 msgid "Whoosh reindex task scheduled"
 msgstr ""
 
@@ -976,76 +979,80 @@
 msgstr ""
 
 #: kallithea/controllers/admin/user_groups.py:440
-#: kallithea/controllers/admin/users.py:384
+#: kallithea/controllers/admin/users.py:383
 msgid "Updated permissions"
 msgstr ""
 
 #: kallithea/controllers/admin/user_groups.py:444
-#: kallithea/controllers/admin/users.py:388
+#: kallithea/controllers/admin/users.py:387
 msgid "An error occurred during permissions saving"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:134
+#: kallithea/controllers/admin/users.py:133
 #, python-format
 msgid "Created user %s"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:149
+#: kallithea/controllers/admin/users.py:148
 #, python-format
 msgid "Error occurred during creation of user %s"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:182
+#: kallithea/controllers/admin/users.py:181
 msgid "User updated successfully"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:218
+#: kallithea/controllers/admin/users.py:217
 msgid "Successfully deleted user"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:223
+#: kallithea/controllers/admin/users.py:222
 msgid "An error occurred during deletion of user"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:236
+#: kallithea/controllers/admin/users.py:235
 msgid "The default user cannot be edited"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:463
+#: kallithea/controllers/admin/users.py:462
 #, python-format
 msgid "Added IP address %s to user whitelist"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:469
+#: kallithea/controllers/admin/users.py:468
 msgid "An error occurred while adding IP address"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:483
+#: kallithea/controllers/admin/users.py:482
 msgid "Removed IP address from user whitelist"
 msgstr ""
 
-#: kallithea/lib/auth.py:743
+#: kallithea/lib/auth.py:737
 #, python-format
 msgid "IP %s not allowed"
 msgstr ""
 
-#: kallithea/lib/auth.py:756
+#: kallithea/lib/auth.py:750
 msgid "Invalid API key"
 msgstr ""
 
-#: kallithea/lib/auth.py:812
+#: kallithea/lib/auth.py:768
+msgid "CSRF token leak has been detected - all form tokens have been expired"
+msgstr ""
+
+#: kallithea/lib/auth.py:813
 msgid "You need to be a registered user to perform this action"
 msgstr ""
 
-#: kallithea/lib/auth.py:844
+#: kallithea/lib/auth.py:843
 msgid "You need to be signed in to view this page"
 msgstr ""
 
-#: kallithea/lib/base.py:490
+#: kallithea/lib/base.py:493
 msgid "Repository not found in the filesystem"
 msgstr ""
 
-#: kallithea/lib/base.py:516 kallithea/lib/helpers.py:622
+#: kallithea/lib/base.py:519 kallithea/lib/helpers.py:623
 msgid "Changeset not found"
 msgstr ""
 
@@ -1061,125 +1068,125 @@
 msgid "No changes detected"
 msgstr ""
 
-#: kallithea/lib/helpers.py:609
+#: kallithea/lib/helpers.py:610
 #, python-format
 msgid "Deleted branch: %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:611
+#: kallithea/lib/helpers.py:612
 #, python-format
 msgid "Created tag: %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:671
+#: kallithea/lib/helpers.py:672
 #, python-format
 msgid "Show all combined changesets %s->%s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:677
+#: kallithea/lib/helpers.py:678
 msgid "Compare view"
 msgstr ""
 
-#: kallithea/lib/helpers.py:696
-msgid "and"
-msgstr ""
-
 #: kallithea/lib/helpers.py:697
+msgid "and"
+msgstr ""
+
+#: kallithea/lib/helpers.py:698
 #, python-format
 msgid "%s more"
 msgstr ""
 
-#: kallithea/lib/helpers.py:698 kallithea/templates/changelog/changelog.html:44
+#: kallithea/lib/helpers.py:699 kallithea/templates/changelog/changelog.html:44
 msgid "revisions"
 msgstr ""
 
-#: kallithea/lib/helpers.py:722
+#: kallithea/lib/helpers.py:723
 #, python-format
 msgid "Fork name %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:742
+#: kallithea/lib/helpers.py:743
 #, python-format
 msgid "Pull request %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:752
+#: kallithea/lib/helpers.py:753
 msgid "[deleted] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:754 kallithea/lib/helpers.py:766
+#: kallithea/lib/helpers.py:755 kallithea/lib/helpers.py:767
 msgid "[created] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:756
+#: kallithea/lib/helpers.py:757
 msgid "[created] repository as fork"
 msgstr ""
 
-#: kallithea/lib/helpers.py:758 kallithea/lib/helpers.py:768
+#: kallithea/lib/helpers.py:759 kallithea/lib/helpers.py:769
 msgid "[forked] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:760 kallithea/lib/helpers.py:770
+#: kallithea/lib/helpers.py:761 kallithea/lib/helpers.py:771
 msgid "[updated] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:762
+#: kallithea/lib/helpers.py:763
 msgid "[downloaded] archive from repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:764
+#: kallithea/lib/helpers.py:765
 msgid "[delete] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:772
+#: kallithea/lib/helpers.py:773
 msgid "[created] user"
 msgstr ""
 
-#: kallithea/lib/helpers.py:774
+#: kallithea/lib/helpers.py:775
 msgid "[updated] user"
 msgstr ""
 
-#: kallithea/lib/helpers.py:776
+#: kallithea/lib/helpers.py:777
 msgid "[created] user group"
 msgstr ""
 
-#: kallithea/lib/helpers.py:778
+#: kallithea/lib/helpers.py:779
 msgid "[updated] user group"
 msgstr ""
 
-#: kallithea/lib/helpers.py:780
+#: kallithea/lib/helpers.py:781
 msgid "[commented] on revision in repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:782
+#: kallithea/lib/helpers.py:783
 msgid "[commented] on pull request for"
 msgstr ""
 
-#: kallithea/lib/helpers.py:784
+#: kallithea/lib/helpers.py:785
 msgid "[closed] pull request for"
 msgstr ""
 
-#: kallithea/lib/helpers.py:786
+#: kallithea/lib/helpers.py:787
 msgid "[pushed] into"
 msgstr ""
 
-#: kallithea/lib/helpers.py:788
+#: kallithea/lib/helpers.py:789
 msgid "[committed via Kallithea] into repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:790
+#: kallithea/lib/helpers.py:791
 msgid "[pulled from remote] into repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:792
+#: kallithea/lib/helpers.py:793
 msgid "[pulled] from"
 msgstr ""
 
-#: kallithea/lib/helpers.py:794
+#: kallithea/lib/helpers.py:795
 msgid "[started following] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:796
+#: kallithea/lib/helpers.py:797
 msgid "[stopped following] repository"
 msgstr ""
 
@@ -1189,8 +1196,8 @@
 msgstr ""
 
 #: kallithea/lib/helpers.py:1128
-#: kallithea/templates/compare/compare_diff.html:65
-#: kallithea/templates/pullrequests/pullrequest_show.html:326
+#: kallithea/templates/compare/compare_diff.html:71
+#: kallithea/templates/pullrequests/pullrequest_show.html:337
 msgid "No files"
 msgstr ""
 
@@ -1214,7 +1221,7 @@
 msgid "chmod"
 msgstr ""
 
-#: kallithea/lib/helpers.py:1444
+#: kallithea/lib/helpers.py:1469
 #, python-format
 msgid ""
 "%s repository is not mapped to db perhaps it was created or renamed from "
@@ -1222,7 +1229,7 @@
 "repositories"
 msgstr ""
 
-#: kallithea/lib/utils2.py:415
+#: kallithea/lib/utils2.py:434
 #, python-format
 msgid "%d year"
 msgid_plural "%d years"
@@ -1230,7 +1237,7 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/lib/utils2.py:416
+#: kallithea/lib/utils2.py:435
 #, python-format
 msgid "%d month"
 msgid_plural "%d months"
@@ -1238,7 +1245,7 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/lib/utils2.py:417
+#: kallithea/lib/utils2.py:436
 #, python-format
 msgid "%d day"
 msgid_plural "%d days"
@@ -1246,7 +1253,7 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/lib/utils2.py:418
+#: kallithea/lib/utils2.py:437
 #, python-format
 msgid "%d hour"
 msgid_plural "%d hours"
@@ -1254,7 +1261,7 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/lib/utils2.py:419
+#: kallithea/lib/utils2.py:438
 #, python-format
 msgid "%d minute"
 msgid_plural "%d minutes"
@@ -1262,7 +1269,7 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/lib/utils2.py:420
+#: kallithea/lib/utils2.py:439
 #, python-format
 msgid "%d second"
 msgid_plural "%d seconds"
@@ -1270,27 +1277,27 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/lib/utils2.py:436
+#: kallithea/lib/utils2.py:455
 #, python-format
 msgid "in %s"
 msgstr ""
 
-#: kallithea/lib/utils2.py:438
+#: kallithea/lib/utils2.py:457
 #, python-format
 msgid "%s ago"
 msgstr ""
 
-#: kallithea/lib/utils2.py:440
+#: kallithea/lib/utils2.py:459
 #, python-format
 msgid "in %s and %s"
 msgstr ""
 
-#: kallithea/lib/utils2.py:443
+#: kallithea/lib/utils2.py:462
 #, python-format
 msgid "%s and %s ago"
 msgstr ""
 
-#: kallithea/lib/utils2.py:446
+#: kallithea/lib/utils2.py:465
 msgid "just now"
 msgstr ""
 
@@ -1389,7 +1396,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1531
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1570
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1620
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1665
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1669
 msgid "Kallithea Administrator"
 msgstr ""
 
@@ -1500,7 +1507,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2063
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2102
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2155
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2229
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2237
 msgid "Approved"
 msgstr ""
 
@@ -1515,7 +1522,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2064
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2103
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2156
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2230
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2238
 msgid "Rejected"
 msgstr ""
 
@@ -1542,7 +1549,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1379
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1418
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1471
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1518
 msgid "top level"
 msgstr ""
 
@@ -1689,7 +1696,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1560
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1599
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1651
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1697
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1701
 msgid "Registration disabled"
 msgstr ""
 
@@ -1716,12 +1723,12 @@
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1645
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1691
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1695
 msgid "Repository creation enabled with write permission to a repository group"
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1646
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1692
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1696
 msgid "Repository creation disabled with write permission to a repository group"
 msgstr ""
 
@@ -1730,106 +1737,106 @@
 msgid "on line %s"
 msgstr ""
 
-#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:169
+#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:170
 msgid "[Mention]"
 msgstr ""
 
-#: kallithea/model/db.py:1667
+#: kallithea/model/db.py:1671
 msgid "Default user has no access to new repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1668
-msgid "Default user has read access to new repositories"
-msgstr ""
-
-#: kallithea/model/db.py:1669
-msgid "Default user has write access to new repositories"
-msgstr ""
-
-#: kallithea/model/db.py:1670
-msgid "Default user has admin access to new repositories"
-msgstr ""
-
 #: kallithea/model/db.py:1672
-msgid "Default user has no access to new repository groups"
+msgid "Default user has read access to new repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1673
-msgid "Default user has read access to new repository groups"
+msgid "Default user has write access to new repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1674
-msgid "Default user has write access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1675
-msgid "Default user has admin access to new repository groups"
+msgid "Default user has admin access to new repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1676
+msgid "Default user has no access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1677
-msgid "Default user has no access to new user groups"
+msgid "Default user has read access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1678
-msgid "Default user has read access to new user groups"
+msgid "Default user has write access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1679
-msgid "Default user has write access to new user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1680
-msgid "Default user has admin access to new user groups"
+msgid "Default user has admin access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1681
+msgid "Default user has no access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1682
-msgid "Only admins can create repository groups"
+msgid "Default user has read access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1683
-msgid "Non-admins can create repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1685
-msgid "Only admins can create user groups"
+msgid "Default user has write access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1684
+msgid "Default user has admin access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1686
-msgid "Non-admins can create user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1688
-msgid "Only admins can create top level repositories"
+msgid "Only admins can create repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1687
+msgid "Non-admins can create repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1689
+msgid "Only admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1690
+msgid "Non-admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1692
+msgid "Only admins can create top level repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1693
 msgid "Non-admins can create top level repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1694
+#: kallithea/model/db.py:1698
 #, fuzzy
 msgid "Only admins can fork repositories"
 msgstr "Chyba při vytváření repozitáře %s"
 
-#: kallithea/model/db.py:1695
+#: kallithea/model/db.py:1699
 #, fuzzy
-msgid "Non-admins can can fork repositories"
+msgid "Non-admins can fork repositories"
 msgstr "Chyba při vytváření repozitáře %s"
 
-#: kallithea/model/db.py:1698
+#: kallithea/model/db.py:1702
 msgid "User registration with manual account activation"
 msgstr ""
 
-#: kallithea/model/db.py:1699
+#: kallithea/model/db.py:1703
 msgid "User registration with automatic account activation"
 msgstr ""
 
-#: kallithea/model/db.py:2228
+#: kallithea/model/db.py:2236
 #, fuzzy
 msgid "Not reviewed"
 msgstr ""
 
-#: kallithea/model/db.py:2231
+#: kallithea/model/db.py:2239
 #, fuzzy
 msgid "Under review"
 msgstr ""
@@ -1852,7 +1859,7 @@
 msgid "Enter %(min)i characters or more"
 msgstr ""
 
-#: kallithea/model/forms.py:160
+#: kallithea/model/forms.py:165
 msgid "Name must not contain only digits"
 msgstr ""
 
@@ -1945,7 +1952,7 @@
 msgid "%(user)s wants you to review pull request %(pr_nice_id)s: %(pr_title)s"
 msgstr ""
 
-#: kallithea/model/scm.py:812
+#: kallithea/model/scm.py:708
 msgid "latest tip"
 msgstr ""
 
@@ -1978,15 +1985,15 @@
 "owners or remove those user groups: %s"
 msgstr ""
 
-#: kallithea/model/user.py:360
+#: kallithea/model/user.py:368
 msgid "Password reset link"
 msgstr ""
 
-#: kallithea/model/user.py:408
+#: kallithea/model/user.py:418
 msgid "Password reset notification"
 msgstr ""
 
-#: kallithea/model/user.py:409
+#: kallithea/model/user.py:419
 #, python-format
 msgid ""
 "The password to your account %s has been changed using password reset "
@@ -1997,168 +2004,168 @@
 msgid "Value cannot be an empty list"
 msgstr ""
 
-#: kallithea/model/validators.py:95
+#: kallithea/model/validators.py:96
 #, python-format
 msgid "Username \"%(username)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:97
+#: kallithea/model/validators.py:98
 #, python-format
 msgid "Username \"%(username)s\" cannot be used"
 msgstr ""
 
-#: kallithea/model/validators.py:99
+#: kallithea/model/validators.py:100
 msgid ""
 "Username may only contain alphanumeric characters underscores, periods or"
 " dashes and must begin with an alphanumeric character or underscore"
 msgstr ""
 
-#: kallithea/model/validators.py:126
+#: kallithea/model/validators.py:127
 msgid "The input is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:133
+#: kallithea/model/validators.py:134
 #, python-format
 msgid "Username %(username)s is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:152
+#: kallithea/model/validators.py:154
 msgid "Invalid user group name"
 msgstr ""
 
-#: kallithea/model/validators.py:153
-#, python-format
-msgid "User group \"%(usergroup)s\" already exists"
-msgstr ""
-
 #: kallithea/model/validators.py:155
+#, python-format
+msgid "User group \"%(usergroup)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:157
 msgid ""
 "user group name may only contain alphanumeric characters underscores, "
 "periods or dashes and must begin with alphanumeric character"
 msgstr ""
 
-#: kallithea/model/validators.py:193
+#: kallithea/model/validators.py:197
 msgid "Cannot assign this group as parent"
 msgstr ""
 
-#: kallithea/model/validators.py:194
+#: kallithea/model/validators.py:198
 #, python-format
 msgid "Group \"%(group_name)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:196
+#: kallithea/model/validators.py:200
 #, python-format
 msgid "Repository with name \"%(group_name)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:254
+#: kallithea/model/validators.py:258
 msgid "Invalid characters (non-ascii) in password"
 msgstr ""
 
-#: kallithea/model/validators.py:269
+#: kallithea/model/validators.py:273
 msgid "Invalid old password"
 msgstr ""
 
-#: kallithea/model/validators.py:285
+#: kallithea/model/validators.py:289
 msgid "Passwords do not match"
 msgstr ""
 
-#: kallithea/model/validators.py:300
+#: kallithea/model/validators.py:304
 msgid "Invalid username or password"
 msgstr ""
 
-#: kallithea/model/validators.py:331
+#: kallithea/model/validators.py:335
 msgid "Token mismatch"
 msgstr ""
 
-#: kallithea/model/validators.py:345
+#: kallithea/model/validators.py:351
 #, python-format
 msgid "Repository name %(repo)s is not allowed"
 msgstr ""
 
-#: kallithea/model/validators.py:347
+#: kallithea/model/validators.py:353
 #, python-format
 msgid "Repository named %(repo)s already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:348
+#: kallithea/model/validators.py:354
 #, python-format
 msgid "Repository \"%(repo)s\" already exists in group \"%(group)s\""
 msgstr ""
 
-#: kallithea/model/validators.py:350
+#: kallithea/model/validators.py:356
 #, python-format
 msgid "Repository group with name \"%(repo)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:465
+#: kallithea/model/validators.py:470
 #, fuzzy
 msgid "Invalid repository URL"
 msgstr "Prázdný repozitář"
 
-#: kallithea/model/validators.py:466
+#: kallithea/model/validators.py:471
 msgid ""
 "Invalid repository URL. It must be a valid http, https, ssh, svn+http or "
 "svn+https URL"
 msgstr ""
 
-#: kallithea/model/validators.py:489
+#: kallithea/model/validators.py:496
 msgid "Fork has to be the same type as parent"
 msgstr ""
 
-#: kallithea/model/validators.py:504
+#: kallithea/model/validators.py:511
 msgid "You don't have permissions to create repository in this group"
 msgstr ""
 
-#: kallithea/model/validators.py:506
+#: kallithea/model/validators.py:513
 msgid "no permission to create repository in root location"
 msgstr ""
 
-#: kallithea/model/validators.py:556
+#: kallithea/model/validators.py:563
 msgid "You don't have permissions to create a group in this location"
 msgstr ""
 
-#: kallithea/model/validators.py:597
+#: kallithea/model/validators.py:604
 msgid "This username or user group name is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:690
+#: kallithea/model/validators.py:697
 msgid "This is not a valid path"
 msgstr ""
 
-#: kallithea/model/validators.py:705
+#: kallithea/model/validators.py:714
 msgid "This email address is already in use"
 msgstr ""
 
-#: kallithea/model/validators.py:725
+#: kallithea/model/validators.py:734
 #, python-format
 msgid "Email address \"%(email)s\" not found"
 msgstr ""
 
-#: kallithea/model/validators.py:762
+#: kallithea/model/validators.py:771
 msgid ""
 "The LDAP Login attribute of the CN must be specified - this is the name "
 "of the attribute that is equivalent to \"username\""
 msgstr ""
 
-#: kallithea/model/validators.py:774
+#: kallithea/model/validators.py:783
 msgid "Please enter a valid IPv4 or IPv6 address"
 msgstr ""
 
-#: kallithea/model/validators.py:775
+#: kallithea/model/validators.py:784
 #, python-format
 msgid "The network size (bits) must be within the range of 0-32 (not %(bits)r)"
 msgstr ""
 
-#: kallithea/model/validators.py:808
+#: kallithea/model/validators.py:817
 msgid "Key name can only consist of letters, underscore, dash or numbers"
 msgstr ""
 
-#: kallithea/model/validators.py:822
+#: kallithea/model/validators.py:831
 msgid "Filename cannot be inside a directory"
 msgstr ""
 
-#: kallithea/model/validators.py:838
+#: kallithea/model/validators.py:847
 #, python-format
 msgid "Plugins %(loaded)s and %(next_to_load)s both export the same name"
 msgstr ""
@@ -2285,7 +2292,7 @@
 #: kallithea/templates/admin/user_groups/user_groups.html:50
 #: kallithea/templates/pullrequests/pullrequest_data.html:16
 #: kallithea/templates/pullrequests/pullrequest_show.html:156
-#: kallithea/templates/pullrequests/pullrequest_show.html:233
+#: kallithea/templates/pullrequests/pullrequest_show.html:244
 #: kallithea/templates/summary/summary.html:134
 msgid "Owner"
 msgstr ""
@@ -2333,7 +2340,7 @@
 #: kallithea/templates/index_base.html:144
 #: kallithea/templates/admin/my_account/my_account_repos.html:61
 #: kallithea/templates/admin/my_account/my_account_watched.html:61
-#: kallithea/templates/base/base.html:140 kallithea/templates/base/root.html:47
+#: kallithea/templates/base/root.html:47
 #: kallithea/templates/bookmarks/bookmarks.html:83
 #: kallithea/templates/branches/branches.html:83
 #: kallithea/templates/journal/journal.html:202
@@ -2343,7 +2350,7 @@
 msgstr ""
 
 #: kallithea/templates/login.html:5 kallithea/templates/login.html:15
-#: kallithea/templates/base/base.html:326
+#: kallithea/templates/base/base.html:414
 msgid "Log In"
 msgstr ""
 
@@ -2358,7 +2365,7 @@
 #: kallithea/templates/admin/users/user_add.html:32
 #: kallithea/templates/admin/users/user_edit_profile.html:24
 #: kallithea/templates/admin/users/users.html:50
-#: kallithea/templates/base/base.html:302
+#: kallithea/templates/base/base.html:390
 #: kallithea/templates/pullrequests/pullrequest_show.html:166
 msgid "Username"
 msgstr ""
@@ -2366,7 +2373,7 @@
 #: kallithea/templates/login.html:33 kallithea/templates/register.html:33
 #: kallithea/templates/admin/my_account/my_account.html:37
 #: kallithea/templates/admin/users/user_add.html:41
-#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:399
 msgid "Password"
 msgstr ""
 
@@ -2378,7 +2385,7 @@
 msgid "Forgot your password ?"
 msgstr ""
 
-#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:322
+#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:410
 msgid "Don't have an account ?"
 msgstr ""
 
@@ -2499,10 +2506,6 @@
 msgid "There are no branches yet"
 msgstr ""
 
-#: kallithea/templates/switch_to_list.html:16
-msgid "Closed Branches"
-msgstr ""
-
 #: kallithea/templates/switch_to_list.html:32
 #: kallithea/templates/tags/tags_data.html:44
 msgid "There are no tags yet"
@@ -2731,12 +2734,12 @@
 msgid "Never"
 msgstr ""
 
-#: kallithea/templates/admin/gists/edit.html:145
+#: kallithea/templates/admin/gists/edit.html:146
 msgid "Update Gist"
 msgstr ""
 
-#: kallithea/templates/admin/gists/edit.html:146
-#: kallithea/templates/changeset/changeset_file_comment.html:81
+#: kallithea/templates/admin/gists/edit.html:147
+#: kallithea/templates/changeset/changeset_file_comment.html:105
 msgid "Cancel"
 msgstr ""
 
@@ -2759,7 +2762,7 @@
 
 #: kallithea/templates/admin/gists/index.html:37
 #: kallithea/templates/admin/gists/show.html:25
-#: kallithea/templates/base/base.html:237
+#: kallithea/templates/base/base.html:321
 msgid "Create New Gist"
 msgstr ""
 
@@ -2847,7 +2850,8 @@
 #: kallithea/templates/admin/settings/settings_hooks.html:36
 #: kallithea/templates/admin/users/user_edit_emails.html:19
 #: kallithea/templates/admin/users/user_edit_ips.html:22
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+#: kallithea/templates/changeset/changeset_file_comment.html:95
 #: kallithea/templates/data_table/_dt_elements.html:129
 #: kallithea/templates/data_table/_dt_elements.html:157
 #: kallithea/templates/data_table/_dt_elements.html:173
@@ -2867,8 +2871,6 @@
 #: kallithea/templates/base/perms_summary.html:43
 #: kallithea/templates/base/perms_summary.html:79
 #: kallithea/templates/base/perms_summary.html:81
-#: kallithea/templates/changeset/changeset_file_comment.html:83
-#: kallithea/templates/changeset/changeset_file_comment.html:192
 #: kallithea/templates/data_table/_dt_elements.html:122
 #: kallithea/templates/data_table/_dt_elements.html:123
 #: kallithea/templates/data_table/_dt_elements.html:150
@@ -2895,13 +2897,12 @@
 msgstr ""
 
 #: kallithea/templates/admin/gists/show.html:86
-#: kallithea/templates/files/files_source.html:73
 msgid "Show as raw"
 msgstr ""
 
 #: kallithea/templates/admin/my_account/my_account.html:5
 #: kallithea/templates/admin/my_account/my_account.html:9
-#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:431
 msgid "My Account"
 msgstr ""
 
@@ -3086,7 +3087,7 @@
 msgstr ""
 
 #: kallithea/templates/admin/notifications/notifications.html:26
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 msgid "Pull Requests"
 msgstr ""
 
@@ -3104,7 +3105,7 @@
 msgstr ""
 
 #: kallithea/templates/admin/notifications/show_notification.html:9
-#: kallithea/templates/base/base.html:342
+#: kallithea/templates/base/base.html:430
 msgid "Notifications"
 msgstr ""
 
@@ -3303,7 +3304,7 @@
 #: kallithea/templates/admin/repos/repo_edit.html:40
 #: kallithea/templates/admin/settings/settings.html:11
 #: kallithea/templates/admin/user_groups/user_group_edit.html:29
-#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:151
+#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:148
 #: kallithea/templates/data_table/_dt_elements.html:45
 #: kallithea/templates/data_table/_dt_elements.html:49
 msgid "Settings"
@@ -3569,6 +3570,11 @@
 msgid "Unlock Repository"
 msgstr "Prázdný repozitář"
 
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:56
+#, python-format
+msgid "Locked by %s on %s"
+msgstr ""
+
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:60
 #, fuzzy
 msgid "Confirm to lock repository."
@@ -3629,10 +3635,6 @@
 msgid "Invalidate Repository Cache"
 msgstr ""
 
-#: kallithea/templates/admin/repos/repo_edit_caches.html:4
-msgid "Confirm to invalidate repository cache."
-msgstr ""
-
 #: kallithea/templates/admin/repos/repo_edit_caches.html:7
 msgid ""
 "Manually invalidate cache for this repository. On first access, the "
@@ -4374,21 +4376,17 @@
 msgid "Files"
 msgstr ""
 
-#: kallithea/templates/base/base.html:138
-msgid "Switch To"
-msgstr ""
-
-#: kallithea/templates/base/base.html:145
-#: kallithea/templates/base/base.html:147
+#: kallithea/templates/base/base.html:142
+#: kallithea/templates/base/base.html:144
 msgid "Options"
 msgstr ""
 
-#: kallithea/templates/base/base.html:155
+#: kallithea/templates/base/base.html:152
 #: kallithea/templates/forks/forks_data.html:21
 msgid "Compare Fork"
 msgstr ""
 
-#: kallithea/templates/base/base.html:157
+#: kallithea/templates/base/base.html:154
 #: kallithea/templates/bookmarks/bookmarks.html:56
 #: kallithea/templates/bookmarks/bookmarks_data.html:13
 #: kallithea/templates/branches/branches.html:56
@@ -4398,111 +4396,116 @@
 msgid "Compare"
 msgstr ""
 
-#: kallithea/templates/base/base.html:159
-#: kallithea/templates/base/base.html:247
+#: kallithea/templates/base/base.html:156
+#: kallithea/templates/base/base.html:331
 #: kallithea/templates/search/search.html:14
 #: kallithea/templates/search/search.html:54
 msgid "Search"
 msgstr ""
 
-#: kallithea/templates/base/base.html:163
+#: kallithea/templates/base/base.html:160
 msgid "Unlock"
 msgstr ""
 
-#: kallithea/templates/base/base.html:165
+#: kallithea/templates/base/base.html:162
 msgid "Lock"
 msgstr ""
 
-#: kallithea/templates/base/base.html:173
+#: kallithea/templates/base/base.html:170
 msgid "Follow"
 msgstr ""
 
+#: kallithea/templates/base/base.html:171
+msgid "Unfollow"
+msgstr ""
+
 #: kallithea/templates/base/base.html:174
-msgid "Unfollow"
-msgstr ""
-
-#: kallithea/templates/base/base.html:177
 #: kallithea/templates/data_table/_dt_elements.html:37
 #: kallithea/templates/data_table/_dt_elements.html:41
 #: kallithea/templates/forks/fork.html:9
 msgid "Fork"
 msgstr ""
 
-#: kallithea/templates/base/base.html:178
+#: kallithea/templates/base/base.html:175
 #: kallithea/templates/pullrequests/pullrequest.html:88
 msgid "Create Pull Request"
 msgstr ""
 
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 #, python-format
 msgid "Show Pull Requests for %s"
 msgstr ""
 
-#: kallithea/templates/base/base.html:221
+#: kallithea/templates/base/base.html:193
+msgid "Switch To"
+msgstr ""
+
+#: kallithea/templates/base/base.html:203
+#: kallithea/templates/base/base.html:485
+msgid "No matches found"
+msgstr ""
+
+#: kallithea/templates/base/base.html:305
 msgid "Show recent activity"
 msgstr ""
 
-#: kallithea/templates/base/base.html:227
-#: kallithea/templates/base/base.html:228
+#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:312
 msgid "Public journal"
 msgstr ""
 
-#: kallithea/templates/base/base.html:233
+#: kallithea/templates/base/base.html:317
 msgid "Show public gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:234
+#: kallithea/templates/base/base.html:318
 msgid "Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:238
+#: kallithea/templates/base/base.html:322
 msgid "All Public Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:240
+#: kallithea/templates/base/base.html:324
 msgid "My Public Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:241
+#: kallithea/templates/base/base.html:325
 msgid "My Private Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:246
+#: kallithea/templates/base/base.html:330
 msgid "Search in repositories"
 msgstr ""
 
-#: kallithea/templates/base/base.html:269
-#: kallithea/templates/base/base.html:270
+#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:354
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:6
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:10
 msgid "My Pull Requests"
 msgstr ""
 
-#: kallithea/templates/base/base.html:289
+#: kallithea/templates/base/base.html:377
 msgid "Not Logged In"
 msgstr ""
 
-#: kallithea/templates/base/base.html:296
+#: kallithea/templates/base/base.html:384
 msgid "Login to Your Account"
 msgstr ""
 
-#: kallithea/templates/base/base.html:319
+#: kallithea/templates/base/base.html:407
 msgid "Forgot password ?"
 msgstr ""
 
-#: kallithea/templates/base/base.html:346
+#: kallithea/templates/base/base.html:434
 msgid "Log Out"
 msgstr ""
 
-#: kallithea/templates/base/base.html:395
-msgid "No matches found"
-msgstr ""
-
-#: kallithea/templates/base/base.html:524
+#: kallithea/templates/base/base.html:615
 msgid "Keyboard shortcuts"
 msgstr ""
 
-#: kallithea/templates/base/base.html:533
+#: kallithea/templates/base/base.html:624
 msgid "Site-wide shortcuts"
 msgstr ""
 
@@ -4605,7 +4608,6 @@
 
 #: kallithea/templates/base/root.html:31
 #, fuzzy
-#| msgid "on pull request"
 msgid "Open New Pull Request from {0}"
 msgstr "Změna stavu-> %s"
 
@@ -4623,6 +4625,7 @@
 
 #: kallithea/templates/base/root.html:35
 #: kallithea/templates/changeset/diff_block.html:8
+#: kallithea/templates/changeset/diff_block.html:21
 msgid "Collapse Diff"
 msgstr ""
 
@@ -4733,51 +4736,54 @@
 #: kallithea/templates/changelog/changelog_summary_data.html:20
 #, python-format
 msgid ""
-"Changeset status: %s\n"
+"Changeset status: %s by %s\n"
 "Click to open associated pull request %s"
 msgstr ""
 
 #: kallithea/templates/changelog/changelog.html:96
-#: kallithea/templates/compare/compare_cs.html:24
-#, python-format
-msgid "Changeset status: %s"
-msgstr ""
-
-#: kallithea/templates/changelog/changelog.html:115
+#: kallithea/templates/changelog/changelog_summary_data.html:24
+#, fuzzy, python-format
+#| msgid "Set changeset status"
+msgid "Changeset status: %s by %s"
+msgstr "Změny"
+
+#: kallithea/templates/changelog/changelog.html:116
 #: kallithea/templates/compare/compare_cs.html:63
 msgid "Expand commit message"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:124
+#: kallithea/templates/changelog/changelog.html:125
 #: kallithea/templates/compare/compare_cs.html:30
 msgid "Changeset has comments"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:134
-#: kallithea/templates/changelog/changelog_summary_data.html:54
+#: kallithea/templates/changelog/changelog.html:135
+#: kallithea/templates/changelog/changelog_summary_data.html:57
 #: kallithea/templates/changeset/changeset.html:94
 #: kallithea/templates/changeset/changeset_range.html:92
 #, python-format
 msgid "Bookmark %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:140
-#: kallithea/templates/changelog/changelog_summary_data.html:60
+#: kallithea/templates/changelog/changelog.html:141
+#: kallithea/templates/changelog/changelog_summary_data.html:63
 #: kallithea/templates/changeset/changeset.html:101
 #: kallithea/templates/changeset/changeset_range.html:98
+#: kallithea/templates/compare/compare_cs.html:69
+#: kallithea/templates/pullrequests/pullrequest_show.html:203
 #, python-format
 msgid "Tag %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:145
-#: kallithea/templates/changelog/changelog_summary_data.html:65
+#: kallithea/templates/changelog/changelog.html:146
+#: kallithea/templates/changelog/changelog_summary_data.html:68
 #: kallithea/templates/changeset/changeset.html:106
 #: kallithea/templates/changeset/changeset_range.html:102
 #, python-format
 msgid "Branch %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:310
+#: kallithea/templates/changelog/changelog.html:311
 msgid "There are no changes yet"
 msgstr ""
 
@@ -4793,7 +4799,7 @@
 
 #: kallithea/templates/changelog/changelog_details.html:6
 #: kallithea/templates/changeset/changeset.html:79
-#: kallithea/templates/changeset/diff_block.html:79
+#: kallithea/templates/changeset/diff_block.html:47
 msgid "Added"
 msgstr ""
 
@@ -4823,22 +4829,22 @@
 msgid "Refs"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:81
+#: kallithea/templates/changelog/changelog_summary_data.html:84
 msgid "Add or upload files directly via Kallithea"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:84
+#: kallithea/templates/changelog/changelog_summary_data.html:87
 #: kallithea/templates/files/files_add.html:21
 #: kallithea/templates/files/files_ypjax.html:9
 msgid "Add New File"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:90
+#: kallithea/templates/changelog/changelog_summary_data.html:93
 #, fuzzy
 msgid "Push new repository"
 msgstr "Prázdný repozitář"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:98
+#: kallithea/templates/changelog/changelog_summary_data.html:101
 msgid "Existing repository?"
 msgstr ""
 
@@ -4856,13 +4862,13 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:50
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #: kallithea/templates/changeset/changeset_range.html:48
 msgid "Changeset status"
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:54
-#: kallithea/templates/changeset/diff_block.html:27
+#: kallithea/templates/changeset/diff_block.html:72
 #: kallithea/templates/files/diff_2way.html:49
 msgid "Raw diff"
 msgstr ""
@@ -4872,7 +4878,7 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:60
-#: kallithea/templates/changeset/diff_block.html:30
+#: kallithea/templates/changeset/diff_block.html:75
 #: kallithea/templates/files/diff_2way.html:52
 msgid "Download diff"
 msgstr ""
@@ -4899,8 +4905,8 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:166
-#: kallithea/templates/compare/compare_diff.html:54
-#: kallithea/templates/pullrequests/pullrequest_show.html:318
+#: kallithea/templates/compare/compare_diff.html:60
+#: kallithea/templates/pullrequests/pullrequest_show.html:329
 #, python-format
 msgid "%s file changed"
 msgid_plural "%s files changed"
@@ -4909,8 +4915,8 @@
 msgstr[2] ""
 
 #: kallithea/templates/changeset/changeset.html:168
-#: kallithea/templates/compare/compare_diff.html:56
-#: kallithea/templates/pullrequests/pullrequest_show.html:320
+#: kallithea/templates/compare/compare_diff.html:62
+#: kallithea/templates/pullrequests/pullrequest_show.html:331
 #, python-format
 msgid "%s file changed with %s insertions and %s deletions"
 msgid_plural "%s files changed with %s insertions and %s deletions"
@@ -4920,13 +4926,13 @@
 
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Show full diff anyway"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset.html:247
-#: kallithea/templates/changeset/changeset.html:284
+#: kallithea/templates/changeset/changeset.html:231
+#: kallithea/templates/changeset/changeset.html:268
 #, fuzzy
 msgid "No revisions"
 msgstr "Neznámá revize %s"
@@ -4945,62 +4951,71 @@
 msgid "on this changeset"
 msgstr "Žádné změny"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
 #, fuzzy
 msgid "Delete comment?"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #, fuzzy
 msgid "Status change"
 msgstr "Změna stavu-> %s"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:59
-msgid "Commenting on line {1}."
+msgid "Commenting on line."
 msgstr ""
 
 #: kallithea/templates/changeset/changeset_file_comment.html:60
-#: kallithea/templates/changeset/changeset_file_comment.html:148
-#, python-format
-msgid "Comments parsed using %s syntax with %s support."
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:62
-msgid "Use @username inside this text to notify another user"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:72
-#: kallithea/templates/changeset/changeset_file_comment.html:184
-msgid "Comment preview"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:77
+msgid ""
+"Comments are in plain text. Use @username inside this text to notify "
+"another user."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:67
+#, fuzzy
+msgid "Set changeset status"
+msgstr "Změny"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:69
+msgid "Vote for pull request status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:75
+#, fuzzy
+msgid "No change"
+msgstr "Žádné změny"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:88
+#, fuzzy
+msgid "Finish pull request"
+msgstr "Změna stavu-> %s"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:91
+#, fuzzy
+msgid "Close"
+msgstr "(zavřeno)"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:103
 msgid "Submitting ..."
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:80
-#: kallithea/templates/changeset/changeset_file_comment.html:190
+#: kallithea/templates/changeset/changeset_file_comment.html:104
 msgid "Comment"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:82
-#: kallithea/templates/changeset/changeset_file_comment.html:191
-msgid "Preview"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "You need to be logged in to comment."
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "Login now"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:94
+#: kallithea/templates/changeset/changeset_file_comment.html:116
 msgid "Hide"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:106
+#: kallithea/templates/changeset/changeset_file_comment.html:128
 #, python-format
 msgid "%d comment"
 msgid_plural "%d comments"
@@ -5008,7 +5023,7 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:107
+#: kallithea/templates/changeset/changeset_file_comment.html:129
 #, fuzzy, python-format
 msgid "%d inline"
 msgid_plural "%d inline"
@@ -5016,7 +5031,7 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:108
+#: kallithea/templates/changeset/changeset_file_comment.html:130
 #, python-format
 msgid "%d general"
 msgid_plural "%d general"
@@ -5024,29 +5039,6 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:150
-msgid "Use @username inside this text to notify another user."
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:157
-msgid "Vote for pull request status"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:159
-#, fuzzy
-msgid "Set changeset status"
-msgstr "Změny"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:163
-#, fuzzy
-msgid "No change"
-msgstr "Žádné změny"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:176
-#, fuzzy
-msgid "Close"
-msgstr "(zavřeno)"
-
 #: kallithea/templates/changeset/changeset_range.html:5
 #, python-format
 msgid "%s Changesets"
@@ -5056,29 +5048,28 @@
 msgid "Files affected"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:21
+#: kallithea/templates/changeset/diff_block.html:54
+msgid "Deleted"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:57
+msgid "Renamed"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:66
 #: kallithea/templates/files/diff_2way.html:43
 msgid "Show full diff for this file"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:24
-#: kallithea/templates/changeset/diff_block.html:98
+#: kallithea/templates/changeset/diff_block.html:69
 #: kallithea/templates/files/diff_2way.html:46
 msgid "Show full side-by-side diff for this file"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:38
+#: kallithea/templates/changeset/diff_block.html:83
 msgid "Show inline comments"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:86
-msgid "Deleted"
-msgstr ""
-
-#: kallithea/templates/changeset/diff_block.html:89
-msgid "Renamed"
-msgstr ""
-
 #: kallithea/templates/compare/compare_cs.html:4
 msgid "No changesets"
 msgstr ""
@@ -5087,6 +5078,11 @@
 msgid "Ancestor"
 msgstr ""
 
+#: kallithea/templates/compare/compare_cs.html:24
+#, python-format
+msgid "Changeset status: %s"
+msgstr ""
+
 #: kallithea/templates/compare/compare_cs.html:44
 msgid "First (oldest) changeset in this list"
 msgstr ""
@@ -5099,29 +5095,29 @@
 msgid "Position in this list of changesets"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:76
+#: kallithea/templates/compare/compare_cs.html:85
 msgid "Show merge diff"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:86
-#: kallithea/templates/pullrequests/pullrequest_show.html:310
+#: kallithea/templates/compare/compare_cs.html:95
+#: kallithea/templates/pullrequests/pullrequest_show.html:321
 msgid "Common ancestor"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:90
-msgid "No common ancestor found - repositories are unrelated"
-msgstr ""
-
-#: kallithea/templates/compare/compare_cs.html:98
-msgid "is"
-msgstr ""
-
 #: kallithea/templates/compare/compare_cs.html:99
+msgid "No common ancestor found - repositories are unrelated"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:107
+msgid "is"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:108
 #, fuzzy, python-format
 msgid "%s changesets"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:100
+#: kallithea/templates/compare/compare_cs.html:109
 msgid "behind"
 msgstr ""
 
@@ -5132,20 +5128,20 @@
 msgstr ""
 
 #: kallithea/templates/compare/compare_diff.html:13
-#: kallithea/templates/compare/compare_diff.html:35
+#: kallithea/templates/compare/compare_diff.html:41
 msgid "Compare Revisions"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:33
+#: kallithea/templates/compare/compare_diff.html:39
 msgid "Swap"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:42
+#: kallithea/templates/compare/compare_diff.html:48
 msgid "Compare revisions, branches, bookmarks, or tags."
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:47
-#: kallithea/templates/pullrequests/pullrequest_show.html:305
+#: kallithea/templates/compare/compare_diff.html:53
+#: kallithea/templates/pullrequests/pullrequest_show.html:316
 #, python-format
 msgid "Showing %s commit"
 msgid_plural "Showing %s commits"
@@ -5153,8 +5149,8 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
 msgid "Show full diff"
 msgstr ""
 
@@ -5213,17 +5209,23 @@
 msgid "We have received a request to reset the password for your account."
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:7
-msgid "To set a new password, click the following link"
+#: kallithea/templates/email_templates/password_reset.html:8
+msgid ""
+"This account is however managed outside this system and the password "
+"cannot be changed here."
 msgstr ""
 
 #: kallithea/templates/email_templates/password_reset.html:10
+msgid "To set a new password, click the following link"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:13
 msgid ""
 "Should you not be able to use the link above, please type the following "
 "code into the password reset form"
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:12
+#: kallithea/templates/email_templates/password_reset.html:16
 msgid ""
 "If it weren't you who requested the password reset, just disregard this "
 "message."
@@ -5306,7 +5308,7 @@
 msgstr ""
 
 #: kallithea/templates/files/files_add.html:53
-msgid "New file mode"
+msgid "New file type"
 msgstr ""
 
 #: kallithea/templates/files/files_add.html:64
@@ -5439,8 +5441,16 @@
 msgid "Binary file (%s)"
 msgstr ""
 
-#: kallithea/templates/files/files_source.html:73
-msgid "File is too big to display"
+#: kallithea/templates/files/files_source.html:74
+msgid "File is too big to display."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:76
+msgid "Show full annotation anyway."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:78
+msgid "Show as raw."
 msgstr ""
 
 #: kallithea/templates/files/files_ypjax.html:5
@@ -5705,42 +5715,48 @@
 msgid "Current revision - no change"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:213
+#: kallithea/templates/pullrequests/pullrequest_show.html:215
+msgid ""
+"Pull requests do not change once created. Select a revision and save to "
+"replace this pull request with a new one."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:224
 msgid "Pull Request Reviewers"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:238
+#: kallithea/templates/pullrequests/pullrequest_show.html:249
 #, fuzzy
 msgid "Remove reviewer"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:250
-msgid "Type name of reviewer to add"
-msgstr ""
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:258
-#, fuzzy
-msgid "Potential Reviewers"
-msgstr ""
-
 #: kallithea/templates/pullrequests/pullrequest_show.html:261
+msgid "Type name of reviewer to add"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:269
+#, fuzzy
+msgid "Potential Reviewers"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:272
 msgid "Click to add the repository owner as reviewer:"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:284
+#: kallithea/templates/pullrequests/pullrequest_show.html:295
 msgid "Save Changes"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:285
-msgid "Save as New Pull Request"
-msgstr ""
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:286
+#: kallithea/templates/pullrequests/pullrequest_show.html:296
+msgid "Save Updates as New Pull Request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:297
 #, fuzzy
 msgid "Cancel Changes"
 msgstr "Žádné změny"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#: kallithea/templates/pullrequests/pullrequest_show.html:307
 msgid "Pull Request Content"
 msgstr ""
 
@@ -5750,9 +5766,9 @@
 msgstr ""
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:11
-#, python-format
-msgid "Pull Requests from %s'"
-msgstr ""
+#, fuzzy, python-format
+msgid "Pull Requests from '%s'"
+msgstr "Změna stavu-> %s"
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:13
 #, python-format
@@ -6047,8 +6063,6 @@
 #~ msgstr ""
 
 #~ msgid ""
-#~ "_: \n"
-#~ ""
 #~ msgstr ""
 
 #~ msgid "%(user)s wants you to review pull request #%(pr_id)s: %(pr_title)s"
@@ -6324,39 +6338,12 @@
 #~ msgid "Your password reset link was sent"
 #~ msgstr ""
 
-#~ msgid ""
-#~ "Your password reset was successful, new"
-#~ " password has been sent to your "
-#~ "email"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " changeset %(short_id)s on %(branch)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Added by %(pr_username)s] %(repo_name)s pull"
-#~ " request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " pull request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
 #~ msgid "Your new password"
 #~ msgstr ""
 
 #~ msgid "Your new Kallithea password:%s"
 #~ msgstr ""
 
-#~ msgid ""
-#~ "Password reset link will be sent "
-#~ "to the email address matching your "
-#~ "username."
-#~ msgstr ""
-
 #~ msgid "Open New Pull Request for Selected Changesets"
 #~ msgstr ""
 
@@ -6377,3 +6364,51 @@
 
 #~ msgid "Created by"
 #~ msgstr ""
+
+#~ msgid "You can only delete files with revision being a valid branch "
+#~ msgstr ""
+
+#~ msgid "You can only edit files with revision being a valid branch "
+#~ msgstr ""
+
+#~ msgid "This pull request can be updated with changes on %s:"
+#~ msgstr ""
+
+#~ msgid "Confirm to invalidate repository cache."
+#~ msgstr ""
+
+#~ msgid "Commenting on line {1}."
+#~ msgstr ""
+
+#~ msgid "Comments parsed using %s syntax with %s support."
+#~ msgstr ""
+
+#~ msgid "Use @username inside this text to notify another user"
+#~ msgstr ""
+
+#~ msgid "Comment preview"
+#~ msgstr ""
+
+#~ msgid "Preview"
+#~ msgstr ""
+
+#~ msgid "Use @username inside this text to notify another user."
+#~ msgstr ""
+
+#~ msgid "New file mode"
+#~ msgstr ""
+
+#~ msgid "File is too big to display"
+#~ msgstr ""
+
+#~ msgid "Save as New Pull Request"
+#~ msgstr ""
+
+#~ msgid "Pull Requests from %s'"
+#~ msgstr ""
+
+#~ msgid ""
+#~ "Changeset status: %s\n"
+#~ "Click to open associated pull request %s"
+#~ msgstr ""
+
--- a/kallithea/i18n/de/LC_MESSAGES/kallithea.po	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/i18n/de/LC_MESSAGES/kallithea.po	Fri Nov 18 01:11:13 2016 +0100
@@ -7,24 +7,24 @@
 msgstr ""
 "Project-Id-Version: Kallithea 0.3\n"
 "Report-Msgid-Bugs-To: translations@kallithea-scm.org\n"
-"POT-Creation-Date: 2015-09-08 10:34+0200\n"
-"PO-Revision-Date: 2015-09-08 10:56+0200\n"
-"Last-Translator: Robert Rauch <mail@robertrauch.de>\n"
+"POT-Creation-Date: 2016-03-14 16:51+0100\n"
+"PO-Revision-Date: 2016-03-21 00:29+0000\n"
+"Last-Translator: Robert Martinez <ntttq@inboxen.org>\n"
 "Language-Team: German "
-"<https://hosted.weblate.org/projects/kallithea/stable/de/>\n"
+"<https://hosted.weblate.org/projects/kallithea/kallithea/de/>\n"
 "Language: de\n"
 "MIME-Version: 1.0\n"
 "Content-Type: text/plain; charset=UTF-8\n"
 "Content-Transfer-Encoding: 8bit\n"
 "Plural-Forms: nplurals=2; plural=n != 1;\n"
-"X-Generator: Weblate 2.4-dev\n"
-
-#: kallithea/controllers/changelog.py:86
-#: kallithea/controllers/pullrequests.py:241 kallithea/lib/base.py:512
+"X-Generator: Weblate 2.6-dev\n"
+
+#: kallithea/controllers/changelog.py:85
+#: kallithea/controllers/pullrequests.py:240 kallithea/lib/base.py:515
 msgid "There are no changesets yet"
 msgstr "Es gibt noch keine Änderungssätze"
 
-#: kallithea/controllers/changelog.py:166
+#: kallithea/controllers/changelog.py:164
 #: kallithea/controllers/admin/permissions.py:61
 #: kallithea/controllers/admin/permissions.py:65
 #: kallithea/controllers/admin/permissions.py:69
@@ -36,50 +36,40 @@
 msgid "None"
 msgstr "Keine"
 
-#: kallithea/controllers/changelog.py:169 kallithea/controllers/files.py:197
+#: kallithea/controllers/changelog.py:167 kallithea/controllers/files.py:198
 msgid "(closed)"
 msgstr "(geschlossen)"
 
-#: kallithea/controllers/changeset.py:89
+#: kallithea/controllers/changeset.py:88
 msgid "Show whitespace"
 msgstr "Zeige unsichtbare Zeichen"
 
-#: kallithea/controllers/changeset.py:96 kallithea/controllers/changeset.py:103
+#: kallithea/controllers/changeset.py:95 kallithea/controllers/changeset.py:102
 #: kallithea/templates/files/diff_2way.html:55
 msgid "Ignore whitespace"
 msgstr "Ignoriere unsichtbare Zeichen"
 
-#: kallithea/controllers/changeset.py:169
-#, python-format
-#| msgid "increase diff context to %(num)s lines"
+#: kallithea/controllers/changeset.py:168
+#, python-format
 msgid "Increase diff context to %(num)s lines"
 msgstr "Erhöhe diff-Kontext auf %(num)s Zeilen"
 
-#: kallithea/controllers/changeset.py:212 kallithea/controllers/files.py:97
-#: kallithea/controllers/files.py:117 kallithea/controllers/files.py:743
+#: kallithea/controllers/changeset.py:233 kallithea/controllers/files.py:97
+#: kallithea/controllers/files.py:117 kallithea/controllers/files.py:744
 msgid "Such revision does not exist for this repository"
 msgstr "Die angegebene Version existiert nicht in diesem Repository"
 
-#: kallithea/controllers/changeset.py:383
-msgid ""
-"Changing status on a changeset associated with a closed pull request is "
-"not allowed"
-msgstr ""
-"Eine Änderung des Status eines Änderungssatzes, der mit einem geschlossen"
-" Pull-Request assoziert ist, ist nicht erlaubt"
-
-#: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:42
+#: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:41
 msgid "Select changeset"
 msgstr "Änderungssätze auswählen"
 
-#: kallithea/controllers/compare.py:258
+#: kallithea/controllers/compare.py:261
 msgid "Cannot compare repositories without using common ancestor"
 msgstr ""
 "Ohne einen gemeinsamen Vorfahren ist ein Vergleich der Repositories nicht"
 " möglich"
 
 #: kallithea/controllers/error.py:71
-#| msgid "revisions"
 msgid "No response"
 msgstr "Keine Rückmeldung"
 
@@ -126,10 +116,10 @@
 #: kallithea/controllers/feed.py:87
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
-#: kallithea/templates/pullrequests/pullrequest_show.html:335
-#: kallithea/templates/pullrequests/pullrequest_show.html:359
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Changeset was too big and was cut off..."
 msgstr "Der Änderungssatz war zu groß und wurde abgeschnitten..."
 
@@ -147,103 +137,104 @@
 msgid "There are no files yet. %s"
 msgstr "Es gibt hier noch keine Dateien. %s"
 
-#: kallithea/controllers/files.py:194
+#: kallithea/controllers/files.py:195
 #, python-format
 msgid "%s at %s"
 msgstr "%s auf %s"
 
-#: kallithea/controllers/files.py:306 kallithea/controllers/files.py:366
-#: kallithea/controllers/files.py:433
+#: kallithea/controllers/files.py:307 kallithea/controllers/files.py:367
+#: kallithea/controllers/files.py:434
 #, python-format
 msgid "This repository has been locked by %s on %s"
 msgstr "Dieses Repository ist von %s am %s gesperrt worden"
 
-#: kallithea/controllers/files.py:318
-msgid "You can only delete files with revision being a valid branch "
+#: kallithea/controllers/files.py:319
+#, fuzzy
+msgid "You can only delete files with revision being a valid branch"
 msgstr "Du kannst nur Dateien löschen, deren Revision ein gültiger Branch ist "
 
-#: kallithea/controllers/files.py:329
+#: kallithea/controllers/files.py:330
 #, python-format
 msgid "Deleted file %s via Kallithea"
 msgstr "Datei %s via Kallithea gelöscht"
 
-#: kallithea/controllers/files.py:351
+#: kallithea/controllers/files.py:352
 #, python-format
 msgid "Successfully deleted file %s"
 msgstr "Datei %s erfolgreich gelöscht"
 
-#: kallithea/controllers/files.py:355 kallithea/controllers/files.py:421
-#: kallithea/controllers/files.py:502
+#: kallithea/controllers/files.py:356 kallithea/controllers/files.py:422
+#: kallithea/controllers/files.py:503
 msgid "Error occurred during commit"
 msgstr "Während des Commits trat ein Fehler auf"
 
-#: kallithea/controllers/files.py:378
-msgid "You can only edit files with revision being a valid branch "
-msgstr ""
-"Du kannst nur Dateien bearbeiten, deren Revision ein gültiger Branch ist "
-
-#: kallithea/controllers/files.py:392
+#: kallithea/controllers/files.py:379
+#, fuzzy
+msgid "You can only edit files with revision being a valid branch"
+msgstr "Du kannst nur Dateien bearbeiten, deren Revision ein gültiger Branch ist "
+
+#: kallithea/controllers/files.py:393
 #, python-format
 msgid "Edited file %s via Kallithea"
 msgstr "Datei %s via Kallithea editiert"
 
-#: kallithea/controllers/files.py:408
+#: kallithea/controllers/files.py:409
 msgid "No changes"
 msgstr "Keine Änderungen"
 
-#: kallithea/controllers/files.py:417 kallithea/controllers/files.py:491
+#: kallithea/controllers/files.py:418 kallithea/controllers/files.py:492
 #, python-format
 msgid "Successfully committed to %s"
 msgstr "Der Commit zu %s war erfolgreich"
 
-#: kallithea/controllers/files.py:444
+#: kallithea/controllers/files.py:445
 msgid "Added file via Kallithea"
 msgstr "Datei via Kallithea hinzugefügt"
 
-#: kallithea/controllers/files.py:465
+#: kallithea/controllers/files.py:466
 msgid "No content"
 msgstr "Kein Inhalt"
 
-#: kallithea/controllers/files.py:469
+#: kallithea/controllers/files.py:470
 msgid "No filename"
 msgstr "Kein Dateiname"
 
-#: kallithea/controllers/files.py:494
+#: kallithea/controllers/files.py:495
 msgid "Location must be relative path and must not contain .. in path"
 msgstr "Der Ort muss ein relativer Pfad sein und darf nicht .. enthalten"
 
-#: kallithea/controllers/files.py:527
+#: kallithea/controllers/files.py:528
 msgid "Downloads disabled"
 msgstr "Downloads gesperrt"
 
-#: kallithea/controllers/files.py:538
+#: kallithea/controllers/files.py:539
 #, python-format
 msgid "Unknown revision %s"
 msgstr "Unbekannte Revision %s"
 
-#: kallithea/controllers/files.py:540
+#: kallithea/controllers/files.py:541
 msgid "Empty repository"
 msgstr "Leeres Repository"
 
-#: kallithea/controllers/files.py:542
+#: kallithea/controllers/files.py:543
 msgid "Unknown archive type"
 msgstr "Unbekannter Archivtyp"
 
-#: kallithea/controllers/files.py:772
+#: kallithea/controllers/files.py:773
 #: kallithea/templates/changeset/changeset_range.html:9
 #: kallithea/templates/email_templates/pull_request.html:15
 #: kallithea/templates/pullrequests/pullrequest.html:97
 msgid "Changesets"
 msgstr "Änderungssätze"
 
-#: kallithea/controllers/files.py:773 kallithea/controllers/pullrequests.py:176
-#: kallithea/model/scm.py:821 kallithea/templates/switch_to_list.html:3
+#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:175
+#: kallithea/model/scm.py:716 kallithea/templates/switch_to_list.html:3
 #: kallithea/templates/branches/branches.html:10
 msgid "Branches"
 msgstr "Entwicklungszweige"
 
-#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:177
-#: kallithea/model/scm.py:832 kallithea/templates/switch_to_list.html:25
+#: kallithea/controllers/files.py:775 kallithea/controllers/pullrequests.py:176
+#: kallithea/model/scm.py:727 kallithea/templates/switch_to_list.html:25
 #: kallithea/templates/tags/tags.html:10
 msgid "Tags"
 msgstr "Tags"
@@ -257,31 +248,35 @@
 msgid "Groups"
 msgstr "Gruppen"
 
-#: kallithea/controllers/home.py:89
+#: kallithea/controllers/home.py:94
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:106
 #: kallithea/templates/admin/repos/repo_add.html:12
 #: kallithea/templates/admin/repos/repo_add.html:16
 #: kallithea/templates/admin/repos/repos.html:9
 #: kallithea/templates/admin/users/user_edit_advanced.html:6
 #: kallithea/templates/base/base.html:60 kallithea/templates/base/base.html:77
-#: kallithea/templates/base/base.html:131
-#: kallithea/templates/base/base.html:397
-#: kallithea/templates/base/base.html:569
+#: kallithea/templates/base/base.html:124
+#: kallithea/templates/base/base.html:479
+#: kallithea/templates/base/base.html:653
 msgid "Repositories"
 msgstr "Repositories"
 
-#: kallithea/controllers/home.py:130
+#: kallithea/controllers/home.py:139
 #: kallithea/templates/files/files_add.html:32
 #: kallithea/templates/files/files_delete.html:23
 #: kallithea/templates/files/files_edit.html:32
 msgid "Branch"
 msgstr "Zweig"
 
-#: kallithea/controllers/home.py:136
+#: kallithea/controllers/home.py:145 kallithea/templates/switch_to_list.html:16
+msgid "Closed Branches"
+msgstr "Geschlossene Branches"
+
+#: kallithea/controllers/home.py:151
 msgid "Tag"
 msgstr "Marke"
 
-#: kallithea/controllers/home.py:142
+#: kallithea/controllers/home.py:157
 msgid "Bookmark"
 msgstr "Lesezeichen"
 
@@ -292,98 +287,100 @@
 msgstr "Öffentliches Logbuch"
 
 #: kallithea/controllers/journal.py:115 kallithea/controllers/journal.py:157
-#: kallithea/templates/base/base.html:229
+#: kallithea/templates/base/base.html:306
 #: kallithea/templates/journal/journal.html:4
 #: kallithea/templates/journal/journal.html:12
 msgid "Journal"
 msgstr "Logbuch"
 
-#: kallithea/controllers/login.py:150 kallithea/controllers/login.py:196
-#| msgid "bad captcha"
+#: kallithea/controllers/login.py:144 kallithea/controllers/login.py:190
 msgid "Bad captcha"
 msgstr "Falsches Captcha"
 
-#: kallithea/controllers/login.py:156
-msgid "You have successfully registered into Kallithea"
-msgstr "Sie haben sich erfolgreich bei Kallithea registriert"
-
-#: kallithea/controllers/login.py:201
-msgid "Your password reset link was sent"
-msgstr "Ihr Passwort Zurücksetzen link wurde versendet"
-
-#: kallithea/controllers/login.py:222
-msgid ""
-"Your password reset was successful, new password has been sent to your "
-"email"
-msgstr ""
-"Das Zurücksetzen des Passworted war erfolgreich, ein neues Passwort wurde"
-" an ihre EMail Addresse gesendet"
-
-#: kallithea/controllers/pullrequests.py:124
+#: kallithea/controllers/login.py:150
+msgid "You have successfully registered with %s"
+msgstr "Sie haben sich erfolgreich bei %s registriert"
+
+#: kallithea/controllers/login.py:195
+#, fuzzy
+msgid "A password reset confirmation code has been sent"
+msgstr "Ihr Link um das Passwort zurückzusetzen wurde versendet"
+
+#: kallithea/controllers/login.py:244
+#, fuzzy
+msgid "Invalid password reset token"
+msgstr "Link zum Zurücksetzen des Passworts"
+
+#: kallithea/controllers/login.py:249
+#: kallithea/controllers/admin/my_account.py:167
+msgid "Successfully updated password"
+msgstr "Erfolgreich Kennwort geändert"
+
+#: kallithea/controllers/pullrequests.py:123
 #, python-format
 msgid "%s (closed)"
 msgstr "%s (geschlossen)"
 
-#: kallithea/controllers/pullrequests.py:152
+#: kallithea/controllers/pullrequests.py:151
 #: kallithea/templates/changeset/changeset.html:12
 #: kallithea/templates/email_templates/changeset_comment.html:17
 msgid "Changeset"
 msgstr "Änderungssatz"
 
-#: kallithea/controllers/pullrequests.py:173
+#: kallithea/controllers/pullrequests.py:172
 msgid "Special"
 msgstr "Spezial"
 
-#: kallithea/controllers/pullrequests.py:174
+#: kallithea/controllers/pullrequests.py:173
 msgid "Peer branches"
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:175 kallithea/model/scm.py:827
+msgstr "Branches anderer"
+
+#: kallithea/controllers/pullrequests.py:174 kallithea/model/scm.py:722
 #: kallithea/templates/switch_to_list.html:38
 #: kallithea/templates/bookmarks/bookmarks.html:10
 msgid "Bookmarks"
 msgstr "Lesezeichen"
 
-#: kallithea/controllers/pullrequests.py:306
+#: kallithea/controllers/pullrequests.py:312
 #, python-format
 msgid "Error creating pull request: %s"
 msgstr "Fehler beim Erstellen des Pull-Requests: %s"
 
-#: kallithea/controllers/pullrequests.py:352
-#: kallithea/controllers/pullrequests.py:499
+#: kallithea/controllers/pullrequests.py:358
+#: kallithea/controllers/pullrequests.py:505
 msgid "No description"
 msgstr "Keine Beschreibung"
 
-#: kallithea/controllers/pullrequests.py:359
+#: kallithea/controllers/pullrequests.py:365
 msgid "Successfully opened new pull request"
 msgstr "Es wurde erfolgreich ein neuer Pullrequest eröffnet"
 
-#: kallithea/controllers/pullrequests.py:362
-#: kallithea/controllers/pullrequests.py:449
-#: kallithea/controllers/pullrequests.py:504
+#: kallithea/controllers/pullrequests.py:368
+#: kallithea/controllers/pullrequests.py:455
+#: kallithea/controllers/pullrequests.py:512
 #, python-format
 msgid "Invalid reviewer \"%s\" specified"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:365
-#: kallithea/controllers/pullrequests.py:452
+#: kallithea/controllers/pullrequests.py:371
+#: kallithea/controllers/pullrequests.py:458
 msgid "Error occurred while creating pull request"
 msgstr "Während des Erstellens des Pull Requests trat ein Fehler auf"
 
-#: kallithea/controllers/pullrequests.py:397
+#: kallithea/controllers/pullrequests.py:403
 msgid "Missing changesets since the previous pull request:"
 msgstr "Fehlende Changesets seit letztem Pull Request:"
 
-#: kallithea/controllers/pullrequests.py:404
+#: kallithea/controllers/pullrequests.py:410
 #, python-format
 msgid "New changesets on %s %s since the previous pull request:"
 msgstr "Neue Changesets in %s %s seit dem letzten Pull Request:"
 
-#: kallithea/controllers/pullrequests.py:411
+#: kallithea/controllers/pullrequests.py:417
 msgid "Ancestor didn't change - show diff since previous version:"
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:418
+msgstr "Vorgänger unverändert - zeige Diff zu lezter Version:"
+
+#: kallithea/controllers/pullrequests.py:424
 #, python-format
 msgid ""
 "This pull request is based on another %s revision and there is no simple "
@@ -392,62 +389,67 @@
 "Dieser Pull Request basiert auf einer anderen %s Revision. Daher ist kein"
 " Simple Diff verfügbar."
 
-#: kallithea/controllers/pullrequests.py:420
+#: kallithea/controllers/pullrequests.py:426
 #, python-format
 msgid "No changes found on %s %s since previous version."
 msgstr "Keine Änderungen seit der letzten Version gefunden in %s %s."
 
-#: kallithea/controllers/pullrequests.py:458
+#: kallithea/controllers/pullrequests.py:464
 #, python-format
 msgid "Closed, replaced by %s ."
 msgstr "Geschlossen, ersetzt durch %s."
 
-#: kallithea/controllers/pullrequests.py:466
+#: kallithea/controllers/pullrequests.py:472
 msgid "Pull request update created"
 msgstr "Pull Request Update erstellt"
 
-#: kallithea/controllers/pullrequests.py:508
+#: kallithea/controllers/pullrequests.py:516
 msgid "Pull request updated"
 msgstr "Pull Request aktualisiert"
 
-#: kallithea/controllers/pullrequests.py:523
+#: kallithea/controllers/pullrequests.py:531
 msgid "Successfully deleted pull request"
 msgstr "Erfolgreich Pull-Request gelöscht"
 
-#: kallithea/controllers/pullrequests.py:582
+#: kallithea/controllers/pullrequests.py:597
 #, python-format
 msgid "This pull request has already been merged to %s."
 msgstr "Dieser Pull Request wurde bereits in %s integriert."
 
-#: kallithea/controllers/pullrequests.py:584
+#: kallithea/controllers/pullrequests.py:599
 msgid "This pull request has been closed and can not be updated."
 msgstr ""
 "Dieser Pull Request wurde geschlossen und kann daher nicht aktualisiert "
 "werden."
 
-#: kallithea/controllers/pullrequests.py:602
-#, python-format
-msgid "This pull request can be updated with changes on %s:"
-msgstr "Dieser Pull Request kann mit Änderungen in %s aktualisiert werden:"
-
-#: kallithea/controllers/pullrequests.py:605
+#: kallithea/controllers/pullrequests.py:617
+#, python-format
+msgid "The following changes are available on %s:"
+msgstr "Die folgenden Änderungen sind verfügbar unter %s:"
+
+#: kallithea/controllers/pullrequests.py:621
 msgid "No changesets found for updating this pull request."
 msgstr "Keine Changesets gefunden, um den Pull Request zu aktualisieren."
 
-#: kallithea/controllers/pullrequests.py:613
+#: kallithea/controllers/pullrequests.py:629
 #, python-format
 msgid "Note: Branch %s has another head: %s."
 msgstr "Hinweis: Branch %s hat einen anderen Head: %s."
 
-#: kallithea/controllers/pullrequests.py:619
+#: kallithea/controllers/pullrequests.py:635
 msgid "Git pull requests don't support updates yet."
 msgstr "Git Pull Request unterstützen bisher keine Updates."
 
-#: kallithea/controllers/pullrequests.py:710
+#: kallithea/controllers/pullrequests.py:727
 msgid "No permission to change pull request status"
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:715
+msgstr "Keine Berechtigung zum Ändern des Pull Request Status"
+
+#: kallithea/controllers/pullrequests.py:738
+#, fuzzy, python-format
+msgid "Successfully deleted pull request %s"
+msgstr "Erfolgreich Pull-Request gelöscht"
+
+#: kallithea/controllers/pullrequests.py:748
 msgid "Closing."
 msgstr "Schließen."
 
@@ -463,12 +465,12 @@
 msgid "An error occurred during search operation."
 msgstr "Während der Suchoperation trat ein Fehler auf."
 
-#: kallithea/controllers/summary.py:180
+#: kallithea/controllers/summary.py:181
 #: kallithea/templates/summary/summary.html:384
 msgid "No data ready yet"
 msgstr "Es stehen noch keine Daten zur Verfügung"
 
-#: kallithea/controllers/summary.py:183
+#: kallithea/controllers/summary.py:184
 #: kallithea/templates/summary/summary.html:98
 msgid "Statistics are disabled for this repository"
 msgstr "Statistiken sind deaktiviert für dieses Repository"
@@ -489,71 +491,70 @@
 msgid "Error occurred during update of defaults"
 msgstr "Ein Fehler trat beim updaten der Standardeinstellungen auf"
 
-#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/gists.py:58
 #: kallithea/controllers/admin/my_account.py:243
-#: kallithea/controllers/admin/users.py:283
-#| msgid "forever"
+#: kallithea/controllers/admin/users.py:284
 msgid "Forever"
 msgstr "Immer"
 
+#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/my_account.py:244
+#: kallithea/controllers/admin/users.py:285
+msgid "5 minutes"
+msgstr "5 Minuten"
+
 #: kallithea/controllers/admin/gists.py:60
-#: kallithea/controllers/admin/my_account.py:244
-#: kallithea/controllers/admin/users.py:284
-msgid "5 minutes"
-msgstr "5 Minuten"
+#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/users.py:286
+msgid "1 hour"
+msgstr "1 Stunde"
 
 #: kallithea/controllers/admin/gists.py:61
-#: kallithea/controllers/admin/my_account.py:245
-#: kallithea/controllers/admin/users.py:285
-msgid "1 hour"
-msgstr "1 Stunde"
+#: kallithea/controllers/admin/my_account.py:246
+#: kallithea/controllers/admin/users.py:287
+msgid "1 day"
+msgstr "1 Tag"
 
 #: kallithea/controllers/admin/gists.py:62
-#: kallithea/controllers/admin/my_account.py:246
-#: kallithea/controllers/admin/users.py:286
-msgid "1 day"
-msgstr "1 Tag"
-
-#: kallithea/controllers/admin/gists.py:63
 #: kallithea/controllers/admin/my_account.py:247
-#: kallithea/controllers/admin/users.py:287
+#: kallithea/controllers/admin/users.py:288
 msgid "1 month"
 msgstr "1 Monat"
 
-#: kallithea/controllers/admin/gists.py:67
+#: kallithea/controllers/admin/gists.py:66
 #: kallithea/controllers/admin/my_account.py:249
-#: kallithea/controllers/admin/users.py:289
+#: kallithea/controllers/admin/users.py:290
 msgid "Lifetime"
 msgstr "Lebenszeit"
 
-#: kallithea/controllers/admin/gists.py:146
+#: kallithea/controllers/admin/gists.py:145
 msgid "Error occurred during gist creation"
 msgstr "Ein fehler trat auf bei der Erstellung des gist"
 
-#: kallithea/controllers/admin/gists.py:184
+#: kallithea/controllers/admin/gists.py:183
 #, python-format
 msgid "Deleted gist %s"
 msgstr "gist %s gelöscht"
 
-#: kallithea/controllers/admin/gists.py:233
+#: kallithea/controllers/admin/gists.py:232
 msgid "Unmodified"
 msgstr "Ungeändert"
 
-#: kallithea/controllers/admin/gists.py:262
+#: kallithea/controllers/admin/gists.py:261
 msgid "Successfully updated gist content"
 msgstr "Erfolgreich Kerninhalt aktualisiert"
 
-#: kallithea/controllers/admin/gists.py:267
+#: kallithea/controllers/admin/gists.py:266
 msgid "Successfully updated gist data"
 msgstr "Erfolgreich Kerndaten aktualisiert"
 
-#: kallithea/controllers/admin/gists.py:270
+#: kallithea/controllers/admin/gists.py:269
 #, python-format
 msgid "Error occurred during update of gist %s"
 msgstr "Fehler beim Aktualisieren der Kerndaten %s"
 
-#: kallithea/controllers/admin/my_account.py:70 kallithea/model/user.py:208
-#: kallithea/model/user.py:230
+#: kallithea/controllers/admin/my_account.py:70 kallithea/model/user.py:215
+#: kallithea/model/user.py:237
 msgid "You can't edit this user since it's crucial for entire application"
 msgstr ""
 "Sie können diesen Benutzer nicht editieren, da er von entscheidender "
@@ -564,47 +565,43 @@
 msgstr "Ihr Account wurde erfolgreich aktualisiert"
 
 #: kallithea/controllers/admin/my_account.py:144
-#: kallithea/controllers/admin/users.py:204
+#: kallithea/controllers/admin/users.py:201
 #, python-format
 msgid "Error occurred during update of user %s"
 msgstr "Fehler beim Aktualisieren der Benutzer %s"
 
-#: kallithea/controllers/admin/my_account.py:167
-msgid "Successfully updated password"
-msgstr "Erfolgreich Kennwort geändert"
-
 #: kallithea/controllers/admin/my_account.py:178
 msgid "Error occurred during update of user password"
 msgstr "Fehler bei der Änderung des Kennworts"
 
 #: kallithea/controllers/admin/my_account.py:220
-#: kallithea/controllers/admin/users.py:413
+#: kallithea/controllers/admin/users.py:414
 #, python-format
 msgid "Added email %s to user"
 msgstr "Die EMail Addresse %s wurde zum Benutzer hinzugefügt"
 
 #: kallithea/controllers/admin/my_account.py:226
-#: kallithea/controllers/admin/users.py:419
+#: kallithea/controllers/admin/users.py:420
 msgid "An error occurred during email saving"
 msgstr "Währen der Speicherung der EMail Addresse trat ein Fehler auf"
 
 #: kallithea/controllers/admin/my_account.py:235
-#: kallithea/controllers/admin/users.py:431
+#: kallithea/controllers/admin/users.py:432
 msgid "Removed email from user"
 msgstr "Die EMail Addresse wurde vom Benutzer entfernt"
 
 #: kallithea/controllers/admin/my_account.py:259
-#: kallithea/controllers/admin/users.py:306
+#: kallithea/controllers/admin/users.py:307
 msgid "API key successfully created"
 msgstr "API Key wurde erfolgreich erstellt"
 
 #: kallithea/controllers/admin/my_account.py:271
-#: kallithea/controllers/admin/users.py:319
+#: kallithea/controllers/admin/users.py:320
 msgid "API key successfully reset"
 msgstr "API-Schlüssel erfolgreich zurückgesetzt"
 
 #: kallithea/controllers/admin/my_account.py:275
-#: kallithea/controllers/admin/users.py:323
+#: kallithea/controllers/admin/users.py:324
 msgid "API key successfully deleted"
 msgstr "API-Schlüssel erfolgreich gelöscht"
 
@@ -654,10 +651,10 @@
 #: kallithea/templates/admin/users/user_edit_profile.html:105
 #: kallithea/templates/admin/users/users.html:10
 #: kallithea/templates/admin/users/users.html:55
-#: kallithea/templates/base/base.html:259
-#: kallithea/templates/base/base.html:260
-#: kallithea/templates/base/base.html:266
-#: kallithea/templates/base/base.html:267
+#: kallithea/templates/base/base.html:336
+#: kallithea/templates/base/base.html:337
+#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:344
 #: kallithea/templates/base/perms_summary.html:17
 msgid "Admin"
 msgstr "Admin"
@@ -688,7 +685,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1564
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1603
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1655
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1701
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1705
 msgid "Manual activation of external account"
 msgstr "Manuelle Aktivierung externen Kontos"
 
@@ -700,7 +697,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1565
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1604
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1656
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1702
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1706
 msgid "Automatic activation of external account"
 msgstr "Automatische Aktivierung externen Kontos"
 
@@ -721,201 +718,198 @@
 msgid "Error occurred during update of permissions"
 msgstr "Fehler bei der Änderung der globalen Berechtigungen"
 
-#: kallithea/controllers/admin/repo_groups.py:188
+#: kallithea/controllers/admin/repo_groups.py:187
 #, python-format
 msgid "Error occurred during creation of repository group %s"
 msgstr "Fehler bei der Erstellung der Repositoriumsgruppe %s"
 
-#: kallithea/controllers/admin/repo_groups.py:193
+#: kallithea/controllers/admin/repo_groups.py:192
 #, python-format
 msgid "Created repository group %s"
 msgstr "Repositoriumsgruppe %s erstellt"
 
-#: kallithea/controllers/admin/repo_groups.py:250
+#: kallithea/controllers/admin/repo_groups.py:249
 #, python-format
 msgid "Updated repository group %s"
 msgstr "Repositoriumsgruppe %s aktualisiert"
 
-#: kallithea/controllers/admin/repo_groups.py:266
+#: kallithea/controllers/admin/repo_groups.py:265
 #, python-format
 msgid "Error occurred during update of repository group %s"
 msgstr "Fehler bei der Aktualisierung der Repositoriumsgruppe %s"
 
-#: kallithea/controllers/admin/repo_groups.py:284
+#: kallithea/controllers/admin/repo_groups.py:283
 #, python-format
 msgid "This group contains %s repositories and cannot be deleted"
 msgstr "Die Gruppe enthält %s Repositorys und kann nicht gelöscht werden"
 
-#: kallithea/controllers/admin/repo_groups.py:291
+#: kallithea/controllers/admin/repo_groups.py:290
 #, python-format
 msgid "This group contains %s subgroups and cannot be deleted"
 msgstr "Diese Gruppe enthält %s Untergruppen und kann nicht gelöscht werden"
 
-#: kallithea/controllers/admin/repo_groups.py:297
+#: kallithea/controllers/admin/repo_groups.py:296
 #, python-format
 msgid "Removed repository group %s"
 msgstr "Repositoriumsgruppe %s entfernt"
 
-#: kallithea/controllers/admin/repo_groups.py:302
+#: kallithea/controllers/admin/repo_groups.py:301
 #, python-format
 msgid "Error occurred during deletion of repository group %s"
 msgstr "Fehler beim Löschen der Repositoriumsgruppe %s"
 
-#: kallithea/controllers/admin/repo_groups.py:405
-#: kallithea/controllers/admin/repo_groups.py:440
+#: kallithea/controllers/admin/repo_groups.py:404
+#: kallithea/controllers/admin/repo_groups.py:439
 #: kallithea/controllers/admin/user_groups.py:340
 msgid "Cannot revoke permission for yourself as admin"
 msgstr "Als Administrator kann man sich keine Berechtigungen entziehen"
 
-#: kallithea/controllers/admin/repo_groups.py:420
+#: kallithea/controllers/admin/repo_groups.py:419
 msgid "Repository group permissions updated"
 msgstr "Berechtigungen der Repositoriumsgruppe aktualisiert"
 
-#: kallithea/controllers/admin/repo_groups.py:457
-#: kallithea/controllers/admin/repos.py:398
+#: kallithea/controllers/admin/repo_groups.py:456
+#: kallithea/controllers/admin/repos.py:397
 #: kallithea/controllers/admin/user_groups.py:352
 msgid "An error occurred during revoking of permission"
 msgstr "Fehler beim Entzug der Berechtigungen"
 
-#: kallithea/controllers/admin/repos.py:152
+#: kallithea/controllers/admin/repos.py:151
 #, python-format
 msgid "Error creating repository %s"
 msgstr "Fehler beim Erstellen des Repositoriums %s"
 
-#: kallithea/controllers/admin/repos.py:213
+#: kallithea/controllers/admin/repos.py:212
 #, python-format
 msgid "Created repository %s from %s"
 msgstr "Repositorium %s von %s erstellt"
 
-#: kallithea/controllers/admin/repos.py:222
+#: kallithea/controllers/admin/repos.py:221
 #, python-format
 msgid "Forked repository %s as %s"
 msgstr "Aufgespaltenes Repositorium %s zu %s"
 
-#: kallithea/controllers/admin/repos.py:225
+#: kallithea/controllers/admin/repos.py:224
 #, python-format
 msgid "Created repository %s"
 msgstr "Repositorium erzeugt %s"
 
-#: kallithea/controllers/admin/repos.py:262
+#: kallithea/controllers/admin/repos.py:261
 #, python-format
 msgid "Repository %s updated successfully"
 msgstr "Repository %s wurde erfolgreich aktualisiert"
 
-#: kallithea/controllers/admin/repos.py:283
+#: kallithea/controllers/admin/repos.py:282
 #, python-format
 msgid "Error occurred during update of repository %s"
 msgstr "Fehler bei der Aktualisierung des Repositoriums %s"
 
-#: kallithea/controllers/admin/repos.py:310
+#: kallithea/controllers/admin/repos.py:309
 #, python-format
 msgid "Detached %s forks"
 msgstr "%s Spaltung abgetrennt"
 
-#: kallithea/controllers/admin/repos.py:313
+#: kallithea/controllers/admin/repos.py:312
 #, python-format
 msgid "Deleted %s forks"
 msgstr "%s Spaltung gelöscht"
 
-#: kallithea/controllers/admin/repos.py:318
+#: kallithea/controllers/admin/repos.py:317
 #, python-format
 msgid "Deleted repository %s"
 msgstr "Repositorium %s gelöscht"
 
-#: kallithea/controllers/admin/repos.py:321
-#, python-format
-#| msgid "Cannot delete %s it still contains attached forks"
+#: kallithea/controllers/admin/repos.py:320
+#, python-format
 msgid "Cannot delete repository %s which still has forks"
 msgstr "%s konnte nicht gelöscht werden, da es noch Forks besitzt"
 
-#: kallithea/controllers/admin/repos.py:326
+#: kallithea/controllers/admin/repos.py:325
 #, python-format
 msgid "An error occurred during deletion of %s"
 msgstr "Beim Löschen von %s trat ein Fehler auf"
 
-#: kallithea/controllers/admin/repos.py:374
+#: kallithea/controllers/admin/repos.py:373
 msgid "Repository permissions updated"
 msgstr "Repositoriumsberechtigungen aktualisiert"
 
-#: kallithea/controllers/admin/repos.py:430
+#: kallithea/controllers/admin/repos.py:429
 msgid "An error occurred during creation of field"
 msgstr "Fehler während der Erzeugung des Feldes"
 
-#: kallithea/controllers/admin/repos.py:444
+#: kallithea/controllers/admin/repos.py:443
 msgid "An error occurred during removal of field"
 msgstr "Fehler beim Entfernen des Feldes"
 
-#: kallithea/controllers/admin/repos.py:460
+#: kallithea/controllers/admin/repos.py:459
 msgid "-- Not a fork --"
 msgstr "-- Keine Abspaltung --"
 
-#: kallithea/controllers/admin/repos.py:491
+#: kallithea/controllers/admin/repos.py:490
 msgid "Updated repository visibility in public journal"
 msgstr "Sichtbarkeit des Repositorys im Öffentlichen Logbuch aktualisiert"
 
-#: kallithea/controllers/admin/repos.py:495
+#: kallithea/controllers/admin/repos.py:494
 msgid "An error occurred during setting this repository in public journal"
 msgstr ""
 "Es trat ein Fehler während der Aktualisierung der Sicherbarkeit dieses "
 "Repositorys im Öffentlichen Logbuch auf"
 
-#: kallithea/controllers/admin/repos.py:512
+#: kallithea/controllers/admin/repos.py:511
 msgid "Nothing"
 msgstr "Nichts"
 
-#: kallithea/controllers/admin/repos.py:514
+#: kallithea/controllers/admin/repos.py:513
 #, python-format
 msgid "Marked repository %s as fork of %s"
 msgstr "Markiere Repository %s als Abzweig von Repository %s"
 
-#: kallithea/controllers/admin/repos.py:521
+#: kallithea/controllers/admin/repos.py:520
 msgid "An error occurred during this operation"
 msgstr "Während dieser operation trat ein Fehler auf"
 
-#: kallithea/controllers/admin/repos.py:537
-#: kallithea/controllers/admin/repos.py:564
-#| msgid "Repository is not locked"
+#: kallithea/controllers/admin/repos.py:536
+#: kallithea/controllers/admin/repos.py:563
 msgid "Repository has been locked"
 msgstr "Repository wurde gesperrt"
 
-#: kallithea/controllers/admin/repos.py:540
-#: kallithea/controllers/admin/repos.py:561
-#| msgid "Repository is not locked"
+#: kallithea/controllers/admin/repos.py:539
+#: kallithea/controllers/admin/repos.py:560
 msgid "Repository has been unlocked"
 msgstr "Repository nicht mehr gesperrt"
 
-#: kallithea/controllers/admin/repos.py:543
-#: kallithea/controllers/admin/repos.py:568
+#: kallithea/controllers/admin/repos.py:542
+#: kallithea/controllers/admin/repos.py:567
 msgid "An error occurred during unlocking"
 msgstr "Fehler beim Entsperren"
 
-#: kallithea/controllers/admin/repos.py:582
+#: kallithea/controllers/admin/repos.py:581
 msgid "Cache invalidation successful"
 msgstr "Cache Entfernung war erfolgreich"
 
-#: kallithea/controllers/admin/repos.py:586
+#: kallithea/controllers/admin/repos.py:585
 msgid "An error occurred during cache invalidation"
 msgstr "Währen der Cache Invalidierung trat ein Fehler auf"
 
-#: kallithea/controllers/admin/repos.py:601
+#: kallithea/controllers/admin/repos.py:600
 msgid "Pulled from remote location"
 msgstr "Von entferntem Ort übertragen"
 
-#: kallithea/controllers/admin/repos.py:604
+#: kallithea/controllers/admin/repos.py:603
 msgid "An error occurred during pull from remote location"
 msgstr ""
 "Es trat ein Fehler auf während das Repository von einem Entfernten "
 "Speicherort übertragen wurde"
 
-#: kallithea/controllers/admin/repos.py:637
+#: kallithea/controllers/admin/repos.py:636
 msgid "An error occurred during deletion of repository stats"
 msgstr "Während des löschens der Repository Statistiken trat ein Fehler auf"
 
-#: kallithea/controllers/admin/settings.py:170
+#: kallithea/controllers/admin/settings.py:141
 msgid "Updated VCS settings"
 msgstr "VCS-Einstellungen aktualisiert"
 
-#: kallithea/controllers/admin/settings.py:174
+#: kallithea/controllers/admin/settings.py:145
 msgid ""
 "Unable to activate hgsubversion support. The \"hgsubversion\" library is "
 "missing"
@@ -923,55 +917,55 @@
 "hgsubversion-Unterstützung konnte nicht aktiviert werden. Die "
 "\"hgsubversion\"-Bibliothek fehlt"
 
-#: kallithea/controllers/admin/settings.py:180
-#: kallithea/controllers/admin/settings.py:274
+#: kallithea/controllers/admin/settings.py:151
+#: kallithea/controllers/admin/settings.py:248
 msgid "Error occurred while updating application settings"
 msgstr ""
 "Ein Fehler ist während der Aktualisierung der Applikationseinstellungen "
 "aufgetreten"
 
-#: kallithea/controllers/admin/settings.py:213
+#: kallithea/controllers/admin/settings.py:187
 #, python-format
 msgid "Repositories successfully rescanned. Added: %s. Removed: %s."
 msgstr ""
 "Die Repositories wurden erfolgreich überprüft. Hinzugefügt: %s. Entfernt:"
 " %s."
 
-#: kallithea/controllers/admin/settings.py:270
+#: kallithea/controllers/admin/settings.py:244
 msgid "Updated application settings"
 msgstr "Anwendungseinstellungen aktualisiert"
 
-#: kallithea/controllers/admin/settings.py:327
+#: kallithea/controllers/admin/settings.py:301
 msgid "Updated visualisation settings"
 msgstr "Visualisierungseinstellungen aktualisiert"
 
-#: kallithea/controllers/admin/settings.py:332
+#: kallithea/controllers/admin/settings.py:306
 msgid "Error occurred during updating visualisation settings"
 msgstr ""
 "Es ist ein Fehler während der Aktualisierung der Layouteinstellung "
 "aufgetreten"
 
-#: kallithea/controllers/admin/settings.py:358
+#: kallithea/controllers/admin/settings.py:332
 msgid "Please enter email address"
 msgstr "Bitte gebe eine E-Mailadresse an"
 
-#: kallithea/controllers/admin/settings.py:373
+#: kallithea/controllers/admin/settings.py:347
 msgid "Send email task created"
 msgstr "Task zum Versenden von E-Mails erstellt"
 
-#: kallithea/controllers/admin/settings.py:404
+#: kallithea/controllers/admin/settings.py:378
 msgid "Added new hook"
 msgstr "Neuer Hook hinzugefügt"
 
-#: kallithea/controllers/admin/settings.py:418
+#: kallithea/controllers/admin/settings.py:392
 msgid "Updated hooks"
 msgstr "Die Hooks wurden aktutalisiert"
 
+#: kallithea/controllers/admin/settings.py:396
+msgid "Error occurred during hook creation"
+msgstr "Während der Erzeugung des Hooks ist ein Fehler aufgetreten"
+
 #: kallithea/controllers/admin/settings.py:422
-msgid "Error occurred during hook creation"
-msgstr "Während der Erzeugung des Hooks ist ein Fehler aufgetreten"
-
-#: kallithea/controllers/admin/settings.py:448
 msgid "Whoosh reindex task scheduled"
 msgstr "Whoosh Reindizierungs Aufgabe wurde zur Ausführung geplant"
 
@@ -1012,12 +1006,12 @@
 msgstr "Berechtigungen der Benutzergruppe wurden aktualisiert"
 
 #: kallithea/controllers/admin/user_groups.py:440
-#: kallithea/controllers/admin/users.py:382
+#: kallithea/controllers/admin/users.py:383
 msgid "Updated permissions"
 msgstr "Berechtigungen wurden aktualisiert"
 
 #: kallithea/controllers/admin/user_groups.py:444
-#: kallithea/controllers/admin/users.py:386
+#: kallithea/controllers/admin/users.py:387
 msgid "An error occurred during permissions saving"
 msgstr "Es ist ein Fehler während des Speicherns der Berechtigungen aufgetreten"
 
@@ -1031,57 +1025,61 @@
 msgid "Error occurred during creation of user %s"
 msgstr "Während des Erstellens des Benutzers %s ist ein Fehler aufgetreten"
 
-#: kallithea/controllers/admin/users.py:184
+#: kallithea/controllers/admin/users.py:181
 msgid "User updated successfully"
 msgstr "Der Benutzer wurde erfolgreich aktualisiert"
 
-#: kallithea/controllers/admin/users.py:220
+#: kallithea/controllers/admin/users.py:217
 msgid "Successfully deleted user"
 msgstr "Der Nutzer wurde erfolgreich gelöscht"
 
-#: kallithea/controllers/admin/users.py:225
+#: kallithea/controllers/admin/users.py:222
 msgid "An error occurred during deletion of user"
 msgstr "Während der Löschen des Benutzers trat ein Fehler auf"
 
-#: kallithea/controllers/admin/users.py:238
+#: kallithea/controllers/admin/users.py:235
 msgid "The default user cannot be edited"
 msgstr "Der Standard-Benutzer kann nicht bearbeitet werden"
 
-#: kallithea/controllers/admin/users.py:461
+#: kallithea/controllers/admin/users.py:462
 #, python-format
 msgid "Added IP address %s to user whitelist"
 msgstr "Die IP-Adresse %s wurde zur Nutzerwhitelist hinzugefügt"
 
-#: kallithea/controllers/admin/users.py:467
+#: kallithea/controllers/admin/users.py:468
 msgid "An error occurred while adding IP address"
 msgstr "Während des Speicherns der IP-Adresse ist ein Fehler aufgetreten"
 
-#: kallithea/controllers/admin/users.py:481
+#: kallithea/controllers/admin/users.py:482
 msgid "Removed IP address from user whitelist"
 msgstr "IP-Adresse wurde von der Nutzerwhitelist entfernt"
 
-#: kallithea/lib/auth.py:744
+#: kallithea/lib/auth.py:737
 #, python-format
 msgid "IP %s not allowed"
 msgstr "IP-Adresse %s ist nicht erlaubt"
 
-#: kallithea/lib/auth.py:757
+#: kallithea/lib/auth.py:750
 msgid "Invalid API key"
 msgstr "Ungültiger API Key"
 
-#: kallithea/lib/auth.py:795
+#: kallithea/lib/auth.py:768
+msgid "CSRF token leak has been detected - all form tokens have been expired"
+msgstr ""
+
+#: kallithea/lib/auth.py:813
 msgid "You need to be a registered user to perform this action"
 msgstr "Sie müssen ein Registrierter Nutzer sein um diese Aktion durchzuführen"
 
-#: kallithea/lib/auth.py:827
+#: kallithea/lib/auth.py:843
 msgid "You need to be signed in to view this page"
 msgstr "Sie müssen sich anmelden um diese Seite aufzurufen"
 
-#: kallithea/lib/base.py:490
+#: kallithea/lib/base.py:493
 msgid "Repository not found in the filesystem"
 msgstr "Das Repository konnte nicht im Filesystem gefunden werden"
 
-#: kallithea/lib/base.py:516 kallithea/lib/helpers.py:622
+#: kallithea/lib/base.py:519 kallithea/lib/helpers.py:623
 msgid "Changeset not found"
 msgstr "Änderungssatz nicht gefunden"
 
@@ -1099,127 +1097,125 @@
 msgid "No changes detected"
 msgstr "Keine Änderungen erkannt"
 
-#: kallithea/lib/helpers.py:609
+#: kallithea/lib/helpers.py:610
 #, python-format
 msgid "Deleted branch: %s"
 msgstr "Branch %s gelöscht"
 
-#: kallithea/lib/helpers.py:611
+#: kallithea/lib/helpers.py:612
 #, python-format
 msgid "Created tag: %s"
 msgstr "Tag %s erstellt"
 
-#: kallithea/lib/helpers.py:671
+#: kallithea/lib/helpers.py:672
 #, python-format
 msgid "Show all combined changesets %s->%s"
 msgstr "Zeige alle Kombinierten Änderungensätze %s->%s"
 
-#: kallithea/lib/helpers.py:677
+#: kallithea/lib/helpers.py:678
 msgid "Compare view"
 msgstr "Vergleichsansicht"
 
-#: kallithea/lib/helpers.py:696
+#: kallithea/lib/helpers.py:697
 msgid "and"
 msgstr "und"
 
-#: kallithea/lib/helpers.py:697
+#: kallithea/lib/helpers.py:698
 #, python-format
 msgid "%s more"
 msgstr "%s mehr"
 
-#: kallithea/lib/helpers.py:698 kallithea/templates/changelog/changelog.html:44
+#: kallithea/lib/helpers.py:699 kallithea/templates/changelog/changelog.html:44
 msgid "revisions"
 msgstr "revisionen"
 
-#: kallithea/lib/helpers.py:722
+#: kallithea/lib/helpers.py:723
 #, fuzzy, python-format
-#| msgid "fork name %s"
 msgid "Fork name %s"
 msgstr "Fork Name %s"
 
-#: kallithea/lib/helpers.py:742
+#: kallithea/lib/helpers.py:743
 #, fuzzy, python-format
-#| msgid "Pull request #%s"
 msgid "Pull request %s"
 msgstr "Pull Request #%s"
 
-#: kallithea/lib/helpers.py:752
+#: kallithea/lib/helpers.py:753
 msgid "[deleted] repository"
 msgstr "[gelöscht] Repository"
 
-#: kallithea/lib/helpers.py:754 kallithea/lib/helpers.py:766
+#: kallithea/lib/helpers.py:755 kallithea/lib/helpers.py:767
 msgid "[created] repository"
 msgstr "[erstellt] Repository"
 
-#: kallithea/lib/helpers.py:756
+#: kallithea/lib/helpers.py:757
 msgid "[created] repository as fork"
 msgstr "[erstellt] Repository als Fork"
 
-#: kallithea/lib/helpers.py:758 kallithea/lib/helpers.py:768
+#: kallithea/lib/helpers.py:759 kallithea/lib/helpers.py:769
 msgid "[forked] repository"
 msgstr "[forked] Repository"
 
-#: kallithea/lib/helpers.py:760 kallithea/lib/helpers.py:770
+#: kallithea/lib/helpers.py:761 kallithea/lib/helpers.py:771
 msgid "[updated] repository"
 msgstr "[aktualisiert] Repository"
 
-#: kallithea/lib/helpers.py:762
+#: kallithea/lib/helpers.py:763
 msgid "[downloaded] archive from repository"
 msgstr "Archiv von Repository [heruntergeladen]"
 
-#: kallithea/lib/helpers.py:764
+#: kallithea/lib/helpers.py:765
 msgid "[delete] repository"
 msgstr "Repository [gelöscht]"
 
-#: kallithea/lib/helpers.py:772
+#: kallithea/lib/helpers.py:773
 msgid "[created] user"
 msgstr "Benutzer [erstellt]"
 
-#: kallithea/lib/helpers.py:774
+#: kallithea/lib/helpers.py:775
 msgid "[updated] user"
 msgstr "Benutzer [akutalisiert]"
 
-#: kallithea/lib/helpers.py:776
+#: kallithea/lib/helpers.py:777
 msgid "[created] user group"
 msgstr "Benutzergruppe [erstellt]"
 
-#: kallithea/lib/helpers.py:778
+#: kallithea/lib/helpers.py:779
 msgid "[updated] user group"
 msgstr "Benutzergruppe [aktualisiert]"
 
-#: kallithea/lib/helpers.py:780
+#: kallithea/lib/helpers.py:781
 msgid "[commented] on revision in repository"
 msgstr "Revision [kommentiert] in Repository"
 
-#: kallithea/lib/helpers.py:782
+#: kallithea/lib/helpers.py:783
 msgid "[commented] on pull request for"
 msgstr "Pull Request [kommentiert] für"
 
-#: kallithea/lib/helpers.py:784
+#: kallithea/lib/helpers.py:785
 msgid "[closed] pull request for"
 msgstr "Pull Request [geschlossen] für"
 
-#: kallithea/lib/helpers.py:786
+#: kallithea/lib/helpers.py:787
 msgid "[pushed] into"
 msgstr "[Pushed] in"
 
-#: kallithea/lib/helpers.py:788
+#: kallithea/lib/helpers.py:789
 msgid "[committed via Kallithea] into repository"
 msgstr "[via Kallithea] in Repository [committed]"
 
-#: kallithea/lib/helpers.py:790
+#: kallithea/lib/helpers.py:791
 msgid "[pulled from remote] into repository"
 msgstr "[Pulled von Remote] in Repository"
 
-#: kallithea/lib/helpers.py:792
+#: kallithea/lib/helpers.py:793
 msgid "[pulled] from"
 msgstr "[Pulled] von"
 
-#: kallithea/lib/helpers.py:794
+#: kallithea/lib/helpers.py:795
 msgid "[started following] repository"
 msgstr "[Following gestartet] für Repository"
 
-#: kallithea/lib/helpers.py:796
+#: kallithea/lib/helpers.py:797
 msgid "[stopped following] repository"
 msgstr "[Following gestoppt] für Repository"
 
@@ -1229,8 +1225,8 @@
 msgstr " und %s weitere"
 
 #: kallithea/lib/helpers.py:1128
-#: kallithea/templates/compare/compare_diff.html:65
-#: kallithea/templates/pullrequests/pullrequest_show.html:322
+#: kallithea/templates/compare/compare_diff.html:71
+#: kallithea/templates/pullrequests/pullrequest_show.html:337
 msgid "No files"
 msgstr "Keine Dateien"
 
@@ -1254,7 +1250,7 @@
 msgid "chmod"
 msgstr "chmod"
 
-#: kallithea/lib/helpers.py:1444
+#: kallithea/lib/helpers.py:1469
 #, python-format
 msgid ""
 "%s repository is not mapped to db perhaps it was created or renamed from "
@@ -1265,69 +1261,69 @@
 "es im Dateisystem erstellt oder umbenannt. Bitte starten sie die "
 "Applikation erneut um die Repositories neu zu Indizieren"
 
-#: kallithea/lib/utils2.py:415
+#: kallithea/lib/utils2.py:434
 #, python-format
 msgid "%d year"
 msgid_plural "%d years"
 msgstr[0] "%d Jahr"
 msgstr[1] "%d Jahre"
 
-#: kallithea/lib/utils2.py:416
+#: kallithea/lib/utils2.py:435
 #, python-format
 msgid "%d month"
 msgid_plural "%d months"
 msgstr[0] "%d Monat"
 msgstr[1] "%d Monate"
 
-#: kallithea/lib/utils2.py:417
+#: kallithea/lib/utils2.py:436
 #, python-format
 msgid "%d day"
 msgid_plural "%d days"
 msgstr[0] "%d Tag"
 msgstr[1] "%d Tage"
 
-#: kallithea/lib/utils2.py:418
+#: kallithea/lib/utils2.py:437
 #, python-format
 msgid "%d hour"
 msgid_plural "%d hours"
 msgstr[0] "%d Stunde"
 msgstr[1] "%d Stunden"
 
-#: kallithea/lib/utils2.py:419
+#: kallithea/lib/utils2.py:438
 #, python-format
 msgid "%d minute"
 msgid_plural "%d minutes"
 msgstr[0] "%d Minute"
 msgstr[1] "%d Minuten"
 
-#: kallithea/lib/utils2.py:420
+#: kallithea/lib/utils2.py:439
 #, python-format
 msgid "%d second"
 msgid_plural "%d seconds"
 msgstr[0] "%d Sekunde"
 msgstr[1] "%d Sekunden"
 
-#: kallithea/lib/utils2.py:436
+#: kallithea/lib/utils2.py:455
 #, python-format
 msgid "in %s"
 msgstr "in %s"
 
-#: kallithea/lib/utils2.py:438
+#: kallithea/lib/utils2.py:457
 #, python-format
 msgid "%s ago"
 msgstr "vor %s"
 
-#: kallithea/lib/utils2.py:440
+#: kallithea/lib/utils2.py:459
 #, python-format
 msgid "in %s and %s"
 msgstr "in %s und %s"
 
-#: kallithea/lib/utils2.py:443
+#: kallithea/lib/utils2.py:462
 #, python-format
 msgid "%s and %s ago"
 msgstr "%s und %s her"
 
-#: kallithea/lib/utils2.py:446
+#: kallithea/lib/utils2.py:465
 msgid "just now"
 msgstr "jetzt gerade"
 
@@ -1426,7 +1422,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1531
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1570
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1620
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1665
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1669
 msgid "Kallithea Administrator"
 msgstr "Kallithea Administrator"
 
@@ -1537,7 +1533,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2063
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2102
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2155
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2229
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2237
 msgid "Approved"
 msgstr "Akzeptiert"
 
@@ -1552,7 +1548,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2064
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2103
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2156
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2230
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2238
 msgid "Rejected"
 msgstr "Abgelehnt"
 
@@ -1579,7 +1575,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1379
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1418
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1471
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1518
 msgid "top level"
 msgstr "höchste Ebene"
 
@@ -1726,7 +1722,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1560
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1599
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1651
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1697
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1701
 msgid "Registration disabled"
 msgstr "Registrierung deaktiviert"
 
@@ -1753,14 +1749,14 @@
 msgstr "Benutzerregistrierung mit automatische Kontoaktivierung"
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1645
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1691
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1695
 msgid "Repository creation enabled with write permission to a repository group"
 msgstr ""
 "Erstellung von Repositories mit Schreibzugriff für Repositorygruppe "
 "aktiviert"
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1646
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1692
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1696
 msgid "Repository creation disabled with write permission to a repository group"
 msgstr ""
 "Erstellung von Repositories mit Schreibzugriff für Repositorygruppe "
@@ -1771,125 +1767,111 @@
 msgid "on line %s"
 msgstr "in Zeile %s"
 
-#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:169
+#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:170
 msgid "[Mention]"
 msgstr "[Mention]"
 
-#: kallithea/model/db.py:1667
+#: kallithea/model/db.py:1671
 msgid "Default user has no access to new repositories"
 msgstr "Der Standard-Benutzer hat keinen Zugriff auf neue Repositories"
 
-#: kallithea/model/db.py:1668
-#| msgid "Unauthorized access to resource"
-msgid "Default user has read access to new repositories"
-msgstr "Der Standard-Benutzer hat Leserechte auf neuen Repositories"
-
-#: kallithea/model/db.py:1669
-#| msgid "Unauthorized access to resource"
-msgid "Default user has write access to new repositories"
-msgstr "Der Standard-Benutzer hat Schreibrechte auf neuen Repositories"
-
-#: kallithea/model/db.py:1670
-msgid "Default user has admin access to new repositories"
-msgstr "Der Standard-Benutzer hat Admin-Rechte auf neuen Repositories"
-
 #: kallithea/model/db.py:1672
-msgid "Default user has no access to new repository groups"
-msgstr "Der Standard-Benutzer hat keinen Zugriff auf neue Repository-Gruppen"
+msgid "Default user has read access to new repositories"
+msgstr "Der Standard-Benutzer hat Leserechte auf neuen Repositories"
 
 #: kallithea/model/db.py:1673
+msgid "Default user has write access to new repositories"
+msgstr "Der Standard-Benutzer hat Schreibrechte auf neuen Repositories"
+
+#: kallithea/model/db.py:1674
+msgid "Default user has admin access to new repositories"
+msgstr "Der Standard-Benutzer hat Admin-Rechte auf neuen Repositories"
+
+#: kallithea/model/db.py:1676
+msgid "Default user has no access to new repository groups"
+msgstr "Der Standard-Benutzer hat keinen Zugriff auf neue Repository-Gruppen"
+
+#: kallithea/model/db.py:1677
 msgid "Default user has read access to new repository groups"
 msgstr "Der Standard-Benutzer hat Leserechte auf neuen Repository-Gruppen"
 
-#: kallithea/model/db.py:1674
+#: kallithea/model/db.py:1678
 msgid "Default user has write access to new repository groups"
 msgstr "Der Standard-Benutzer Schreibrechte auf neuen Repository-Gruppen"
 
-#: kallithea/model/db.py:1675
+#: kallithea/model/db.py:1679
 msgid "Default user has admin access to new repository groups"
 msgstr "Der Standard-Benutzer Admin-Rechte auf neuen Repository-Gruppen"
 
-#: kallithea/model/db.py:1677
+#: kallithea/model/db.py:1681
 msgid "Default user has no access to new user groups"
 msgstr "Der Standard-Benutzer hat keinen Zugriff auf neue Benutzer-Gruppen"
 
-#: kallithea/model/db.py:1678
+#: kallithea/model/db.py:1682
 msgid "Default user has read access to new user groups"
 msgstr "Der Standard-Benutzer hat Leserechte auf neuen Benutzer-Gruppen"
 
-#: kallithea/model/db.py:1679
+#: kallithea/model/db.py:1683
 msgid "Default user has write access to new user groups"
 msgstr "Der Standard-Benutzer hat Schreibrechte auf neuen Benutzer-Gruppen"
 
-#: kallithea/model/db.py:1680
+#: kallithea/model/db.py:1684
 msgid "Default user has admin access to new user groups"
 msgstr "Der Standard-Benutzer hat Admin-Rechte auf neuen Benutzer-Gruppen"
 
-#: kallithea/model/db.py:1682
-#, python-format
-#| msgid "Created repository group %s"
+#: kallithea/model/db.py:1686
 msgid "Only admins can create repository groups"
 msgstr "Nur Admins können Repository-Gruppen erstellen"
 
-#: kallithea/model/db.py:1683
-#, fuzzy, python-format
-#| msgid "Created repository group %s"
+#: kallithea/model/db.py:1687
+#, fuzzy
 msgid "Non-admins can create repository groups"
 msgstr "Nicht-Admins können Repository-Gruppen erstellen"
 
-#: kallithea/model/db.py:1685
-#| msgid "[created] user group"
+#: kallithea/model/db.py:1689
 msgid "Only admins can create user groups"
 msgstr "Nur Admins können Benutzer-Gruppen erstellen"
 
-#: kallithea/model/db.py:1686
-#| msgid "[created] user group"
+#: kallithea/model/db.py:1690
 msgid "Non-admins can create user groups"
 msgstr "Nicht-Admins können Benutzer-Gruppen erstellen"
 
-#: kallithea/model/db.py:1688
+#: kallithea/model/db.py:1692
 #, fuzzy
-#| msgid "Top level repositories"
 msgid "Only admins can create top level repositories"
 msgstr "Repositories oberster Ebene"
 
-#: kallithea/model/db.py:1689
+#: kallithea/model/db.py:1693
 #, fuzzy
-#| msgid "Top level repositories"
 msgid "Non-admins can create top level repositories"
 msgstr "Repositories oberster Ebene"
 
-#: kallithea/model/db.py:1694
-#| msgid "Location of repositories"
+#: kallithea/model/db.py:1698
 msgid "Only admins can fork repositories"
 msgstr "Nur Admins können Repositories forken"
 
-#: kallithea/model/db.py:1695
-#| msgid "Location of repositories"
-msgid "Non-admins can can fork repositories"
-msgstr "Nicht-Admins können Repositories forken"
-
-#: kallithea/model/db.py:1698
-#, fuzzy
-#| msgid "User Registration with manual account activation"
-msgid "User registration with manual account activation"
-msgstr "Benutzerregistrierung mit manueller Kontoaktivierung"
-
 #: kallithea/model/db.py:1699
 #, fuzzy
-#| msgid "User Registration with automatic account activation"
+msgid "Non-admins can fork repositories"
+msgstr "Nicht-Admins können Repositories forken"
+
+#: kallithea/model/db.py:1702
+#, fuzzy
+msgid "User registration with manual account activation"
+msgstr "Benutzerregistrierung mit manueller Kontoaktivierung"
+
+#: kallithea/model/db.py:1703
+#, fuzzy
 msgid "User registration with automatic account activation"
 msgstr "Benutzerregistrierung mit automatische Kontoaktivierung"
 
-#: kallithea/model/db.py:2228
+#: kallithea/model/db.py:2236
 #, fuzzy
-#| msgid "Not Reviewed"
 msgid "Not reviewed"
 msgstr "Nicht Begutachtet"
 
-#: kallithea/model/db.py:2231
+#: kallithea/model/db.py:2239
 #, fuzzy
-#| msgid "Under Review"
 msgid "Under review"
 msgstr "In Begutachtung"
 
@@ -1911,43 +1893,37 @@
 msgid "Enter %(min)i characters or more"
 msgstr "Bitte mindestens %(min)i Zeichen eingeben"
 
-#: kallithea/model/forms.py:160
+#: kallithea/model/forms.py:165
 msgid "Name must not contain only digits"
 msgstr "Name darf nicht nur Ziffern enthalten"
 
 #: kallithea/model/notification.py:254
 #, fuzzy, python-format
-#| msgid "%(user)s commented on changeset at %(when)s"
 msgid "%(user)s commented on changeset %(age)s"
 msgstr "%(user)s hat am %(when)s ein Changeset kommentiert"
 
 #: kallithea/model/notification.py:255
 #, fuzzy, python-format
-#| msgid "%(user)s sent message at %(when)s"
 msgid "%(user)s sent message %(age)s"
 msgstr "%(user)s hat am %(when)s eine Nachricht gesendet"
 
 #: kallithea/model/notification.py:256
 #, fuzzy, python-format
-#| msgid "%(user)s mentioned you at %(when)s"
 msgid "%(user)s mentioned you %(age)s"
 msgstr "%(user)s hat Sie am %(when)s erwähnt"
 
 #: kallithea/model/notification.py:257
 #, fuzzy, python-format
-#| msgid "%(user)s registered in Kallithea at %(when)s"
 msgid "%(user)s registered in Kallithea %(age)s"
 msgstr "%(user)s hat sich am %(when)s bei Kallithea registriert"
 
 #: kallithea/model/notification.py:258
 #, fuzzy, python-format
-#| msgid "%(user)s opened new pull request at %(when)s"
 msgid "%(user)s opened new pull request %(age)s"
 msgstr "%(user)s hat am %(when)s einen neuen Pull Request eröffnet"
 
 #: kallithea/model/notification.py:259
 #, fuzzy, python-format
-#| msgid "%(user)s commented on pull request at %(when)s"
 msgid "%(user)s commented on pull request %(age)s"
 msgstr "%(user)s hat am %(when)s einen Pull Request kommentiert"
 
@@ -1983,11 +1959,7 @@
 
 #: kallithea/model/notification.py:302
 #, fuzzy, python-format
-#| msgid "" "Comment on %(repo_name)s changeset %(short_id)s on %(branch)s by "
-#| "%(comment_username)s"
-msgid ""
-"[Comment from %(comment_username)s] %(repo_name)s changeset %(short_id)s "
-"on %(branch)s"
+msgid "[Comment] %(repo_name)s changeset %(short_id)s on %(branch)s"
 msgstr ""
 "Kommentar für %(repo_name)s Changeset %(short_id)s in %(branch)s erstellt"
 " von %(comment_username)s"
@@ -1999,21 +1971,14 @@
 
 #: kallithea/model/notification.py:307
 #, fuzzy, python-format
-#| msgid "" "
-msgid ""
-"[Added by %(pr_username)s] %(repo_name)s pull request %(pr_nice_id)s from"
-" %(ref)s"
+msgid "[Added] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
 msgstr ""
 "Review Request für %(repo_name)s Pull Request #%(pr_id)s von %(ref)s "
 "erstellt von %(pr_username)s"
 
 #: kallithea/model/notification.py:308
 #, fuzzy, python-format
-#| msgid "" "Comment on %(repo_name)s pull request #%(pr_id)s from %(ref)s by "
-#| "%(comment_username)s"
-msgid ""
-"[Comment from %(comment_username)s] %(repo_name)s pull request "
-"%(pr_nice_id)s from %(ref)s"
+msgid "[Comment] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
 msgstr ""
 "Kommentar von %(comment_username)s für %(repo_name)s Pull Request "
 "#%(pr_id)s von %(ref)s"
@@ -2024,27 +1989,25 @@
 
 #: kallithea/model/pull_request.py:137
 #, fuzzy, python-format
-#| msgid "%(user)s wants you to review pull request #%(pr_id)s: %(pr_title)s"
 msgid "%(user)s wants you to review pull request %(pr_nice_id)s: %(pr_title)s"
 msgstr "%(user)s möchte ein Review des Pull Request #%(pr_id)s: %(pr_title)s"
 
-#: kallithea/model/scm.py:813
+#: kallithea/model/scm.py:708
 msgid "latest tip"
 msgstr "Letzter Tip"
 
-#: kallithea/model/user.py:185
+#: kallithea/model/user.py:192
 msgid "New user registration"
 msgstr "Neue Benutzerregistrierung"
 
-#: kallithea/model/user.py:249
+#: kallithea/model/user.py:256
 #, fuzzy
-#| msgid "You can't remove this user since it's crucial for entire application"
 msgid "You can't remove this user since it is crucial for the entire application"
 msgstr ""
 "Sie können diesen Benutzer nicht löschen, da er von entscheidender "
 "Bedeutung für die gesamte Applikation ist"
 
-#: kallithea/model/user.py:254
+#: kallithea/model/user.py:261
 #, python-format
 msgid ""
 "User \"%s\" still owns %s repositories and cannot be removed. Switch "
@@ -2054,7 +2017,7 @@
 "nicht entfernt werden. Entweder muss der Besitzer geändert oder das "
 "Repository entfernt werden: %s"
 
-#: kallithea/model/user.py:259
+#: kallithea/model/user.py:266
 #, python-format
 msgid ""
 "User \"%s\" still owns %s repository groups and cannot be removed. Switch"
@@ -2064,7 +2027,7 @@
 "kann daher nicht entfernt werden. Entweder muss der Besitzer geändert "
 "oder die Repositorygruppen müssen entfernt werden: %s"
 
-#: kallithea/model/user.py:266
+#: kallithea/model/user.py:273
 #, python-format
 msgid ""
 "User \"%s\" still owns %s user groups and cannot be removed. Switch "
@@ -2074,37 +2037,38 @@
 "nicht entfernt werden. Entweder muss der Besitzer geändert oder die "
 "Benutzergruppen müssen gelöscht werden: %s"
 
-#: kallithea/model/user.py:296
+#: kallithea/model/user.py:368
 msgid "Password reset link"
 msgstr "Link zum Zurücksetzen des Passworts"
 
-#: kallithea/model/user.py:319
-msgid "Your new password"
-msgstr "Dein neues Passwort"
-
-#: kallithea/model/user.py:320
-#, python-format
-msgid "Your new Kallithea password:%s"
-msgstr "Ihr neues Kallithea-Passwort: %s"
+#: kallithea/model/user.py:418
+#, fuzzy
+msgid "Password reset notification"
+msgstr "Link zum Zurücksetzen des Passworts"
+
+#: kallithea/model/user.py:419
+#, python-format
+msgid ""
+"The password to your account %s has been changed using password reset "
+"form."
+msgstr ""
 
 #: kallithea/model/validators.py:77 kallithea/model/validators.py:78
 msgid "Value cannot be an empty list"
 msgstr "Eine leere Liste ist kein gültiger Wert"
 
-#: kallithea/model/validators.py:95
+#: kallithea/model/validators.py:96
 #, python-format
 msgid "Username \"%(username)s\" already exists"
 msgstr "Benutezrname \"%(username)s\" existiert bereits"
 
-#: kallithea/model/validators.py:97
+#: kallithea/model/validators.py:98
 #, fuzzy, python-format
-#| msgid "Username %(username)s is not valid"
 msgid "Username \"%(username)s\" cannot be used"
 msgstr "Benutzername \"%(username)s\" ist ungültig"
 
-#: kallithea/model/validators.py:99
+#: kallithea/model/validators.py:100
 #, fuzzy
-#| msgid "" "
 msgid ""
 "Username may only contain alphanumeric characters underscores, periods or"
 " dashes and must begin with an alphanumeric character or underscore"
@@ -2113,25 +2077,25 @@
 "oder Bindestriche enthalten und muss mit einem alphanumerischen Zeichen "
 "oder einem Unterstrich beginnen"
 
-#: kallithea/model/validators.py:126
+#: kallithea/model/validators.py:127
 msgid "The input is not valid"
 msgstr "Die Eingabe ist nicht gültig"
 
-#: kallithea/model/validators.py:133
+#: kallithea/model/validators.py:134
 #, python-format
 msgid "Username %(username)s is not valid"
 msgstr "Benutzername \"%(username)s\" ist ungültig"
 
-#: kallithea/model/validators.py:152
+#: kallithea/model/validators.py:154
 msgid "Invalid user group name"
 msgstr "Ungültiger Benutzergruppenname"
 
-#: kallithea/model/validators.py:153
+#: kallithea/model/validators.py:155
 #, python-format
 msgid "User group \"%(usergroup)s\" already exists"
 msgstr "Benutzergruppe \"%(usergroup)s\" existiert bereits"
 
-#: kallithea/model/validators.py:155
+#: kallithea/model/validators.py:157
 msgid ""
 "user group name may only contain alphanumeric characters underscores, "
 "periods or dashes and must begin with alphanumeric character"
@@ -2140,116 +2104,111 @@
 "Unterstriche, Punkte oder Bindestriche enthalten und muss mit einem "
 "alphanumerischen Zeichen beginnen"
 
-#: kallithea/model/validators.py:193
+#: kallithea/model/validators.py:197
 msgid "Cannot assign this group as parent"
 msgstr "Kann diese Gruppe nicht als vorgesetzt setzen"
 
-#: kallithea/model/validators.py:194
+#: kallithea/model/validators.py:198
 #, python-format
 msgid "Group \"%(group_name)s\" already exists"
 msgstr "Gruppe \"%(group_name)s\" existiert bereits"
 
-#: kallithea/model/validators.py:196
+#: kallithea/model/validators.py:200
 #, python-format
 msgid "Repository with name \"%(group_name)s\" already exists"
 msgstr "Es gibt bereits ein Repository mit \"%(group_name)s\""
 
-#: kallithea/model/validators.py:254
+#: kallithea/model/validators.py:258
 msgid "Invalid characters (non-ascii) in password"
 msgstr "Üngültige(nicht ASCII) Zeichen im Passwort"
 
-#: kallithea/model/validators.py:269
+#: kallithea/model/validators.py:273
 msgid "Invalid old password"
 msgstr "Ungültiges altes Passwort"
 
-#: kallithea/model/validators.py:285
+#: kallithea/model/validators.py:289
 msgid "Passwords do not match"
 msgstr "Die Passwörter stimmen nicht überein"
 
-#: kallithea/model/validators.py:300
+#: kallithea/model/validators.py:304
 #, fuzzy
-#| msgid "invalid password"
 msgid "Invalid username or password"
 msgstr "Ungültiges Passwort"
 
-#: kallithea/model/validators.py:331
+#: kallithea/model/validators.py:335
 msgid "Token mismatch"
 msgstr "Schlüssel  stimmt nicht überein"
 
-#: kallithea/model/validators.py:345
+#: kallithea/model/validators.py:351
 #, fuzzy, python-format
-#| msgid "Repository name %(repo)s is disallowed"
 msgid "Repository name %(repo)s is not allowed"
 msgstr "Repository  Name \"%(repo)s\" ist verboten"
 
-#: kallithea/model/validators.py:347
+#: kallithea/model/validators.py:353
 #, python-format
 msgid "Repository named %(repo)s already exists"
 msgstr "Es gibt bereits ein Repository mit \"%(repo)s\""
 
-#: kallithea/model/validators.py:348
+#: kallithea/model/validators.py:354
 #, python-format
 msgid "Repository \"%(repo)s\" already exists in group \"%(group)s\""
 msgstr ""
 "Es gibt bereits ein Repository mit \"%(repo)s\" in der Gruppe "
 "\"%(group)s\""
 
-#: kallithea/model/validators.py:350
+#: kallithea/model/validators.py:356
 #, python-format
 msgid "Repository group with name \"%(repo)s\" already exists"
 msgstr "Eine Repositorygruppe mit dem Namen \"%(repo)s\" existiert bereits"
 
-#: kallithea/model/validators.py:465
+#: kallithea/model/validators.py:470
 #, fuzzy
-#| msgid "private repository"
 msgid "Invalid repository URL"
 msgstr "privates Repository"
 
-#: kallithea/model/validators.py:466
+#: kallithea/model/validators.py:471
 msgid ""
 "Invalid repository URL. It must be a valid http, https, ssh, svn+http or "
 "svn+https URL"
 msgstr ""
 
-#: kallithea/model/validators.py:489
+#: kallithea/model/validators.py:496
 msgid "Fork has to be the same type as parent"
 msgstr "Forke um den selben typ wie der Vorgesetze zu haben"
 
-#: kallithea/model/validators.py:504
+#: kallithea/model/validators.py:511
 msgid "You don't have permissions to create repository in this group"
 msgstr ""
 "Du hast nicht die erforderlichen Berechtigungen, um in dieser Gruppe ein "
 "Repository zu erzeugen"
 
-#: kallithea/model/validators.py:506
+#: kallithea/model/validators.py:513
 msgid "no permission to create repository in root location"
 msgstr "keine Berechtigung, um ein Repository auf höchster Ebene anzulegen"
 
-#: kallithea/model/validators.py:556
+#: kallithea/model/validators.py:563
 msgid "You don't have permissions to create a group in this location"
 msgstr "Sie haben keine Berechtigung, um an diesem Ort ein Repository anzulegen"
 
-#: kallithea/model/validators.py:597
+#: kallithea/model/validators.py:604
 msgid "This username or user group name is not valid"
 msgstr "Dieser Benutzername oder Benutzergruppenname ist nicht gültig"
 
-#: kallithea/model/validators.py:690
+#: kallithea/model/validators.py:697
 msgid "This is not a valid path"
 msgstr "Dies ist ein Ungültiger Pfad"
 
-#: kallithea/model/validators.py:705
+#: kallithea/model/validators.py:714
 #, fuzzy
-#| msgid "This email address is already taken"
 msgid "This email address is already in use"
 msgstr "Diese E-Mailaddresse ist bereits in Benutzung"
 
-#: kallithea/model/validators.py:725
+#: kallithea/model/validators.py:734
 #, fuzzy, python-format
-#| msgid "email \"%(email)s\" does not exist."
 msgid "Email address \"%(email)s\" not found"
 msgstr "E-MailAddresse \"%(email)s\" existiert nicht."
 
-#: kallithea/model/validators.py:762
+#: kallithea/model/validators.py:771
 msgid ""
 "The LDAP Login attribute of the CN must be specified - this is the name "
 "of the attribute that is equivalent to \"username\""
@@ -2257,28 +2216,28 @@
 "Das LDAP-Login-Attribut des CN muss angeben werden - Es ist der Name des "
 "Attributes äquivalent zu \"Benutzername\""
 
-#: kallithea/model/validators.py:774
+#: kallithea/model/validators.py:783
 msgid "Please enter a valid IPv4 or IPv6 address"
 msgstr "Bitte eine gültige IPv4- oder IPv6-Adresse angeben"
 
-#: kallithea/model/validators.py:775
+#: kallithea/model/validators.py:784
 #, python-format
 msgid "The network size (bits) must be within the range of 0-32 (not %(bits)r)"
 msgstr ""
 "Die Größe (in Bits) des Netzwerks muss im Bereich 0-32 liegen (nicht "
 "%(bits)r)"
 
-#: kallithea/model/validators.py:808
+#: kallithea/model/validators.py:817
 msgid "Key name can only consist of letters, underscore, dash or numbers"
 msgstr ""
 "Der Name eines Schlüssels darf nur aus Buchstaben, Ziffern, Unterstrich "
 "und Bindestrich bestehen"
 
-#: kallithea/model/validators.py:822
+#: kallithea/model/validators.py:831
 msgid "Filename cannot be inside a directory"
 msgstr "Dateiname darf kein Unterverzeichnis enthalten"
 
-#: kallithea/model/validators.py:838
+#: kallithea/model/validators.py:847
 #, python-format
 msgid "Plugins %(loaded)s and %(next_to_load)s both export the same name"
 msgstr ""
@@ -2405,7 +2364,9 @@
 #: kallithea/templates/admin/repos/repos.html:50
 #: kallithea/templates/admin/user_groups/user_group_edit_advanced.html:8
 #: kallithea/templates/admin/user_groups/user_groups.html:50
-#: kallithea/templates/pullrequests/pullrequest_show.html:229
+#: kallithea/templates/pullrequests/pullrequest_data.html:16
+#: kallithea/templates/pullrequests/pullrequest_show.html:156
+#: kallithea/templates/pullrequests/pullrequest_show.html:244
 #: kallithea/templates/summary/summary.html:134
 msgid "Owner"
 msgstr "Besitzer"
@@ -2413,7 +2374,7 @@
 #: kallithea/templates/index_base.html:140
 #: kallithea/templates/admin/my_account/my_account_repos.html:57
 #: kallithea/templates/admin/my_account/my_account_watched.html:57
-#: kallithea/templates/base/root.html:44
+#: kallithea/templates/base/root.html:43
 #: kallithea/templates/bookmarks/bookmarks.html:79
 #: kallithea/templates/branches/branches.html:79
 #: kallithea/templates/journal/journal.html:198
@@ -2425,7 +2386,7 @@
 #: kallithea/templates/index_base.html:141
 #: kallithea/templates/admin/my_account/my_account_repos.html:58
 #: kallithea/templates/admin/my_account/my_account_watched.html:58
-#: kallithea/templates/base/root.html:45
+#: kallithea/templates/base/root.html:44
 #: kallithea/templates/bookmarks/bookmarks.html:80
 #: kallithea/templates/branches/branches.html:80
 #: kallithea/templates/journal/journal.html:199
@@ -2441,7 +2402,7 @@
 #: kallithea/templates/index_base.html:143
 #: kallithea/templates/admin/my_account/my_account_repos.html:60
 #: kallithea/templates/admin/my_account/my_account_watched.html:60
-#: kallithea/templates/base/root.html:47
+#: kallithea/templates/base/root.html:46
 #: kallithea/templates/bookmarks/bookmarks.html:82
 #: kallithea/templates/branches/branches.html:82
 #: kallithea/templates/journal/journal.html:201
@@ -2453,7 +2414,7 @@
 #: kallithea/templates/index_base.html:144
 #: kallithea/templates/admin/my_account/my_account_repos.html:61
 #: kallithea/templates/admin/my_account/my_account_watched.html:61
-#: kallithea/templates/base/base.html:147 kallithea/templates/base/root.html:48
+#: kallithea/templates/base/root.html:47
 #: kallithea/templates/bookmarks/bookmarks.html:83
 #: kallithea/templates/branches/branches.html:83
 #: kallithea/templates/journal/journal.html:202
@@ -2463,7 +2424,7 @@
 msgstr "Lade..."
 
 #: kallithea/templates/login.html:5 kallithea/templates/login.html:15
-#: kallithea/templates/base/base.html:333
+#: kallithea/templates/base/base.html:414
 msgid "Log In"
 msgstr "Log In"
 
@@ -2478,14 +2439,15 @@
 #: kallithea/templates/admin/users/user_add.html:32
 #: kallithea/templates/admin/users/user_edit_profile.html:24
 #: kallithea/templates/admin/users/users.html:50
-#: kallithea/templates/base/base.html:309
+#: kallithea/templates/base/base.html:390
+#: kallithea/templates/pullrequests/pullrequest_show.html:166
 msgid "Username"
 msgstr "Benutzername"
 
 #: kallithea/templates/login.html:33 kallithea/templates/register.html:33
 #: kallithea/templates/admin/my_account/my_account.html:37
 #: kallithea/templates/admin/users/user_add.html:41
-#: kallithea/templates/base/base.html:318
+#: kallithea/templates/base/base.html:399
 msgid "Password"
 msgstr "Passwort"
 
@@ -2497,7 +2459,7 @@
 msgid "Forgot your password ?"
 msgstr "Passowrt Vergessen?"
 
-#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:329
+#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:410
 msgid "Don't have an account ?"
 msgstr "Kein Account?"
 
@@ -2510,11 +2472,14 @@
 msgstr "Passwort zurücksetzen"
 
 #: kallithea/templates/password_reset.html:12
+#: kallithea/templates/password_reset_confirmation.html:12
 #, python-format
 msgid "Reset Your Password to %s"
 msgstr "Setze dein Passwort auf %s zurück"
 
 #: kallithea/templates/password_reset.html:14
+#: kallithea/templates/password_reset_confirmation.html:5
+#: kallithea/templates/password_reset_confirmation.html:14
 msgid "Reset Your Password"
 msgstr "Setze dein Passwort zurück"
 
@@ -2532,13 +2497,43 @@
 msgstr "E-Mail zum Zurücksetzen des Passworts anfordern"
 
 #: kallithea/templates/password_reset.html:47
+#, fuzzy
 msgid ""
-"Password reset link will be sent to the email address matching your "
-"username."
+"A password reset link will be sent to the specified email address if it "
+"is registered in the system."
 msgstr ""
 "Der Link zum Zurücksetzen des Passworts wird an die zum Benutzernamen "
 "zugehörige E-Mailaddresse gesendet."
 
+#: kallithea/templates/password_reset_confirmation.html:19
+#, python-format
+msgid "You are about to set a new password for the email address %s."
+msgstr ""
+
+#: kallithea/templates/password_reset_confirmation.html:20
+msgid ""
+"Note that you must use the same browser session for this as the one used "
+"to request the password reset."
+msgstr ""
+
+#: kallithea/templates/password_reset_confirmation.html:30
+msgid "Code you received in the email"
+msgstr ""
+
+#: kallithea/templates/password_reset_confirmation.html:39
+#, fuzzy
+msgid "New Password"
+msgstr "Neues Passwort"
+
+#: kallithea/templates/password_reset_confirmation.html:48
+#, fuzzy
+msgid "Confirm New Password"
+msgstr "Bestätige neues Passwort"
+
+#: kallithea/templates/password_reset_confirmation.html:56
+msgid "Confirm"
+msgstr "Bestätigen"
+
 #: kallithea/templates/register.html:5 kallithea/templates/register.html:14
 #: kallithea/templates/register.html:90
 msgid "Sign Up"
@@ -2592,10 +2587,6 @@
 msgid "There are no branches yet"
 msgstr "Es gibt bisher keine Branches"
 
-#: kallithea/templates/switch_to_list.html:16
-msgid "Closed Branches"
-msgstr "Geschlossene Branches"
-
 #: kallithea/templates/switch_to_list.html:32
 #: kallithea/templates/tags/tags_data.html:44
 msgid "There are no tags yet"
@@ -2684,7 +2675,6 @@
 
 #: kallithea/templates/admin/auth/auth_settings.html:33
 #, fuzzy
-#| msgid "" "
 msgid ""
 "Comma-separated list of plugins; Kallithea will try user authentication "
 "in plugin order"
@@ -2829,16 +2819,15 @@
 #: kallithea/templates/admin/users/user_edit_api_keys.html:8
 #: kallithea/templates/admin/users/user_edit_api_keys.html:27
 #, fuzzy
-#| msgid "never"
 msgid "Never"
 msgstr "nie"
 
-#: kallithea/templates/admin/gists/edit.html:145
+#: kallithea/templates/admin/gists/edit.html:146
 msgid "Update Gist"
 msgstr "Gist aktualisieren"
 
-#: kallithea/templates/admin/gists/edit.html:146
-#: kallithea/templates/changeset/changeset_file_comment.html:81
+#: kallithea/templates/admin/gists/edit.html:147
+#: kallithea/templates/changeset/changeset_file_comment.html:105
 msgid "Cancel"
 msgstr "Abbrechen"
 
@@ -2861,7 +2850,7 @@
 
 #: kallithea/templates/admin/gists/index.html:37
 #: kallithea/templates/admin/gists/show.html:25
-#: kallithea/templates/base/base.html:244
+#: kallithea/templates/base/base.html:321
 msgid "Create New Gist"
 msgstr "Neuen Gist erstellen"
 
@@ -2949,7 +2938,8 @@
 #: kallithea/templates/admin/settings/settings_hooks.html:36
 #: kallithea/templates/admin/users/user_edit_emails.html:19
 #: kallithea/templates/admin/users/user_edit_ips.html:22
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+#: kallithea/templates/changeset/changeset_file_comment.html:95
 #: kallithea/templates/data_table/_dt_elements.html:129
 #: kallithea/templates/data_table/_dt_elements.html:157
 #: kallithea/templates/data_table/_dt_elements.html:173
@@ -2969,8 +2959,6 @@
 #: kallithea/templates/base/perms_summary.html:43
 #: kallithea/templates/base/perms_summary.html:79
 #: kallithea/templates/base/perms_summary.html:81
-#: kallithea/templates/changeset/changeset_file_comment.html:83
-#: kallithea/templates/changeset/changeset_file_comment.html:192
 #: kallithea/templates/data_table/_dt_elements.html:122
 #: kallithea/templates/data_table/_dt_elements.html:123
 #: kallithea/templates/data_table/_dt_elements.html:150
@@ -2997,13 +2985,12 @@
 msgstr "erstellt"
 
 #: kallithea/templates/admin/gists/show.html:86
-#: kallithea/templates/files/files_source.html:73
 msgid "Show as raw"
 msgstr ""
 
 #: kallithea/templates/admin/my_account/my_account.html:5
 #: kallithea/templates/admin/my_account/my_account.html:9
-#: kallithea/templates/base/base.html:350
+#: kallithea/templates/base/base.html:431
 msgid "My Account"
 msgstr "Mein Account"
 
@@ -3014,7 +3001,6 @@
 
 #: kallithea/templates/admin/my_account/my_account.html:36
 #, fuzzy
-#| msgid "New email address"
 msgid "Email Addresses"
 msgstr "Neue E-Mailadresse"
 
@@ -3025,14 +3011,12 @@
 
 #: kallithea/templates/admin/my_account/my_account.html:39
 #, fuzzy
-#| msgid "repositories"
 msgid "Owned Repositories"
 msgstr "Repositories"
 
 #: kallithea/templates/admin/my_account/my_account.html:40
 #: kallithea/templates/journal/journal.html:53
 #, fuzzy
-#| msgid "repositories"
 msgid "Watched Repositories"
 msgstr "Repositories"
 
@@ -3041,7 +3025,6 @@
 #: kallithea/templates/admin/user_groups/user_group_edit.html:32
 #: kallithea/templates/admin/users/user_edit.html:34
 #, fuzzy
-#| msgid "Copy permissions"
 msgid "Show Permissions"
 msgstr "Berechtigungen kopieren"
 
@@ -3053,42 +3036,36 @@
 #: kallithea/templates/admin/my_account/my_account_api_keys.html:14
 #: kallithea/templates/admin/users/user_edit_api_keys.html:14
 #, fuzzy, python-format
-#| msgid "Confirm to reset this api key: %s"
 msgid "Confirm to reset this API key: %s"
 msgstr "Zurücksetzen des API Keys \"%s\" bestätigen"
 
 #: kallithea/templates/admin/my_account/my_account_api_keys.html:30
 #: kallithea/templates/admin/users/user_edit_api_keys.html:30
 #, fuzzy
-#| msgid "expired"
 msgid "Expired"
 msgstr "verfallen"
 
 #: kallithea/templates/admin/my_account/my_account_api_keys.html:40
 #: kallithea/templates/admin/users/user_edit_api_keys.html:40
 #, fuzzy, python-format
-#| msgid "Confirm to remove this api key: %s"
 msgid "Confirm to remove this API key: %s"
 msgstr "Entfernen des API Keys \"%s\" bestätigen"
 
 #: kallithea/templates/admin/my_account/my_account_api_keys.html:42
 #: kallithea/templates/admin/users/user_edit_api_keys.html:42
 #, fuzzy
-#| msgid "remove"
 msgid "Remove"
 msgstr "entfernen"
 
 #: kallithea/templates/admin/my_account/my_account_api_keys.html:49
 #: kallithea/templates/admin/users/user_edit_api_keys.html:49
 #, fuzzy
-#| msgid "No additional api keys specified"
 msgid "No additional API keys specified"
 msgstr "Keine weiteren API Keys spezifiziert"
 
 #: kallithea/templates/admin/my_account/my_account_api_keys.html:61
 #: kallithea/templates/admin/users/user_edit_api_keys.html:61
 #, fuzzy
-#| msgid "New api key"
 msgid "New API key"
 msgstr "Neuer API Key"
 
@@ -3167,7 +3144,6 @@
 #: kallithea/templates/admin/my_account/my_account_profile.html:16
 #: kallithea/templates/admin/users/user_edit_profile.html:15
 #, fuzzy
-#| msgid "current IP"
 msgid "Current IP"
 msgstr "Aktuelle IP-Adresse"
 
@@ -3177,7 +3153,7 @@
 
 #: kallithea/templates/admin/my_account/my_account_repos.html:59
 #: kallithea/templates/admin/my_account/my_account_watched.html:59
-#: kallithea/templates/base/root.html:46
+#: kallithea/templates/base/root.html:45
 #: kallithea/templates/bookmarks/bookmarks.html:81
 #: kallithea/templates/branches/branches.html:81
 #: kallithea/templates/journal/journal.html:200
@@ -3204,7 +3180,7 @@
 msgstr "Kommentare"
 
 #: kallithea/templates/admin/notifications/notifications.html:26
-#: kallithea/templates/base/base.html:190
+#: kallithea/templates/base/base.html:180
 msgid "Pull Requests"
 msgstr "Pull Requests"
 
@@ -3222,7 +3198,7 @@
 msgstr "Zeige Benachrichtigung"
 
 #: kallithea/templates/admin/notifications/show_notification.html:9
-#: kallithea/templates/base/base.html:349
+#: kallithea/templates/base/base.html:430
 msgid "Notifications"
 msgstr "Benachrichtigungen"
 
@@ -3267,7 +3243,6 @@
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:26
 #, fuzzy
-#| msgid "Import existing repository ?"
 msgid "Apply to all existing repositories"
 msgstr "Bestehendes Repository importieren?"
 
@@ -3295,13 +3270,11 @@
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:40
 #, fuzzy
-#| msgid "Import existing repository ?"
 msgid "Apply to all existing repository groups"
 msgstr "Bestehendes Repository importieren?"
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:41
 #, fuzzy
-#| msgid "Copy permission set from parent repository group."
 msgid "Permissions for the Default user on new repository groups."
 msgstr "Rechte der übergeordneten Repositorygruppe kopieren."
 
@@ -3312,9 +3285,6 @@
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:53
 #, fuzzy
-#| msgid "" "
-#| " "
-#| " "will be lost"
 msgid ""
 "All default permissions on each user group will be reset to chosen "
 "permission, note that all custom default permission on user groups will "
@@ -3326,7 +3296,7 @@
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:54
 msgid "Apply to all existing user groups"
-msgstr ""
+msgstr "Auf alle bestehenden Benutzergruppen anwenden"
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:55
 msgid "Permissions for the Default user on new user groups."
@@ -3334,7 +3304,6 @@
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:60
 #, fuzzy
-#| msgid "Repository creation"
 msgid "Top level repository creation"
 msgstr "Repository erstellung"
 
@@ -3354,7 +3323,6 @@
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:74
 #, fuzzy
-#| msgid "" "
 msgid ""
 "With this, write permission to a repository group allows creating "
 "repositories inside that group. Without this, group write permissions "
@@ -3390,7 +3358,6 @@
 #: kallithea/templates/admin/permissions/permissions_ips.html:13
 #: kallithea/templates/admin/users/user_edit_ips.html:23
 #, fuzzy, python-format
-#| msgid "Confirm to delete this ip: %s"
 msgid "Confirm to delete this IP address: %s"
 msgstr "Bestätigen diese IP zu löschen: %s"
 
@@ -3448,7 +3415,7 @@
 #: kallithea/templates/admin/repos/repo_edit.html:40
 #: kallithea/templates/admin/settings/settings.html:11
 #: kallithea/templates/admin/user_groups/user_group_edit.html:29
-#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:158
+#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:148
 #: kallithea/templates/data_table/_dt_elements.html:45
 #: kallithea/templates/data_table/_dt_elements.html:49
 msgid "Settings"
@@ -3487,7 +3454,7 @@
 #: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:9
 #: kallithea/templates/admin/user_groups/user_group_edit_advanced.html:7
 #: kallithea/templates/admin/users/user_edit_advanced.html:8
-#: kallithea/templates/pullrequests/pullrequest_show.html:146
+#: kallithea/templates/pullrequests/pullrequest_show.html:148
 msgid "Created on"
 msgstr "Erstellt am"
 
@@ -3507,7 +3474,6 @@
 #: kallithea/templates/admin/repos/repo_edit_permissions.html:12
 #: kallithea/templates/admin/user_groups/user_group_edit_perms.html:11
 #, fuzzy
-#| msgid "user/user group"
 msgid "User/User Group"
 msgstr "Benutzer/Benutzergruppe"
 
@@ -3518,7 +3484,6 @@
 #: kallithea/templates/admin/user_groups/user_group_edit_perms.html:28
 #: kallithea/templates/admin/user_groups/user_group_edit_perms.html:45
 #, fuzzy
-#| msgid "default"
 msgid "Default"
 msgstr "standart"
 
@@ -3529,7 +3494,6 @@
 #: kallithea/templates/admin/user_groups/user_group_edit_perms.html:34
 #: kallithea/templates/admin/user_groups/user_group_edit_perms.html:71
 #, fuzzy
-#| msgid "revoke"
 msgid "Revoke"
 msgstr "entziehen"
 
@@ -3590,7 +3554,6 @@
 
 #: kallithea/templates/admin/repos/repo_add_base.html:17
 #, fuzzy
-#| msgid "[created] repository"
 msgid "Clone remote repository"
 msgstr "[erstellt] Repository"
 
@@ -3722,6 +3685,11 @@
 msgid "Unlock Repository"
 msgstr "Repository entsperren"
 
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:56
+#, python-format
+msgid "Locked by %s on %s"
+msgstr ""
+
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:60
 msgid "Confirm to lock repository."
 msgstr "Sperren des Repositorys bestätigen."
@@ -3778,10 +3746,6 @@
 msgid "Invalidate Repository Cache"
 msgstr "Ungültiger Repositorycache"
 
-#: kallithea/templates/admin/repos/repo_edit_caches.html:4
-msgid "Confirm to invalidate repository cache."
-msgstr ""
-
 #: kallithea/templates/admin/repos/repo_edit_caches.html:7
 msgid ""
 "Manually invalidate cache for this repository. On first access, the "
@@ -3846,25 +3810,21 @@
 
 #: kallithea/templates/admin/repos/repo_edit_permissions.html:21
 #, fuzzy
-#| msgid "private repository"
 msgid "Private Repository"
 msgstr "privates Repository"
 
 #: kallithea/templates/admin/repos/repo_edit_remote.html:3
-#, fuzzy, python-format
-#| msgid "Created repository %s"
+#, fuzzy
 msgid "Remote repository URL"
 msgstr "Repositorium erzeugt %s"
 
 #: kallithea/templates/admin/repos/repo_edit_remote.html:9
 #, fuzzy
-#| msgid "[pulled from remote] into repository"
 msgid "Pull Changes from Remote Repository"
 msgstr "[Pulled von Remote] in Repository"
 
 #: kallithea/templates/admin/repos/repo_edit_remote.html:11
 #, fuzzy
-#| msgid "[pulled from remote] into repository"
 msgid "Confirm to pull changes from remote repository."
 msgstr "[Pulled von Remote] in Repository"
 
@@ -3874,7 +3834,6 @@
 
 #: kallithea/templates/admin/repos/repo_edit_settings.html:11
 #, fuzzy
-#| msgid "private repository"
 msgid "Permanent Repository ID"
 msgstr "privates Repository"
 
@@ -3898,13 +3857,11 @@
 
 #: kallithea/templates/admin/repos/repo_edit_settings.html:21
 #, fuzzy
-#| msgid "[created] repository"
 msgid "Remote repository"
 msgstr "[erstellt] Repository"
 
 #: kallithea/templates/admin/repos/repo_edit_settings.html:25
 #, fuzzy
-#| msgid "Repository"
 msgid "Repository URL"
 msgstr "Repository"
 
@@ -4043,7 +4000,7 @@
 msgid "Custom Hooks"
 msgstr ""
 
-#: kallithea/templates/admin/settings/settings_hooks.html:68
+#: kallithea/templates/admin/settings/settings_hooks.html:67
 msgid "Failed to remove hook"
 msgstr ""
 
@@ -4079,7 +4036,18 @@
 "Current hooks will be updated to the latest version."
 msgstr ""
 
+#: kallithea/templates/admin/settings/settings_mapping.html:28
+msgid "Overwrite existing Git hooks"
+msgstr ""
+
 #: kallithea/templates/admin/settings/settings_mapping.html:30
+msgid ""
+"If installing Git hooks, overwrite any existing hooks, even if they do "
+"not seem to come from Kallithea. WARNING: This operation will destroy any"
+" custom git hooks you may have deployed by hand!"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:35
 msgid "Rescan Repositories"
 msgstr ""
 
@@ -4107,7 +4075,6 @@
 
 #: kallithea/templates/admin/settings/settings_system.html:4
 #, fuzzy
-#| msgid "check for updates"
 msgid "Check for updates"
 msgstr "Auf Updates prüfen"
 
@@ -4310,7 +4277,6 @@
 
 #: kallithea/templates/admin/settings/settings_visual.html:92
 #, fuzzy
-#| msgid "Settings"
 msgid "Meta Tagging"
 msgstr "Einstellungen"
 
@@ -4352,7 +4318,6 @@
 
 #: kallithea/templates/admin/user_groups/user_group_edit.html:33
 #, fuzzy
-#| msgid "members"
 msgid "Show Members"
 msgstr "mitglieder"
 
@@ -4497,47 +4462,43 @@
 msgid "Git repository"
 msgstr "Git Repository"
 
-#: kallithea/templates/base/base.html:126
+#: kallithea/templates/base/base.html:119
 msgid "Create Fork"
 msgstr "Fork erstellen"
 
-#: kallithea/templates/base/base.html:137
+#: kallithea/templates/base/base.html:130
 #: kallithea/templates/data_table/_dt_elements.html:13
 #: kallithea/templates/data_table/_dt_elements.html:17
 #: kallithea/templates/summary/summary.html:8
 msgid "Summary"
 msgstr "Zusammenfassung"
 
-#: kallithea/templates/base/base.html:139
-#: kallithea/templates/base/base.html:141
+#: kallithea/templates/base/base.html:132
+#: kallithea/templates/base/base.html:134
 #: kallithea/templates/changelog/changelog.html:14
 #: kallithea/templates/data_table/_dt_elements.html:21
 #: kallithea/templates/data_table/_dt_elements.html:25
 msgid "Changelog"
 msgstr ""
 
-#: kallithea/templates/base/base.html:143
+#: kallithea/templates/base/base.html:136
 #: kallithea/templates/data_table/_dt_elements.html:29
 #: kallithea/templates/data_table/_dt_elements.html:33
 #: kallithea/templates/files/files.html:11
 msgid "Files"
 msgstr "Dateien"
 
-#: kallithea/templates/base/base.html:145
-msgid "Switch To"
-msgstr ""
+#: kallithea/templates/base/base.html:142
+#: kallithea/templates/base/base.html:144
+msgid "Options"
+msgstr "Optionen"
 
 #: kallithea/templates/base/base.html:152
-#: kallithea/templates/base/base.html:154
-msgid "Options"
-msgstr "Optionen"
-
-#: kallithea/templates/base/base.html:162
 #: kallithea/templates/forks/forks_data.html:21
 msgid "Compare Fork"
 msgstr "Fork vergleichen"
 
-#: kallithea/templates/base/base.html:164
+#: kallithea/templates/base/base.html:154
 #: kallithea/templates/bookmarks/bookmarks.html:56
 #: kallithea/templates/bookmarks/bookmarks_data.html:13
 #: kallithea/templates/branches/branches.html:56
@@ -4547,117 +4508,121 @@
 msgid "Compare"
 msgstr ""
 
-#: kallithea/templates/base/base.html:166
-#: kallithea/templates/base/base.html:254
+#: kallithea/templates/base/base.html:156
+#: kallithea/templates/base/base.html:331
 #: kallithea/templates/search/search.html:14
 #: kallithea/templates/search/search.html:54
 msgid "Search"
 msgstr ""
 
+#: kallithea/templates/base/base.html:160
+msgid "Unlock"
+msgstr ""
+
+#: kallithea/templates/base/base.html:162
+msgid "Lock"
+msgstr ""
+
 #: kallithea/templates/base/base.html:170
-msgid "Unlock"
-msgstr ""
-
-#: kallithea/templates/base/base.html:172
-msgid "Lock"
-msgstr ""
-
-#: kallithea/templates/base/base.html:180
 msgid "Follow"
 msgstr ""
 
-#: kallithea/templates/base/base.html:181
+#: kallithea/templates/base/base.html:171
 msgid "Unfollow"
 msgstr ""
 
-#: kallithea/templates/base/base.html:184
+#: kallithea/templates/base/base.html:174
 #: kallithea/templates/data_table/_dt_elements.html:37
 #: kallithea/templates/data_table/_dt_elements.html:41
 #: kallithea/templates/forks/fork.html:9
 msgid "Fork"
 msgstr ""
 
-#: kallithea/templates/base/base.html:185
+#: kallithea/templates/base/base.html:175
 #: kallithea/templates/pullrequests/pullrequest.html:88
 msgid "Create Pull Request"
 msgstr ""
 
-#: kallithea/templates/base/base.html:190
+#: kallithea/templates/base/base.html:180
 #, python-format
 msgid "Show Pull Requests for %s"
 msgstr ""
 
-#: kallithea/templates/base/base.html:228
+#: kallithea/templates/base/base.html:193
+msgid "Switch To"
+msgstr ""
+
+#: kallithea/templates/base/base.html:203
+#: kallithea/templates/base/base.html:485
+msgid "No matches found"
+msgstr "Keine Übereinstimmungen gefunden"
+
+#: kallithea/templates/base/base.html:305
 msgid "Show recent activity"
 msgstr ""
 
-#: kallithea/templates/base/base.html:234
-#: kallithea/templates/base/base.html:235
+#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:312
 msgid "Public journal"
 msgstr "Öffentliches Logbuch"
 
-#: kallithea/templates/base/base.html:240
+#: kallithea/templates/base/base.html:317
 msgid "Show public gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:241
+#: kallithea/templates/base/base.html:318
 msgid "Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:245
+#: kallithea/templates/base/base.html:322
 msgid "All Public Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:247
+#: kallithea/templates/base/base.html:324
 msgid "My Public Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:248
+#: kallithea/templates/base/base.html:325
 msgid "My Private Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:253
+#: kallithea/templates/base/base.html:330
 msgid "Search in repositories"
 msgstr ""
 
-#: kallithea/templates/base/base.html:276
-#: kallithea/templates/base/base.html:277
-#: kallithea/templates/pullrequests/pullrequest_show_my.html:4
-#: kallithea/templates/pullrequests/pullrequest_show_my.html:8
+#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:354
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:6
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:10
 msgid "My Pull Requests"
 msgstr "Meine Pull Requests"
 
-#: kallithea/templates/base/base.html:296
+#: kallithea/templates/base/base.html:377
 msgid "Not Logged In"
 msgstr "Nicht eingeloggt"
 
-#: kallithea/templates/base/base.html:303
+#: kallithea/templates/base/base.html:384
 msgid "Login to Your Account"
 msgstr ""
 
-#: kallithea/templates/base/base.html:326
+#: kallithea/templates/base/base.html:407
 msgid "Forgot password ?"
 msgstr "Passwort vergessen?"
 
-#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:434
 msgid "Log Out"
 msgstr ""
 
-#: kallithea/templates/base/base.html:402
-msgid "No matches found"
-msgstr "Keine Übereinstimmungen gefunden"
-
-#: kallithea/templates/base/base.html:531
+#: kallithea/templates/base/base.html:615
 msgid "Keyboard shortcuts"
 msgstr ""
 
-#: kallithea/templates/base/base.html:540
+#: kallithea/templates/base/base.html:624
 msgid "Site-wide shortcuts"
 msgstr ""
 
 #: kallithea/templates/base/default_perms_box.html:14
 #, fuzzy
-#| msgid "Repository Defaults"
 msgid "Inherit defaults"
 msgstr "Repositorystandards"
 
@@ -4753,52 +4718,50 @@
 msgstr ""
 
 #: kallithea/templates/base/root.html:31
-#: kallithea/templates/pullrequests/pullrequest_show_all.html:30
-msgid "Open New Pull Request"
-msgstr "Einen neuen Pull Request eröffnen"
+#, fuzzy
+msgid "Open New Pull Request from {0}"
+msgstr "Kommentar von Pull Request"
 
 #: kallithea/templates/base/root.html:32
-msgid "Open New Pull Request for Selected Changesets"
+msgid "Open New Pull Request for {0} &rarr; {1}"
 msgstr ""
 
 #: kallithea/templates/base/root.html:33
-msgid "Show Selected Changesets __S &rarr; __E"
-msgstr ""
+#, fuzzy
+msgid "Show Selected Changesets {0} &rarr; {1}"
+msgstr "Ausgewähltes Changeset anzeigen __S"
 
 #: kallithea/templates/base/root.html:34
-msgid "Show Selected Changeset __S"
-msgstr "Ausgewähltes Changeset anzeigen __S"
+msgid "Selection Link"
+msgstr ""
 
 #: kallithea/templates/base/root.html:35
-msgid "Selection Link"
+#: kallithea/templates/changeset/diff_block.html:8
+#: kallithea/templates/changeset/diff_block.html:21
+msgid "Collapse Diff"
 msgstr ""
 
 #: kallithea/templates/base/root.html:36
-#: kallithea/templates/changeset/diff_block.html:8
-msgid "Collapse Diff"
+msgid "Expand Diff"
 msgstr ""
 
 #: kallithea/templates/base/root.html:37
-msgid "Expand Diff"
+msgid "Failed to revoke permission"
 msgstr ""
 
 #: kallithea/templates/base/root.html:38
-msgid "Failed to revoke permission"
-msgstr ""
+msgid "Confirm to revoke permission for {0}: {1} ?"
+msgstr "Widerruf der Rechte für {0}: {1} bestätigen?"
 
 #: kallithea/templates/base/root.html:39
-msgid "Confirm to revoke permission for {0}: {1} ?"
-msgstr "Widerruf der Rechte für {0}: {1} bestätigen?"
+msgid "enabled"
+msgstr "Aktiviert"
 
 #: kallithea/templates/base/root.html:40
-msgid "enabled"
-msgstr "Aktiviert"
-
-#: kallithea/templates/base/root.html:41
 msgid "disabled"
 msgstr "Deaktiviert"
 
-#: kallithea/templates/base/root.html:43
+#: kallithea/templates/base/root.html:42
 msgid "Specify changeset"
 msgstr "Changeset angeben"
 
@@ -4816,7 +4779,6 @@
 #: kallithea/templates/branches/branches.html:53
 #: kallithea/templates/branches/branches_data.html:10
 #: kallithea/templates/changelog/changelog_summary_data.html:10
-#: kallithea/templates/pullrequests/pullrequest_data.html:16
 #: kallithea/templates/tags/tags.html:53
 #: kallithea/templates/tags/tags_data.html:10
 msgid "Author"
@@ -4856,7 +4818,7 @@
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/templates/changelog/changelog.html:52
+#: kallithea/templates/changelog/changelog.html:49
 msgid "Clear selection"
 msgstr ""
 
@@ -4884,51 +4846,54 @@
 #: kallithea/templates/changelog/changelog_summary_data.html:20
 #, python-format
 msgid ""
-"Changeset status: %s\n"
+"Changeset status: %s by %s\n"
 "Click to open associated pull request %s"
 msgstr ""
 
 #: kallithea/templates/changelog/changelog.html:96
-#: kallithea/templates/compare/compare_cs.html:24
-#, python-format
-msgid "Changeset status: %s"
-msgstr ""
-
-#: kallithea/templates/changelog/changelog.html:115
+#: kallithea/templates/changelog/changelog_summary_data.html:24
+#, fuzzy, python-format
+#| msgid "Set changeset status"
+msgid "Changeset status: %s by %s"
+msgstr "Setze Changesetstatus"
+
+#: kallithea/templates/changelog/changelog.html:116
 #: kallithea/templates/compare/compare_cs.html:63
 msgid "Expand commit message"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:124
+#: kallithea/templates/changelog/changelog.html:125
 #: kallithea/templates/compare/compare_cs.html:30
 msgid "Changeset has comments"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:134
-#: kallithea/templates/changelog/changelog_summary_data.html:54
+#: kallithea/templates/changelog/changelog.html:135
+#: kallithea/templates/changelog/changelog_summary_data.html:57
 #: kallithea/templates/changeset/changeset.html:94
 #: kallithea/templates/changeset/changeset_range.html:92
 #, python-format
 msgid "Bookmark %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:140
-#: kallithea/templates/changelog/changelog_summary_data.html:60
+#: kallithea/templates/changelog/changelog.html:141
+#: kallithea/templates/changelog/changelog_summary_data.html:63
 #: kallithea/templates/changeset/changeset.html:101
 #: kallithea/templates/changeset/changeset_range.html:98
+#: kallithea/templates/compare/compare_cs.html:69
+#: kallithea/templates/pullrequests/pullrequest_show.html:203
 #, python-format
 msgid "Tag %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:145
-#: kallithea/templates/changelog/changelog_summary_data.html:65
+#: kallithea/templates/changelog/changelog.html:146
+#: kallithea/templates/changelog/changelog_summary_data.html:68
 #: kallithea/templates/changeset/changeset.html:106
 #: kallithea/templates/changeset/changeset_range.html:102
 #, python-format
 msgid "Branch %s"
 msgstr "Branch %s"
 
-#: kallithea/templates/changelog/changelog.html:291
+#: kallithea/templates/changelog/changelog.html:311
 msgid "There are no changes yet"
 msgstr "Bisher gibt es keine Änderungen"
 
@@ -4944,7 +4909,7 @@
 
 #: kallithea/templates/changelog/changelog_details.html:6
 #: kallithea/templates/changeset/changeset.html:79
-#: kallithea/templates/changeset/diff_block.html:79
+#: kallithea/templates/changeset/diff_block.html:47
 msgid "Added"
 msgstr ""
 
@@ -4974,23 +4939,22 @@
 msgid "Refs"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:81
+#: kallithea/templates/changelog/changelog_summary_data.html:84
 msgid "Add or upload files directly via Kallithea"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:84
+#: kallithea/templates/changelog/changelog_summary_data.html:87
 #: kallithea/templates/files/files_add.html:21
 #: kallithea/templates/files/files_ypjax.html:9
 msgid "Add New File"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:90
+#: kallithea/templates/changelog/changelog_summary_data.html:93
 #, fuzzy
-#| msgid "private repository"
 msgid "Push new repository"
 msgstr "privates Repository"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:98
+#: kallithea/templates/changelog/changelog_summary_data.html:101
 msgid "Existing repository?"
 msgstr ""
 
@@ -5008,13 +4972,13 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:50
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #: kallithea/templates/changeset/changeset_range.html:48
 msgid "Changeset status"
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:54
-#: kallithea/templates/changeset/diff_block.html:27
+#: kallithea/templates/changeset/diff_block.html:72
 #: kallithea/templates/files/diff_2way.html:49
 msgid "Raw diff"
 msgstr ""
@@ -5024,7 +4988,7 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:60
-#: kallithea/templates/changeset/diff_block.html:30
+#: kallithea/templates/changeset/diff_block.html:75
 #: kallithea/templates/files/diff_2way.html:52
 msgid "Download diff"
 msgstr ""
@@ -5044,19 +5008,17 @@
 
 #: kallithea/templates/changeset/changeset.html:135
 #, fuzzy
-#| msgid "Created by"
 msgid "Replaced by:"
 msgstr "Erstellt von"
 
 #: kallithea/templates/changeset/changeset.html:149
 #, fuzzy
-#| msgid "Created by"
 msgid "Preceded by:"
 msgstr "Erstellt von"
 
 #: kallithea/templates/changeset/changeset.html:166
-#: kallithea/templates/compare/compare_diff.html:54
-#: kallithea/templates/pullrequests/pullrequest_show.html:314
+#: kallithea/templates/compare/compare_diff.html:60
+#: kallithea/templates/pullrequests/pullrequest_show.html:329
 #, python-format
 msgid "%s file changed"
 msgid_plural "%s files changed"
@@ -5064,8 +5026,8 @@
 msgstr[1] ""
 
 #: kallithea/templates/changeset/changeset.html:168
-#: kallithea/templates/compare/compare_diff.html:56
-#: kallithea/templates/pullrequests/pullrequest_show.html:316
+#: kallithea/templates/compare/compare_diff.html:62
+#: kallithea/templates/pullrequests/pullrequest_show.html:331
 #, python-format
 msgid "%s file changed with %s insertions and %s deletions"
 msgid_plural "%s files changed with %s insertions and %s deletions"
@@ -5074,21 +5036,19 @@
 
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/pullrequests/pullrequest_show.html:335
-#: kallithea/templates/pullrequests/pullrequest_show.html:359
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Show full diff anyway"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset.html:247
-#: kallithea/templates/changeset/changeset.html:284
+#: kallithea/templates/changeset/changeset.html:231
+#: kallithea/templates/changeset/changeset.html:268
 #, fuzzy
-#| msgid "revisions"
 msgid "No revisions"
 msgstr "revisionen"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:21
 #, fuzzy
-#| msgid "Comment from pull request"
 msgid "on pull request"
 msgstr "Kommentar von Pull Request"
 
@@ -5097,107 +5057,91 @@
 msgstr "Kein Titel"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:24
-#, fuzzy, python-format
-#| msgid "%s changesets"
+#, fuzzy
 msgid "on this changeset"
 msgstr "%s Changesets"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
 msgid "Delete comment?"
 msgstr "Kommentar löschen?"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #, fuzzy
-#| msgid "Latest Changes"
 msgid "Status change"
 msgstr "Letzte Änderungen"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:59
-msgid "Commenting on line {1}."
+msgid "Commenting on line."
 msgstr ""
 
 #: kallithea/templates/changeset/changeset_file_comment.html:60
-#: kallithea/templates/changeset/changeset_file_comment.html:148
-#, python-format
-msgid "Comments parsed using %s syntax with %s support."
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:62
-msgid "Use @username inside this text to notify another user"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:72
-#: kallithea/templates/changeset/changeset_file_comment.html:184
-msgid "Comment preview"
-msgstr "Kommentarvorschau"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:77
+msgid ""
+"Comments are in plain text. Use @username inside this text to notify "
+"another user."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:67
+msgid "Set changeset status"
+msgstr "Setze Changesetstatus"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:69
+msgid "Vote for pull request status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:75
+msgid "No change"
+msgstr "Keine Änderungen"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:88
+#, fuzzy
+msgid "Finish pull request"
+msgstr "Kommentar von Pull Request"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:91
+msgid "Close"
+msgstr "Schließen"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:103
 msgid "Submitting ..."
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:80
-#: kallithea/templates/changeset/changeset_file_comment.html:190
+#: kallithea/templates/changeset/changeset_file_comment.html:104
 msgid "Comment"
 msgstr "Kommentar"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:82
-#: kallithea/templates/changeset/changeset_file_comment.html:191
-msgid "Preview"
-msgstr "Vorschau"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "You need to be logged in to comment."
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "Login now"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:94
+#: kallithea/templates/changeset/changeset_file_comment.html:116
 msgid "Hide"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:106
+#: kallithea/templates/changeset/changeset_file_comment.html:128
 #, python-format
 msgid "%d comment"
 msgid_plural "%d comments"
 msgstr[0] "%d Kommentar"
 msgstr[1] "%d Kommentare"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:107
+#: kallithea/templates/changeset/changeset_file_comment.html:129
 #, python-format
 msgid "%d inline"
 msgid_plural "%d inline"
 msgstr[0] "%d inline"
 msgstr[1] "%d inline"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:108
+#: kallithea/templates/changeset/changeset_file_comment.html:130
 #, python-format
 msgid "%d general"
 msgid_plural "%d general"
 msgstr[0] "%d generell"
 msgstr[1] "%d generell"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:150
-msgid "Use @username inside this text to notify another user."
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:157
-msgid "Vote for pull request status"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:159
-msgid "Set changeset status"
-msgstr "Setze Changesetstatus"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:163
-msgid "No change"
-msgstr "Keine Änderungen"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:176
-msgid "Close"
-msgstr "Schließen"
-
 #: kallithea/templates/changeset/changeset_range.html:5
 #, python-format
 msgid "%s Changesets"
@@ -5207,29 +5151,28 @@
 msgid "Files affected"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:21
+#: kallithea/templates/changeset/diff_block.html:54
+msgid "Deleted"
+msgstr "Gelöscht"
+
+#: kallithea/templates/changeset/diff_block.html:57
+msgid "Renamed"
+msgstr "Umbenannt"
+
+#: kallithea/templates/changeset/diff_block.html:66
 #: kallithea/templates/files/diff_2way.html:43
 msgid "Show full diff for this file"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:24
-#: kallithea/templates/changeset/diff_block.html:98
+#: kallithea/templates/changeset/diff_block.html:69
 #: kallithea/templates/files/diff_2way.html:46
 msgid "Show full side-by-side diff for this file"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:38
+#: kallithea/templates/changeset/diff_block.html:83
 msgid "Show inline comments"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:86
-msgid "Deleted"
-msgstr "Gelöscht"
-
-#: kallithea/templates/changeset/diff_block.html:89
-msgid "Renamed"
-msgstr "Umbenannt"
-
 #: kallithea/templates/compare/compare_cs.html:4
 msgid "No changesets"
 msgstr ""
@@ -5238,6 +5181,11 @@
 msgid "Ancestor"
 msgstr ""
 
+#: kallithea/templates/compare/compare_cs.html:24
+#, python-format
+msgid "Changeset status: %s"
+msgstr ""
+
 #: kallithea/templates/compare/compare_cs.html:44
 msgid "First (oldest) changeset in this list"
 msgstr ""
@@ -5250,29 +5198,29 @@
 msgid "Position in this list of changesets"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:76
+#: kallithea/templates/compare/compare_cs.html:85
 msgid "Show merge diff"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:86
-#: kallithea/templates/pullrequests/pullrequest_show.html:306
+#: kallithea/templates/compare/compare_cs.html:95
+#: kallithea/templates/pullrequests/pullrequest_show.html:321
 msgid "Common ancestor"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:90
-msgid "No common ancestor found - repositories are unrelated"
-msgstr ""
-
-#: kallithea/templates/compare/compare_cs.html:98
-msgid "is"
-msgstr ""
-
 #: kallithea/templates/compare/compare_cs.html:99
+msgid "No common ancestor found - repositories are unrelated"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:107
+msgid "is"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:108
 #, python-format
 msgid "%s changesets"
 msgstr "%s Changesets"
 
-#: kallithea/templates/compare/compare_cs.html:100
+#: kallithea/templates/compare/compare_cs.html:109
 msgid "behind"
 msgstr "zurück"
 
@@ -5283,28 +5231,28 @@
 msgstr ""
 
 #: kallithea/templates/compare/compare_diff.html:13
-#: kallithea/templates/compare/compare_diff.html:35
+#: kallithea/templates/compare/compare_diff.html:41
 msgid "Compare Revisions"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:33
+#: kallithea/templates/compare/compare_diff.html:39
 msgid "Swap"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:42
+#: kallithea/templates/compare/compare_diff.html:48
 msgid "Compare revisions, branches, bookmarks, or tags."
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:47
-#: kallithea/templates/pullrequests/pullrequest_show.html:301
+#: kallithea/templates/compare/compare_diff.html:53
+#: kallithea/templates/pullrequests/pullrequest_show.html:316
 #, python-format
 msgid "Showing %s commit"
 msgid_plural "Showing %s commits"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
 msgid "Show full diff"
 msgstr ""
 
@@ -5360,20 +5308,33 @@
 msgstr "Hallo %s"
 
 #: kallithea/templates/email_templates/password_reset.html:6
-msgid "We received a request to create a new password for your account."
+#, fuzzy
+msgid "We have received a request to reset the password for your account."
 msgstr ""
 "Wir haben eine Anforderung erhalten, für deinen Account ein neues "
 "Passwort zu erstellen."
 
-#: kallithea/templates/email_templates/password_reset.html:7
-msgid "You can generate it by clicking following URL"
-msgstr "Du kannst es über die folgende URL erstellen"
+#: kallithea/templates/email_templates/password_reset.html:8
+msgid ""
+"This account is however managed outside this system and the password "
+"cannot be changed here."
+msgstr ""
 
 #: kallithea/templates/email_templates/password_reset.html:10
-msgid "Please ignore this email if you did not request a new password ."
-msgstr ""
-"Bitte ignoriere diese E-Mail, wenn du kein neues Passwort angefordert "
-"hast."
+msgid "To set a new password, click the following link"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:13
+msgid ""
+"Should you not be able to use the link above, please type the following "
+"code into the password reset form"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:16
+msgid ""
+"If it weren't you who requested the password reset, just disregard this "
+"message."
+msgstr ""
 
 #: kallithea/templates/email_templates/pull_request.html:5
 #, python-format
@@ -5452,8 +5413,9 @@
 msgstr ""
 
 #: kallithea/templates/files/files_add.html:53
-msgid "New file mode"
-msgstr ""
+#, fuzzy
+msgid "New file type"
+msgstr "neue Datei"
 
 #: kallithea/templates/files/files_add.html:64
 #: kallithea/templates/files/files_delete.html:43
@@ -5583,10 +5545,19 @@
 msgid "Binary file (%s)"
 msgstr ""
 
-#: kallithea/templates/files/files_source.html:73
-msgid "File is too big to display"
+#: kallithea/templates/files/files_source.html:74
+#, fuzzy
+msgid "File is too big to display."
 msgstr "Die Datei ist zu groß, um sie anzuzeigen"
 
+#: kallithea/templates/files/files_source.html:76
+msgid "Show full annotation anyway."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:78
+msgid "Show as raw."
+msgstr ""
+
 #: kallithea/templates/files/files_ypjax.html:5
 msgid "annotation"
 msgstr ""
@@ -5733,7 +5704,6 @@
 
 #: kallithea/templates/pullrequests/pullrequest_data.html:14
 #, fuzzy
-#| msgid "revoke"
 msgid "Vote"
 msgstr "entziehen"
 
@@ -5774,20 +5744,16 @@
 
 #: kallithea/templates/pullrequests/pullrequest_data.html:70
 #, fuzzy, python-format
-#| msgid "Confirm to delete this group: %s with %s repository"
-#| msgid_plural "Confirm to delete this group: %s with %s repositories"
 msgid "Confirm again to delete this pull request with %s comments"
 msgstr "Löschen der Gruppe bestätigen: %s mit %s Repository"
 
 #: kallithea/templates/pullrequests/pullrequest_show.html:6
 #, fuzzy, python-format
-#| msgid "Pull request #%s"
 msgid "%s Pull Request %s"
 msgstr "Pull Request #%s"
 
 #: kallithea/templates/pullrequests/pullrequest_show.html:10
 #, fuzzy, python-format
-#| msgid "Pull request #%s from %s#%s"
 msgid "Pull request %s from %s#%s"
 msgstr "Pull Request #%s von %s#%s"
 
@@ -5835,98 +5801,111 @@
 msgid "Target"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:131
+#: kallithea/templates/pullrequests/pullrequest_show.html:124
+msgid ""
+"This is just a range of changesets and doesn't have a target or a real "
+"merge ancestor."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:133
 msgid "Pull changes"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:154
-msgid "Created by"
-msgstr "Erstellt von"
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:169
+#: kallithea/templates/pullrequests/pullrequest_show.html:173
 msgid "Update"
 msgstr "Aktualisierung"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:187
+#: kallithea/templates/pullrequests/pullrequest_show.html:191
 msgid "Current revision - no change"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:209
+#: kallithea/templates/pullrequests/pullrequest_show.html:215
+msgid ""
+"Pull requests do not change once created. Select a revision and save to "
+"replace this pull request with a new one."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:224
 msgid "Pull Request Reviewers"
 msgstr "Pull Request Reviewers"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:234
+#: kallithea/templates/pullrequests/pullrequest_show.html:249
 msgid "Remove reviewer"
 msgstr "Reviewer entfernen"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:246
+#: kallithea/templates/pullrequests/pullrequest_show.html:261
 msgid "Type name of reviewer to add"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:254
+#: kallithea/templates/pullrequests/pullrequest_show.html:269
 msgid "Potential Reviewers"
 msgstr "Potentielle Reviewer"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:257
+#: kallithea/templates/pullrequests/pullrequest_show.html:272
 msgid "Click to add the repository owner as reviewer:"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:280
+#: kallithea/templates/pullrequests/pullrequest_show.html:295
 msgid "Save Changes"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:281
-msgid "Save as New Pull Request"
+#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#, fuzzy
+msgid "Save Updates as New Pull Request"
 msgstr "Als neuen Pull Request speichern"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:282
+#: kallithea/templates/pullrequests/pullrequest_show.html:297
 msgid "Cancel Changes"
 msgstr "Änderungen verwerfen"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:292
+#: kallithea/templates/pullrequests/pullrequest_show.html:307
 msgid "Pull Request Content"
 msgstr "Inhalt des Pull Requests"
 
-#: kallithea/templates/pullrequests/pullrequest_show_all.html:4
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:6
 #, python-format
 msgid "%s Pull Requests"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show_all.html:9
-#, python-format
-msgid "Pull Requests from %s'"
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:11
+#, fuzzy, python-format
+msgid "Pull Requests from '%s'"
 msgstr "Pull Requests von '%s'"
 
-#: kallithea/templates/pullrequests/pullrequest_show_all.html:11
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:13
 #, python-format
 msgid "Pull Requests to '%s'"
 msgstr "Pull Requests für '%s'"
 
-#: kallithea/templates/pullrequests/pullrequest_show_all.html:35
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:32
+msgid "Open New Pull Request"
+msgstr "Einen neuen Pull Request eröffnen"
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:37
 #, python-format
 msgid "Show Pull Requests to %s"
 msgstr "Zeige Pull Requests für '%s'"
 
-#: kallithea/templates/pullrequests/pullrequest_show_all.html:37
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:39
 #, python-format
 msgid "Show Pull Requests from '%s'"
 msgstr "Zeige Pull Requests von '%s'"
 
-#: kallithea/templates/pullrequests/pullrequest_show_all.html:47
-#: kallithea/templates/pullrequests/pullrequest_show_my.html:26
-msgid "Hide closed pull requests (only show open pull requests)"
-msgstr ""
-
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:49
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:28
+msgid "Hide closed pull requests (only show open pull requests)"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:51
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:30
 msgid "Show closed pull requests (in addition to open pull requests)"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show_my_data.html:3
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:35
 msgid "Pull Requests Created by Me"
 msgstr "Von mir erstellte Pull Requests"
 
-#: kallithea/templates/pullrequests/pullrequest_show_my_data.html:6
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:38
 msgid "Pull Requests I Participate In"
 msgstr ""
 
@@ -6177,14 +6156,9 @@
 
 #~ msgid "Invalid clone URL, provide a valid clone http(s)/svn+http(s)/ssh URL"
 #~ msgstr ""
-#~ "Ungültige Clone-URL, gültige Clone-URL"
-#~ " (http(s)/svn+http(s)/ssh) angeben"
 
 #~ msgid "Revisions %(revs)s are already part of pull request or have set status"
 #~ msgstr ""
-#~ "Die Revisionen %(revs)s sind bereits "
-#~ "Bestandteil des Pull Requests oder haben"
-#~ " den Status"
 
 #~ msgid "Defaults"
 #~ msgstr "Voreinstellungen"
@@ -6208,9 +6182,8 @@
 #~ msgstr "löschen"
 
 #~ msgid ""
-#~ "Your user is in an external source"
-#~ " of record; some details cannot be"
-#~ " managed here"
+#~ "_: \n"
+#~ ""
 #~ msgstr ""
 
 #~ msgid "Permissions Administration"
@@ -6264,20 +6237,6 @@
 #~ msgid "Non-changeable id"
 #~ msgstr ""
 
-#~ msgid ""
-#~ "In case this repository is renamed "
-#~ "or moved into another group the "
-#~ "repository URL changes.\n"
-#~ "                               Using the above "
-#~ "URL guarantees that this repository will"
-#~ " always be accessible under such URL."
-#~ "\n"
-#~ "                               Useful for CI "
-#~ "systems, or any other cases that "
-#~ "you need to hardcode the URL into"
-#~ " 3rd party service."
-#~ msgstr ""
-
 #~ msgid "edit"
 #~ msgstr "bearbeiten"
 
@@ -6323,12 +6282,6 @@
 #~ msgid "Destroy old data"
 #~ msgstr ""
 
-#~ msgid ""
-#~ "Check this option to remove references"
-#~ " to repositories that no longer exist"
-#~ " in on the filesystem."
-#~ msgstr ""
-
 #~ msgid "Meta-Tagging"
 #~ msgstr ""
 
@@ -6338,29 +6291,12 @@
 #~ msgid "user groups"
 #~ msgstr "Benutzergruppen"
 
-#~ msgid ""
-#~ "This user is in an external source"
-#~ " of record (%s); some details cannot"
-#~ " be managed here."
-#~ msgstr ""
-
 #~ msgid "Inherit from defaults"
 #~ msgstr ""
 
-#~ msgid ""
-#~ "Select to inherit permissions from %s"
-#~ " permissions settings, and default IP "
-#~ "address whitelist."
-#~ msgstr ""
-
 #~ msgid "show"
 #~ msgstr ""
 
-#~ msgid ""
-#~ "Changeset status: %s\n"
-#~ "Click to open associated pull request #%s"
-#~ msgstr ""
-
 #~ msgid "Push new repo"
 #~ msgstr ""
 
@@ -6385,11 +6321,6 @@
 #~ msgid "Comment on changeset"
 #~ msgstr ""
 
-#~ msgid ""
-#~ "Use @username inside this text to "
-#~ "send notification to another local user."
-#~ msgstr ""
-
 #~ msgid "revision"
 #~ msgstr ""
 
@@ -6416,3 +6347,56 @@
 
 #~ msgid "with subrepos"
 #~ msgstr ""
+
+#~ msgid "This pull request can be updated with changes on %s:"
+#~ msgstr "Dieser Pull Request kann mit Änderungen in %s aktualisiert werden:"
+
+#~ msgid "Your new password"
+#~ msgstr "Dein neues Passwort"
+
+#~ msgid "Your new Kallithea password:%s"
+#~ msgstr "Ihr neues Kallithea-Passwort: %s"
+
+#~ msgid "Confirm to invalidate repository cache."
+#~ msgstr ""
+
+#~ msgid "Open New Pull Request for Selected Changesets"
+#~ msgstr ""
+
+#~ msgid "Show Selected Changesets __S &rarr; __E"
+#~ msgstr ""
+
+#~ msgid "Commenting on line {1}."
+#~ msgstr ""
+
+#~ msgid "Comments parsed using %s syntax with %s support."
+#~ msgstr ""
+
+#~ msgid "Use @username inside this text to notify another user"
+#~ msgstr ""
+
+#~ msgid "Comment preview"
+#~ msgstr "Kommentarvorschau"
+
+#~ msgid "Preview"
+#~ msgstr "Vorschau"
+
+#~ msgid "Use @username inside this text to notify another user."
+#~ msgstr ""
+
+#~ msgid "You can generate it by clicking following URL"
+#~ msgstr "Du kannst es über die folgende URL erstellen"
+
+#~ msgid "Please ignore this email if you did not request a new password ."
+#~ msgstr ""
+
+#~ msgid "New file mode"
+#~ msgstr ""
+
+#~ msgid "Created by"
+#~ msgstr "Erstellt von"
+
+#~ msgid ""
+#~ "Changeset status: %s\n"
+#~ "Click to open associated pull request %s"
+#~ msgstr ""
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/i18n/el/LC_MESSAGES/kallithea.po	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,6015 @@
+# Greek translations for Kallithea.
+# Copyright (C) 2015 Various authors, licensing as GPLv3
+# This file is distributed under the same license as the Kallithea project.
+# Automatically generated, 2015.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: Kallithea 0.3\n"
+"Report-Msgid-Bugs-To: translations@kallithea-scm.org\n"
+"POT-Creation-Date: 2016-03-14 16:51+0100\n"
+"PO-Revision-Date: 2016-02-10 12:01+0000\n"
+"Last-Translator: Asterios Dimitriou <steve@pci.gr>\n"
+"Language-Team: Greek "
+"<https://hosted.weblate.org/projects/kallithea/kallithea/el/>\n"
+"Language: el\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+"X-Generator: Weblate 2.5-dev\n"
+
+#: kallithea/controllers/changelog.py:85
+#: kallithea/controllers/pullrequests.py:240 kallithea/lib/base.py:515
+msgid "There are no changesets yet"
+msgstr "Δεν υπάρχουν σετ αλλαγών ακόμα"
+
+#: kallithea/controllers/changelog.py:164
+#: kallithea/controllers/admin/permissions.py:61
+#: kallithea/controllers/admin/permissions.py:65
+#: kallithea/controllers/admin/permissions.py:69
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:7
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:104
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:8
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:7
+#: kallithea/templates/base/perms_summary.html:14
+msgid "None"
+msgstr "Χωρίς"
+
+#: kallithea/controllers/changelog.py:167 kallithea/controllers/files.py:198
+msgid "(closed)"
+msgstr "(κλειστό)"
+
+#: kallithea/controllers/changeset.py:88
+msgid "Show whitespace"
+msgstr "Εμφάνιση κενού"
+
+#: kallithea/controllers/changeset.py:95 kallithea/controllers/changeset.py:102
+#: kallithea/templates/files/diff_2way.html:55
+msgid "Ignore whitespace"
+msgstr "Αγνόηση κενού"
+
+#: kallithea/controllers/changeset.py:168
+#, python-format
+msgid "Increase diff context to %(num)s lines"
+msgstr "Αύξηση του diff πλαισίου σε %(num)s γραμμές"
+
+#: kallithea/controllers/changeset.py:233 kallithea/controllers/files.py:97
+#: kallithea/controllers/files.py:117 kallithea/controllers/files.py:744
+msgid "Such revision does not exist for this repository"
+msgstr "Δεν υπάρχει τέτοια αναθεώρηση για αυτό το αποθετήριο"
+
+#: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:41
+msgid "Select changeset"
+msgstr "Επιλογή σετ αλλαγών"
+
+#: kallithea/controllers/compare.py:261
+msgid "Cannot compare repositories without using common ancestor"
+msgstr ""
+"Δεν μπορεί να γίνει σύγκριση αποθετηρίων χωρίς να χρησιμοποιηθεί κοινός "
+"πρόγονος"
+
+#: kallithea/controllers/error.py:71
+msgid "No response"
+msgstr "Χωρίς απόκριση"
+
+#: kallithea/controllers/error.py:72
+msgid "Unknown error"
+msgstr "Άγνωστο λάθος"
+
+#: kallithea/controllers/error.py:100
+msgid "The request could not be understood by the server due to malformed syntax."
+msgstr ""
+"Η αίτηση δεν  μπόρεσε να ερμηνευτεί από τον εξυπηρετητή λόγω κακής "
+"διατύπωσης."
+
+#: kallithea/controllers/error.py:103
+msgid "Unauthorized access to resource"
+msgstr "Ανεξουσιοδοτημένη πρόσβαση στον πόρο"
+
+#: kallithea/controllers/error.py:105
+msgid "You don't have permission to view this page"
+msgstr "Δεν έχετε άδεια για να εμφανίσετε αυτή τη σελίδα"
+
+#: kallithea/controllers/error.py:107
+msgid "The resource could not be found"
+msgstr "Ο πόρος δεν μπορεί να βρεθεί"
+
+#: kallithea/controllers/error.py:109
+msgid ""
+"The server encountered an unexpected condition which prevented it from "
+"fulfilling the request."
+msgstr ""
+"Ο εξυπηρετητής συνάντησε μια απρόσμενη κατάσταση που τον απέτρεψαν να "
+"πραγματοποιήσει την αίτηση."
+
+#: kallithea/controllers/feed.py:55
+#, python-format
+msgid "Changes on %s repository"
+msgstr "Αλλαγές στο αποθετήριο %s"
+
+#: kallithea/controllers/feed.py:56
+#, python-format
+msgid "%s %s feed"
+msgstr "%s %s τροφοδοσία"
+
+#: kallithea/controllers/feed.py:87
+#: kallithea/templates/changeset/changeset.html:182
+#: kallithea/templates/changeset/changeset.html:195
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
+msgid "Changeset was too big and was cut off..."
+msgstr "Το σετ αλλαγών ήταν πολύ μεγάλο και περικόπηκε..."
+
+#: kallithea/controllers/feed.py:91
+#, python-format
+msgid "%s committed on %s"
+msgstr "%s συνέβαλε στο %s"
+
+#: kallithea/controllers/files.py:92
+msgid "Click here to add new file"
+msgstr "Κλικ εδώ για προθήκη νέου αρχείου"
+
+#: kallithea/controllers/files.py:93
+#, python-format
+msgid "There are no files yet. %s"
+msgstr "Δεν υπάρχουν αρχεία ακόμα. %s"
+
+#: kallithea/controllers/files.py:195
+#, python-format
+msgid "%s at %s"
+msgstr "%s την %s"
+
+#: kallithea/controllers/files.py:307 kallithea/controllers/files.py:367
+#: kallithea/controllers/files.py:434
+#, python-format
+msgid "This repository has been locked by %s on %s"
+msgstr "Το αποθετήριο κλειδώθηκε από %s την %s"
+
+#: kallithea/controllers/files.py:319
+#, fuzzy
+msgid "You can only delete files with revision being a valid branch"
+msgstr ""
+"Μπορείτε να διαγράψετε μόνο αρχεία σε αναθεώρηση που βρίσκονται σε έγκυρη"
+" διακλάδωση "
+
+#: kallithea/controllers/files.py:330
+#, python-format
+msgid "Deleted file %s via Kallithea"
+msgstr "Διαγραφή αρχείου %s μέσω του Kallithea"
+
+#: kallithea/controllers/files.py:352
+#, python-format
+msgid "Successfully deleted file %s"
+msgstr "Επιτυχής διαγραφή αρχείου %s"
+
+#: kallithea/controllers/files.py:356 kallithea/controllers/files.py:422
+#: kallithea/controllers/files.py:503
+msgid "Error occurred during commit"
+msgstr "Συνέβη λάθος κατά το commit"
+
+#: kallithea/controllers/files.py:379
+#, fuzzy
+msgid "You can only edit files with revision being a valid branch"
+msgstr ""
+"Μπορείτε να επεξεργαστείτε μόνο αρχεία σε αναθεώρηση που βρίσκονται σε "
+"έγκυρη διακλάδωση "
+
+#: kallithea/controllers/files.py:393
+#, python-format
+msgid "Edited file %s via Kallithea"
+msgstr "Επεξεργασία αρχείου %s μέσω του Kallithea"
+
+#: kallithea/controllers/files.py:409
+msgid "No changes"
+msgstr "Καμία αλλαγή"
+
+#: kallithea/controllers/files.py:418 kallithea/controllers/files.py:492
+#, python-format
+msgid "Successfully committed to %s"
+msgstr "Επιτυχής παράδοση σε %s"
+
+#: kallithea/controllers/files.py:445
+msgid "Added file via Kallithea"
+msgstr "Προσθήκη αρχείου μέσω Kallithea"
+
+#: kallithea/controllers/files.py:466
+msgid "No content"
+msgstr "Χωρίς περιεχόμενο"
+
+#: kallithea/controllers/files.py:470
+msgid "No filename"
+msgstr "Χωρίς όνομα αρχείου"
+
+#: kallithea/controllers/files.py:495
+msgid "Location must be relative path and must not contain .. in path"
+msgstr ""
+"Η τοποθεσία πρέπει να είναι σχετική διαδρομή και να μην περιέχει .. μέσα "
+"της"
+
+#: kallithea/controllers/files.py:528
+msgid "Downloads disabled"
+msgstr "Οι μεταφορτώσεις απενεργοποιήθηκαν"
+
+#: kallithea/controllers/files.py:539
+#, python-format
+msgid "Unknown revision %s"
+msgstr "Άγνωστη αναθεώρηση %s"
+
+#: kallithea/controllers/files.py:541
+msgid "Empty repository"
+msgstr "Άδειο αποθετήριο"
+
+#: kallithea/controllers/files.py:543
+msgid "Unknown archive type"
+msgstr "Άγνωστος τύπος αρχειοθέτησης"
+
+#: kallithea/controllers/files.py:773
+#: kallithea/templates/changeset/changeset_range.html:9
+#: kallithea/templates/email_templates/pull_request.html:15
+#: kallithea/templates/pullrequests/pullrequest.html:97
+msgid "Changesets"
+msgstr "Σετ αλλαγών"
+
+#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:175
+#: kallithea/model/scm.py:716 kallithea/templates/switch_to_list.html:3
+#: kallithea/templates/branches/branches.html:10
+msgid "Branches"
+msgstr "Κλάδοι"
+
+#: kallithea/controllers/files.py:775 kallithea/controllers/pullrequests.py:176
+#: kallithea/model/scm.py:727 kallithea/templates/switch_to_list.html:25
+#: kallithea/templates/tags/tags.html:10
+msgid "Tags"
+msgstr "Ετικέτες"
+
+#: kallithea/controllers/forks.py:186
+#, python-format
+msgid "An error occurred during repository forking %s"
+msgstr "Συνέβει ένα λάθος κατά την διακλάδωση του αποθετηρίου %s"
+
+#: kallithea/controllers/home.py:84
+msgid "Groups"
+msgstr "Ομάδες"
+
+#: kallithea/controllers/home.py:94
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:106
+#: kallithea/templates/admin/repos/repo_add.html:12
+#: kallithea/templates/admin/repos/repo_add.html:16
+#: kallithea/templates/admin/repos/repos.html:9
+#: kallithea/templates/admin/users/user_edit_advanced.html:6
+#: kallithea/templates/base/base.html:60 kallithea/templates/base/base.html:77
+#: kallithea/templates/base/base.html:124
+#: kallithea/templates/base/base.html:479
+#: kallithea/templates/base/base.html:653
+msgid "Repositories"
+msgstr "Αποθετήρια"
+
+#: kallithea/controllers/home.py:139
+#: kallithea/templates/files/files_add.html:32
+#: kallithea/templates/files/files_delete.html:23
+#: kallithea/templates/files/files_edit.html:32
+msgid "Branch"
+msgstr "Κλάδος"
+
+#: kallithea/controllers/home.py:145 kallithea/templates/switch_to_list.html:16
+msgid "Closed Branches"
+msgstr ""
+
+#: kallithea/controllers/home.py:151
+msgid "Tag"
+msgstr "Ετικέτα"
+
+#: kallithea/controllers/home.py:157
+msgid "Bookmark"
+msgstr "Σελιδοδείκτης"
+
+#: kallithea/controllers/journal.py:111 kallithea/controllers/journal.py:153
+#: kallithea/templates/journal/public_journal.html:4
+#: kallithea/templates/journal/public_journal.html:21
+msgid "Public Journal"
+msgstr "Δημόσιο Ημερολόγιο"
+
+#: kallithea/controllers/journal.py:115 kallithea/controllers/journal.py:157
+#: kallithea/templates/base/base.html:306
+#: kallithea/templates/journal/journal.html:4
+#: kallithea/templates/journal/journal.html:12
+msgid "Journal"
+msgstr "Ημερολόγιο"
+
+#: kallithea/controllers/login.py:144 kallithea/controllers/login.py:190
+msgid "Bad captcha"
+msgstr "Λάθος captcha"
+
+#: kallithea/controllers/login.py:150
+msgid "You have successfully registered with %s"
+msgstr "Εγγραφήκατε επιτυχώς στο %s"
+
+#: kallithea/controllers/login.py:195
+msgid "A password reset confirmation code has been sent"
+msgstr "Στάλθηκε ένας κωδικός επιβεβαίωσης επαναφοράς του συνθηματικού"
+
+#: kallithea/controllers/login.py:244
+msgid "Invalid password reset token"
+msgstr "Άκυρο τεκμήριο (token) επαναφοράς του συνθηματικού"
+
+#: kallithea/controllers/login.py:249
+#: kallithea/controllers/admin/my_account.py:167
+msgid "Successfully updated password"
+msgstr "Το συνθηματικό ενημερώθηκε επιτυχώς"
+
+#: kallithea/controllers/pullrequests.py:123
+#, python-format
+msgid "%s (closed)"
+msgstr "%s (κλειστό)"
+
+#: kallithea/controllers/pullrequests.py:151
+#: kallithea/templates/changeset/changeset.html:12
+#: kallithea/templates/email_templates/changeset_comment.html:17
+msgid "Changeset"
+msgstr "Σετ αλλαγών"
+
+#: kallithea/controllers/pullrequests.py:172
+msgid "Special"
+msgstr "Ειδικός"
+
+#: kallithea/controllers/pullrequests.py:173
+msgid "Peer branches"
+msgstr "Ομότιμοι κλάδοι"
+
+#: kallithea/controllers/pullrequests.py:174 kallithea/model/scm.py:722
+#: kallithea/templates/switch_to_list.html:38
+#: kallithea/templates/bookmarks/bookmarks.html:10
+msgid "Bookmarks"
+msgstr "Σελιδοδείκτες"
+
+#: kallithea/controllers/pullrequests.py:312
+#, python-format
+msgid "Error creating pull request: %s"
+msgstr "Λάθος στη δημιουργία αιτήματος έλξης - pull request: %s"
+
+#: kallithea/controllers/pullrequests.py:358
+#: kallithea/controllers/pullrequests.py:505
+msgid "No description"
+msgstr "Χωρίς περιγραφή"
+
+#: kallithea/controllers/pullrequests.py:365
+msgid "Successfully opened new pull request"
+msgstr "Ένα νέο αίτημα έλξης (pull request) δημιουργήθηκε επιτυχώς"
+
+#: kallithea/controllers/pullrequests.py:368
+#: kallithea/controllers/pullrequests.py:455
+#: kallithea/controllers/pullrequests.py:512
+#, python-format
+msgid "Invalid reviewer \"%s\" specified"
+msgstr "Καθορίστηκε άκυρος σχολιαστής \"%s\""
+
+#: kallithea/controllers/pullrequests.py:371
+#: kallithea/controllers/pullrequests.py:458
+msgid "Error occurred while creating pull request"
+msgstr "Λάθος κατά τη δημιουργία αιτήματος έλξης (pull request)"
+
+#: kallithea/controllers/pullrequests.py:403
+msgid "Missing changesets since the previous pull request:"
+msgstr "Ελλιπή σετ αλλαγών από την προηγούμενη αίτηση έλξης:"
+
+#: kallithea/controllers/pullrequests.py:410
+#, python-format
+msgid "New changesets on %s %s since the previous pull request:"
+msgstr "Καινούρια σετ αλλαγών στα %s %s από την προηγούμενη αίτηση έλξης:"
+
+#: kallithea/controllers/pullrequests.py:417
+msgid "Ancestor didn't change - show diff since previous version:"
+msgstr "Το γονικό δεν άλλαξε - εμφάνισε τις διαφορές από την προηγούμενη έκδοση:"
+
+#: kallithea/controllers/pullrequests.py:424
+#, python-format
+msgid ""
+"This pull request is based on another %s revision and there is no simple "
+"diff."
+msgstr ""
+"Αυτή η αίτηση έλξης είναι βασισμένη σε μία άλλη %s αναθεώρηση και δεν "
+"υπάρχει ένα απλό diff."
+
+#: kallithea/controllers/pullrequests.py:426
+#, python-format
+msgid "No changes found on %s %s since previous version."
+msgstr "Δεν βρέθηκαν αλλαγές στο %s %s από την προηγούμενη έκδοση."
+
+#: kallithea/controllers/pullrequests.py:464
+#, python-format
+msgid "Closed, replaced by %s ."
+msgstr "Κλειστό, αντικαταστάθηκε από %s."
+
+#: kallithea/controllers/pullrequests.py:472
+msgid "Pull request update created"
+msgstr "Δημιουργήθηκε ενημέρωση αιτήματος έλξης"
+
+#: kallithea/controllers/pullrequests.py:516
+msgid "Pull request updated"
+msgstr "Ενημερώθηκε η αίτηση έλξης"
+
+#: kallithea/controllers/pullrequests.py:531
+msgid "Successfully deleted pull request"
+msgstr "Επιτυχής διαγραφή αιτήματος έλξης"
+
+#: kallithea/controllers/pullrequests.py:597
+#, python-format
+msgid "This pull request has already been merged to %s."
+msgstr "Το αίτημα έλξης έχει ήδη συγχωνευτεί με το %s."
+
+#: kallithea/controllers/pullrequests.py:599
+msgid "This pull request has been closed and can not be updated."
+msgstr "Αυτό το αίτημα έλξης έχει κλείσει και δεν μπορεί να ενημερωθεί."
+
+#: kallithea/controllers/pullrequests.py:617
+#, python-format
+msgid "The following changes are available on %s:"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:621
+msgid "No changesets found for updating this pull request."
+msgstr "Δεν βρέθηκαν σετ αλλαγών για ενημέρωση αυτού του αιτήματος έλξης."
+
+#: kallithea/controllers/pullrequests.py:629
+#, python-format
+msgid "Note: Branch %s has another head: %s."
+msgstr "Σημείωση: Ο κλάδος %s έχει άλλη κεφαλή (head): %s."
+
+#: kallithea/controllers/pullrequests.py:635
+msgid "Git pull requests don't support updates yet."
+msgstr "Αιτήματα έλξης του git δεν υποστηρίζουν ακόμα ενημερώσεις."
+
+#: kallithea/controllers/pullrequests.py:727
+msgid "No permission to change pull request status"
+msgstr "Χωρίς δικαιώματα αλλαγής της κατάστασης του αιτήματος έλξης"
+
+#: kallithea/controllers/pullrequests.py:738
+#, fuzzy, python-format
+msgid "Successfully deleted pull request %s"
+msgstr "Επιτυχής διαγραφή αιτήματος έλξης"
+
+#: kallithea/controllers/pullrequests.py:748
+msgid "Closing."
+msgstr "Κλείνει."
+
+#: kallithea/controllers/search.py:135
+msgid "Invalid search query. Try quoting it."
+msgstr "Άκυρο αίτημα αναζήτησης. Δοκιμάστε με εισαγωγικά."
+
+#: kallithea/controllers/search.py:140
+msgid "There is no index to search in. Please run whoosh indexer"
+msgstr ""
+"Δεν υπάρχει ευρετήριο για την αναζήτηση. Παρακαλώ τρέξτε τον whoosh για "
+"την δημιουργία του"
+
+#: kallithea/controllers/search.py:144
+msgid "An error occurred during search operation."
+msgstr "Ένα λάθος συνέβη κατά την διαδικασία αναζήτησης."
+
+#: kallithea/controllers/summary.py:181
+#: kallithea/templates/summary/summary.html:384
+msgid "No data ready yet"
+msgstr "Δεν υπάρχουν ακόμα έτοιμα δεδομένα"
+
+#: kallithea/controllers/summary.py:184
+#: kallithea/templates/summary/summary.html:98
+msgid "Statistics are disabled for this repository"
+msgstr "Τα στατιστικά είναι απενεργοποιημένα για αυτό το αποθετήριο"
+
+#: kallithea/controllers/admin/auth_settings.py:135
+msgid "Auth settings updated successfully"
+msgstr "Οι ρυθμίσεις εξουσιοδότησης ενημερώθηκαν επιτυχώς"
+
+#: kallithea/controllers/admin/auth_settings.py:146
+msgid "error occurred during update of auth settings"
+msgstr "παρουσιάστηκε βλάβη κατά την ενημέρωση των ρυθμίσεων εξουσιοδότησης"
+
+#: kallithea/controllers/admin/defaults.py:97
+msgid "Default settings updated successfully"
+msgstr "Οι προεπιλεγμένες ρυθμίσεις ενημερώθηκαν επιτυχώς"
+
+#: kallithea/controllers/admin/defaults.py:112
+msgid "Error occurred during update of defaults"
+msgstr "Συνέβη μία βλάβη κατά την ενημέρωση των προεπιλογών"
+
+#: kallithea/controllers/admin/gists.py:58
+#: kallithea/controllers/admin/my_account.py:243
+#: kallithea/controllers/admin/users.py:284
+msgid "Forever"
+msgstr "Πάντα"
+
+#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/my_account.py:244
+#: kallithea/controllers/admin/users.py:285
+msgid "5 minutes"
+msgstr "5 λεπτά"
+
+#: kallithea/controllers/admin/gists.py:60
+#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/users.py:286
+msgid "1 hour"
+msgstr "1 ώρα"
+
+#: kallithea/controllers/admin/gists.py:61
+#: kallithea/controllers/admin/my_account.py:246
+#: kallithea/controllers/admin/users.py:287
+msgid "1 day"
+msgstr "1 ημέρα"
+
+#: kallithea/controllers/admin/gists.py:62
+#: kallithea/controllers/admin/my_account.py:247
+#: kallithea/controllers/admin/users.py:288
+msgid "1 month"
+msgstr "1 μήνας"
+
+#: kallithea/controllers/admin/gists.py:66
+#: kallithea/controllers/admin/my_account.py:249
+#: kallithea/controllers/admin/users.py:290
+msgid "Lifetime"
+msgstr "Διάρκεια ζωής"
+
+#: kallithea/controllers/admin/gists.py:145
+msgid "Error occurred during gist creation"
+msgstr "Συνέβη μία βλάβη κατά τη δημιουργία του gist"
+
+#: kallithea/controllers/admin/gists.py:183
+#, python-format
+msgid "Deleted gist %s"
+msgstr "Διαγράφηκε το gist %s"
+
+#: kallithea/controllers/admin/gists.py:232
+msgid "Unmodified"
+msgstr "Mη τροποποιημένo"
+
+#: kallithea/controllers/admin/gists.py:261
+msgid "Successfully updated gist content"
+msgstr "Το περιεχόμενο του gist ενημερώθηκε επιτυχώς"
+
+#: kallithea/controllers/admin/gists.py:266
+msgid "Successfully updated gist data"
+msgstr "Τα δεδομένα του gist ενημερώθηκαν επιτυχώς"
+
+#: kallithea/controllers/admin/gists.py:269
+#, python-format
+msgid "Error occurred during update of gist %s"
+msgstr "Σφάλμα συνέβη κατά την ενημέρωση του gist %s"
+
+#: kallithea/controllers/admin/my_account.py:70 kallithea/model/user.py:215
+#: kallithea/model/user.py:237
+msgid "You can't edit this user since it's crucial for entire application"
+msgstr ""
+"Δεν μπορείτε να επεξεργαστείτε αυτόν το χρήστη καθώς είναι κρίσιμος για "
+"όλη την εφαρμογή"
+
+#: kallithea/controllers/admin/my_account.py:129
+msgid "Your account was updated successfully"
+msgstr "Ο λογαριασμός σας ενημερώθηκε επιτυχώς"
+
+#: kallithea/controllers/admin/my_account.py:144
+#: kallithea/controllers/admin/users.py:201
+#, python-format
+msgid "Error occurred during update of user %s"
+msgstr "Συνέβη ένα σφάλμα κατά την ενημέρωση του χρήστη %s"
+
+#: kallithea/controllers/admin/my_account.py:178
+msgid "Error occurred during update of user password"
+msgstr "Συνέβη ένα σφάλμα κατά την ενημέρωση του κωδικού του χρήστη"
+
+#: kallithea/controllers/admin/my_account.py:220
+#: kallithea/controllers/admin/users.py:414
+#, python-format
+msgid "Added email %s to user"
+msgstr "Προστέθηκε το email %s στον χρήστη"
+
+#: kallithea/controllers/admin/my_account.py:226
+#: kallithea/controllers/admin/users.py:420
+msgid "An error occurred during email saving"
+msgstr "Συνέβη ένα σφάλμα κατά την αποθήκευση του email"
+
+#: kallithea/controllers/admin/my_account.py:235
+#: kallithea/controllers/admin/users.py:432
+msgid "Removed email from user"
+msgstr "Αφαιρέθηκε το email από τον χρήστη"
+
+#: kallithea/controllers/admin/my_account.py:259
+#: kallithea/controllers/admin/users.py:307
+msgid "API key successfully created"
+msgstr "Το API κλειδί δημιουργήθηκε επιτυχώς"
+
+#: kallithea/controllers/admin/my_account.py:271
+#: kallithea/controllers/admin/users.py:320
+msgid "API key successfully reset"
+msgstr "Το API κλειδί επαναφέρθηκε επιτυχώς"
+
+#: kallithea/controllers/admin/my_account.py:275
+#: kallithea/controllers/admin/users.py:324
+msgid "API key successfully deleted"
+msgstr "Το API κλειδί διαγράφηκε επιτυχώς"
+
+#: kallithea/controllers/admin/permissions.py:62
+#: kallithea/controllers/admin/permissions.py:66
+#: kallithea/controllers/admin/permissions.py:70
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:8
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:9
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:8
+#: kallithea/templates/base/perms_summary.html:15
+msgid "Read"
+msgstr "Ανάγνωση"
+
+#: kallithea/controllers/admin/permissions.py:63
+#: kallithea/controllers/admin/permissions.py:67
+#: kallithea/controllers/admin/permissions.py:71
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:9
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:10
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:9
+#: kallithea/templates/base/perms_summary.html:16
+msgid "Write"
+msgstr "Εγγραφή"
+
+#: kallithea/controllers/admin/permissions.py:64
+#: kallithea/controllers/admin/permissions.py:68
+#: kallithea/controllers/admin/permissions.py:72
+#: kallithea/templates/admin/auth/auth_settings.html:9
+#: kallithea/templates/admin/defaults/defaults.html:9
+#: kallithea/templates/admin/permissions/permissions.html:9
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:9
+#: kallithea/templates/admin/repo_groups/repo_group_edit.html:9
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:10
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:47
+#: kallithea/templates/admin/repo_groups/repo_groups.html:10
+#: kallithea/templates/admin/repos/repo_add.html:10
+#: kallithea/templates/admin/repos/repo_add.html:14
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:11
+#: kallithea/templates/admin/repos/repos.html:9
+#: kallithea/templates/admin/settings/settings.html:9
+#: kallithea/templates/admin/user_groups/user_group_add.html:8
+#: kallithea/templates/admin/user_groups/user_group_edit.html:9
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:10
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:47
+#: kallithea/templates/admin/user_groups/user_groups.html:10
+#: kallithea/templates/admin/users/user_add.html:8
+#: kallithea/templates/admin/users/user_edit.html:9
+#: kallithea/templates/admin/users/user_edit_profile.html:105
+#: kallithea/templates/admin/users/users.html:10
+#: kallithea/templates/admin/users/users.html:55
+#: kallithea/templates/base/base.html:336
+#: kallithea/templates/base/base.html:337
+#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:344
+#: kallithea/templates/base/perms_summary.html:17
+msgid "Admin"
+msgstr "Διαχειριστής"
+
+#: kallithea/controllers/admin/permissions.py:75
+#: kallithea/controllers/admin/permissions.py:86
+#: kallithea/controllers/admin/permissions.py:91
+#: kallithea/controllers/admin/permissions.py:94
+#: kallithea/controllers/admin/permissions.py:97
+#: kallithea/controllers/admin/permissions.py:100
+#: kallithea/templates/admin/auth/auth_settings.html:40
+msgid "Disabled"
+msgstr "Απενεργοποιημένο"
+
+#: kallithea/controllers/admin/permissions.py:77
+msgid "Allowed with manual account activation"
+msgstr "Επιτρέπεται με χειροποίητη ενεργοποίηση του λογαριασμού"
+
+#: kallithea/controllers/admin/permissions.py:79
+msgid "Allowed with automatic account activation"
+msgstr "Επιτρέπεται με αυτόματη ενεργοποίηση του λογαριασμού"
+
+#: kallithea/controllers/admin/permissions.py:82
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1439
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1485
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1542
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1543
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1564
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1603
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1655
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1705
+msgid "Manual activation of external account"
+msgstr "Χειροποίητη ενεργοποίηση εξωτερικού λογαριασμού"
+
+#: kallithea/controllers/admin/permissions.py:83
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1440
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1486
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1543
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1544
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1565
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1604
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1656
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1706
+msgid "Automatic activation of external account"
+msgstr "Αυτόματη ενεργοποίηση εξωτερικού λογαριασμού"
+
+#: kallithea/controllers/admin/permissions.py:87
+#: kallithea/controllers/admin/permissions.py:90
+#: kallithea/controllers/admin/permissions.py:95
+#: kallithea/controllers/admin/permissions.py:98
+#: kallithea/controllers/admin/permissions.py:101
+#: kallithea/templates/admin/auth/auth_settings.html:40
+msgid "Enabled"
+msgstr "Ενεργό"
+
+#: kallithea/controllers/admin/permissions.py:124
+msgid "Global permissions updated successfully"
+msgstr ""
+
+#: kallithea/controllers/admin/permissions.py:139
+msgid "Error occurred during update of permissions"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:187
+#, python-format
+msgid "Error occurred during creation of repository group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:192
+#, python-format
+msgid "Created repository group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:249
+#, python-format
+msgid "Updated repository group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:265
+#, python-format
+msgid "Error occurred during update of repository group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:283
+#, python-format
+msgid "This group contains %s repositories and cannot be deleted"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:290
+#, python-format
+msgid "This group contains %s subgroups and cannot be deleted"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:296
+#, python-format
+msgid "Removed repository group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:301
+#, python-format
+msgid "Error occurred during deletion of repository group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:404
+#: kallithea/controllers/admin/repo_groups.py:439
+#: kallithea/controllers/admin/user_groups.py:340
+msgid "Cannot revoke permission for yourself as admin"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:419
+msgid "Repository group permissions updated"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:456
+#: kallithea/controllers/admin/repos.py:397
+#: kallithea/controllers/admin/user_groups.py:352
+msgid "An error occurred during revoking of permission"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:151
+#, python-format
+msgid "Error creating repository %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:212
+#, python-format
+msgid "Created repository %s from %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:221
+#, python-format
+msgid "Forked repository %s as %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:224
+#, python-format
+msgid "Created repository %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:261
+#, python-format
+msgid "Repository %s updated successfully"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:282
+#, python-format
+msgid "Error occurred during update of repository %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:309
+#, python-format
+msgid "Detached %s forks"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:312
+#, python-format
+msgid "Deleted %s forks"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:317
+#, python-format
+msgid "Deleted repository %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:320
+#, python-format
+msgid "Cannot delete repository %s which still has forks"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:325
+#, python-format
+msgid "An error occurred during deletion of %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:373
+msgid "Repository permissions updated"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:429
+msgid "An error occurred during creation of field"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:443
+msgid "An error occurred during removal of field"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:459
+msgid "-- Not a fork --"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:490
+msgid "Updated repository visibility in public journal"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:494
+msgid "An error occurred during setting this repository in public journal"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:511
+msgid "Nothing"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:513
+#, python-format
+msgid "Marked repository %s as fork of %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:520
+msgid "An error occurred during this operation"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:536
+#: kallithea/controllers/admin/repos.py:563
+msgid "Repository has been locked"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:539
+#: kallithea/controllers/admin/repos.py:560
+msgid "Repository has been unlocked"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:542
+#: kallithea/controllers/admin/repos.py:567
+msgid "An error occurred during unlocking"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:581
+msgid "Cache invalidation successful"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:585
+msgid "An error occurred during cache invalidation"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:600
+msgid "Pulled from remote location"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:603
+msgid "An error occurred during pull from remote location"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:636
+msgid "An error occurred during deletion of repository stats"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:141
+msgid "Updated VCS settings"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:145
+msgid ""
+"Unable to activate hgsubversion support. The \"hgsubversion\" library is "
+"missing"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:151
+#: kallithea/controllers/admin/settings.py:248
+msgid "Error occurred while updating application settings"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:187
+#, python-format
+msgid "Repositories successfully rescanned. Added: %s. Removed: %s."
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:244
+msgid "Updated application settings"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:301
+msgid "Updated visualisation settings"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:306
+msgid "Error occurred during updating visualisation settings"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:332
+msgid "Please enter email address"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:347
+msgid "Send email task created"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:378
+msgid "Added new hook"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:392
+msgid "Updated hooks"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:396
+msgid "Error occurred during hook creation"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:422
+msgid "Whoosh reindex task scheduled"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:150
+#, python-format
+msgid "Created user group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:163
+#, python-format
+msgid "Error occurred during creation of user group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:201
+#, python-format
+msgid "Updated user group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:224
+#, python-format
+msgid "Error occurred during update of user group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:242
+msgid "Successfully deleted user group"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:247
+msgid "An error occurred during deletion of user group"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:314
+msgid "Target group cannot be the same"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:320
+msgid "User group permissions updated"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:440
+#: kallithea/controllers/admin/users.py:383
+msgid "Updated permissions"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:444
+#: kallithea/controllers/admin/users.py:387
+msgid "An error occurred during permissions saving"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:133
+#, python-format
+msgid "Created user %s"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:148
+#, python-format
+msgid "Error occurred during creation of user %s"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:181
+msgid "User updated successfully"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:217
+msgid "Successfully deleted user"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:222
+msgid "An error occurred during deletion of user"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:235
+msgid "The default user cannot be edited"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:462
+#, python-format
+msgid "Added IP address %s to user whitelist"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:468
+msgid "An error occurred while adding IP address"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:482
+msgid "Removed IP address from user whitelist"
+msgstr ""
+
+#: kallithea/lib/auth.py:737
+#, python-format
+msgid "IP %s not allowed"
+msgstr ""
+
+#: kallithea/lib/auth.py:750
+msgid "Invalid API key"
+msgstr ""
+
+#: kallithea/lib/auth.py:768
+msgid "CSRF token leak has been detected - all form tokens have been expired"
+msgstr ""
+
+#: kallithea/lib/auth.py:813
+msgid "You need to be a registered user to perform this action"
+msgstr ""
+
+#: kallithea/lib/auth.py:843
+msgid "You need to be signed in to view this page"
+msgstr ""
+
+#: kallithea/lib/base.py:493
+msgid "Repository not found in the filesystem"
+msgstr ""
+
+#: kallithea/lib/base.py:519 kallithea/lib/helpers.py:623
+msgid "Changeset not found"
+msgstr ""
+
+#: kallithea/lib/diffs.py:66
+msgid "Binary file"
+msgstr ""
+
+#: kallithea/lib/diffs.py:82
+msgid "Changeset was too big and was cut off, use diff menu to display this diff"
+msgstr ""
+
+#: kallithea/lib/diffs.py:92
+msgid "No changes detected"
+msgstr ""
+
+#: kallithea/lib/helpers.py:610
+#, python-format
+msgid "Deleted branch: %s"
+msgstr ""
+
+#: kallithea/lib/helpers.py:612
+#, python-format
+msgid "Created tag: %s"
+msgstr ""
+
+#: kallithea/lib/helpers.py:672
+#, python-format
+msgid "Show all combined changesets %s->%s"
+msgstr ""
+
+#: kallithea/lib/helpers.py:678
+msgid "Compare view"
+msgstr ""
+
+#: kallithea/lib/helpers.py:697
+msgid "and"
+msgstr ""
+
+#: kallithea/lib/helpers.py:698
+#, python-format
+msgid "%s more"
+msgstr ""
+
+#: kallithea/lib/helpers.py:699 kallithea/templates/changelog/changelog.html:44
+msgid "revisions"
+msgstr ""
+
+#: kallithea/lib/helpers.py:723
+#, python-format
+msgid "Fork name %s"
+msgstr ""
+
+#: kallithea/lib/helpers.py:743
+#, python-format
+msgid "Pull request %s"
+msgstr ""
+
+#: kallithea/lib/helpers.py:753
+msgid "[deleted] repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:755 kallithea/lib/helpers.py:767
+msgid "[created] repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:757
+msgid "[created] repository as fork"
+msgstr ""
+
+#: kallithea/lib/helpers.py:759 kallithea/lib/helpers.py:769
+msgid "[forked] repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:761 kallithea/lib/helpers.py:771
+msgid "[updated] repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:763
+msgid "[downloaded] archive from repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:765
+msgid "[delete] repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:773
+msgid "[created] user"
+msgstr ""
+
+#: kallithea/lib/helpers.py:775
+msgid "[updated] user"
+msgstr ""
+
+#: kallithea/lib/helpers.py:777
+msgid "[created] user group"
+msgstr ""
+
+#: kallithea/lib/helpers.py:779
+msgid "[updated] user group"
+msgstr ""
+
+#: kallithea/lib/helpers.py:781
+msgid "[commented] on revision in repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:783
+msgid "[commented] on pull request for"
+msgstr ""
+
+#: kallithea/lib/helpers.py:785
+msgid "[closed] pull request for"
+msgstr ""
+
+#: kallithea/lib/helpers.py:787
+msgid "[pushed] into"
+msgstr ""
+
+#: kallithea/lib/helpers.py:789
+msgid "[committed via Kallithea] into repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:791
+msgid "[pulled from remote] into repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:793
+msgid "[pulled] from"
+msgstr ""
+
+#: kallithea/lib/helpers.py:795
+msgid "[started following] repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:797
+msgid "[stopped following] repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:1124
+#, python-format
+msgid " and %s more"
+msgstr ""
+
+#: kallithea/lib/helpers.py:1128
+#: kallithea/templates/compare/compare_diff.html:71
+#: kallithea/templates/pullrequests/pullrequest_show.html:337
+msgid "No files"
+msgstr ""
+
+#: kallithea/lib/helpers.py:1194
+msgid "new file"
+msgstr ""
+
+#: kallithea/lib/helpers.py:1197
+msgid "mod"
+msgstr ""
+
+#: kallithea/lib/helpers.py:1200
+msgid "del"
+msgstr ""
+
+#: kallithea/lib/helpers.py:1203
+msgid "rename"
+msgstr ""
+
+#: kallithea/lib/helpers.py:1208
+msgid "chmod"
+msgstr ""
+
+#: kallithea/lib/helpers.py:1469
+#, python-format
+msgid ""
+"%s repository is not mapped to db perhaps it was created or renamed from "
+"the filesystem please run the application again in order to rescan "
+"repositories"
+msgstr ""
+
+#: kallithea/lib/utils2.py:434
+#, python-format
+msgid "%d year"
+msgid_plural "%d years"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/lib/utils2.py:435
+#, python-format
+msgid "%d month"
+msgid_plural "%d months"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/lib/utils2.py:436
+#, python-format
+msgid "%d day"
+msgid_plural "%d days"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/lib/utils2.py:437
+#, python-format
+msgid "%d hour"
+msgid_plural "%d hours"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/lib/utils2.py:438
+#, python-format
+msgid "%d minute"
+msgid_plural "%d minutes"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/lib/utils2.py:439
+#, python-format
+msgid "%d second"
+msgid_plural "%d seconds"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/lib/utils2.py:455
+#, python-format
+msgid "in %s"
+msgstr ""
+
+#: kallithea/lib/utils2.py:457
+#, python-format
+msgid "%s ago"
+msgstr ""
+
+#: kallithea/lib/utils2.py:459
+#, python-format
+msgid "in %s and %s"
+msgstr ""
+
+#: kallithea/lib/utils2.py:462
+#, python-format
+msgid "%s and %s ago"
+msgstr ""
+
+#: kallithea/lib/utils2.py:465
+msgid "just now"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1163
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1182
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1303
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1388
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1408
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1454
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1511
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1512
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1533
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1572
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1622
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1649
+msgid "Repository no access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1164
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1183
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1304
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1389
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1409
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1455
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1512
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1513
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1534
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1573
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1623
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1650
+msgid "Repository read access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1165
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1184
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1305
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1390
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1410
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1456
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1513
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1535
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1574
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1624
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1651
+msgid "Repository write access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1166
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1185
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1306
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1391
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1411
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1457
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1515
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1536
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1575
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1625
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1652
+msgid "Repository admin access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1168
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1187
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1308
+msgid "Repository Group no access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1169
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1188
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1309
+msgid "Repository Group read access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1170
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1189
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1310
+msgid "Repository Group write access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1171
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1190
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1311
+msgid "Repository Group admin access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1173
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1192
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1313
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1398
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1406
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1452
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1509
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1510
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1531
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1570
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1620
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1669
+msgid "Kallithea Administrator"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1174
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1193
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1314
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1399
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1429
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1475
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1532
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1533
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1554
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1593
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1643
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1670
+msgid "Repository creation disabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1175
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1194
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1315
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1400
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1430
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1476
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1533
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1534
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1555
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1594
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1644
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1671
+msgid "Repository creation enabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1176
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1195
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1316
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1401
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1432
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1478
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1535
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1536
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1557
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1596
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1648
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1675
+msgid "Repository forking disabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1177
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1196
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1317
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1402
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1433
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1479
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1536
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1537
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1558
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1597
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1649
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1676
+msgid "Repository forking enabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1178
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1197
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1318
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1403
+msgid "Register disabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1179
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1198
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1319
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1404
+msgid "Register new user with Kallithea with manual activation"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1182
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1201
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1322
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1407
+msgid "Register new user with Kallithea with auto activation"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1623
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1650
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1763
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1838
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1934
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1980
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:2040
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:2041
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2062
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2101
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2154
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2200
+msgid "Not Reviewed"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1624
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1651
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1764
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1839
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1935
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1981
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:2041
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:2042
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2063
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2102
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2155
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2237
+msgid "Approved"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1625
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1652
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1765
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1840
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1936
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1982
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:2042
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:2043
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2064
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2103
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2156
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2238
+msgid "Rejected"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1626
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1653
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1766
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1841
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1937
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1983
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:2043
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:2044
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2065
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2104
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2157
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2203
+msgid "Under Review"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1252
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1270
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1300
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1357
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1358
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1379
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1418
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1471
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1518
+msgid "top level"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1393
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1413
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1459
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1516
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1517
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1538
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1577
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1627
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1654
+msgid "Repository group no access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1394
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1414
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1460
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1517
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1518
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1539
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1578
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1628
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1655
+msgid "Repository group read access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1395
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1415
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1461
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1518
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1519
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1540
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1579
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1629
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1656
+msgid "Repository group write access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1396
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1416
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1462
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1519
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1520
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1541
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1580
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1630
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1657
+msgid "Repository group admin access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1418
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1464
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1521
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1522
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1543
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1582
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1632
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1659
+msgid "User group no access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1419
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1465
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1522
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1523
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1544
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1583
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1633
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1660
+msgid "User group read access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1420
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1466
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1523
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1524
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1545
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1584
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1634
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1661
+msgid "User group write access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1421
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1467
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1524
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1525
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1546
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1585
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1635
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1662
+msgid "User group admin access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1423
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1469
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1526
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1527
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1548
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1587
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1637
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1664
+msgid "Repository Group creation disabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1424
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1470
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1527
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1528
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1549
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1588
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1638
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1665
+msgid "Repository Group creation enabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1426
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1472
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1529
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1530
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1551
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1590
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1640
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1667
+msgid "User Group creation disabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1427
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1473
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1530
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1531
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1552
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1591
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1641
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1668
+msgid "User Group creation enabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1435
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1481
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1538
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1539
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1560
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1599
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1651
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1701
+msgid "Registration disabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1436
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1482
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1539
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1540
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1561
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1600
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1652
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1679
+msgid "User Registration with manual account activation"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1437
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1483
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1540
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1541
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1562
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1601
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1653
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1680
+msgid "User Registration with automatic account activation"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1645
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1695
+msgid "Repository creation enabled with write permission to a repository group"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1646
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1696
+msgid "Repository creation disabled with write permission to a repository group"
+msgstr ""
+
+#: kallithea/model/comment.py:72
+#, python-format
+msgid "on line %s"
+msgstr ""
+
+#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:170
+msgid "[Mention]"
+msgstr ""
+
+#: kallithea/model/db.py:1671
+msgid "Default user has no access to new repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1672
+msgid "Default user has read access to new repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1673
+msgid "Default user has write access to new repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1674
+msgid "Default user has admin access to new repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1676
+msgid "Default user has no access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1677
+msgid "Default user has read access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1678
+msgid "Default user has write access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1679
+msgid "Default user has admin access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1681
+msgid "Default user has no access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1682
+msgid "Default user has read access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1683
+msgid "Default user has write access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1684
+msgid "Default user has admin access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1686
+msgid "Only admins can create repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1687
+msgid "Non-admins can create repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1689
+msgid "Only admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1690
+msgid "Non-admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1692
+msgid "Only admins can create top level repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1693
+msgid "Non-admins can create top level repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1698
+msgid "Only admins can fork repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1699
+msgid "Non-admins can fork repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1702
+msgid "User registration with manual account activation"
+msgstr ""
+
+#: kallithea/model/db.py:1703
+msgid "User registration with automatic account activation"
+msgstr ""
+
+#: kallithea/model/db.py:2236
+msgid "Not reviewed"
+msgstr ""
+
+#: kallithea/model/db.py:2239
+msgid "Under review"
+msgstr ""
+
+#: kallithea/model/forms.py:57
+msgid "Please enter a login"
+msgstr ""
+
+#: kallithea/model/forms.py:58
+#, python-format
+msgid "Enter a value %(min)i characters long or more"
+msgstr ""
+
+#: kallithea/model/forms.py:66
+msgid "Please enter a password"
+msgstr ""
+
+#: kallithea/model/forms.py:67
+#, python-format
+msgid "Enter %(min)i characters or more"
+msgstr ""
+
+#: kallithea/model/forms.py:165
+msgid "Name must not contain only digits"
+msgstr ""
+
+#: kallithea/model/notification.py:254
+#, python-format
+msgid "%(user)s commented on changeset %(age)s"
+msgstr ""
+
+#: kallithea/model/notification.py:255
+#, python-format
+msgid "%(user)s sent message %(age)s"
+msgstr ""
+
+#: kallithea/model/notification.py:256
+#, python-format
+msgid "%(user)s mentioned you %(age)s"
+msgstr ""
+
+#: kallithea/model/notification.py:257
+#, python-format
+msgid "%(user)s registered in Kallithea %(age)s"
+msgstr ""
+
+#: kallithea/model/notification.py:258
+#, python-format
+msgid "%(user)s opened new pull request %(age)s"
+msgstr ""
+
+#: kallithea/model/notification.py:259
+#, python-format
+msgid "%(user)s commented on pull request %(age)s"
+msgstr ""
+
+#: kallithea/model/notification.py:266
+#, python-format
+msgid "%(user)s commented on changeset at %(when)s"
+msgstr ""
+
+#: kallithea/model/notification.py:267
+#, python-format
+msgid "%(user)s sent message at %(when)s"
+msgstr ""
+
+#: kallithea/model/notification.py:268
+#, python-format
+msgid "%(user)s mentioned you at %(when)s"
+msgstr ""
+
+#: kallithea/model/notification.py:269
+#, python-format
+msgid "%(user)s registered in Kallithea at %(when)s"
+msgstr ""
+
+#: kallithea/model/notification.py:270
+#, python-format
+msgid "%(user)s opened new pull request at %(when)s"
+msgstr ""
+
+#: kallithea/model/notification.py:271
+#, python-format
+msgid "%(user)s commented on pull request at %(when)s"
+msgstr ""
+
+#: kallithea/model/notification.py:302
+#, python-format
+msgid "[Comment] %(repo_name)s changeset %(short_id)s on %(branch)s"
+msgstr ""
+
+#: kallithea/model/notification.py:305
+#, python-format
+msgid "New user %(new_username)s registered"
+msgstr ""
+
+#: kallithea/model/notification.py:307
+#, python-format
+msgid "[Added] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
+msgstr ""
+
+#: kallithea/model/notification.py:308
+#, python-format
+msgid "[Comment] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
+msgstr ""
+
+#: kallithea/model/notification.py:321
+msgid "Closing"
+msgstr ""
+
+#: kallithea/model/pull_request.py:137
+#, python-format
+msgid "%(user)s wants you to review pull request %(pr_nice_id)s: %(pr_title)s"
+msgstr ""
+
+#: kallithea/model/scm.py:708
+msgid "latest tip"
+msgstr ""
+
+#: kallithea/model/user.py:192
+msgid "New user registration"
+msgstr ""
+
+#: kallithea/model/user.py:256
+msgid "You can't remove this user since it is crucial for the entire application"
+msgstr ""
+
+#: kallithea/model/user.py:261
+#, python-format
+msgid ""
+"User \"%s\" still owns %s repositories and cannot be removed. Switch "
+"owners or remove those repositories: %s"
+msgstr ""
+
+#: kallithea/model/user.py:266
+#, python-format
+msgid ""
+"User \"%s\" still owns %s repository groups and cannot be removed. Switch"
+" owners or remove those repository groups: %s"
+msgstr ""
+
+#: kallithea/model/user.py:273
+#, python-format
+msgid ""
+"User \"%s\" still owns %s user groups and cannot be removed. Switch "
+"owners or remove those user groups: %s"
+msgstr ""
+
+#: kallithea/model/user.py:368
+msgid "Password reset link"
+msgstr ""
+
+#: kallithea/model/user.py:418
+msgid "Password reset notification"
+msgstr ""
+
+#: kallithea/model/user.py:419
+#, python-format
+msgid ""
+"The password to your account %s has been changed using password reset "
+"form."
+msgstr ""
+
+#: kallithea/model/validators.py:77 kallithea/model/validators.py:78
+msgid "Value cannot be an empty list"
+msgstr ""
+
+#: kallithea/model/validators.py:96
+#, python-format
+msgid "Username \"%(username)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:98
+#, python-format
+msgid "Username \"%(username)s\" cannot be used"
+msgstr ""
+
+#: kallithea/model/validators.py:100
+msgid ""
+"Username may only contain alphanumeric characters underscores, periods or"
+" dashes and must begin with an alphanumeric character or underscore"
+msgstr ""
+
+#: kallithea/model/validators.py:127
+msgid "The input is not valid"
+msgstr ""
+
+#: kallithea/model/validators.py:134
+#, python-format
+msgid "Username %(username)s is not valid"
+msgstr ""
+
+#: kallithea/model/validators.py:154
+msgid "Invalid user group name"
+msgstr ""
+
+#: kallithea/model/validators.py:155
+#, python-format
+msgid "User group \"%(usergroup)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:157
+msgid ""
+"user group name may only contain alphanumeric characters underscores, "
+"periods or dashes and must begin with alphanumeric character"
+msgstr ""
+
+#: kallithea/model/validators.py:197
+msgid "Cannot assign this group as parent"
+msgstr ""
+
+#: kallithea/model/validators.py:198
+#, python-format
+msgid "Group \"%(group_name)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:200
+#, python-format
+msgid "Repository with name \"%(group_name)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:258
+msgid "Invalid characters (non-ascii) in password"
+msgstr ""
+
+#: kallithea/model/validators.py:273
+msgid "Invalid old password"
+msgstr ""
+
+#: kallithea/model/validators.py:289
+msgid "Passwords do not match"
+msgstr ""
+
+#: kallithea/model/validators.py:304
+msgid "Invalid username or password"
+msgstr ""
+
+#: kallithea/model/validators.py:335
+msgid "Token mismatch"
+msgstr ""
+
+#: kallithea/model/validators.py:351
+#, python-format
+msgid "Repository name %(repo)s is not allowed"
+msgstr ""
+
+#: kallithea/model/validators.py:353
+#, python-format
+msgid "Repository named %(repo)s already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:354
+#, python-format
+msgid "Repository \"%(repo)s\" already exists in group \"%(group)s\""
+msgstr ""
+
+#: kallithea/model/validators.py:356
+#, python-format
+msgid "Repository group with name \"%(repo)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:470
+msgid "Invalid repository URL"
+msgstr ""
+
+#: kallithea/model/validators.py:471
+msgid ""
+"Invalid repository URL. It must be a valid http, https, ssh, svn+http or "
+"svn+https URL"
+msgstr ""
+
+#: kallithea/model/validators.py:496
+msgid "Fork has to be the same type as parent"
+msgstr ""
+
+#: kallithea/model/validators.py:511
+msgid "You don't have permissions to create repository in this group"
+msgstr ""
+
+#: kallithea/model/validators.py:513
+msgid "no permission to create repository in root location"
+msgstr ""
+
+#: kallithea/model/validators.py:563
+msgid "You don't have permissions to create a group in this location"
+msgstr ""
+
+#: kallithea/model/validators.py:604
+msgid "This username or user group name is not valid"
+msgstr ""
+
+#: kallithea/model/validators.py:697
+msgid "This is not a valid path"
+msgstr ""
+
+#: kallithea/model/validators.py:714
+msgid "This email address is already in use"
+msgstr ""
+
+#: kallithea/model/validators.py:734
+#, python-format
+msgid "Email address \"%(email)s\" not found"
+msgstr ""
+
+#: kallithea/model/validators.py:771
+msgid ""
+"The LDAP Login attribute of the CN must be specified - this is the name "
+"of the attribute that is equivalent to \"username\""
+msgstr ""
+
+#: kallithea/model/validators.py:783
+msgid "Please enter a valid IPv4 or IPv6 address"
+msgstr ""
+
+#: kallithea/model/validators.py:784
+#, python-format
+msgid "The network size (bits) must be within the range of 0-32 (not %(bits)r)"
+msgstr ""
+
+#: kallithea/model/validators.py:817
+msgid "Key name can only consist of letters, underscore, dash or numbers"
+msgstr ""
+
+#: kallithea/model/validators.py:831
+msgid "Filename cannot be inside a directory"
+msgstr ""
+
+#: kallithea/model/validators.py:847
+#, python-format
+msgid "Plugins %(loaded)s and %(next_to_load)s both export the same name"
+msgstr ""
+
+#: kallithea/templates/about.html:4 kallithea/templates/about.html:17
+msgid "About"
+msgstr ""
+
+#: kallithea/templates/index.html:5
+msgid "Dashboard"
+msgstr ""
+
+#: kallithea/templates/index_base.html:6
+#: kallithea/templates/admin/my_account/my_account_repos.html:3
+#: kallithea/templates/admin/my_account/my_account_watched.html:3
+#: kallithea/templates/admin/repo_groups/repo_groups.html:9
+#: kallithea/templates/admin/repos/repos.html:9
+#: kallithea/templates/admin/user_groups/user_groups.html:9
+#: kallithea/templates/admin/users/users.html:9
+#: kallithea/templates/bookmarks/bookmarks.html:9
+#: kallithea/templates/branches/branches.html:9
+#: kallithea/templates/journal/journal.html:9
+#: kallithea/templates/journal/journal.html:48
+#: kallithea/templates/journal/journal.html:49
+#: kallithea/templates/tags/tags.html:9
+msgid "quick filter..."
+msgstr ""
+
+#: kallithea/templates/index_base.html:6
+msgid "repositories"
+msgstr ""
+
+#: kallithea/templates/index_base.html:20
+#: kallithea/templates/index_base.html:25
+#: kallithea/templates/admin/repos/repo_add.html:5
+#: kallithea/templates/admin/repos/repo_add.html:19
+#: kallithea/templates/admin/repos/repos.html:22
+msgid "Add Repository"
+msgstr ""
+
+#: kallithea/templates/index_base.html:22
+#: kallithea/templates/index_base.html:27
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:5
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:13
+#: kallithea/templates/admin/repo_groups/repo_groups.html:26
+msgid "Add Repository Group"
+msgstr ""
+
+#: kallithea/templates/index_base.html:32
+msgid "You have admin right to this group, and can edit it"
+msgstr ""
+
+#: kallithea/templates/index_base.html:32
+msgid "Edit Repository Group"
+msgstr ""
+
+#: kallithea/templates/index_base.html:45
+msgid "Group Name"
+msgstr ""
+
+#: kallithea/templates/index_base.html:46
+#: kallithea/templates/index_base.html:127
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:64
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:42
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:17
+#: kallithea/templates/admin/repo_groups/repo_groups.html:47
+#: kallithea/templates/admin/repos/repo_add_base.html:28
+#: kallithea/templates/admin/repos/repo_edit_settings.html:65
+#: kallithea/templates/admin/repos/repos.html:48
+#: kallithea/templates/admin/user_groups/user_group_add.html:40
+#: kallithea/templates/admin/user_groups/user_group_edit_settings.html:15
+#: kallithea/templates/admin/user_groups/user_groups.html:47
+#: kallithea/templates/admin/users/user_edit_api_keys.html:64
+#: kallithea/templates/email_templates/changeset_comment.html:18
+#: kallithea/templates/email_templates/pull_request.html:12
+#: kallithea/templates/forks/fork.html:38
+#: kallithea/templates/pullrequests/pullrequest.html:40
+#: kallithea/templates/pullrequests/pullrequest_show.html:38
+#: kallithea/templates/pullrequests/pullrequest_show.html:63
+#: kallithea/templates/summary/summary.html:85
+msgid "Description"
+msgstr ""
+
+#: kallithea/templates/index_base.html:125
+#: kallithea/templates/admin/my_account/my_account_repos.html:46
+#: kallithea/templates/admin/my_account/my_account_watched.html:46
+#: kallithea/templates/admin/repo_groups/repo_groups.html:46
+#: kallithea/templates/admin/repos/repo_add_base.html:9
+#: kallithea/templates/admin/repos/repo_edit_settings.html:7
+#: kallithea/templates/admin/repos/repos.html:47
+#: kallithea/templates/admin/user_groups/user_groups.html:46
+#: kallithea/templates/base/perms_summary.html:53
+#: kallithea/templates/bookmarks/bookmarks.html:49
+#: kallithea/templates/bookmarks/bookmarks_data.html:7
+#: kallithea/templates/branches/branches.html:49
+#: kallithea/templates/branches/branches_data.html:7
+#: kallithea/templates/files/files_browser.html:60
+#: kallithea/templates/journal/journal.html:187
+#: kallithea/templates/journal/journal.html:278
+#: kallithea/templates/tags/tags.html:49
+#: kallithea/templates/tags/tags_data.html:7
+msgid "Name"
+msgstr ""
+
+#: kallithea/templates/index_base.html:128
+msgid "Last Change"
+msgstr ""
+
+#: kallithea/templates/index_base.html:130
+#: kallithea/templates/admin/my_account/my_account_repos.html:48
+#: kallithea/templates/admin/my_account/my_account_watched.html:48
+#: kallithea/templates/admin/repos/repos.html:49
+#: kallithea/templates/journal/journal.html:189
+#: kallithea/templates/journal/journal.html:280
+msgid "Tip"
+msgstr ""
+
+#: kallithea/templates/index_base.html:132
+#: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:10
+#: kallithea/templates/admin/repo_groups/repo_groups.html:49
+#: kallithea/templates/admin/repos/repo_edit_settings.html:53
+#: kallithea/templates/admin/repos/repos.html:50
+#: kallithea/templates/admin/user_groups/user_group_edit_advanced.html:8
+#: kallithea/templates/admin/user_groups/user_groups.html:50
+#: kallithea/templates/pullrequests/pullrequest_data.html:16
+#: kallithea/templates/pullrequests/pullrequest_show.html:156
+#: kallithea/templates/pullrequests/pullrequest_show.html:244
+#: kallithea/templates/summary/summary.html:134
+msgid "Owner"
+msgstr ""
+
+#: kallithea/templates/index_base.html:140
+#: kallithea/templates/admin/my_account/my_account_repos.html:57
+#: kallithea/templates/admin/my_account/my_account_watched.html:57
+#: kallithea/templates/base/root.html:43
+#: kallithea/templates/bookmarks/bookmarks.html:79
+#: kallithea/templates/branches/branches.html:79
+#: kallithea/templates/journal/journal.html:198
+#: kallithea/templates/journal/journal.html:289
+#: kallithea/templates/tags/tags.html:79
+msgid "Click to sort ascending"
+msgstr ""
+
+#: kallithea/templates/index_base.html:141
+#: kallithea/templates/admin/my_account/my_account_repos.html:58
+#: kallithea/templates/admin/my_account/my_account_watched.html:58
+#: kallithea/templates/base/root.html:44
+#: kallithea/templates/bookmarks/bookmarks.html:80
+#: kallithea/templates/branches/branches.html:80
+#: kallithea/templates/journal/journal.html:199
+#: kallithea/templates/journal/journal.html:290
+#: kallithea/templates/tags/tags.html:80
+msgid "Click to sort descending"
+msgstr ""
+
+#: kallithea/templates/index_base.html:142
+msgid "No repositories found."
+msgstr ""
+
+#: kallithea/templates/index_base.html:143
+#: kallithea/templates/admin/my_account/my_account_repos.html:60
+#: kallithea/templates/admin/my_account/my_account_watched.html:60
+#: kallithea/templates/base/root.html:46
+#: kallithea/templates/bookmarks/bookmarks.html:82
+#: kallithea/templates/branches/branches.html:82
+#: kallithea/templates/journal/journal.html:201
+#: kallithea/templates/journal/journal.html:292
+#: kallithea/templates/tags/tags.html:82
+msgid "Data error."
+msgstr ""
+
+#: kallithea/templates/index_base.html:144
+#: kallithea/templates/admin/my_account/my_account_repos.html:61
+#: kallithea/templates/admin/my_account/my_account_watched.html:61
+#: kallithea/templates/base/root.html:47
+#: kallithea/templates/bookmarks/bookmarks.html:83
+#: kallithea/templates/branches/branches.html:83
+#: kallithea/templates/journal/journal.html:202
+#: kallithea/templates/journal/journal.html:293
+#: kallithea/templates/tags/tags.html:83
+msgid "Loading..."
+msgstr ""
+
+#: kallithea/templates/login.html:5 kallithea/templates/login.html:15
+#: kallithea/templates/base/base.html:414
+msgid "Log In"
+msgstr ""
+
+#: kallithea/templates/login.html:13
+#, python-format
+msgid "Log In to %s"
+msgstr ""
+
+#: kallithea/templates/login.html:26 kallithea/templates/register.html:24
+#: kallithea/templates/admin/admin_log.html:5
+#: kallithea/templates/admin/my_account/my_account_profile.html:25
+#: kallithea/templates/admin/users/user_add.html:32
+#: kallithea/templates/admin/users/user_edit_profile.html:24
+#: kallithea/templates/admin/users/users.html:50
+#: kallithea/templates/base/base.html:390
+#: kallithea/templates/pullrequests/pullrequest_show.html:166
+msgid "Username"
+msgstr ""
+
+#: kallithea/templates/login.html:33 kallithea/templates/register.html:33
+#: kallithea/templates/admin/my_account/my_account.html:37
+#: kallithea/templates/admin/users/user_add.html:41
+#: kallithea/templates/base/base.html:399
+msgid "Password"
+msgstr ""
+
+#: kallithea/templates/login.html:44
+msgid "Remember me"
+msgstr ""
+
+#: kallithea/templates/login.html:53
+msgid "Forgot your password ?"
+msgstr ""
+
+#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:410
+msgid "Don't have an account ?"
+msgstr ""
+
+#: kallithea/templates/login.html:59
+msgid "Sign In"
+msgstr ""
+
+#: kallithea/templates/password_reset.html:5
+msgid "Password Reset"
+msgstr ""
+
+#: kallithea/templates/password_reset.html:12
+#: kallithea/templates/password_reset_confirmation.html:12
+#, python-format
+msgid "Reset Your Password to %s"
+msgstr ""
+
+#: kallithea/templates/password_reset.html:14
+#: kallithea/templates/password_reset_confirmation.html:5
+#: kallithea/templates/password_reset_confirmation.html:14
+msgid "Reset Your Password"
+msgstr ""
+
+#: kallithea/templates/password_reset.html:25
+msgid "Email Address"
+msgstr ""
+
+#: kallithea/templates/password_reset.html:35
+#: kallithea/templates/register.html:79
+msgid "Captcha"
+msgstr ""
+
+#: kallithea/templates/password_reset.html:46
+msgid "Send Password Reset Email"
+msgstr ""
+
+#: kallithea/templates/password_reset.html:47
+msgid ""
+"A password reset link will be sent to the specified email address if it "
+"is registered in the system."
+msgstr ""
+
+#: kallithea/templates/password_reset_confirmation.html:19
+#, python-format
+msgid "You are about to set a new password for the email address %s."
+msgstr ""
+
+#: kallithea/templates/password_reset_confirmation.html:20
+msgid ""
+"Note that you must use the same browser session for this as the one used "
+"to request the password reset."
+msgstr ""
+
+#: kallithea/templates/password_reset_confirmation.html:30
+msgid "Code you received in the email"
+msgstr ""
+
+#: kallithea/templates/password_reset_confirmation.html:39
+msgid "New Password"
+msgstr ""
+
+#: kallithea/templates/password_reset_confirmation.html:48
+msgid "Confirm New Password"
+msgstr ""
+
+#: kallithea/templates/password_reset_confirmation.html:56
+msgid "Confirm"
+msgstr ""
+
+#: kallithea/templates/register.html:5 kallithea/templates/register.html:14
+#: kallithea/templates/register.html:90
+msgid "Sign Up"
+msgstr ""
+
+#: kallithea/templates/register.html:12
+#, python-format
+msgid "Sign Up to %s"
+msgstr ""
+
+#: kallithea/templates/register.html:42
+msgid "Re-enter password"
+msgstr ""
+
+#: kallithea/templates/register.html:51
+#: kallithea/templates/admin/my_account/my_account_profile.html:34
+#: kallithea/templates/admin/users/user_add.html:59
+#: kallithea/templates/admin/users/user_edit_profile.html:78
+#: kallithea/templates/admin/users/users.html:51
+msgid "First Name"
+msgstr ""
+
+#: kallithea/templates/register.html:60
+#: kallithea/templates/admin/my_account/my_account_profile.html:43
+#: kallithea/templates/admin/users/user_add.html:68
+#: kallithea/templates/admin/users/user_edit_profile.html:87
+#: kallithea/templates/admin/users/users.html:52
+msgid "Last Name"
+msgstr ""
+
+#: kallithea/templates/register.html:69
+#: kallithea/templates/admin/my_account/my_account_profile.html:52
+#: kallithea/templates/admin/settings/settings.html:31
+#: kallithea/templates/admin/users/user_add.html:77
+#: kallithea/templates/admin/users/user_edit_profile.html:33
+msgid "Email"
+msgstr ""
+
+#: kallithea/templates/register.html:92
+msgid "Registered accounts are ready to use and need no further action."
+msgstr ""
+
+#: kallithea/templates/register.html:94
+msgid "Please wait for an administrator to activate your account."
+msgstr ""
+
+#: kallithea/templates/switch_to_list.html:10
+#: kallithea/templates/branches/branches_data.html:69
+msgid "There are no branches yet"
+msgstr ""
+
+#: kallithea/templates/switch_to_list.html:32
+#: kallithea/templates/tags/tags_data.html:44
+msgid "There are no tags yet"
+msgstr ""
+
+#: kallithea/templates/switch_to_list.html:45
+#: kallithea/templates/bookmarks/bookmarks_data.html:43
+msgid "There are no bookmarks yet"
+msgstr ""
+
+#: kallithea/templates/admin/admin.html:5
+#: kallithea/templates/admin/admin.html:13
+#: kallithea/templates/base/base.html:59
+msgid "Admin Journal"
+msgstr ""
+
+#: kallithea/templates/admin/admin.html:10
+msgid "journal filter..."
+msgstr ""
+
+#: kallithea/templates/admin/admin.html:12
+#: kallithea/templates/journal/journal.html:11
+msgid "Filter"
+msgstr ""
+
+#: kallithea/templates/admin/admin.html:13
+#: kallithea/templates/journal/journal.html:12
+#, python-format
+msgid "%s Entry"
+msgid_plural "%s Entries"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/admin/admin_log.html:6
+#: kallithea/templates/admin/my_account/my_account_repos.html:50
+#: kallithea/templates/admin/my_account/my_account_watched.html:50
+#: kallithea/templates/admin/repo_groups/repo_groups.html:50
+#: kallithea/templates/admin/repos/repo_edit_fields.html:8
+#: kallithea/templates/admin/repos/repos.html:52
+#: kallithea/templates/admin/user_groups/user_groups.html:51
+#: kallithea/templates/admin/users/users.html:57
+#: kallithea/templates/journal/journal.html:191
+#: kallithea/templates/journal/journal.html:282
+msgid "Action"
+msgstr ""
+
+#: kallithea/templates/admin/admin_log.html:7
+#: kallithea/templates/admin/permissions/permissions_globals.html:18
+msgid "Repository"
+msgstr ""
+
+#: kallithea/templates/admin/admin_log.html:8
+#: kallithea/templates/bookmarks/bookmarks.html:51
+#: kallithea/templates/bookmarks/bookmarks_data.html:9
+#: kallithea/templates/branches/branches.html:51
+#: kallithea/templates/branches/branches_data.html:9
+#: kallithea/templates/tags/tags.html:51
+#: kallithea/templates/tags/tags_data.html:9
+msgid "Date"
+msgstr ""
+
+#: kallithea/templates/admin/admin_log.html:9
+msgid "From IP"
+msgstr ""
+
+#: kallithea/templates/admin/admin_log.html:63
+msgid "No actions yet"
+msgstr ""
+
+#: kallithea/templates/admin/auth/auth_settings.html:5
+msgid "Authentication Settings"
+msgstr ""
+
+#: kallithea/templates/admin/auth/auth_settings.html:11
+#: kallithea/templates/base/base.html:65
+msgid "Authentication"
+msgstr ""
+
+#: kallithea/templates/admin/auth/auth_settings.html:28
+msgid "Authentication Plugins"
+msgstr ""
+
+#: kallithea/templates/admin/auth/auth_settings.html:31
+msgid "Enabled Plugins"
+msgstr ""
+
+#: kallithea/templates/admin/auth/auth_settings.html:33
+msgid ""
+"Comma-separated list of plugins; Kallithea will try user authentication "
+"in plugin order"
+msgstr ""
+
+#: kallithea/templates/admin/auth/auth_settings.html:34
+msgid "Available built-in plugins"
+msgstr ""
+
+#: kallithea/templates/admin/auth/auth_settings.html:51
+msgid "Plugin"
+msgstr ""
+
+#: kallithea/templates/admin/auth/auth_settings.html:101
+#: kallithea/templates/admin/defaults/defaults.html:82
+#: kallithea/templates/admin/my_account/my_account_password.html:36
+#: kallithea/templates/admin/my_account/my_account_profile.html:60
+#: kallithea/templates/admin/permissions/permissions_globals.html:112
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:69
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:114
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:42
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:101
+#: kallithea/templates/admin/repos/repo_edit_settings.html:127
+#: kallithea/templates/admin/settings/settings_hooks.html:53
+#: kallithea/templates/admin/user_groups/user_group_add.html:57
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:104
+#: kallithea/templates/admin/user_groups/user_group_edit_settings.html:60
+#: kallithea/templates/admin/users/user_add.html:96
+#: kallithea/templates/admin/users/user_edit_profile.html:113
+#: kallithea/templates/base/default_perms_box.html:64
+msgid "Save"
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:5
+#: kallithea/templates/admin/defaults/defaults.html:11
+#: kallithea/templates/base/base.html:66
+msgid "Repository Defaults"
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:33
+#: kallithea/templates/admin/repos/repo_add_base.html:55
+#: kallithea/templates/admin/repos/repo_edit_fields.html:7
+msgid "Type"
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:42
+#: kallithea/templates/admin/repos/repo_add_base.html:73
+#: kallithea/templates/admin/repos/repo_edit_settings.html:75
+#: kallithea/templates/data_table/_dt_elements.html:72
+msgid "Private repository"
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:46
+#: kallithea/templates/admin/repos/repo_add_base.html:77
+#: kallithea/templates/admin/repos/repo_edit_settings.html:79
+#: kallithea/templates/forks/fork.html:72
+msgid ""
+"Private repositories are only visible to people explicitly added as "
+"collaborators."
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:53
+#: kallithea/templates/admin/repos/repo_edit_settings.html:84
+msgid "Enable statistics"
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:57
+#: kallithea/templates/admin/repos/repo_edit_settings.html:88
+msgid "Enable statistics window on summary page."
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:63
+#: kallithea/templates/admin/repos/repo_edit_settings.html:93
+msgid "Enable downloads"
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:67
+#: kallithea/templates/admin/repos/repo_edit_settings.html:97
+msgid "Enable download menu on summary page."
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:73
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:34
+#: kallithea/templates/admin/repos/repo_edit_settings.html:102
+msgid "Enable locking"
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:77
+#: kallithea/templates/admin/repos/repo_edit_settings.html:106
+msgid "Enable lock-by-pulling on repository."
+msgstr ""
+
+#: kallithea/templates/admin/gists/edit.html:5
+#: kallithea/templates/admin/gists/edit.html:18
+msgid "Edit Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/edit.html:36
+#, python-format
+msgid ""
+"Gist was update since you started editing. Copy your changes and click "
+"%(here)s to reload new version."
+msgstr ""
+
+#: kallithea/templates/admin/gists/edit.html:55
+#: kallithea/templates/admin/gists/new.html:39
+msgid "Gist description ..."
+msgstr ""
+
+#: kallithea/templates/admin/gists/edit.html:57
+#: kallithea/templates/admin/gists/new.html:41
+msgid "Gist lifetime"
+msgstr ""
+
+#: kallithea/templates/admin/gists/edit.html:61
+#: kallithea/templates/admin/gists/edit.html:63
+#: kallithea/templates/admin/gists/index.html:57
+#: kallithea/templates/admin/gists/index.html:59
+#: kallithea/templates/admin/gists/show.html:47
+#: kallithea/templates/admin/gists/show.html:49
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:8
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:27
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:32
+#: kallithea/templates/admin/users/user_edit_api_keys.html:8
+#: kallithea/templates/admin/users/user_edit_api_keys.html:27
+#: kallithea/templates/admin/users/user_edit_api_keys.html:32
+msgid "Expires"
+msgstr ""
+
+#: kallithea/templates/admin/gists/edit.html:61
+#: kallithea/templates/admin/gists/index.html:57
+#: kallithea/templates/admin/gists/show.html:47
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:8
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:27
+#: kallithea/templates/admin/users/user_edit_api_keys.html:8
+#: kallithea/templates/admin/users/user_edit_api_keys.html:27
+msgid "Never"
+msgstr ""
+
+#: kallithea/templates/admin/gists/edit.html:146
+msgid "Update Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/edit.html:147
+#: kallithea/templates/changeset/changeset_file_comment.html:105
+msgid "Cancel"
+msgstr ""
+
+#: kallithea/templates/admin/gists/index.html:6
+#: kallithea/templates/admin/gists/index.html:16
+#, python-format
+msgid "Private Gists for User %s"
+msgstr ""
+
+#: kallithea/templates/admin/gists/index.html:8
+#: kallithea/templates/admin/gists/index.html:18
+#, python-format
+msgid "Public Gists for User %s"
+msgstr ""
+
+#: kallithea/templates/admin/gists/index.html:10
+#: kallithea/templates/admin/gists/index.html:20
+msgid "Public Gists"
+msgstr ""
+
+#: kallithea/templates/admin/gists/index.html:37
+#: kallithea/templates/admin/gists/show.html:25
+#: kallithea/templates/base/base.html:321
+msgid "Create New Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/index.html:54
+#: kallithea/templates/data_table/_dt_elements.html:141
+msgid "Created"
+msgstr ""
+
+#: kallithea/templates/admin/gists/index.html:74
+msgid "There are no gists yet"
+msgstr ""
+
+#: kallithea/templates/admin/gists/new.html:5
+#: kallithea/templates/admin/gists/new.html:18
+msgid "New Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/new.html:47
+msgid "name this file..."
+msgstr ""
+
+#: kallithea/templates/admin/gists/new.html:56
+msgid "Create Private Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/new.html:57
+msgid "Create Public Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/new.html:58
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:15
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:70
+#: kallithea/templates/admin/my_account/my_account_emails.html:46
+#: kallithea/templates/admin/my_account/my_account_password.html:37
+#: kallithea/templates/admin/my_account/my_account_profile.html:61
+#: kallithea/templates/admin/permissions/permissions_globals.html:113
+#: kallithea/templates/admin/permissions/permissions_ips.html:39
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:115
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:43
+#: kallithea/templates/admin/repos/repo_edit_fields.html:59
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:102
+#: kallithea/templates/admin/repos/repo_edit_settings.html:128
+#: kallithea/templates/admin/settings/settings_global.html:57
+#: kallithea/templates/admin/settings/settings_vcs.html:81
+#: kallithea/templates/admin/settings/settings_visual.html:117
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:105
+#: kallithea/templates/admin/users/user_edit_api_keys.html:15
+#: kallithea/templates/admin/users/user_edit_api_keys.html:70
+#: kallithea/templates/admin/users/user_edit_emails.html:46
+#: kallithea/templates/admin/users/user_edit_ips.html:50
+#: kallithea/templates/admin/users/user_edit_profile.html:114
+#: kallithea/templates/base/default_perms_box.html:65
+#: kallithea/templates/files/files_add.html:65
+#: kallithea/templates/files/files_delete.html:44
+#: kallithea/templates/files/files_edit.html:68
+#: kallithea/templates/pullrequests/pullrequest.html:89
+msgid "Reset"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:5
+#: kallithea/templates/admin/gists/show.html:9
+msgid "Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:10
+#: kallithea/templates/email_templates/changeset_comment.html:15
+#: kallithea/templates/email_templates/pull_request.html:10
+#: kallithea/templates/email_templates/pull_request_comment.html:15
+msgid "URL"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:37
+msgid "Public Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:39
+msgid "Private Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:56
+#: kallithea/templates/admin/my_account/my_account_emails.html:19
+#: kallithea/templates/admin/permissions/permissions_ips.html:12
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:75
+#: kallithea/templates/admin/repos/repo_edit_fields.html:18
+#: kallithea/templates/admin/settings/settings_hooks.html:36
+#: kallithea/templates/admin/users/user_edit_emails.html:19
+#: kallithea/templates/admin/users/user_edit_ips.html:22
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+#: kallithea/templates/changeset/changeset_file_comment.html:95
+#: kallithea/templates/data_table/_dt_elements.html:129
+#: kallithea/templates/data_table/_dt_elements.html:157
+#: kallithea/templates/data_table/_dt_elements.html:173
+#: kallithea/templates/data_table/_dt_elements.html:189
+#: kallithea/templates/files/files_source.html:39
+#: kallithea/templates/files/files_source.html:42
+#: kallithea/templates/files/files_source.html:45
+#: kallithea/templates/pullrequests/pullrequest_data.html:20
+msgid "Delete"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:56
+msgid "Confirm to delete this Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:63
+#: kallithea/templates/base/perms_summary.html:43
+#: kallithea/templates/base/perms_summary.html:79
+#: kallithea/templates/base/perms_summary.html:81
+#: kallithea/templates/data_table/_dt_elements.html:122
+#: kallithea/templates/data_table/_dt_elements.html:123
+#: kallithea/templates/data_table/_dt_elements.html:150
+#: kallithea/templates/data_table/_dt_elements.html:151
+#: kallithea/templates/data_table/_dt_elements.html:165
+#: kallithea/templates/data_table/_dt_elements.html:167
+#: kallithea/templates/data_table/_dt_elements.html:181
+#: kallithea/templates/data_table/_dt_elements.html:183
+#: kallithea/templates/files/diff_2way.html:56
+#: kallithea/templates/files/files_source.html:41
+#: kallithea/templates/files/files_source.html:44
+#: kallithea/templates/pullrequests/pullrequest_show.html:41
+msgid "Edit"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:65
+#: kallithea/templates/files/files_edit.html:49
+#: kallithea/templates/files/files_source.html:34
+msgid "Show as Raw"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:73
+msgid "created"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:86
+msgid "Show as raw"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account.html:5
+#: kallithea/templates/admin/my_account/my_account.html:9
+#: kallithea/templates/base/base.html:431
+msgid "My Account"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account.html:35
+#: kallithea/templates/admin/users/user_edit.html:29
+msgid "Profile"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account.html:36
+msgid "Email Addresses"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account.html:38
+#: kallithea/templates/admin/users/user_edit.html:31
+msgid "API Keys"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account.html:39
+msgid "Owned Repositories"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account.html:40
+#: kallithea/templates/journal/journal.html:53
+msgid "Watched Repositories"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account.html:41
+#: kallithea/templates/admin/permissions/permissions.html:30
+#: kallithea/templates/admin/user_groups/user_group_edit.html:32
+#: kallithea/templates/admin/users/user_edit.html:34
+msgid "Show Permissions"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:6
+#: kallithea/templates/admin/users/user_edit_api_keys.html:6
+msgid "Built-in"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:14
+#: kallithea/templates/admin/users/user_edit_api_keys.html:14
+#, python-format
+msgid "Confirm to reset this API key: %s"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:30
+#: kallithea/templates/admin/users/user_edit_api_keys.html:30
+msgid "Expired"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:40
+#: kallithea/templates/admin/users/user_edit_api_keys.html:40
+#, python-format
+msgid "Confirm to remove this API key: %s"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:42
+#: kallithea/templates/admin/users/user_edit_api_keys.html:42
+msgid "Remove"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:49
+#: kallithea/templates/admin/users/user_edit_api_keys.html:49
+msgid "No additional API keys specified"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:61
+#: kallithea/templates/admin/users/user_edit_api_keys.html:61
+msgid "New API key"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:69
+#: kallithea/templates/admin/my_account/my_account_emails.html:45
+#: kallithea/templates/admin/permissions/permissions_ips.html:38
+#: kallithea/templates/admin/repos/repo_add_base.html:81
+#: kallithea/templates/admin/repos/repo_edit_fields.html:58
+#: kallithea/templates/admin/users/user_edit_api_keys.html:69
+#: kallithea/templates/admin/users/user_edit_emails.html:45
+#: kallithea/templates/admin/users/user_edit_ips.html:49
+msgid "Add"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_emails.html:7
+#: kallithea/templates/admin/users/user_edit_emails.html:7
+msgid "Primary"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_emails.html:20
+#: kallithea/templates/admin/users/user_edit_emails.html:20
+#, python-format
+msgid "Confirm to delete this email: %s"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_emails.html:26
+#: kallithea/templates/admin/users/user_edit_emails.html:26
+msgid "No additional emails specified."
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_emails.html:38
+#: kallithea/templates/admin/users/user_edit_emails.html:38
+msgid "New email address"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_password.html:1
+msgid "Change Your Account Password"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_password.html:10
+msgid "Current password"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_password.html:19
+#: kallithea/templates/admin/users/user_edit_profile.html:60
+msgid "New password"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_password.html:28
+msgid "Confirm new password"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_password.html:45
+#, python-format
+msgid "This account is managed with %s and the password cannot be changed here"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_profile.html:11
+msgid "Change your avatar at"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_profile.html:12
+#: kallithea/templates/admin/users/user_edit_profile.html:9
+msgid "Using"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_profile.html:14
+#: kallithea/templates/admin/users/user_edit_profile.html:11
+msgid "Avatars are disabled"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_profile.html:15
+msgid "Missing email, please update your user email address."
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_profile.html:16
+#: kallithea/templates/admin/users/user_edit_profile.html:15
+msgid "Current IP"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_repos.html:1
+msgid "Repositories You Own"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_repos.html:59
+#: kallithea/templates/admin/my_account/my_account_watched.html:59
+#: kallithea/templates/base/root.html:45
+#: kallithea/templates/bookmarks/bookmarks.html:81
+#: kallithea/templates/branches/branches.html:81
+#: kallithea/templates/journal/journal.html:200
+#: kallithea/templates/journal/journal.html:291
+#: kallithea/templates/tags/tags.html:81
+msgid "No records found."
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_watched.html:1
+msgid "Repositories You are Watching"
+msgstr ""
+
+#: kallithea/templates/admin/notifications/notifications.html:5
+#: kallithea/templates/admin/notifications/notifications.html:9
+msgid "My Notifications"
+msgstr ""
+
+#: kallithea/templates/admin/notifications/notifications.html:24
+msgid "All"
+msgstr ""
+
+#: kallithea/templates/admin/notifications/notifications.html:25
+msgid "Comments"
+msgstr ""
+
+#: kallithea/templates/admin/notifications/notifications.html:26
+#: kallithea/templates/base/base.html:180
+msgid "Pull Requests"
+msgstr ""
+
+#: kallithea/templates/admin/notifications/notifications.html:30
+msgid "Mark All Read"
+msgstr ""
+
+#: kallithea/templates/admin/notifications/notifications_data.html:40
+msgid "No notifications here yet"
+msgstr ""
+
+#: kallithea/templates/admin/notifications/show_notification.html:5
+#: kallithea/templates/admin/notifications/show_notification.html:11
+msgid "Show Notification"
+msgstr ""
+
+#: kallithea/templates/admin/notifications/show_notification.html:9
+#: kallithea/templates/base/base.html:430
+msgid "Notifications"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions.html:5
+#: kallithea/templates/admin/permissions/permissions.html:11
+#: kallithea/templates/base/base.html:64
+msgid "Default Permissions"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions.html:28
+#: kallithea/templates/admin/settings/settings.html:29
+msgid "Global"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions.html:29
+#: kallithea/templates/admin/users/user_edit.html:32
+msgid "IP Whitelist"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:7
+msgid "Anonymous access"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:13
+#, python-format
+msgid ""
+"Allow access to Kallithea without needing to log in. Anonymous users use "
+"%s user permissions."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:25
+msgid ""
+"All default permissions on each repository will be reset to chosen "
+"permission, note that all custom default permission on repositories will "
+"be lost"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:26
+msgid "Apply to all existing repositories"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:27
+msgid "Permissions for the Default user on new repositories."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:32
+#: kallithea/templates/admin/repos/repo_add_base.html:37
+#: kallithea/templates/admin/repos/repo_edit_settings.html:35
+#: kallithea/templates/data_table/_dt_elements.html:202
+#: kallithea/templates/forks/fork.html:48
+msgid "Repository group"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:39
+msgid ""
+"All default permissions on each repository group will be reset to chosen "
+"permission, note that all custom default permission on repository groups "
+"will be lost"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:40
+msgid "Apply to all existing repository groups"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:41
+msgid "Permissions for the Default user on new repository groups."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:46
+#: kallithea/templates/data_table/_dt_elements.html:209
+msgid "User group"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:53
+msgid ""
+"All default permissions on each user group will be reset to chosen "
+"permission, note that all custom default permission on user groups will "
+"be lost"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:54
+msgid "Apply to all existing user groups"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:55
+msgid "Permissions for the Default user on new user groups."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:60
+msgid "Top level repository creation"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:64
+msgid "Enable this to allow non-admins to create repositories at the top level."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:65
+msgid ""
+"Note: This will also give all users API access to create repositories "
+"everywhere. That might change in future versions."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:70
+msgid "Repository creation with group write access"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:74
+msgid ""
+"With this, write permission to a repository group allows creating "
+"repositories inside that group. Without this, group write permissions "
+"mean nothing."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:79
+msgid "User group creation"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:83
+msgid "Enable this to allow non-admins to create user groups."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:88
+msgid "Repository forking"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:92
+msgid "Enable this to allow non-admins to fork repositories."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:97
+msgid "Registration"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:105
+msgid "External auth account activation"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_ips.html:13
+#: kallithea/templates/admin/users/user_edit_ips.html:23
+#, python-format
+msgid "Confirm to delete this IP address: %s"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_ips.html:19
+#: kallithea/templates/admin/users/user_edit_ips.html:30
+msgid "All IP addresses are allowed."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_ips.html:30
+#: kallithea/templates/admin/users/user_edit_ips.html:42
+msgid "New IP address"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:11
+#: kallithea/templates/admin/repo_groups/repo_group_edit.html:11
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:105
+#: kallithea/templates/admin/repo_groups/repo_groups.html:10
+#: kallithea/templates/base/base.html:61 kallithea/templates/base/base.html:80
+msgid "Repository Groups"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:33
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:8
+#: kallithea/templates/admin/user_groups/user_group_add.html:32
+#: kallithea/templates/admin/user_groups/user_group_edit_settings.html:7
+msgid "Group name"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:51
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:26
+msgid "Group parent"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:60
+#: kallithea/templates/admin/repos/repo_add_base.html:46
+msgid "Copy parent group permissions"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:64
+#: kallithea/templates/admin/repos/repo_add_base.html:50
+msgid "Copy permission set from parent repository group."
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit.html:5
+#, python-format
+msgid "%s Repository Group Settings"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit.html:21
+msgid "Add Child Group"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit.html:40
+#: kallithea/templates/admin/repos/repo_edit.html:12
+#: kallithea/templates/admin/repos/repo_edit.html:40
+#: kallithea/templates/admin/settings/settings.html:11
+#: kallithea/templates/admin/user_groups/user_group_edit.html:29
+#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:148
+#: kallithea/templates/data_table/_dt_elements.html:45
+#: kallithea/templates/data_table/_dt_elements.html:49
+msgid "Settings"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit.html:41
+#: kallithea/templates/admin/repos/repo_edit.html:46
+#: kallithea/templates/admin/user_groups/user_group_edit.html:30
+#: kallithea/templates/admin/users/user_edit.html:33
+msgid "Advanced"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit.html:42
+#: kallithea/templates/admin/repos/repo_edit.html:43
+#: kallithea/templates/admin/user_groups/user_group_edit.html:31
+msgid "Permissions"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:1
+#, python-format
+msgid "Repository Group: %s"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:6
+msgid "Top level repositories"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:7
+msgid "Total repositories"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:8
+msgid "Children groups"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:9
+#: kallithea/templates/admin/user_groups/user_group_edit_advanced.html:7
+#: kallithea/templates/admin/users/user_edit_advanced.html:8
+#: kallithea/templates/pullrequests/pullrequest_show.html:148
+msgid "Created on"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:21
+#: kallithea/templates/data_table/_dt_elements.html:190
+#, python-format
+msgid "Confirm to delete this group: %s with %s repository"
+msgid_plural "Confirm to delete this group: %s with %s repositories"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:25
+msgid "Delete this repository group"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:11
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:12
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:11
+msgid "User/User Group"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:28
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:45
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:24
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:37
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:28
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:45
+msgid "Default"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:34
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:71
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:43
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:68
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:34
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:71
+msgid "Revoke"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:97
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:94
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:97
+msgid "Add new"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:103
+msgid "Apply to children"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:107
+msgid "Both"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:108
+msgid ""
+"Set or revoke permission to all children of that group, including non-"
+"private repositories and other groups if selected."
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:38
+msgid ""
+"Enable lock-by-pulling on group. This option will be applied to all other"
+" groups and repositories inside"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:53
+msgid "Remove this group"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:53
+msgid "Confirm to delete this group"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_show.html:4
+#, python-format
+msgid "%s Repository group dashboard"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_show.html:9
+msgid "Home"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_show.html:13
+msgid "with"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_groups.html:5
+msgid "Repository Groups Administration"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_groups.html:48
+msgid "Number of Top-level Repositories"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_add_base.html:17
+msgid "Clone remote repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_add_base.html:22
+msgid ""
+"Optional: URL of a remote repository. If set, the repository will be "
+"created as a clone from this URL."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_add_base.html:32
+#: kallithea/templates/admin/repos/repo_edit_settings.html:69
+#: kallithea/templates/forks/fork.html:42
+msgid "Keep it short and to the point. Use a README file for longer descriptions."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_add_base.html:41
+#: kallithea/templates/admin/repos/repo_edit_settings.html:39
+#: kallithea/templates/forks/fork.html:52
+msgid "Optionally select a group to put this repository into."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_add_base.html:59
+msgid "Type of repository to create."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_add_base.html:64
+#: kallithea/templates/admin/repos/repo_edit_settings.html:44
+#: kallithea/templates/forks/fork.html:58
+msgid "Landing revision"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_add_base.html:68
+msgid ""
+"Default revision for files page, downloads, full text search index and "
+"readme generation"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_creating.html:9
+#, python-format
+msgid "%s Creating Repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_creating.html:13
+msgid "Creating repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_creating.html:27
+#, python-format
+msgid ""
+"Repository \"%(repo_name)s\" is being created, you will be redirected "
+"when this process is finished.repo_name"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_creating.html:39
+msgid ""
+"We're sorry but error occurred during this operation. Please check your "
+"Kallithea server logs, or contact administrator."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit.html:8
+#, python-format
+msgid "%s Repository Settings"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit.html:49
+msgid "Extra Fields"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit.html:52
+msgid "Caches"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit.html:55
+msgid "Remote"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit.html:58
+#: kallithea/templates/summary/statistics.html:8
+#: kallithea/templates/summary/summary.html:171
+#: kallithea/templates/summary/summary.html:172
+msgid "Statistics"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:1
+msgid "Parent"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:5
+#: kallithea/templates/admin/repos/repo_edit_fork.html:5
+msgid "Set"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:8
+#: kallithea/templates/admin/repos/repo_edit_fork.html:9
+msgid "Manually set this repository as a fork of another from the list."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:22
+msgid "Public Journal Visibility"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:29
+msgid "Remove from public journal"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:34
+msgid "Add to Public Journal"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:40
+msgid ""
+"All actions done in this repository will be visible to everyone in the "
+"public journal."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:46
+msgid "Change Locking"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:52
+msgid "Confirm to unlock repository."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:54
+msgid "Unlock Repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:56
+#, python-format
+msgid "Locked by %s on %s"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:60
+msgid "Confirm to lock repository."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:62
+msgid "Lock Repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:64
+msgid "Repository is not locked"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:68
+msgid ""
+"Force locking on the repository. Works only when anonymous access is "
+"disabled. Triggering a pull locks the repository.  The user who is "
+"pulling locks the repository; only the user who pulled and locked it can "
+"unlock it by doing a push."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:79
+#: kallithea/templates/data_table/_dt_elements.html:130
+#, python-format
+msgid "Confirm to delete this repository: %s"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:81
+msgid "Delete this Repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:84
+#, python-format
+msgid "This repository has %s fork"
+msgid_plural "This repository has %s forks"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:85
+msgid "Detach forks"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:86
+msgid "Delete forks"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:90
+msgid ""
+"The deleted repository will be moved away and hidden until the "
+"administrator expires it. The administrator can both permanently delete "
+"it or restore it."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_caches.html:4
+msgid "Invalidate Repository Cache"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_caches.html:7
+msgid ""
+"Manually invalidate cache for this repository. On first access, the "
+"repository will be cached again."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_caches.html:12
+msgid "List of Cached Values"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_caches.html:15
+msgid "Prefix"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_caches.html:16
+#: kallithea/templates/admin/repos/repo_edit_fields.html:6
+msgid "Key"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_caches.html:17
+#: kallithea/templates/admin/user_groups/user_group_add.html:49
+#: kallithea/templates/admin/user_groups/user_group_edit_settings.html:24
+#: kallithea/templates/admin/user_groups/user_groups.html:49
+#: kallithea/templates/admin/users/user_add.html:86
+#: kallithea/templates/admin/users/user_edit_profile.html:96
+#: kallithea/templates/admin/users/users.html:54
+msgid "Active"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_fields.html:5
+msgid "Label"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_fields.html:19
+#, python-format
+msgid "Confirm to delete this field: %s"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_fields.html:33
+msgid "New field key"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_fields.html:41
+msgid "New field label"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_fields.html:44
+msgid "Enter short label"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_fields.html:50
+msgid "New field description"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_fields.html:53
+msgid "Enter description of a field"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_fields.html:66
+msgid "Extra fields are disabled."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:21
+msgid "Private Repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_remote.html:3
+msgid "Remote repository URL"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_remote.html:9
+msgid "Pull Changes from Remote Repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_remote.html:11
+msgid "Confirm to pull changes from remote repository."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_remote.html:17
+msgid "This repository does not have a remote repository URL."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:11
+msgid "Permanent Repository ID"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:11
+msgid "What is that?"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:13
+msgid "URL by id"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:14
+msgid ""
+"In case this repository is renamed or moved into another group the "
+"repository URL changes.\n"
+"                               Using the above permanent URL guarantees "
+"that this repository always will be accessible on that URL.\n"
+"                               This is useful for CI systems, or any "
+"other cases that you need to hardcode the URL into a 3rd party service."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:21
+msgid "Remote repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:25
+msgid "Repository URL"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:29
+msgid ""
+"Optional: URL of a remote repository. If set, the repository can be "
+"pulled from this URL."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:48
+msgid "Default revision for files page, downloads, whoosh and readme"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:58
+msgid "Change owner of this repository."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_statistics.html:6
+msgid "Processed commits"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_statistics.html:7
+msgid "Processed progress"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_statistics.html:10
+msgid "Reset Statistics"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_statistics.html:10
+msgid "Confirm to remove current statistics."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repos.html:5
+msgid "Repositories Administration"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repos.html:51
+msgid "State"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings.html:5
+msgid "Settings Administration"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings.html:27
+msgid "VCS"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings.html:28
+msgid "Remap and Rescan"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings.html:30
+msgid "Visual"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings.html:32
+#: kallithea/templates/admin/settings/settings_vcs.html:19
+msgid "Hooks"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings.html:33
+msgid "Full Text Search"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings.html:34
+msgid "System Info"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_email.html:7
+msgid "Send test email to"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_email.html:15
+msgid "Send"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:8
+msgid "Site branding"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:12
+msgid "Set a custom title for your Kallithea Service."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:18
+msgid "HTTP authentication realm"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:27
+msgid "Analytics HTML block"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:31
+msgid ""
+"HTML with JavaScript for web analytics systems like Google Analytics or "
+"Piwik. This will be added at the bottom of every page."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:37
+msgid "ReCaptcha public key"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:41
+msgid "Public key for reCaptcha system."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:47
+msgid "ReCaptcha private key"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:51
+msgid ""
+"Private key for reCaptcha system. Setting this value will enable captcha "
+"on registration."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:56
+#: kallithea/templates/admin/settings/settings_vcs.html:80
+#: kallithea/templates/admin/settings/settings_visual.html:116
+msgid "Save Settings"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_hooks.html:1
+msgid "Built-in Mercurial Hooks (Read-Only)"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_hooks.html:15
+msgid ""
+"Hooks can be used to trigger actions on certain events such as push / "
+"pull. They can trigger Python functions or external applications."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_hooks.html:19
+msgid "Custom Hooks"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_hooks.html:67
+msgid "Failed to remove hook"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:6
+msgid "Rescan option"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:11
+msgid "Delete records of missing repositories"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:13
+msgid ""
+"Check this option to remove all comments, pull requests and other records"
+" related to repositories that no longer exist in the filesystem."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:17
+msgid "Invalidate cache for all repositories"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:19
+msgid "Check this to reload data and clear cache keys for all repositories."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:23
+msgid "Install Git hooks"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:25
+msgid ""
+"Verify if Kallithea's Git hooks are installed for each repository. "
+"Current hooks will be updated to the latest version."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:28
+msgid "Overwrite existing Git hooks"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:30
+msgid ""
+"If installing Git hooks, overwrite any existing hooks, even if they do "
+"not seem to come from Kallithea. WARNING: This operation will destroy any"
+" custom git hooks you may have deployed by hand!"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:35
+msgid "Rescan Repositories"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_search.html:7
+msgid "Index build option"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_search.html:12
+msgid "Build from scratch"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_search.html:15
+msgid ""
+"This option completely reindexeses all of the repositories for proper "
+"fulltext search capabilities."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_search.html:21
+msgid "Reindex"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:4
+msgid "Kallithea version"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:4
+msgid "Check for updates"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:5
+msgid "Kallithea configuration file"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:6
+msgid "Python version"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:7
+msgid "Platform"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:8
+msgid "Git version"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:9
+msgid "Git path"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:10
+msgid "Upgrade info endpoint"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:10
+msgid "Note: please make sure this server can access this URL"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:15
+msgid "Checking for updates..."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:23
+msgid "Python Packages"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:6
+msgid "Web"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:11
+msgid "Require SSL for vcs operations"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:13
+msgid ""
+"Activate to require SSL both pushing and pulling. If SSL certificate is "
+"missing, it will return an HTTP Error 406: Not Acceptable."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:24
+msgid "Show repository size after push"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:28
+msgid "Log user push commands"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:32
+msgid "Log user pull commands"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:36
+msgid "Update repository after push (hg update)"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:42
+msgid "Mercurial extensions"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:47
+msgid "Enable largefiles extension"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:51
+msgid "Enable hgsubversion extension"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:53
+msgid ""
+"Requires hgsubversion library to be installed. Enables cloning of remote "
+"Subversion repositories while converting them to Mercurial."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:64
+msgid "Location of repositories"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:69
+msgid ""
+"Click to unlock. You must restart Kallithea in order to make this setting"
+" take effect."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:72
+msgid ""
+"Filesystem location where repositories are stored. After changing this "
+"value, a restart and rescan of the repository folder are both required."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:8
+msgid "General"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:13
+msgid "Use repository extra fields"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:15
+msgid "Allows storing additional customized fields per repository."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:18
+msgid "Show Kallithea version"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:20
+msgid "Shows or hides a version number of Kallithea displayed in the footer."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:24
+msgid "Use Gravatars in Kallithea"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:30
+msgid ""
+"Gravatar URL allows you to use another avatar server application.\n"
+"                                                        The following "
+"variables of the URL will be replaced accordingly.\n"
+"                                                        {scheme}    "
+"'http' or 'https' sent from running Kallithea server,\n"
+"                                                        {email}     user "
+"email,\n"
+"                                                        {md5email}  md5 "
+"hash of the user email (like at gravatar.com),\n"
+"                                                        {size}      size "
+"of the image that is expected from the server application,\n"
+"                                                        {netloc}    "
+"network location/server host of running Kallithea server"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:42
+msgid ""
+"Schema of clone URL construction eg. '{scheme}://{user}@{netloc}/{repo}'."
+"\n"
+"                                                        The following "
+"variables are available:\n"
+"                                                        {scheme} 'http' "
+"or 'https' sent from running Kallithea server,\n"
+"                                                        {user}   current "
+"user username,\n"
+"                                                        {netloc} network "
+"location/server host of running Kallithea server,\n"
+"                                                        {repo}   full "
+"repository name,\n"
+"                                                        {repoid} ID of "
+"repository, can be used to contruct clone-by-id"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:55
+msgid "Dashboard items"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:59
+msgid ""
+"Number of items displayed in the main page dashboard before pagination is"
+" shown."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:65
+msgid "Admin pages items"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:69
+msgid ""
+"Number of items displayed in the admin pages grids before pagination is "
+"shown."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:75
+msgid "Icons"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:80
+msgid "Show public repository icon on repositories"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:84
+msgid "Show private repository icon on repositories"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:86
+msgid "Show public/private icons next to repository names."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:92
+msgid "Meta Tagging"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:97
+msgid "Stylify recognised meta tags:"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:111
+msgid ""
+"Parses meta tags from the repository description field and turns them "
+"into colored tags."
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_add.html:5
+msgid "Add user group"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_add.html:10
+#: kallithea/templates/admin/user_groups/user_group_edit.html:11
+#: kallithea/templates/admin/user_groups/user_groups.html:10
+#: kallithea/templates/base/base.html:63 kallithea/templates/base/base.html:83
+msgid "User Groups"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_add.html:12
+#: kallithea/templates/admin/user_groups/user_groups.html:25
+msgid "Add User Group"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_add.html:44
+#: kallithea/templates/admin/user_groups/user_group_edit_settings.html:19
+msgid "Short, optional description for this user group."
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit.html:5
+#, python-format
+msgid "%s user group settings"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit.html:33
+msgid "Show Members"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit_advanced.html:1
+#, python-format
+msgid "User Group: %s"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit_advanced.html:6
+#: kallithea/templates/admin/user_groups/user_group_edit_settings.html:32
+#: kallithea/templates/admin/user_groups/user_groups.html:48
+msgid "Members"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit_advanced.html:19
+#: kallithea/templates/data_table/_dt_elements.html:174
+#, python-format
+msgid "Confirm to delete this user group: %s"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit_advanced.html:21
+msgid "Delete this user group"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit_members.html:17
+msgid "No members yet"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit_settings.html:40
+msgid "Chosen group members"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit_settings.html:49
+msgid "Available members"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_groups.html:5
+msgid "User Groups Administration"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_add.html:5
+msgid "Add user"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_add.html:10
+#: kallithea/templates/admin/users/user_edit.html:11
+#: kallithea/templates/admin/users/users.html:10
+#: kallithea/templates/base/base.html:62
+msgid "Users"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_add.html:12
+#: kallithea/templates/admin/users/users.html:24
+msgid "Add User"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_add.html:50
+msgid "Password confirmation"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit.html:5
+#, python-format
+msgid "%s user settings"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit.html:30
+msgid "Emails"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_advanced.html:1
+#, python-format
+msgid "User: %s"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_advanced.html:7
+#: kallithea/templates/admin/users/user_edit_profile.html:42
+msgid "Source of Record"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_advanced.html:9
+#: kallithea/templates/admin/users/users.html:53
+msgid "Last Login"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_advanced.html:10
+msgid "Member of User Groups"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_advanced.html:21
+#: kallithea/templates/data_table/_dt_elements.html:158
+#, python-format
+msgid "Confirm to delete this user: %s"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_advanced.html:23
+msgid "Delete this user"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_ips.html:8
+#, python-format
+msgid "Inherited from %s"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_profile.html:8
+msgid "Change avatar at"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_profile.html:12
+msgid "Missing email, please update this user email address."
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_profile.html:51
+msgid "Name in Source of Record"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_profile.html:69
+msgid "New password confirmation"
+msgstr ""
+
+#: kallithea/templates/admin/users/users.html:5
+msgid "Users Administration"
+msgstr ""
+
+#: kallithea/templates/admin/users/users.html:56
+msgid "Auth Type"
+msgstr ""
+
+#: kallithea/templates/base/base.html:18
+#, python-format
+msgid "Server instance: %s"
+msgstr ""
+
+#: kallithea/templates/base/base.html:30
+msgid "Support"
+msgstr ""
+
+#: kallithea/templates/base/base.html:90
+msgid "Mercurial repository"
+msgstr ""
+
+#: kallithea/templates/base/base.html:93
+msgid "Git repository"
+msgstr ""
+
+#: kallithea/templates/base/base.html:119
+msgid "Create Fork"
+msgstr ""
+
+#: kallithea/templates/base/base.html:130
+#: kallithea/templates/data_table/_dt_elements.html:13
+#: kallithea/templates/data_table/_dt_elements.html:17
+#: kallithea/templates/summary/summary.html:8
+msgid "Summary"
+msgstr ""
+
+#: kallithea/templates/base/base.html:132
+#: kallithea/templates/base/base.html:134
+#: kallithea/templates/changelog/changelog.html:14
+#: kallithea/templates/data_table/_dt_elements.html:21
+#: kallithea/templates/data_table/_dt_elements.html:25
+msgid "Changelog"
+msgstr ""
+
+#: kallithea/templates/base/base.html:136
+#: kallithea/templates/data_table/_dt_elements.html:29
+#: kallithea/templates/data_table/_dt_elements.html:33
+#: kallithea/templates/files/files.html:11
+msgid "Files"
+msgstr ""
+
+#: kallithea/templates/base/base.html:142
+#: kallithea/templates/base/base.html:144
+msgid "Options"
+msgstr ""
+
+#: kallithea/templates/base/base.html:152
+#: kallithea/templates/forks/forks_data.html:21
+msgid "Compare Fork"
+msgstr ""
+
+#: kallithea/templates/base/base.html:154
+#: kallithea/templates/bookmarks/bookmarks.html:56
+#: kallithea/templates/bookmarks/bookmarks_data.html:13
+#: kallithea/templates/branches/branches.html:56
+#: kallithea/templates/branches/branches_data.html:13
+#: kallithea/templates/tags/tags.html:56
+#: kallithea/templates/tags/tags_data.html:13
+msgid "Compare"
+msgstr ""
+
+#: kallithea/templates/base/base.html:156
+#: kallithea/templates/base/base.html:331
+#: kallithea/templates/search/search.html:14
+#: kallithea/templates/search/search.html:54
+msgid "Search"
+msgstr ""
+
+#: kallithea/templates/base/base.html:160
+msgid "Unlock"
+msgstr ""
+
+#: kallithea/templates/base/base.html:162
+msgid "Lock"
+msgstr ""
+
+#: kallithea/templates/base/base.html:170
+msgid "Follow"
+msgstr ""
+
+#: kallithea/templates/base/base.html:171
+msgid "Unfollow"
+msgstr ""
+
+#: kallithea/templates/base/base.html:174
+#: kallithea/templates/data_table/_dt_elements.html:37
+#: kallithea/templates/data_table/_dt_elements.html:41
+#: kallithea/templates/forks/fork.html:9
+msgid "Fork"
+msgstr ""
+
+#: kallithea/templates/base/base.html:175
+#: kallithea/templates/pullrequests/pullrequest.html:88
+msgid "Create Pull Request"
+msgstr ""
+
+#: kallithea/templates/base/base.html:180
+#, python-format
+msgid "Show Pull Requests for %s"
+msgstr ""
+
+#: kallithea/templates/base/base.html:193
+msgid "Switch To"
+msgstr ""
+
+#: kallithea/templates/base/base.html:203
+#: kallithea/templates/base/base.html:485
+msgid "No matches found"
+msgstr ""
+
+#: kallithea/templates/base/base.html:305
+msgid "Show recent activity"
+msgstr ""
+
+#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:312
+msgid "Public journal"
+msgstr ""
+
+#: kallithea/templates/base/base.html:317
+msgid "Show public gists"
+msgstr ""
+
+#: kallithea/templates/base/base.html:318
+msgid "Gists"
+msgstr ""
+
+#: kallithea/templates/base/base.html:322
+msgid "All Public Gists"
+msgstr ""
+
+#: kallithea/templates/base/base.html:324
+msgid "My Public Gists"
+msgstr ""
+
+#: kallithea/templates/base/base.html:325
+msgid "My Private Gists"
+msgstr ""
+
+#: kallithea/templates/base/base.html:330
+msgid "Search in repositories"
+msgstr ""
+
+#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:354
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:6
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:10
+msgid "My Pull Requests"
+msgstr ""
+
+#: kallithea/templates/base/base.html:377
+msgid "Not Logged In"
+msgstr ""
+
+#: kallithea/templates/base/base.html:384
+msgid "Login to Your Account"
+msgstr ""
+
+#: kallithea/templates/base/base.html:407
+msgid "Forgot password ?"
+msgstr ""
+
+#: kallithea/templates/base/base.html:434
+msgid "Log Out"
+msgstr ""
+
+#: kallithea/templates/base/base.html:615
+msgid "Keyboard shortcuts"
+msgstr ""
+
+#: kallithea/templates/base/base.html:624
+msgid "Site-wide shortcuts"
+msgstr ""
+
+#: kallithea/templates/base/default_perms_box.html:14
+msgid "Inherit defaults"
+msgstr ""
+
+#: kallithea/templates/base/default_perms_box.html:19
+#, python-format
+msgid ""
+"Select to inherit global settings, IP whitelist and permissions from the "
+"%s."
+msgstr ""
+
+#: kallithea/templates/base/default_perms_box.html:28
+msgid "Create repositories"
+msgstr ""
+
+#: kallithea/templates/base/default_perms_box.html:33
+msgid "Select this option to allow repository creation for this user"
+msgstr ""
+
+#: kallithea/templates/base/default_perms_box.html:40
+msgid "Create user groups"
+msgstr ""
+
+#: kallithea/templates/base/default_perms_box.html:45
+msgid "Select this option to allow user group creation for this user"
+msgstr ""
+
+#: kallithea/templates/base/default_perms_box.html:52
+msgid "Fork repositories"
+msgstr ""
+
+#: kallithea/templates/base/default_perms_box.html:57
+msgid "Select this option to allow repository forking for this user"
+msgstr ""
+
+#: kallithea/templates/base/perms_summary.html:13
+#: kallithea/templates/changelog/changelog.html:42
+msgid "Show"
+msgstr ""
+
+#: kallithea/templates/base/perms_summary.html:22
+msgid "No permissions defined yet"
+msgstr ""
+
+#: kallithea/templates/base/perms_summary.html:30
+#: kallithea/templates/base/perms_summary.html:54
+msgid "Permission"
+msgstr ""
+
+#: kallithea/templates/base/perms_summary.html:32
+#: kallithea/templates/base/perms_summary.html:56
+msgid "Edit Permission"
+msgstr ""
+
+#: kallithea/templates/base/perms_summary.html:90
+msgid "No permission defined"
+msgstr ""
+
+#: kallithea/templates/base/root.html:22
+msgid "Add Another Comment"
+msgstr ""
+
+#: kallithea/templates/base/root.html:23
+#: kallithea/templates/data_table/_dt_elements.html:214
+msgid "Stop following this repository"
+msgstr ""
+
+#: kallithea/templates/base/root.html:24
+msgid "Start following this repository"
+msgstr ""
+
+#: kallithea/templates/base/root.html:25
+msgid "Group"
+msgstr ""
+
+#: kallithea/templates/base/root.html:26
+msgid "members"
+msgstr ""
+
+#: kallithea/templates/base/root.html:27
+msgid "Loading ..."
+msgstr ""
+
+#: kallithea/templates/base/root.html:28
+msgid "loading ..."
+msgstr ""
+
+#: kallithea/templates/base/root.html:29
+msgid "Search truncated"
+msgstr ""
+
+#: kallithea/templates/base/root.html:30
+msgid "No matching files"
+msgstr ""
+
+#: kallithea/templates/base/root.html:31
+msgid "Open New Pull Request from {0}"
+msgstr ""
+
+#: kallithea/templates/base/root.html:32
+msgid "Open New Pull Request for {0} &rarr; {1}"
+msgstr ""
+
+#: kallithea/templates/base/root.html:33
+msgid "Show Selected Changesets {0} &rarr; {1}"
+msgstr ""
+
+#: kallithea/templates/base/root.html:34
+msgid "Selection Link"
+msgstr ""
+
+#: kallithea/templates/base/root.html:35
+#: kallithea/templates/changeset/diff_block.html:8
+#: kallithea/templates/changeset/diff_block.html:21
+msgid "Collapse Diff"
+msgstr ""
+
+#: kallithea/templates/base/root.html:36
+msgid "Expand Diff"
+msgstr ""
+
+#: kallithea/templates/base/root.html:37
+msgid "Failed to revoke permission"
+msgstr ""
+
+#: kallithea/templates/base/root.html:38
+msgid "Confirm to revoke permission for {0}: {1} ?"
+msgstr ""
+
+#: kallithea/templates/base/root.html:39
+msgid "enabled"
+msgstr ""
+
+#: kallithea/templates/base/root.html:40
+msgid "disabled"
+msgstr ""
+
+#: kallithea/templates/base/root.html:42
+msgid "Specify changeset"
+msgstr ""
+
+#: kallithea/templates/bookmarks/bookmarks.html:5
+#, python-format
+msgid "%s Bookmarks"
+msgstr ""
+
+#: kallithea/templates/bookmarks/bookmarks.html:26
+msgid "Compare Bookmarks"
+msgstr ""
+
+#: kallithea/templates/bookmarks/bookmarks.html:53
+#: kallithea/templates/bookmarks/bookmarks_data.html:10
+#: kallithea/templates/branches/branches.html:53
+#: kallithea/templates/branches/branches_data.html:10
+#: kallithea/templates/changelog/changelog_summary_data.html:10
+#: kallithea/templates/tags/tags.html:53
+#: kallithea/templates/tags/tags_data.html:10
+msgid "Author"
+msgstr ""
+
+#: kallithea/templates/bookmarks/bookmarks.html:54
+#: kallithea/templates/bookmarks/bookmarks_data.html:12
+#: kallithea/templates/branches/branches.html:54
+#: kallithea/templates/branches/branches_data.html:12
+#: kallithea/templates/changelog/changelog_summary_data.html:7
+#: kallithea/templates/files/files_browser.html:32
+#: kallithea/templates/pullrequests/pullrequest.html:62
+#: kallithea/templates/pullrequests/pullrequest.html:78
+#: kallithea/templates/tags/tags.html:54
+#: kallithea/templates/tags/tags_data.html:12
+msgid "Revision"
+msgstr ""
+
+#: kallithea/templates/branches/branches.html:5
+#, python-format
+msgid "%s Branches"
+msgstr ""
+
+#: kallithea/templates/branches/branches.html:26
+msgid "Compare Branches"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:6
+#, python-format
+msgid "%s Changelog"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:21
+#, python-format
+msgid "showing %d out of %d revision"
+msgid_plural "showing %d out of %d revisions"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/changelog/changelog.html:49
+msgid "Clear selection"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:55
+msgid "Go to tip of repository"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:60
+#: kallithea/templates/forks/forks_data.html:19
+#, python-format
+msgid "Compare fork with %s"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:62
+#, python-format
+msgid "Compare fork with parent repository (%s)"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:66
+#: kallithea/templates/files/files.html:29
+msgid "Branch filter:"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:92
+#: kallithea/templates/changelog/changelog_summary_data.html:20
+#, python-format
+msgid ""
+"Changeset status: %s by %s\n"
+"Click to open associated pull request %s"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:96
+#: kallithea/templates/changelog/changelog_summary_data.html:24
+#, python-format
+msgid "Changeset status: %s by %s"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:116
+#: kallithea/templates/compare/compare_cs.html:63
+msgid "Expand commit message"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:125
+#: kallithea/templates/compare/compare_cs.html:30
+msgid "Changeset has comments"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:135
+#: kallithea/templates/changelog/changelog_summary_data.html:57
+#: kallithea/templates/changeset/changeset.html:94
+#: kallithea/templates/changeset/changeset_range.html:92
+#, python-format
+msgid "Bookmark %s"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:141
+#: kallithea/templates/changelog/changelog_summary_data.html:63
+#: kallithea/templates/changeset/changeset.html:101
+#: kallithea/templates/changeset/changeset_range.html:98
+#: kallithea/templates/compare/compare_cs.html:69
+#: kallithea/templates/pullrequests/pullrequest_show.html:203
+#, python-format
+msgid "Tag %s"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:146
+#: kallithea/templates/changelog/changelog_summary_data.html:68
+#: kallithea/templates/changeset/changeset.html:106
+#: kallithea/templates/changeset/changeset_range.html:102
+#, python-format
+msgid "Branch %s"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:311
+msgid "There are no changes yet"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_details.html:4
+#: kallithea/templates/changeset/changeset.html:77
+msgid "Removed"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_details.html:5
+#: kallithea/templates/changeset/changeset.html:78
+msgid "Changed"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_details.html:6
+#: kallithea/templates/changeset/changeset.html:79
+#: kallithea/templates/changeset/diff_block.html:47
+msgid "Added"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_details.html:8
+#: kallithea/templates/changelog/changelog_details.html:9
+#: kallithea/templates/changelog/changelog_details.html:10
+#: kallithea/templates/changeset/changeset.html:81
+#: kallithea/templates/changeset/changeset.html:82
+#: kallithea/templates/changeset/changeset.html:83
+#, python-format
+msgid "Affected %s files"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_summary_data.html:8
+#: kallithea/templates/files/files_add.html:60
+#: kallithea/templates/files/files_delete.html:39
+#: kallithea/templates/files/files_edit.html:63
+msgid "Commit Message"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_summary_data.html:9
+#: kallithea/templates/pullrequests/pullrequest_data.html:17
+msgid "Age"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_summary_data.html:11
+msgid "Refs"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_summary_data.html:84
+msgid "Add or upload files directly via Kallithea"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_summary_data.html:87
+#: kallithea/templates/files/files_add.html:21
+#: kallithea/templates/files/files_ypjax.html:9
+msgid "Add New File"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_summary_data.html:93
+msgid "Push new repository"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_summary_data.html:101
+msgid "Existing repository?"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:8
+#, python-format
+msgid "%s Changeset"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:36
+msgid "Parent rev."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:42
+msgid "Child rev."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:50
+#: kallithea/templates/changeset/changeset_file_comment.html:39
+#: kallithea/templates/changeset/changeset_range.html:48
+msgid "Changeset status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:54
+#: kallithea/templates/changeset/diff_block.html:72
+#: kallithea/templates/files/diff_2way.html:49
+msgid "Raw diff"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:57
+msgid "Patch diff"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:60
+#: kallithea/templates/changeset/diff_block.html:75
+#: kallithea/templates/files/diff_2way.html:52
+msgid "Download diff"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:89
+#: kallithea/templates/changeset/changeset_range.html:88
+msgid "Merge"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:123
+msgid "Grafted from:"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:129
+msgid "Transplanted from:"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:135
+msgid "Replaced by:"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:149
+msgid "Preceded by:"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:166
+#: kallithea/templates/compare/compare_diff.html:60
+#: kallithea/templates/pullrequests/pullrequest_show.html:329
+#, python-format
+msgid "%s file changed"
+msgid_plural "%s files changed"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/changeset/changeset.html:168
+#: kallithea/templates/compare/compare_diff.html:62
+#: kallithea/templates/pullrequests/pullrequest_show.html:331
+#, python-format
+msgid "%s file changed with %s insertions and %s deletions"
+msgid_plural "%s files changed with %s insertions and %s deletions"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/changeset/changeset.html:182
+#: kallithea/templates/changeset/changeset.html:195
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
+msgid "Show full diff anyway"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:231
+#: kallithea/templates/changeset/changeset.html:268
+msgid "No revisions"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:21
+msgid "on pull request"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:22
+msgid "No title"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:24
+msgid "on this changeset"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+msgid "Delete comment?"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:39
+msgid "Status change"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:59
+msgid "Commenting on line."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:60
+msgid ""
+"Comments are in plain text. Use @username inside this text to notify "
+"another user."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:67
+msgid "Set changeset status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:69
+msgid "Vote for pull request status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:75
+msgid "No change"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:88
+#, fuzzy
+msgid "Finish pull request"
+msgstr "Λάθος στη δημιουργία αιτήματος έλξης - pull request: %s"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:91
+msgid "Close"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:103
+msgid "Submitting ..."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:104
+msgid "Comment"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:112
+msgid "You need to be logged in to comment."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:112
+msgid "Login now"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:116
+msgid "Hide"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:128
+#, python-format
+msgid "%d comment"
+msgid_plural "%d comments"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:129
+#, python-format
+msgid "%d inline"
+msgid_plural "%d inline"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:130
+#, python-format
+msgid "%d general"
+msgid_plural "%d general"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/changeset/changeset_range.html:5
+#, python-format
+msgid "%s Changesets"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_range.html:56
+msgid "Files affected"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:54
+msgid "Deleted"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:57
+msgid "Renamed"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:66
+#: kallithea/templates/files/diff_2way.html:43
+msgid "Show full diff for this file"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:69
+#: kallithea/templates/files/diff_2way.html:46
+msgid "Show full side-by-side diff for this file"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:83
+msgid "Show inline comments"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:4
+msgid "No changesets"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:8
+msgid "Ancestor"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:24
+#, python-format
+msgid "Changeset status: %s"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:44
+msgid "First (oldest) changeset in this list"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:46
+msgid "Last (most recent) changeset in this list"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:48
+msgid "Position in this list of changesets"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:85
+msgid "Show merge diff"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:95
+#: kallithea/templates/pullrequests/pullrequest_show.html:321
+msgid "Common ancestor"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:99
+msgid "No common ancestor found - repositories are unrelated"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:107
+msgid "is"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:108
+#, python-format
+msgid "%s changesets"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:109
+msgid "behind"
+msgstr ""
+
+#: kallithea/templates/compare/compare_diff.html:6
+#: kallithea/templates/compare/compare_diff.html:8
+#, python-format
+msgid "%s Compare"
+msgstr ""
+
+#: kallithea/templates/compare/compare_diff.html:13
+#: kallithea/templates/compare/compare_diff.html:41
+msgid "Compare Revisions"
+msgstr ""
+
+#: kallithea/templates/compare/compare_diff.html:39
+msgid "Swap"
+msgstr ""
+
+#: kallithea/templates/compare/compare_diff.html:48
+msgid "Compare revisions, branches, bookmarks, or tags."
+msgstr ""
+
+#: kallithea/templates/compare/compare_diff.html:53
+#: kallithea/templates/pullrequests/pullrequest_show.html:316
+#, python-format
+msgid "Showing %s commit"
+msgid_plural "Showing %s commits"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+msgid "Show full diff"
+msgstr ""
+
+#: kallithea/templates/data_table/_dt_elements.html:74
+msgid "Public repository"
+msgstr ""
+
+#: kallithea/templates/data_table/_dt_elements.html:84
+msgid "Repository creation in progress..."
+msgstr ""
+
+#: kallithea/templates/data_table/_dt_elements.html:98
+msgid "No changesets yet"
+msgstr ""
+
+#: kallithea/templates/data_table/_dt_elements.html:105
+#: kallithea/templates/data_table/_dt_elements.html:107
+#, python-format
+msgid "Subscribe to %s rss feed"
+msgstr ""
+
+#: kallithea/templates/data_table/_dt_elements.html:113
+#: kallithea/templates/data_table/_dt_elements.html:115
+#, python-format
+msgid "Subscribe to %s atom feed"
+msgstr ""
+
+#: kallithea/templates/data_table/_dt_elements.html:139
+msgid "Creating"
+msgstr ""
+
+#: kallithea/templates/email_templates/changeset_comment.html:5
+#, python-format
+msgid "Comment from %s on %s changeset %s mentioned you"
+msgstr ""
+
+#: kallithea/templates/email_templates/changeset_comment.html:7
+#, python-format
+msgid "Comment from %s on %s changeset %s"
+msgstr ""
+
+#: kallithea/templates/email_templates/changeset_comment.html:12
+msgid "The changeset status was changed to"
+msgstr ""
+
+#: kallithea/templates/email_templates/main.html:6
+msgid "This is an automatic notification. Don't reply to this mail."
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:4
+#, python-format
+msgid "Hello %s"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:6
+msgid "We have received a request to reset the password for your account."
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:8
+msgid ""
+"This account is however managed outside this system and the password "
+"cannot be changed here."
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:10
+msgid "To set a new password, click the following link"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:13
+msgid ""
+"Should you not be able to use the link above, please type the following "
+"code into the password reset form"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:16
+msgid ""
+"If it weren't you who requested the password reset, just disregard this "
+"message."
+msgstr ""
+
+#: kallithea/templates/email_templates/pull_request.html:5
+#, python-format
+msgid "%s mentioned you on %s pull request \"%s\""
+msgstr ""
+
+#: kallithea/templates/email_templates/pull_request.html:7
+#, python-format
+msgid "%s requested your review of %s pull request \"%s\""
+msgstr ""
+
+#: kallithea/templates/email_templates/pull_request_comment.html:4
+#, python-format
+msgid "Comment from %s on %s pull request \"%s\""
+msgstr ""
+
+#: kallithea/templates/email_templates/pull_request_comment.html:9
+msgid "The comment closed the pull request with status"
+msgstr ""
+
+#: kallithea/templates/email_templates/pull_request_comment.html:11
+msgid "The comment was made with status"
+msgstr ""
+
+#: kallithea/templates/email_templates/registration.html:6
+msgid "View this user here"
+msgstr ""
+
+#: kallithea/templates/files/diff_2way.html:15
+#, python-format
+msgid "%s File side-by-side diff"
+msgstr ""
+
+#: kallithea/templates/files/diff_2way.html:19
+#: kallithea/templates/files/file_diff.html:8
+msgid "File diff"
+msgstr ""
+
+#: kallithea/templates/files/file_diff.html:4
+#, python-format
+msgid "%s File Diff"
+msgstr ""
+
+#: kallithea/templates/files/files.html:4
+#: kallithea/templates/files/files.html:80
+#, python-format
+msgid "%s Files"
+msgstr ""
+
+#: kallithea/templates/files/files_add.html:4
+#, python-format
+msgid "%s Files Add"
+msgstr ""
+
+#: kallithea/templates/files/files_add.html:40
+#: kallithea/templates/files/files_edit.html:38
+#: kallithea/templates/files/files_ypjax.html:3
+msgid "Location"
+msgstr ""
+
+#: kallithea/templates/files/files_add.html:42
+msgid "Enter filename..."
+msgstr ""
+
+#: kallithea/templates/files/files_add.html:44
+#: kallithea/templates/files/files_add.html:48
+msgid "or"
+msgstr ""
+
+#: kallithea/templates/files/files_add.html:44
+msgid "Upload File"
+msgstr ""
+
+#: kallithea/templates/files/files_add.html:48
+msgid "Create New File"
+msgstr ""
+
+#: kallithea/templates/files/files_add.html:53
+#, fuzzy
+msgid "New file type"
+msgstr "Άγνωστος τύπος αρχειοθέτησης"
+
+#: kallithea/templates/files/files_add.html:64
+#: kallithea/templates/files/files_delete.html:43
+#: kallithea/templates/files/files_edit.html:67
+msgid "Commit Changes"
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:33
+msgid "Previous revision"
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:35
+msgid "Next revision"
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:41
+msgid "Follow current branch"
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:44
+msgid "Search File List"
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:48
+msgid "Loading file list..."
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:61
+msgid "Size"
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:62
+msgid "Last Revision"
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:63
+msgid "Last Modified"
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:64
+msgid "Last Committer"
+msgstr ""
+
+#: kallithea/templates/files/files_delete.html:4
+#, python-format
+msgid "%s Files Delete"
+msgstr ""
+
+#: kallithea/templates/files/files_delete.html:12
+#: kallithea/templates/files/files_delete.html:31
+msgid "Delete file"
+msgstr ""
+
+#: kallithea/templates/files/files_edit.html:4
+#, python-format
+msgid "%s File Edit"
+msgstr ""
+
+#: kallithea/templates/files/files_edit.html:21
+msgid "Edit file"
+msgstr ""
+
+#: kallithea/templates/files/files_edit.html:48
+#: kallithea/templates/files/files_source.html:32
+msgid "Show Annotation"
+msgstr ""
+
+#: kallithea/templates/files/files_edit.html:50
+#: kallithea/templates/files/files_source.html:35
+msgid "Download as Raw"
+msgstr ""
+
+#: kallithea/templates/files/files_edit.html:53
+msgid "Source"
+msgstr ""
+
+#: kallithea/templates/files/files_edit.html:58
+msgid "Editing file"
+msgstr ""
+
+#: kallithea/templates/files/files_history_box.html:2
+#, python-format
+msgid "%s author"
+msgid_plural "%s authors"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/files/files_source.html:7
+msgid "Diff to Revision"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:8
+msgid "Show at Revision"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:10
+msgid "Show Full History"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:11
+msgid "Show Authors"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:30
+msgid "Show Source"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:38
+#, python-format
+msgid "Edit on Branch:%s"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:41
+msgid "Editing binary files not allowed"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:44
+msgid "Editing files allowed only when on branch head revision"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:45
+msgid "Deleting files allowed only when on branch head revision"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:63
+#, python-format
+msgid "Binary file (%s)"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:74
+msgid "File is too big to display."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:76
+msgid "Show full annotation anyway."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:78
+msgid "Show as raw."
+msgstr ""
+
+#: kallithea/templates/files/files_ypjax.html:5
+msgid "annotation"
+msgstr ""
+
+#: kallithea/templates/files/files_ypjax.html:23
+msgid "Go Back"
+msgstr ""
+
+#: kallithea/templates/files/files_ypjax.html:24
+msgid "No files at given path"
+msgstr ""
+
+#: kallithea/templates/followers/followers.html:5
+#, python-format
+msgid "%s Followers"
+msgstr ""
+
+#: kallithea/templates/followers/followers.html:9
+#: kallithea/templates/summary/summary.html:142
+#: kallithea/templates/summary/summary.html:143
+msgid "Followers"
+msgstr ""
+
+#: kallithea/templates/followers/followers_data.html:12
+msgid "Started following -"
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:5
+#, python-format
+msgid "Fork repository %s"
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:27
+msgid "Fork name"
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:62
+msgid "Default revision for files page, downloads, whoosh, and readme."
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:68
+msgid "Private"
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:77
+msgid "Copy permissions"
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:81
+msgid "Copy permissions from forked repository"
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:87
+msgid "Update after clone"
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:91
+msgid "Checkout source after making a clone"
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:96
+msgid "Fork this Repository"
+msgstr ""
+
+#: kallithea/templates/forks/forks.html:5
+#, python-format
+msgid "%s Forks"
+msgstr ""
+
+#: kallithea/templates/forks/forks.html:9
+#: kallithea/templates/summary/summary.html:148
+#: kallithea/templates/summary/summary.html:149
+msgid "Forks"
+msgstr ""
+
+#: kallithea/templates/forks/forks_data.html:17
+msgid "Forked"
+msgstr ""
+
+#: kallithea/templates/forks/forks_data.html:30
+msgid "There are no forks yet"
+msgstr ""
+
+#: kallithea/templates/journal/journal.html:21
+msgid "ATOM journal feed"
+msgstr ""
+
+#: kallithea/templates/journal/journal.html:22
+msgid "RSS journal feed"
+msgstr ""
+
+#: kallithea/templates/journal/journal.html:56
+msgid "My Repositories"
+msgstr ""
+
+#: kallithea/templates/journal/journal_data.html:43
+msgid "No entries yet"
+msgstr ""
+
+#: kallithea/templates/journal/public_journal.html:13
+msgid "ATOM public journal feed"
+msgstr ""
+
+#: kallithea/templates/journal/public_journal.html:14
+msgid "RSS public journal feed"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest.html:4
+#: kallithea/templates/pullrequests/pullrequest.html:8
+msgid "New Pull Request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest.html:31
+#: kallithea/templates/pullrequests/pullrequest_data.html:15
+#: kallithea/templates/pullrequests/pullrequest_show.html:29
+#: kallithea/templates/pullrequests/pullrequest_show.html:54
+msgid "Title"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest.html:34
+msgid "Summarize the changes - or leave empty"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest.html:43
+#: kallithea/templates/pullrequests/pullrequest_show.html:66
+msgid "Write a short description on this pull request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest.html:49
+msgid "Changeset flow"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest.html:56
+msgid "Origin repository"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest.html:72
+msgid "Destination repository"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:6
+msgid "No entries"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:14
+msgid "Vote"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:18
+msgid "From"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:19
+msgid "To"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:28
+#, python-format
+msgid "You voted: %s"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:30
+msgid "You didn't vote"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:35
+msgid "(no title)"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:37
+#: kallithea/templates/pullrequests/pullrequest_show.html:31
+#: kallithea/templates/pullrequests/pullrequest_show.html:83
+msgid "Closed"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:67
+msgid "Delete Pull Request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:68
+msgid "Confirm to delete this pull request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:70
+#, python-format
+msgid "Confirm again to delete this pull request with %s comments"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:6
+#, python-format
+msgid "%s Pull Request %s"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:10
+#, python-format
+msgid "Pull request %s from %s#%s"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:57
+msgid "Summarize the changes"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:74
+msgid "Reviewer voting result"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:80
+#: kallithea/templates/pullrequests/pullrequest_show.html:81
+msgid "Pull request status calculated from votes"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:93
+msgid "Still not reviewed by"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:97
+#, python-format
+msgid "%d reviewer"
+msgid_plural "%d reviewers"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:99
+msgid "Pull request was reviewed by all reviewers"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:101
+msgid "There are no reviewers"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:107
+msgid "Origin"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:113
+msgid "on"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:120
+msgid "Target"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:124
+msgid ""
+"This is just a range of changesets and doesn't have a target or a real "
+"merge ancestor."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:133
+msgid "Pull changes"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:173
+msgid "Update"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:191
+msgid "Current revision - no change"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:215
+msgid ""
+"Pull requests do not change once created. Select a revision and save to "
+"replace this pull request with a new one."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:224
+msgid "Pull Request Reviewers"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:249
+msgid "Remove reviewer"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:261
+msgid "Type name of reviewer to add"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:269
+msgid "Potential Reviewers"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:272
+msgid "Click to add the repository owner as reviewer:"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:295
+msgid "Save Changes"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#, fuzzy
+msgid "Save Updates as New Pull Request"
+msgstr "Ένα νέο αίτημα έλξης (pull request) δημιουργήθηκε επιτυχώς"
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:297
+msgid "Cancel Changes"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:307
+msgid "Pull Request Content"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:6
+#, python-format
+msgid "%s Pull Requests"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:11
+#, python-format
+msgid "Pull Requests from '%s'"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:13
+#, python-format
+msgid "Pull Requests to '%s'"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:32
+msgid "Open New Pull Request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:37
+#, python-format
+msgid "Show Pull Requests to %s"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:39
+#, python-format
+msgid "Show Pull Requests from '%s'"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:49
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:28
+msgid "Hide closed pull requests (only show open pull requests)"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:51
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:30
+msgid "Show closed pull requests (in addition to open pull requests)"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:35
+msgid "Pull Requests Created by Me"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:38
+msgid "Pull Requests I Participate In"
+msgstr ""
+
+#: kallithea/templates/search/search.html:6
+#, python-format
+msgid "%s Search"
+msgstr ""
+
+#: kallithea/templates/search/search.html:8
+#: kallithea/templates/search/search.html:16
+msgid "Search in All Repositories"
+msgstr ""
+
+#: kallithea/templates/search/search.html:50
+msgid "Search term"
+msgstr ""
+
+#: kallithea/templates/search/search.html:62
+msgid "Search in"
+msgstr ""
+
+#: kallithea/templates/search/search.html:65
+msgid "File contents"
+msgstr ""
+
+#: kallithea/templates/search/search.html:66
+msgid "Commit messages"
+msgstr ""
+
+#: kallithea/templates/search/search.html:67
+msgid "File names"
+msgstr ""
+
+#: kallithea/templates/search/search_commit.html:35
+#: kallithea/templates/search/search_content.html:21
+#: kallithea/templates/search/search_path.html:15
+msgid "Permission denied"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:4
+#, python-format
+msgid "%s Statistics"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:16
+#: kallithea/templates/summary/summary.html:39
+#, python-format
+msgid "%s ATOM feed"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:17
+#: kallithea/templates/summary/summary.html:40
+#, python-format
+msgid "%s RSS feed"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:36
+#: kallithea/templates/summary/summary.html:100
+#: kallithea/templates/summary/summary.html:116
+msgid "Enable"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:39
+msgid "Stats gathered: "
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:89
+#: kallithea/templates/summary/summary.html:349
+msgid "files"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:113
+#: kallithea/templates/summary/summary.html:373
+msgid "Show more"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:390
+msgid "commits"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:391
+msgid "files added"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:392
+msgid "files changed"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:393
+msgid "files removed"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:395
+msgid "commit"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:396
+msgid "file added"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:397
+msgid "file changed"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:398
+msgid "file removed"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:4
+#, python-format
+msgid "%s Summary"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:13
+#, python-format
+msgid "Repository locked by %s"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:15
+msgid "Repository unlocked"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:22
+msgid "Fork of"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:29
+msgid "Clone from"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:72
+msgid "Clone URL"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:78
+msgid "Show by Name"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:79
+msgid "Show by ID"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:92
+msgid "Trending files"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:108
+msgid "Download"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:112
+msgid "There are no downloads yet"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:114
+msgid "Downloads are disabled for this repository"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:120
+msgid "Download as zip"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:125
+msgid "Check this to download archive with subrepos"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:125
+msgid "With subrepos"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:156
+msgid "Repository Size"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:163
+#: kallithea/templates/summary/summary.html:165
+msgid "Feed"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:186
+msgid "Latest Changes"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:188
+msgid "Quick Start"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:202
+#, python-format
+msgid "Readme file from revision %s:%s"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:293
+#, python-format
+msgid "Download %s as %s"
+msgstr ""
+
+#: kallithea/templates/tags/tags.html:5
+#, python-format
+msgid "%s Tags"
+msgstr ""
+
+#: kallithea/templates/tags/tags.html:26
+msgid "Compare Tags"
+msgstr ""
+
+#~ msgid ""
+#~ msgstr ""
+
+#~ msgid "This pull request can be updated with changes on %s:"
+#~ msgstr "Αυτό το αίτημα έλξης μπορεί να ενημερωθεί με αλλαγές στο %s:"
+
+#~ msgid "Non-admins can can fork repositories"
+#~ msgstr ""
+
+#~ msgid "Confirm to invalidate repository cache."
+#~ msgstr ""
+
+#~ msgid "Commenting on line {1}."
+#~ msgstr ""
+
+#~ msgid "Comments parsed using %s syntax with %s support."
+#~ msgstr ""
+
+#~ msgid "Use @username inside this text to notify another user"
+#~ msgstr ""
+
+#~ msgid "Comment preview"
+#~ msgstr ""
+
+#~ msgid "Preview"
+#~ msgstr ""
+
+#~ msgid "Use @username inside this text to notify another user."
+#~ msgstr ""
+
+#~ msgid "New file mode"
+#~ msgstr ""
+
+#~ msgid "File is too big to display"
+#~ msgstr ""
+
+#~ msgid "Save as New Pull Request"
+#~ msgstr ""
+
+#~ msgid "Pull Requests from %s'"
+#~ msgstr ""
+
+#~ msgid ""
+#~ "Changeset status: %s\n"
+#~ "Click to open associated pull request %s"
+#~ msgstr ""
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/i18n/es/LC_MESSAGES/kallithea.po	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,5814 @@
+# Translations template for Kallithea.
+# Copyright (C) 2016 Various authors, licensing as GPLv3
+# This file is distributed under the same license as the Kallithea project.
+# FIRST AUTHOR <EMAIL@ADDRESS>, 2016.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: Kallithea 0.3\n"
+"Report-Msgid-Bugs-To: translations@kallithea-scm.org\n"
+"POT-Creation-Date: 2016-02-22 19:35+0100\n"
+"PO-Revision-Date: 2016-03-08 09:09+0000\n"
+"Last-Translator: Oscar Curero <oscar@naiandei.net>\n"
+"Language-Team: Spanish "
+"<https://hosted.weblate.org/projects/kallithea/stable/es/>\n"
+"Language: es\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+"X-Generator: Weblate 2.5-dev\n"
+
+#: kallithea/controllers/changelog.py:85
+#: kallithea/controllers/pullrequests.py:237 kallithea/lib/base.py:515
+msgid "There are no changesets yet"
+msgstr "Aún no hay cambios"
+
+#: kallithea/controllers/changelog.py:164
+#: kallithea/controllers/admin/permissions.py:61
+#: kallithea/controllers/admin/permissions.py:65
+#: kallithea/controllers/admin/permissions.py:69
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:7
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:104
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:8
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:7
+#: kallithea/templates/base/perms_summary.html:14
+msgid "None"
+msgstr "Ninguno"
+
+#: kallithea/controllers/changelog.py:167 kallithea/controllers/files.py:197
+msgid "(closed)"
+msgstr "(cerrado)"
+
+#: kallithea/controllers/changeset.py:88
+msgid "Show whitespace"
+msgstr "Mostrar espacios en blanco"
+
+#: kallithea/controllers/changeset.py:95 kallithea/controllers/changeset.py:102
+#: kallithea/templates/files/diff_2way.html:55
+msgid "Ignore whitespace"
+msgstr "Ignorar espacios en blanco"
+
+#: kallithea/controllers/changeset.py:168
+#, python-format
+msgid "Increase diff context to %(num)s lines"
+msgstr "Aumentar el contexto del diff a %(num)s lineas"
+
+#: kallithea/controllers/changeset.py:233 kallithea/controllers/files.py:96
+#: kallithea/controllers/files.py:116 kallithea/controllers/files.py:743
+#, fuzzy
+msgid "Such revision does not exist for this repository"
+msgstr "La revisión no existe en este repositorio"
+
+#: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:41
+msgid "Select changeset"
+msgstr "Seleccionar cambios"
+
+#: kallithea/controllers/compare.py:261
+msgid "Cannot compare repositories without using common ancestor"
+msgstr "No se pueden comparar repositorios sin usar un ancestro común"
+
+#: kallithea/controllers/error.py:71
+msgid "No response"
+msgstr "No hay respuesta"
+
+#: kallithea/controllers/error.py:72
+msgid "Unknown error"
+msgstr "Error desconocido"
+
+#: kallithea/controllers/error.py:100
+msgid "The request could not be understood by the server due to malformed syntax."
+msgstr ""
+"La petición no ha podido ser atendida por el servidor debido un error de "
+"sintaxis."
+
+#: kallithea/controllers/error.py:103
+msgid "Unauthorized access to resource"
+msgstr "Acceso no autorizado al recurso"
+
+#: kallithea/controllers/error.py:105
+msgid "You don't have permission to view this page"
+msgstr "No tiene permiso para ver esta página"
+
+#: kallithea/controllers/error.py:107
+msgid "The resource could not be found"
+msgstr "No se ha encontrado el recurso"
+
+#: kallithea/controllers/error.py:109
+msgid "The server encountered an unexpected condition which prevented it from fulfilling the request."
+msgstr ""
+"La petición no se ha podido completar debido a que el servidor encontró un "
+"problema inesperado."
+
+#: kallithea/controllers/feed.py:55
+#, fuzzy, python-format
+msgid "Changes on %s repository"
+msgstr "Cambios en %s repositorio"
+
+#: kallithea/controllers/feed.py:56
+#, python-format
+msgid "%s %s feed"
+msgstr "%s%s canal"
+
+#: kallithea/controllers/feed.py:87
+#: kallithea/templates/changeset/changeset.html:182
+#: kallithea/templates/changeset/changeset.html:195
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
+msgid "Changeset was too big and was cut off..."
+msgstr "El cambio era demasiado grande y se redució..."
+
+#: kallithea/controllers/feed.py:91
+#, python-format
+msgid "%s committed on %s"
+msgstr "%s anotó en %s"
+
+#: kallithea/controllers/files.py:91
+msgid "Click here to add new file"
+msgstr "Haga clic aquí para añadir un archivo nuevo"
+
+#: kallithea/controllers/files.py:92
+#, python-format
+msgid "There are no files yet. %s"
+msgstr "Aún no hay archivos. %s"
+
+#: kallithea/controllers/files.py:194
+#, python-format
+msgid "%s at %s"
+msgstr "%s en %s"
+
+#: kallithea/controllers/files.py:306 kallithea/controllers/files.py:366
+#: kallithea/controllers/files.py:433
+#, python-format
+msgid "This repository has been locked by %s on %s"
+msgstr "Este repositorio ha sido bloqueado por %s en %s"
+
+#: kallithea/controllers/files.py:318
+msgid "You can only delete files with revision being a valid branch"
+msgstr "Sólo puede borrar archivos si la revisión pertenece a una rama válida"
+
+#: kallithea/controllers/files.py:329
+#, python-format
+msgid "Deleted file %s via Kallithea"
+msgstr "Archivo %s eliminado mediante Kallithea"
+
+#: kallithea/controllers/files.py:351
+#, python-format
+msgid "Successfully deleted file %s"
+msgstr "El archivo %s se eliminó correctamente"
+
+#: kallithea/controllers/files.py:355 kallithea/controllers/files.py:421
+#: kallithea/controllers/files.py:502
+msgid "Error occurred during commit"
+msgstr "Ocurrió un error al anotar los cambios"
+
+#: kallithea/controllers/files.py:378
+msgid "You can only edit files with revision being a valid branch"
+msgstr "Sólo puede editar archivos si la revisión pertenece a una rama válida"
+
+#: kallithea/controllers/files.py:392
+#, python-format
+msgid "Edited file %s via Kallithea"
+msgstr "Archivo %s editado mediante Kallithea"
+
+#: kallithea/controllers/files.py:408
+msgid "No changes"
+msgstr "No hay cambios"
+
+#: kallithea/controllers/files.py:417 kallithea/controllers/files.py:491
+#, python-format
+msgid "Successfully committed to %s"
+msgstr "Anotado correctamente a %s"
+
+#: kallithea/controllers/files.py:444
+msgid "Added file via Kallithea"
+msgstr "Archivo añadido mediante Kallithea"
+
+#: kallithea/controllers/files.py:465
+msgid "No content"
+msgstr "Sin contenido"
+
+#: kallithea/controllers/files.py:469
+msgid "No filename"
+msgstr "Sin nombre de archivo"
+
+#: kallithea/controllers/files.py:494
+#, fuzzy
+msgid "Location must be relative path and must not contain .. in path"
+msgstr "La ruta debe ser relativa y no debe contener .. en la ruta"
+
+#: kallithea/controllers/files.py:527
+msgid "Downloads disabled"
+msgstr "Descargas deshabilitadas"
+
+#: kallithea/controllers/files.py:538
+#, python-format
+msgid "Unknown revision %s"
+msgstr "Revisión desconocida %s"
+
+#: kallithea/controllers/files.py:540
+msgid "Empty repository"
+msgstr "Repositorio vacío"
+
+#: kallithea/controllers/files.py:542
+msgid "Unknown archive type"
+msgstr "Tipo de archivo desconocido"
+
+#: kallithea/controllers/files.py:772
+#: kallithea/templates/changeset/changeset_range.html:9
+#: kallithea/templates/email_templates/pull_request.html:15
+#: kallithea/templates/pullrequests/pullrequest.html:97
+msgid "Changesets"
+msgstr "Cambios"
+
+#: kallithea/controllers/files.py:773 kallithea/controllers/pullrequests.py:175
+#: kallithea/model/scm.py:820 kallithea/templates/switch_to_list.html:3
+#: kallithea/templates/branches/branches.html:10
+msgid "Branches"
+msgstr "Ramas"
+
+#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:176
+#: kallithea/model/scm.py:831 kallithea/templates/switch_to_list.html:25
+#: kallithea/templates/tags/tags.html:10
+msgid "Tags"
+msgstr "Etiquetas"
+
+#: kallithea/controllers/forks.py:186
+#, python-format
+msgid "An error occurred during repository forking %s"
+msgstr "Ocurrió un error mientras se bifurcaba el repositorio %s"
+
+#: kallithea/controllers/home.py:84
+msgid "Groups"
+msgstr "Grupos"
+
+#: kallithea/controllers/home.py:89
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:106
+#: kallithea/templates/admin/repos/repo_add.html:12
+#: kallithea/templates/admin/repos/repo_add.html:16
+#: kallithea/templates/admin/repos/repos.html:9
+#: kallithea/templates/admin/users/user_edit_advanced.html:6
+#: kallithea/templates/base/base.html:60 kallithea/templates/base/base.html:77
+#: kallithea/templates/base/base.html:124
+#: kallithea/templates/base/base.html:479
+#: kallithea/templates/base/base.html:653
+msgid "Repositories"
+msgstr "Repositorios"
+
+#: kallithea/controllers/home.py:130
+#: kallithea/templates/files/files_add.html:32
+#: kallithea/templates/files/files_delete.html:23
+#: kallithea/templates/files/files_edit.html:32
+msgid "Branch"
+msgstr "Rama"
+
+#: kallithea/controllers/home.py:136 kallithea/templates/switch_to_list.html:16
+msgid "Closed Branches"
+msgstr "Ramas cerradas"
+
+#: kallithea/controllers/home.py:142
+msgid "Tag"
+msgstr "Etiqueta"
+
+#: kallithea/controllers/home.py:148
+msgid "Bookmark"
+msgstr "Marcador"
+
+#: kallithea/controllers/journal.py:111 kallithea/controllers/journal.py:153
+#: kallithea/templates/journal/public_journal.html:4
+#: kallithea/templates/journal/public_journal.html:21
+msgid "Public Journal"
+msgstr "Registro público"
+
+#: kallithea/controllers/journal.py:115 kallithea/controllers/journal.py:157
+#: kallithea/templates/base/base.html:306
+#: kallithea/templates/journal/journal.html:4
+#: kallithea/templates/journal/journal.html:12
+msgid "Journal"
+msgstr "Registro"
+
+#: kallithea/controllers/login.py:144 kallithea/controllers/login.py:190
+msgid "Bad captcha"
+msgstr "CAPTCHA erróneo"
+
+#: kallithea/controllers/login.py:150
+msgid "You have successfully registered with %s"
+msgstr "El registro en %s se ha efectuado correctamente"
+
+#: kallithea/controllers/login.py:195
+msgid "A password reset confirmation code has been sent"
+msgstr "Se ha enviado una confirmación de restauración de contraseña"
+
+#: kallithea/controllers/login.py:244
+msgid "Invalid password reset token"
+msgstr "Señal de restauración de contraseña inválida"
+
+#: kallithea/controllers/login.py:249
+#: kallithea/controllers/admin/my_account.py:167
+msgid "Successfully updated password"
+msgstr "Contraseña actualizada correctamente"
+
+#: kallithea/controllers/pullrequests.py:123
+#, python-format
+msgid "%s (closed)"
+msgstr "%s (cerrado)"
+
+#: kallithea/controllers/pullrequests.py:151
+#: kallithea/templates/changeset/changeset.html:12
+#: kallithea/templates/email_templates/changeset_comment.html:17
+msgid "Changeset"
+msgstr "Cambio"
+
+#: kallithea/controllers/pullrequests.py:172
+msgid "Special"
+msgstr "Especial"
+
+#: kallithea/controllers/pullrequests.py:173
+#, fuzzy
+msgid "Peer branches"
+msgstr "Ramas de los pares"
+
+#: kallithea/controllers/pullrequests.py:174 kallithea/model/scm.py:826
+#: kallithea/templates/switch_to_list.html:38
+#: kallithea/templates/bookmarks/bookmarks.html:10
+msgid "Bookmarks"
+msgstr "Marcadores"
+
+#: kallithea/controllers/pullrequests.py:309
+#, python-format
+msgid "Error creating pull request: %s"
+msgstr "Error al crear la petición de pull: %s"
+
+#: kallithea/controllers/pullrequests.py:355
+#: kallithea/controllers/pullrequests.py:502
+msgid "No description"
+msgstr "No hay descripción"
+
+#: kallithea/controllers/pullrequests.py:362
+msgid "Successfully opened new pull request"
+msgstr "La petición de pull se ha creado correctamente"
+
+#: kallithea/controllers/pullrequests.py:365
+#: kallithea/controllers/pullrequests.py:452
+#: kallithea/controllers/pullrequests.py:509
+#, python-format
+msgid "Invalid reviewer \"%s\" specified"
+msgstr "El validador \"%s\" no es correcto"
+
+#: kallithea/controllers/pullrequests.py:368
+#: kallithea/controllers/pullrequests.py:455
+msgid "Error occurred while creating pull request"
+msgstr "Ocurrió un error al crear la petición de pull"
+
+#: kallithea/controllers/pullrequests.py:400
+msgid "Missing changesets since the previous pull request:"
+msgstr "Cambios que faltan desde la ultima petición de pull:"
+
+#: kallithea/controllers/pullrequests.py:407
+#, fuzzy, python-format
+msgid "New changesets on %s %s since the previous pull request:"
+msgstr "Cambios nuevos en %s %s desde la ultima petición pull:"
+
+#: kallithea/controllers/pullrequests.py:414
+msgid "Ancestor didn't change - show diff since previous version:"
+msgstr ""
+"El ascendente no ha cambiado - ver diferencias desde la versión anterior:"
+
+#: kallithea/controllers/pullrequests.py:421
+#, python-format
+msgid "This pull request is based on another %s revision and there is no simple diff."
+msgstr ""
+"La petición de pull está basada en otra %s revisión y no hay un diff simple."
+
+#: kallithea/controllers/pullrequests.py:423
+#, python-format
+msgid "No changes found on %s %s since previous version."
+msgstr "No se encontró ningún cambio en %s %s desde la versión anterior."
+
+#: kallithea/controllers/pullrequests.py:461
+#, python-format
+msgid "Closed, replaced by %s ."
+msgstr "Cerrado, reemplazado por %s."
+
+#: kallithea/controllers/pullrequests.py:469
+msgid "Pull request update created"
+msgstr "Actualización de la petición pull creada"
+
+#: kallithea/controllers/pullrequests.py:513
+msgid "Pull request updated"
+msgstr "Petición pull actualizada"
+
+#: kallithea/controllers/pullrequests.py:528
+msgid "Successfully deleted pull request"
+msgstr "Petición pull eliminada correctamente"
+
+#: kallithea/controllers/pullrequests.py:594
+#, python-format
+msgid "This pull request has already been merged to %s."
+msgstr "La petición pull ya ha sido incluida a %s."
+
+#: kallithea/controllers/pullrequests.py:596
+msgid "This pull request has been closed and can not be updated."
+msgstr "La petición pull esta cerrada y no se puede actualizar."
+
+#: kallithea/controllers/pullrequests.py:614
+#, python-format
+msgid "The following changes are available on %s:"
+msgstr "Los siguientes cambios están disponibles en %s:"
+
+#: kallithea/controllers/pullrequests.py:618
+msgid "No changesets found for updating this pull request."
+msgstr "No se encontraron cambios para actualizar la petición pull."
+
+#: kallithea/controllers/pullrequests.py:626
+#, fuzzy, python-format
+msgid "Note: Branch %s has another head: %s."
+msgstr "Nota: la rama %s tiene otro head: %s."
+
+#: kallithea/controllers/pullrequests.py:632
+msgid "Git pull requests don't support updates yet."
+msgstr "La peticiones pull de Git aún no soportan actualizaciones."
+
+#: kallithea/controllers/pullrequests.py:724
+msgid "No permission to change pull request status"
+msgstr "No tene permiso para cambiar el estado de la petición pull"
+
+#: kallithea/controllers/pullrequests.py:735
+#, python-format
+msgid "Successfully deleted pull request %s"
+msgstr "Petición de pull %s eliminada correctamente"
+
+#: kallithea/controllers/pullrequests.py:745
+msgid "Closing."
+msgstr "Cerrado."
+
+#: kallithea/controllers/search.py:135
+msgid "Invalid search query. Try quoting it."
+msgstr "Consulta de búsqueda inválida. Inténtelo entre comillas."
+
+#: kallithea/controllers/search.py:140
+msgid "There is no index to search in. Please run whoosh indexer"
+msgstr ""
+"No hay ningún indice para buscar. Por favor, ejecute el indexador whoosh"
+
+#: kallithea/controllers/search.py:144
+msgid "An error occurred during search operation."
+msgstr "Ocurrió un error mientras se ejecutaba la búsqueda."
+
+#: kallithea/controllers/summary.py:181
+#: kallithea/templates/summary/summary.html:384
+msgid "No data ready yet"
+msgstr "Todavía no hay datos disponibles"
+
+#: kallithea/controllers/summary.py:184
+#: kallithea/templates/summary/summary.html:98
+msgid "Statistics are disabled for this repository"
+msgstr "Las estadísticas están deshabilitadas en este repositorio"
+
+#: kallithea/controllers/admin/auth_settings.py:135
+msgid "Auth settings updated successfully"
+msgstr "Los ajustes de autentificación se han actualizado correctamente"
+
+#: kallithea/controllers/admin/auth_settings.py:146
+msgid "error occurred during update of auth settings"
+msgstr "ocurrió un error al actualizar los ajustes de autentificación"
+
+#: kallithea/controllers/admin/defaults.py:97
+msgid "Default settings updated successfully"
+msgstr "Los ajustes predeterminados se han actualizado correctamente"
+
+#: kallithea/controllers/admin/defaults.py:112
+msgid "Error occurred during update of defaults"
+msgstr "Ocurrió un error al actualizar los ajustes predeterminados"
+
+#: kallithea/controllers/admin/gists.py:58
+#: kallithea/controllers/admin/my_account.py:243
+#: kallithea/controllers/admin/users.py:284
+msgid "Forever"
+msgstr "Para siempre"
+
+#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/my_account.py:244
+#: kallithea/controllers/admin/users.py:285
+msgid "5 minutes"
+msgstr "5 minutos"
+
+#: kallithea/controllers/admin/gists.py:60
+#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/users.py:286
+msgid "1 hour"
+msgstr "1 hora"
+
+#: kallithea/controllers/admin/gists.py:61
+#: kallithea/controllers/admin/my_account.py:246
+#: kallithea/controllers/admin/users.py:287
+msgid "1 day"
+msgstr "1 día"
+
+#: kallithea/controllers/admin/gists.py:62
+#: kallithea/controllers/admin/my_account.py:247
+#: kallithea/controllers/admin/users.py:288
+msgid "1 month"
+msgstr "1 mes"
+
+#: kallithea/controllers/admin/gists.py:66
+#: kallithea/controllers/admin/my_account.py:249
+#: kallithea/controllers/admin/users.py:290
+msgid "Lifetime"
+msgstr "Tiempo de vida"
+
+#: kallithea/controllers/admin/gists.py:145
+msgid "Error occurred during gist creation"
+msgstr "Ocurrió un error mientras se creaba el gist"
+
+#: kallithea/controllers/admin/gists.py:183
+#, python-format
+msgid "Deleted gist %s"
+msgstr "Gist %s eliminado"
+
+#: kallithea/controllers/admin/gists.py:232
+msgid "Unmodified"
+msgstr "Sin modificar"
+
+#: kallithea/controllers/admin/gists.py:261
+msgid "Successfully updated gist content"
+msgstr "Gist actualizado correctamente"
+
+#: kallithea/controllers/admin/gists.py:266
+msgid "Successfully updated gist data"
+msgstr ""
+
+#: kallithea/controllers/admin/gists.py:269
+#, python-format
+msgid "Error occurred during update of gist %s"
+msgstr ""
+
+#: kallithea/controllers/admin/my_account.py:70 kallithea/model/user.py:215
+#: kallithea/model/user.py:237
+msgid "You can't edit this user since it's crucial for entire application"
+msgstr ""
+
+#: kallithea/controllers/admin/my_account.py:129
+msgid "Your account was updated successfully"
+msgstr ""
+
+#: kallithea/controllers/admin/my_account.py:144
+#: kallithea/controllers/admin/users.py:201
+#, python-format
+msgid "Error occurred during update of user %s"
+msgstr ""
+
+#: kallithea/controllers/admin/my_account.py:178
+msgid "Error occurred during update of user password"
+msgstr ""
+
+#: kallithea/controllers/admin/my_account.py:220
+#: kallithea/controllers/admin/users.py:414
+#, python-format
+msgid "Added email %s to user"
+msgstr ""
+
+#: kallithea/controllers/admin/my_account.py:226
+#: kallithea/controllers/admin/users.py:420
+msgid "An error occurred during email saving"
+msgstr ""
+
+#: kallithea/controllers/admin/my_account.py:235
+#: kallithea/controllers/admin/users.py:432
+msgid "Removed email from user"
+msgstr ""
+
+#: kallithea/controllers/admin/my_account.py:259
+#: kallithea/controllers/admin/users.py:307
+msgid "API key successfully created"
+msgstr ""
+
+#: kallithea/controllers/admin/my_account.py:271
+#: kallithea/controllers/admin/users.py:320
+msgid "API key successfully reset"
+msgstr ""
+
+#: kallithea/controllers/admin/my_account.py:275
+#: kallithea/controllers/admin/users.py:324
+msgid "API key successfully deleted"
+msgstr ""
+
+#: kallithea/controllers/admin/permissions.py:62
+#: kallithea/controllers/admin/permissions.py:66
+#: kallithea/controllers/admin/permissions.py:70
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:8
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:9
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:8
+#: kallithea/templates/base/perms_summary.html:15
+msgid "Read"
+msgstr ""
+
+#: kallithea/controllers/admin/permissions.py:63
+#: kallithea/controllers/admin/permissions.py:67
+#: kallithea/controllers/admin/permissions.py:71
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:9
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:10
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:9
+#: kallithea/templates/base/perms_summary.html:16
+msgid "Write"
+msgstr ""
+
+#: kallithea/controllers/admin/permissions.py:64
+#: kallithea/controllers/admin/permissions.py:68
+#: kallithea/controllers/admin/permissions.py:72
+#: kallithea/templates/admin/auth/auth_settings.html:9
+#: kallithea/templates/admin/defaults/defaults.html:9
+#: kallithea/templates/admin/permissions/permissions.html:9
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:9
+#: kallithea/templates/admin/repo_groups/repo_group_edit.html:9
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:10
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:47
+#: kallithea/templates/admin/repo_groups/repo_groups.html:10
+#: kallithea/templates/admin/repos/repo_add.html:10
+#: kallithea/templates/admin/repos/repo_add.html:14
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:11
+#: kallithea/templates/admin/repos/repos.html:9
+#: kallithea/templates/admin/settings/settings.html:9
+#: kallithea/templates/admin/user_groups/user_group_add.html:8
+#: kallithea/templates/admin/user_groups/user_group_edit.html:9
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:10
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:47
+#: kallithea/templates/admin/user_groups/user_groups.html:10
+#: kallithea/templates/admin/users/user_add.html:8
+#: kallithea/templates/admin/users/user_edit.html:9
+#: kallithea/templates/admin/users/user_edit_profile.html:105
+#: kallithea/templates/admin/users/users.html:10
+#: kallithea/templates/admin/users/users.html:55
+#: kallithea/templates/base/base.html:336
+#: kallithea/templates/base/base.html:337
+#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:344
+#: kallithea/templates/base/perms_summary.html:17
+msgid "Admin"
+msgstr ""
+
+#: kallithea/controllers/admin/permissions.py:75
+#: kallithea/controllers/admin/permissions.py:86
+#: kallithea/controllers/admin/permissions.py:91
+#: kallithea/controllers/admin/permissions.py:94
+#: kallithea/controllers/admin/permissions.py:97
+#: kallithea/controllers/admin/permissions.py:100
+#: kallithea/templates/admin/auth/auth_settings.html:40
+msgid "Disabled"
+msgstr ""
+
+#: kallithea/controllers/admin/permissions.py:77
+msgid "Allowed with manual account activation"
+msgstr ""
+
+#: kallithea/controllers/admin/permissions.py:79
+msgid "Allowed with automatic account activation"
+msgstr ""
+
+#: kallithea/controllers/admin/permissions.py:82
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1439
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1485
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1542
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1543
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1564
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1603
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1655
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1707
+msgid "Manual activation of external account"
+msgstr ""
+
+#: kallithea/controllers/admin/permissions.py:83
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1440
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1486
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1543
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1544
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1565
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1604
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1656
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1708
+msgid "Automatic activation of external account"
+msgstr ""
+
+#: kallithea/controllers/admin/permissions.py:87
+#: kallithea/controllers/admin/permissions.py:90
+#: kallithea/controllers/admin/permissions.py:95
+#: kallithea/controllers/admin/permissions.py:98
+#: kallithea/controllers/admin/permissions.py:101
+#: kallithea/templates/admin/auth/auth_settings.html:40
+msgid "Enabled"
+msgstr ""
+
+#: kallithea/controllers/admin/permissions.py:124
+msgid "Global permissions updated successfully"
+msgstr ""
+
+#: kallithea/controllers/admin/permissions.py:139
+msgid "Error occurred during update of permissions"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:187
+#, python-format
+msgid "Error occurred during creation of repository group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:192
+#, python-format
+msgid "Created repository group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:249
+#, python-format
+msgid "Updated repository group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:265
+#, python-format
+msgid "Error occurred during update of repository group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:283
+#, python-format
+msgid "This group contains %s repositories and cannot be deleted"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:290
+#, python-format
+msgid "This group contains %s subgroups and cannot be deleted"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:296
+#, python-format
+msgid "Removed repository group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:301
+#, python-format
+msgid "Error occurred during deletion of repository group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:404
+#: kallithea/controllers/admin/repo_groups.py:439
+#: kallithea/controllers/admin/user_groups.py:340
+msgid "Cannot revoke permission for yourself as admin"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:419
+msgid "Repository group permissions updated"
+msgstr ""
+
+#: kallithea/controllers/admin/repo_groups.py:456
+#: kallithea/controllers/admin/repos.py:397
+#: kallithea/controllers/admin/user_groups.py:352
+msgid "An error occurred during revoking of permission"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:151
+#, python-format
+msgid "Error creating repository %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:212
+#, python-format
+msgid "Created repository %s from %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:221
+#, python-format
+msgid "Forked repository %s as %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:224
+#, python-format
+msgid "Created repository %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:261
+#, python-format
+msgid "Repository %s updated successfully"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:282
+#, python-format
+msgid "Error occurred during update of repository %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:309
+#, python-format
+msgid "Detached %s forks"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:312
+#, python-format
+msgid "Deleted %s forks"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:317
+#, python-format
+msgid "Deleted repository %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:320
+#, python-format
+msgid "Cannot delete repository %s which still has forks"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:325
+#, python-format
+msgid "An error occurred during deletion of %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:373
+msgid "Repository permissions updated"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:429
+msgid "An error occurred during creation of field"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:443
+msgid "An error occurred during removal of field"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:459
+msgid "-- Not a fork --"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:490
+msgid "Updated repository visibility in public journal"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:494
+msgid "An error occurred during setting this repository in public journal"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:511
+msgid "Nothing"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:513
+#, python-format
+msgid "Marked repository %s as fork of %s"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:520
+msgid "An error occurred during this operation"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:536
+#: kallithea/controllers/admin/repos.py:563
+msgid "Repository has been locked"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:539
+#: kallithea/controllers/admin/repos.py:560
+msgid "Repository has been unlocked"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:542
+#: kallithea/controllers/admin/repos.py:567
+msgid "An error occurred during unlocking"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:581
+msgid "Cache invalidation successful"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:585
+msgid "An error occurred during cache invalidation"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:600
+msgid "Pulled from remote location"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:603
+msgid "An error occurred during pull from remote location"
+msgstr ""
+
+#: kallithea/controllers/admin/repos.py:636
+msgid "An error occurred during deletion of repository stats"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:141
+msgid "Updated VCS settings"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:145
+msgid "Unable to activate hgsubversion support. The \"hgsubversion\" library is missing"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:151
+#: kallithea/controllers/admin/settings.py:248
+msgid "Error occurred while updating application settings"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:187
+#, python-format
+msgid "Repositories successfully rescanned. Added: %s. Removed: %s."
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:244
+msgid "Updated application settings"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:301
+msgid "Updated visualisation settings"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:306
+msgid "Error occurred during updating visualisation settings"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:332
+msgid "Please enter email address"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:347
+msgid "Send email task created"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:378
+msgid "Added new hook"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:392
+msgid "Updated hooks"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:396
+msgid "Error occurred during hook creation"
+msgstr ""
+
+#: kallithea/controllers/admin/settings.py:422
+msgid "Whoosh reindex task scheduled"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:150
+#, python-format
+msgid "Created user group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:163
+#, python-format
+msgid "Error occurred during creation of user group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:201
+#, python-format
+msgid "Updated user group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:224
+#, python-format
+msgid "Error occurred during update of user group %s"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:242
+msgid "Successfully deleted user group"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:247
+msgid "An error occurred during deletion of user group"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:314
+msgid "Target group cannot be the same"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:320
+msgid "User group permissions updated"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:440
+#: kallithea/controllers/admin/users.py:383
+msgid "Updated permissions"
+msgstr ""
+
+#: kallithea/controllers/admin/user_groups.py:444
+#: kallithea/controllers/admin/users.py:387
+msgid "An error occurred during permissions saving"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:133
+#, python-format
+msgid "Created user %s"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:148
+#, python-format
+msgid "Error occurred during creation of user %s"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:181
+msgid "User updated successfully"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:217
+msgid "Successfully deleted user"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:222
+msgid "An error occurred during deletion of user"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:235
+msgid "The default user cannot be edited"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:462
+#, python-format
+msgid "Added IP address %s to user whitelist"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:468
+msgid "An error occurred while adding IP address"
+msgstr ""
+
+#: kallithea/controllers/admin/users.py:482
+msgid "Removed IP address from user whitelist"
+msgstr ""
+
+#: kallithea/lib/auth.py:737
+#, python-format
+msgid "IP %s not allowed"
+msgstr ""
+
+#: kallithea/lib/auth.py:750
+msgid "Invalid API key"
+msgstr ""
+
+#: kallithea/lib/auth.py:768
+msgid "CSRF token leak has been detected - all form tokens have been expired"
+msgstr ""
+
+#: kallithea/lib/auth.py:813
+msgid "You need to be a registered user to perform this action"
+msgstr ""
+
+#: kallithea/lib/auth.py:843
+msgid "You need to be signed in to view this page"
+msgstr ""
+
+#: kallithea/lib/base.py:493
+msgid "Repository not found in the filesystem"
+msgstr ""
+
+#: kallithea/lib/base.py:519 kallithea/lib/helpers.py:618
+msgid "Changeset not found"
+msgstr ""
+
+#: kallithea/lib/diffs.py:66
+msgid "Binary file"
+msgstr ""
+
+#: kallithea/lib/diffs.py:82
+msgid "Changeset was too big and was cut off, use diff menu to display this diff"
+msgstr ""
+
+#: kallithea/lib/diffs.py:92
+msgid "No changes detected"
+msgstr ""
+
+#: kallithea/lib/helpers.py:605
+#, python-format
+msgid "Deleted branch: %s"
+msgstr ""
+
+#: kallithea/lib/helpers.py:607
+#, python-format
+msgid "Created tag: %s"
+msgstr ""
+
+#: kallithea/lib/helpers.py:667
+#, python-format
+msgid "Show all combined changesets %s->%s"
+msgstr ""
+
+#: kallithea/lib/helpers.py:673
+msgid "Compare view"
+msgstr ""
+
+#: kallithea/lib/helpers.py:692
+msgid "and"
+msgstr ""
+
+#: kallithea/lib/helpers.py:693
+#, python-format
+msgid "%s more"
+msgstr ""
+
+#: kallithea/lib/helpers.py:694 kallithea/templates/changelog/changelog.html:44
+msgid "revisions"
+msgstr ""
+
+#: kallithea/lib/helpers.py:718
+#, python-format
+msgid "Fork name %s"
+msgstr ""
+
+#: kallithea/lib/helpers.py:738
+#, python-format
+msgid "Pull request %s"
+msgstr ""
+
+#: kallithea/lib/helpers.py:748
+msgid "[deleted] repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:750 kallithea/lib/helpers.py:762
+msgid "[created] repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:752
+msgid "[created] repository as fork"
+msgstr ""
+
+#: kallithea/lib/helpers.py:754 kallithea/lib/helpers.py:764
+msgid "[forked] repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:756 kallithea/lib/helpers.py:766
+msgid "[updated] repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:758
+msgid "[downloaded] archive from repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:760
+msgid "[delete] repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:768
+msgid "[created] user"
+msgstr ""
+
+#: kallithea/lib/helpers.py:770
+msgid "[updated] user"
+msgstr ""
+
+#: kallithea/lib/helpers.py:772
+msgid "[created] user group"
+msgstr ""
+
+#: kallithea/lib/helpers.py:774
+msgid "[updated] user group"
+msgstr ""
+
+#: kallithea/lib/helpers.py:776
+msgid "[commented] on revision in repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:778
+msgid "[commented] on pull request for"
+msgstr ""
+
+#: kallithea/lib/helpers.py:780
+msgid "[closed] pull request for"
+msgstr ""
+
+#: kallithea/lib/helpers.py:782
+msgid "[pushed] into"
+msgstr ""
+
+#: kallithea/lib/helpers.py:784
+msgid "[committed via Kallithea] into repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:786
+msgid "[pulled from remote] into repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:788
+msgid "[pulled] from"
+msgstr ""
+
+#: kallithea/lib/helpers.py:790
+msgid "[started following] repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:792
+msgid "[stopped following] repository"
+msgstr ""
+
+#: kallithea/lib/helpers.py:1119
+#, python-format
+msgid " and %s more"
+msgstr ""
+
+#: kallithea/lib/helpers.py:1123
+#: kallithea/templates/compare/compare_diff.html:71
+#: kallithea/templates/pullrequests/pullrequest_show.html:337
+msgid "No files"
+msgstr ""
+
+#: kallithea/lib/helpers.py:1189
+msgid "new file"
+msgstr ""
+
+#: kallithea/lib/helpers.py:1192
+msgid "mod"
+msgstr ""
+
+#: kallithea/lib/helpers.py:1195
+msgid "del"
+msgstr ""
+
+#: kallithea/lib/helpers.py:1198
+msgid "rename"
+msgstr ""
+
+#: kallithea/lib/helpers.py:1203
+msgid "chmod"
+msgstr ""
+
+#: kallithea/lib/helpers.py:1464
+#, python-format
+msgid "%s repository is not mapped to db perhaps it was created or renamed from the filesystem please run the application again in order to rescan repositories"
+msgstr ""
+
+#: kallithea/lib/utils2.py:434
+#, python-format
+msgid "%d year"
+msgid_plural "%d years"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/lib/utils2.py:435
+#, python-format
+msgid "%d month"
+msgid_plural "%d months"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/lib/utils2.py:436
+#, python-format
+msgid "%d day"
+msgid_plural "%d days"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/lib/utils2.py:437
+#, python-format
+msgid "%d hour"
+msgid_plural "%d hours"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/lib/utils2.py:438
+#, python-format
+msgid "%d minute"
+msgid_plural "%d minutes"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/lib/utils2.py:439
+#, python-format
+msgid "%d second"
+msgid_plural "%d seconds"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/lib/utils2.py:455
+#, python-format
+msgid "in %s"
+msgstr ""
+
+#: kallithea/lib/utils2.py:457
+#, python-format
+msgid "%s ago"
+msgstr ""
+
+#: kallithea/lib/utils2.py:459
+#, python-format
+msgid "in %s and %s"
+msgstr ""
+
+#: kallithea/lib/utils2.py:462
+#, python-format
+msgid "%s and %s ago"
+msgstr ""
+
+#: kallithea/lib/utils2.py:465
+msgid "just now"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1163
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1182
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1303
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1388
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1408
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1454
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1511
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1512
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1533
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1572
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1622
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1649
+msgid "Repository no access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1164
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1183
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1304
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1389
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1409
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1455
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1512
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1513
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1534
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1573
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1623
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1650
+msgid "Repository read access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1165
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1184
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1305
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1390
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1410
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1456
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1513
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1535
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1574
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1624
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1651
+msgid "Repository write access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1166
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1185
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1306
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1391
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1411
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1457
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1515
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1536
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1575
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1625
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1652
+msgid "Repository admin access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1168
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1187
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1308
+msgid "Repository Group no access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1169
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1188
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1309
+msgid "Repository Group read access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1170
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1189
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1310
+msgid "Repository Group write access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1171
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1190
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1311
+msgid "Repository Group admin access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1173
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1192
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1313
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1398
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1406
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1452
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1509
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1510
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1531
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1570
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1620
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1671
+msgid "Kallithea Administrator"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1174
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1193
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1314
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1399
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1429
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1475
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1532
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1533
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1554
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1593
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1643
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1670
+msgid "Repository creation disabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1175
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1194
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1315
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1400
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1430
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1476
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1533
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1534
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1555
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1594
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1644
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1671
+msgid "Repository creation enabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1176
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1195
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1316
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1401
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1432
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1478
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1535
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1536
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1557
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1596
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1648
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1675
+msgid "Repository forking disabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1177
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1196
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1317
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1402
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1433
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1479
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1536
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1537
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1558
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1597
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1649
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1676
+msgid "Repository forking enabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1178
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1197
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1318
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1403
+msgid "Register disabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1179
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1198
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1319
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1404
+msgid "Register new user with Kallithea with manual activation"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1182
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1201
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1322
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1407
+msgid "Register new user with Kallithea with auto activation"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1623
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1650
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1763
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1838
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1934
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1980
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:2040
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:2041
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2062
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2101
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2154
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2200
+msgid "Not Reviewed"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1624
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1651
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1764
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1839
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1935
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1981
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:2041
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:2042
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2063
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2102
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2155
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2238
+msgid "Approved"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1625
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1652
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1765
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1840
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1936
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1982
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:2042
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:2043
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2064
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2103
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2156
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2239
+msgid "Rejected"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_4_0.py:1626
+#: kallithea/lib/dbmigrate/schema/db_1_5_0.py:1653
+#: kallithea/lib/dbmigrate/schema/db_1_5_2.py:1766
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1841
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1937
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1983
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:2043
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:2044
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2065
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2104
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2157
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2203
+msgid "Under Review"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1252
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1270
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1300
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1357
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1358
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1379
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1418
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1471
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1520
+msgid "top level"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1393
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1413
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1459
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1516
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1517
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1538
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1577
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1627
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1654
+msgid "Repository group no access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1394
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1414
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1460
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1517
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1518
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1539
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1578
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1628
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1655
+msgid "Repository group read access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1395
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1415
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1461
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1518
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1519
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1540
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1579
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1629
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1656
+msgid "Repository group write access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_6_0.py:1396
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1416
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1462
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1519
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1520
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1541
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1580
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1630
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1657
+msgid "Repository group admin access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1418
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1464
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1521
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1522
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1543
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1582
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1632
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1659
+msgid "User group no access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1419
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1465
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1522
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1523
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1544
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1583
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1633
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1660
+msgid "User group read access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1420
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1466
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1523
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1524
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1545
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1584
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1634
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1661
+msgid "User group write access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1421
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1467
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1524
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1525
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1546
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1585
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1635
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1662
+msgid "User group admin access"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1423
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1469
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1526
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1527
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1548
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1587
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1637
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1664
+msgid "Repository Group creation disabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1424
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1470
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1527
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1528
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1549
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1588
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1638
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1665
+msgid "Repository Group creation enabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1426
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1472
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1529
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1530
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1551
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1590
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1640
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1667
+msgid "User Group creation disabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1427
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1473
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1530
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1531
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1552
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1591
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1641
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1668
+msgid "User Group creation enabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1435
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1481
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1538
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1539
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1560
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1599
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1651
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1703
+msgid "Registration disabled"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1436
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1482
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1539
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1540
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1561
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1600
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1652
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1679
+msgid "User Registration with manual account activation"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1437
+#: kallithea/lib/dbmigrate/schema/db_1_8_0.py:1483
+#: kallithea/lib/dbmigrate/schema/db_2_0_0.py:1540
+#: kallithea/lib/dbmigrate/schema/db_2_0_1.py:1541
+#: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1562
+#: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1601
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1653
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1680
+msgid "User Registration with automatic account activation"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1645
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1697
+msgid "Repository creation enabled with write permission to a repository group"
+msgstr ""
+
+#: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1646
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1698
+msgid "Repository creation disabled with write permission to a repository group"
+msgstr ""
+
+#: kallithea/model/comment.py:72
+#, python-format
+msgid "on line %s"
+msgstr ""
+
+#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:170
+msgid "[Mention]"
+msgstr ""
+
+#: kallithea/model/db.py:1673
+msgid "Default user has no access to new repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1674
+msgid "Default user has read access to new repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1675
+msgid "Default user has write access to new repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1676
+msgid "Default user has admin access to new repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1678
+msgid "Default user has no access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1679
+msgid "Default user has read access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1680
+msgid "Default user has write access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1681
+msgid "Default user has admin access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1683
+msgid "Default user has no access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1684
+msgid "Default user has read access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1685
+msgid "Default user has write access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1686
+msgid "Default user has admin access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1688
+msgid "Only admins can create repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1689
+msgid "Non-admins can create repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1691
+msgid "Only admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1692
+msgid "Non-admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1694
+msgid "Only admins can create top level repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1695
+msgid "Non-admins can create top level repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1700
+msgid "Only admins can fork repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1701
+msgid "Non-admins can fork repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1704
+msgid "User registration with manual account activation"
+msgstr ""
+
+#: kallithea/model/db.py:1705
+msgid "User registration with automatic account activation"
+msgstr ""
+
+#: kallithea/model/db.py:2237
+msgid "Not reviewed"
+msgstr ""
+
+#: kallithea/model/db.py:2240
+msgid "Under review"
+msgstr ""
+
+#: kallithea/model/forms.py:57
+msgid "Please enter a login"
+msgstr ""
+
+#: kallithea/model/forms.py:58
+#, python-format
+msgid "Enter a value %(min)i characters long or more"
+msgstr ""
+
+#: kallithea/model/forms.py:66
+msgid "Please enter a password"
+msgstr ""
+
+#: kallithea/model/forms.py:67
+#, python-format
+msgid "Enter %(min)i characters or more"
+msgstr ""
+
+#: kallithea/model/forms.py:165
+msgid "Name must not contain only digits"
+msgstr ""
+
+#: kallithea/model/notification.py:254
+#, python-format
+msgid "%(user)s commented on changeset %(age)s"
+msgstr ""
+
+#: kallithea/model/notification.py:255
+#, python-format
+msgid "%(user)s sent message %(age)s"
+msgstr ""
+
+#: kallithea/model/notification.py:256
+#, python-format
+msgid "%(user)s mentioned you %(age)s"
+msgstr ""
+
+#: kallithea/model/notification.py:257
+#, python-format
+msgid "%(user)s registered in Kallithea %(age)s"
+msgstr ""
+
+#: kallithea/model/notification.py:258
+#, python-format
+msgid "%(user)s opened new pull request %(age)s"
+msgstr ""
+
+#: kallithea/model/notification.py:259
+#, python-format
+msgid "%(user)s commented on pull request %(age)s"
+msgstr ""
+
+#: kallithea/model/notification.py:266
+#, python-format
+msgid "%(user)s commented on changeset at %(when)s"
+msgstr ""
+
+#: kallithea/model/notification.py:267
+#, python-format
+msgid "%(user)s sent message at %(when)s"
+msgstr ""
+
+#: kallithea/model/notification.py:268
+#, python-format
+msgid "%(user)s mentioned you at %(when)s"
+msgstr ""
+
+#: kallithea/model/notification.py:269
+#, python-format
+msgid "%(user)s registered in Kallithea at %(when)s"
+msgstr ""
+
+#: kallithea/model/notification.py:270
+#, python-format
+msgid "%(user)s opened new pull request at %(when)s"
+msgstr ""
+
+#: kallithea/model/notification.py:271
+#, python-format
+msgid "%(user)s commented on pull request at %(when)s"
+msgstr ""
+
+#: kallithea/model/notification.py:302
+#, python-format
+msgid "[Comment] %(repo_name)s changeset %(short_id)s on %(branch)s"
+msgstr ""
+
+#: kallithea/model/notification.py:305
+#, python-format
+msgid "New user %(new_username)s registered"
+msgstr ""
+
+#: kallithea/model/notification.py:307
+#, python-format
+msgid "[Added] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
+msgstr ""
+
+#: kallithea/model/notification.py:308
+#, python-format
+msgid "[Comment] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
+msgstr ""
+
+#: kallithea/model/notification.py:321
+msgid "Closing"
+msgstr ""
+
+#: kallithea/model/pull_request.py:137
+#, python-format
+msgid "%(user)s wants you to review pull request %(pr_nice_id)s: %(pr_title)s"
+msgstr ""
+
+#: kallithea/model/scm.py:812
+msgid "latest tip"
+msgstr ""
+
+#: kallithea/model/user.py:192
+msgid "New user registration"
+msgstr ""
+
+#: kallithea/model/user.py:256
+msgid "You can't remove this user since it is crucial for the entire application"
+msgstr ""
+
+#: kallithea/model/user.py:261
+#, python-format
+msgid "User \"%s\" still owns %s repositories and cannot be removed. Switch owners or remove those repositories: %s"
+msgstr ""
+
+#: kallithea/model/user.py:266
+#, python-format
+msgid "User \"%s\" still owns %s repository groups and cannot be removed. Switch owners or remove those repository groups: %s"
+msgstr ""
+
+#: kallithea/model/user.py:273
+#, python-format
+msgid "User \"%s\" still owns %s user groups and cannot be removed. Switch owners or remove those user groups: %s"
+msgstr ""
+
+#: kallithea/model/user.py:368
+msgid "Password reset link"
+msgstr ""
+
+#: kallithea/model/user.py:418
+msgid "Password reset notification"
+msgstr ""
+
+#: kallithea/model/user.py:419
+#, python-format
+msgid "The password to your account %s has been changed using password reset form."
+msgstr ""
+
+#: kallithea/model/validators.py:77 kallithea/model/validators.py:78
+msgid "Value cannot be an empty list"
+msgstr ""
+
+#: kallithea/model/validators.py:96
+#, python-format
+msgid "Username \"%(username)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:98
+#, python-format
+msgid "Username \"%(username)s\" cannot be used"
+msgstr ""
+
+#: kallithea/model/validators.py:100
+msgid "Username may only contain alphanumeric characters underscores, periods or dashes and must begin with an alphanumeric character or underscore"
+msgstr ""
+
+#: kallithea/model/validators.py:127
+msgid "The input is not valid"
+msgstr ""
+
+#: kallithea/model/validators.py:134
+#, python-format
+msgid "Username %(username)s is not valid"
+msgstr ""
+
+#: kallithea/model/validators.py:154
+msgid "Invalid user group name"
+msgstr ""
+
+#: kallithea/model/validators.py:155
+#, python-format
+msgid "User group \"%(usergroup)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:157
+msgid "user group name may only contain alphanumeric characters underscores, periods or dashes and must begin with alphanumeric character"
+msgstr ""
+
+#: kallithea/model/validators.py:197
+msgid "Cannot assign this group as parent"
+msgstr ""
+
+#: kallithea/model/validators.py:198
+#, python-format
+msgid "Group \"%(group_name)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:200
+#, python-format
+msgid "Repository with name \"%(group_name)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:258
+msgid "Invalid characters (non-ascii) in password"
+msgstr ""
+
+#: kallithea/model/validators.py:273
+msgid "Invalid old password"
+msgstr ""
+
+#: kallithea/model/validators.py:289
+msgid "Passwords do not match"
+msgstr ""
+
+#: kallithea/model/validators.py:304
+msgid "Invalid username or password"
+msgstr ""
+
+#: kallithea/model/validators.py:335
+msgid "Token mismatch"
+msgstr ""
+
+#: kallithea/model/validators.py:351
+#, python-format
+msgid "Repository name %(repo)s is not allowed"
+msgstr ""
+
+#: kallithea/model/validators.py:353
+#, python-format
+msgid "Repository named %(repo)s already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:354
+#, python-format
+msgid "Repository \"%(repo)s\" already exists in group \"%(group)s\""
+msgstr ""
+
+#: kallithea/model/validators.py:356
+#, python-format
+msgid "Repository group with name \"%(repo)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:470
+msgid "Invalid repository URL"
+msgstr ""
+
+#: kallithea/model/validators.py:471
+msgid "Invalid repository URL. It must be a valid http, https, ssh, svn+http or svn+https URL"
+msgstr ""
+
+#: kallithea/model/validators.py:496
+msgid "Fork has to be the same type as parent"
+msgstr ""
+
+#: kallithea/model/validators.py:511
+msgid "You don't have permissions to create repository in this group"
+msgstr ""
+
+#: kallithea/model/validators.py:513
+msgid "no permission to create repository in root location"
+msgstr ""
+
+#: kallithea/model/validators.py:563
+msgid "You don't have permissions to create a group in this location"
+msgstr ""
+
+#: kallithea/model/validators.py:604
+msgid "This username or user group name is not valid"
+msgstr ""
+
+#: kallithea/model/validators.py:697
+msgid "This is not a valid path"
+msgstr ""
+
+#: kallithea/model/validators.py:714
+msgid "This email address is already in use"
+msgstr ""
+
+#: kallithea/model/validators.py:734
+#, python-format
+msgid "Email address \"%(email)s\" not found"
+msgstr ""
+
+#: kallithea/model/validators.py:771
+msgid "The LDAP Login attribute of the CN must be specified - this is the name of the attribute that is equivalent to \"username\""
+msgstr ""
+
+#: kallithea/model/validators.py:783
+msgid "Please enter a valid IPv4 or IPv6 address"
+msgstr ""
+
+#: kallithea/model/validators.py:784
+#, python-format
+msgid "The network size (bits) must be within the range of 0-32 (not %(bits)r)"
+msgstr ""
+
+#: kallithea/model/validators.py:817
+msgid "Key name can only consist of letters, underscore, dash or numbers"
+msgstr ""
+
+#: kallithea/model/validators.py:831
+msgid "Filename cannot be inside a directory"
+msgstr ""
+
+#: kallithea/model/validators.py:847
+#, python-format
+msgid "Plugins %(loaded)s and %(next_to_load)s both export the same name"
+msgstr ""
+
+#: kallithea/templates/about.html:4 kallithea/templates/about.html:17
+msgid "About"
+msgstr ""
+
+#: kallithea/templates/index.html:5
+msgid "Dashboard"
+msgstr ""
+
+#: kallithea/templates/index_base.html:6
+#: kallithea/templates/admin/my_account/my_account_repos.html:3
+#: kallithea/templates/admin/my_account/my_account_watched.html:3
+#: kallithea/templates/admin/repo_groups/repo_groups.html:9
+#: kallithea/templates/admin/repos/repos.html:9
+#: kallithea/templates/admin/user_groups/user_groups.html:9
+#: kallithea/templates/admin/users/users.html:9
+#: kallithea/templates/bookmarks/bookmarks.html:9
+#: kallithea/templates/branches/branches.html:9
+#: kallithea/templates/journal/journal.html:9
+#: kallithea/templates/journal/journal.html:48
+#: kallithea/templates/journal/journal.html:49
+#: kallithea/templates/tags/tags.html:9
+msgid "quick filter..."
+msgstr ""
+
+#: kallithea/templates/index_base.html:6
+msgid "repositories"
+msgstr ""
+
+#: kallithea/templates/index_base.html:20
+#: kallithea/templates/index_base.html:25
+#: kallithea/templates/admin/repos/repo_add.html:5
+#: kallithea/templates/admin/repos/repo_add.html:19
+#: kallithea/templates/admin/repos/repos.html:22
+msgid "Add Repository"
+msgstr ""
+
+#: kallithea/templates/index_base.html:22
+#: kallithea/templates/index_base.html:27
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:5
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:13
+#: kallithea/templates/admin/repo_groups/repo_groups.html:26
+msgid "Add Repository Group"
+msgstr ""
+
+#: kallithea/templates/index_base.html:32
+msgid "You have admin right to this group, and can edit it"
+msgstr ""
+
+#: kallithea/templates/index_base.html:32
+msgid "Edit Repository Group"
+msgstr ""
+
+#: kallithea/templates/index_base.html:45
+msgid "Group Name"
+msgstr ""
+
+#: kallithea/templates/index_base.html:46
+#: kallithea/templates/index_base.html:127
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:64
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:42
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:17
+#: kallithea/templates/admin/repo_groups/repo_groups.html:47
+#: kallithea/templates/admin/repos/repo_add_base.html:28
+#: kallithea/templates/admin/repos/repo_edit_settings.html:65
+#: kallithea/templates/admin/repos/repos.html:48
+#: kallithea/templates/admin/user_groups/user_group_add.html:40
+#: kallithea/templates/admin/user_groups/user_group_edit_settings.html:15
+#: kallithea/templates/admin/user_groups/user_groups.html:47
+#: kallithea/templates/admin/users/user_edit_api_keys.html:64
+#: kallithea/templates/email_templates/changeset_comment.html:18
+#: kallithea/templates/email_templates/pull_request.html:12
+#: kallithea/templates/forks/fork.html:38
+#: kallithea/templates/pullrequests/pullrequest.html:40
+#: kallithea/templates/pullrequests/pullrequest_show.html:38
+#: kallithea/templates/pullrequests/pullrequest_show.html:63
+#: kallithea/templates/summary/summary.html:85
+msgid "Description"
+msgstr ""
+
+#: kallithea/templates/index_base.html:125
+#: kallithea/templates/admin/my_account/my_account_repos.html:46
+#: kallithea/templates/admin/my_account/my_account_watched.html:46
+#: kallithea/templates/admin/repo_groups/repo_groups.html:46
+#: kallithea/templates/admin/repos/repo_add_base.html:9
+#: kallithea/templates/admin/repos/repo_edit_settings.html:7
+#: kallithea/templates/admin/repos/repos.html:47
+#: kallithea/templates/admin/user_groups/user_groups.html:46
+#: kallithea/templates/base/perms_summary.html:53
+#: kallithea/templates/bookmarks/bookmarks.html:49
+#: kallithea/templates/bookmarks/bookmarks_data.html:7
+#: kallithea/templates/branches/branches.html:49
+#: kallithea/templates/branches/branches_data.html:7
+#: kallithea/templates/files/files_browser.html:60
+#: kallithea/templates/journal/journal.html:187
+#: kallithea/templates/journal/journal.html:278
+#: kallithea/templates/tags/tags.html:49
+#: kallithea/templates/tags/tags_data.html:7
+msgid "Name"
+msgstr ""
+
+#: kallithea/templates/index_base.html:128
+msgid "Last Change"
+msgstr ""
+
+#: kallithea/templates/index_base.html:130
+#: kallithea/templates/admin/my_account/my_account_repos.html:48
+#: kallithea/templates/admin/my_account/my_account_watched.html:48
+#: kallithea/templates/admin/repos/repos.html:49
+#: kallithea/templates/journal/journal.html:189
+#: kallithea/templates/journal/journal.html:280
+msgid "Tip"
+msgstr ""
+
+#: kallithea/templates/index_base.html:132
+#: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:10
+#: kallithea/templates/admin/repo_groups/repo_groups.html:49
+#: kallithea/templates/admin/repos/repo_edit_settings.html:53
+#: kallithea/templates/admin/repos/repos.html:50
+#: kallithea/templates/admin/user_groups/user_group_edit_advanced.html:8
+#: kallithea/templates/admin/user_groups/user_groups.html:50
+#: kallithea/templates/pullrequests/pullrequest_data.html:16
+#: kallithea/templates/pullrequests/pullrequest_show.html:156
+#: kallithea/templates/pullrequests/pullrequest_show.html:244
+#: kallithea/templates/summary/summary.html:134
+msgid "Owner"
+msgstr ""
+
+#: kallithea/templates/index_base.html:140
+#: kallithea/templates/admin/my_account/my_account_repos.html:57
+#: kallithea/templates/admin/my_account/my_account_watched.html:57
+#: kallithea/templates/base/root.html:43
+#: kallithea/templates/bookmarks/bookmarks.html:79
+#: kallithea/templates/branches/branches.html:79
+#: kallithea/templates/journal/journal.html:198
+#: kallithea/templates/journal/journal.html:289
+#: kallithea/templates/tags/tags.html:79
+msgid "Click to sort ascending"
+msgstr ""
+
+#: kallithea/templates/index_base.html:141
+#: kallithea/templates/admin/my_account/my_account_repos.html:58
+#: kallithea/templates/admin/my_account/my_account_watched.html:58
+#: kallithea/templates/base/root.html:44
+#: kallithea/templates/bookmarks/bookmarks.html:80
+#: kallithea/templates/branches/branches.html:80
+#: kallithea/templates/journal/journal.html:199
+#: kallithea/templates/journal/journal.html:290
+#: kallithea/templates/tags/tags.html:80
+msgid "Click to sort descending"
+msgstr ""
+
+#: kallithea/templates/index_base.html:142
+msgid "No repositories found."
+msgstr ""
+
+#: kallithea/templates/index_base.html:143
+#: kallithea/templates/admin/my_account/my_account_repos.html:60
+#: kallithea/templates/admin/my_account/my_account_watched.html:60
+#: kallithea/templates/base/root.html:46
+#: kallithea/templates/bookmarks/bookmarks.html:82
+#: kallithea/templates/branches/branches.html:82
+#: kallithea/templates/journal/journal.html:201
+#: kallithea/templates/journal/journal.html:292
+#: kallithea/templates/tags/tags.html:82
+msgid "Data error."
+msgstr ""
+
+#: kallithea/templates/index_base.html:144
+#: kallithea/templates/admin/my_account/my_account_repos.html:61
+#: kallithea/templates/admin/my_account/my_account_watched.html:61
+#: kallithea/templates/base/root.html:47
+#: kallithea/templates/bookmarks/bookmarks.html:83
+#: kallithea/templates/branches/branches.html:83
+#: kallithea/templates/journal/journal.html:202
+#: kallithea/templates/journal/journal.html:293
+#: kallithea/templates/tags/tags.html:83
+msgid "Loading..."
+msgstr ""
+
+#: kallithea/templates/login.html:5 kallithea/templates/login.html:15
+#: kallithea/templates/base/base.html:414
+msgid "Log In"
+msgstr ""
+
+#: kallithea/templates/login.html:13
+#, python-format
+msgid "Log In to %s"
+msgstr ""
+
+#: kallithea/templates/login.html:26 kallithea/templates/register.html:24
+#: kallithea/templates/admin/admin_log.html:5
+#: kallithea/templates/admin/my_account/my_account_profile.html:25
+#: kallithea/templates/admin/users/user_add.html:32
+#: kallithea/templates/admin/users/user_edit_profile.html:24
+#: kallithea/templates/admin/users/users.html:50
+#: kallithea/templates/base/base.html:390
+#: kallithea/templates/pullrequests/pullrequest_show.html:166
+msgid "Username"
+msgstr ""
+
+#: kallithea/templates/login.html:33 kallithea/templates/register.html:33
+#: kallithea/templates/admin/my_account/my_account.html:37
+#: kallithea/templates/admin/users/user_add.html:41
+#: kallithea/templates/base/base.html:399
+msgid "Password"
+msgstr ""
+
+#: kallithea/templates/login.html:44
+msgid "Remember me"
+msgstr ""
+
+#: kallithea/templates/login.html:53
+msgid "Forgot your password ?"
+msgstr ""
+
+#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:410
+msgid "Don't have an account ?"
+msgstr ""
+
+#: kallithea/templates/login.html:59
+msgid "Sign In"
+msgstr ""
+
+#: kallithea/templates/password_reset.html:5
+msgid "Password Reset"
+msgstr ""
+
+#: kallithea/templates/password_reset.html:12
+#: kallithea/templates/password_reset_confirmation.html:12
+#, python-format
+msgid "Reset Your Password to %s"
+msgstr ""
+
+#: kallithea/templates/password_reset.html:14
+#: kallithea/templates/password_reset_confirmation.html:5
+#: kallithea/templates/password_reset_confirmation.html:14
+msgid "Reset Your Password"
+msgstr ""
+
+#: kallithea/templates/password_reset.html:25
+msgid "Email Address"
+msgstr ""
+
+#: kallithea/templates/password_reset.html:35
+#: kallithea/templates/register.html:79
+msgid "Captcha"
+msgstr ""
+
+#: kallithea/templates/password_reset.html:46
+msgid "Send Password Reset Email"
+msgstr ""
+
+#: kallithea/templates/password_reset.html:47
+msgid "A password reset link will be sent to the specified email address if it is registered in the system."
+msgstr ""
+
+#: kallithea/templates/password_reset_confirmation.html:19
+#, python-format
+msgid "You are about to set a new password for the email address %s."
+msgstr ""
+
+#: kallithea/templates/password_reset_confirmation.html:20
+msgid "Note that you must use the same browser session for this as the one used to request the password reset."
+msgstr ""
+
+#: kallithea/templates/password_reset_confirmation.html:30
+msgid "Code you received in the email"
+msgstr ""
+
+#: kallithea/templates/password_reset_confirmation.html:39
+msgid "New Password"
+msgstr ""
+
+#: kallithea/templates/password_reset_confirmation.html:48
+msgid "Confirm New Password"
+msgstr ""
+
+#: kallithea/templates/password_reset_confirmation.html:56
+msgid "Confirm"
+msgstr ""
+
+#: kallithea/templates/register.html:5 kallithea/templates/register.html:14
+#: kallithea/templates/register.html:90
+msgid "Sign Up"
+msgstr ""
+
+#: kallithea/templates/register.html:12
+#, python-format
+msgid "Sign Up to %s"
+msgstr ""
+
+#: kallithea/templates/register.html:42
+msgid "Re-enter password"
+msgstr ""
+
+#: kallithea/templates/register.html:51
+#: kallithea/templates/admin/my_account/my_account_profile.html:34
+#: kallithea/templates/admin/users/user_add.html:59
+#: kallithea/templates/admin/users/user_edit_profile.html:78
+#: kallithea/templates/admin/users/users.html:51
+msgid "First Name"
+msgstr ""
+
+#: kallithea/templates/register.html:60
+#: kallithea/templates/admin/my_account/my_account_profile.html:43
+#: kallithea/templates/admin/users/user_add.html:68
+#: kallithea/templates/admin/users/user_edit_profile.html:87
+#: kallithea/templates/admin/users/users.html:52
+msgid "Last Name"
+msgstr ""
+
+#: kallithea/templates/register.html:69
+#: kallithea/templates/admin/my_account/my_account_profile.html:52
+#: kallithea/templates/admin/settings/settings.html:31
+#: kallithea/templates/admin/users/user_add.html:77
+#: kallithea/templates/admin/users/user_edit_profile.html:33
+msgid "Email"
+msgstr ""
+
+#: kallithea/templates/register.html:92
+msgid "Registered accounts are ready to use and need no further action."
+msgstr ""
+
+#: kallithea/templates/register.html:94
+msgid "Please wait for an administrator to activate your account."
+msgstr ""
+
+#: kallithea/templates/switch_to_list.html:10
+#: kallithea/templates/branches/branches_data.html:69
+msgid "There are no branches yet"
+msgstr ""
+
+#: kallithea/templates/switch_to_list.html:32
+#: kallithea/templates/tags/tags_data.html:44
+msgid "There are no tags yet"
+msgstr ""
+
+#: kallithea/templates/switch_to_list.html:45
+#: kallithea/templates/bookmarks/bookmarks_data.html:43
+msgid "There are no bookmarks yet"
+msgstr ""
+
+#: kallithea/templates/admin/admin.html:5
+#: kallithea/templates/admin/admin.html:13
+#: kallithea/templates/base/base.html:59
+msgid "Admin Journal"
+msgstr ""
+
+#: kallithea/templates/admin/admin.html:10
+msgid "journal filter..."
+msgstr ""
+
+#: kallithea/templates/admin/admin.html:12
+#: kallithea/templates/journal/journal.html:11
+msgid "Filter"
+msgstr ""
+
+#: kallithea/templates/admin/admin.html:13
+#: kallithea/templates/journal/journal.html:12
+#, python-format
+msgid "%s Entry"
+msgid_plural "%s Entries"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/admin/admin_log.html:6
+#: kallithea/templates/admin/my_account/my_account_repos.html:50
+#: kallithea/templates/admin/my_account/my_account_watched.html:50
+#: kallithea/templates/admin/repo_groups/repo_groups.html:50
+#: kallithea/templates/admin/repos/repo_edit_fields.html:8
+#: kallithea/templates/admin/repos/repos.html:52
+#: kallithea/templates/admin/user_groups/user_groups.html:51
+#: kallithea/templates/admin/users/users.html:57
+#: kallithea/templates/journal/journal.html:191
+#: kallithea/templates/journal/journal.html:282
+msgid "Action"
+msgstr ""
+
+#: kallithea/templates/admin/admin_log.html:7
+#: kallithea/templates/admin/permissions/permissions_globals.html:18
+msgid "Repository"
+msgstr ""
+
+#: kallithea/templates/admin/admin_log.html:8
+#: kallithea/templates/bookmarks/bookmarks.html:51
+#: kallithea/templates/bookmarks/bookmarks_data.html:9
+#: kallithea/templates/branches/branches.html:51
+#: kallithea/templates/branches/branches_data.html:9
+#: kallithea/templates/tags/tags.html:51
+#: kallithea/templates/tags/tags_data.html:9
+msgid "Date"
+msgstr ""
+
+#: kallithea/templates/admin/admin_log.html:9
+msgid "From IP"
+msgstr ""
+
+#: kallithea/templates/admin/admin_log.html:63
+msgid "No actions yet"
+msgstr ""
+
+#: kallithea/templates/admin/auth/auth_settings.html:5
+msgid "Authentication Settings"
+msgstr ""
+
+#: kallithea/templates/admin/auth/auth_settings.html:11
+#: kallithea/templates/base/base.html:65
+msgid "Authentication"
+msgstr ""
+
+#: kallithea/templates/admin/auth/auth_settings.html:28
+msgid "Authentication Plugins"
+msgstr ""
+
+#: kallithea/templates/admin/auth/auth_settings.html:31
+msgid "Enabled Plugins"
+msgstr ""
+
+#: kallithea/templates/admin/auth/auth_settings.html:33
+msgid "Comma-separated list of plugins; Kallithea will try user authentication in plugin order"
+msgstr ""
+
+#: kallithea/templates/admin/auth/auth_settings.html:34
+msgid "Available built-in plugins"
+msgstr ""
+
+#: kallithea/templates/admin/auth/auth_settings.html:51
+msgid "Plugin"
+msgstr ""
+
+#: kallithea/templates/admin/auth/auth_settings.html:101
+#: kallithea/templates/admin/defaults/defaults.html:82
+#: kallithea/templates/admin/my_account/my_account_password.html:36
+#: kallithea/templates/admin/my_account/my_account_profile.html:60
+#: kallithea/templates/admin/permissions/permissions_globals.html:112
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:69
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:114
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:42
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:101
+#: kallithea/templates/admin/repos/repo_edit_settings.html:127
+#: kallithea/templates/admin/settings/settings_hooks.html:53
+#: kallithea/templates/admin/user_groups/user_group_add.html:57
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:104
+#: kallithea/templates/admin/user_groups/user_group_edit_settings.html:60
+#: kallithea/templates/admin/users/user_add.html:96
+#: kallithea/templates/admin/users/user_edit_profile.html:113
+#: kallithea/templates/base/default_perms_box.html:64
+msgid "Save"
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:5
+#: kallithea/templates/admin/defaults/defaults.html:11
+#: kallithea/templates/base/base.html:66
+msgid "Repository Defaults"
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:33
+#: kallithea/templates/admin/repos/repo_add_base.html:55
+#: kallithea/templates/admin/repos/repo_edit_fields.html:7
+msgid "Type"
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:42
+#: kallithea/templates/admin/repos/repo_add_base.html:73
+#: kallithea/templates/admin/repos/repo_edit_settings.html:75
+#: kallithea/templates/data_table/_dt_elements.html:72
+msgid "Private repository"
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:46
+#: kallithea/templates/admin/repos/repo_add_base.html:77
+#: kallithea/templates/admin/repos/repo_edit_settings.html:79
+#: kallithea/templates/forks/fork.html:72
+msgid "Private repositories are only visible to people explicitly added as collaborators."
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:53
+#: kallithea/templates/admin/repos/repo_edit_settings.html:84
+msgid "Enable statistics"
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:57
+#: kallithea/templates/admin/repos/repo_edit_settings.html:88
+msgid "Enable statistics window on summary page."
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:63
+#: kallithea/templates/admin/repos/repo_edit_settings.html:93
+msgid "Enable downloads"
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:67
+#: kallithea/templates/admin/repos/repo_edit_settings.html:97
+msgid "Enable download menu on summary page."
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:73
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:34
+#: kallithea/templates/admin/repos/repo_edit_settings.html:102
+msgid "Enable locking"
+msgstr ""
+
+#: kallithea/templates/admin/defaults/defaults.html:77
+#: kallithea/templates/admin/repos/repo_edit_settings.html:106
+msgid "Enable lock-by-pulling on repository."
+msgstr ""
+
+#: kallithea/templates/admin/gists/edit.html:5
+#: kallithea/templates/admin/gists/edit.html:18
+msgid "Edit Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/edit.html:36
+#, python-format
+msgid "Gist was update since you started editing. Copy your changes and click %(here)s to reload new version."
+msgstr ""
+
+#: kallithea/templates/admin/gists/edit.html:55
+#: kallithea/templates/admin/gists/new.html:39
+msgid "Gist description ..."
+msgstr ""
+
+#: kallithea/templates/admin/gists/edit.html:57
+#: kallithea/templates/admin/gists/new.html:41
+msgid "Gist lifetime"
+msgstr ""
+
+#: kallithea/templates/admin/gists/edit.html:61
+#: kallithea/templates/admin/gists/edit.html:63
+#: kallithea/templates/admin/gists/index.html:57
+#: kallithea/templates/admin/gists/index.html:59
+#: kallithea/templates/admin/gists/show.html:47
+#: kallithea/templates/admin/gists/show.html:49
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:8
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:27
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:32
+#: kallithea/templates/admin/users/user_edit_api_keys.html:8
+#: kallithea/templates/admin/users/user_edit_api_keys.html:27
+#: kallithea/templates/admin/users/user_edit_api_keys.html:32
+msgid "Expires"
+msgstr ""
+
+#: kallithea/templates/admin/gists/edit.html:61
+#: kallithea/templates/admin/gists/index.html:57
+#: kallithea/templates/admin/gists/show.html:47
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:8
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:27
+#: kallithea/templates/admin/users/user_edit_api_keys.html:8
+#: kallithea/templates/admin/users/user_edit_api_keys.html:27
+msgid "Never"
+msgstr ""
+
+#: kallithea/templates/admin/gists/edit.html:146
+msgid "Update Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/edit.html:147
+#: kallithea/templates/changeset/changeset_file_comment.html:105
+msgid "Cancel"
+msgstr ""
+
+#: kallithea/templates/admin/gists/index.html:6
+#: kallithea/templates/admin/gists/index.html:16
+#, python-format
+msgid "Private Gists for User %s"
+msgstr ""
+
+#: kallithea/templates/admin/gists/index.html:8
+#: kallithea/templates/admin/gists/index.html:18
+#, python-format
+msgid "Public Gists for User %s"
+msgstr ""
+
+#: kallithea/templates/admin/gists/index.html:10
+#: kallithea/templates/admin/gists/index.html:20
+msgid "Public Gists"
+msgstr ""
+
+#: kallithea/templates/admin/gists/index.html:37
+#: kallithea/templates/admin/gists/show.html:25
+#: kallithea/templates/base/base.html:321
+msgid "Create New Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/index.html:54
+#: kallithea/templates/data_table/_dt_elements.html:141
+msgid "Created"
+msgstr ""
+
+#: kallithea/templates/admin/gists/index.html:74
+msgid "There are no gists yet"
+msgstr ""
+
+#: kallithea/templates/admin/gists/new.html:5
+#: kallithea/templates/admin/gists/new.html:18
+msgid "New Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/new.html:47
+msgid "name this file..."
+msgstr ""
+
+#: kallithea/templates/admin/gists/new.html:56
+msgid "Create Private Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/new.html:57
+msgid "Create Public Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/new.html:58
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:15
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:70
+#: kallithea/templates/admin/my_account/my_account_emails.html:46
+#: kallithea/templates/admin/my_account/my_account_password.html:37
+#: kallithea/templates/admin/my_account/my_account_profile.html:61
+#: kallithea/templates/admin/permissions/permissions_globals.html:113
+#: kallithea/templates/admin/permissions/permissions_ips.html:39
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:115
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:43
+#: kallithea/templates/admin/repos/repo_edit_fields.html:59
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:102
+#: kallithea/templates/admin/repos/repo_edit_settings.html:128
+#: kallithea/templates/admin/settings/settings_global.html:57
+#: kallithea/templates/admin/settings/settings_vcs.html:81
+#: kallithea/templates/admin/settings/settings_visual.html:117
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:105
+#: kallithea/templates/admin/users/user_edit_api_keys.html:15
+#: kallithea/templates/admin/users/user_edit_api_keys.html:70
+#: kallithea/templates/admin/users/user_edit_emails.html:46
+#: kallithea/templates/admin/users/user_edit_ips.html:50
+#: kallithea/templates/admin/users/user_edit_profile.html:114
+#: kallithea/templates/base/default_perms_box.html:65
+#: kallithea/templates/files/files_add.html:65
+#: kallithea/templates/files/files_delete.html:44
+#: kallithea/templates/files/files_edit.html:68
+#: kallithea/templates/pullrequests/pullrequest.html:89
+msgid "Reset"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:5
+#: kallithea/templates/admin/gists/show.html:9
+msgid "Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:10
+#: kallithea/templates/email_templates/changeset_comment.html:15
+#: kallithea/templates/email_templates/pull_request.html:10
+#: kallithea/templates/email_templates/pull_request_comment.html:15
+msgid "URL"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:37
+msgid "Public Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:39
+msgid "Private Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:56
+#: kallithea/templates/admin/my_account/my_account_emails.html:19
+#: kallithea/templates/admin/permissions/permissions_ips.html:12
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:75
+#: kallithea/templates/admin/repos/repo_edit_fields.html:18
+#: kallithea/templates/admin/settings/settings_hooks.html:36
+#: kallithea/templates/admin/users/user_edit_emails.html:19
+#: kallithea/templates/admin/users/user_edit_ips.html:22
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+#: kallithea/templates/changeset/changeset_file_comment.html:95
+#: kallithea/templates/data_table/_dt_elements.html:129
+#: kallithea/templates/data_table/_dt_elements.html:157
+#: kallithea/templates/data_table/_dt_elements.html:173
+#: kallithea/templates/data_table/_dt_elements.html:189
+#: kallithea/templates/files/files_source.html:39
+#: kallithea/templates/files/files_source.html:42
+#: kallithea/templates/files/files_source.html:45
+#: kallithea/templates/pullrequests/pullrequest_data.html:20
+msgid "Delete"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:56
+msgid "Confirm to delete this Gist"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:63
+#: kallithea/templates/base/perms_summary.html:43
+#: kallithea/templates/base/perms_summary.html:79
+#: kallithea/templates/base/perms_summary.html:81
+#: kallithea/templates/data_table/_dt_elements.html:122
+#: kallithea/templates/data_table/_dt_elements.html:123
+#: kallithea/templates/data_table/_dt_elements.html:150
+#: kallithea/templates/data_table/_dt_elements.html:151
+#: kallithea/templates/data_table/_dt_elements.html:165
+#: kallithea/templates/data_table/_dt_elements.html:167
+#: kallithea/templates/data_table/_dt_elements.html:181
+#: kallithea/templates/data_table/_dt_elements.html:183
+#: kallithea/templates/files/diff_2way.html:56
+#: kallithea/templates/files/files_source.html:41
+#: kallithea/templates/files/files_source.html:44
+#: kallithea/templates/pullrequests/pullrequest_show.html:41
+msgid "Edit"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:65
+#: kallithea/templates/files/files_edit.html:49
+#: kallithea/templates/files/files_source.html:34
+msgid "Show as Raw"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:73
+msgid "created"
+msgstr ""
+
+#: kallithea/templates/admin/gists/show.html:86
+msgid "Show as raw"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account.html:5
+#: kallithea/templates/admin/my_account/my_account.html:9
+#: kallithea/templates/base/base.html:431
+msgid "My Account"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account.html:35
+#: kallithea/templates/admin/users/user_edit.html:29
+msgid "Profile"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account.html:36
+msgid "Email Addresses"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account.html:38
+#: kallithea/templates/admin/users/user_edit.html:31
+msgid "API Keys"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account.html:39
+msgid "Owned Repositories"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account.html:40
+#: kallithea/templates/journal/journal.html:53
+msgid "Watched Repositories"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account.html:41
+#: kallithea/templates/admin/permissions/permissions.html:30
+#: kallithea/templates/admin/user_groups/user_group_edit.html:32
+#: kallithea/templates/admin/users/user_edit.html:34
+msgid "Show Permissions"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:6
+#: kallithea/templates/admin/users/user_edit_api_keys.html:6
+msgid "Built-in"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:14
+#: kallithea/templates/admin/users/user_edit_api_keys.html:14
+#, python-format
+msgid "Confirm to reset this API key: %s"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:30
+#: kallithea/templates/admin/users/user_edit_api_keys.html:30
+msgid "Expired"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:40
+#: kallithea/templates/admin/users/user_edit_api_keys.html:40
+#, python-format
+msgid "Confirm to remove this API key: %s"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:42
+#: kallithea/templates/admin/users/user_edit_api_keys.html:42
+msgid "Remove"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:49
+#: kallithea/templates/admin/users/user_edit_api_keys.html:49
+msgid "No additional API keys specified"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:61
+#: kallithea/templates/admin/users/user_edit_api_keys.html:61
+msgid "New API key"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_api_keys.html:69
+#: kallithea/templates/admin/my_account/my_account_emails.html:45
+#: kallithea/templates/admin/permissions/permissions_ips.html:38
+#: kallithea/templates/admin/repos/repo_add_base.html:81
+#: kallithea/templates/admin/repos/repo_edit_fields.html:58
+#: kallithea/templates/admin/users/user_edit_api_keys.html:69
+#: kallithea/templates/admin/users/user_edit_emails.html:45
+#: kallithea/templates/admin/users/user_edit_ips.html:49
+msgid "Add"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_emails.html:7
+#: kallithea/templates/admin/users/user_edit_emails.html:7
+msgid "Primary"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_emails.html:20
+#: kallithea/templates/admin/users/user_edit_emails.html:20
+#, python-format
+msgid "Confirm to delete this email: %s"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_emails.html:26
+#: kallithea/templates/admin/users/user_edit_emails.html:26
+msgid "No additional emails specified."
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_emails.html:38
+#: kallithea/templates/admin/users/user_edit_emails.html:38
+msgid "New email address"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_password.html:1
+msgid "Change Your Account Password"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_password.html:10
+msgid "Current password"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_password.html:19
+#: kallithea/templates/admin/users/user_edit_profile.html:60
+msgid "New password"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_password.html:28
+msgid "Confirm new password"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_password.html:45
+#, python-format
+msgid "This account is managed with %s and the password cannot be changed here"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_profile.html:11
+msgid "Change your avatar at"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_profile.html:12
+#: kallithea/templates/admin/users/user_edit_profile.html:9
+msgid "Using"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_profile.html:14
+#: kallithea/templates/admin/users/user_edit_profile.html:11
+msgid "Avatars are disabled"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_profile.html:15
+msgid "Missing email, please update your user email address."
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_profile.html:16
+#: kallithea/templates/admin/users/user_edit_profile.html:15
+msgid "Current IP"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_repos.html:1
+msgid "Repositories You Own"
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_repos.html:59
+#: kallithea/templates/admin/my_account/my_account_watched.html:59
+#: kallithea/templates/base/root.html:45
+#: kallithea/templates/bookmarks/bookmarks.html:81
+#: kallithea/templates/branches/branches.html:81
+#: kallithea/templates/journal/journal.html:200
+#: kallithea/templates/journal/journal.html:291
+#: kallithea/templates/tags/tags.html:81
+msgid "No records found."
+msgstr ""
+
+#: kallithea/templates/admin/my_account/my_account_watched.html:1
+msgid "Repositories You are Watching"
+msgstr ""
+
+#: kallithea/templates/admin/notifications/notifications.html:5
+#: kallithea/templates/admin/notifications/notifications.html:9
+msgid "My Notifications"
+msgstr ""
+
+#: kallithea/templates/admin/notifications/notifications.html:24
+msgid "All"
+msgstr ""
+
+#: kallithea/templates/admin/notifications/notifications.html:25
+msgid "Comments"
+msgstr ""
+
+#: kallithea/templates/admin/notifications/notifications.html:26
+#: kallithea/templates/base/base.html:180
+msgid "Pull Requests"
+msgstr ""
+
+#: kallithea/templates/admin/notifications/notifications.html:30
+msgid "Mark All Read"
+msgstr ""
+
+#: kallithea/templates/admin/notifications/notifications_data.html:40
+msgid "No notifications here yet"
+msgstr ""
+
+#: kallithea/templates/admin/notifications/show_notification.html:5
+#: kallithea/templates/admin/notifications/show_notification.html:11
+msgid "Show Notification"
+msgstr ""
+
+#: kallithea/templates/admin/notifications/show_notification.html:9
+#: kallithea/templates/base/base.html:430
+msgid "Notifications"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions.html:5
+#: kallithea/templates/admin/permissions/permissions.html:11
+#: kallithea/templates/base/base.html:64
+msgid "Default Permissions"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions.html:28
+#: kallithea/templates/admin/settings/settings.html:29
+msgid "Global"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions.html:29
+#: kallithea/templates/admin/users/user_edit.html:32
+msgid "IP Whitelist"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:7
+msgid "Anonymous access"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:13
+#, python-format
+msgid "Allow access to Kallithea without needing to log in. Anonymous users use %s user permissions."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:25
+msgid "All default permissions on each repository will be reset to chosen permission, note that all custom default permission on repositories will be lost"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:26
+msgid "Apply to all existing repositories"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:27
+msgid "Permissions for the Default user on new repositories."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:32
+#: kallithea/templates/admin/repos/repo_add_base.html:37
+#: kallithea/templates/admin/repos/repo_edit_settings.html:35
+#: kallithea/templates/data_table/_dt_elements.html:202
+#: kallithea/templates/forks/fork.html:48
+msgid "Repository group"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:39
+msgid "All default permissions on each repository group will be reset to chosen permission, note that all custom default permission on repository groups will be lost"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:40
+msgid "Apply to all existing repository groups"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:41
+msgid "Permissions for the Default user on new repository groups."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:46
+#: kallithea/templates/data_table/_dt_elements.html:209
+msgid "User group"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:53
+msgid "All default permissions on each user group will be reset to chosen permission, note that all custom default permission on user groups will be lost"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:54
+msgid "Apply to all existing user groups"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:55
+msgid "Permissions for the Default user on new user groups."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:60
+msgid "Top level repository creation"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:64
+msgid "Enable this to allow non-admins to create repositories at the top level."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:65
+msgid "Note: This will also give all users API access to create repositories everywhere. That might change in future versions."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:70
+msgid "Repository creation with group write access"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:74
+msgid "With this, write permission to a repository group allows creating repositories inside that group. Without this, group write permissions mean nothing."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:79
+msgid "User group creation"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:83
+msgid "Enable this to allow non-admins to create user groups."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:88
+msgid "Repository forking"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:92
+msgid "Enable this to allow non-admins to fork repositories."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:97
+msgid "Registration"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_globals.html:105
+msgid "External auth account activation"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_ips.html:13
+#: kallithea/templates/admin/users/user_edit_ips.html:23
+#, python-format
+msgid "Confirm to delete this IP address: %s"
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_ips.html:19
+#: kallithea/templates/admin/users/user_edit_ips.html:30
+msgid "All IP addresses are allowed."
+msgstr ""
+
+#: kallithea/templates/admin/permissions/permissions_ips.html:30
+#: kallithea/templates/admin/users/user_edit_ips.html:42
+msgid "New IP address"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:11
+#: kallithea/templates/admin/repo_groups/repo_group_edit.html:11
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:105
+#: kallithea/templates/admin/repo_groups/repo_groups.html:10
+#: kallithea/templates/base/base.html:61 kallithea/templates/base/base.html:80
+msgid "Repository Groups"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:33
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:8
+#: kallithea/templates/admin/user_groups/user_group_add.html:32
+#: kallithea/templates/admin/user_groups/user_group_edit_settings.html:7
+msgid "Group name"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:51
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:26
+msgid "Group parent"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:60
+#: kallithea/templates/admin/repos/repo_add_base.html:46
+msgid "Copy parent group permissions"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_add.html:64
+#: kallithea/templates/admin/repos/repo_add_base.html:50
+msgid "Copy permission set from parent repository group."
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit.html:5
+#, python-format
+msgid "%s Repository Group Settings"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit.html:21
+msgid "Add Child Group"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit.html:40
+#: kallithea/templates/admin/repos/repo_edit.html:12
+#: kallithea/templates/admin/repos/repo_edit.html:40
+#: kallithea/templates/admin/settings/settings.html:11
+#: kallithea/templates/admin/user_groups/user_group_edit.html:29
+#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:148
+#: kallithea/templates/data_table/_dt_elements.html:45
+#: kallithea/templates/data_table/_dt_elements.html:49
+msgid "Settings"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit.html:41
+#: kallithea/templates/admin/repos/repo_edit.html:46
+#: kallithea/templates/admin/user_groups/user_group_edit.html:30
+#: kallithea/templates/admin/users/user_edit.html:33
+msgid "Advanced"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit.html:42
+#: kallithea/templates/admin/repos/repo_edit.html:43
+#: kallithea/templates/admin/user_groups/user_group_edit.html:31
+msgid "Permissions"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:1
+#, python-format
+msgid "Repository Group: %s"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:6
+msgid "Top level repositories"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:7
+msgid "Total repositories"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:8
+msgid "Children groups"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:9
+#: kallithea/templates/admin/user_groups/user_group_edit_advanced.html:7
+#: kallithea/templates/admin/users/user_edit_advanced.html:8
+#: kallithea/templates/pullrequests/pullrequest_show.html:148
+msgid "Created on"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:21
+#: kallithea/templates/data_table/_dt_elements.html:190
+#, python-format
+msgid "Confirm to delete this group: %s with %s repository"
+msgid_plural "Confirm to delete this group: %s with %s repositories"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html:25
+msgid "Delete this repository group"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:11
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:12
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:11
+msgid "User/User Group"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:28
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:45
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:24
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:37
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:28
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:45
+msgid "Default"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:34
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:71
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:43
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:68
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:34
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:71
+msgid "Revoke"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:97
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:94
+#: kallithea/templates/admin/user_groups/user_group_edit_perms.html:97
+msgid "Add new"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:103
+msgid "Apply to children"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:107
+msgid "Both"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:108
+msgid "Set or revoke permission to all children of that group, including non-private repositories and other groups if selected."
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:38
+msgid "Enable lock-by-pulling on group. This option will be applied to all other groups and repositories inside"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:53
+msgid "Remove this group"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:53
+msgid "Confirm to delete this group"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_show.html:4
+#, python-format
+msgid "%s Repository group dashboard"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_show.html:9
+msgid "Home"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_group_show.html:13
+msgid "with"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_groups.html:5
+msgid "Repository Groups Administration"
+msgstr ""
+
+#: kallithea/templates/admin/repo_groups/repo_groups.html:48
+msgid "Number of Top-level Repositories"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_add_base.html:17
+msgid "Clone remote repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_add_base.html:22
+msgid "Optional: URL of a remote repository. If set, the repository will be created as a clone from this URL."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_add_base.html:32
+#: kallithea/templates/admin/repos/repo_edit_settings.html:69
+#: kallithea/templates/forks/fork.html:42
+msgid "Keep it short and to the point. Use a README file for longer descriptions."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_add_base.html:41
+#: kallithea/templates/admin/repos/repo_edit_settings.html:39
+#: kallithea/templates/forks/fork.html:52
+msgid "Optionally select a group to put this repository into."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_add_base.html:59
+msgid "Type of repository to create."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_add_base.html:64
+#: kallithea/templates/admin/repos/repo_edit_settings.html:44
+#: kallithea/templates/forks/fork.html:58
+msgid "Landing revision"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_add_base.html:68
+msgid "Default revision for files page, downloads, full text search index and readme generation"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_creating.html:9
+#, python-format
+msgid "%s Creating Repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_creating.html:13
+msgid "Creating repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_creating.html:27
+#, python-format
+msgid "Repository \"%(repo_name)s\" is being created, you will be redirected when this process is finished.repo_name"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_creating.html:39
+msgid "We're sorry but error occurred during this operation. Please check your Kallithea server logs, or contact administrator."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit.html:8
+#, python-format
+msgid "%s Repository Settings"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit.html:49
+msgid "Extra Fields"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit.html:52
+msgid "Caches"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit.html:55
+msgid "Remote"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit.html:58
+#: kallithea/templates/summary/statistics.html:8
+#: kallithea/templates/summary/summary.html:171
+#: kallithea/templates/summary/summary.html:172
+msgid "Statistics"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:1
+msgid "Parent"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:5
+#: kallithea/templates/admin/repos/repo_edit_fork.html:5
+msgid "Set"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:8
+#: kallithea/templates/admin/repos/repo_edit_fork.html:9
+msgid "Manually set this repository as a fork of another from the list."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:22
+msgid "Public Journal Visibility"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:29
+msgid "Remove from public journal"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:34
+msgid "Add to Public Journal"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:40
+msgid "All actions done in this repository will be visible to everyone in the public journal."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:46
+msgid "Change Locking"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:52
+msgid "Confirm to unlock repository."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:54
+msgid "Unlock Repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:56
+#, python-format
+msgid "Locked by %s on %s"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:60
+msgid "Confirm to lock repository."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:62
+msgid "Lock Repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:64
+msgid "Repository is not locked"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:68
+msgid "Force locking on the repository. Works only when anonymous access is disabled. Triggering a pull locks the repository.  The user who is pulling locks the repository; only the user who pulled and locked it can unlock it by doing a push."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:79
+#: kallithea/templates/data_table/_dt_elements.html:130
+#, python-format
+msgid "Confirm to delete this repository: %s"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:81
+msgid "Delete this Repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:84
+#, python-format
+msgid "This repository has %s fork"
+msgid_plural "This repository has %s forks"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:85
+msgid "Detach forks"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:86
+msgid "Delete forks"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:90
+msgid "The deleted repository will be moved away and hidden until the administrator expires it. The administrator can both permanently delete it or restore it."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_caches.html:4
+msgid "Invalidate Repository Cache"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_caches.html:7
+msgid "Manually invalidate cache for this repository. On first access, the repository will be cached again."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_caches.html:12
+msgid "List of Cached Values"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_caches.html:15
+msgid "Prefix"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_caches.html:16
+#: kallithea/templates/admin/repos/repo_edit_fields.html:6
+msgid "Key"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_caches.html:17
+#: kallithea/templates/admin/user_groups/user_group_add.html:49
+#: kallithea/templates/admin/user_groups/user_group_edit_settings.html:24
+#: kallithea/templates/admin/user_groups/user_groups.html:49
+#: kallithea/templates/admin/users/user_add.html:86
+#: kallithea/templates/admin/users/user_edit_profile.html:96
+#: kallithea/templates/admin/users/users.html:54
+msgid "Active"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_fields.html:5
+msgid "Label"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_fields.html:19
+#, python-format
+msgid "Confirm to delete this field: %s"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_fields.html:33
+msgid "New field key"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_fields.html:41
+msgid "New field label"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_fields.html:44
+msgid "Enter short label"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_fields.html:50
+msgid "New field description"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_fields.html:53
+msgid "Enter description of a field"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_fields.html:66
+msgid "Extra fields are disabled."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_permissions.html:21
+msgid "Private Repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_remote.html:3
+msgid "Remote repository URL"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_remote.html:9
+msgid "Pull Changes from Remote Repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_remote.html:11
+msgid "Confirm to pull changes from remote repository."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_remote.html:17
+msgid "This repository does not have a remote repository URL."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:11
+msgid "Permanent Repository ID"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:11
+msgid "What is that?"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:13
+msgid "URL by id"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:14
+msgid ""
+"In case this repository is renamed or moved into another group the repository URL changes.\n"
+"                               Using the above permanent URL guarantees that this repository always will be accessible on that URL.\n"
+"                               This is useful for CI systems, or any other cases that you need to hardcode the URL into a 3rd party service."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:21
+msgid "Remote repository"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:25
+msgid "Repository URL"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:29
+msgid "Optional: URL of a remote repository. If set, the repository can be pulled from this URL."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:48
+msgid "Default revision for files page, downloads, whoosh and readme"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_settings.html:58
+msgid "Change owner of this repository."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_statistics.html:6
+msgid "Processed commits"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_statistics.html:7
+msgid "Processed progress"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_statistics.html:10
+msgid "Reset Statistics"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repo_edit_statistics.html:10
+msgid "Confirm to remove current statistics."
+msgstr ""
+
+#: kallithea/templates/admin/repos/repos.html:5
+msgid "Repositories Administration"
+msgstr ""
+
+#: kallithea/templates/admin/repos/repos.html:51
+msgid "State"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings.html:5
+msgid "Settings Administration"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings.html:27
+msgid "VCS"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings.html:28
+msgid "Remap and Rescan"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings.html:30
+msgid "Visual"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings.html:32
+#: kallithea/templates/admin/settings/settings_vcs.html:19
+msgid "Hooks"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings.html:33
+msgid "Full Text Search"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings.html:34
+msgid "System Info"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_email.html:7
+msgid "Send test email to"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_email.html:15
+msgid "Send"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:8
+msgid "Site branding"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:12
+msgid "Set a custom title for your Kallithea Service."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:18
+msgid "HTTP authentication realm"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:27
+msgid "Analytics HTML block"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:31
+msgid "HTML with JavaScript for web analytics systems like Google Analytics or Piwik. This will be added at the bottom of every page."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:37
+msgid "ReCaptcha public key"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:41
+msgid "Public key for reCaptcha system."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:47
+msgid "ReCaptcha private key"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:51
+msgid "Private key for reCaptcha system. Setting this value will enable captcha on registration."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_global.html:56
+#: kallithea/templates/admin/settings/settings_vcs.html:80
+#: kallithea/templates/admin/settings/settings_visual.html:116
+msgid "Save Settings"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_hooks.html:1
+msgid "Built-in Mercurial Hooks (Read-Only)"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_hooks.html:15
+msgid "Hooks can be used to trigger actions on certain events such as push / pull. They can trigger Python functions or external applications."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_hooks.html:19
+msgid "Custom Hooks"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_hooks.html:67
+msgid "Failed to remove hook"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:6
+msgid "Rescan option"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:11
+msgid "Delete records of missing repositories"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:13
+msgid "Check this option to remove all comments, pull requests and other records related to repositories that no longer exist in the filesystem."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:17
+msgid "Invalidate cache for all repositories"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:19
+msgid "Check this to reload data and clear cache keys for all repositories."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:23
+msgid "Install Git hooks"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:25
+msgid "Verify if Kallithea's Git hooks are installed for each repository. Current hooks will be updated to the latest version."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:28
+msgid "Overwrite existing Git hooks"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:30
+msgid "If installing Git hooks, overwrite any existing hooks, even if they do not seem to come from Kallithea. WARNING: This operation will destroy any custom git hooks you may have deployed by hand!"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_mapping.html:35
+msgid "Rescan Repositories"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_search.html:7
+msgid "Index build option"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_search.html:12
+msgid "Build from scratch"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_search.html:15
+msgid "This option completely reindexeses all of the repositories for proper fulltext search capabilities."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_search.html:21
+msgid "Reindex"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:4
+msgid "Kallithea version"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:4
+msgid "Check for updates"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:5
+msgid "Kallithea configuration file"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:6
+msgid "Python version"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:7
+msgid "Platform"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:8
+msgid "Git version"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:9
+msgid "Git path"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:10
+msgid "Upgrade info endpoint"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:10
+msgid "Note: please make sure this server can access this URL"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:15
+msgid "Checking for updates..."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_system.html:23
+msgid "Python Packages"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:6
+msgid "Web"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:11
+msgid "Require SSL for vcs operations"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:13
+msgid "Activate to require SSL both pushing and pulling. If SSL certificate is missing, it will return an HTTP Error 406: Not Acceptable."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:24
+msgid "Show repository size after push"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:28
+msgid "Log user push commands"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:32
+msgid "Log user pull commands"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:36
+msgid "Update repository after push (hg update)"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:42
+msgid "Mercurial extensions"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:47
+msgid "Enable largefiles extension"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:51
+msgid "Enable hgsubversion extension"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:53
+msgid "Requires hgsubversion library to be installed. Enables cloning of remote Subversion repositories while converting them to Mercurial."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:64
+msgid "Location of repositories"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:69
+msgid "Click to unlock. You must restart Kallithea in order to make this setting take effect."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_vcs.html:72
+msgid "Filesystem location where repositories are stored. After changing this value, a restart and rescan of the repository folder are both required."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:8
+msgid "General"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:13
+msgid "Use repository extra fields"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:15
+msgid "Allows storing additional customized fields per repository."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:18
+msgid "Show Kallithea version"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:20
+msgid "Shows or hides a version number of Kallithea displayed in the footer."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:24
+msgid "Use Gravatars in Kallithea"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:30
+msgid ""
+"Gravatar URL allows you to use another avatar server application.\n"
+"                                                        The following variables of the URL will be replaced accordingly.\n"
+"                                                        {scheme}    'http' or 'https' sent from running Kallithea server,\n"
+"                                                        {email}     user email,\n"
+"                                                        {md5email}  md5 hash of the user email (like at gravatar.com),\n"
+"                                                        {size}      size of the image that is expected from the server application,\n"
+"                                                        {netloc}    network location/server host of running Kallithea server"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:42
+msgid ""
+"Schema of clone URL construction eg. '{scheme}://{user}@{netloc}/{repo}'.\n"
+"                                                        The following variables are available:\n"
+"                                                        {scheme} 'http' or 'https' sent from running Kallithea server,\n"
+"                                                        {user}   current user username,\n"
+"                                                        {netloc} network location/server host of running Kallithea server,\n"
+"                                                        {repo}   full repository name,\n"
+"                                                        {repoid} ID of repository, can be used to contruct clone-by-id"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:55
+msgid "Dashboard items"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:59
+msgid "Number of items displayed in the main page dashboard before pagination is shown."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:65
+msgid "Admin pages items"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:69
+msgid "Number of items displayed in the admin pages grids before pagination is shown."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:75
+msgid "Icons"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:80
+msgid "Show public repository icon on repositories"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:84
+msgid "Show private repository icon on repositories"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:86
+msgid "Show public/private icons next to repository names."
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:92
+msgid "Meta Tagging"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:97
+msgid "Stylify recognised meta tags:"
+msgstr ""
+
+#: kallithea/templates/admin/settings/settings_visual.html:111
+msgid "Parses meta tags from the repository description field and turns them into colored tags."
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_add.html:5
+msgid "Add user group"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_add.html:10
+#: kallithea/templates/admin/user_groups/user_group_edit.html:11
+#: kallithea/templates/admin/user_groups/user_groups.html:10
+#: kallithea/templates/base/base.html:63 kallithea/templates/base/base.html:83
+msgid "User Groups"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_add.html:12
+#: kallithea/templates/admin/user_groups/user_groups.html:25
+msgid "Add User Group"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_add.html:44
+#: kallithea/templates/admin/user_groups/user_group_edit_settings.html:19
+msgid "Short, optional description for this user group."
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit.html:5
+#, python-format
+msgid "%s user group settings"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit.html:33
+msgid "Show Members"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit_advanced.html:1
+#, python-format
+msgid "User Group: %s"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit_advanced.html:6
+#: kallithea/templates/admin/user_groups/user_group_edit_settings.html:32
+#: kallithea/templates/admin/user_groups/user_groups.html:48
+msgid "Members"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit_advanced.html:19
+#: kallithea/templates/data_table/_dt_elements.html:174
+#, python-format
+msgid "Confirm to delete this user group: %s"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit_advanced.html:21
+msgid "Delete this user group"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit_members.html:17
+msgid "No members yet"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit_settings.html:40
+msgid "Chosen group members"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_group_edit_settings.html:49
+msgid "Available members"
+msgstr ""
+
+#: kallithea/templates/admin/user_groups/user_groups.html:5
+msgid "User Groups Administration"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_add.html:5
+msgid "Add user"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_add.html:10
+#: kallithea/templates/admin/users/user_edit.html:11
+#: kallithea/templates/admin/users/users.html:10
+#: kallithea/templates/base/base.html:62
+msgid "Users"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_add.html:12
+#: kallithea/templates/admin/users/users.html:24
+msgid "Add User"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_add.html:50
+msgid "Password confirmation"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit.html:5
+#, python-format
+msgid "%s user settings"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit.html:30
+msgid "Emails"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_advanced.html:1
+#, python-format
+msgid "User: %s"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_advanced.html:7
+#: kallithea/templates/admin/users/user_edit_profile.html:42
+msgid "Source of Record"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_advanced.html:9
+#: kallithea/templates/admin/users/users.html:53
+msgid "Last Login"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_advanced.html:10
+msgid "Member of User Groups"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_advanced.html:21
+#: kallithea/templates/data_table/_dt_elements.html:158
+#, python-format
+msgid "Confirm to delete this user: %s"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_advanced.html:23
+msgid "Delete this user"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_ips.html:8
+#, python-format
+msgid "Inherited from %s"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_profile.html:8
+msgid "Change avatar at"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_profile.html:12
+msgid "Missing email, please update this user email address."
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_profile.html:51
+msgid "Name in Source of Record"
+msgstr ""
+
+#: kallithea/templates/admin/users/user_edit_profile.html:69
+msgid "New password confirmation"
+msgstr ""
+
+#: kallithea/templates/admin/users/users.html:5
+msgid "Users Administration"
+msgstr ""
+
+#: kallithea/templates/admin/users/users.html:56
+msgid "Auth Type"
+msgstr ""
+
+#: kallithea/templates/base/base.html:18
+#, python-format
+msgid "Server instance: %s"
+msgstr ""
+
+#: kallithea/templates/base/base.html:30
+msgid "Support"
+msgstr ""
+
+#: kallithea/templates/base/base.html:90
+msgid "Mercurial repository"
+msgstr ""
+
+#: kallithea/templates/base/base.html:93
+msgid "Git repository"
+msgstr ""
+
+#: kallithea/templates/base/base.html:119
+msgid "Create Fork"
+msgstr ""
+
+#: kallithea/templates/base/base.html:130
+#: kallithea/templates/data_table/_dt_elements.html:13
+#: kallithea/templates/data_table/_dt_elements.html:17
+#: kallithea/templates/summary/summary.html:8
+msgid "Summary"
+msgstr ""
+
+#: kallithea/templates/base/base.html:132
+#: kallithea/templates/base/base.html:134
+#: kallithea/templates/changelog/changelog.html:14
+#: kallithea/templates/data_table/_dt_elements.html:21
+#: kallithea/templates/data_table/_dt_elements.html:25
+msgid "Changelog"
+msgstr ""
+
+#: kallithea/templates/base/base.html:136
+#: kallithea/templates/data_table/_dt_elements.html:29
+#: kallithea/templates/data_table/_dt_elements.html:33
+#: kallithea/templates/files/files.html:11
+msgid "Files"
+msgstr ""
+
+#: kallithea/templates/base/base.html:142
+#: kallithea/templates/base/base.html:144
+msgid "Options"
+msgstr ""
+
+#: kallithea/templates/base/base.html:152
+#: kallithea/templates/forks/forks_data.html:21
+msgid "Compare Fork"
+msgstr ""
+
+#: kallithea/templates/base/base.html:154
+#: kallithea/templates/bookmarks/bookmarks.html:56
+#: kallithea/templates/bookmarks/bookmarks_data.html:13
+#: kallithea/templates/branches/branches.html:56
+#: kallithea/templates/branches/branches_data.html:13
+#: kallithea/templates/tags/tags.html:56
+#: kallithea/templates/tags/tags_data.html:13
+msgid "Compare"
+msgstr ""
+
+#: kallithea/templates/base/base.html:156
+#: kallithea/templates/base/base.html:331
+#: kallithea/templates/search/search.html:14
+#: kallithea/templates/search/search.html:54
+msgid "Search"
+msgstr ""
+
+#: kallithea/templates/base/base.html:160
+msgid "Unlock"
+msgstr ""
+
+#: kallithea/templates/base/base.html:162
+msgid "Lock"
+msgstr ""
+
+#: kallithea/templates/base/base.html:170
+msgid "Follow"
+msgstr ""
+
+#: kallithea/templates/base/base.html:171
+msgid "Unfollow"
+msgstr ""
+
+#: kallithea/templates/base/base.html:174
+#: kallithea/templates/data_table/_dt_elements.html:37
+#: kallithea/templates/data_table/_dt_elements.html:41
+#: kallithea/templates/forks/fork.html:9
+msgid "Fork"
+msgstr ""
+
+#: kallithea/templates/base/base.html:175
+#: kallithea/templates/pullrequests/pullrequest.html:88
+msgid "Create Pull Request"
+msgstr ""
+
+#: kallithea/templates/base/base.html:180
+#, python-format
+msgid "Show Pull Requests for %s"
+msgstr ""
+
+#: kallithea/templates/base/base.html:193
+msgid "Switch To"
+msgstr ""
+
+#: kallithea/templates/base/base.html:203
+#: kallithea/templates/base/base.html:485
+msgid "No matches found"
+msgstr ""
+
+#: kallithea/templates/base/base.html:305
+msgid "Show recent activity"
+msgstr ""
+
+#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:312
+msgid "Public journal"
+msgstr ""
+
+#: kallithea/templates/base/base.html:317
+msgid "Show public gists"
+msgstr ""
+
+#: kallithea/templates/base/base.html:318
+msgid "Gists"
+msgstr ""
+
+#: kallithea/templates/base/base.html:322
+msgid "All Public Gists"
+msgstr ""
+
+#: kallithea/templates/base/base.html:324
+msgid "My Public Gists"
+msgstr ""
+
+#: kallithea/templates/base/base.html:325
+msgid "My Private Gists"
+msgstr ""
+
+#: kallithea/templates/base/base.html:330
+msgid "Search in repositories"
+msgstr ""
+
+#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:354
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:6
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:10
+msgid "My Pull Requests"
+msgstr ""
+
+#: kallithea/templates/base/base.html:377
+msgid "Not Logged In"
+msgstr ""
+
+#: kallithea/templates/base/base.html:384
+msgid "Login to Your Account"
+msgstr ""
+
+#: kallithea/templates/base/base.html:407
+msgid "Forgot password ?"
+msgstr ""
+
+#: kallithea/templates/base/base.html:434
+msgid "Log Out"
+msgstr ""
+
+#: kallithea/templates/base/base.html:615
+msgid "Keyboard shortcuts"
+msgstr ""
+
+#: kallithea/templates/base/base.html:624
+msgid "Site-wide shortcuts"
+msgstr ""
+
+#: kallithea/templates/base/default_perms_box.html:14
+msgid "Inherit defaults"
+msgstr ""
+
+#: kallithea/templates/base/default_perms_box.html:19
+#, python-format
+msgid "Select to inherit global settings, IP whitelist and permissions from the %s."
+msgstr ""
+
+#: kallithea/templates/base/default_perms_box.html:28
+msgid "Create repositories"
+msgstr ""
+
+#: kallithea/templates/base/default_perms_box.html:33
+msgid "Select this option to allow repository creation for this user"
+msgstr ""
+
+#: kallithea/templates/base/default_perms_box.html:40
+msgid "Create user groups"
+msgstr ""
+
+#: kallithea/templates/base/default_perms_box.html:45
+msgid "Select this option to allow user group creation for this user"
+msgstr ""
+
+#: kallithea/templates/base/default_perms_box.html:52
+msgid "Fork repositories"
+msgstr ""
+
+#: kallithea/templates/base/default_perms_box.html:57
+msgid "Select this option to allow repository forking for this user"
+msgstr ""
+
+#: kallithea/templates/base/perms_summary.html:13
+#: kallithea/templates/changelog/changelog.html:42
+msgid "Show"
+msgstr ""
+
+#: kallithea/templates/base/perms_summary.html:22
+msgid "No permissions defined yet"
+msgstr ""
+
+#: kallithea/templates/base/perms_summary.html:30
+#: kallithea/templates/base/perms_summary.html:54
+msgid "Permission"
+msgstr ""
+
+#: kallithea/templates/base/perms_summary.html:32
+#: kallithea/templates/base/perms_summary.html:56
+msgid "Edit Permission"
+msgstr ""
+
+#: kallithea/templates/base/perms_summary.html:90
+msgid "No permission defined"
+msgstr ""
+
+#: kallithea/templates/base/root.html:22
+msgid "Add Another Comment"
+msgstr ""
+
+#: kallithea/templates/base/root.html:23
+#: kallithea/templates/data_table/_dt_elements.html:214
+msgid "Stop following this repository"
+msgstr ""
+
+#: kallithea/templates/base/root.html:24
+msgid "Start following this repository"
+msgstr ""
+
+#: kallithea/templates/base/root.html:25
+msgid "Group"
+msgstr ""
+
+#: kallithea/templates/base/root.html:26
+msgid "members"
+msgstr ""
+
+#: kallithea/templates/base/root.html:27
+msgid "Loading ..."
+msgstr ""
+
+#: kallithea/templates/base/root.html:28
+msgid "loading ..."
+msgstr ""
+
+#: kallithea/templates/base/root.html:29
+msgid "Search truncated"
+msgstr ""
+
+#: kallithea/templates/base/root.html:30
+msgid "No matching files"
+msgstr ""
+
+#: kallithea/templates/base/root.html:31
+msgid "Open New Pull Request from {0}"
+msgstr ""
+
+#: kallithea/templates/base/root.html:32
+msgid "Open New Pull Request for {0} &rarr; {1}"
+msgstr ""
+
+#: kallithea/templates/base/root.html:33
+msgid "Show Selected Changesets {0} &rarr; {1}"
+msgstr ""
+
+#: kallithea/templates/base/root.html:34
+msgid "Selection Link"
+msgstr ""
+
+#: kallithea/templates/base/root.html:35
+#: kallithea/templates/changeset/diff_block.html:8
+#: kallithea/templates/changeset/diff_block.html:21
+msgid "Collapse Diff"
+msgstr ""
+
+#: kallithea/templates/base/root.html:36
+msgid "Expand Diff"
+msgstr ""
+
+#: kallithea/templates/base/root.html:37
+msgid "Failed to revoke permission"
+msgstr ""
+
+#: kallithea/templates/base/root.html:38
+msgid "Confirm to revoke permission for {0}: {1} ?"
+msgstr ""
+
+#: kallithea/templates/base/root.html:39
+msgid "enabled"
+msgstr ""
+
+#: kallithea/templates/base/root.html:40
+msgid "disabled"
+msgstr ""
+
+#: kallithea/templates/base/root.html:42
+msgid "Specify changeset"
+msgstr ""
+
+#: kallithea/templates/bookmarks/bookmarks.html:5
+#, python-format
+msgid "%s Bookmarks"
+msgstr ""
+
+#: kallithea/templates/bookmarks/bookmarks.html:26
+msgid "Compare Bookmarks"
+msgstr ""
+
+#: kallithea/templates/bookmarks/bookmarks.html:53
+#: kallithea/templates/bookmarks/bookmarks_data.html:10
+#: kallithea/templates/branches/branches.html:53
+#: kallithea/templates/branches/branches_data.html:10
+#: kallithea/templates/changelog/changelog_summary_data.html:10
+#: kallithea/templates/tags/tags.html:53
+#: kallithea/templates/tags/tags_data.html:10
+msgid "Author"
+msgstr ""
+
+#: kallithea/templates/bookmarks/bookmarks.html:54
+#: kallithea/templates/bookmarks/bookmarks_data.html:12
+#: kallithea/templates/branches/branches.html:54
+#: kallithea/templates/branches/branches_data.html:12
+#: kallithea/templates/changelog/changelog_summary_data.html:7
+#: kallithea/templates/files/files_browser.html:32
+#: kallithea/templates/pullrequests/pullrequest.html:62
+#: kallithea/templates/pullrequests/pullrequest.html:78
+#: kallithea/templates/tags/tags.html:54
+#: kallithea/templates/tags/tags_data.html:12
+msgid "Revision"
+msgstr ""
+
+#: kallithea/templates/branches/branches.html:5
+#, python-format
+msgid "%s Branches"
+msgstr ""
+
+#: kallithea/templates/branches/branches.html:26
+msgid "Compare Branches"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:6
+#, python-format
+msgid "%s Changelog"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:21
+#, python-format
+msgid "showing %d out of %d revision"
+msgid_plural "showing %d out of %d revisions"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/changelog/changelog.html:49
+msgid "Clear selection"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:55
+msgid "Go to tip of repository"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:60
+#: kallithea/templates/forks/forks_data.html:19
+#, python-format
+msgid "Compare fork with %s"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:62
+#, python-format
+msgid "Compare fork with parent repository (%s)"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:66
+#: kallithea/templates/files/files.html:29
+msgid "Branch filter:"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:92
+#: kallithea/templates/changelog/changelog_summary_data.html:20
+#, python-format
+msgid ""
+"Changeset status: %s\n"
+"Click to open associated pull request %s"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:96
+#: kallithea/templates/compare/compare_cs.html:24
+#, python-format
+msgid "Changeset status: %s"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:115
+#: kallithea/templates/compare/compare_cs.html:63
+msgid "Expand commit message"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:124
+#: kallithea/templates/compare/compare_cs.html:30
+msgid "Changeset has comments"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:134
+#: kallithea/templates/changelog/changelog_summary_data.html:54
+#: kallithea/templates/changeset/changeset.html:94
+#: kallithea/templates/changeset/changeset_range.html:92
+#, python-format
+msgid "Bookmark %s"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:140
+#: kallithea/templates/changelog/changelog_summary_data.html:60
+#: kallithea/templates/changeset/changeset.html:101
+#: kallithea/templates/changeset/changeset_range.html:98
+#: kallithea/templates/compare/compare_cs.html:69
+#: kallithea/templates/pullrequests/pullrequest_show.html:203
+#, python-format
+msgid "Tag %s"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:145
+#: kallithea/templates/changelog/changelog_summary_data.html:65
+#: kallithea/templates/changeset/changeset.html:106
+#: kallithea/templates/changeset/changeset_range.html:102
+#, python-format
+msgid "Branch %s"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:310
+msgid "There are no changes yet"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_details.html:4
+#: kallithea/templates/changeset/changeset.html:77
+msgid "Removed"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_details.html:5
+#: kallithea/templates/changeset/changeset.html:78
+msgid "Changed"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_details.html:6
+#: kallithea/templates/changeset/changeset.html:79
+#: kallithea/templates/changeset/diff_block.html:47
+msgid "Added"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_details.html:8
+#: kallithea/templates/changelog/changelog_details.html:9
+#: kallithea/templates/changelog/changelog_details.html:10
+#: kallithea/templates/changeset/changeset.html:81
+#: kallithea/templates/changeset/changeset.html:82
+#: kallithea/templates/changeset/changeset.html:83
+#, python-format
+msgid "Affected %s files"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_summary_data.html:8
+#: kallithea/templates/files/files_add.html:60
+#: kallithea/templates/files/files_delete.html:39
+#: kallithea/templates/files/files_edit.html:63
+msgid "Commit Message"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_summary_data.html:9
+#: kallithea/templates/pullrequests/pullrequest_data.html:17
+msgid "Age"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_summary_data.html:11
+msgid "Refs"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_summary_data.html:81
+msgid "Add or upload files directly via Kallithea"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_summary_data.html:84
+#: kallithea/templates/files/files_add.html:21
+#: kallithea/templates/files/files_ypjax.html:9
+msgid "Add New File"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_summary_data.html:90
+msgid "Push new repository"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog_summary_data.html:98
+msgid "Existing repository?"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:8
+#, python-format
+msgid "%s Changeset"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:36
+msgid "Parent rev."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:42
+msgid "Child rev."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:50
+#: kallithea/templates/changeset/changeset_file_comment.html:39
+#: kallithea/templates/changeset/changeset_range.html:48
+msgid "Changeset status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:54
+#: kallithea/templates/changeset/diff_block.html:72
+#: kallithea/templates/files/diff_2way.html:49
+msgid "Raw diff"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:57
+msgid "Patch diff"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:60
+#: kallithea/templates/changeset/diff_block.html:75
+#: kallithea/templates/files/diff_2way.html:52
+msgid "Download diff"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:89
+#: kallithea/templates/changeset/changeset_range.html:88
+msgid "Merge"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:123
+msgid "Grafted from:"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:129
+msgid "Transplanted from:"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:135
+msgid "Replaced by:"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:149
+msgid "Preceded by:"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:166
+#: kallithea/templates/compare/compare_diff.html:60
+#: kallithea/templates/pullrequests/pullrequest_show.html:329
+#, python-format
+msgid "%s file changed"
+msgid_plural "%s files changed"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/changeset/changeset.html:168
+#: kallithea/templates/compare/compare_diff.html:62
+#: kallithea/templates/pullrequests/pullrequest_show.html:331
+#, python-format
+msgid "%s file changed with %s insertions and %s deletions"
+msgid_plural "%s files changed with %s insertions and %s deletions"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/changeset/changeset.html:182
+#: kallithea/templates/changeset/changeset.html:195
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
+msgid "Show full diff anyway"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset.html:231
+#: kallithea/templates/changeset/changeset.html:268
+msgid "No revisions"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:21
+msgid "on pull request"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:22
+msgid "No title"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:24
+msgid "on this changeset"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+msgid "Delete comment?"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:39
+msgid "Status change"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:59
+msgid "Commenting on line."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:60
+msgid "Comments are in plain text. Use @username inside this text to notify another user."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:67
+msgid "Set changeset status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:69
+msgid "Vote for pull request status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:75
+msgid "No change"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:88
+msgid "Finish pull request"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:91
+msgid "Close"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:103
+msgid "Submitting ..."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:104
+msgid "Comment"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:112
+msgid "You need to be logged in to comment."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:112
+msgid "Login now"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:116
+msgid "Hide"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:128
+#, python-format
+msgid "%d comment"
+msgid_plural "%d comments"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:129
+#, python-format
+msgid "%d inline"
+msgid_plural "%d inline"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:130
+#, python-format
+msgid "%d general"
+msgid_plural "%d general"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/changeset/changeset_range.html:5
+#, python-format
+msgid "%s Changesets"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_range.html:56
+msgid "Files affected"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:54
+msgid "Deleted"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:57
+msgid "Renamed"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:66
+#: kallithea/templates/files/diff_2way.html:43
+msgid "Show full diff for this file"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:69
+#: kallithea/templates/files/diff_2way.html:46
+msgid "Show full side-by-side diff for this file"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:83
+msgid "Show inline comments"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:4
+msgid "No changesets"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:8
+msgid "Ancestor"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:44
+msgid "First (oldest) changeset in this list"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:46
+msgid "Last (most recent) changeset in this list"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:48
+msgid "Position in this list of changesets"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:85
+msgid "Show merge diff"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:95
+#: kallithea/templates/pullrequests/pullrequest_show.html:321
+msgid "Common ancestor"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:99
+msgid "No common ancestor found - repositories are unrelated"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:107
+msgid "is"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:108
+#, python-format
+msgid "%s changesets"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:109
+msgid "behind"
+msgstr ""
+
+#: kallithea/templates/compare/compare_diff.html:6
+#: kallithea/templates/compare/compare_diff.html:8
+#, python-format
+msgid "%s Compare"
+msgstr ""
+
+#: kallithea/templates/compare/compare_diff.html:13
+#: kallithea/templates/compare/compare_diff.html:41
+msgid "Compare Revisions"
+msgstr ""
+
+#: kallithea/templates/compare/compare_diff.html:39
+msgid "Swap"
+msgstr ""
+
+#: kallithea/templates/compare/compare_diff.html:48
+msgid "Compare revisions, branches, bookmarks, or tags."
+msgstr ""
+
+#: kallithea/templates/compare/compare_diff.html:53
+#: kallithea/templates/pullrequests/pullrequest_show.html:316
+#, python-format
+msgid "Showing %s commit"
+msgid_plural "Showing %s commits"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+msgid "Show full diff"
+msgstr ""
+
+#: kallithea/templates/data_table/_dt_elements.html:74
+msgid "Public repository"
+msgstr ""
+
+#: kallithea/templates/data_table/_dt_elements.html:84
+msgid "Repository creation in progress..."
+msgstr ""
+
+#: kallithea/templates/data_table/_dt_elements.html:98
+msgid "No changesets yet"
+msgstr ""
+
+#: kallithea/templates/data_table/_dt_elements.html:105
+#: kallithea/templates/data_table/_dt_elements.html:107
+#, python-format
+msgid "Subscribe to %s rss feed"
+msgstr ""
+
+#: kallithea/templates/data_table/_dt_elements.html:113
+#: kallithea/templates/data_table/_dt_elements.html:115
+#, python-format
+msgid "Subscribe to %s atom feed"
+msgstr ""
+
+#: kallithea/templates/data_table/_dt_elements.html:139
+msgid "Creating"
+msgstr ""
+
+#: kallithea/templates/email_templates/changeset_comment.html:5
+#, python-format
+msgid "Comment from %s on %s changeset %s mentioned you"
+msgstr ""
+
+#: kallithea/templates/email_templates/changeset_comment.html:7
+#, python-format
+msgid "Comment from %s on %s changeset %s"
+msgstr ""
+
+#: kallithea/templates/email_templates/changeset_comment.html:12
+msgid "The changeset status was changed to"
+msgstr ""
+
+#: kallithea/templates/email_templates/main.html:6
+msgid "This is an automatic notification. Don't reply to this mail."
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:4
+#, python-format
+msgid "Hello %s"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:6
+msgid "We have received a request to reset the password for your account."
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:8
+msgid "This account is however managed outside this system and the password cannot be changed here."
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:10
+msgid "To set a new password, click the following link"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:13
+msgid "Should you not be able to use the link above, please type the following code into the password reset form"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:16
+msgid "If it weren't you who requested the password reset, just disregard this message."
+msgstr ""
+
+#: kallithea/templates/email_templates/pull_request.html:5
+#, python-format
+msgid "%s mentioned you on %s pull request \"%s\""
+msgstr ""
+
+#: kallithea/templates/email_templates/pull_request.html:7
+#, python-format
+msgid "%s requested your review of %s pull request \"%s\""
+msgstr ""
+
+#: kallithea/templates/email_templates/pull_request_comment.html:4
+#, python-format
+msgid "Comment from %s on %s pull request \"%s\""
+msgstr ""
+
+#: kallithea/templates/email_templates/pull_request_comment.html:9
+msgid "The comment closed the pull request with status"
+msgstr ""
+
+#: kallithea/templates/email_templates/pull_request_comment.html:11
+msgid "The comment was made with status"
+msgstr ""
+
+#: kallithea/templates/email_templates/registration.html:6
+msgid "View this user here"
+msgstr ""
+
+#: kallithea/templates/files/diff_2way.html:15
+#, python-format
+msgid "%s File side-by-side diff"
+msgstr ""
+
+#: kallithea/templates/files/diff_2way.html:19
+#: kallithea/templates/files/file_diff.html:8
+msgid "File diff"
+msgstr ""
+
+#: kallithea/templates/files/file_diff.html:4
+#, python-format
+msgid "%s File Diff"
+msgstr ""
+
+#: kallithea/templates/files/files.html:4
+#: kallithea/templates/files/files.html:80
+#, python-format
+msgid "%s Files"
+msgstr ""
+
+#: kallithea/templates/files/files_add.html:4
+#, python-format
+msgid "%s Files Add"
+msgstr ""
+
+#: kallithea/templates/files/files_add.html:40
+#: kallithea/templates/files/files_edit.html:38
+#: kallithea/templates/files/files_ypjax.html:3
+msgid "Location"
+msgstr ""
+
+#: kallithea/templates/files/files_add.html:42
+msgid "Enter filename..."
+msgstr ""
+
+#: kallithea/templates/files/files_add.html:44
+#: kallithea/templates/files/files_add.html:48
+msgid "or"
+msgstr ""
+
+#: kallithea/templates/files/files_add.html:44
+msgid "Upload File"
+msgstr ""
+
+#: kallithea/templates/files/files_add.html:48
+msgid "Create New File"
+msgstr ""
+
+#: kallithea/templates/files/files_add.html:53
+msgid "New file type"
+msgstr ""
+
+#: kallithea/templates/files/files_add.html:64
+#: kallithea/templates/files/files_delete.html:43
+#: kallithea/templates/files/files_edit.html:67
+msgid "Commit Changes"
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:33
+msgid "Previous revision"
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:35
+msgid "Next revision"
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:41
+msgid "Follow current branch"
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:44
+msgid "Search File List"
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:48
+msgid "Loading file list..."
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:61
+msgid "Size"
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:62
+msgid "Last Revision"
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:63
+msgid "Last Modified"
+msgstr ""
+
+#: kallithea/templates/files/files_browser.html:64
+msgid "Last Committer"
+msgstr ""
+
+#: kallithea/templates/files/files_delete.html:4
+#, python-format
+msgid "%s Files Delete"
+msgstr ""
+
+#: kallithea/templates/files/files_delete.html:12
+#: kallithea/templates/files/files_delete.html:31
+msgid "Delete file"
+msgstr ""
+
+#: kallithea/templates/files/files_edit.html:4
+#, python-format
+msgid "%s File Edit"
+msgstr ""
+
+#: kallithea/templates/files/files_edit.html:21
+msgid "Edit file"
+msgstr ""
+
+#: kallithea/templates/files/files_edit.html:48
+#: kallithea/templates/files/files_source.html:32
+msgid "Show Annotation"
+msgstr ""
+
+#: kallithea/templates/files/files_edit.html:50
+#: kallithea/templates/files/files_source.html:35
+msgid "Download as Raw"
+msgstr ""
+
+#: kallithea/templates/files/files_edit.html:53
+msgid "Source"
+msgstr ""
+
+#: kallithea/templates/files/files_edit.html:58
+msgid "Editing file"
+msgstr ""
+
+#: kallithea/templates/files/files_history_box.html:2
+#, python-format
+msgid "%s author"
+msgid_plural "%s authors"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/files/files_source.html:7
+msgid "Diff to Revision"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:8
+msgid "Show at Revision"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:10
+msgid "Show Full History"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:11
+msgid "Show Authors"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:30
+msgid "Show Source"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:38
+#, python-format
+msgid "Edit on Branch:%s"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:41
+msgid "Editing binary files not allowed"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:44
+msgid "Editing files allowed only when on branch head revision"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:45
+msgid "Deleting files allowed only when on branch head revision"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:63
+#, python-format
+msgid "Binary file (%s)"
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:74
+msgid "File is too big to display."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:76
+msgid "Show full annotation anyway."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:78
+msgid "Show as raw."
+msgstr ""
+
+#: kallithea/templates/files/files_ypjax.html:5
+msgid "annotation"
+msgstr ""
+
+#: kallithea/templates/files/files_ypjax.html:23
+msgid "Go Back"
+msgstr ""
+
+#: kallithea/templates/files/files_ypjax.html:24
+msgid "No files at given path"
+msgstr ""
+
+#: kallithea/templates/followers/followers.html:5
+#, python-format
+msgid "%s Followers"
+msgstr ""
+
+#: kallithea/templates/followers/followers.html:9
+#: kallithea/templates/summary/summary.html:142
+#: kallithea/templates/summary/summary.html:143
+msgid "Followers"
+msgstr ""
+
+#: kallithea/templates/followers/followers_data.html:12
+msgid "Started following -"
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:5
+#, python-format
+msgid "Fork repository %s"
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:27
+msgid "Fork name"
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:62
+msgid "Default revision for files page, downloads, whoosh, and readme."
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:68
+msgid "Private"
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:77
+msgid "Copy permissions"
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:81
+msgid "Copy permissions from forked repository"
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:87
+msgid "Update after clone"
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:91
+msgid "Checkout source after making a clone"
+msgstr ""
+
+#: kallithea/templates/forks/fork.html:96
+msgid "Fork this Repository"
+msgstr ""
+
+#: kallithea/templates/forks/forks.html:5
+#, python-format
+msgid "%s Forks"
+msgstr ""
+
+#: kallithea/templates/forks/forks.html:9
+#: kallithea/templates/summary/summary.html:148
+#: kallithea/templates/summary/summary.html:149
+msgid "Forks"
+msgstr ""
+
+#: kallithea/templates/forks/forks_data.html:17
+msgid "Forked"
+msgstr ""
+
+#: kallithea/templates/forks/forks_data.html:30
+msgid "There are no forks yet"
+msgstr ""
+
+#: kallithea/templates/journal/journal.html:21
+msgid "ATOM journal feed"
+msgstr ""
+
+#: kallithea/templates/journal/journal.html:22
+msgid "RSS journal feed"
+msgstr ""
+
+#: kallithea/templates/journal/journal.html:56
+msgid "My Repositories"
+msgstr ""
+
+#: kallithea/templates/journal/journal_data.html:43
+msgid "No entries yet"
+msgstr ""
+
+#: kallithea/templates/journal/public_journal.html:13
+msgid "ATOM public journal feed"
+msgstr ""
+
+#: kallithea/templates/journal/public_journal.html:14
+msgid "RSS public journal feed"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest.html:4
+#: kallithea/templates/pullrequests/pullrequest.html:8
+msgid "New Pull Request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest.html:31
+#: kallithea/templates/pullrequests/pullrequest_data.html:15
+#: kallithea/templates/pullrequests/pullrequest_show.html:29
+#: kallithea/templates/pullrequests/pullrequest_show.html:54
+msgid "Title"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest.html:34
+msgid "Summarize the changes - or leave empty"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest.html:43
+#: kallithea/templates/pullrequests/pullrequest_show.html:66
+msgid "Write a short description on this pull request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest.html:49
+msgid "Changeset flow"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest.html:56
+msgid "Origin repository"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest.html:72
+msgid "Destination repository"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:6
+msgid "No entries"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:14
+msgid "Vote"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:18
+msgid "From"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:19
+msgid "To"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:28
+#, python-format
+msgid "You voted: %s"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:30
+msgid "You didn't vote"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:35
+msgid "(no title)"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:37
+#: kallithea/templates/pullrequests/pullrequest_show.html:31
+#: kallithea/templates/pullrequests/pullrequest_show.html:83
+msgid "Closed"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:67
+msgid "Delete Pull Request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:68
+msgid "Confirm to delete this pull request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_data.html:70
+#, python-format
+msgid "Confirm again to delete this pull request with %s comments"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:6
+#, python-format
+msgid "%s Pull Request %s"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:10
+#, python-format
+msgid "Pull request %s from %s#%s"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:57
+msgid "Summarize the changes"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:74
+msgid "Reviewer voting result"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:80
+#: kallithea/templates/pullrequests/pullrequest_show.html:81
+msgid "Pull request status calculated from votes"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:93
+msgid "Still not reviewed by"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:97
+#, python-format
+msgid "%d reviewer"
+msgid_plural "%d reviewers"
+msgstr[0] ""
+msgstr[1] ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:99
+msgid "Pull request was reviewed by all reviewers"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:101
+msgid "There are no reviewers"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:107
+msgid "Origin"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:113
+msgid "on"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:120
+msgid "Target"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:124
+msgid "This is just a range of changesets and doesn't have a target or a real merge ancestor."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:133
+msgid "Pull changes"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:173
+msgid "Update"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:191
+msgid "Current revision - no change"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:215
+msgid "Pull requests do not change once created. Select a revision and save to replace this pull request with a new one."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:224
+msgid "Pull Request Reviewers"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:249
+msgid "Remove reviewer"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:261
+msgid "Type name of reviewer to add"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:269
+msgid "Potential Reviewers"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:272
+msgid "Click to add the repository owner as reviewer:"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:295
+msgid "Save Changes"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:296
+msgid "Save Updates as New Pull Request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:297
+msgid "Cancel Changes"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:307
+msgid "Pull Request Content"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:6
+#, python-format
+msgid "%s Pull Requests"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:11
+#, python-format
+msgid "Pull Requests from '%s'"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:13
+#, python-format
+msgid "Pull Requests to '%s'"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:32
+msgid "Open New Pull Request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:37
+#, python-format
+msgid "Show Pull Requests to %s"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:39
+#, python-format
+msgid "Show Pull Requests from '%s'"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:49
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:28
+msgid "Hide closed pull requests (only show open pull requests)"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_all.html:51
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:30
+msgid "Show closed pull requests (in addition to open pull requests)"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:35
+msgid "Pull Requests Created by Me"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show_my.html:38
+msgid "Pull Requests I Participate In"
+msgstr ""
+
+#: kallithea/templates/search/search.html:6
+#, python-format
+msgid "%s Search"
+msgstr ""
+
+#: kallithea/templates/search/search.html:8
+#: kallithea/templates/search/search.html:16
+msgid "Search in All Repositories"
+msgstr ""
+
+#: kallithea/templates/search/search.html:50
+msgid "Search term"
+msgstr ""
+
+#: kallithea/templates/search/search.html:62
+msgid "Search in"
+msgstr ""
+
+#: kallithea/templates/search/search.html:65
+msgid "File contents"
+msgstr ""
+
+#: kallithea/templates/search/search.html:66
+msgid "Commit messages"
+msgstr ""
+
+#: kallithea/templates/search/search.html:67
+msgid "File names"
+msgstr ""
+
+#: kallithea/templates/search/search_commit.html:35
+#: kallithea/templates/search/search_content.html:21
+#: kallithea/templates/search/search_path.html:15
+msgid "Permission denied"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:4
+#, python-format
+msgid "%s Statistics"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:16
+#: kallithea/templates/summary/summary.html:39
+#, python-format
+msgid "%s ATOM feed"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:17
+#: kallithea/templates/summary/summary.html:40
+#, python-format
+msgid "%s RSS feed"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:36
+#: kallithea/templates/summary/summary.html:100
+#: kallithea/templates/summary/summary.html:116
+msgid "Enable"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:39
+msgid "Stats gathered: "
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:89
+#: kallithea/templates/summary/summary.html:349
+msgid "files"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:113
+#: kallithea/templates/summary/summary.html:373
+msgid "Show more"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:390
+msgid "commits"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:391
+msgid "files added"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:392
+msgid "files changed"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:393
+msgid "files removed"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:395
+msgid "commit"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:396
+msgid "file added"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:397
+msgid "file changed"
+msgstr ""
+
+#: kallithea/templates/summary/statistics.html:398
+msgid "file removed"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:4
+#, python-format
+msgid "%s Summary"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:13
+#, python-format
+msgid "Repository locked by %s"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:15
+msgid "Repository unlocked"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:22
+msgid "Fork of"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:29
+msgid "Clone from"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:72
+msgid "Clone URL"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:78
+msgid "Show by Name"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:79
+msgid "Show by ID"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:92
+msgid "Trending files"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:108
+msgid "Download"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:112
+msgid "There are no downloads yet"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:114
+msgid "Downloads are disabled for this repository"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:120
+msgid "Download as zip"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:125
+msgid "Check this to download archive with subrepos"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:125
+msgid "With subrepos"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:156
+msgid "Repository Size"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:163
+#: kallithea/templates/summary/summary.html:165
+msgid "Feed"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:186
+msgid "Latest Changes"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:188
+msgid "Quick Start"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:202
+#, python-format
+msgid "Readme file from revision %s:%s"
+msgstr ""
+
+#: kallithea/templates/summary/summary.html:293
+#, python-format
+msgid "Download %s as %s"
+msgstr ""
+
+#: kallithea/templates/tags/tags.html:5
+#, python-format
+msgid "%s Tags"
+msgstr ""
+
+#: kallithea/templates/tags/tags.html:26
+msgid "Compare Tags"
+msgstr ""
--- a/kallithea/i18n/fr/LC_MESSAGES/kallithea.po	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/i18n/fr/LC_MESSAGES/kallithea.po	Fri Nov 18 01:11:13 2016 +0100
@@ -7,24 +7,24 @@
 msgstr ""
 "Project-Id-Version: Kallithea 0.3\n"
 "Report-Msgid-Bugs-To: translations@kallithea-scm.org\n"
-"POT-Creation-Date: 2015-09-08 10:34+0200\n"
-"PO-Revision-Date: 2015-09-10 15:13+0200\n"
+"POT-Creation-Date: 2016-03-14 16:51+0100\n"
+"PO-Revision-Date: 2016-03-21 13:00+0000\n"
 "Last-Translator: Étienne Gilli <etienne.gilli@gmail.com>\n"
 "Language-Team: French "
-"<https://hosted.weblate.org/projects/kallithea/stable/fr/>\n"
+"<https://hosted.weblate.org/projects/kallithea/kallithea/fr/>\n"
 "Language: fr\n"
 "MIME-Version: 1.0\n"
 "Content-Type: text/plain; charset=UTF-8\n"
 "Content-Transfer-Encoding: 8bit\n"
 "Plural-Forms: nplurals=2; plural=n > 1;\n"
-"X-Generator: Weblate 2.4-dev\n"
-
-#: kallithea/controllers/changelog.py:86
-#: kallithea/controllers/pullrequests.py:238 kallithea/lib/base.py:512
+"X-Generator: Weblate 2.6-dev\n"
+
+#: kallithea/controllers/changelog.py:85
+#: kallithea/controllers/pullrequests.py:240 kallithea/lib/base.py:515
 msgid "There are no changesets yet"
 msgstr "Il n’y a aucun changement pour le moment"
 
-#: kallithea/controllers/changelog.py:166
+#: kallithea/controllers/changelog.py:164
 #: kallithea/controllers/admin/permissions.py:61
 #: kallithea/controllers/admin/permissions.py:65
 #: kallithea/controllers/admin/permissions.py:69
@@ -36,37 +36,29 @@
 msgid "None"
 msgstr "Aucun"
 
-#: kallithea/controllers/changelog.py:169 kallithea/controllers/files.py:196
+#: kallithea/controllers/changelog.py:167 kallithea/controllers/files.py:198
 msgid "(closed)"
 msgstr "(fermé)"
 
-#: kallithea/controllers/changeset.py:89
+#: kallithea/controllers/changeset.py:88
 msgid "Show whitespace"
 msgstr "Afficher les espaces et tabulations"
 
-#: kallithea/controllers/changeset.py:96 kallithea/controllers/changeset.py:103
+#: kallithea/controllers/changeset.py:95 kallithea/controllers/changeset.py:102
 #: kallithea/templates/files/diff_2way.html:55
 msgid "Ignore whitespace"
 msgstr "Ignorer les espaces et tabulations"
 
-#: kallithea/controllers/changeset.py:169
+#: kallithea/controllers/changeset.py:168
 #, python-format
 msgid "Increase diff context to %(num)s lines"
 msgstr "Augmenter le contexte du diff à %(num)s lignes"
 
-#: kallithea/controllers/changeset.py:212 kallithea/controllers/files.py:96
-#: kallithea/controllers/files.py:116 kallithea/controllers/files.py:742
+#: kallithea/controllers/changeset.py:233 kallithea/controllers/files.py:97
+#: kallithea/controllers/files.py:117 kallithea/controllers/files.py:744
 msgid "Such revision does not exist for this repository"
 msgstr "Une telle révision n'existe pas pour ce dépôt"
 
-#: kallithea/controllers/changeset.py:383
-msgid ""
-"Changing status on a changeset associated with a closed pull request is "
-"not allowed"
-msgstr ""
-"La modification de l'état sur un ensemble de modifications associé à une "
-"demande de tirage fermé n'est pas autorisé"
-
 #: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:41
 msgid "Select changeset"
 msgstr "Sélectionner le changeset"
@@ -122,10 +114,10 @@
 #: kallithea/controllers/feed.py:87
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Changeset was too big and was cut off..."
 msgstr "Cet ensemble de changements était trop important et a été découpé…"
 
@@ -134,117 +126,117 @@
 msgid "%s committed on %s"
 msgstr "%s a commité, le %s"
 
-#: kallithea/controllers/files.py:91
+#: kallithea/controllers/files.py:92
 msgid "Click here to add new file"
 msgstr "Ajouter un nouveau fichier"
 
-#: kallithea/controllers/files.py:92
+#: kallithea/controllers/files.py:93
 #, python-format
 msgid "There are no files yet. %s"
 msgstr "Il n'y a actuellement pas de fichiers. %s"
 
-#: kallithea/controllers/files.py:193
+#: kallithea/controllers/files.py:195
 #, python-format
 msgid "%s at %s"
 msgstr "%s à %s"
 
-#: kallithea/controllers/files.py:305 kallithea/controllers/files.py:365
-#: kallithea/controllers/files.py:432
+#: kallithea/controllers/files.py:307 kallithea/controllers/files.py:367
+#: kallithea/controllers/files.py:434
 #, python-format
 msgid "This repository has been locked by %s on %s"
 msgstr "Ce dépôt a été verrouillé par %s sur %s"
 
-#: kallithea/controllers/files.py:317
-msgid "You can only delete files with revision being a valid branch "
+#: kallithea/controllers/files.py:319
+msgid "You can only delete files with revision being a valid branch"
 msgstr ""
-"Vous pouvez supprimer uniquement les fichiers avec révision étant dans "
-"une branche valide "
-
-#: kallithea/controllers/files.py:328
+"Vous ne pouvez supprimer que les fichiers dont la révision est une branche "
+"valide"
+
+#: kallithea/controllers/files.py:330
 #, python-format
 msgid "Deleted file %s via Kallithea"
 msgstr "Le fichier %s a été supprimé via Kallithea"
 
-#: kallithea/controllers/files.py:350
+#: kallithea/controllers/files.py:352
 #, python-format
 msgid "Successfully deleted file %s"
 msgstr "Suppression du fichier %s effectuée avec succès"
 
-#: kallithea/controllers/files.py:354 kallithea/controllers/files.py:420
-#: kallithea/controllers/files.py:501
+#: kallithea/controllers/files.py:356 kallithea/controllers/files.py:422
+#: kallithea/controllers/files.py:503
 msgid "Error occurred during commit"
 msgstr "Une erreur est survenue durant le commit"
 
-#: kallithea/controllers/files.py:377
-msgid "You can only edit files with revision being a valid branch "
+#: kallithea/controllers/files.py:379
+msgid "You can only edit files with revision being a valid branch"
 msgstr ""
-"Vous pouvez modifier uniquement les fichiers dont la révision est dans "
-"une branche valide "
-
-#: kallithea/controllers/files.py:391
+"Vous ne pouvez modifier que les fichiers dont la révision est une branche "
+"valide"
+
+#: kallithea/controllers/files.py:393
 #, python-format
 msgid "Edited file %s via Kallithea"
 msgstr "%s édité via Kallithea"
 
-#: kallithea/controllers/files.py:407
+#: kallithea/controllers/files.py:409
 msgid "No changes"
 msgstr "Aucun changement"
 
-#: kallithea/controllers/files.py:416 kallithea/controllers/files.py:490
+#: kallithea/controllers/files.py:418 kallithea/controllers/files.py:492
 #, python-format
 msgid "Successfully committed to %s"
 msgstr "Commit réalisé avec succès sur %s"
 
-#: kallithea/controllers/files.py:443
+#: kallithea/controllers/files.py:445
 msgid "Added file via Kallithea"
 msgstr "%s ajouté par Kallithea"
 
-#: kallithea/controllers/files.py:464
+#: kallithea/controllers/files.py:466
 msgid "No content"
 msgstr "Aucun contenu"
 
-#: kallithea/controllers/files.py:468
+#: kallithea/controllers/files.py:470
 msgid "No filename"
 msgstr "Aucun nom de fichier"
 
-#: kallithea/controllers/files.py:493
+#: kallithea/controllers/files.py:495
 msgid "Location must be relative path and must not contain .. in path"
 msgstr ""
 "Le chemin doit être un chemin relatif et ne doit pas contenir .. dans le "
 "chemin"
 
-#: kallithea/controllers/files.py:526
+#: kallithea/controllers/files.py:528
 msgid "Downloads disabled"
 msgstr "Les téléchargements sont désactivés"
 
-#: kallithea/controllers/files.py:537
+#: kallithea/controllers/files.py:539
 #, python-format
 msgid "Unknown revision %s"
 msgstr "Révision %s inconnue"
 
-#: kallithea/controllers/files.py:539
+#: kallithea/controllers/files.py:541
 msgid "Empty repository"
 msgstr "Dépôt vide"
 
-#: kallithea/controllers/files.py:541
+#: kallithea/controllers/files.py:543
 msgid "Unknown archive type"
 msgstr "Type d’archive inconnu"
 
-#: kallithea/controllers/files.py:771
+#: kallithea/controllers/files.py:773
 #: kallithea/templates/changeset/changeset_range.html:9
 #: kallithea/templates/email_templates/pull_request.html:15
 #: kallithea/templates/pullrequests/pullrequest.html:97
 msgid "Changesets"
 msgstr "Changesets"
 
-#: kallithea/controllers/files.py:772 kallithea/controllers/pullrequests.py:176
-#: kallithea/model/scm.py:820 kallithea/templates/switch_to_list.html:3
+#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:175
+#: kallithea/model/scm.py:716 kallithea/templates/switch_to_list.html:3
 #: kallithea/templates/branches/branches.html:10
 msgid "Branches"
 msgstr "Branches"
 
-#: kallithea/controllers/files.py:773 kallithea/controllers/pullrequests.py:177
-#: kallithea/model/scm.py:831 kallithea/templates/switch_to_list.html:25
+#: kallithea/controllers/files.py:775 kallithea/controllers/pullrequests.py:176
+#: kallithea/model/scm.py:727 kallithea/templates/switch_to_list.html:25
 #: kallithea/templates/tags/tags.html:10
 msgid "Tags"
 msgstr "Tags"
@@ -258,7 +250,7 @@
 msgid "Groups"
 msgstr "Groupes"
 
-#: kallithea/controllers/home.py:89
+#: kallithea/controllers/home.py:94
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:106
 #: kallithea/templates/admin/repos/repo_add.html:12
 #: kallithea/templates/admin/repos/repo_add.html:16
@@ -266,23 +258,27 @@
 #: kallithea/templates/admin/users/user_edit_advanced.html:6
 #: kallithea/templates/base/base.html:60 kallithea/templates/base/base.html:77
 #: kallithea/templates/base/base.html:124
-#: kallithea/templates/base/base.html:390
-#: kallithea/templates/base/base.html:562
+#: kallithea/templates/base/base.html:479
+#: kallithea/templates/base/base.html:653
 msgid "Repositories"
 msgstr "Dépôts"
 
-#: kallithea/controllers/home.py:130
+#: kallithea/controllers/home.py:139
 #: kallithea/templates/files/files_add.html:32
 #: kallithea/templates/files/files_delete.html:23
 #: kallithea/templates/files/files_edit.html:32
 msgid "Branch"
 msgstr "Branche"
 
-#: kallithea/controllers/home.py:136
+#: kallithea/controllers/home.py:145 kallithea/templates/switch_to_list.html:16
+msgid "Closed Branches"
+msgstr "Branches fermées"
+
+#: kallithea/controllers/home.py:151
 msgid "Tag"
 msgstr "Étiquette"
 
-#: kallithea/controllers/home.py:142
+#: kallithea/controllers/home.py:157
 msgid "Bookmark"
 msgstr "Signet"
 
@@ -293,103 +289,100 @@
 msgstr "Journal public"
 
 #: kallithea/controllers/journal.py:115 kallithea/controllers/journal.py:157
-#: kallithea/templates/base/base.html:222
+#: kallithea/templates/base/base.html:306
 #: kallithea/templates/journal/journal.html:4
 #: kallithea/templates/journal/journal.html:12
 msgid "Journal"
 msgstr "Historique"
 
-#: kallithea/controllers/login.py:151 kallithea/controllers/login.py:197
+#: kallithea/controllers/login.py:144 kallithea/controllers/login.py:190
 msgid "Bad captcha"
 msgstr "Mauvais captcha"
 
-#: kallithea/controllers/login.py:157
-msgid "You have successfully registered into Kallithea"
-msgstr "Vous vous êtes inscrits avec succès à Kallithea"
-
-#: kallithea/controllers/login.py:202
-#| msgid "Your password reset link was sent"
+#: kallithea/controllers/login.py:150
+msgid "You have successfully registered with %s"
+msgstr "Vous vous êtes inscrits avec succès à %s"
+
+#: kallithea/controllers/login.py:195
 msgid "A password reset confirmation code has been sent"
-msgstr ""
-"Un lien de confirmation de réinitialisation de mot de passe a été envoyé"
-
-#: kallithea/controllers/login.py:251
-#| msgid "Password reset link"
+msgstr "Un lien de confirmation de réinitialisation de mot de passe a été envoyé"
+
+#: kallithea/controllers/login.py:244
 msgid "Invalid password reset token"
 msgstr "Clé de réinitialisation de mot de passe invalide"
 
-#: kallithea/controllers/login.py:256
+#: kallithea/controllers/login.py:249
 #: kallithea/controllers/admin/my_account.py:167
 msgid "Successfully updated password"
 msgstr "Mot de passe mis à jour avec succès"
 
-#: kallithea/controllers/pullrequests.py:124
+#: kallithea/controllers/pullrequests.py:123
 #, python-format
 msgid "%s (closed)"
 msgstr "%s (fermé)"
 
-#: kallithea/controllers/pullrequests.py:152
+#: kallithea/controllers/pullrequests.py:151
 #: kallithea/templates/changeset/changeset.html:12
 #: kallithea/templates/email_templates/changeset_comment.html:17
 msgid "Changeset"
 msgstr "Changements"
 
-#: kallithea/controllers/pullrequests.py:173
+#: kallithea/controllers/pullrequests.py:172
 msgid "Special"
 msgstr "Spécial"
 
-#: kallithea/controllers/pullrequests.py:174
+#: kallithea/controllers/pullrequests.py:173
 msgid "Peer branches"
 msgstr "Branches appairées"
 
-#: kallithea/controllers/pullrequests.py:175 kallithea/model/scm.py:826
+#: kallithea/controllers/pullrequests.py:174 kallithea/model/scm.py:722
 #: kallithea/templates/switch_to_list.html:38
 #: kallithea/templates/bookmarks/bookmarks.html:10
 msgid "Bookmarks"
 msgstr "Signets"
 
-#: kallithea/controllers/pullrequests.py:310
+#: kallithea/controllers/pullrequests.py:312
 #, python-format
 msgid "Error creating pull request: %s"
 msgstr "Erreur de création de la demande de pull : %s"
 
-#: kallithea/controllers/pullrequests.py:356
-#: kallithea/controllers/pullrequests.py:503
+#: kallithea/controllers/pullrequests.py:358
+#: kallithea/controllers/pullrequests.py:505
 msgid "No description"
 msgstr "Aucune description"
 
-#: kallithea/controllers/pullrequests.py:363
+#: kallithea/controllers/pullrequests.py:365
 msgid "Successfully opened new pull request"
 msgstr "La requête de pull a été ouverte avec succès"
 
-#: kallithea/controllers/pullrequests.py:366
-#: kallithea/controllers/pullrequests.py:453
-#: kallithea/controllers/pullrequests.py:509
+#: kallithea/controllers/pullrequests.py:368
+#: kallithea/controllers/pullrequests.py:455
+#: kallithea/controllers/pullrequests.py:512
 #, python-format
 msgid "Invalid reviewer \"%s\" specified"
 msgstr "Reviewer spécifié \"%s\" non valide"
 
-#: kallithea/controllers/pullrequests.py:369
-#: kallithea/controllers/pullrequests.py:456
+#: kallithea/controllers/pullrequests.py:371
+#: kallithea/controllers/pullrequests.py:458
 msgid "Error occurred while creating pull request"
 msgstr "Une erreur est survenue durant la création de la pull request"
 
-#: kallithea/controllers/pullrequests.py:401
+#: kallithea/controllers/pullrequests.py:403
 msgid "Missing changesets since the previous pull request:"
 msgstr "Changeset manquant depuis la précédente pull request :"
 
-#: kallithea/controllers/pullrequests.py:408
+#: kallithea/controllers/pullrequests.py:410
 #, python-format
 msgid "New changesets on %s %s since the previous pull request:"
 msgstr "Nouveau changeset sur %s %s depuis la précédente pull request :"
 
-#: kallithea/controllers/pullrequests.py:415
+#: kallithea/controllers/pullrequests.py:417
 msgid "Ancestor didn't change - show diff since previous version:"
 msgstr ""
 "L'ancêtre n'a pas changé - montrer les différences avec la version "
 "précédente :"
 
-#: kallithea/controllers/pullrequests.py:422
+#: kallithea/controllers/pullrequests.py:424
 #, python-format
 msgid ""
 "This pull request is based on another %s revision and there is no simple "
@@ -398,60 +391,65 @@
 "Cette demande de pull est basée sur une autre révision %s et il n'y a pas"
 " de diff simple."
 
-#: kallithea/controllers/pullrequests.py:424
+#: kallithea/controllers/pullrequests.py:426
 #, python-format
 msgid "No changes found on %s %s since previous version."
 msgstr "Aucun changement constaté sur %s %s depuis la version précédente."
 
-#: kallithea/controllers/pullrequests.py:462
+#: kallithea/controllers/pullrequests.py:464
 #, python-format
 msgid "Closed, replaced by %s ."
 msgstr "Fermé, remplacé par %s."
 
-#: kallithea/controllers/pullrequests.py:470
+#: kallithea/controllers/pullrequests.py:472
 msgid "Pull request update created"
 msgstr "Mise à jour de la pull request créée"
 
-#: kallithea/controllers/pullrequests.py:513
+#: kallithea/controllers/pullrequests.py:516
 msgid "Pull request updated"
 msgstr "Pull request mise à jour"
 
-#: kallithea/controllers/pullrequests.py:528
+#: kallithea/controllers/pullrequests.py:531
 msgid "Successfully deleted pull request"
 msgstr "La requête de pull a été supprimée avec succès"
 
-#: kallithea/controllers/pullrequests.py:594
+#: kallithea/controllers/pullrequests.py:597
 #, python-format
 msgid "This pull request has already been merged to %s."
 msgstr "Cette pull request a déjà été fusionnée à %s."
 
-#: kallithea/controllers/pullrequests.py:596
+#: kallithea/controllers/pullrequests.py:599
 msgid "This pull request has been closed and can not be updated."
 msgstr "Cette pull request a été fermée et ne peut pas être mise à jour."
 
-#: kallithea/controllers/pullrequests.py:614
-#, python-format
-msgid "This pull request can be updated with changes on %s:"
-msgstr "Cette demande de pull peut être mise à jour avec les modifications de %s :"
-
 #: kallithea/controllers/pullrequests.py:617
+#, python-format
+msgid "The following changes are available on %s:"
+msgstr "Les modifications suivantes sont disponibles sur %s :"
+
+#: kallithea/controllers/pullrequests.py:621
 msgid "No changesets found for updating this pull request."
 msgstr "Pas de changeset trouvé pour ce pull request."
 
-#: kallithea/controllers/pullrequests.py:625
+#: kallithea/controllers/pullrequests.py:629
 #, python-format
 msgid "Note: Branch %s has another head: %s."
 msgstr "Note: La branche %s a une autre tête: %s."
 
-#: kallithea/controllers/pullrequests.py:631
+#: kallithea/controllers/pullrequests.py:635
 msgid "Git pull requests don't support updates yet."
 msgstr "Le smises à jour des Git pull requests ne sont pas encore supportées."
 
-#: kallithea/controllers/pullrequests.py:722
+#: kallithea/controllers/pullrequests.py:727
 msgid "No permission to change pull request status"
 msgstr "Permission manquante pour changer le statut du pull request"
 
-#: kallithea/controllers/pullrequests.py:727
+#: kallithea/controllers/pullrequests.py:738
+#, python-format
+msgid "Successfully deleted pull request %s"
+msgstr "La requête de pull %s a été supprimée avec succès"
+
+#: kallithea/controllers/pullrequests.py:748
 msgid "Closing."
 msgstr "Fermeture."
 
@@ -469,12 +467,12 @@
 msgid "An error occurred during search operation."
 msgstr "Une erreur est survenue pendant la recherche."
 
-#: kallithea/controllers/summary.py:180
+#: kallithea/controllers/summary.py:181
 #: kallithea/templates/summary/summary.html:384
 msgid "No data ready yet"
 msgstr "Aucune donnée actuellement disponible"
 
-#: kallithea/controllers/summary.py:183
+#: kallithea/controllers/summary.py:184
 #: kallithea/templates/summary/summary.html:98
 msgid "Statistics are disabled for this repository"
 msgstr "La mise à jour des statistiques est désactivée pour ce dépôt"
@@ -497,64 +495,64 @@
 msgid "Error occurred during update of defaults"
 msgstr "Une erreur est survenue durant la mise à jour des réglages par défaut"
 
-#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/gists.py:58
 #: kallithea/controllers/admin/my_account.py:243
-#: kallithea/controllers/admin/users.py:285
+#: kallithea/controllers/admin/users.py:284
 msgid "Forever"
 msgstr "Pour toujours"
 
+#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/my_account.py:244
+#: kallithea/controllers/admin/users.py:285
+msgid "5 minutes"
+msgstr "5 minute"
+
 #: kallithea/controllers/admin/gists.py:60
-#: kallithea/controllers/admin/my_account.py:244
+#: kallithea/controllers/admin/my_account.py:245
 #: kallithea/controllers/admin/users.py:286
-msgid "5 minutes"
-msgstr "5 minute"
+msgid "1 hour"
+msgstr "1 heure"
 
 #: kallithea/controllers/admin/gists.py:61
-#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/my_account.py:246
 #: kallithea/controllers/admin/users.py:287
-msgid "1 hour"
-msgstr "1 heure"
+msgid "1 day"
+msgstr "1 jour"
 
 #: kallithea/controllers/admin/gists.py:62
-#: kallithea/controllers/admin/my_account.py:246
+#: kallithea/controllers/admin/my_account.py:247
 #: kallithea/controllers/admin/users.py:288
-msgid "1 day"
-msgstr "1 jour"
-
-#: kallithea/controllers/admin/gists.py:63
-#: kallithea/controllers/admin/my_account.py:247
-#: kallithea/controllers/admin/users.py:289
 msgid "1 month"
 msgstr "1 mois"
 
-#: kallithea/controllers/admin/gists.py:67
+#: kallithea/controllers/admin/gists.py:66
 #: kallithea/controllers/admin/my_account.py:249
-#: kallithea/controllers/admin/users.py:291
+#: kallithea/controllers/admin/users.py:290
 msgid "Lifetime"
 msgstr "Toujours"
 
-#: kallithea/controllers/admin/gists.py:146
+#: kallithea/controllers/admin/gists.py:145
 msgid "Error occurred during gist creation"
 msgstr "Une erreur est survenue lors de la création du gist"
 
-#: kallithea/controllers/admin/gists.py:184
+#: kallithea/controllers/admin/gists.py:183
 #, python-format
 msgid "Deleted gist %s"
 msgstr "Gist %s supprimé"
 
-#: kallithea/controllers/admin/gists.py:233
+#: kallithea/controllers/admin/gists.py:232
 msgid "Unmodified"
 msgstr "Non modifié"
 
-#: kallithea/controllers/admin/gists.py:262
+#: kallithea/controllers/admin/gists.py:261
 msgid "Successfully updated gist content"
 msgstr "Le contenu du gist a été mis à jour avec succès"
 
-#: kallithea/controllers/admin/gists.py:267
+#: kallithea/controllers/admin/gists.py:266
 msgid "Successfully updated gist data"
 msgstr "Les données du gist on été mises à jour avec succès"
 
-#: kallithea/controllers/admin/gists.py:270
+#: kallithea/controllers/admin/gists.py:269
 #, python-format
 msgid "Error occurred during update of gist %s"
 msgstr "Une erreur est survenue durant la mise à jour du gist %s"
@@ -571,7 +569,7 @@
 msgstr "Votre compte a été mis à jour avec succès"
 
 #: kallithea/controllers/admin/my_account.py:144
-#: kallithea/controllers/admin/users.py:202
+#: kallithea/controllers/admin/users.py:201
 #, python-format
 msgid "Error occurred during update of user %s"
 msgstr "Une erreur est survenue durant la mise à jour de l'utilisateur %s"
@@ -583,33 +581,33 @@
 "l'utilisateur"
 
 #: kallithea/controllers/admin/my_account.py:220
-#: kallithea/controllers/admin/users.py:415
+#: kallithea/controllers/admin/users.py:414
 #, python-format
 msgid "Added email %s to user"
 msgstr "L’e-mail « %s » a été ajouté à l’utilisateur"
 
 #: kallithea/controllers/admin/my_account.py:226
-#: kallithea/controllers/admin/users.py:421
+#: kallithea/controllers/admin/users.py:420
 msgid "An error occurred during email saving"
 msgstr "Une erreur est survenue durant l’enregistrement de l’e-mail"
 
 #: kallithea/controllers/admin/my_account.py:235
-#: kallithea/controllers/admin/users.py:433
+#: kallithea/controllers/admin/users.py:432
 msgid "Removed email from user"
 msgstr "L’e-mail a été enlevé de l’utilisateur"
 
 #: kallithea/controllers/admin/my_account.py:259
-#: kallithea/controllers/admin/users.py:308
+#: kallithea/controllers/admin/users.py:307
 msgid "API key successfully created"
 msgstr "Clé d'API créée avec succès"
 
 #: kallithea/controllers/admin/my_account.py:271
-#: kallithea/controllers/admin/users.py:321
+#: kallithea/controllers/admin/users.py:320
 msgid "API key successfully reset"
 msgstr "Clé d'API remise à zéro avec succès"
 
 #: kallithea/controllers/admin/my_account.py:275
-#: kallithea/controllers/admin/users.py:325
+#: kallithea/controllers/admin/users.py:324
 msgid "API key successfully deleted"
 msgstr "Clé d'API supprimée avec succès"
 
@@ -659,10 +657,10 @@
 #: kallithea/templates/admin/users/user_edit_profile.html:105
 #: kallithea/templates/admin/users/users.html:10
 #: kallithea/templates/admin/users/users.html:55
-#: kallithea/templates/base/base.html:252
-#: kallithea/templates/base/base.html:253
-#: kallithea/templates/base/base.html:259
-#: kallithea/templates/base/base.html:260
+#: kallithea/templates/base/base.html:336
+#: kallithea/templates/base/base.html:337
+#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:344
 #: kallithea/templates/base/perms_summary.html:17
 msgid "Admin"
 msgstr "Administration"
@@ -693,7 +691,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1564
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1603
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1655
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1701
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1705
 msgid "Manual activation of external account"
 msgstr "Activation manuelle du compte externe"
 
@@ -705,7 +703,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1565
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1604
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1656
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1702
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1706
 msgid "Automatic activation of external account"
 msgstr "Activation automatique du compte externe"
 
@@ -726,196 +724,196 @@
 msgid "Error occurred during update of permissions"
 msgstr "Une erreur est survenue durant la mise à jour des permissions"
 
-#: kallithea/controllers/admin/repo_groups.py:188
+#: kallithea/controllers/admin/repo_groups.py:187
 #, python-format
 msgid "Error occurred during creation of repository group %s"
 msgstr "Une erreur est survenue durant la création du groupe de dépôts %s"
 
-#: kallithea/controllers/admin/repo_groups.py:193
+#: kallithea/controllers/admin/repo_groups.py:192
 #, python-format
 msgid "Created repository group %s"
 msgstr "Groupe de dépôts %s créé"
 
-#: kallithea/controllers/admin/repo_groups.py:250
+#: kallithea/controllers/admin/repo_groups.py:249
 #, python-format
 msgid "Updated repository group %s"
 msgstr "Groupe de dépôts %s mis à jour"
 
-#: kallithea/controllers/admin/repo_groups.py:266
+#: kallithea/controllers/admin/repo_groups.py:265
 #, python-format
 msgid "Error occurred during update of repository group %s"
 msgstr "Une erreur est survenue durant la mise à jour du groupe de dépôts %s"
 
-#: kallithea/controllers/admin/repo_groups.py:284
+#: kallithea/controllers/admin/repo_groups.py:283
 #, python-format
 msgid "This group contains %s repositories and cannot be deleted"
 msgstr "Ce groupe contient %s dépôts et ne peut être supprimé"
 
-#: kallithea/controllers/admin/repo_groups.py:291
+#: kallithea/controllers/admin/repo_groups.py:290
 #, python-format
 msgid "This group contains %s subgroups and cannot be deleted"
 msgstr "Ce groupe contient %s sous-groupes et ne peut pas être supprimé"
 
-#: kallithea/controllers/admin/repo_groups.py:297
+#: kallithea/controllers/admin/repo_groups.py:296
 #, python-format
 msgid "Removed repository group %s"
 msgstr "Groupe de dépôts %s supprimé"
 
-#: kallithea/controllers/admin/repo_groups.py:302
+#: kallithea/controllers/admin/repo_groups.py:301
 #, python-format
 msgid "Error occurred during deletion of repository group %s"
 msgstr "Une erreur est survenue durant la suppression du groupe de dépôts %s"
 
-#: kallithea/controllers/admin/repo_groups.py:405
-#: kallithea/controllers/admin/repo_groups.py:440
+#: kallithea/controllers/admin/repo_groups.py:404
+#: kallithea/controllers/admin/repo_groups.py:439
 #: kallithea/controllers/admin/user_groups.py:340
 msgid "Cannot revoke permission for yourself as admin"
 msgstr "Impossible de révoquer votre permission d'administrateur"
 
-#: kallithea/controllers/admin/repo_groups.py:420
+#: kallithea/controllers/admin/repo_groups.py:419
 msgid "Repository group permissions updated"
 msgstr "Permissions du groupe de dépôts mises à jour"
 
-#: kallithea/controllers/admin/repo_groups.py:457
-#: kallithea/controllers/admin/repos.py:398
+#: kallithea/controllers/admin/repo_groups.py:456
+#: kallithea/controllers/admin/repos.py:397
 #: kallithea/controllers/admin/user_groups.py:352
 msgid "An error occurred during revoking of permission"
 msgstr "Une erreur est survenue durant la révocation de la permission"
 
-#: kallithea/controllers/admin/repos.py:152
+#: kallithea/controllers/admin/repos.py:151
 #, python-format
 msgid "Error creating repository %s"
 msgstr "Erreur de création du dépôt %s"
 
-#: kallithea/controllers/admin/repos.py:213
+#: kallithea/controllers/admin/repos.py:212
 #, python-format
 msgid "Created repository %s from %s"
 msgstr "Dépôt %s créé depuis %s"
 
-#: kallithea/controllers/admin/repos.py:222
+#: kallithea/controllers/admin/repos.py:221
 #, python-format
 msgid "Forked repository %s as %s"
 msgstr "dépôt %s forké en tant que %s"
 
-#: kallithea/controllers/admin/repos.py:225
+#: kallithea/controllers/admin/repos.py:224
 #, python-format
 msgid "Created repository %s"
 msgstr "Dépôt %s créé"
 
-#: kallithea/controllers/admin/repos.py:262
+#: kallithea/controllers/admin/repos.py:261
 #, python-format
 msgid "Repository %s updated successfully"
 msgstr "Dépôt %s mis à jour avec succès"
 
-#: kallithea/controllers/admin/repos.py:283
+#: kallithea/controllers/admin/repos.py:282
 #, python-format
 msgid "Error occurred during update of repository %s"
 msgstr "Une erreur est survenue durant la mise à jour du dépôt %s"
 
-#: kallithea/controllers/admin/repos.py:310
+#: kallithea/controllers/admin/repos.py:309
 #, python-format
 msgid "Detached %s forks"
 msgstr "%s forks détachés"
 
-#: kallithea/controllers/admin/repos.py:313
+#: kallithea/controllers/admin/repos.py:312
 #, python-format
 msgid "Deleted %s forks"
 msgstr "%s forks supprimés"
 
-#: kallithea/controllers/admin/repos.py:318
+#: kallithea/controllers/admin/repos.py:317
 #, python-format
 msgid "Deleted repository %s"
 msgstr "Dépôt %s supprimé"
 
-#: kallithea/controllers/admin/repos.py:321
+#: kallithea/controllers/admin/repos.py:320
 #, python-format
 msgid "Cannot delete repository %s which still has forks"
 msgstr "Impossible de supprimer le dépôt %s : des forks y sont attachés"
 
-#: kallithea/controllers/admin/repos.py:326
+#: kallithea/controllers/admin/repos.py:325
 #, python-format
 msgid "An error occurred during deletion of %s"
 msgstr "Erreur pendant la suppression de %s"
 
-#: kallithea/controllers/admin/repos.py:374
+#: kallithea/controllers/admin/repos.py:373
 msgid "Repository permissions updated"
 msgstr "Permissions du dépôt mises à jour"
 
-#: kallithea/controllers/admin/repos.py:430
+#: kallithea/controllers/admin/repos.py:429
 msgid "An error occurred during creation of field"
 msgstr "Une erreur est survenue durant la création du champ"
 
-#: kallithea/controllers/admin/repos.py:444
+#: kallithea/controllers/admin/repos.py:443
 msgid "An error occurred during removal of field"
 msgstr "Une erreur est survenue durant la suppression du champ"
 
-#: kallithea/controllers/admin/repos.py:460
+#: kallithea/controllers/admin/repos.py:459
 msgid "-- Not a fork --"
 msgstr "-- Pas un fork --"
 
-#: kallithea/controllers/admin/repos.py:491
+#: kallithea/controllers/admin/repos.py:490
 msgid "Updated repository visibility in public journal"
 msgstr "La visibilité du dépôt dans le journal public a été mise à jour"
 
-#: kallithea/controllers/admin/repos.py:495
+#: kallithea/controllers/admin/repos.py:494
 msgid "An error occurred during setting this repository in public journal"
 msgstr ""
 "Une erreur est survenue durant la configuration du journal public pour ce"
 " dépôt"
 
-#: kallithea/controllers/admin/repos.py:512
+#: kallithea/controllers/admin/repos.py:511
 msgid "Nothing"
 msgstr "[Aucun dépôt]"
 
-#: kallithea/controllers/admin/repos.py:514
+#: kallithea/controllers/admin/repos.py:513
 #, python-format
 msgid "Marked repository %s as fork of %s"
 msgstr "Le dépôt %s a été marké comme fork de %s"
 
-#: kallithea/controllers/admin/repos.py:521
+#: kallithea/controllers/admin/repos.py:520
 msgid "An error occurred during this operation"
 msgstr "Une erreur est survenue durant cette opération"
 
-#: kallithea/controllers/admin/repos.py:537
-#: kallithea/controllers/admin/repos.py:564
+#: kallithea/controllers/admin/repos.py:536
+#: kallithea/controllers/admin/repos.py:563
 msgid "Repository has been locked"
 msgstr "Ce dépôt a été verrouillé"
 
-#: kallithea/controllers/admin/repos.py:540
-#: kallithea/controllers/admin/repos.py:561
+#: kallithea/controllers/admin/repos.py:539
+#: kallithea/controllers/admin/repos.py:560
 msgid "Repository has been unlocked"
 msgstr "Ce dépôt a été déverrouillé"
 
-#: kallithea/controllers/admin/repos.py:543
-#: kallithea/controllers/admin/repos.py:568
+#: kallithea/controllers/admin/repos.py:542
+#: kallithea/controllers/admin/repos.py:567
 msgid "An error occurred during unlocking"
 msgstr "Une erreur est survenue durant le déverrouillage"
 
-#: kallithea/controllers/admin/repos.py:582
+#: kallithea/controllers/admin/repos.py:581
 msgid "Cache invalidation successful"
 msgstr "Invalidation du cache réalisée avec succès"
 
-#: kallithea/controllers/admin/repos.py:586
+#: kallithea/controllers/admin/repos.py:585
 msgid "An error occurred during cache invalidation"
 msgstr "Une erreur est survenue durant l’invalidation du cache"
 
-#: kallithea/controllers/admin/repos.py:601
+#: kallithea/controllers/admin/repos.py:600
 msgid "Pulled from remote location"
 msgstr "Les changements distants ont été récupérés"
 
-#: kallithea/controllers/admin/repos.py:604
+#: kallithea/controllers/admin/repos.py:603
 msgid "An error occurred during pull from remote location"
 msgstr "Une erreur est survenue durant le pull depuis la source distante"
 
-#: kallithea/controllers/admin/repos.py:637
+#: kallithea/controllers/admin/repos.py:636
 msgid "An error occurred during deletion of repository stats"
 msgstr "Une erreur est survenue durant la suppression des statistiques du dépôt"
 
-#: kallithea/controllers/admin/settings.py:170
+#: kallithea/controllers/admin/settings.py:141
 msgid "Updated VCS settings"
 msgstr "Réglages des gestionnaires de versions mis à jour"
 
-#: kallithea/controllers/admin/settings.py:174
+#: kallithea/controllers/admin/settings.py:145
 msgid ""
 "Unable to activate hgsubversion support. The \"hgsubversion\" library is "
 "missing"
@@ -923,53 +921,53 @@
 "Impossible d'activer la prise en charge de hgsubversion. La bibliothèque "
 "« hgsubversion » est manquante"
 
-#: kallithea/controllers/admin/settings.py:180
-#: kallithea/controllers/admin/settings.py:277
+#: kallithea/controllers/admin/settings.py:151
+#: kallithea/controllers/admin/settings.py:248
 msgid "Error occurred while updating application settings"
 msgstr ""
 "Une erreur est survenue durant la mise à jour des réglages de "
 "l'application"
 
-#: kallithea/controllers/admin/settings.py:216
+#: kallithea/controllers/admin/settings.py:187
 #, python-format
 msgid "Repositories successfully rescanned. Added: %s. Removed: %s."
 msgstr "Dépôts ré-analysés avec succès. Ajouté : %s. Supprimé : %s."
 
-#: kallithea/controllers/admin/settings.py:273
+#: kallithea/controllers/admin/settings.py:244
 msgid "Updated application settings"
 msgstr "Réglages mis à jour"
 
-#: kallithea/controllers/admin/settings.py:330
+#: kallithea/controllers/admin/settings.py:301
 msgid "Updated visualisation settings"
 msgstr "Réglages d’affichage mis à jour"
 
-#: kallithea/controllers/admin/settings.py:335
+#: kallithea/controllers/admin/settings.py:306
 msgid "Error occurred during updating visualisation settings"
 msgstr ""
 "Une erreur est survenue durant la mise à jour des réglages de "
 "visualisation"
 
-#: kallithea/controllers/admin/settings.py:361
+#: kallithea/controllers/admin/settings.py:332
 msgid "Please enter email address"
 msgstr "Veuillez entrer votre adresse e-mail"
 
-#: kallithea/controllers/admin/settings.py:376
+#: kallithea/controllers/admin/settings.py:347
 msgid "Send email task created"
 msgstr "Tâche d'envoi d'e-mail créée"
 
-#: kallithea/controllers/admin/settings.py:407
+#: kallithea/controllers/admin/settings.py:378
 msgid "Added new hook"
 msgstr "Le nouveau hook a été ajouté"
 
-#: kallithea/controllers/admin/settings.py:421
+#: kallithea/controllers/admin/settings.py:392
 msgid "Updated hooks"
 msgstr "Hooks mis à jour"
 
-#: kallithea/controllers/admin/settings.py:425
+#: kallithea/controllers/admin/settings.py:396
 msgid "Error occurred during hook creation"
 msgstr "Une erreur est survenue durant la création du hook"
 
-#: kallithea/controllers/admin/settings.py:451
+#: kallithea/controllers/admin/settings.py:422
 msgid "Whoosh reindex task scheduled"
 msgstr "La tâche de réindexation Whoosh a été planifiée"
 
@@ -1010,76 +1008,82 @@
 msgstr "Permissions du groupe d'utilisateurs mises à jour"
 
 #: kallithea/controllers/admin/user_groups.py:440
-#: kallithea/controllers/admin/users.py:384
+#: kallithea/controllers/admin/users.py:383
 msgid "Updated permissions"
 msgstr "Permissions mises à jour"
 
 #: kallithea/controllers/admin/user_groups.py:444
-#: kallithea/controllers/admin/users.py:388
+#: kallithea/controllers/admin/users.py:387
 msgid "An error occurred during permissions saving"
 msgstr "Une erreur est survenue durant l’enregistrement des permissions"
 
-#: kallithea/controllers/admin/users.py:134
+#: kallithea/controllers/admin/users.py:133
 #, python-format
 msgid "Created user %s"
 msgstr "Utilisateur %s créé"
 
-#: kallithea/controllers/admin/users.py:149
+#: kallithea/controllers/admin/users.py:148
 #, python-format
 msgid "Error occurred during creation of user %s"
 msgstr "Une erreur est survenue durant la création de l'utilisateur %s"
 
-#: kallithea/controllers/admin/users.py:182
+#: kallithea/controllers/admin/users.py:181
 msgid "User updated successfully"
 msgstr "L’utilisateur a été mis à jour avec succès"
 
-#: kallithea/controllers/admin/users.py:218
+#: kallithea/controllers/admin/users.py:217
 msgid "Successfully deleted user"
 msgstr "Utilisateur supprimé avec succès"
 
-#: kallithea/controllers/admin/users.py:223
+#: kallithea/controllers/admin/users.py:222
 msgid "An error occurred during deletion of user"
 msgstr "Une erreur est survenue durant la suppression de l’utilisateur"
 
-#: kallithea/controllers/admin/users.py:236
+#: kallithea/controllers/admin/users.py:235
 msgid "The default user cannot be edited"
 msgstr "L'utilisateur par défaut ne peut pas être modifié"
 
-#: kallithea/controllers/admin/users.py:463
+#: kallithea/controllers/admin/users.py:462
 #, python-format
 msgid "Added IP address %s to user whitelist"
 msgstr "L'adresse IP %s a été ajoutée à la liste blanche"
 
-#: kallithea/controllers/admin/users.py:469
+#: kallithea/controllers/admin/users.py:468
 msgid "An error occurred while adding IP address"
 msgstr "Une erreur est survenue durant la sauvegarde d'IP"
 
-#: kallithea/controllers/admin/users.py:483
+#: kallithea/controllers/admin/users.py:482
 msgid "Removed IP address from user whitelist"
 msgstr "L'adresse IP a été supprimée de la liste blanche"
 
-#: kallithea/lib/auth.py:743
+#: kallithea/lib/auth.py:737
 #, python-format
 msgid "IP %s not allowed"
 msgstr "IP %s non autorisée"
 
-#: kallithea/lib/auth.py:756
+#: kallithea/lib/auth.py:750
 msgid "Invalid API key"
 msgstr "Clé d'API invalide"
 
-#: kallithea/lib/auth.py:812
+#: kallithea/lib/auth.py:768
+msgid "CSRF token leak has been detected - all form tokens have been expired"
+msgstr ""
+"Une fuite de jeton CSRF a été détectée - tous les jetons de formulaire ont "
+"été marqués « expirés »"
+
+#: kallithea/lib/auth.py:813
 msgid "You need to be a registered user to perform this action"
 msgstr "Vous devez être un utilisateur enregistré pour effectuer cette action"
 
-#: kallithea/lib/auth.py:844
+#: kallithea/lib/auth.py:843
 msgid "You need to be signed in to view this page"
 msgstr "Vous devez être connecté pour visualiser cette page"
 
-#: kallithea/lib/base.py:490
+#: kallithea/lib/base.py:493
 msgid "Repository not found in the filesystem"
 msgstr "Dépôt non trouvé sur le système de fichiers"
 
-#: kallithea/lib/base.py:516 kallithea/lib/helpers.py:622
+#: kallithea/lib/base.py:519 kallithea/lib/helpers.py:623
 msgid "Changeset not found"
 msgstr "Ensemble de changements non trouvé"
 
@@ -1097,125 +1101,125 @@
 msgid "No changes detected"
 msgstr "Aucun changement détecté"
 
-#: kallithea/lib/helpers.py:609
+#: kallithea/lib/helpers.py:610
 #, python-format
 msgid "Deleted branch: %s"
 msgstr "Branche supprimée : %s"
 
-#: kallithea/lib/helpers.py:611
+#: kallithea/lib/helpers.py:612
 #, python-format
 msgid "Created tag: %s"
 msgstr "Étiquette créée : %s"
 
-#: kallithea/lib/helpers.py:671
+#: kallithea/lib/helpers.py:672
 #, python-format
 msgid "Show all combined changesets %s->%s"
 msgstr "Afficher les changements combinés %s->%s"
 
-#: kallithea/lib/helpers.py:677
+#: kallithea/lib/helpers.py:678
 msgid "Compare view"
 msgstr "Vue de comparaison"
 
-#: kallithea/lib/helpers.py:696
+#: kallithea/lib/helpers.py:697
 msgid "and"
 msgstr "et"
 
-#: kallithea/lib/helpers.py:697
+#: kallithea/lib/helpers.py:698
 #, python-format
 msgid "%s more"
 msgstr "%s de plus"
 
-#: kallithea/lib/helpers.py:698 kallithea/templates/changelog/changelog.html:44
+#: kallithea/lib/helpers.py:699 kallithea/templates/changelog/changelog.html:44
 msgid "revisions"
 msgstr "révisions"
 
-#: kallithea/lib/helpers.py:722
+#: kallithea/lib/helpers.py:723
 #, python-format
 msgid "Fork name %s"
 msgstr "Nom du fork %s"
 
-#: kallithea/lib/helpers.py:742
+#: kallithea/lib/helpers.py:743
 #, python-format
 msgid "Pull request %s"
 msgstr "Requête de pull %s"
 
-#: kallithea/lib/helpers.py:752
+#: kallithea/lib/helpers.py:753
 msgid "[deleted] repository"
 msgstr "[a supprimé] le dépôt"
 
-#: kallithea/lib/helpers.py:754 kallithea/lib/helpers.py:766
+#: kallithea/lib/helpers.py:755 kallithea/lib/helpers.py:767
 msgid "[created] repository"
 msgstr "[a créé] le dépôt"
 
-#: kallithea/lib/helpers.py:756
+#: kallithea/lib/helpers.py:757
 msgid "[created] repository as fork"
 msgstr "[a créé] le dépôt en tant que fork"
 
-#: kallithea/lib/helpers.py:758 kallithea/lib/helpers.py:768
+#: kallithea/lib/helpers.py:759 kallithea/lib/helpers.py:769
 msgid "[forked] repository"
 msgstr "[a forké] le dépôt"
 
-#: kallithea/lib/helpers.py:760 kallithea/lib/helpers.py:770
+#: kallithea/lib/helpers.py:761 kallithea/lib/helpers.py:771
 msgid "[updated] repository"
 msgstr "[a mis à jour] le dépôt"
 
-#: kallithea/lib/helpers.py:762
+#: kallithea/lib/helpers.py:763
 msgid "[downloaded] archive from repository"
 msgstr "[téléchargée] archive depuis le dépôt"
 
-#: kallithea/lib/helpers.py:764
+#: kallithea/lib/helpers.py:765
 msgid "[delete] repository"
 msgstr "[a supprimé] le dépôt"
 
-#: kallithea/lib/helpers.py:772
+#: kallithea/lib/helpers.py:773
 msgid "[created] user"
 msgstr "[a créé] l’utilisateur"
 
-#: kallithea/lib/helpers.py:774
+#: kallithea/lib/helpers.py:775
 msgid "[updated] user"
 msgstr "[a mis à jour] l’utilisateur"
 
-#: kallithea/lib/helpers.py:776
+#: kallithea/lib/helpers.py:777
 msgid "[created] user group"
 msgstr "[créé] groupe d'utilisateurs"
 
-#: kallithea/lib/helpers.py:778
+#: kallithea/lib/helpers.py:779
 msgid "[updated] user group"
 msgstr "[mis à jour] groupe d'utilisateurs"
 
-#: kallithea/lib/helpers.py:780
+#: kallithea/lib/helpers.py:781
 msgid "[commented] on revision in repository"
 msgstr "[a commenté] une révision du dépôt"
 
-#: kallithea/lib/helpers.py:782
+#: kallithea/lib/helpers.py:783
 msgid "[commented] on pull request for"
 msgstr "[a commenté] la requête de pull pour"
 
-#: kallithea/lib/helpers.py:784
+#: kallithea/lib/helpers.py:785
 msgid "[closed] pull request for"
 msgstr "[a fermé] la requête de pull de"
 
-#: kallithea/lib/helpers.py:786
+#: kallithea/lib/helpers.py:787
 msgid "[pushed] into"
 msgstr "[a pushé] dans"
 
-#: kallithea/lib/helpers.py:788
+#: kallithea/lib/helpers.py:789
 msgid "[committed via Kallithea] into repository"
 msgstr "[a commité via Kallithea] dans le dépôt"
 
-#: kallithea/lib/helpers.py:790
+#: kallithea/lib/helpers.py:791
 msgid "[pulled from remote] into repository"
 msgstr "[a pullé depuis un site distant] dans le dépôt"
 
-#: kallithea/lib/helpers.py:792
+#: kallithea/lib/helpers.py:793
 msgid "[pulled] from"
 msgstr "[a pullé] depuis"
 
-#: kallithea/lib/helpers.py:794
+#: kallithea/lib/helpers.py:795
 msgid "[started following] repository"
 msgstr "[suit maintenant] le dépôt"
 
-#: kallithea/lib/helpers.py:796
+#: kallithea/lib/helpers.py:797
 msgid "[stopped following] repository"
 msgstr "[ne suit plus] le dépôt"
 
@@ -1225,8 +1229,8 @@
 msgstr " et %s de plus"
 
 #: kallithea/lib/helpers.py:1128
-#: kallithea/templates/compare/compare_diff.html:65
-#: kallithea/templates/pullrequests/pullrequest_show.html:326
+#: kallithea/templates/compare/compare_diff.html:71
+#: kallithea/templates/pullrequests/pullrequest_show.html:337
 msgid "No files"
 msgstr "Aucun fichier"
 
@@ -1250,7 +1254,7 @@
 msgid "chmod"
 msgstr "chmod"
 
-#: kallithea/lib/helpers.py:1444
+#: kallithea/lib/helpers.py:1469
 #, python-format
 msgid ""
 "%s repository is not mapped to db perhaps it was created or renamed from "
@@ -1261,69 +1265,69 @@
 "probablement été créé ou renommé manuellement. Veuillez relancer "
 "l’application pour rescanner les dépôts"
 
-#: kallithea/lib/utils2.py:415
+#: kallithea/lib/utils2.py:434
 #, python-format
 msgid "%d year"
 msgid_plural "%d years"
 msgstr[0] "%d an"
 msgstr[1] "%d ans"
 
-#: kallithea/lib/utils2.py:416
+#: kallithea/lib/utils2.py:435
 #, python-format
 msgid "%d month"
 msgid_plural "%d months"
 msgstr[0] "%d mois"
 msgstr[1] "%d mois"
 
-#: kallithea/lib/utils2.py:417
+#: kallithea/lib/utils2.py:436
 #, python-format
 msgid "%d day"
 msgid_plural "%d days"
 msgstr[0] "%d jour"
 msgstr[1] "%d jours"
 
-#: kallithea/lib/utils2.py:418
+#: kallithea/lib/utils2.py:437
 #, python-format
 msgid "%d hour"
 msgid_plural "%d hours"
 msgstr[0] "%d heure"
 msgstr[1] "%d heures"
 
-#: kallithea/lib/utils2.py:419
+#: kallithea/lib/utils2.py:438
 #, python-format
 msgid "%d minute"
 msgid_plural "%d minutes"
 msgstr[0] "%d minute"
 msgstr[1] "%d minutes"
 
-#: kallithea/lib/utils2.py:420
+#: kallithea/lib/utils2.py:439
 #, python-format
 msgid "%d second"
 msgid_plural "%d seconds"
 msgstr[0] "%d seconde"
 msgstr[1] "%d secondes"
 
-#: kallithea/lib/utils2.py:436
+#: kallithea/lib/utils2.py:455
 #, python-format
 msgid "in %s"
 msgstr "dans %s"
 
-#: kallithea/lib/utils2.py:438
+#: kallithea/lib/utils2.py:457
 #, python-format
 msgid "%s ago"
 msgstr "Il y a %s"
 
-#: kallithea/lib/utils2.py:440
+#: kallithea/lib/utils2.py:459
 #, python-format
 msgid "in %s and %s"
 msgstr "dans %s et %s"
 
-#: kallithea/lib/utils2.py:443
+#: kallithea/lib/utils2.py:462
 #, python-format
 msgid "%s and %s ago"
 msgstr "Il y a %s et %s"
 
-#: kallithea/lib/utils2.py:446
+#: kallithea/lib/utils2.py:465
 msgid "just now"
 msgstr "à l’instant"
 
@@ -1422,7 +1426,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1531
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1570
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1620
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1665
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1669
 msgid "Kallithea Administrator"
 msgstr "Administrateur Kallithea"
 
@@ -1533,7 +1537,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2063
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2102
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2155
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2229
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2237
 msgid "Approved"
 msgstr "Approuvée"
 
@@ -1548,7 +1552,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2064
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2103
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2156
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2230
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2238
 msgid "Rejected"
 msgstr "Rejetée"
 
@@ -1575,7 +1579,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1379
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1418
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1471
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1518
 msgid "top level"
 msgstr "niveau supérieur"
 
@@ -1722,7 +1726,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1560
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1599
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1651
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1697
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1701
 msgid "Registration disabled"
 msgstr "Enregistrement désactivé"
 
@@ -1749,14 +1753,14 @@
 msgstr "Enregistrement des utilisateurs avec activation de compte automatique"
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1645
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1691
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1695
 msgid "Repository creation enabled with write permission to a repository group"
 msgstr ""
 "Création de dépôts activée avec l'accès en écriture vers un groupe de "
 "dépôts"
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1646
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1692
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1696
 msgid "Repository creation disabled with write permission to a repository group"
 msgstr ""
 "Création de dépôts désactivée avec l'accès en écriture vers un groupe de "
@@ -1767,119 +1771,119 @@
 msgid "on line %s"
 msgstr "à la ligne %s"
 
-#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:169
+#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:170
 msgid "[Mention]"
 msgstr "[Mention]"
 
-#: kallithea/model/db.py:1667
+#: kallithea/model/db.py:1671
 msgid "Default user has no access to new repositories"
 msgstr "L'utilisateur par défaut n'a pas accès aux nouveaux dépôts"
 
-#: kallithea/model/db.py:1668
+#: kallithea/model/db.py:1672
 msgid "Default user has read access to new repositories"
 msgstr "L'utilisateur par défaut a un accès en lecture aux nouveaux dépôts"
 
-#: kallithea/model/db.py:1669
+#: kallithea/model/db.py:1673
 msgid "Default user has write access to new repositories"
 msgstr "L'utilisateur par défaut a un accès en écriture aux nouveaux dépôts"
 
-#: kallithea/model/db.py:1670
+#: kallithea/model/db.py:1674
 msgid "Default user has admin access to new repositories"
 msgstr "L'utilisateur par défaut a un accès administrateur aux nouveaux dépôts"
 
-#: kallithea/model/db.py:1672
+#: kallithea/model/db.py:1676
 msgid "Default user has no access to new repository groups"
 msgstr "L'utilisateur par défaut n'a pas accès aux nouveaux groupes de dépôts"
 
-#: kallithea/model/db.py:1673
+#: kallithea/model/db.py:1677
 msgid "Default user has read access to new repository groups"
 msgstr ""
-"L'utilisateur par défaut a accès en lecture seule aux nouveaux groupes de "
-"dépôts"
-
-#: kallithea/model/db.py:1674
+"L'utilisateur par défaut a accès en lecture seule aux nouveaux groupes de"
+" dépôts"
+
+#: kallithea/model/db.py:1678
 msgid "Default user has write access to new repository groups"
 msgstr ""
-"L'utilisateur par défaut a accès en écriture aux nouveaux groupes de dépôts"
-
-#: kallithea/model/db.py:1675
+"L'utilisateur par défaut a accès en écriture aux nouveaux groupes de "
+"dépôts"
+
+#: kallithea/model/db.py:1679
 msgid "Default user has admin access to new repository groups"
 msgstr ""
 "L'utilisateur par défaut a accès administrateur aux nouveaux groupes de "
 "dépôts"
 
-#: kallithea/model/db.py:1677
+#: kallithea/model/db.py:1681
 msgid "Default user has no access to new user groups"
-msgstr ""
-"L'utilisateur par défaut n'a pas accès aux nouveaux groupes d'utilisateurs"
-
-#: kallithea/model/db.py:1678
+msgstr "L'utilisateur par défaut n'a pas accès aux nouveaux groupes d'utilisateurs"
+
+#: kallithea/model/db.py:1682
 msgid "Default user has read access to new user groups"
 msgstr ""
 "L'utilisateur par défaut a accès en lecture seule aux nouveaux groupes "
 "d'utilisateurs"
 
-#: kallithea/model/db.py:1679
+#: kallithea/model/db.py:1683
 msgid "Default user has write access to new user groups"
 msgstr ""
 "L'utilisateur par défaut a accès en écriture aux nouveaux groupes "
 "d'utilisateurs"
 
-#: kallithea/model/db.py:1680
+#: kallithea/model/db.py:1684
 msgid "Default user has admin access to new user groups"
 msgstr ""
 "L'utilisateur par défaut a un accès administrateur aux nouveaux groupes "
 "d'utilisateurs"
 
-#: kallithea/model/db.py:1682
+#: kallithea/model/db.py:1686
 msgid "Only admins can create repository groups"
 msgstr "Seul un administrateur peut créer un groupe de dépôts"
 
-#: kallithea/model/db.py:1683
+#: kallithea/model/db.py:1687
 msgid "Non-admins can create repository groups"
-msgstr ""
-"Les utilisateurs non-administrateurs peuvent créer des groupes de dépôts"
-
-#: kallithea/model/db.py:1685
+msgstr "Les utilisateurs non-administrateurs peuvent créer des groupes de dépôts"
+
+#: kallithea/model/db.py:1689
 msgid "Only admins can create user groups"
 msgstr "Seul un administrateur peut créer des groupes d'utilisateurs"
 
-#: kallithea/model/db.py:1686
+#: kallithea/model/db.py:1690
 msgid "Non-admins can create user groups"
 msgstr ""
-"Les utilisateurs non-administrateurs peuvent créer des groupes d'utilisateurs"
-
-#: kallithea/model/db.py:1688
+"Les utilisateurs non-administrateurs peuvent créer des groupes "
+"d'utilisateurs"
+
+#: kallithea/model/db.py:1692
 msgid "Only admins can create top level repositories"
 msgstr "Seul un administrateur peut créer des dépôts de niveau supérieur"
 
-#: kallithea/model/db.py:1689
+#: kallithea/model/db.py:1693
 msgid "Non-admins can create top level repositories"
 msgstr ""
 "Les utilisateurs non-administrateurs peuvent créer des dépôts de niveau "
 "supérieur"
 
-#: kallithea/model/db.py:1694
+#: kallithea/model/db.py:1698
 msgid "Only admins can fork repositories"
 msgstr "Seul un administrateur peut faire un fork de dépôt"
 
-#: kallithea/model/db.py:1695
-msgid "Non-admins can can fork repositories"
+#: kallithea/model/db.py:1699
+msgid "Non-admins can fork repositories"
 msgstr "Les utilisateurs non-administrateurs peuvent faire un fork de dépôt"
 
-#: kallithea/model/db.py:1698
+#: kallithea/model/db.py:1702
 msgid "User registration with manual account activation"
 msgstr "Enregistrement des utilisateurs avec activation de compte manuelle"
 
-#: kallithea/model/db.py:1699
+#: kallithea/model/db.py:1703
 msgid "User registration with automatic account activation"
 msgstr "Enregistrement des utilisateurs avec activation de compte automatique"
 
-#: kallithea/model/db.py:2228
+#: kallithea/model/db.py:2236
 msgid "Not reviewed"
 msgstr "Pas encore relue"
 
-#: kallithea/model/db.py:2231
+#: kallithea/model/db.py:2239
 msgid "Under review"
 msgstr "En cours de relecture"
 
@@ -1901,7 +1905,7 @@
 msgid "Enter %(min)i characters or more"
 msgstr "Entrez au moins %(min)i caractères"
 
-#: kallithea/model/forms.py:160
+#: kallithea/model/forms.py:165
 msgid "Name must not contain only digits"
 msgstr "Le nom ne doit pas contenir seulement des chiffres"
 
@@ -1977,7 +1981,6 @@
 
 #: kallithea/model/notification.py:307
 #, python-format
-#| msgid "%(user)s wants you to review pull request %(pr_nice_id)s:"
 msgid "[Added] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
 msgstr ""
 "[Ajouté] Demande de pull %(pr_nice_id)s à partir de %(ref)s pour "
@@ -1985,7 +1988,6 @@
 
 #: kallithea/model/notification.py:308
 #, python-format
-#| msgid "[commented] on pull request for"
 msgid "[Comment] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
 msgstr ""
 "[Commentaire] Demande de pull %(pr_nice_id)s à partir de %(ref)s pour "
@@ -2002,7 +2004,7 @@
 "%(user)s veut que vous regardiez la demande de pull %(pr_nice_id)s : "
 "%(pr_title)s"
 
-#: kallithea/model/scm.py:812
+#: kallithea/model/scm.py:708
 msgid "latest tip"
 msgstr "Dernier sommet"
 
@@ -2013,8 +2015,8 @@
 #: kallithea/model/user.py:256
 msgid "You can't remove this user since it is crucial for the entire application"
 msgstr ""
-"Vous ne pouvez pas supprimer cet utilisateur ; il est nécessaire pour le bon "
-"fonctionnement de l’application"
+"Vous ne pouvez pas supprimer cet utilisateur ; il est nécessaire pour le "
+"bon fonctionnement de l’application"
 
 #: kallithea/model/user.py:261
 #, python-format
@@ -2040,20 +2042,19 @@
 "User \"%s\" still owns %s user groups and cannot be removed. Switch "
 "owners or remove those user groups: %s"
 msgstr ""
-"L’utilisateur « %s » possède %s groupes d'utilisateurs et ne peut pas être "
-"supprimé. Changez les propriétaires de ces groupes d'utilisateurs ou "
-"supprimez-les : %s"
-
-#: kallithea/model/user.py:360
+"L’utilisateur « %s » possède %s groupes d'utilisateurs et ne peut pas "
+"être supprimé. Changez les propriétaires de ces groupes d'utilisateurs ou"
+" supprimez-les : %s"
+
+#: kallithea/model/user.py:368
 msgid "Password reset link"
 msgstr "Lien de remise à zéro du mot de passe"
 
-#: kallithea/model/user.py:408
-#| msgid "Password reset link"
+#: kallithea/model/user.py:418
 msgid "Password reset notification"
 msgstr "Notification de réinitialisation du mot de passe"
 
-#: kallithea/model/user.py:409
+#: kallithea/model/user.py:419
 #, python-format
 msgid ""
 "The password to your account %s has been changed using password reset "
@@ -2066,44 +2067,44 @@
 msgid "Value cannot be an empty list"
 msgstr "Cette valeur ne peut être une liste vide"
 
-#: kallithea/model/validators.py:95
+#: kallithea/model/validators.py:96
 #, python-format
 msgid "Username \"%(username)s\" already exists"
 msgstr "Le nom d’utilisateur « %(username)s » existe déjà"
 
-#: kallithea/model/validators.py:97
+#: kallithea/model/validators.py:98
 #, python-format
 msgid "Username \"%(username)s\" cannot be used"
 msgstr "Le nom d’utilisateur « %(username)s » n’est pas valide"
 
-#: kallithea/model/validators.py:99
+#: kallithea/model/validators.py:100
 msgid ""
 "Username may only contain alphanumeric characters underscores, periods or"
 " dashes and must begin with an alphanumeric character or underscore"
 msgstr ""
-"Le nom d'utilisateur ne peut contenir que des caractères alphanumériques, "
-"des underscores (_), points, traits d'union et doit commencer avec un "
+"Le nom d'utilisateur ne peut contenir que des caractères alphanumériques,"
+" des underscores (_), points, traits d'union et doit commencer avec un "
 "caractère alphanumérique ou un underscore"
 
-#: kallithea/model/validators.py:126
+#: kallithea/model/validators.py:127
 msgid "The input is not valid"
 msgstr "L'entrée n'est pas valide"
 
-#: kallithea/model/validators.py:133
+#: kallithea/model/validators.py:134
 #, python-format
 msgid "Username %(username)s is not valid"
 msgstr "Le nom d’utilisateur « %(username)s » n’est pas valide"
 
-#: kallithea/model/validators.py:152
+#: kallithea/model/validators.py:154
 msgid "Invalid user group name"
 msgstr "Nom de groupe d'utilisateurs invalide"
 
-#: kallithea/model/validators.py:153
+#: kallithea/model/validators.py:155
 #, python-format
 msgid "User group \"%(usergroup)s\" already exists"
 msgstr "Le groupe d'utilisateurs « %(usergroup)s » existe déjà"
 
-#: kallithea/model/validators.py:155
+#: kallithea/model/validators.py:157
 msgid ""
 "user group name may only contain alphanumeric characters underscores, "
 "periods or dashes and must begin with alphanumeric character"
@@ -2112,106 +2113,106 @@
 "alphanumériques, des tirets, des points, des traits d'union et doit "
 "commencer avec un caractère alphanumérique"
 
-#: kallithea/model/validators.py:193
+#: kallithea/model/validators.py:197
 msgid "Cannot assign this group as parent"
 msgstr "Impossible d’assigner ce groupe en tant que parent"
 
-#: kallithea/model/validators.py:194
+#: kallithea/model/validators.py:198
 #, python-format
 msgid "Group \"%(group_name)s\" already exists"
 msgstr "Le groupe « %(group_name)s » existe déjà"
 
-#: kallithea/model/validators.py:196
+#: kallithea/model/validators.py:200
 #, python-format
 msgid "Repository with name \"%(group_name)s\" already exists"
 msgstr "Un dépôt portant le nom « %(group_name)s » existe déjà"
 
-#: kallithea/model/validators.py:254
+#: kallithea/model/validators.py:258
 msgid "Invalid characters (non-ascii) in password"
 msgstr "Caractères incorrects (non-ASCII) dans le mot de passe"
 
-#: kallithea/model/validators.py:269
+#: kallithea/model/validators.py:273
 msgid "Invalid old password"
 msgstr "Ancien mot de passe invalide"
 
-#: kallithea/model/validators.py:285
+#: kallithea/model/validators.py:289
 msgid "Passwords do not match"
 msgstr "Les mots de passe ne correspondent pas"
 
-#: kallithea/model/validators.py:300
+#: kallithea/model/validators.py:304
 msgid "Invalid username or password"
 msgstr "Nom d'utilisateur ou mot de passe invalide"
 
-#: kallithea/model/validators.py:331
+#: kallithea/model/validators.py:335
 msgid "Token mismatch"
 msgstr "Jeton d’authentification incorrect"
 
-#: kallithea/model/validators.py:345
+#: kallithea/model/validators.py:351
 #, python-format
 msgid "Repository name %(repo)s is not allowed"
 msgstr "Le nom de dépôt « %(repo)s » n’est pas autorisé"
 
-#: kallithea/model/validators.py:347
+#: kallithea/model/validators.py:353
 #, python-format
 msgid "Repository named %(repo)s already exists"
 msgstr "Un dépôt portant le nom « %(repo)s » existe déjà"
 
-#: kallithea/model/validators.py:348
+#: kallithea/model/validators.py:354
 #, python-format
 msgid "Repository \"%(repo)s\" already exists in group \"%(group)s\""
 msgstr "Le dépôt « %(repo)s » existe déjà dans le groupe « %(group)s »"
 
-#: kallithea/model/validators.py:350
+#: kallithea/model/validators.py:356
 #, python-format
 msgid "Repository group with name \"%(repo)s\" already exists"
 msgstr "Un groupe de dépôts avec le nom « %(repo)s » existe déjà"
 
-#: kallithea/model/validators.py:465
+#: kallithea/model/validators.py:470
 msgid "Invalid repository URL"
 msgstr "URL de dépôt invalide"
 
-#: kallithea/model/validators.py:466
+#: kallithea/model/validators.py:471
 msgid ""
 "Invalid repository URL. It must be a valid http, https, ssh, svn+http or "
 "svn+https URL"
 msgstr ""
-"URL de dépôt invalide. Ce doit être une URL valide de type http, https, ssh, "
-"svn+http ou svn+https"
-
-#: kallithea/model/validators.py:489
+"URL de dépôt invalide. Ce doit être une URL valide de type http, https, "
+"ssh, svn+http ou svn+https"
+
+#: kallithea/model/validators.py:496
 msgid "Fork has to be the same type as parent"
 msgstr "Le fork doit être du même type que le parent"
 
-#: kallithea/model/validators.py:504
+#: kallithea/model/validators.py:511
 msgid "You don't have permissions to create repository in this group"
 msgstr "Vous n’avez pas la permission de créer un dépôt dans ce"
 
-#: kallithea/model/validators.py:506
+#: kallithea/model/validators.py:513
 msgid "no permission to create repository in root location"
 msgstr "pas de permission de créer un dépôt dans la racine"
 
-#: kallithea/model/validators.py:556
+#: kallithea/model/validators.py:563
 msgid "You don't have permissions to create a group in this location"
 msgstr "Vous n'avez pas les permissions pour créer un groupe dans cet endroit"
 
-#: kallithea/model/validators.py:597
+#: kallithea/model/validators.py:604
 msgid "This username or user group name is not valid"
 msgstr "Ce nom d'utilisateur ou nom de groupe d'utilisateurs n'est pas valide"
 
-#: kallithea/model/validators.py:690
+#: kallithea/model/validators.py:697
 msgid "This is not a valid path"
 msgstr "Ceci n’est pas un chemin valide"
 
-#: kallithea/model/validators.py:705
+#: kallithea/model/validators.py:714
 msgid "This email address is already in use"
 msgstr "Cette adresse e-mail est déjà enregistrée"
 
-#: kallithea/model/validators.py:725
+#: kallithea/model/validators.py:734
 #, python-format
 msgid "Email address \"%(email)s\" not found"
 msgstr "L’adresse e-mail « %(email)s » n’existe pas"
 
-#: kallithea/model/validators.py:762
+#: kallithea/model/validators.py:771
 msgid ""
 "The LDAP Login attribute of the CN must be specified - this is the name "
 "of the attribute that is equivalent to \"username\""
@@ -2219,26 +2220,26 @@
 "L’attribut Login du CN doit être spécifié. Cet attribut correspond au nom"
 " d’utilisateur"
 
-#: kallithea/model/validators.py:774
+#: kallithea/model/validators.py:783
 msgid "Please enter a valid IPv4 or IPv6 address"
 msgstr "Veuillez entrer une adresse IPv4 ou IPv6 valide"
 
-#: kallithea/model/validators.py:775
+#: kallithea/model/validators.py:784
 #, python-format
 msgid "The network size (bits) must be within the range of 0-32 (not %(bits)r)"
 msgstr "La taille du réseau (bits) doit être entre 0 et 32 (et non %(bits)r)"
 
-#: kallithea/model/validators.py:808
+#: kallithea/model/validators.py:817
 msgid "Key name can only consist of letters, underscore, dash or numbers"
 msgstr ""
 "Le nom de la clé ne peut consister que de letters, de traits d'union, de "
 "tirets ou de nombres"
 
-#: kallithea/model/validators.py:822
+#: kallithea/model/validators.py:831
 msgid "Filename cannot be inside a directory"
 msgstr "Le nom du fichier ne peut être à l'intérieur d'un répertoire"
 
-#: kallithea/model/validators.py:838
+#: kallithea/model/validators.py:847
 #, python-format
 msgid "Plugins %(loaded)s and %(next_to_load)s both export the same name"
 msgstr ""
@@ -2367,7 +2368,7 @@
 #: kallithea/templates/admin/user_groups/user_groups.html:50
 #: kallithea/templates/pullrequests/pullrequest_data.html:16
 #: kallithea/templates/pullrequests/pullrequest_show.html:156
-#: kallithea/templates/pullrequests/pullrequest_show.html:233
+#: kallithea/templates/pullrequests/pullrequest_show.html:244
 #: kallithea/templates/summary/summary.html:134
 msgid "Owner"
 msgstr "Propriétaire"
@@ -2415,7 +2416,7 @@
 #: kallithea/templates/index_base.html:144
 #: kallithea/templates/admin/my_account/my_account_repos.html:61
 #: kallithea/templates/admin/my_account/my_account_watched.html:61
-#: kallithea/templates/base/base.html:140 kallithea/templates/base/root.html:47
+#: kallithea/templates/base/root.html:47
 #: kallithea/templates/bookmarks/bookmarks.html:83
 #: kallithea/templates/branches/branches.html:83
 #: kallithea/templates/journal/journal.html:202
@@ -2425,7 +2426,7 @@
 msgstr "Chargement…"
 
 #: kallithea/templates/login.html:5 kallithea/templates/login.html:15
-#: kallithea/templates/base/base.html:326
+#: kallithea/templates/base/base.html:414
 msgid "Log In"
 msgstr "Connexion"
 
@@ -2440,7 +2441,7 @@
 #: kallithea/templates/admin/users/user_add.html:32
 #: kallithea/templates/admin/users/user_edit_profile.html:24
 #: kallithea/templates/admin/users/users.html:50
-#: kallithea/templates/base/base.html:302
+#: kallithea/templates/base/base.html:390
 #: kallithea/templates/pullrequests/pullrequest_show.html:166
 msgid "Username"
 msgstr "Nom d’utilisateur"
@@ -2448,7 +2449,7 @@
 #: kallithea/templates/login.html:33 kallithea/templates/register.html:33
 #: kallithea/templates/admin/my_account/my_account.html:37
 #: kallithea/templates/admin/users/user_add.html:41
-#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:399
 msgid "Password"
 msgstr "Mot de passe"
 
@@ -2460,7 +2461,7 @@
 msgid "Forgot your password ?"
 msgstr "Mot de passe oublié ?"
 
-#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:322
+#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:410
 msgid "Don't have an account ?"
 msgstr "Vous n’avez pas de compte ?"
 
@@ -2498,39 +2499,37 @@
 msgstr "Envoyer l'E-mail de réinitialisation du mot de passe"
 
 #: kallithea/templates/password_reset.html:47
-#| msgid "" "
 msgid ""
 "A password reset link will be sent to the specified email address if it "
 "is registered in the system."
 msgstr ""
-"Un lien de réinitialisation du mot de passe sera envoyé à l'adresse e-mail "
-"indiquée si elle est enregistrée dans le système."
+"Un lien de réinitialisation du mot de passe sera envoyé à l'adresse "
+"e-mail indiquée si elle est enregistrée dans le système."
 
 #: kallithea/templates/password_reset_confirmation.html:19
 #, python-format
 msgid "You are about to set a new password for the email address %s."
 msgstr ""
-"Vous êtes sur le point de changer le mot de passe pour l'adresse e-mail %s."
+"Vous êtes sur le point de changer le mot de passe pour l'adresse e-mail "
+"%s."
 
 #: kallithea/templates/password_reset_confirmation.html:20
 msgid ""
 "Note that you must use the same browser session for this as the one used "
 "to request the password reset."
 msgstr ""
-"Vous devez utiliser la même session de navigateur pour cette opération que "
-"celle utilisée pour la demande de réinitialisation de mot de passe."
+"Vous devez utiliser la même session de navigateur pour cette opération "
+"que celle utilisée pour la demande de réinitialisation de mot de passe."
 
 #: kallithea/templates/password_reset_confirmation.html:30
 msgid "Code you received in the email"
 msgstr "Le code que vous avez reçu dans l'e-mail"
 
 #: kallithea/templates/password_reset_confirmation.html:39
-#| msgid "New password"
 msgid "New Password"
 msgstr "Nouveau mot de passe"
 
 #: kallithea/templates/password_reset_confirmation.html:48
-#| msgid "Confirm new password"
 msgid "Confirm New Password"
 msgstr "Confirmer le nouveau mot de passe"
 
@@ -2579,8 +2578,8 @@
 #: kallithea/templates/register.html:92
 msgid "Registered accounts are ready to use and need no further action."
 msgstr ""
-"Les comptes enregistrés sont prêts à être utilisés, et ne nécessitent aucune "
-"autre action."
+"Les comptes enregistrés sont prêts à être utilisés, et ne nécessitent "
+"aucune autre action."
 
 #: kallithea/templates/register.html:94
 msgid "Please wait for an administrator to activate your account."
@@ -2591,10 +2590,6 @@
 msgid "There are no branches yet"
 msgstr "Aucune branche n’a été créée pour le moment"
 
-#: kallithea/templates/switch_to_list.html:16
-msgid "Closed Branches"
-msgstr "Branches fermées"
-
 #: kallithea/templates/switch_to_list.html:32
 #: kallithea/templates/tags/tags_data.html:44
 msgid "There are no tags yet"
@@ -2686,8 +2681,9 @@
 "Comma-separated list of plugins; Kallithea will try user authentication "
 "in plugin order"
 msgstr ""
-"Une liste séparée avec des virgules des greffons. L'ordre des greffons est "
-"aussi celui dans lequel Kallithea va essayer d'authentifier un utilisateur"
+"Une liste séparée avec des virgules des greffons. L'ordre des greffons "
+"est aussi celui dans lequel Kallithea va essayer d'authentifier un "
+"utilisateur"
 
 #: kallithea/templates/admin/auth/auth_settings.html:34
 msgid "Available built-in plugins"
@@ -2827,12 +2823,12 @@
 msgid "Never"
 msgstr "Jamais"
 
-#: kallithea/templates/admin/gists/edit.html:145
+#: kallithea/templates/admin/gists/edit.html:146
 msgid "Update Gist"
 msgstr "Mettre à jour le gist"
 
-#: kallithea/templates/admin/gists/edit.html:146
-#: kallithea/templates/changeset/changeset_file_comment.html:81
+#: kallithea/templates/admin/gists/edit.html:147
+#: kallithea/templates/changeset/changeset_file_comment.html:105
 msgid "Cancel"
 msgstr "Annuler"
 
@@ -2855,7 +2851,7 @@
 
 #: kallithea/templates/admin/gists/index.html:37
 #: kallithea/templates/admin/gists/show.html:25
-#: kallithea/templates/base/base.html:237
+#: kallithea/templates/base/base.html:321
 msgid "Create New Gist"
 msgstr "Créer un nouveau gist"
 
@@ -2943,7 +2939,8 @@
 #: kallithea/templates/admin/settings/settings_hooks.html:36
 #: kallithea/templates/admin/users/user_edit_emails.html:19
 #: kallithea/templates/admin/users/user_edit_ips.html:22
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+#: kallithea/templates/changeset/changeset_file_comment.html:95
 #: kallithea/templates/data_table/_dt_elements.html:129
 #: kallithea/templates/data_table/_dt_elements.html:157
 #: kallithea/templates/data_table/_dt_elements.html:173
@@ -2963,8 +2960,6 @@
 #: kallithea/templates/base/perms_summary.html:43
 #: kallithea/templates/base/perms_summary.html:79
 #: kallithea/templates/base/perms_summary.html:81
-#: kallithea/templates/changeset/changeset_file_comment.html:83
-#: kallithea/templates/changeset/changeset_file_comment.html:192
 #: kallithea/templates/data_table/_dt_elements.html:122
 #: kallithea/templates/data_table/_dt_elements.html:123
 #: kallithea/templates/data_table/_dt_elements.html:150
@@ -2991,13 +2986,12 @@
 msgstr "créé"
 
 #: kallithea/templates/admin/gists/show.html:86
-#: kallithea/templates/files/files_source.html:73
 msgid "Show as raw"
 msgstr "Montrer en brut"
 
 #: kallithea/templates/admin/my_account/my_account.html:5
 #: kallithea/templates/admin/my_account/my_account.html:9
-#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:431
 msgid "My Account"
 msgstr "Mon compte"
 
@@ -3120,8 +3114,7 @@
 #: kallithea/templates/admin/my_account/my_account_password.html:45
 #, python-format
 msgid "This account is managed with %s and the password cannot be changed here"
-msgstr ""
-"Ce compte est géré avec %s et le mot de passe ne peut pas être changé ici"
+msgstr "Ce compte est géré avec %s et le mot de passe ne peut pas être changé ici"
 
 #: kallithea/templates/admin/my_account/my_account_profile.html:11
 msgid "Change your avatar at"
@@ -3179,7 +3172,7 @@
 msgstr "Commentaires"
 
 #: kallithea/templates/admin/notifications/notifications.html:26
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 msgid "Pull Requests"
 msgstr "Demandes de pull"
 
@@ -3197,7 +3190,7 @@
 msgstr "Montrer Notification"
 
 #: kallithea/templates/admin/notifications/show_notification.html:9
-#: kallithea/templates/base/base.html:342
+#: kallithea/templates/base/base.html:430
 msgid "Notifications"
 msgstr "Notifications"
 
@@ -3236,9 +3229,9 @@
 "permission, note that all custom default permission on repositories will "
 "be lost"
 msgstr ""
-"Toutes les permissions par défaut de chaque dépôt vont être réinitialisées "
-"aux valeurs choisies. Notez que toutes les permissions par défaut "
-"personnalisées sur les dépôts seront perdues"
+"Toutes les permissions par défaut de chaque dépôt vont être "
+"réinitialisées aux valeurs choisies. Notez que toutes les permissions par"
+" défaut personnalisées sur les dépôts seront perdues"
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:26
 msgid "Apply to all existing repositories"
@@ -3263,8 +3256,8 @@
 "will be lost"
 msgstr ""
 "Toutes les permissions par défaut de chaque groupe de dépôts vont être "
-"réinitialisées aux valeurs choisies. Notez que toutes les permissions par "
-"défaut personnalisées sur les groupes de dépôts seront perdues"
+"réinitialisées aux valeurs choisies. Notez que toutes les permissions par"
+" défaut personnalisées sur les groupes de dépôts seront perdues"
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:40
 msgid "Apply to all existing repository groups"
@@ -3273,7 +3266,8 @@
 #: kallithea/templates/admin/permissions/permissions_globals.html:41
 msgid "Permissions for the Default user on new repository groups."
 msgstr ""
-"Permissions pour l'utilisateur par défaut sur les nouveaux groupes de dépôts."
+"Permissions pour l'utilisateur par défaut sur les nouveaux groupes de "
+"dépôts."
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:46
 #: kallithea/templates/data_table/_dt_elements.html:209
@@ -3286,9 +3280,10 @@
 "permission, note that all custom default permission on user groups will "
 "be lost"
 msgstr ""
-"Toutes les permissions par défaut de chaque groupe d'utilisateurs vont être "
-"réinitialisées aux valeurs choisies. Notez que toutes les permissions par "
-"défaut personnalisées sur les groupes d'utilisateurs seront perdues"
+"Toutes les permissions par défaut de chaque groupe d'utilisateurs vont "
+"être réinitialisées aux valeurs choisies. Notez que toutes les "
+"permissions par défaut personnalisées sur les groupes d'utilisateurs "
+"seront perdues"
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:54
 msgid "Apply to all existing user groups"
@@ -3307,17 +3302,17 @@
 #: kallithea/templates/admin/permissions/permissions_globals.html:64
 msgid "Enable this to allow non-admins to create repositories at the top level."
 msgstr ""
-"Activer pour autoriser les non-administrateurs à créer des dépôts au niveau "
-"supérieur."
+"Activer pour autoriser les non-administrateurs à créer des dépôts au "
+"niveau supérieur."
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:65
 msgid ""
 "Note: This will also give all users API access to create repositories "
 "everywhere. That might change in future versions."
 msgstr ""
-"Note : Cela autorisera également tous les utilisateurs à utiliser l'API pour "
-"créer des dépôts partout. Ce comportement peut changer dans des versions "
-"futures."
+"Note : Cela autorisera également tous les utilisateurs à utiliser l'API "
+"pour créer des dépôts partout. Ce comportement peut changer dans des "
+"versions futures."
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:70
 msgid "Repository creation with group write access"
@@ -3349,8 +3344,7 @@
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:92
 msgid "Enable this to allow non-admins to fork repositories."
-msgstr ""
-"Activer pour autoriser les non-administrateurs à faire des fork de dépôt."
+msgstr "Activer pour autoriser les non-administrateurs à faire des fork de dépôt."
 
 #: kallithea/templates/admin/permissions/permissions_globals.html:97
 msgid "Registration"
@@ -3420,7 +3414,7 @@
 #: kallithea/templates/admin/repos/repo_edit.html:40
 #: kallithea/templates/admin/settings/settings.html:11
 #: kallithea/templates/admin/user_groups/user_group_edit.html:29
-#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:151
+#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:148
 #: kallithea/templates/data_table/_dt_elements.html:45
 #: kallithea/templates/data_table/_dt_elements.html:49
 msgid "Settings"
@@ -3567,8 +3561,8 @@
 "Optional: URL of a remote repository. If set, the repository will be "
 "created as a clone from this URL."
 msgstr ""
-"Optionnel : URL d'un dépôt distant. Si renseigné, le dépôt sera créé comme "
-"un clone à partir de cette URL."
+"Optionnel : URL d'un dépôt distant. Si renseigné, le dépôt sera créé "
+"comme un clone à partir de cette URL."
 
 #: kallithea/templates/admin/repos/repo_add_base.html:32
 #: kallithea/templates/admin/repos/repo_edit_settings.html:69
@@ -3626,8 +3620,8 @@
 "We're sorry but error occurred during this operation. Please check your "
 "Kallithea server logs, or contact administrator."
 msgstr ""
-"Désolé, une erreur est survenue pendant l'opération. Vérifiez les journaux "
-"du serveur Kallithea, ou contactez votre administrateur."
+"Désolé, une erreur est survenue pendant l'opération. Vérifiez les "
+"journaux du serveur Kallithea, ou contactez votre administrateur."
 
 #: kallithea/templates/admin/repos/repo_edit.html:8
 #, python-format
@@ -3684,8 +3678,8 @@
 "All actions done in this repository will be visible to everyone in the "
 "public journal."
 msgstr ""
-"Les actions réalisées sur ce dépôt seront visibles à tous depuis le journal "
-"public."
+"Les actions réalisées sur ce dépôt seront visibles à tous depuis le "
+"journal public."
 
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:46
 msgid "Change Locking"
@@ -3699,6 +3693,11 @@
 msgid "Unlock Repository"
 msgstr "Déverrouiller le dépôt"
 
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:56
+#, python-format
+msgid "Locked by %s on %s"
+msgstr "Verrouillé par %s sur %s"
+
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:60
 msgid "Confirm to lock repository."
 msgstr "Veuillez confirmer le verrouillage de ce dépôt."
@@ -3718,10 +3717,10 @@
 "pulling locks the repository; only the user who pulled and locked it can "
 "unlock it by doing a push."
 msgstr ""
-"Forcer le verrouillage du dépôt. Ne fonctionne que lorsque l'accès anonyme "
-"est désactivé. Déclencher un pull verrouille le dépôt. L'utilisateur qui "
-"fait le pull verrouille le dépôt ; seul l'utilisateur qui a fait le pull et "
-"a verrouillé peut déverrouiller en faisant un push."
+"Forcer le verrouillage du dépôt. Ne fonctionne que lorsque l'accès "
+"anonyme est désactivé. Déclencher un pull verrouille le dépôt. "
+"L'utilisateur qui fait le pull verrouille le dépôt ; seul l'utilisateur "
+"qui a fait le pull et a verrouillé peut déverrouiller en faisant un push."
 
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:79
 #: kallithea/templates/data_table/_dt_elements.html:130
@@ -3754,25 +3753,21 @@
 "administrator expires it. The administrator can both permanently delete "
 "it or restore it."
 msgstr ""
-"Le dépôt supprimé sera mis de côté et caché jusqu'à ce que l'administrateur "
-"le fasse expirer. L'administrateur peut soit le supprimer définitivement, "
-"soit le restaurer."
+"Le dépôt supprimé sera mis de côté et caché jusqu'à ce que "
+"l'administrateur le fasse expirer. L'administrateur peut soit le "
+"supprimer définitivement, soit le restaurer."
 
 #: kallithea/templates/admin/repos/repo_edit_caches.html:4
 msgid "Invalidate Repository Cache"
 msgstr "Invalider le cache du dépôt"
 
-#: kallithea/templates/admin/repos/repo_edit_caches.html:4
-msgid "Confirm to invalidate repository cache."
-msgstr "Voulez-vous vraiment invalider le cache du dépôt ?"
-
 #: kallithea/templates/admin/repos/repo_edit_caches.html:7
 msgid ""
 "Manually invalidate cache for this repository. On first access, the "
 "repository will be cached again."
 msgstr ""
-"Invalider manuellement le cache de ce dépôt. Au prochain accès sur ce dépôt, "
-"il sera à nouveau mis en cache."
+"Invalider manuellement le cache de ce dépôt. Au prochain accès sur ce "
+"dépôt, il sera à nouveau mis en cache."
 
 #: kallithea/templates/admin/repos/repo_edit_caches.html:12
 msgid "List of Cached Values"
@@ -3844,8 +3839,7 @@
 
 #: kallithea/templates/admin/repos/repo_edit_remote.html:11
 msgid "Confirm to pull changes from remote repository."
-msgstr ""
-"Voulez-vous vraiment récupérer les changements depuis le dépôt distant ?"
+msgstr "Voulez-vous vraiment récupérer les changements depuis le dépôt distant ?"
 
 #: kallithea/templates/admin/repos/repo_edit_remote.html:17
 msgid "This repository does not have a remote repository URL."
@@ -3874,11 +3868,11 @@
 msgstr ""
 "Si ce dépôt est renommé ou déplacé dans un autre groupe, l'URL du dépôt "
 "change.\n"
-"                               L'utilisation de l'URL permanente ci-dessus "
-"garantit que ce dépôt sera toujours accessible via cette URL.\n"
+"                               L'utilisation de l'URL permanente ci-"
+"dessus garantit que ce dépôt sera toujours accessible via cette URL.\n"
 "                               Cela peut être utile pour les systèmes "
-"d'intégration continue, ou dans tous les cas où vous devez saisir l'URL « en "
-"dur » dans un service tiers."
+"d'intégration continue, ou dans tous les cas où vous devez saisir l'URL "
+"« en dur » dans un service tiers."
 
 #: kallithea/templates/admin/repos/repo_edit_settings.html:21
 msgid "Remote repository"
@@ -4026,9 +4020,9 @@
 "Hooks can be used to trigger actions on certain events such as push / "
 "pull. They can trigger Python functions or external applications."
 msgstr ""
-"Les hooks peuvent être utilisés pour déclencher des actions lors de certains "
-"évènements comme le push et le pull. Ils peuvent déclencher des fonctions "
-"Python ou des applications externes."
+"Les hooks peuvent être utilisés pour déclencher des actions lors de "
+"certains évènements comme le push et le pull. Ils peuvent déclencher des "
+"fonctions Python ou des applications externes."
 
 #: kallithea/templates/admin/settings/settings_hooks.html:19
 msgid "Custom Hooks"
@@ -4051,9 +4045,9 @@
 "Check this option to remove all comments, pull requests and other records"
 " related to repositories that no longer exist in the filesystem."
 msgstr ""
-"Cocher cette option pour supprimer tous les commentaires, les requêtes de "
-"pull et d'autres informations liées aux dépôts qui n'existent plus sur le "
-"système de fichiers."
+"Cocher cette option pour supprimer tous les commentaires, les requêtes de"
+" pull et d'autres informations liées aux dépôts qui n'existent plus sur "
+"le système de fichiers."
 
 #: kallithea/templates/admin/settings/settings_mapping.html:17
 msgid "Invalidate cache for all repositories"
@@ -4061,8 +4055,7 @@
 
 #: kallithea/templates/admin/settings/settings_mapping.html:19
 msgid "Check this to reload data and clear cache keys for all repositories."
-msgstr ""
-"Cocher pour recharger les données et vider le cache pour tous les dépôts."
+msgstr "Cocher pour recharger les données et vider le cache pour tous les dépôts."
 
 #: kallithea/templates/admin/settings/settings_mapping.html:23
 msgid "Install Git hooks"
@@ -4073,8 +4066,8 @@
 "Verify if Kallithea's Git hooks are installed for each repository. "
 "Current hooks will be updated to the latest version."
 msgstr ""
-"Vérifier si les hooks Git de Kallithea sont installés pour chaque dépôt. Les "
-"hooks actuels seront mis à jour vers la dernière version."
+"Vérifier si les hooks Git de Kallithea sont installés pour chaque dépôt. "
+"Les hooks actuels seront mis à jour vers la dernière version."
 
 #: kallithea/templates/admin/settings/settings_mapping.html:28
 msgid "Overwrite existing Git hooks"
@@ -4086,9 +4079,9 @@
 "not seem to come from Kallithea. WARNING: This operation will destroy any"
 " custom git hooks you may have deployed by hand!"
 msgstr ""
-"Lors de l'installation des hooks Git, écraser tous les hooks existants, même "
-"s'ils ne semblent pas provenir de Kallithea. ATTENTION : cette opération "
-"détruira tous les hooks Git que vous avez déployés à la main !"
+"Lors de l'installation des hooks Git, écraser tous les hooks existants, "
+"même s'ils ne semblent pas provenir de Kallithea. ATTENTION : cette "
+"opération détruira tous les hooks Git que vous avez déployés à la main !"
 
 #: kallithea/templates/admin/settings/settings_mapping.html:35
 msgid "Rescan Repositories"
@@ -4107,8 +4100,8 @@
 "This option completely reindexeses all of the repositories for proper "
 "fulltext search capabilities."
 msgstr ""
-"Cette option ré-indexe complètement tous les dépôts pour pouvoir faire des "
-"recherches dans le texte complet."
+"Cette option ré-indexe complètement tous les dépôts pour pouvoir faire "
+"des recherches dans le texte complet."
 
 #: kallithea/templates/admin/settings/settings_search.html:21
 msgid "Reindex"
@@ -4171,9 +4164,9 @@
 "Activate to require SSL both pushing and pulling. If SSL certificate is "
 "missing, it will return an HTTP Error 406: Not Acceptable."
 msgstr ""
-"Activez pour faire en sorte que Kallithea force l'utilisation de SSL pour "
-"pousser ou tirer. Si le certificat SSL est manquant, une erreur « HTTP 406: "
-"Not Acceptable » sera renvoyée."
+"Activez pour faire en sorte que Kallithea force l'utilisation de SSL pour"
+" pousser ou tirer. Si le certificat SSL est manquant, une erreur « HTTP "
+"406: Not Acceptable » sera renvoyée."
 
 #: kallithea/templates/admin/settings/settings_vcs.html:24
 msgid "Show repository size after push"
@@ -4208,8 +4201,8 @@
 "Requires hgsubversion library to be installed. Enables cloning of remote "
 "Subversion repositories while converting them to Mercurial."
 msgstr ""
-"La bibliothèque hgsubversion doit être installée. Elle permet de cloner des "
-"dépôts SVN distants et de les migrer vers Mercurial."
+"La bibliothèque hgsubversion doit être installée. Elle permet de cloner "
+"des dépôts SVN distants et de les migrer vers Mercurial."
 
 #: kallithea/templates/admin/settings/settings_vcs.html:64
 msgid "Location of repositories"
@@ -4229,7 +4222,8 @@
 "value, a restart and rescan of the repository folder are both required."
 msgstr ""
 "Emplacement où les dépôts sont stockés sur le système de fichiers. La "
-"modification de cette valeur nécessite un re-démarrage et un nouveau scan."
+"modification de cette valeur nécessite un re-démarrage et un nouveau "
+"scan."
 
 #: kallithea/templates/admin/settings/settings_visual.html:8
 msgid "General"
@@ -4242,7 +4236,8 @@
 #: kallithea/templates/admin/settings/settings_visual.html:15
 msgid "Allows storing additional customized fields per repository."
 msgstr ""
-"Permet d'enregistrer des champs personnalisés additionnels pour chaque dépôt."
+"Permet d'enregistrer des champs personnalisés additionnels pour chaque "
+"dépôt."
 
 #: kallithea/templates/admin/settings/settings_visual.html:18
 msgid "Show Kallithea version"
@@ -4250,8 +4245,7 @@
 
 #: kallithea/templates/admin/settings/settings_visual.html:20
 msgid "Shows or hides a version number of Kallithea displayed in the footer."
-msgstr ""
-"Afficher ou cacher le numéro de version de Kallithea dans le pied de page."
+msgstr "Afficher ou cacher le numéro de version de Kallithea dans le pied de page."
 
 #: kallithea/templates/admin/settings/settings_visual.html:24
 msgid "Use Gravatars in Kallithea"
@@ -4276,15 +4270,16 @@
 "L'URL de Gravatar vous permet d'utiliser un autre serveur d'avatars.\n"
 "                                                        Les variables "
 "suivantes dans l'URL seront remplacées comme suit :\n"
-"                                                        {scheme}    'http' "
-"ou 'https' envoyé à partir du serveur Kallithea en cours d'utilisation,\n"
-"                                                        {email}     adresse "
-"e-mail de l'utilisateur,\n"
+"                                                        {scheme}    "
+"'http' ou 'https' envoyé à partir du serveur Kallithea en cours "
+"d'utilisation,\n"
+"                                                        {email}     "
+"adresse e-mail de l'utilisateur,\n"
 "                                                        {md5email}  "
 "empreinte md5 (hash) de l'adresse e-mail de l'utilisateur (comme sur "
 "gravatar.com),\n"
-"                                                        {size}      taille "
-"de l'image demandée au serveur,\n"
+"                                                        {size}      "
+"taille de l'image demandée au serveur,\n"
 "                                                        {netloc}    "
 "emplacement réseau/hôte du serveur Kallithea en cours d'utilisation."
 
@@ -4309,16 +4304,17 @@
 "'{scheme}://{user}@{netloc}/{repo}'.\n"
 "                                                       Les variables "
 "suivantes sont disponibles :\n"
-"                                                        {scheme}    'http' "
-"ou 'https' envoyé à partir du serveur Kallithea en cours d'utilisation,\n"
-"                                                        {user}     nom de "
-"l'utilisateur courant,\n"
+"                                                        {scheme}    "
+"'http' ou 'https' envoyé à partir du serveur Kallithea en cours "
+"d'utilisation,\n"
+"                                                        {user}     nom de"
+" l'utilisateur courant,\n"
 "                                                        {netloc}    "
 "emplacement réseau/hôte du serveur Kallithea en cours d'utilisation,\n"
 "                                                        {repo}    nom "
 "complet du dépôt,\n"
-"                                                        {repoid}    ID du "
-"dépôt, peut être utilisé pour cloner par ID."
+"                                                        {repoid}    ID du"
+" dépôt, peut être utilisé pour cloner par ID."
 
 #: kallithea/templates/admin/settings/settings_visual.html:55
 msgid "Dashboard items"
@@ -4329,8 +4325,8 @@
 "Number of items displayed in the main page dashboard before pagination is"
 " shown."
 msgstr ""
-"Nombre d'éléments affichés dans la page principale du tableau de bord avant "
-"d'afficher la pagination."
+"Nombre d'éléments affichés dans la page principale du tableau de bord "
+"avant d'afficher la pagination."
 
 #: kallithea/templates/admin/settings/settings_visual.html:65
 msgid "Admin pages items"
@@ -4341,8 +4337,8 @@
 "Number of items displayed in the admin pages grids before pagination is "
 "shown."
 msgstr ""
-"Nombre d'éléments affichés dans les grilles des pages admin avant d'afficher "
-"la pagination."
+"Nombre d'éléments affichés dans les grilles des pages admin avant "
+"d'afficher la pagination."
 
 #: kallithea/templates/admin/settings/settings_visual.html:75
 msgid "Icons"
@@ -4513,7 +4509,8 @@
 #: kallithea/templates/admin/users/user_edit_profile.html:12
 msgid "Missing email, please update this user email address."
 msgstr ""
-"E-mail manquant, veuillez mettre à jour l'adresse e-mail de cet utilisateur."
+"E-mail manquant, veuillez mettre à jour l'adresse e-mail de cet "
+"utilisateur."
 
 #: kallithea/templates/admin/users/user_edit_profile.html:51
 msgid "Name in Source of Record"
@@ -4574,21 +4571,17 @@
 msgid "Files"
 msgstr "Fichiers"
 
-#: kallithea/templates/base/base.html:138
-msgid "Switch To"
-msgstr "Basculer vers"
-
-#: kallithea/templates/base/base.html:145
-#: kallithea/templates/base/base.html:147
+#: kallithea/templates/base/base.html:142
+#: kallithea/templates/base/base.html:144
 msgid "Options"
 msgstr "Options"
 
-#: kallithea/templates/base/base.html:155
+#: kallithea/templates/base/base.html:152
 #: kallithea/templates/forks/forks_data.html:21
 msgid "Compare Fork"
 msgstr "Comparer le fork"
 
-#: kallithea/templates/base/base.html:157
+#: kallithea/templates/base/base.html:154
 #: kallithea/templates/bookmarks/bookmarks.html:56
 #: kallithea/templates/bookmarks/bookmarks_data.html:13
 #: kallithea/templates/branches/branches.html:56
@@ -4598,111 +4591,116 @@
 msgid "Compare"
 msgstr "Comparer"
 
-#: kallithea/templates/base/base.html:159
-#: kallithea/templates/base/base.html:247
+#: kallithea/templates/base/base.html:156
+#: kallithea/templates/base/base.html:331
 #: kallithea/templates/search/search.html:14
 #: kallithea/templates/search/search.html:54
 msgid "Search"
 msgstr "Rechercher"
 
-#: kallithea/templates/base/base.html:163
+#: kallithea/templates/base/base.html:160
 msgid "Unlock"
 msgstr "Déverrouiller"
 
-#: kallithea/templates/base/base.html:165
+#: kallithea/templates/base/base.html:162
 msgid "Lock"
 msgstr "Verrouiller"
 
-#: kallithea/templates/base/base.html:173
+#: kallithea/templates/base/base.html:170
 msgid "Follow"
 msgstr "Suivre"
 
+#: kallithea/templates/base/base.html:171
+msgid "Unfollow"
+msgstr "Arrêter de suivre"
+
 #: kallithea/templates/base/base.html:174
-msgid "Unfollow"
-msgstr "Arrêter de suivre"
-
-#: kallithea/templates/base/base.html:177
 #: kallithea/templates/data_table/_dt_elements.html:37
 #: kallithea/templates/data_table/_dt_elements.html:41
 #: kallithea/templates/forks/fork.html:9
 msgid "Fork"
 msgstr "Fork"
 
-#: kallithea/templates/base/base.html:178
+#: kallithea/templates/base/base.html:175
 #: kallithea/templates/pullrequests/pullrequest.html:88
 msgid "Create Pull Request"
 msgstr "Créer une requête de pull"
 
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 #, python-format
 msgid "Show Pull Requests for %s"
 msgstr "Afficher les requêtes de pull pour %s"
 
-#: kallithea/templates/base/base.html:221
+#: kallithea/templates/base/base.html:193
+msgid "Switch To"
+msgstr "Basculer vers"
+
+#: kallithea/templates/base/base.html:203
+#: kallithea/templates/base/base.html:485
+msgid "No matches found"
+msgstr "Aucune correspondance trouvée"
+
+#: kallithea/templates/base/base.html:305
 msgid "Show recent activity"
 msgstr "Afficher l'activité récente"
 
-#: kallithea/templates/base/base.html:227
-#: kallithea/templates/base/base.html:228
+#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:312
 msgid "Public journal"
 msgstr "Journal public"
 
-#: kallithea/templates/base/base.html:233
+#: kallithea/templates/base/base.html:317
 msgid "Show public gists"
 msgstr "Afficher les gists publics"
 
-#: kallithea/templates/base/base.html:234
+#: kallithea/templates/base/base.html:318
 msgid "Gists"
 msgstr "Gists"
 
-#: kallithea/templates/base/base.html:238
+#: kallithea/templates/base/base.html:322
 msgid "All Public Gists"
 msgstr "Tous les Gists publics"
 
-#: kallithea/templates/base/base.html:240
+#: kallithea/templates/base/base.html:324
 msgid "My Public Gists"
 msgstr "Mes Gists publics"
 
-#: kallithea/templates/base/base.html:241
+#: kallithea/templates/base/base.html:325
 msgid "My Private Gists"
 msgstr "Mes Gist privés"
 
-#: kallithea/templates/base/base.html:246
+#: kallithea/templates/base/base.html:330
 msgid "Search in repositories"
 msgstr "Recherche dans les dépôts"
 
-#: kallithea/templates/base/base.html:269
-#: kallithea/templates/base/base.html:270
+#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:354
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:6
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:10
 msgid "My Pull Requests"
 msgstr "Mes requêtes de pull"
 
-#: kallithea/templates/base/base.html:289
+#: kallithea/templates/base/base.html:377
 msgid "Not Logged In"
 msgstr "Non connecté"
 
-#: kallithea/templates/base/base.html:296
+#: kallithea/templates/base/base.html:384
 msgid "Login to Your Account"
 msgstr "Connexion à votre compte"
 
-#: kallithea/templates/base/base.html:319
+#: kallithea/templates/base/base.html:407
 msgid "Forgot password ?"
 msgstr "Mot de passe oublié ?"
 
-#: kallithea/templates/base/base.html:346
+#: kallithea/templates/base/base.html:434
 msgid "Log Out"
 msgstr "Se déconnecter"
 
-#: kallithea/templates/base/base.html:395
-msgid "No matches found"
-msgstr "Aucune correspondance trouvée"
-
-#: kallithea/templates/base/base.html:524
+#: kallithea/templates/base/base.html:615
 msgid "Keyboard shortcuts"
 msgstr "Raccourcis clavier"
 
-#: kallithea/templates/base/base.html:533
+#: kallithea/templates/base/base.html:624
 msgid "Site-wide shortcuts"
 msgstr "Raccourcis globaux"
 
@@ -4716,8 +4714,8 @@
 "Select to inherit global settings, IP whitelist and permissions from the "
 "%s."
 msgstr ""
-"Sélectionner pour hériter des réglages généraux, de la liste blanche d'IP et "
-"des permissions depuis les %s."
+"Sélectionner pour hériter des réglages généraux, de la liste blanche d'IP"
+" et des permissions depuis les %s."
 
 #: kallithea/templates/base/default_perms_box.html:28
 msgid "Create repositories"
@@ -4726,7 +4724,8 @@
 #: kallithea/templates/base/default_perms_box.html:33
 msgid "Select this option to allow repository creation for this user"
 msgstr ""
-"Sélectionner cette option pour autoriser cet utilisateur à créer des dépôts"
+"Sélectionner cette option pour autoriser cet utilisateur à créer des "
+"dépôts"
 
 #: kallithea/templates/base/default_perms_box.html:40
 msgid "Create user groups"
@@ -4735,8 +4734,8 @@
 #: kallithea/templates/base/default_perms_box.html:45
 msgid "Select this option to allow user group creation for this user"
 msgstr ""
-"Sélectionner cette option pour autoriser cet utilisateur à créer des groupes "
-"d'utilisateurs"
+"Sélectionner cette option pour autoriser cet utilisateur à créer des "
+"groupes d'utilisateurs"
 
 #: kallithea/templates/base/default_perms_box.html:52
 msgid "Fork repositories"
@@ -4745,7 +4744,8 @@
 #: kallithea/templates/base/default_perms_box.html:57
 msgid "Select this option to allow repository forking for this user"
 msgstr ""
-"Sélectionner cette option pour autoriser cet utilisateur à forker des dépôts"
+"Sélectionner cette option pour autoriser cet utilisateur à forker des "
+"dépôts"
 
 #: kallithea/templates/base/perms_summary.html:13
 #: kallithea/templates/changelog/changelog.html:42
@@ -4808,7 +4808,6 @@
 msgstr "Aucun fichier correspondant"
 
 #: kallithea/templates/base/root.html:31
-#| msgid "on pull request"
 msgid "Open New Pull Request from {0}"
 msgstr "Ouvrir une nouvelle requête de pull à partir de {0}"
 
@@ -4817,7 +4816,6 @@
 msgstr "Ouvrir une nouvelle requête de pull pour {0} &rarr; {1}"
 
 #: kallithea/templates/base/root.html:33
-#| msgid "Show Selected Changeset __S"
 msgid "Show Selected Changesets {0} &rarr; {1}"
 msgstr "Afficher les changesets sélectionnés {0} &rarr; {1}"
 
@@ -4827,6 +4825,7 @@
 
 #: kallithea/templates/base/root.html:35
 #: kallithea/templates/changeset/diff_block.html:8
+#: kallithea/templates/changeset/diff_block.html:21
 msgid "Collapse Diff"
 msgstr "Replier le Diff"
 
@@ -4934,54 +4933,58 @@
 #: kallithea/templates/changelog/changelog.html:92
 #: kallithea/templates/changelog/changelog_summary_data.html:20
 #, python-format
+#| msgid "" "Changeset status: %s\n" "Click to open associated pull request %s"
 msgid ""
-"Changeset status: %s\n"
+"Changeset status: %s by %s\n"
 "Click to open associated pull request %s"
 msgstr ""
-"Statut du changeset : %s\n"
+"Statut du changeset : %s par %s\n"
 "Cliquer pour ouvrir la requête de pull %s associée"
 
 #: kallithea/templates/changelog/changelog.html:96
-#: kallithea/templates/compare/compare_cs.html:24
-#, python-format
-msgid "Changeset status: %s"
-msgstr "Statut de changeset : %s"
-
-#: kallithea/templates/changelog/changelog.html:115
+#: kallithea/templates/changelog/changelog_summary_data.html:24
+#, python-format
+#| msgid "Changeset status: %s"
+msgid "Changeset status: %s by %s"
+msgstr "Statut de changeset : %s par %s"
+
+#: kallithea/templates/changelog/changelog.html:116
 #: kallithea/templates/compare/compare_cs.html:63
 msgid "Expand commit message"
 msgstr "Développer le message de commit"
 
-#: kallithea/templates/changelog/changelog.html:124
+#: kallithea/templates/changelog/changelog.html:125
 #: kallithea/templates/compare/compare_cs.html:30
 msgid "Changeset has comments"
 msgstr "Le changeset a des commentaires"
 
-#: kallithea/templates/changelog/changelog.html:134
-#: kallithea/templates/changelog/changelog_summary_data.html:54
+#: kallithea/templates/changelog/changelog.html:135
+#: kallithea/templates/changelog/changelog_summary_data.html:57
 #: kallithea/templates/changeset/changeset.html:94
 #: kallithea/templates/changeset/changeset_range.html:92
 #, python-format
 msgid "Bookmark %s"
 msgstr "Marque-page %s"
 
-#: kallithea/templates/changelog/changelog.html:140
-#: kallithea/templates/changelog/changelog_summary_data.html:60
+#: kallithea/templates/changelog/changelog.html:141
+#: kallithea/templates/changelog/changelog_summary_data.html:63
 #: kallithea/templates/changeset/changeset.html:101
 #: kallithea/templates/changeset/changeset_range.html:98
+#: kallithea/templates/compare/compare_cs.html:69
+#: kallithea/templates/pullrequests/pullrequest_show.html:203
 #, python-format
 msgid "Tag %s"
 msgstr "Tag %s"
 
-#: kallithea/templates/changelog/changelog.html:145
-#: kallithea/templates/changelog/changelog_summary_data.html:65
+#: kallithea/templates/changelog/changelog.html:146
+#: kallithea/templates/changelog/changelog_summary_data.html:68
 #: kallithea/templates/changeset/changeset.html:106
 #: kallithea/templates/changeset/changeset_range.html:102
 #, python-format
 msgid "Branch %s"
 msgstr "Branche %s"
 
-#: kallithea/templates/changelog/changelog.html:310
+#: kallithea/templates/changelog/changelog.html:311
 msgid "There are no changes yet"
 msgstr "Il n’y a aucun changement pour le moment"
 
@@ -4997,7 +5000,7 @@
 
 #: kallithea/templates/changelog/changelog_details.html:6
 #: kallithea/templates/changeset/changeset.html:79
-#: kallithea/templates/changeset/diff_block.html:79
+#: kallithea/templates/changeset/diff_block.html:47
 msgid "Added"
 msgstr "Ajouté"
 
@@ -5027,21 +5030,21 @@
 msgid "Refs"
 msgstr "Refs"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:81
+#: kallithea/templates/changelog/changelog_summary_data.html:84
 msgid "Add or upload files directly via Kallithea"
 msgstr "Ajouter ou téléverser des fichiers directement via Kallithea"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:84
+#: kallithea/templates/changelog/changelog_summary_data.html:87
 #: kallithea/templates/files/files_add.html:21
 #: kallithea/templates/files/files_ypjax.html:9
 msgid "Add New File"
 msgstr "Ajouter un nouveau fichier"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:90
+#: kallithea/templates/changelog/changelog_summary_data.html:93
 msgid "Push new repository"
 msgstr "Pusher le nouveau dépôt"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:98
+#: kallithea/templates/changelog/changelog_summary_data.html:101
 msgid "Existing repository?"
 msgstr "Le dépôt existe déjà ?"
 
@@ -5059,13 +5062,13 @@
 msgstr "Révision fille"
 
 #: kallithea/templates/changeset/changeset.html:50
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #: kallithea/templates/changeset/changeset_range.html:48
 msgid "Changeset status"
 msgstr "Statut du changeset"
 
 #: kallithea/templates/changeset/changeset.html:54
-#: kallithea/templates/changeset/diff_block.html:27
+#: kallithea/templates/changeset/diff_block.html:72
 #: kallithea/templates/files/diff_2way.html:49
 msgid "Raw diff"
 msgstr "Diff brut"
@@ -5075,7 +5078,7 @@
 msgstr "Diff patch"
 
 #: kallithea/templates/changeset/changeset.html:60
-#: kallithea/templates/changeset/diff_block.html:30
+#: kallithea/templates/changeset/diff_block.html:75
 #: kallithea/templates/files/diff_2way.html:52
 msgid "Download diff"
 msgstr "Télécharger le diff"
@@ -5102,8 +5105,8 @@
 msgstr "Précédé par :"
 
 #: kallithea/templates/changeset/changeset.html:166
-#: kallithea/templates/compare/compare_diff.html:54
-#: kallithea/templates/pullrequests/pullrequest_show.html:318
+#: kallithea/templates/compare/compare_diff.html:60
+#: kallithea/templates/pullrequests/pullrequest_show.html:329
 #, python-format
 msgid "%s file changed"
 msgid_plural "%s files changed"
@@ -5111,8 +5114,8 @@
 msgstr[1] "%s fichiers changés"
 
 #: kallithea/templates/changeset/changeset.html:168
-#: kallithea/templates/compare/compare_diff.html:56
-#: kallithea/templates/pullrequests/pullrequest_show.html:320
+#: kallithea/templates/compare/compare_diff.html:62
+#: kallithea/templates/pullrequests/pullrequest_show.html:331
 #, python-format
 msgid "%s file changed with %s insertions and %s deletions"
 msgid_plural "%s files changed with %s insertions and %s deletions"
@@ -5121,13 +5124,13 @@
 
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Show full diff anyway"
 msgstr "Afficher le diff complet quand même"
 
-#: kallithea/templates/changeset/changeset.html:247
-#: kallithea/templates/changeset/changeset.html:284
+#: kallithea/templates/changeset/changeset.html:231
+#: kallithea/templates/changeset/changeset.html:268
 msgid "No revisions"
 msgstr "Aucune révision"
 
@@ -5143,106 +5146,87 @@
 msgid "on this changeset"
 msgstr "sur ce changeset"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
 msgid "Delete comment?"
 msgstr "Supprimer le commentaire ?"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 msgid "Status change"
 msgstr "Changement de statut"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:59
-msgid "Commenting on line {1}."
-msgstr "Commentaire sur la ligne {1}."
+msgid "Commenting on line."
+msgstr "Création d’un commentaire sur la ligne."
 
 #: kallithea/templates/changeset/changeset_file_comment.html:60
-#: kallithea/templates/changeset/changeset_file_comment.html:148
-#, python-format
-msgid "Comments parsed using %s syntax with %s support."
-msgstr ""
-"Les commentaires sont analysés avec la syntaxe %s, avec le support de la "
-"commande %s."
-
-#: kallithea/templates/changeset/changeset_file_comment.html:62
-msgid "Use @username inside this text to notify another user"
+msgid ""
+"Comments are in plain text. Use @username inside this text to notify "
+"another user."
 msgstr ""
-"Utilisez @nomutilisateur dans ce texte pour envoyer une notification à un "
-"autre utilisateur"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:72
-#: kallithea/templates/changeset/changeset_file_comment.html:184
-msgid "Comment preview"
-msgstr "Aperçu du commentaire"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:77
+"Les commentaires sont du texte brut. Utilisez @nomutilisateur dans ce texte "
+"pour envoyer une notification à un autre utilisateur."
+
+#: kallithea/templates/changeset/changeset_file_comment.html:67
+msgid "Set changeset status"
+msgstr "Modifier le statut du changeset"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:69
+msgid "Vote for pull request status"
+msgstr "Voter pour le statut de la requête de pull"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:75
+msgid "No change"
+msgstr "Aucun changement"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:88
+msgid "Finish pull request"
+msgstr "Terminer la requête de pull"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:91
+msgid "Close"
+msgstr "Fermer"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:103
 msgid "Submitting ..."
 msgstr "Envoi…"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:80
-#: kallithea/templates/changeset/changeset_file_comment.html:190
+#: kallithea/templates/changeset/changeset_file_comment.html:104
 msgid "Comment"
 msgstr "Commentaire"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:82
-#: kallithea/templates/changeset/changeset_file_comment.html:191
-msgid "Preview"
-msgstr "Aperçu"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "You need to be logged in to comment."
 msgstr "Vous devez être connecté pour poster des commentaires."
 
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "Login now"
 msgstr "Se connecter maintenant"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:94
+#: kallithea/templates/changeset/changeset_file_comment.html:116
 msgid "Hide"
 msgstr "Masquer"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:106
+#: kallithea/templates/changeset/changeset_file_comment.html:128
 #, python-format
 msgid "%d comment"
 msgid_plural "%d comments"
 msgstr[0] "%d commentaire"
 msgstr[1] "%d commentaires"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:107
+#: kallithea/templates/changeset/changeset_file_comment.html:129
 #, python-format
 msgid "%d inline"
 msgid_plural "%d inline"
 msgstr[0] "%d de ligne"
 msgstr[1] "%d de ligne"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:108
+#: kallithea/templates/changeset/changeset_file_comment.html:130
 #, python-format
 msgid "%d general"
 msgid_plural "%d general"
 msgstr[0] "%d général"
 msgstr[1] "%d généraux"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:150
-msgid "Use @username inside this text to notify another user."
-msgstr ""
-"Utilisez @nomutilisateur dans ce texte pour envoyer une notification à un "
-"autre utilisateur."
-
-#: kallithea/templates/changeset/changeset_file_comment.html:157
-msgid "Vote for pull request status"
-msgstr "Voter pour le statut de la requête de pull"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:159
-msgid "Set changeset status"
-msgstr "Modifier le statut du changeset"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:163
-msgid "No change"
-msgstr "Aucun changement"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:176
-msgid "Close"
-msgstr "Fermer"
-
 #: kallithea/templates/changeset/changeset_range.html:5
 #, python-format
 msgid "%s Changesets"
@@ -5252,29 +5236,28 @@
 msgid "Files affected"
 msgstr "Fichiers affectés"
 
-#: kallithea/templates/changeset/diff_block.html:21
+#: kallithea/templates/changeset/diff_block.html:54
+msgid "Deleted"
+msgstr "Supprimé"
+
+#: kallithea/templates/changeset/diff_block.html:57
+msgid "Renamed"
+msgstr "Renommé"
+
+#: kallithea/templates/changeset/diff_block.html:66
 #: kallithea/templates/files/diff_2way.html:43
 msgid "Show full diff for this file"
 msgstr "Afficher le diff complet pour ce fichier"
 
-#: kallithea/templates/changeset/diff_block.html:24
-#: kallithea/templates/changeset/diff_block.html:98
+#: kallithea/templates/changeset/diff_block.html:69
 #: kallithea/templates/files/diff_2way.html:46
 msgid "Show full side-by-side diff for this file"
 msgstr "Afficher le diff complet côte-à-côte pour ce fichier"
 
-#: kallithea/templates/changeset/diff_block.html:38
+#: kallithea/templates/changeset/diff_block.html:83
 msgid "Show inline comments"
 msgstr "Afficher les commentaires de ligne"
 
-#: kallithea/templates/changeset/diff_block.html:86
-msgid "Deleted"
-msgstr "Supprimé"
-
-#: kallithea/templates/changeset/diff_block.html:89
-msgid "Renamed"
-msgstr "Renommé"
-
 #: kallithea/templates/compare/compare_cs.html:4
 msgid "No changesets"
 msgstr "Aucun changeset"
@@ -5283,6 +5266,11 @@
 msgid "Ancestor"
 msgstr "Ancêtre"
 
+#: kallithea/templates/compare/compare_cs.html:24
+#, python-format
+msgid "Changeset status: %s"
+msgstr "Statut de changeset : %s"
+
 #: kallithea/templates/compare/compare_cs.html:44
 msgid "First (oldest) changeset in this list"
 msgstr "Premier changeset dans cette liste (le plus vieux)"
@@ -5295,29 +5283,29 @@
 msgid "Position in this list of changesets"
 msgstr "Position dans cette liste de changesets"
 
-#: kallithea/templates/compare/compare_cs.html:76
+#: kallithea/templates/compare/compare_cs.html:85
 msgid "Show merge diff"
 msgstr "Afficher le diff de fusion"
 
-#: kallithea/templates/compare/compare_cs.html:86
-#: kallithea/templates/pullrequests/pullrequest_show.html:310
+#: kallithea/templates/compare/compare_cs.html:95
+#: kallithea/templates/pullrequests/pullrequest_show.html:321
 msgid "Common ancestor"
 msgstr "Ancêtre commun"
 
-#: kallithea/templates/compare/compare_cs.html:90
+#: kallithea/templates/compare/compare_cs.html:99
 msgid "No common ancestor found - repositories are unrelated"
 msgstr "Aucun ancêtre commun trouvé - les dépôts n'ont aucun lien entre eux"
 
-#: kallithea/templates/compare/compare_cs.html:98
+#: kallithea/templates/compare/compare_cs.html:107
 msgid "is"
 msgstr "est"
 
-#: kallithea/templates/compare/compare_cs.html:99
+#: kallithea/templates/compare/compare_cs.html:108
 #, python-format
 msgid "%s changesets"
 msgstr "Changesets de %s"
 
-#: kallithea/templates/compare/compare_cs.html:100
+#: kallithea/templates/compare/compare_cs.html:109
 msgid "behind"
 msgstr "derrière"
 
@@ -5328,28 +5316,28 @@
 msgstr "Comparaison de %s"
 
 #: kallithea/templates/compare/compare_diff.html:13
-#: kallithea/templates/compare/compare_diff.html:35
+#: kallithea/templates/compare/compare_diff.html:41
 msgid "Compare Revisions"
 msgstr "Comparer les révisions"
 
-#: kallithea/templates/compare/compare_diff.html:33
+#: kallithea/templates/compare/compare_diff.html:39
 msgid "Swap"
 msgstr "Échanger"
 
-#: kallithea/templates/compare/compare_diff.html:42
+#: kallithea/templates/compare/compare_diff.html:48
 msgid "Compare revisions, branches, bookmarks, or tags."
 msgstr "Comparer les révisions, les branches, les marque-pages ou les tags."
 
-#: kallithea/templates/compare/compare_diff.html:47
-#: kallithea/templates/pullrequests/pullrequest_show.html:305
+#: kallithea/templates/compare/compare_diff.html:53
+#: kallithea/templates/pullrequests/pullrequest_show.html:316
 #, python-format
 msgid "Showing %s commit"
 msgid_plural "Showing %s commits"
 msgstr[0] "Affichage de %s commit"
 msgstr[1] "Affichage de %s commits"
 
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
 msgid "Show full diff"
 msgstr "Afficher le diff complet"
 
@@ -5410,19 +5398,27 @@
 "Nous avons reçu une demande de réinitialisation du mot de passe de votre "
 "compte."
 
-#: kallithea/templates/email_templates/password_reset.html:7
+#: kallithea/templates/email_templates/password_reset.html:8
+msgid ""
+"This account is however managed outside this system and the password "
+"cannot be changed here."
+msgstr ""
+"Cependant, ce compte est géré hors de ce système et le mot de passe ne peut "
+"pas être changé ici."
+
+#: kallithea/templates/email_templates/password_reset.html:10
 msgid "To set a new password, click the following link"
 msgstr "Pour choisir un nouveau mot de passe, cliquez sur le lien suivant"
 
-#: kallithea/templates/email_templates/password_reset.html:10
+#: kallithea/templates/email_templates/password_reset.html:13
 msgid ""
 "Should you not be able to use the link above, please type the following "
 "code into the password reset form"
 msgstr ""
-"Si vous ne pouvez pas utiliser le lien ci-dessus, merci de saisir le code "
-"suivant dans le formulaire de réinitialisation de mot de passe"
-
-#: kallithea/templates/email_templates/password_reset.html:12
+"Si vous ne pouvez pas utiliser le lien ci-dessus, merci de saisir le code"
+" suivant dans le formulaire de réinitialisation de mot de passe"
+
+#: kallithea/templates/email_templates/password_reset.html:16
 msgid ""
 "If it weren't you who requested the password reset, just disregard this "
 "message."
@@ -5507,8 +5503,8 @@
 msgstr "Créer un nouveau fichier"
 
 #: kallithea/templates/files/files_add.html:53
-msgid "New file mode"
-msgstr "Mode du nouveau fichier"
+msgid "New file type"
+msgstr "Nouveau type de fichier"
 
 #: kallithea/templates/files/files_add.html:64
 #: kallithea/templates/files/files_delete.html:43
@@ -5628,23 +5624,31 @@
 #: kallithea/templates/files/files_source.html:44
 msgid "Editing files allowed only when on branch head revision"
 msgstr ""
-"Édition de fichiers autorisée uniquement sur la révision de tête (head) de "
-"la branche"
+"Édition de fichiers autorisée uniquement sur la révision de tête (head) "
+"de la branche"
 
 #: kallithea/templates/files/files_source.html:45
 msgid "Deleting files allowed only when on branch head revision"
 msgstr ""
-"Suppression de fichiers autorisée uniquement sur la révision de tête (head) "
-"de la branche"
+"Suppression de fichiers autorisée uniquement sur la révision de tête "
+"(head) de la branche"
 
 #: kallithea/templates/files/files_source.html:63
 #, python-format
 msgid "Binary file (%s)"
 msgstr "Fichier binaire (%s)"
 
-#: kallithea/templates/files/files_source.html:73
-msgid "File is too big to display"
-msgstr "Ce fichier est trop gros pour être affiché"
+#: kallithea/templates/files/files_source.html:74
+msgid "File is too big to display."
+msgstr "Ce fichier est trop gros pour être affiché."
+
+#: kallithea/templates/files/files_source.html:76
+msgid "Show full annotation anyway."
+msgstr "Afficher les annotations complètes quand même."
+
+#: kallithea/templates/files/files_source.html:78
+msgid "Show as raw."
+msgstr "Afficher en tant que texte brut."
 
 #: kallithea/templates/files/files_ypjax.html:5
 msgid "annotation"
@@ -5897,8 +5901,8 @@
 "This is just a range of changesets and doesn't have a target or a real "
 "merge ancestor."
 msgstr ""
-"Ceci est juste une série de changesets, et n'a pas de cible ou de véritable "
-"ancêtre de fusion."
+"Ceci est juste une série de changesets, et n'a pas de cible ou de "
+"véritable ancêtre de fusion."
 
 #: kallithea/templates/pullrequests/pullrequest_show.html:133
 msgid "Pull changes"
@@ -5912,39 +5916,49 @@
 msgid "Current revision - no change"
 msgstr "Révision courante - aucun changement"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:213
+#: kallithea/templates/pullrequests/pullrequest_show.html:215
+msgid ""
+"Pull requests do not change once created. Select a revision and save to "
+"replace this pull request with a new one."
+msgstr ""
+"Les requêtes de pull ne peuvent pas changer après leur création. "
+"Sélectionner une révision puis sauvegarder afin de remplacer cette requête "
+"de pull par une nouvelle."
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:224
 msgid "Pull Request Reviewers"
 msgstr "Relecteurs de la requête de pull"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:238
+#: kallithea/templates/pullrequests/pullrequest_show.html:249
 msgid "Remove reviewer"
 msgstr "Supprimer le relecteur"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:250
-msgid "Type name of reviewer to add"
-msgstr "Saisir le nom du relecteur à ajouter"
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:258
-msgid "Potential Reviewers"
-msgstr "Relecteurs potentiels"
-
 #: kallithea/templates/pullrequests/pullrequest_show.html:261
+msgid "Type name of reviewer to add"
+msgstr "Saisir le nom du relecteur à ajouter"
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:269
+msgid "Potential Reviewers"
+msgstr "Relecteurs potentiels"
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:272
 msgid "Click to add the repository owner as reviewer:"
 msgstr "Cliquer pour ajouter le propriétaire du dépôt comme relecteur :"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:284
+#: kallithea/templates/pullrequests/pullrequest_show.html:295
 msgid "Save Changes"
 msgstr "Enregistrer les changements"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:285
-msgid "Save as New Pull Request"
-msgstr "Sauvegarder en tant que nouvelle requête de pull"
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:286
+#: kallithea/templates/pullrequests/pullrequest_show.html:296
+msgid "Save Updates as New Pull Request"
+msgstr ""
+"Sauvegarder les modifications entrantes en tant que nouvelle requête de pull"
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:297
 msgid "Cancel Changes"
 msgstr "Annuler les modifications"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#: kallithea/templates/pullrequests/pullrequest_show.html:307
 msgid "Pull Request Content"
 msgstr "Contenu de la requête de pull"
 
@@ -5955,8 +5969,8 @@
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:11
 #, python-format
-msgid "Pull Requests from %s'"
-msgstr "Requête de pull depuis %s'"
+msgid "Pull Requests from '%s'"
+msgstr "Requêtes de pull depuis '%s'"
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:13
 #, python-format
@@ -5988,7 +6002,8 @@
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:30
 msgid "Show closed pull requests (in addition to open pull requests)"
 msgstr ""
-"Afficher les requêtes de pull fermées (en plus des requêtes de pull ouvertes)"
+"Afficher les requêtes de pull fermées (en plus des requêtes de pull "
+"ouvertes)"
 
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:35
 msgid "Pull Requests Created by Me"
@@ -6422,30 +6437,6 @@
 #~ msgid "reviewer"
 #~ msgstr ""
 
-#~ msgid ""
-#~ "Your password reset was successful, new"
-#~ " password has been sent to your "
-#~ "email"
-#~ msgstr ""
-#~ "Votre mot de passe a été "
-#~ "réinitialisé. Votre nouveau mot de passe"
-#~ " vous a été envoyé par e-mail"
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " changeset %(short_id)s on %(branch)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Added by %(pr_username)s] %(repo_name)s pull"
-#~ " request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " pull request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
 #~ msgid "Your new password"
 #~ msgstr "Votre nouveau mot de passe"
 
@@ -6469,3 +6460,24 @@
 
 #~ msgid "Created by"
 #~ msgstr "créé"
+
+#~ msgid "This pull request can be updated with changes on %s:"
+#~ msgstr ""
+
+#~ msgid "Confirm to invalidate repository cache."
+#~ msgstr "Voulez-vous vraiment invalider le cache du dépôt ?"
+
+#~ msgid "Comments parsed using %s syntax with %s support."
+#~ msgstr ""
+
+#~ msgid "Use @username inside this text to notify another user"
+#~ msgstr ""
+
+#~ msgid "Comment preview"
+#~ msgstr "Aperçu du commentaire"
+
+#~ msgid "Preview"
+#~ msgstr "Aperçu"
+
+#~ msgid "New file mode"
+#~ msgstr "Mode du nouveau fichier"
--- a/kallithea/i18n/how_to	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/i18n/how_to	Fri Nov 18 01:11:13 2016 +0100
@@ -94,4 +94,4 @@
 
 Run Kallithea tests by executing::
 
-    nosetests
+    py.test
--- a/kallithea/i18n/hu/LC_MESSAGES/kallithea.po	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/i18n/hu/LC_MESSAGES/kallithea.po	Fri Nov 18 01:11:13 2016 +0100
@@ -7,7 +7,7 @@
 msgstr ""
 "Project-Id-Version: Kallithea 0.3\n"
 "Report-Msgid-Bugs-To: translations@kallithea-scm.org\n"
-"POT-Creation-Date: 2015-09-08 10:34+0200\n"
+"POT-Creation-Date: 2016-03-14 16:51+0100\n"
 "PO-Revision-Date: 2015-04-11 00:59+0200\n"
 "Last-Translator: Balázs Úr <urbalazs@gmail.com>\n"
 "Language-Team: Hungarian "
@@ -19,12 +19,12 @@
 "Plural-Forms: nplurals=2; plural=n != 1;\n"
 "X-Generator: Weblate 2.3-dev\n"
 
-#: kallithea/controllers/changelog.py:86
-#: kallithea/controllers/pullrequests.py:238 kallithea/lib/base.py:512
+#: kallithea/controllers/changelog.py:85
+#: kallithea/controllers/pullrequests.py:240 kallithea/lib/base.py:515
 msgid "There are no changesets yet"
 msgstr ""
 
-#: kallithea/controllers/changelog.py:166
+#: kallithea/controllers/changelog.py:164
 #: kallithea/controllers/admin/permissions.py:61
 #: kallithea/controllers/admin/permissions.py:65
 #: kallithea/controllers/admin/permissions.py:69
@@ -36,35 +36,29 @@
 msgid "None"
 msgstr ""
 
-#: kallithea/controllers/changelog.py:169 kallithea/controllers/files.py:196
+#: kallithea/controllers/changelog.py:167 kallithea/controllers/files.py:198
 msgid "(closed)"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:89
+#: kallithea/controllers/changeset.py:88
 msgid "Show whitespace"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:96 kallithea/controllers/changeset.py:103
+#: kallithea/controllers/changeset.py:95 kallithea/controllers/changeset.py:102
 #: kallithea/templates/files/diff_2way.html:55
 msgid "Ignore whitespace"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:169
+#: kallithea/controllers/changeset.py:168
 #, python-format
 msgid "Increase diff context to %(num)s lines"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:212 kallithea/controllers/files.py:96
-#: kallithea/controllers/files.py:116 kallithea/controllers/files.py:742
+#: kallithea/controllers/changeset.py:233 kallithea/controllers/files.py:97
+#: kallithea/controllers/files.py:117 kallithea/controllers/files.py:744
 msgid "Such revision does not exist for this repository"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:383
-msgid ""
-"Changing status on a changeset associated with a closed pull request is "
-"not allowed"
-msgstr ""
-
 #: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:41
 msgid "Select changeset"
 msgstr ""
@@ -116,10 +110,10 @@
 #: kallithea/controllers/feed.py:87
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Changeset was too big and was cut off..."
 msgstr ""
 
@@ -128,111 +122,111 @@
 msgid "%s committed on %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:91
+#: kallithea/controllers/files.py:92
 msgid "Click here to add new file"
 msgstr ""
 
-#: kallithea/controllers/files.py:92
+#: kallithea/controllers/files.py:93
 #, python-format
 msgid "There are no files yet. %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:193
+#: kallithea/controllers/files.py:195
 #, python-format
 msgid "%s at %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:305 kallithea/controllers/files.py:365
-#: kallithea/controllers/files.py:432
+#: kallithea/controllers/files.py:307 kallithea/controllers/files.py:367
+#: kallithea/controllers/files.py:434
 #, python-format
 msgid "This repository has been locked by %s on %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:317
-msgid "You can only delete files with revision being a valid branch "
-msgstr ""
-
-#: kallithea/controllers/files.py:328
+#: kallithea/controllers/files.py:319
+msgid "You can only delete files with revision being a valid branch"
+msgstr ""
+
+#: kallithea/controllers/files.py:330
 #, python-format
 msgid "Deleted file %s via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:350
+#: kallithea/controllers/files.py:352
 #, python-format
 msgid "Successfully deleted file %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:354 kallithea/controllers/files.py:420
-#: kallithea/controllers/files.py:501
+#: kallithea/controllers/files.py:356 kallithea/controllers/files.py:422
+#: kallithea/controllers/files.py:503
 msgid "Error occurred during commit"
 msgstr ""
 
-#: kallithea/controllers/files.py:377
-msgid "You can only edit files with revision being a valid branch "
-msgstr ""
-
-#: kallithea/controllers/files.py:391
+#: kallithea/controllers/files.py:379
+msgid "You can only edit files with revision being a valid branch"
+msgstr ""
+
+#: kallithea/controllers/files.py:393
 #, python-format
 msgid "Edited file %s via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:407
+#: kallithea/controllers/files.py:409
 msgid "No changes"
 msgstr ""
 
-#: kallithea/controllers/files.py:416 kallithea/controllers/files.py:490
+#: kallithea/controllers/files.py:418 kallithea/controllers/files.py:492
 #, python-format
 msgid "Successfully committed to %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:443
+#: kallithea/controllers/files.py:445
 msgid "Added file via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:464
+#: kallithea/controllers/files.py:466
 msgid "No content"
 msgstr ""
 
-#: kallithea/controllers/files.py:468
+#: kallithea/controllers/files.py:470
 msgid "No filename"
 msgstr ""
 
-#: kallithea/controllers/files.py:493
+#: kallithea/controllers/files.py:495
 msgid "Location must be relative path and must not contain .. in path"
 msgstr ""
 
-#: kallithea/controllers/files.py:526
+#: kallithea/controllers/files.py:528
 msgid "Downloads disabled"
 msgstr ""
 
-#: kallithea/controllers/files.py:537
-#, python-format
-msgid "Unknown revision %s"
-msgstr ""
-
 #: kallithea/controllers/files.py:539
-msgid "Empty repository"
+#, python-format
+msgid "Unknown revision %s"
 msgstr ""
 
 #: kallithea/controllers/files.py:541
+msgid "Empty repository"
+msgstr ""
+
+#: kallithea/controllers/files.py:543
 msgid "Unknown archive type"
 msgstr ""
 
-#: kallithea/controllers/files.py:771
+#: kallithea/controllers/files.py:773
 #: kallithea/templates/changeset/changeset_range.html:9
 #: kallithea/templates/email_templates/pull_request.html:15
 #: kallithea/templates/pullrequests/pullrequest.html:97
 msgid "Changesets"
 msgstr ""
 
-#: kallithea/controllers/files.py:772 kallithea/controllers/pullrequests.py:176
-#: kallithea/model/scm.py:820 kallithea/templates/switch_to_list.html:3
+#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:175
+#: kallithea/model/scm.py:716 kallithea/templates/switch_to_list.html:3
 #: kallithea/templates/branches/branches.html:10
 msgid "Branches"
 msgstr ""
 
-#: kallithea/controllers/files.py:773 kallithea/controllers/pullrequests.py:177
-#: kallithea/model/scm.py:831 kallithea/templates/switch_to_list.html:25
+#: kallithea/controllers/files.py:775 kallithea/controllers/pullrequests.py:176
+#: kallithea/model/scm.py:727 kallithea/templates/switch_to_list.html:25
 #: kallithea/templates/tags/tags.html:10
 msgid "Tags"
 msgstr ""
@@ -246,7 +240,7 @@
 msgid "Groups"
 msgstr ""
 
-#: kallithea/controllers/home.py:89
+#: kallithea/controllers/home.py:94
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:106
 #: kallithea/templates/admin/repos/repo_add.html:12
 #: kallithea/templates/admin/repos/repo_add.html:16
@@ -254,23 +248,27 @@
 #: kallithea/templates/admin/users/user_edit_advanced.html:6
 #: kallithea/templates/base/base.html:60 kallithea/templates/base/base.html:77
 #: kallithea/templates/base/base.html:124
-#: kallithea/templates/base/base.html:390
-#: kallithea/templates/base/base.html:562
+#: kallithea/templates/base/base.html:479
+#: kallithea/templates/base/base.html:653
 msgid "Repositories"
 msgstr ""
 
-#: kallithea/controllers/home.py:130
+#: kallithea/controllers/home.py:139
 #: kallithea/templates/files/files_add.html:32
 #: kallithea/templates/files/files_delete.html:23
 #: kallithea/templates/files/files_edit.html:32
 msgid "Branch"
 msgstr ""
 
-#: kallithea/controllers/home.py:136
+#: kallithea/controllers/home.py:145 kallithea/templates/switch_to_list.html:16
+msgid "Closed Branches"
+msgstr ""
+
+#: kallithea/controllers/home.py:151
 msgid "Tag"
 msgstr ""
 
-#: kallithea/controllers/home.py:142
+#: kallithea/controllers/home.py:157
 msgid "Bookmark"
 msgstr ""
 
@@ -281,158 +279,163 @@
 msgstr ""
 
 #: kallithea/controllers/journal.py:115 kallithea/controllers/journal.py:157
-#: kallithea/templates/base/base.html:222
+#: kallithea/templates/base/base.html:306
 #: kallithea/templates/journal/journal.html:4
 #: kallithea/templates/journal/journal.html:12
 msgid "Journal"
 msgstr ""
 
-#: kallithea/controllers/login.py:151 kallithea/controllers/login.py:197
+#: kallithea/controllers/login.py:144 kallithea/controllers/login.py:190
 msgid "Bad captcha"
 msgstr ""
 
-#: kallithea/controllers/login.py:157
-msgid "You have successfully registered into Kallithea"
-msgstr ""
-
-#: kallithea/controllers/login.py:202
+#: kallithea/controllers/login.py:150
+msgid "You have successfully registered with %s"
+msgstr ""
+
+#: kallithea/controllers/login.py:195
 msgid "A password reset confirmation code has been sent"
 msgstr ""
 
-#: kallithea/controllers/login.py:251
+#: kallithea/controllers/login.py:244
 msgid "Invalid password reset token"
 msgstr ""
 
-#: kallithea/controllers/login.py:256
+#: kallithea/controllers/login.py:249
 #: kallithea/controllers/admin/my_account.py:167
 msgid "Successfully updated password"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:124
+#: kallithea/controllers/pullrequests.py:123
 #, python-format
 msgid "%s (closed)"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:152
+#: kallithea/controllers/pullrequests.py:151
 #: kallithea/templates/changeset/changeset.html:12
 #: kallithea/templates/email_templates/changeset_comment.html:17
 msgid "Changeset"
 msgstr ""
 
+#: kallithea/controllers/pullrequests.py:172
+msgid "Special"
+msgstr ""
+
 #: kallithea/controllers/pullrequests.py:173
-msgid "Special"
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:174
 msgid "Peer branches"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:175 kallithea/model/scm.py:826
+#: kallithea/controllers/pullrequests.py:174 kallithea/model/scm.py:722
 #: kallithea/templates/switch_to_list.html:38
 #: kallithea/templates/bookmarks/bookmarks.html:10
 msgid "Bookmarks"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:310
+#: kallithea/controllers/pullrequests.py:312
 #, python-format
 msgid "Error creating pull request: %s"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:356
-#: kallithea/controllers/pullrequests.py:503
+#: kallithea/controllers/pullrequests.py:358
+#: kallithea/controllers/pullrequests.py:505
 msgid "No description"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:363
+#: kallithea/controllers/pullrequests.py:365
 msgid "Successfully opened new pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:366
-#: kallithea/controllers/pullrequests.py:453
-#: kallithea/controllers/pullrequests.py:509
+#: kallithea/controllers/pullrequests.py:368
+#: kallithea/controllers/pullrequests.py:455
+#: kallithea/controllers/pullrequests.py:512
 #, python-format
 msgid "Invalid reviewer \"%s\" specified"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:369
-#: kallithea/controllers/pullrequests.py:456
+#: kallithea/controllers/pullrequests.py:371
+#: kallithea/controllers/pullrequests.py:458
 msgid "Error occurred while creating pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:401
+#: kallithea/controllers/pullrequests.py:403
 msgid "Missing changesets since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:408
+#: kallithea/controllers/pullrequests.py:410
 #, python-format
 msgid "New changesets on %s %s since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:415
+#: kallithea/controllers/pullrequests.py:417
 msgid "Ancestor didn't change - show diff since previous version:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:422
+#: kallithea/controllers/pullrequests.py:424
 #, python-format
 msgid ""
 "This pull request is based on another %s revision and there is no simple "
 "diff."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:424
+#: kallithea/controllers/pullrequests.py:426
 #, python-format
 msgid "No changes found on %s %s since previous version."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:462
+#: kallithea/controllers/pullrequests.py:464
 #, python-format
 msgid "Closed, replaced by %s ."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:470
+#: kallithea/controllers/pullrequests.py:472
 msgid "Pull request update created"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:513
+#: kallithea/controllers/pullrequests.py:516
 msgid "Pull request updated"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:528
+#: kallithea/controllers/pullrequests.py:531
 msgid "Successfully deleted pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:594
+#: kallithea/controllers/pullrequests.py:597
 #, python-format
 msgid "This pull request has already been merged to %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:596
+#: kallithea/controllers/pullrequests.py:599
 msgid "This pull request has been closed and can not be updated."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:614
-#, python-format
-msgid "This pull request can be updated with changes on %s:"
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:617
+#, python-format
+msgid "The following changes are available on %s:"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:621
 msgid "No changesets found for updating this pull request."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:625
+#: kallithea/controllers/pullrequests.py:629
 #, python-format
 msgid "Note: Branch %s has another head: %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:631
+#: kallithea/controllers/pullrequests.py:635
 msgid "Git pull requests don't support updates yet."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:722
-msgid "No permission to change pull request status"
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:727
+msgid "No permission to change pull request status"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:738
+#, python-format
+msgid "Successfully deleted pull request %s"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:748
 msgid "Closing."
 msgstr ""
 
@@ -448,12 +451,12 @@
 msgid "An error occurred during search operation."
 msgstr ""
 
-#: kallithea/controllers/summary.py:180
+#: kallithea/controllers/summary.py:181
 #: kallithea/templates/summary/summary.html:384
 msgid "No data ready yet"
 msgstr ""
 
-#: kallithea/controllers/summary.py:183
+#: kallithea/controllers/summary.py:184
 #: kallithea/templates/summary/summary.html:98
 msgid "Statistics are disabled for this repository"
 msgstr ""
@@ -474,64 +477,64 @@
 msgid "Error occurred during update of defaults"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/gists.py:58
 #: kallithea/controllers/admin/my_account.py:243
+#: kallithea/controllers/admin/users.py:284
+msgid "Forever"
+msgstr ""
+
+#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/my_account.py:244
 #: kallithea/controllers/admin/users.py:285
-msgid "Forever"
+msgid "5 minutes"
 msgstr ""
 
 #: kallithea/controllers/admin/gists.py:60
-#: kallithea/controllers/admin/my_account.py:244
+#: kallithea/controllers/admin/my_account.py:245
 #: kallithea/controllers/admin/users.py:286
-msgid "5 minutes"
+msgid "1 hour"
 msgstr ""
 
 #: kallithea/controllers/admin/gists.py:61
-#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/my_account.py:246
 #: kallithea/controllers/admin/users.py:287
-msgid "1 hour"
+msgid "1 day"
 msgstr ""
 
 #: kallithea/controllers/admin/gists.py:62
-#: kallithea/controllers/admin/my_account.py:246
+#: kallithea/controllers/admin/my_account.py:247
 #: kallithea/controllers/admin/users.py:288
-msgid "1 day"
-msgstr ""
-
-#: kallithea/controllers/admin/gists.py:63
-#: kallithea/controllers/admin/my_account.py:247
-#: kallithea/controllers/admin/users.py:289
 msgid "1 month"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:67
+#: kallithea/controllers/admin/gists.py:66
 #: kallithea/controllers/admin/my_account.py:249
-#: kallithea/controllers/admin/users.py:291
+#: kallithea/controllers/admin/users.py:290
 msgid "Lifetime"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:146
+#: kallithea/controllers/admin/gists.py:145
 msgid "Error occurred during gist creation"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:184
+#: kallithea/controllers/admin/gists.py:183
 #, python-format
 msgid "Deleted gist %s"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:233
+#: kallithea/controllers/admin/gists.py:232
 msgid "Unmodified"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:262
+#: kallithea/controllers/admin/gists.py:261
 msgid "Successfully updated gist content"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:267
+#: kallithea/controllers/admin/gists.py:266
 msgid "Successfully updated gist data"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:270
+#: kallithea/controllers/admin/gists.py:269
 #, python-format
 msgid "Error occurred during update of gist %s"
 msgstr ""
@@ -546,7 +549,7 @@
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:144
-#: kallithea/controllers/admin/users.py:202
+#: kallithea/controllers/admin/users.py:201
 #, python-format
 msgid "Error occurred during update of user %s"
 msgstr ""
@@ -556,33 +559,33 @@
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:220
-#: kallithea/controllers/admin/users.py:415
+#: kallithea/controllers/admin/users.py:414
 #, python-format
 msgid "Added email %s to user"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:226
-#: kallithea/controllers/admin/users.py:421
+#: kallithea/controllers/admin/users.py:420
 msgid "An error occurred during email saving"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:235
-#: kallithea/controllers/admin/users.py:433
+#: kallithea/controllers/admin/users.py:432
 msgid "Removed email from user"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:259
-#: kallithea/controllers/admin/users.py:308
+#: kallithea/controllers/admin/users.py:307
 msgid "API key successfully created"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:271
-#: kallithea/controllers/admin/users.py:321
+#: kallithea/controllers/admin/users.py:320
 msgid "API key successfully reset"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:275
-#: kallithea/controllers/admin/users.py:325
+#: kallithea/controllers/admin/users.py:324
 msgid "API key successfully deleted"
 msgstr ""
 
@@ -632,10 +635,10 @@
 #: kallithea/templates/admin/users/user_edit_profile.html:105
 #: kallithea/templates/admin/users/users.html:10
 #: kallithea/templates/admin/users/users.html:55
-#: kallithea/templates/base/base.html:252
-#: kallithea/templates/base/base.html:253
-#: kallithea/templates/base/base.html:259
-#: kallithea/templates/base/base.html:260
+#: kallithea/templates/base/base.html:336
+#: kallithea/templates/base/base.html:337
+#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:344
 #: kallithea/templates/base/perms_summary.html:17
 msgid "Admin"
 msgstr ""
@@ -666,7 +669,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1564
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1603
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1655
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1701
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1705
 msgid "Manual activation of external account"
 msgstr ""
 
@@ -678,7 +681,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1565
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1604
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1656
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1702
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1706
 msgid "Automatic activation of external account"
 msgstr ""
 
@@ -699,244 +702,244 @@
 msgid "Error occurred during update of permissions"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:188
+#: kallithea/controllers/admin/repo_groups.py:187
 #, python-format
 msgid "Error occurred during creation of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:193
+#: kallithea/controllers/admin/repo_groups.py:192
 #, python-format
 msgid "Created repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:250
+#: kallithea/controllers/admin/repo_groups.py:249
 #, python-format
 msgid "Updated repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:266
+#: kallithea/controllers/admin/repo_groups.py:265
 #, python-format
 msgid "Error occurred during update of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:284
+#: kallithea/controllers/admin/repo_groups.py:283
 #, python-format
 msgid "This group contains %s repositories and cannot be deleted"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:291
+#: kallithea/controllers/admin/repo_groups.py:290
 #, python-format
 msgid "This group contains %s subgroups and cannot be deleted"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:297
+#: kallithea/controllers/admin/repo_groups.py:296
 #, python-format
 msgid "Removed repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:302
+#: kallithea/controllers/admin/repo_groups.py:301
 #, python-format
 msgid "Error occurred during deletion of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:405
-#: kallithea/controllers/admin/repo_groups.py:440
+#: kallithea/controllers/admin/repo_groups.py:404
+#: kallithea/controllers/admin/repo_groups.py:439
 #: kallithea/controllers/admin/user_groups.py:340
 msgid "Cannot revoke permission for yourself as admin"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:420
+#: kallithea/controllers/admin/repo_groups.py:419
 msgid "Repository group permissions updated"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:457
-#: kallithea/controllers/admin/repos.py:398
+#: kallithea/controllers/admin/repo_groups.py:456
+#: kallithea/controllers/admin/repos.py:397
 #: kallithea/controllers/admin/user_groups.py:352
 msgid "An error occurred during revoking of permission"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:152
+#: kallithea/controllers/admin/repos.py:151
 #, python-format
 msgid "Error creating repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:213
+#: kallithea/controllers/admin/repos.py:212
 #, python-format
 msgid "Created repository %s from %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:222
+#: kallithea/controllers/admin/repos.py:221
 #, python-format
 msgid "Forked repository %s as %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:225
+#: kallithea/controllers/admin/repos.py:224
 #, python-format
 msgid "Created repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:262
+#: kallithea/controllers/admin/repos.py:261
 #, python-format
 msgid "Repository %s updated successfully"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:283
+#: kallithea/controllers/admin/repos.py:282
 #, python-format
 msgid "Error occurred during update of repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:310
+#: kallithea/controllers/admin/repos.py:309
 #, python-format
 msgid "Detached %s forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:313
+#: kallithea/controllers/admin/repos.py:312
 #, python-format
 msgid "Deleted %s forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:318
+#: kallithea/controllers/admin/repos.py:317
 #, python-format
 msgid "Deleted repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:321
+#: kallithea/controllers/admin/repos.py:320
 #, python-format
 msgid "Cannot delete repository %s which still has forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:326
+#: kallithea/controllers/admin/repos.py:325
 #, python-format
 msgid "An error occurred during deletion of %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:374
+#: kallithea/controllers/admin/repos.py:373
 msgid "Repository permissions updated"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:430
+#: kallithea/controllers/admin/repos.py:429
 msgid "An error occurred during creation of field"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:444
+#: kallithea/controllers/admin/repos.py:443
 msgid "An error occurred during removal of field"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:460
+#: kallithea/controllers/admin/repos.py:459
 msgid "-- Not a fork --"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:491
+#: kallithea/controllers/admin/repos.py:490
 msgid "Updated repository visibility in public journal"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:495
+#: kallithea/controllers/admin/repos.py:494
 msgid "An error occurred during setting this repository in public journal"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:512
+#: kallithea/controllers/admin/repos.py:511
 msgid "Nothing"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:514
+#: kallithea/controllers/admin/repos.py:513
 #, python-format
 msgid "Marked repository %s as fork of %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:521
+#: kallithea/controllers/admin/repos.py:520
 msgid "An error occurred during this operation"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:537
-#: kallithea/controllers/admin/repos.py:564
+#: kallithea/controllers/admin/repos.py:536
+#: kallithea/controllers/admin/repos.py:563
 #, fuzzy
 msgid "Repository has been locked"
 msgstr "Ennek a tárolónak %s elágazása van"
 
-#: kallithea/controllers/admin/repos.py:540
-#: kallithea/controllers/admin/repos.py:561
+#: kallithea/controllers/admin/repos.py:539
+#: kallithea/controllers/admin/repos.py:560
 #, fuzzy
 msgid "Repository has been unlocked"
 msgstr "Ennek a tárolónak %s elágazása van"
 
-#: kallithea/controllers/admin/repos.py:543
-#: kallithea/controllers/admin/repos.py:568
+#: kallithea/controllers/admin/repos.py:542
+#: kallithea/controllers/admin/repos.py:567
 msgid "An error occurred during unlocking"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:582
+#: kallithea/controllers/admin/repos.py:581
 msgid "Cache invalidation successful"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:586
+#: kallithea/controllers/admin/repos.py:585
 msgid "An error occurred during cache invalidation"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:601
+#: kallithea/controllers/admin/repos.py:600
 msgid "Pulled from remote location"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:604
+#: kallithea/controllers/admin/repos.py:603
 msgid "An error occurred during pull from remote location"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:637
+#: kallithea/controllers/admin/repos.py:636
 msgid "An error occurred during deletion of repository stats"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:170
+#: kallithea/controllers/admin/settings.py:141
 msgid "Updated VCS settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:174
+#: kallithea/controllers/admin/settings.py:145
 msgid ""
 "Unable to activate hgsubversion support. The \"hgsubversion\" library is "
 "missing"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:180
-#: kallithea/controllers/admin/settings.py:277
+#: kallithea/controllers/admin/settings.py:151
+#: kallithea/controllers/admin/settings.py:248
 msgid "Error occurred while updating application settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:216
+#: kallithea/controllers/admin/settings.py:187
 #, python-format
 msgid "Repositories successfully rescanned. Added: %s. Removed: %s."
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:273
+#: kallithea/controllers/admin/settings.py:244
 msgid "Updated application settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:330
+#: kallithea/controllers/admin/settings.py:301
 msgid "Updated visualisation settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:335
+#: kallithea/controllers/admin/settings.py:306
 msgid "Error occurred during updating visualisation settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:361
+#: kallithea/controllers/admin/settings.py:332
 msgid "Please enter email address"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:376
+#: kallithea/controllers/admin/settings.py:347
 msgid "Send email task created"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:407
+#: kallithea/controllers/admin/settings.py:378
 msgid "Added new hook"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:421
+#: kallithea/controllers/admin/settings.py:392
 msgid "Updated hooks"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:425
+#: kallithea/controllers/admin/settings.py:396
 msgid "Error occurred during hook creation"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:451
+#: kallithea/controllers/admin/settings.py:422
 msgid "Whoosh reindex task scheduled"
 msgstr ""
 
@@ -977,76 +980,80 @@
 msgstr ""
 
 #: kallithea/controllers/admin/user_groups.py:440
-#: kallithea/controllers/admin/users.py:384
+#: kallithea/controllers/admin/users.py:383
 msgid "Updated permissions"
 msgstr ""
 
 #: kallithea/controllers/admin/user_groups.py:444
-#: kallithea/controllers/admin/users.py:388
+#: kallithea/controllers/admin/users.py:387
 msgid "An error occurred during permissions saving"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:134
+#: kallithea/controllers/admin/users.py:133
 #, python-format
 msgid "Created user %s"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:149
+#: kallithea/controllers/admin/users.py:148
 #, python-format
 msgid "Error occurred during creation of user %s"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:182
+#: kallithea/controllers/admin/users.py:181
 msgid "User updated successfully"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:218
+#: kallithea/controllers/admin/users.py:217
 msgid "Successfully deleted user"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:223
+#: kallithea/controllers/admin/users.py:222
 msgid "An error occurred during deletion of user"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:236
+#: kallithea/controllers/admin/users.py:235
 msgid "The default user cannot be edited"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:463
+#: kallithea/controllers/admin/users.py:462
 #, python-format
 msgid "Added IP address %s to user whitelist"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:469
+#: kallithea/controllers/admin/users.py:468
 msgid "An error occurred while adding IP address"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:483
+#: kallithea/controllers/admin/users.py:482
 msgid "Removed IP address from user whitelist"
 msgstr ""
 
-#: kallithea/lib/auth.py:743
+#: kallithea/lib/auth.py:737
 #, python-format
 msgid "IP %s not allowed"
 msgstr ""
 
-#: kallithea/lib/auth.py:756
+#: kallithea/lib/auth.py:750
 msgid "Invalid API key"
 msgstr ""
 
-#: kallithea/lib/auth.py:812
+#: kallithea/lib/auth.py:768
+msgid "CSRF token leak has been detected - all form tokens have been expired"
+msgstr ""
+
+#: kallithea/lib/auth.py:813
 msgid "You need to be a registered user to perform this action"
 msgstr ""
 
-#: kallithea/lib/auth.py:844
+#: kallithea/lib/auth.py:843
 msgid "You need to be signed in to view this page"
 msgstr ""
 
-#: kallithea/lib/base.py:490
+#: kallithea/lib/base.py:493
 msgid "Repository not found in the filesystem"
 msgstr ""
 
-#: kallithea/lib/base.py:516 kallithea/lib/helpers.py:622
+#: kallithea/lib/base.py:519 kallithea/lib/helpers.py:623
 msgid "Changeset not found"
 msgstr ""
 
@@ -1062,125 +1069,125 @@
 msgid "No changes detected"
 msgstr ""
 
-#: kallithea/lib/helpers.py:609
+#: kallithea/lib/helpers.py:610
 #, python-format
 msgid "Deleted branch: %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:611
+#: kallithea/lib/helpers.py:612
 #, python-format
 msgid "Created tag: %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:671
+#: kallithea/lib/helpers.py:672
 #, python-format
 msgid "Show all combined changesets %s->%s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:677
+#: kallithea/lib/helpers.py:678
 msgid "Compare view"
 msgstr ""
 
-#: kallithea/lib/helpers.py:696
-msgid "and"
-msgstr ""
-
 #: kallithea/lib/helpers.py:697
+msgid "and"
+msgstr ""
+
+#: kallithea/lib/helpers.py:698
 #, python-format
 msgid "%s more"
 msgstr ""
 
-#: kallithea/lib/helpers.py:698 kallithea/templates/changelog/changelog.html:44
+#: kallithea/lib/helpers.py:699 kallithea/templates/changelog/changelog.html:44
 msgid "revisions"
 msgstr ""
 
-#: kallithea/lib/helpers.py:722
+#: kallithea/lib/helpers.py:723
 #, python-format
 msgid "Fork name %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:742
+#: kallithea/lib/helpers.py:743
 #, python-format
 msgid "Pull request %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:752
+#: kallithea/lib/helpers.py:753
 msgid "[deleted] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:754 kallithea/lib/helpers.py:766
+#: kallithea/lib/helpers.py:755 kallithea/lib/helpers.py:767
 msgid "[created] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:756
+#: kallithea/lib/helpers.py:757
 msgid "[created] repository as fork"
 msgstr ""
 
-#: kallithea/lib/helpers.py:758 kallithea/lib/helpers.py:768
+#: kallithea/lib/helpers.py:759 kallithea/lib/helpers.py:769
 msgid "[forked] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:760 kallithea/lib/helpers.py:770
+#: kallithea/lib/helpers.py:761 kallithea/lib/helpers.py:771
 msgid "[updated] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:762
+#: kallithea/lib/helpers.py:763
 msgid "[downloaded] archive from repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:764
+#: kallithea/lib/helpers.py:765
 msgid "[delete] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:772
+#: kallithea/lib/helpers.py:773
 msgid "[created] user"
 msgstr ""
 
-#: kallithea/lib/helpers.py:774
+#: kallithea/lib/helpers.py:775
 msgid "[updated] user"
 msgstr ""
 
-#: kallithea/lib/helpers.py:776
+#: kallithea/lib/helpers.py:777
 msgid "[created] user group"
 msgstr ""
 
-#: kallithea/lib/helpers.py:778
+#: kallithea/lib/helpers.py:779
 msgid "[updated] user group"
 msgstr ""
 
-#: kallithea/lib/helpers.py:780
+#: kallithea/lib/helpers.py:781
 msgid "[commented] on revision in repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:782
+#: kallithea/lib/helpers.py:783
 msgid "[commented] on pull request for"
 msgstr ""
 
-#: kallithea/lib/helpers.py:784
+#: kallithea/lib/helpers.py:785
 msgid "[closed] pull request for"
 msgstr ""
 
-#: kallithea/lib/helpers.py:786
+#: kallithea/lib/helpers.py:787
 msgid "[pushed] into"
 msgstr ""
 
-#: kallithea/lib/helpers.py:788
+#: kallithea/lib/helpers.py:789
 msgid "[committed via Kallithea] into repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:790
+#: kallithea/lib/helpers.py:791
 msgid "[pulled from remote] into repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:792
+#: kallithea/lib/helpers.py:793
 msgid "[pulled] from"
 msgstr ""
 
-#: kallithea/lib/helpers.py:794
+#: kallithea/lib/helpers.py:795
 msgid "[started following] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:796
+#: kallithea/lib/helpers.py:797
 msgid "[stopped following] repository"
 msgstr ""
 
@@ -1190,8 +1197,8 @@
 msgstr ""
 
 #: kallithea/lib/helpers.py:1128
-#: kallithea/templates/compare/compare_diff.html:65
-#: kallithea/templates/pullrequests/pullrequest_show.html:326
+#: kallithea/templates/compare/compare_diff.html:71
+#: kallithea/templates/pullrequests/pullrequest_show.html:337
 msgid "No files"
 msgstr ""
 
@@ -1215,7 +1222,7 @@
 msgid "chmod"
 msgstr ""
 
-#: kallithea/lib/helpers.py:1444
+#: kallithea/lib/helpers.py:1469
 #, python-format
 msgid ""
 "%s repository is not mapped to db perhaps it was created or renamed from "
@@ -1223,69 +1230,69 @@
 "repositories"
 msgstr ""
 
-#: kallithea/lib/utils2.py:415
+#: kallithea/lib/utils2.py:434
 #, python-format
 msgid "%d year"
 msgid_plural "%d years"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:416
+#: kallithea/lib/utils2.py:435
 #, python-format
 msgid "%d month"
 msgid_plural "%d months"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:417
+#: kallithea/lib/utils2.py:436
 #, python-format
 msgid "%d day"
 msgid_plural "%d days"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:418
+#: kallithea/lib/utils2.py:437
 #, python-format
 msgid "%d hour"
 msgid_plural "%d hours"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:419
+#: kallithea/lib/utils2.py:438
 #, python-format
 msgid "%d minute"
 msgid_plural "%d minutes"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:420
+#: kallithea/lib/utils2.py:439
 #, python-format
 msgid "%d second"
 msgid_plural "%d seconds"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:436
+#: kallithea/lib/utils2.py:455
 #, python-format
 msgid "in %s"
 msgstr ""
 
-#: kallithea/lib/utils2.py:438
+#: kallithea/lib/utils2.py:457
 #, python-format
 msgid "%s ago"
 msgstr ""
 
-#: kallithea/lib/utils2.py:440
+#: kallithea/lib/utils2.py:459
 #, python-format
 msgid "in %s and %s"
 msgstr ""
 
-#: kallithea/lib/utils2.py:443
+#: kallithea/lib/utils2.py:462
 #, python-format
 msgid "%s and %s ago"
 msgstr ""
 
-#: kallithea/lib/utils2.py:446
+#: kallithea/lib/utils2.py:465
 msgid "just now"
 msgstr ""
 
@@ -1384,7 +1391,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1531
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1570
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1620
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1665
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1669
 msgid "Kallithea Administrator"
 msgstr ""
 
@@ -1495,7 +1502,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2063
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2102
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2155
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2229
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2237
 msgid "Approved"
 msgstr ""
 
@@ -1510,7 +1517,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2064
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2103
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2156
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2230
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2238
 msgid "Rejected"
 msgstr ""
 
@@ -1537,7 +1544,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1379
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1418
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1471
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1518
 msgid "top level"
 msgstr ""
 
@@ -1684,7 +1691,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1560
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1599
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1651
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1697
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1701
 msgid "Registration disabled"
 msgstr ""
 
@@ -1711,12 +1718,12 @@
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1645
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1691
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1695
 msgid "Repository creation enabled with write permission to a repository group"
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1646
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1692
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1696
 msgid "Repository creation disabled with write permission to a repository group"
 msgstr ""
 
@@ -1725,104 +1732,104 @@
 msgid "on line %s"
 msgstr ""
 
-#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:169
+#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:170
 msgid "[Mention]"
 msgstr ""
 
-#: kallithea/model/db.py:1667
+#: kallithea/model/db.py:1671
 msgid "Default user has no access to new repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1668
-msgid "Default user has read access to new repositories"
-msgstr ""
-
-#: kallithea/model/db.py:1669
-msgid "Default user has write access to new repositories"
-msgstr ""
-
-#: kallithea/model/db.py:1670
-msgid "Default user has admin access to new repositories"
-msgstr ""
-
 #: kallithea/model/db.py:1672
-msgid "Default user has no access to new repository groups"
+msgid "Default user has read access to new repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1673
-msgid "Default user has read access to new repository groups"
+msgid "Default user has write access to new repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1674
-msgid "Default user has write access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1675
-msgid "Default user has admin access to new repository groups"
+msgid "Default user has admin access to new repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1676
+msgid "Default user has no access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1677
-msgid "Default user has no access to new user groups"
+msgid "Default user has read access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1678
-msgid "Default user has read access to new user groups"
+msgid "Default user has write access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1679
-msgid "Default user has write access to new user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1680
-msgid "Default user has admin access to new user groups"
+msgid "Default user has admin access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1681
+msgid "Default user has no access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1682
-msgid "Only admins can create repository groups"
+msgid "Default user has read access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1683
-msgid "Non-admins can create repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1685
-msgid "Only admins can create user groups"
+msgid "Default user has write access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1684
+msgid "Default user has admin access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1686
-msgid "Non-admins can create user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1688
-msgid "Only admins can create top level repositories"
+msgid "Only admins can create repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1687
+msgid "Non-admins can create repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1689
+msgid "Only admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1690
+msgid "Non-admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1692
+msgid "Only admins can create top level repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1693
 msgid "Non-admins can create top level repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1694
-msgid "Only admins can fork repositories"
-msgstr ""
-
-#: kallithea/model/db.py:1695
-msgid "Non-admins can can fork repositories"
-msgstr ""
-
 #: kallithea/model/db.py:1698
-msgid "User registration with manual account activation"
+msgid "Only admins can fork repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1699
+msgid "Non-admins can fork repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1702
+msgid "User registration with manual account activation"
+msgstr ""
+
+#: kallithea/model/db.py:1703
 msgid "User registration with automatic account activation"
 msgstr ""
 
-#: kallithea/model/db.py:2228
+#: kallithea/model/db.py:2236
 #, fuzzy
 msgid "Not reviewed"
 msgstr ""
 
-#: kallithea/model/db.py:2231
+#: kallithea/model/db.py:2239
 #, fuzzy
 msgid "Under review"
 msgstr ""
@@ -1845,7 +1852,7 @@
 msgid "Enter %(min)i characters or more"
 msgstr ""
 
-#: kallithea/model/forms.py:160
+#: kallithea/model/forms.py:165
 msgid "Name must not contain only digits"
 msgstr ""
 
@@ -1938,7 +1945,7 @@
 msgid "%(user)s wants you to review pull request %(pr_nice_id)s: %(pr_title)s"
 msgstr ""
 
-#: kallithea/model/scm.py:812
+#: kallithea/model/scm.py:708
 msgid "latest tip"
 msgstr ""
 
@@ -1971,15 +1978,15 @@
 "owners or remove those user groups: %s"
 msgstr ""
 
-#: kallithea/model/user.py:360
+#: kallithea/model/user.py:368
 msgid "Password reset link"
 msgstr ""
 
-#: kallithea/model/user.py:408
+#: kallithea/model/user.py:418
 msgid "Password reset notification"
 msgstr ""
 
-#: kallithea/model/user.py:409
+#: kallithea/model/user.py:419
 #, python-format
 msgid ""
 "The password to your account %s has been changed using password reset "
@@ -1990,167 +1997,167 @@
 msgid "Value cannot be an empty list"
 msgstr ""
 
-#: kallithea/model/validators.py:95
+#: kallithea/model/validators.py:96
 #, python-format
 msgid "Username \"%(username)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:97
+#: kallithea/model/validators.py:98
 #, python-format
 msgid "Username \"%(username)s\" cannot be used"
 msgstr ""
 
-#: kallithea/model/validators.py:99
+#: kallithea/model/validators.py:100
 msgid ""
 "Username may only contain alphanumeric characters underscores, periods or"
 " dashes and must begin with an alphanumeric character or underscore"
 msgstr ""
 
-#: kallithea/model/validators.py:126
+#: kallithea/model/validators.py:127
 msgid "The input is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:133
+#: kallithea/model/validators.py:134
 #, python-format
 msgid "Username %(username)s is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:152
+#: kallithea/model/validators.py:154
 msgid "Invalid user group name"
 msgstr ""
 
-#: kallithea/model/validators.py:153
-#, python-format
-msgid "User group \"%(usergroup)s\" already exists"
-msgstr ""
-
 #: kallithea/model/validators.py:155
+#, python-format
+msgid "User group \"%(usergroup)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:157
 msgid ""
 "user group name may only contain alphanumeric characters underscores, "
 "periods or dashes and must begin with alphanumeric character"
 msgstr ""
 
-#: kallithea/model/validators.py:193
+#: kallithea/model/validators.py:197
 msgid "Cannot assign this group as parent"
 msgstr ""
 
-#: kallithea/model/validators.py:194
+#: kallithea/model/validators.py:198
 #, python-format
 msgid "Group \"%(group_name)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:196
+#: kallithea/model/validators.py:200
 #, python-format
 msgid "Repository with name \"%(group_name)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:254
+#: kallithea/model/validators.py:258
 msgid "Invalid characters (non-ascii) in password"
 msgstr ""
 
-#: kallithea/model/validators.py:269
+#: kallithea/model/validators.py:273
 msgid "Invalid old password"
 msgstr ""
 
-#: kallithea/model/validators.py:285
+#: kallithea/model/validators.py:289
 msgid "Passwords do not match"
 msgstr ""
 
-#: kallithea/model/validators.py:300
+#: kallithea/model/validators.py:304
 msgid "Invalid username or password"
 msgstr ""
 
-#: kallithea/model/validators.py:331
+#: kallithea/model/validators.py:335
 msgid "Token mismatch"
 msgstr ""
 
-#: kallithea/model/validators.py:345
+#: kallithea/model/validators.py:351
 #, python-format
 msgid "Repository name %(repo)s is not allowed"
 msgstr ""
 
-#: kallithea/model/validators.py:347
+#: kallithea/model/validators.py:353
 #, python-format
 msgid "Repository named %(repo)s already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:348
+#: kallithea/model/validators.py:354
 #, python-format
 msgid "Repository \"%(repo)s\" already exists in group \"%(group)s\""
 msgstr ""
 
-#: kallithea/model/validators.py:350
+#: kallithea/model/validators.py:356
 #, python-format
 msgid "Repository group with name \"%(repo)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:465
+#: kallithea/model/validators.py:470
 msgid "Invalid repository URL"
 msgstr ""
 
-#: kallithea/model/validators.py:466
+#: kallithea/model/validators.py:471
 msgid ""
 "Invalid repository URL. It must be a valid http, https, ssh, svn+http or "
 "svn+https URL"
 msgstr ""
 
-#: kallithea/model/validators.py:489
+#: kallithea/model/validators.py:496
 msgid "Fork has to be the same type as parent"
 msgstr ""
 
-#: kallithea/model/validators.py:504
+#: kallithea/model/validators.py:511
 msgid "You don't have permissions to create repository in this group"
 msgstr ""
 
-#: kallithea/model/validators.py:506
+#: kallithea/model/validators.py:513
 msgid "no permission to create repository in root location"
 msgstr ""
 
-#: kallithea/model/validators.py:556
+#: kallithea/model/validators.py:563
 msgid "You don't have permissions to create a group in this location"
 msgstr ""
 
-#: kallithea/model/validators.py:597
+#: kallithea/model/validators.py:604
 msgid "This username or user group name is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:690
+#: kallithea/model/validators.py:697
 msgid "This is not a valid path"
 msgstr ""
 
-#: kallithea/model/validators.py:705
+#: kallithea/model/validators.py:714
 msgid "This email address is already in use"
 msgstr ""
 
-#: kallithea/model/validators.py:725
+#: kallithea/model/validators.py:734
 #, python-format
 msgid "Email address \"%(email)s\" not found"
 msgstr ""
 
-#: kallithea/model/validators.py:762
+#: kallithea/model/validators.py:771
 msgid ""
 "The LDAP Login attribute of the CN must be specified - this is the name "
 "of the attribute that is equivalent to \"username\""
 msgstr ""
 
-#: kallithea/model/validators.py:774
+#: kallithea/model/validators.py:783
 msgid "Please enter a valid IPv4 or IPv6 address"
 msgstr ""
 
-#: kallithea/model/validators.py:775
+#: kallithea/model/validators.py:784
 #, python-format
 msgid "The network size (bits) must be within the range of 0-32 (not %(bits)r)"
 msgstr ""
 
-#: kallithea/model/validators.py:808
+#: kallithea/model/validators.py:817
 msgid "Key name can only consist of letters, underscore, dash or numbers"
 msgstr ""
 
-#: kallithea/model/validators.py:822
+#: kallithea/model/validators.py:831
 msgid "Filename cannot be inside a directory"
 msgstr ""
 
-#: kallithea/model/validators.py:838
+#: kallithea/model/validators.py:847
 #, python-format
 msgid "Plugins %(loaded)s and %(next_to_load)s both export the same name"
 msgstr ""
@@ -2277,7 +2284,7 @@
 #: kallithea/templates/admin/user_groups/user_groups.html:50
 #: kallithea/templates/pullrequests/pullrequest_data.html:16
 #: kallithea/templates/pullrequests/pullrequest_show.html:156
-#: kallithea/templates/pullrequests/pullrequest_show.html:233
+#: kallithea/templates/pullrequests/pullrequest_show.html:244
 #: kallithea/templates/summary/summary.html:134
 msgid "Owner"
 msgstr ""
@@ -2325,7 +2332,7 @@
 #: kallithea/templates/index_base.html:144
 #: kallithea/templates/admin/my_account/my_account_repos.html:61
 #: kallithea/templates/admin/my_account/my_account_watched.html:61
-#: kallithea/templates/base/base.html:140 kallithea/templates/base/root.html:47
+#: kallithea/templates/base/root.html:47
 #: kallithea/templates/bookmarks/bookmarks.html:83
 #: kallithea/templates/branches/branches.html:83
 #: kallithea/templates/journal/journal.html:202
@@ -2335,7 +2342,7 @@
 msgstr ""
 
 #: kallithea/templates/login.html:5 kallithea/templates/login.html:15
-#: kallithea/templates/base/base.html:326
+#: kallithea/templates/base/base.html:414
 msgid "Log In"
 msgstr ""
 
@@ -2350,7 +2357,7 @@
 #: kallithea/templates/admin/users/user_add.html:32
 #: kallithea/templates/admin/users/user_edit_profile.html:24
 #: kallithea/templates/admin/users/users.html:50
-#: kallithea/templates/base/base.html:302
+#: kallithea/templates/base/base.html:390
 #: kallithea/templates/pullrequests/pullrequest_show.html:166
 msgid "Username"
 msgstr ""
@@ -2358,7 +2365,7 @@
 #: kallithea/templates/login.html:33 kallithea/templates/register.html:33
 #: kallithea/templates/admin/my_account/my_account.html:37
 #: kallithea/templates/admin/users/user_add.html:41
-#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:399
 msgid "Password"
 msgstr ""
 
@@ -2370,7 +2377,7 @@
 msgid "Forgot your password ?"
 msgstr ""
 
-#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:322
+#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:410
 msgid "Don't have an account ?"
 msgstr ""
 
@@ -2491,10 +2498,6 @@
 msgid "There are no branches yet"
 msgstr ""
 
-#: kallithea/templates/switch_to_list.html:16
-msgid "Closed Branches"
-msgstr ""
-
 #: kallithea/templates/switch_to_list.html:32
 #: kallithea/templates/tags/tags_data.html:44
 msgid "There are no tags yet"
@@ -2721,12 +2724,12 @@
 msgid "Never"
 msgstr ""
 
-#: kallithea/templates/admin/gists/edit.html:145
+#: kallithea/templates/admin/gists/edit.html:146
 msgid "Update Gist"
 msgstr ""
 
-#: kallithea/templates/admin/gists/edit.html:146
-#: kallithea/templates/changeset/changeset_file_comment.html:81
+#: kallithea/templates/admin/gists/edit.html:147
+#: kallithea/templates/changeset/changeset_file_comment.html:105
 msgid "Cancel"
 msgstr ""
 
@@ -2749,7 +2752,7 @@
 
 #: kallithea/templates/admin/gists/index.html:37
 #: kallithea/templates/admin/gists/show.html:25
-#: kallithea/templates/base/base.html:237
+#: kallithea/templates/base/base.html:321
 msgid "Create New Gist"
 msgstr ""
 
@@ -2837,7 +2840,8 @@
 #: kallithea/templates/admin/settings/settings_hooks.html:36
 #: kallithea/templates/admin/users/user_edit_emails.html:19
 #: kallithea/templates/admin/users/user_edit_ips.html:22
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+#: kallithea/templates/changeset/changeset_file_comment.html:95
 #: kallithea/templates/data_table/_dt_elements.html:129
 #: kallithea/templates/data_table/_dt_elements.html:157
 #: kallithea/templates/data_table/_dt_elements.html:173
@@ -2857,8 +2861,6 @@
 #: kallithea/templates/base/perms_summary.html:43
 #: kallithea/templates/base/perms_summary.html:79
 #: kallithea/templates/base/perms_summary.html:81
-#: kallithea/templates/changeset/changeset_file_comment.html:83
-#: kallithea/templates/changeset/changeset_file_comment.html:192
 #: kallithea/templates/data_table/_dt_elements.html:122
 #: kallithea/templates/data_table/_dt_elements.html:123
 #: kallithea/templates/data_table/_dt_elements.html:150
@@ -2885,13 +2887,12 @@
 msgstr ""
 
 #: kallithea/templates/admin/gists/show.html:86
-#: kallithea/templates/files/files_source.html:73
 msgid "Show as raw"
 msgstr ""
 
 #: kallithea/templates/admin/my_account/my_account.html:5
 #: kallithea/templates/admin/my_account/my_account.html:9
-#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:431
 msgid "My Account"
 msgstr ""
 
@@ -3072,7 +3073,7 @@
 msgstr ""
 
 #: kallithea/templates/admin/notifications/notifications.html:26
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 msgid "Pull Requests"
 msgstr ""
 
@@ -3090,7 +3091,7 @@
 msgstr ""
 
 #: kallithea/templates/admin/notifications/show_notification.html:9
-#: kallithea/templates/base/base.html:342
+#: kallithea/templates/base/base.html:430
 msgid "Notifications"
 msgstr ""
 
@@ -3288,7 +3289,7 @@
 #: kallithea/templates/admin/repos/repo_edit.html:40
 #: kallithea/templates/admin/settings/settings.html:11
 #: kallithea/templates/admin/user_groups/user_group_edit.html:29
-#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:151
+#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:148
 #: kallithea/templates/data_table/_dt_elements.html:45
 #: kallithea/templates/data_table/_dt_elements.html:49
 msgid "Settings"
@@ -3551,6 +3552,11 @@
 msgid "Unlock Repository"
 msgstr ""
 
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:56
+#, python-format
+msgid "Locked by %s on %s"
+msgstr ""
+
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:60
 msgid "Confirm to lock repository."
 msgstr ""
@@ -3607,10 +3613,6 @@
 msgid "Invalidate Repository Cache"
 msgstr ""
 
-#: kallithea/templates/admin/repos/repo_edit_caches.html:4
-msgid "Confirm to invalidate repository cache."
-msgstr ""
-
 #: kallithea/templates/admin/repos/repo_edit_caches.html:7
 msgid ""
 "Manually invalidate cache for this repository. On first access, the "
@@ -4344,21 +4346,17 @@
 msgid "Files"
 msgstr ""
 
-#: kallithea/templates/base/base.html:138
-msgid "Switch To"
-msgstr ""
-
-#: kallithea/templates/base/base.html:145
-#: kallithea/templates/base/base.html:147
+#: kallithea/templates/base/base.html:142
+#: kallithea/templates/base/base.html:144
 msgid "Options"
 msgstr ""
 
-#: kallithea/templates/base/base.html:155
+#: kallithea/templates/base/base.html:152
 #: kallithea/templates/forks/forks_data.html:21
 msgid "Compare Fork"
 msgstr ""
 
-#: kallithea/templates/base/base.html:157
+#: kallithea/templates/base/base.html:154
 #: kallithea/templates/bookmarks/bookmarks.html:56
 #: kallithea/templates/bookmarks/bookmarks_data.html:13
 #: kallithea/templates/branches/branches.html:56
@@ -4368,111 +4366,116 @@
 msgid "Compare"
 msgstr ""
 
-#: kallithea/templates/base/base.html:159
-#: kallithea/templates/base/base.html:247
+#: kallithea/templates/base/base.html:156
+#: kallithea/templates/base/base.html:331
 #: kallithea/templates/search/search.html:14
 #: kallithea/templates/search/search.html:54
 msgid "Search"
 msgstr ""
 
-#: kallithea/templates/base/base.html:163
+#: kallithea/templates/base/base.html:160
 msgid "Unlock"
 msgstr ""
 
-#: kallithea/templates/base/base.html:165
+#: kallithea/templates/base/base.html:162
 msgid "Lock"
 msgstr ""
 
-#: kallithea/templates/base/base.html:173
+#: kallithea/templates/base/base.html:170
 msgid "Follow"
 msgstr ""
 
+#: kallithea/templates/base/base.html:171
+msgid "Unfollow"
+msgstr ""
+
 #: kallithea/templates/base/base.html:174
-msgid "Unfollow"
-msgstr ""
-
-#: kallithea/templates/base/base.html:177
 #: kallithea/templates/data_table/_dt_elements.html:37
 #: kallithea/templates/data_table/_dt_elements.html:41
 #: kallithea/templates/forks/fork.html:9
 msgid "Fork"
 msgstr ""
 
-#: kallithea/templates/base/base.html:178
+#: kallithea/templates/base/base.html:175
 #: kallithea/templates/pullrequests/pullrequest.html:88
 msgid "Create Pull Request"
 msgstr ""
 
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 #, python-format
 msgid "Show Pull Requests for %s"
 msgstr ""
 
-#: kallithea/templates/base/base.html:221
+#: kallithea/templates/base/base.html:193
+msgid "Switch To"
+msgstr ""
+
+#: kallithea/templates/base/base.html:203
+#: kallithea/templates/base/base.html:485
+msgid "No matches found"
+msgstr ""
+
+#: kallithea/templates/base/base.html:305
 msgid "Show recent activity"
 msgstr ""
 
-#: kallithea/templates/base/base.html:227
-#: kallithea/templates/base/base.html:228
+#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:312
 msgid "Public journal"
 msgstr ""
 
-#: kallithea/templates/base/base.html:233
+#: kallithea/templates/base/base.html:317
 msgid "Show public gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:234
+#: kallithea/templates/base/base.html:318
 msgid "Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:238
+#: kallithea/templates/base/base.html:322
 msgid "All Public Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:240
+#: kallithea/templates/base/base.html:324
 msgid "My Public Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:241
+#: kallithea/templates/base/base.html:325
 msgid "My Private Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:246
+#: kallithea/templates/base/base.html:330
 msgid "Search in repositories"
 msgstr ""
 
-#: kallithea/templates/base/base.html:269
-#: kallithea/templates/base/base.html:270
+#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:354
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:6
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:10
 msgid "My Pull Requests"
 msgstr ""
 
-#: kallithea/templates/base/base.html:289
+#: kallithea/templates/base/base.html:377
 msgid "Not Logged In"
 msgstr ""
 
-#: kallithea/templates/base/base.html:296
+#: kallithea/templates/base/base.html:384
 msgid "Login to Your Account"
 msgstr ""
 
-#: kallithea/templates/base/base.html:319
+#: kallithea/templates/base/base.html:407
 msgid "Forgot password ?"
 msgstr ""
 
-#: kallithea/templates/base/base.html:346
+#: kallithea/templates/base/base.html:434
 msgid "Log Out"
 msgstr ""
 
-#: kallithea/templates/base/base.html:395
-msgid "No matches found"
-msgstr ""
-
-#: kallithea/templates/base/base.html:524
+#: kallithea/templates/base/base.html:615
 msgid "Keyboard shortcuts"
 msgstr ""
 
-#: kallithea/templates/base/base.html:533
+#: kallithea/templates/base/base.html:624
 msgid "Site-wide shortcuts"
 msgstr ""
 
@@ -4589,6 +4592,7 @@
 
 #: kallithea/templates/base/root.html:35
 #: kallithea/templates/changeset/diff_block.html:8
+#: kallithea/templates/changeset/diff_block.html:21
 msgid "Collapse Diff"
 msgstr ""
 
@@ -4697,51 +4701,53 @@
 #: kallithea/templates/changelog/changelog_summary_data.html:20
 #, python-format
 msgid ""
-"Changeset status: %s\n"
+"Changeset status: %s by %s\n"
 "Click to open associated pull request %s"
 msgstr ""
 
 #: kallithea/templates/changelog/changelog.html:96
-#: kallithea/templates/compare/compare_cs.html:24
-#, python-format
-msgid "Changeset status: %s"
-msgstr ""
-
-#: kallithea/templates/changelog/changelog.html:115
+#: kallithea/templates/changelog/changelog_summary_data.html:24
+#, python-format
+msgid "Changeset status: %s by %s"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:116
 #: kallithea/templates/compare/compare_cs.html:63
 msgid "Expand commit message"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:124
+#: kallithea/templates/changelog/changelog.html:125
 #: kallithea/templates/compare/compare_cs.html:30
 msgid "Changeset has comments"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:134
-#: kallithea/templates/changelog/changelog_summary_data.html:54
+#: kallithea/templates/changelog/changelog.html:135
+#: kallithea/templates/changelog/changelog_summary_data.html:57
 #: kallithea/templates/changeset/changeset.html:94
 #: kallithea/templates/changeset/changeset_range.html:92
 #, python-format
 msgid "Bookmark %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:140
-#: kallithea/templates/changelog/changelog_summary_data.html:60
+#: kallithea/templates/changelog/changelog.html:141
+#: kallithea/templates/changelog/changelog_summary_data.html:63
 #: kallithea/templates/changeset/changeset.html:101
 #: kallithea/templates/changeset/changeset_range.html:98
+#: kallithea/templates/compare/compare_cs.html:69
+#: kallithea/templates/pullrequests/pullrequest_show.html:203
 #, python-format
 msgid "Tag %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:145
-#: kallithea/templates/changelog/changelog_summary_data.html:65
+#: kallithea/templates/changelog/changelog.html:146
+#: kallithea/templates/changelog/changelog_summary_data.html:68
 #: kallithea/templates/changeset/changeset.html:106
 #: kallithea/templates/changeset/changeset_range.html:102
 #, python-format
 msgid "Branch %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:310
+#: kallithea/templates/changelog/changelog.html:311
 msgid "There are no changes yet"
 msgstr ""
 
@@ -4757,7 +4763,7 @@
 
 #: kallithea/templates/changelog/changelog_details.html:6
 #: kallithea/templates/changeset/changeset.html:79
-#: kallithea/templates/changeset/diff_block.html:79
+#: kallithea/templates/changeset/diff_block.html:47
 msgid "Added"
 msgstr ""
 
@@ -4787,21 +4793,21 @@
 msgid "Refs"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:81
+#: kallithea/templates/changelog/changelog_summary_data.html:84
 msgid "Add or upload files directly via Kallithea"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:84
+#: kallithea/templates/changelog/changelog_summary_data.html:87
 #: kallithea/templates/files/files_add.html:21
 #: kallithea/templates/files/files_ypjax.html:9
 msgid "Add New File"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:90
+#: kallithea/templates/changelog/changelog_summary_data.html:93
 msgid "Push new repository"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:98
+#: kallithea/templates/changelog/changelog_summary_data.html:101
 msgid "Existing repository?"
 msgstr ""
 
@@ -4819,13 +4825,13 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:50
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #: kallithea/templates/changeset/changeset_range.html:48
 msgid "Changeset status"
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:54
-#: kallithea/templates/changeset/diff_block.html:27
+#: kallithea/templates/changeset/diff_block.html:72
 #: kallithea/templates/files/diff_2way.html:49
 msgid "Raw diff"
 msgstr ""
@@ -4835,7 +4841,7 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:60
-#: kallithea/templates/changeset/diff_block.html:30
+#: kallithea/templates/changeset/diff_block.html:75
 #: kallithea/templates/files/diff_2way.html:52
 msgid "Download diff"
 msgstr ""
@@ -4862,8 +4868,8 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:166
-#: kallithea/templates/compare/compare_diff.html:54
-#: kallithea/templates/pullrequests/pullrequest_show.html:318
+#: kallithea/templates/compare/compare_diff.html:60
+#: kallithea/templates/pullrequests/pullrequest_show.html:329
 #, python-format
 msgid "%s file changed"
 msgid_plural "%s files changed"
@@ -4871,8 +4877,8 @@
 msgstr[1] ""
 
 #: kallithea/templates/changeset/changeset.html:168
-#: kallithea/templates/compare/compare_diff.html:56
-#: kallithea/templates/pullrequests/pullrequest_show.html:320
+#: kallithea/templates/compare/compare_diff.html:62
+#: kallithea/templates/pullrequests/pullrequest_show.html:331
 #, python-format
 msgid "%s file changed with %s insertions and %s deletions"
 msgid_plural "%s files changed with %s insertions and %s deletions"
@@ -4881,13 +4887,13 @@
 
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Show full diff anyway"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset.html:247
-#: kallithea/templates/changeset/changeset.html:284
+#: kallithea/templates/changeset/changeset.html:231
+#: kallithea/templates/changeset/changeset.html:268
 msgid "No revisions"
 msgstr ""
 
@@ -4904,101 +4910,86 @@
 msgid "on this changeset"
 msgstr "%s módosításcsomag"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
 msgid "Delete comment?"
 msgstr "Hozzászólás törlése?"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #, fuzzy
 msgid "Status change"
 msgstr "%s módosításcsomag"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:59
-msgid "Commenting on line {1}."
+msgid "Commenting on line."
 msgstr ""
 
 #: kallithea/templates/changeset/changeset_file_comment.html:60
-#: kallithea/templates/changeset/changeset_file_comment.html:148
-#, python-format
-msgid "Comments parsed using %s syntax with %s support."
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:62
-msgid "Use @username inside this text to notify another user"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:72
-#: kallithea/templates/changeset/changeset_file_comment.html:184
-msgid "Comment preview"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:77
+msgid ""
+"Comments are in plain text. Use @username inside this text to notify "
+"another user."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:67
+msgid "Set changeset status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:69
+msgid "Vote for pull request status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:75
+msgid "No change"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:88
+msgid "Finish pull request"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:91
+msgid "Close"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:103
 msgid "Submitting ..."
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:80
-#: kallithea/templates/changeset/changeset_file_comment.html:190
+#: kallithea/templates/changeset/changeset_file_comment.html:104
 msgid "Comment"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:82
-#: kallithea/templates/changeset/changeset_file_comment.html:191
-msgid "Preview"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "You need to be logged in to comment."
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "Login now"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:94
+#: kallithea/templates/changeset/changeset_file_comment.html:116
 msgid "Hide"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:106
+#: kallithea/templates/changeset/changeset_file_comment.html:128
 #, python-format
 msgid "%d comment"
 msgid_plural "%d comments"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:107
+#: kallithea/templates/changeset/changeset_file_comment.html:129
 #, python-format
 msgid "%d inline"
 msgid_plural "%d inline"
 msgstr[0] "%d sorközi"
 msgstr[1] "%d sorközi"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:108
+#: kallithea/templates/changeset/changeset_file_comment.html:130
 #, python-format
 msgid "%d general"
 msgid_plural "%d general"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:150
-msgid "Use @username inside this text to notify another user."
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:157
-msgid "Vote for pull request status"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:159
-msgid "Set changeset status"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:163
-msgid "No change"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:176
-msgid "Close"
-msgstr ""
-
 #: kallithea/templates/changeset/changeset_range.html:5
 #, python-format
 msgid "%s Changesets"
@@ -5008,29 +4999,28 @@
 msgid "Files affected"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:21
+#: kallithea/templates/changeset/diff_block.html:54
+msgid "Deleted"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:57
+msgid "Renamed"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:66
 #: kallithea/templates/files/diff_2way.html:43
 msgid "Show full diff for this file"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:24
-#: kallithea/templates/changeset/diff_block.html:98
+#: kallithea/templates/changeset/diff_block.html:69
 #: kallithea/templates/files/diff_2way.html:46
 msgid "Show full side-by-side diff for this file"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:38
+#: kallithea/templates/changeset/diff_block.html:83
 msgid "Show inline comments"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:86
-msgid "Deleted"
-msgstr ""
-
-#: kallithea/templates/changeset/diff_block.html:89
-msgid "Renamed"
-msgstr ""
-
 #: kallithea/templates/compare/compare_cs.html:4
 msgid "No changesets"
 msgstr ""
@@ -5039,6 +5029,11 @@
 msgid "Ancestor"
 msgstr ""
 
+#: kallithea/templates/compare/compare_cs.html:24
+#, python-format
+msgid "Changeset status: %s"
+msgstr ""
+
 #: kallithea/templates/compare/compare_cs.html:44
 msgid "First (oldest) changeset in this list"
 msgstr ""
@@ -5051,29 +5046,29 @@
 msgid "Position in this list of changesets"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:76
+#: kallithea/templates/compare/compare_cs.html:85
 msgid "Show merge diff"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:86
-#: kallithea/templates/pullrequests/pullrequest_show.html:310
+#: kallithea/templates/compare/compare_cs.html:95
+#: kallithea/templates/pullrequests/pullrequest_show.html:321
 msgid "Common ancestor"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:90
-msgid "No common ancestor found - repositories are unrelated"
-msgstr ""
-
-#: kallithea/templates/compare/compare_cs.html:98
-msgid "is"
-msgstr ""
-
 #: kallithea/templates/compare/compare_cs.html:99
+msgid "No common ancestor found - repositories are unrelated"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:107
+msgid "is"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:108
 #, python-format
 msgid "%s changesets"
 msgstr "%s módosításcsomag"
 
-#: kallithea/templates/compare/compare_cs.html:100
+#: kallithea/templates/compare/compare_cs.html:109
 msgid "behind"
 msgstr ""
 
@@ -5084,28 +5079,28 @@
 msgstr ""
 
 #: kallithea/templates/compare/compare_diff.html:13
-#: kallithea/templates/compare/compare_diff.html:35
+#: kallithea/templates/compare/compare_diff.html:41
 msgid "Compare Revisions"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:33
+#: kallithea/templates/compare/compare_diff.html:39
 msgid "Swap"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:42
+#: kallithea/templates/compare/compare_diff.html:48
 msgid "Compare revisions, branches, bookmarks, or tags."
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:47
-#: kallithea/templates/pullrequests/pullrequest_show.html:305
+#: kallithea/templates/compare/compare_diff.html:53
+#: kallithea/templates/pullrequests/pullrequest_show.html:316
 #, python-format
 msgid "Showing %s commit"
 msgid_plural "Showing %s commits"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
 msgid "Show full diff"
 msgstr ""
 
@@ -5164,17 +5159,23 @@
 msgid "We have received a request to reset the password for your account."
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:7
-msgid "To set a new password, click the following link"
+#: kallithea/templates/email_templates/password_reset.html:8
+msgid ""
+"This account is however managed outside this system and the password "
+"cannot be changed here."
 msgstr ""
 
 #: kallithea/templates/email_templates/password_reset.html:10
+msgid "To set a new password, click the following link"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:13
 msgid ""
 "Should you not be able to use the link above, please type the following "
 "code into the password reset form"
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:12
+#: kallithea/templates/email_templates/password_reset.html:16
 msgid ""
 "If it weren't you who requested the password reset, just disregard this "
 "message."
@@ -5257,7 +5258,7 @@
 msgstr ""
 
 #: kallithea/templates/files/files_add.html:53
-msgid "New file mode"
+msgid "New file type"
 msgstr ""
 
 #: kallithea/templates/files/files_add.html:64
@@ -5388,8 +5389,16 @@
 msgid "Binary file (%s)"
 msgstr ""
 
-#: kallithea/templates/files/files_source.html:73
-msgid "File is too big to display"
+#: kallithea/templates/files/files_source.html:74
+msgid "File is too big to display."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:76
+msgid "Show full annotation anyway."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:78
+msgid "Show as raw."
 msgstr ""
 
 #: kallithea/templates/files/files_ypjax.html:5
@@ -5652,39 +5661,45 @@
 msgid "Current revision - no change"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:213
+#: kallithea/templates/pullrequests/pullrequest_show.html:215
+msgid ""
+"Pull requests do not change once created. Select a revision and save to "
+"replace this pull request with a new one."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:224
 msgid "Pull Request Reviewers"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:238
+#: kallithea/templates/pullrequests/pullrequest_show.html:249
 msgid "Remove reviewer"
 msgstr "Átnéző eltávolítása"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:250
+#: kallithea/templates/pullrequests/pullrequest_show.html:261
 msgid "Type name of reviewer to add"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:258
+#: kallithea/templates/pullrequests/pullrequest_show.html:269
 msgid "Potential Reviewers"
 msgstr "Lehetséges átnézők"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:261
+#: kallithea/templates/pullrequests/pullrequest_show.html:272
 msgid "Click to add the repository owner as reviewer:"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:284
+#: kallithea/templates/pullrequests/pullrequest_show.html:295
 msgid "Save Changes"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:285
-msgid "Save as New Pull Request"
-msgstr ""
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:286
-msgid "Cancel Changes"
-msgstr ""
-
 #: kallithea/templates/pullrequests/pullrequest_show.html:296
+msgid "Save Updates as New Pull Request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:297
+msgid "Cancel Changes"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:307
 msgid "Pull Request Content"
 msgstr ""
 
@@ -5695,7 +5710,7 @@
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:11
 #, python-format
-msgid "Pull Requests from %s'"
+msgid "Pull Requests from '%s'"
 msgstr ""
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:13
@@ -6271,39 +6286,12 @@
 #~ msgid "Your password reset link was sent"
 #~ msgstr ""
 
-#~ msgid ""
-#~ "Your password reset was successful, new"
-#~ " password has been sent to your "
-#~ "email"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " changeset %(short_id)s on %(branch)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Added by %(pr_username)s] %(repo_name)s pull"
-#~ " request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " pull request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
 #~ msgid "Your new password"
 #~ msgstr ""
 
 #~ msgid "Your new Kallithea password:%s"
 #~ msgstr ""
 
-#~ msgid ""
-#~ "Password reset link will be sent "
-#~ "to the email address matching your "
-#~ "username."
-#~ msgstr ""
-
 #~ msgid "Open New Pull Request for Selected Changesets"
 #~ msgstr ""
 
@@ -6325,3 +6313,53 @@
 #~ msgid "Created by"
 #~ msgstr ""
 
+#~ msgid "You can only delete files with revision being a valid branch "
+#~ msgstr ""
+
+#~ msgid "You can only edit files with revision being a valid branch "
+#~ msgstr ""
+
+#~ msgid "This pull request can be updated with changes on %s:"
+#~ msgstr ""
+
+#~ msgid "Non-admins can can fork repositories"
+#~ msgstr ""
+
+#~ msgid "Confirm to invalidate repository cache."
+#~ msgstr ""
+
+#~ msgid "Commenting on line {1}."
+#~ msgstr ""
+
+#~ msgid "Comments parsed using %s syntax with %s support."
+#~ msgstr ""
+
+#~ msgid "Use @username inside this text to notify another user"
+#~ msgstr ""
+
+#~ msgid "Comment preview"
+#~ msgstr ""
+
+#~ msgid "Preview"
+#~ msgstr ""
+
+#~ msgid "Use @username inside this text to notify another user."
+#~ msgstr ""
+
+#~ msgid "New file mode"
+#~ msgstr ""
+
+#~ msgid "File is too big to display"
+#~ msgstr ""
+
+#~ msgid "Save as New Pull Request"
+#~ msgstr ""
+
+#~ msgid "Pull Requests from %s'"
+#~ msgstr ""
+
+#~ msgid ""
+#~ "Changeset status: %s\n"
+#~ "Click to open associated pull request %s"
+#~ msgstr ""
+
--- a/kallithea/i18n/ja/LC_MESSAGES/kallithea.po	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/i18n/ja/LC_MESSAGES/kallithea.po	Fri Nov 18 01:11:13 2016 +0100
@@ -12,11 +12,11 @@
 msgstr ""
 "Project-Id-Version: Kallithea 0.3\n"
 "Report-Msgid-Bugs-To: translations@kallithea-scm.org\n"
-"POT-Creation-Date: 2015-09-08 10:34+0200\n"
+"POT-Creation-Date: 2016-03-14 16:51+0100\n"
 "PO-Revision-Date: 2016-01-07 01:53+0000\n"
 "Last-Translator: Takumi IINO <trot.thunder@gmail.com>\n"
 "Language-Team: Japanese "
-"<https://hosted.weblate.org/projects/kallithea/stable/ja/>\n"
+"<https://hosted.weblate.org/projects/kallithea/kallithea/ja/>\n"
 "Language: ja\n"
 "MIME-Version: 1.0\n"
 "Content-Type: text/plain; charset=UTF-8\n"
@@ -24,12 +24,12 @@
 "Plural-Forms: nplurals=1; plural=0;\n"
 "X-Generator: Weblate 2.5-dev\n"
 
-#: kallithea/controllers/changelog.py:86
-#: kallithea/controllers/pullrequests.py:238 kallithea/lib/base.py:512
+#: kallithea/controllers/changelog.py:85
+#: kallithea/controllers/pullrequests.py:240 kallithea/lib/base.py:515
 msgid "There are no changesets yet"
 msgstr "まだチェンジセットがありません"
 
-#: kallithea/controllers/changelog.py:166
+#: kallithea/controllers/changelog.py:164
 #: kallithea/controllers/admin/permissions.py:61
 #: kallithea/controllers/admin/permissions.py:65
 #: kallithea/controllers/admin/permissions.py:69
@@ -41,35 +41,29 @@
 msgid "None"
 msgstr "なし"
 
-#: kallithea/controllers/changelog.py:169 kallithea/controllers/files.py:196
+#: kallithea/controllers/changelog.py:167 kallithea/controllers/files.py:198
 msgid "(closed)"
 msgstr "(閉鎖済み)"
 
-#: kallithea/controllers/changeset.py:89
+#: kallithea/controllers/changeset.py:88
 msgid "Show whitespace"
 msgstr "空白を表示"
 
-#: kallithea/controllers/changeset.py:96 kallithea/controllers/changeset.py:103
+#: kallithea/controllers/changeset.py:95 kallithea/controllers/changeset.py:102
 #: kallithea/templates/files/diff_2way.html:55
 msgid "Ignore whitespace"
 msgstr "空白を無視"
 
-#: kallithea/controllers/changeset.py:169
+#: kallithea/controllers/changeset.py:168
 #, python-format
 msgid "Increase diff context to %(num)s lines"
 msgstr "diff コンテキストを %(num)s 行増やす"
 
-#: kallithea/controllers/changeset.py:212 kallithea/controllers/files.py:96
-#: kallithea/controllers/files.py:116 kallithea/controllers/files.py:742
+#: kallithea/controllers/changeset.py:233 kallithea/controllers/files.py:97
+#: kallithea/controllers/files.py:117 kallithea/controllers/files.py:744
 msgid "Such revision does not exist for this repository"
 msgstr "お探しのリビジョンはこのリポジトリにはありません"
 
-#: kallithea/controllers/changeset.py:383
-msgid ""
-"Changing status on a changeset associated with a closed pull request is "
-"not allowed"
-msgstr "クローズしたプルリクエストに関連するチェンジセットのステータスを変更することは許可されていません"
-
 #: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:41
 msgid "Select changeset"
 msgstr "リビジョンを選択"
@@ -121,10 +115,10 @@
 #: kallithea/controllers/feed.py:87
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Changeset was too big and was cut off..."
 msgstr "チェンジセットが大きすぎるため、省略しました..."
 
@@ -133,111 +127,113 @@
 msgid "%s committed on %s"
 msgstr "%s が %s にコミット"
 
-#: kallithea/controllers/files.py:91
+#: kallithea/controllers/files.py:92
 msgid "Click here to add new file"
 msgstr "新しいファイルを追加"
 
-#: kallithea/controllers/files.py:92
+#: kallithea/controllers/files.py:93
 #, python-format
 msgid "There are no files yet. %s"
 msgstr "まだファイルがありません。 %s"
 
-#: kallithea/controllers/files.py:193
+#: kallithea/controllers/files.py:195
 #, fuzzy, python-format
 msgid "%s at %s"
 msgstr "%s と %s の間"
 
-#: kallithea/controllers/files.py:305 kallithea/controllers/files.py:365
-#: kallithea/controllers/files.py:432
+#: kallithea/controllers/files.py:307 kallithea/controllers/files.py:367
+#: kallithea/controllers/files.py:434
 #, python-format
 msgid "This repository has been locked by %s on %s"
 msgstr "このリポジトリは %s によって %s にロックされました"
 
-#: kallithea/controllers/files.py:317
-msgid "You can only delete files with revision being a valid branch "
+#: kallithea/controllers/files.py:319
+#, fuzzy
+msgid "You can only delete files with revision being a valid branch"
 msgstr "有効なブランチ上のリビジョンからしかファイルを削除できません"
 
-#: kallithea/controllers/files.py:328
+#: kallithea/controllers/files.py:330
 #, python-format
 msgid "Deleted file %s via Kallithea"
 msgstr "Kallithea経由で %s を削除"
 
-#: kallithea/controllers/files.py:350
+#: kallithea/controllers/files.py:352
 #, python-format
 msgid "Successfully deleted file %s"
 msgstr "%s ファイルの削除に成功しました"
 
-#: kallithea/controllers/files.py:354 kallithea/controllers/files.py:420
-#: kallithea/controllers/files.py:501
+#: kallithea/controllers/files.py:356 kallithea/controllers/files.py:422
+#: kallithea/controllers/files.py:503
 msgid "Error occurred during commit"
 msgstr "コミット中にエラーが発生しました"
 
-#: kallithea/controllers/files.py:377
-msgid "You can only edit files with revision being a valid branch "
+#: kallithea/controllers/files.py:379
+#, fuzzy
+msgid "You can only edit files with revision being a valid branch"
 msgstr "有効なブランチを示すリビジョンでのみファイルを編集できます "
 
-#: kallithea/controllers/files.py:391
+#: kallithea/controllers/files.py:393
 #, python-format
 msgid "Edited file %s via Kallithea"
 msgstr "Kallithea経由で %s を変更"
 
-#: kallithea/controllers/files.py:407
+#: kallithea/controllers/files.py:409
 msgid "No changes"
 msgstr "変更点なし"
 
-#: kallithea/controllers/files.py:416 kallithea/controllers/files.py:490
+#: kallithea/controllers/files.py:418 kallithea/controllers/files.py:492
 #, python-format
 msgid "Successfully committed to %s"
 msgstr "%s へのコミットが成功しました"
 
-#: kallithea/controllers/files.py:443
+#: kallithea/controllers/files.py:445
 msgid "Added file via Kallithea"
 msgstr "Kallithea経由でファイルを追加"
 
-#: kallithea/controllers/files.py:464
+#: kallithea/controllers/files.py:466
 msgid "No content"
 msgstr "内容がありません"
 
-#: kallithea/controllers/files.py:468
+#: kallithea/controllers/files.py:470
 msgid "No filename"
 msgstr "ファイル名がありません"
 
-#: kallithea/controllers/files.py:493
+#: kallithea/controllers/files.py:495
 msgid "Location must be relative path and must not contain .. in path"
 msgstr "場所には相対パスかつ .. を含まないパスを入力してください"
 
-#: kallithea/controllers/files.py:526
+#: kallithea/controllers/files.py:528
 msgid "Downloads disabled"
 msgstr "ダウンロードは無効化されています"
 
-#: kallithea/controllers/files.py:537
+#: kallithea/controllers/files.py:539
 #, python-format
 msgid "Unknown revision %s"
 msgstr "%s は未知のリビジョンです"
 
-#: kallithea/controllers/files.py:539
+#: kallithea/controllers/files.py:541
 msgid "Empty repository"
 msgstr "空のリポジトリ"
 
-#: kallithea/controllers/files.py:541
+#: kallithea/controllers/files.py:543
 msgid "Unknown archive type"
 msgstr "未知のアーカイブ種別です"
 
-#: kallithea/controllers/files.py:771
+#: kallithea/controllers/files.py:773
 #: kallithea/templates/changeset/changeset_range.html:9
 #: kallithea/templates/email_templates/pull_request.html:15
 #: kallithea/templates/pullrequests/pullrequest.html:97
 msgid "Changesets"
 msgstr "チェンジセット"
 
-#: kallithea/controllers/files.py:772 kallithea/controllers/pullrequests.py:176
-#: kallithea/model/scm.py:820 kallithea/templates/switch_to_list.html:3
+#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:175
+#: kallithea/model/scm.py:716 kallithea/templates/switch_to_list.html:3
 #: kallithea/templates/branches/branches.html:10
 msgid "Branches"
 msgstr "ブランチ"
 
-#: kallithea/controllers/files.py:773 kallithea/controllers/pullrequests.py:177
-#: kallithea/model/scm.py:831 kallithea/templates/switch_to_list.html:25
+#: kallithea/controllers/files.py:775 kallithea/controllers/pullrequests.py:176
+#: kallithea/model/scm.py:727 kallithea/templates/switch_to_list.html:25
 #: kallithea/templates/tags/tags.html:10
 msgid "Tags"
 msgstr "タグ"
@@ -251,7 +247,7 @@
 msgid "Groups"
 msgstr "グループ"
 
-#: kallithea/controllers/home.py:89
+#: kallithea/controllers/home.py:94
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:106
 #: kallithea/templates/admin/repos/repo_add.html:12
 #: kallithea/templates/admin/repos/repo_add.html:16
@@ -259,23 +255,27 @@
 #: kallithea/templates/admin/users/user_edit_advanced.html:6
 #: kallithea/templates/base/base.html:60 kallithea/templates/base/base.html:77
 #: kallithea/templates/base/base.html:124
-#: kallithea/templates/base/base.html:390
-#: kallithea/templates/base/base.html:562
+#: kallithea/templates/base/base.html:479
+#: kallithea/templates/base/base.html:653
 msgid "Repositories"
 msgstr "リポジトリ"
 
-#: kallithea/controllers/home.py:130
+#: kallithea/controllers/home.py:139
 #: kallithea/templates/files/files_add.html:32
 #: kallithea/templates/files/files_delete.html:23
 #: kallithea/templates/files/files_edit.html:32
 msgid "Branch"
 msgstr "ブランチ"
 
-#: kallithea/controllers/home.py:136
+#: kallithea/controllers/home.py:145 kallithea/templates/switch_to_list.html:16
+msgid "Closed Branches"
+msgstr "閉鎖済みブランチ"
+
+#: kallithea/controllers/home.py:151
 msgid "Tag"
 msgstr "タグ"
 
-#: kallithea/controllers/home.py:142
+#: kallithea/controllers/home.py:157
 msgid "Bookmark"
 msgstr "ブックマーク"
 
@@ -286,161 +286,164 @@
 msgstr "公開ジャーナル"
 
 #: kallithea/controllers/journal.py:115 kallithea/controllers/journal.py:157
-#: kallithea/templates/base/base.html:222
+#: kallithea/templates/base/base.html:306
 #: kallithea/templates/journal/journal.html:4
 #: kallithea/templates/journal/journal.html:12
 msgid "Journal"
 msgstr "ジャーナル"
 
-#: kallithea/controllers/login.py:151 kallithea/controllers/login.py:197
+#: kallithea/controllers/login.py:144 kallithea/controllers/login.py:190
 msgid "Bad captcha"
 msgstr "キャプチャが一致しません"
 
-#: kallithea/controllers/login.py:157
-msgid "You have successfully registered into Kallithea"
-msgstr "Kallitheaへの登録を受け付けました"
-
-#: kallithea/controllers/login.py:202
-#| msgid "Your password reset link was sent"
+#: kallithea/controllers/login.py:150
+msgid "You have successfully registered with %s"
+msgstr "%sへの登録を受け付けました"
+
+#: kallithea/controllers/login.py:195
 msgid "A password reset confirmation code has been sent"
 msgstr "パスワードリセットの確認コードが送信されました"
 
-#: kallithea/controllers/login.py:251
-#| msgid "Password reset link"
+#: kallithea/controllers/login.py:244
 msgid "Invalid password reset token"
 msgstr "無効なパスワードリセットトークン"
 
-#: kallithea/controllers/login.py:256
+#: kallithea/controllers/login.py:249
 #: kallithea/controllers/admin/my_account.py:167
 msgid "Successfully updated password"
 msgstr "パスワードを更新しました"
 
-#: kallithea/controllers/pullrequests.py:124
+#: kallithea/controllers/pullrequests.py:123
 #, python-format
 msgid "%s (closed)"
 msgstr "%s (閉鎖済み)"
 
-#: kallithea/controllers/pullrequests.py:152
+#: kallithea/controllers/pullrequests.py:151
 #: kallithea/templates/changeset/changeset.html:12
 #: kallithea/templates/email_templates/changeset_comment.html:17
 msgid "Changeset"
 msgstr "チェンジセット"
 
-#: kallithea/controllers/pullrequests.py:173
+#: kallithea/controllers/pullrequests.py:172
 msgid "Special"
 msgstr "スペシャル"
 
-#: kallithea/controllers/pullrequests.py:174
+#: kallithea/controllers/pullrequests.py:173
 msgid "Peer branches"
 msgstr "相手のブランチ"
 
-#: kallithea/controllers/pullrequests.py:175 kallithea/model/scm.py:826
+#: kallithea/controllers/pullrequests.py:174 kallithea/model/scm.py:722
 #: kallithea/templates/switch_to_list.html:38
 #: kallithea/templates/bookmarks/bookmarks.html:10
 msgid "Bookmarks"
 msgstr "ブックマーク"
 
-#: kallithea/controllers/pullrequests.py:310
+#: kallithea/controllers/pullrequests.py:312
 #, python-format
 msgid "Error creating pull request: %s"
 msgstr "プルリクエスト作成中にエラーが発生しました: %s"
 
-#: kallithea/controllers/pullrequests.py:356
-#: kallithea/controllers/pullrequests.py:503
+#: kallithea/controllers/pullrequests.py:358
+#: kallithea/controllers/pullrequests.py:505
 msgid "No description"
 msgstr "説明がありません"
 
-#: kallithea/controllers/pullrequests.py:363
+#: kallithea/controllers/pullrequests.py:365
 msgid "Successfully opened new pull request"
 msgstr "新しいプルリクエストの作成に成功しました"
 
-#: kallithea/controllers/pullrequests.py:366
-#: kallithea/controllers/pullrequests.py:453
-#: kallithea/controllers/pullrequests.py:509
+#: kallithea/controllers/pullrequests.py:368
+#: kallithea/controllers/pullrequests.py:455
+#: kallithea/controllers/pullrequests.py:512
 #, python-format
 msgid "Invalid reviewer \"%s\" specified"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:369
-#: kallithea/controllers/pullrequests.py:456
+#: kallithea/controllers/pullrequests.py:371
+#: kallithea/controllers/pullrequests.py:458
 msgid "Error occurred while creating pull request"
 msgstr "プルリクエストの作成中にエラーが発生しました"
 
-#: kallithea/controllers/pullrequests.py:401
+#: kallithea/controllers/pullrequests.py:403
 msgid "Missing changesets since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:408
+#: kallithea/controllers/pullrequests.py:410
 #, python-format
 msgid "New changesets on %s %s since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:415
+#: kallithea/controllers/pullrequests.py:417
 msgid "Ancestor didn't change - show diff since previous version:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:422
+#: kallithea/controllers/pullrequests.py:424
 #, python-format
 msgid ""
 "This pull request is based on another %s revision and there is no simple "
 "diff."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:424
+#: kallithea/controllers/pullrequests.py:426
 #, python-format
 msgid "No changes found on %s %s since previous version."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:462
+#: kallithea/controllers/pullrequests.py:464
 #, python-format
 msgid "Closed, replaced by %s ."
 msgstr "%s で置き換えられたのでクローズします。"
 
-#: kallithea/controllers/pullrequests.py:470
+#: kallithea/controllers/pullrequests.py:472
 #, fuzzy
 msgid "Pull request update created"
 msgstr "プルリクエストレビュアー"
 
-#: kallithea/controllers/pullrequests.py:513
+#: kallithea/controllers/pullrequests.py:516
 msgid "Pull request updated"
 msgstr "プルリクエストを更新しました"
 
-#: kallithea/controllers/pullrequests.py:528
+#: kallithea/controllers/pullrequests.py:531
 msgid "Successfully deleted pull request"
 msgstr "プルリクエストの削除に成功しました"
 
-#: kallithea/controllers/pullrequests.py:594
+#: kallithea/controllers/pullrequests.py:597
 #, python-format
 msgid "This pull request has already been merged to %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:596
+#: kallithea/controllers/pullrequests.py:599
 msgid "This pull request has been closed and can not be updated."
 msgstr "このプルリクエストはすでにクローズされていて、更新することはできません。"
 
-#: kallithea/controllers/pullrequests.py:614
-#, python-format
-msgid "This pull request can be updated with changes on %s:"
+#: kallithea/controllers/pullrequests.py:617
+#, python-format
+msgid "The following changes are available on %s:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:617
+#: kallithea/controllers/pullrequests.py:621
 msgid "No changesets found for updating this pull request."
 msgstr "プルリクエストを更新するためのチェンジセットが見つかりません。"
 
-#: kallithea/controllers/pullrequests.py:625
+#: kallithea/controllers/pullrequests.py:629
 #, python-format
 msgid "Note: Branch %s has another head: %s."
 msgstr "ノート: ブランチ%sには別のヘッド%sがあります。"
 
-#: kallithea/controllers/pullrequests.py:631
+#: kallithea/controllers/pullrequests.py:635
 msgid "Git pull requests don't support updates yet."
 msgstr "Gitのプルリクエストはまだ更新をサポートしていません。"
 
-#: kallithea/controllers/pullrequests.py:722
+#: kallithea/controllers/pullrequests.py:727
 msgid "No permission to change pull request status"
 msgstr "プルリクエストステータスを変更する権限がありません"
 
-#: kallithea/controllers/pullrequests.py:727
+#: kallithea/controllers/pullrequests.py:738
+#, fuzzy, python-format
+msgid "Successfully deleted pull request %s"
+msgstr "プルリクエストの削除に成功しました"
+
+#: kallithea/controllers/pullrequests.py:748
 msgid "Closing."
 msgstr "クローズ。"
 
@@ -456,12 +459,12 @@
 msgid "An error occurred during search operation."
 msgstr "検索を実行する際にエラーが発生しました。"
 
-#: kallithea/controllers/summary.py:180
+#: kallithea/controllers/summary.py:181
 #: kallithea/templates/summary/summary.html:384
 msgid "No data ready yet"
 msgstr "まだデータの準備ができていません"
 
-#: kallithea/controllers/summary.py:183
+#: kallithea/controllers/summary.py:184
 #: kallithea/templates/summary/summary.html:98
 msgid "Statistics are disabled for this repository"
 msgstr "このリポジトリの統計は無効化されています"
@@ -482,64 +485,64 @@
 msgid "Error occurred during update of defaults"
 msgstr "デフォルト設定の更新中にエラーが発生しました"
 
-#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/gists.py:58
 #: kallithea/controllers/admin/my_account.py:243
-#: kallithea/controllers/admin/users.py:285
+#: kallithea/controllers/admin/users.py:284
 msgid "Forever"
 msgstr "永久"
 
+#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/my_account.py:244
+#: kallithea/controllers/admin/users.py:285
+msgid "5 minutes"
+msgstr "5 分"
+
 #: kallithea/controllers/admin/gists.py:60
-#: kallithea/controllers/admin/my_account.py:244
+#: kallithea/controllers/admin/my_account.py:245
 #: kallithea/controllers/admin/users.py:286
-msgid "5 minutes"
-msgstr "5 分"
+msgid "1 hour"
+msgstr "1 時間"
 
 #: kallithea/controllers/admin/gists.py:61
-#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/my_account.py:246
 #: kallithea/controllers/admin/users.py:287
-msgid "1 hour"
-msgstr "1 時間"
+msgid "1 day"
+msgstr "1 日"
 
 #: kallithea/controllers/admin/gists.py:62
-#: kallithea/controllers/admin/my_account.py:246
+#: kallithea/controllers/admin/my_account.py:247
 #: kallithea/controllers/admin/users.py:288
-msgid "1 day"
-msgstr "1 日"
-
-#: kallithea/controllers/admin/gists.py:63
-#: kallithea/controllers/admin/my_account.py:247
-#: kallithea/controllers/admin/users.py:289
 msgid "1 month"
 msgstr "1 ヶ月"
 
-#: kallithea/controllers/admin/gists.py:67
+#: kallithea/controllers/admin/gists.py:66
 #: kallithea/controllers/admin/my_account.py:249
-#: kallithea/controllers/admin/users.py:291
+#: kallithea/controllers/admin/users.py:290
 msgid "Lifetime"
 msgstr "有効期間"
 
-#: kallithea/controllers/admin/gists.py:146
+#: kallithea/controllers/admin/gists.py:145
 msgid "Error occurred during gist creation"
 msgstr "gist の作成中にエラーが発生しました"
 
-#: kallithea/controllers/admin/gists.py:184
+#: kallithea/controllers/admin/gists.py:183
 #, python-format
 msgid "Deleted gist %s"
 msgstr "gist %s を削除しました"
 
-#: kallithea/controllers/admin/gists.py:233
+#: kallithea/controllers/admin/gists.py:232
 msgid "Unmodified"
 msgstr "変更しない"
 
-#: kallithea/controllers/admin/gists.py:262
+#: kallithea/controllers/admin/gists.py:261
 msgid "Successfully updated gist content"
 msgstr "Gist の内容を更新しました"
 
-#: kallithea/controllers/admin/gists.py:267
+#: kallithea/controllers/admin/gists.py:266
 msgid "Successfully updated gist data"
 msgstr "Gist データを更新しました"
 
-#: kallithea/controllers/admin/gists.py:270
+#: kallithea/controllers/admin/gists.py:269
 #, python-format
 msgid "Error occurred during update of gist %s"
 msgstr "Gist %s の更新中にエラーが発生しました"
@@ -554,7 +557,7 @@
 msgstr "アカウントの更新に成功しました"
 
 #: kallithea/controllers/admin/my_account.py:144
-#: kallithea/controllers/admin/users.py:202
+#: kallithea/controllers/admin/users.py:201
 #, python-format
 msgid "Error occurred during update of user %s"
 msgstr "ユーザー %s の更新中にエラーが発生しました"
@@ -564,33 +567,33 @@
 msgstr "パスワードの更新中にエラーが発生しました"
 
 #: kallithea/controllers/admin/my_account.py:220
-#: kallithea/controllers/admin/users.py:415
+#: kallithea/controllers/admin/users.py:414
 #, python-format
 msgid "Added email %s to user"
 msgstr "ユーザーにメールアドレス %s を追加しました"
 
 #: kallithea/controllers/admin/my_account.py:226
-#: kallithea/controllers/admin/users.py:421
+#: kallithea/controllers/admin/users.py:420
 msgid "An error occurred during email saving"
 msgstr "メールの保存時にエラーが発生しました"
 
 #: kallithea/controllers/admin/my_account.py:235
-#: kallithea/controllers/admin/users.py:433
+#: kallithea/controllers/admin/users.py:432
 msgid "Removed email from user"
 msgstr "ユーザーからメールアドレスを削除しました"
 
 #: kallithea/controllers/admin/my_account.py:259
-#: kallithea/controllers/admin/users.py:308
+#: kallithea/controllers/admin/users.py:307
 msgid "API key successfully created"
 msgstr "APIキーの作成に成功しました"
 
 #: kallithea/controllers/admin/my_account.py:271
-#: kallithea/controllers/admin/users.py:321
+#: kallithea/controllers/admin/users.py:320
 msgid "API key successfully reset"
 msgstr "APIキーのリセットに成功しました"
 
 #: kallithea/controllers/admin/my_account.py:275
-#: kallithea/controllers/admin/users.py:325
+#: kallithea/controllers/admin/users.py:324
 msgid "API key successfully deleted"
 msgstr "APIキーの削除に成功しました"
 
@@ -640,10 +643,10 @@
 #: kallithea/templates/admin/users/user_edit_profile.html:105
 #: kallithea/templates/admin/users/users.html:10
 #: kallithea/templates/admin/users/users.html:55
-#: kallithea/templates/base/base.html:252
-#: kallithea/templates/base/base.html:253
-#: kallithea/templates/base/base.html:259
-#: kallithea/templates/base/base.html:260
+#: kallithea/templates/base/base.html:336
+#: kallithea/templates/base/base.html:337
+#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:344
 #: kallithea/templates/base/perms_summary.html:17
 msgid "Admin"
 msgstr "管理"
@@ -674,7 +677,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1564
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1603
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1655
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1701
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1705
 msgid "Manual activation of external account"
 msgstr "外部アカウントを手動でアクティベートする"
 
@@ -686,7 +689,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1565
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1604
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1656
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1702
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1706
 msgid "Automatic activation of external account"
 msgstr "外部アカウントを自動でアクティベートする"
 
@@ -707,242 +710,242 @@
 msgid "Error occurred during update of permissions"
 msgstr "権限の更新中にエラーが発生しました"
 
-#: kallithea/controllers/admin/repo_groups.py:188
+#: kallithea/controllers/admin/repo_groups.py:187
 #, python-format
 msgid "Error occurred during creation of repository group %s"
 msgstr "リポジトリグループ %s の作成中にエラーが発生しました"
 
-#: kallithea/controllers/admin/repo_groups.py:193
+#: kallithea/controllers/admin/repo_groups.py:192
 #, python-format
 msgid "Created repository group %s"
 msgstr "リポジトリグループ %s を作成しました"
 
-#: kallithea/controllers/admin/repo_groups.py:250
+#: kallithea/controllers/admin/repo_groups.py:249
 #, python-format
 msgid "Updated repository group %s"
 msgstr "リポジトリグループ %s を更新しました"
 
-#: kallithea/controllers/admin/repo_groups.py:266
+#: kallithea/controllers/admin/repo_groups.py:265
 #, python-format
 msgid "Error occurred during update of repository group %s"
 msgstr "リポジトリグループ %s の更新中にエラーが発生しました"
 
-#: kallithea/controllers/admin/repo_groups.py:284
+#: kallithea/controllers/admin/repo_groups.py:283
 #, python-format
 msgid "This group contains %s repositories and cannot be deleted"
 msgstr "このグループは %s 個のリポジトリを含んでいるため削除できません"
 
-#: kallithea/controllers/admin/repo_groups.py:291
+#: kallithea/controllers/admin/repo_groups.py:290
 #, python-format
 msgid "This group contains %s subgroups and cannot be deleted"
 msgstr "このグループは %s 個のサブグループを含んでいるため削除できません"
 
-#: kallithea/controllers/admin/repo_groups.py:297
+#: kallithea/controllers/admin/repo_groups.py:296
 #, python-format
 msgid "Removed repository group %s"
 msgstr "リポジトリグループ %s を削除しました"
 
-#: kallithea/controllers/admin/repo_groups.py:302
+#: kallithea/controllers/admin/repo_groups.py:301
 #, python-format
 msgid "Error occurred during deletion of repository group %s"
 msgstr "リポジトリグループ %s の削除中にエラーが発生しました"
 
-#: kallithea/controllers/admin/repo_groups.py:405
-#: kallithea/controllers/admin/repo_groups.py:440
+#: kallithea/controllers/admin/repo_groups.py:404
+#: kallithea/controllers/admin/repo_groups.py:439
 #: kallithea/controllers/admin/user_groups.py:340
 msgid "Cannot revoke permission for yourself as admin"
 msgstr "自分自身の管理者としての権限を取り消すことはできません"
 
-#: kallithea/controllers/admin/repo_groups.py:420
+#: kallithea/controllers/admin/repo_groups.py:419
 msgid "Repository group permissions updated"
 msgstr "リポジトリグループ権限を更新しました"
 
-#: kallithea/controllers/admin/repo_groups.py:457
-#: kallithea/controllers/admin/repos.py:398
+#: kallithea/controllers/admin/repo_groups.py:456
+#: kallithea/controllers/admin/repos.py:397
 #: kallithea/controllers/admin/user_groups.py:352
 msgid "An error occurred during revoking of permission"
 msgstr "権限の取消中にエラーが発生しました"
 
-#: kallithea/controllers/admin/repos.py:152
+#: kallithea/controllers/admin/repos.py:151
 #, python-format
 msgid "Error creating repository %s"
 msgstr "リポジトリ %s の作成中にエラーが発生しました"
 
-#: kallithea/controllers/admin/repos.py:213
+#: kallithea/controllers/admin/repos.py:212
 #, python-format
 msgid "Created repository %s from %s"
 msgstr "リポジトリ %s を %s から作成しました"
 
-#: kallithea/controllers/admin/repos.py:222
+#: kallithea/controllers/admin/repos.py:221
 #, python-format
 msgid "Forked repository %s as %s"
 msgstr "リポジトリ %s を %s としてフォークしました"
 
-#: kallithea/controllers/admin/repos.py:225
+#: kallithea/controllers/admin/repos.py:224
 #, python-format
 msgid "Created repository %s"
 msgstr "リポジトリ %s を作成しました"
 
-#: kallithea/controllers/admin/repos.py:262
+#: kallithea/controllers/admin/repos.py:261
 #, python-format
 msgid "Repository %s updated successfully"
 msgstr "リポジトリ %s の更新に成功しました"
 
-#: kallithea/controllers/admin/repos.py:283
+#: kallithea/controllers/admin/repos.py:282
 #, python-format
 msgid "Error occurred during update of repository %s"
 msgstr "リポジトリ %s の更新中にエラーが発生しました"
 
-#: kallithea/controllers/admin/repos.py:310
+#: kallithea/controllers/admin/repos.py:309
 #, python-format
 msgid "Detached %s forks"
 msgstr "%s 個のフォークを切り離しました"
 
-#: kallithea/controllers/admin/repos.py:313
+#: kallithea/controllers/admin/repos.py:312
 #, python-format
 msgid "Deleted %s forks"
 msgstr "%s 個のフォークを削除しました"
 
-#: kallithea/controllers/admin/repos.py:318
+#: kallithea/controllers/admin/repos.py:317
 #, python-format
 msgid "Deleted repository %s"
 msgstr "リポジトリ %s を削除しました"
 
-#: kallithea/controllers/admin/repos.py:321
+#: kallithea/controllers/admin/repos.py:320
 #, python-format
 msgid "Cannot delete repository %s which still has forks"
 msgstr "フォークしたリポジトリが存在するため、 リポジトリ %s は削除できません"
 
-#: kallithea/controllers/admin/repos.py:326
+#: kallithea/controllers/admin/repos.py:325
 #, python-format
 msgid "An error occurred during deletion of %s"
 msgstr "%s の削除中にエラーが発生しました"
 
-#: kallithea/controllers/admin/repos.py:374
+#: kallithea/controllers/admin/repos.py:373
 msgid "Repository permissions updated"
 msgstr "リポジトリ権限を更新しました"
 
-#: kallithea/controllers/admin/repos.py:430
+#: kallithea/controllers/admin/repos.py:429
 msgid "An error occurred during creation of field"
 msgstr "フィールドの作成中にエラーが発生しました"
 
-#: kallithea/controllers/admin/repos.py:444
+#: kallithea/controllers/admin/repos.py:443
 msgid "An error occurred during removal of field"
 msgstr "フィールドの削除中にエラーが発生しました"
 
-#: kallithea/controllers/admin/repos.py:460
+#: kallithea/controllers/admin/repos.py:459
 msgid "-- Not a fork --"
 msgstr "-- フォークではありません --"
 
-#: kallithea/controllers/admin/repos.py:491
+#: kallithea/controllers/admin/repos.py:490
 msgid "Updated repository visibility in public journal"
 msgstr "公開ジャーナルでのリポジトリの可視性を更新しました"
 
-#: kallithea/controllers/admin/repos.py:495
+#: kallithea/controllers/admin/repos.py:494
 msgid "An error occurred during setting this repository in public journal"
 msgstr "このリポジトリの公開ジャーナルの設定中にエラーが発生しました"
 
-#: kallithea/controllers/admin/repos.py:512
+#: kallithea/controllers/admin/repos.py:511
 msgid "Nothing"
 msgstr "ありません"
 
-#: kallithea/controllers/admin/repos.py:514
+#: kallithea/controllers/admin/repos.py:513
 #, python-format
 msgid "Marked repository %s as fork of %s"
 msgstr "%s リポジトリを %s のフォークとする"
 
-#: kallithea/controllers/admin/repos.py:521
+#: kallithea/controllers/admin/repos.py:520
 msgid "An error occurred during this operation"
 msgstr "操作中にエラーが発生しました"
 
-#: kallithea/controllers/admin/repos.py:537
-#: kallithea/controllers/admin/repos.py:564
+#: kallithea/controllers/admin/repos.py:536
+#: kallithea/controllers/admin/repos.py:563
 msgid "Repository has been locked"
 msgstr "リポジトリがロックされました"
 
-#: kallithea/controllers/admin/repos.py:540
-#: kallithea/controllers/admin/repos.py:561
+#: kallithea/controllers/admin/repos.py:539
+#: kallithea/controllers/admin/repos.py:560
 msgid "Repository has been unlocked"
 msgstr "リポジトリのロックが解除されました"
 
-#: kallithea/controllers/admin/repos.py:543
-#: kallithea/controllers/admin/repos.py:568
+#: kallithea/controllers/admin/repos.py:542
+#: kallithea/controllers/admin/repos.py:567
 msgid "An error occurred during unlocking"
 msgstr "アンロック中にエラーが発生しました"
 
-#: kallithea/controllers/admin/repos.py:582
+#: kallithea/controllers/admin/repos.py:581
 msgid "Cache invalidation successful"
 msgstr "キャッシュの無効化に成功しました"
 
-#: kallithea/controllers/admin/repos.py:586
+#: kallithea/controllers/admin/repos.py:585
 msgid "An error occurred during cache invalidation"
 msgstr "キャッシュの無効化中にエラーが発生しました"
 
-#: kallithea/controllers/admin/repos.py:601
+#: kallithea/controllers/admin/repos.py:600
 msgid "Pulled from remote location"
 msgstr "リモートから取得"
 
-#: kallithea/controllers/admin/repos.py:604
+#: kallithea/controllers/admin/repos.py:603
 msgid "An error occurred during pull from remote location"
 msgstr "リモートから取得中にエラーが発生しました"
 
-#: kallithea/controllers/admin/repos.py:637
+#: kallithea/controllers/admin/repos.py:636
 msgid "An error occurred during deletion of repository stats"
 msgstr "リポジトリステートの削除中にエラーが発生しました"
 
-#: kallithea/controllers/admin/settings.py:170
+#: kallithea/controllers/admin/settings.py:141
 msgid "Updated VCS settings"
 msgstr "VCS設定を更新しました"
 
-#: kallithea/controllers/admin/settings.py:174
+#: kallithea/controllers/admin/settings.py:145
 msgid ""
 "Unable to activate hgsubversion support. The \"hgsubversion\" library is "
 "missing"
 msgstr "\"hgsubversion\"ライブラリが見つからないため、hgsubversionサポートを有効に出来ません"
 
-#: kallithea/controllers/admin/settings.py:180
-#: kallithea/controllers/admin/settings.py:277
+#: kallithea/controllers/admin/settings.py:151
+#: kallithea/controllers/admin/settings.py:248
 msgid "Error occurred while updating application settings"
 msgstr "アプリケーション設定の更新中にエラーが発生しました"
 
-#: kallithea/controllers/admin/settings.py:216
+#: kallithea/controllers/admin/settings.py:187
 #, python-format
 msgid "Repositories successfully rescanned. Added: %s. Removed: %s."
 msgstr "リポジトリの再スキャンに成功しました。 追加: %s 削除: %s。"
 
-#: kallithea/controllers/admin/settings.py:273
+#: kallithea/controllers/admin/settings.py:244
 msgid "Updated application settings"
 msgstr "アプリケーション設定を更新しました"
 
-#: kallithea/controllers/admin/settings.py:330
+#: kallithea/controllers/admin/settings.py:301
 msgid "Updated visualisation settings"
 msgstr "表示設定を更新しました"
 
-#: kallithea/controllers/admin/settings.py:335
+#: kallithea/controllers/admin/settings.py:306
 msgid "Error occurred during updating visualisation settings"
 msgstr "表示設定の更新中にエラーが発生しました"
 
-#: kallithea/controllers/admin/settings.py:361
+#: kallithea/controllers/admin/settings.py:332
 msgid "Please enter email address"
 msgstr "メールアドレスを入力してください"
 
-#: kallithea/controllers/admin/settings.py:376
+#: kallithea/controllers/admin/settings.py:347
 msgid "Send email task created"
 msgstr "メール送信タスクを作成しました"
 
-#: kallithea/controllers/admin/settings.py:407
+#: kallithea/controllers/admin/settings.py:378
 msgid "Added new hook"
 msgstr "新しいフックを追加しました"
 
-#: kallithea/controllers/admin/settings.py:421
+#: kallithea/controllers/admin/settings.py:392
 msgid "Updated hooks"
 msgstr "フックを更新しました"
 
-#: kallithea/controllers/admin/settings.py:425
+#: kallithea/controllers/admin/settings.py:396
 msgid "Error occurred during hook creation"
 msgstr "フックの作成中にエラーが発生しました"
 
-#: kallithea/controllers/admin/settings.py:451
+#: kallithea/controllers/admin/settings.py:422
 msgid "Whoosh reindex task scheduled"
 msgstr "Whooshの再インデックスタスクを予定に入れました"
 
@@ -983,76 +986,80 @@
 msgstr "ユーザーグループ権限を更新しました"
 
 #: kallithea/controllers/admin/user_groups.py:440
-#: kallithea/controllers/admin/users.py:384
+#: kallithea/controllers/admin/users.py:383
 msgid "Updated permissions"
 msgstr "権限を更新しました"
 
 #: kallithea/controllers/admin/user_groups.py:444
-#: kallithea/controllers/admin/users.py:388
+#: kallithea/controllers/admin/users.py:387
 msgid "An error occurred during permissions saving"
 msgstr "権限の保存時にエラーが発生しました"
 
-#: kallithea/controllers/admin/users.py:134
+#: kallithea/controllers/admin/users.py:133
 #, python-format
 msgid "Created user %s"
 msgstr "ユーザー %s を作成しました"
 
-#: kallithea/controllers/admin/users.py:149
+#: kallithea/controllers/admin/users.py:148
 #, python-format
 msgid "Error occurred during creation of user %s"
 msgstr "ユーザー %s の作成中にエラーが発生しました"
 
-#: kallithea/controllers/admin/users.py:182
+#: kallithea/controllers/admin/users.py:181
 msgid "User updated successfully"
 msgstr "ユーザーの更新に成功しました"
 
-#: kallithea/controllers/admin/users.py:218
+#: kallithea/controllers/admin/users.py:217
 msgid "Successfully deleted user"
 msgstr "ユーザーの削除に成功しました"
 
-#: kallithea/controllers/admin/users.py:223
+#: kallithea/controllers/admin/users.py:222
 msgid "An error occurred during deletion of user"
 msgstr "ユーザーの削除中にエラーが発生しました"
 
-#: kallithea/controllers/admin/users.py:236
+#: kallithea/controllers/admin/users.py:235
 msgid "The default user cannot be edited"
 msgstr "デフォルト ユーザーを編集できません"
 
-#: kallithea/controllers/admin/users.py:463
+#: kallithea/controllers/admin/users.py:462
 #, python-format
 msgid "Added IP address %s to user whitelist"
 msgstr "ユーザーホワイトリストにIP %s を追加しました"
 
-#: kallithea/controllers/admin/users.py:469
+#: kallithea/controllers/admin/users.py:468
 msgid "An error occurred while adding IP address"
 msgstr "IPアドレスの保存中にエラーが発生しました"
 
-#: kallithea/controllers/admin/users.py:483
+#: kallithea/controllers/admin/users.py:482
 msgid "Removed IP address from user whitelist"
 msgstr "ユーザーホワイトリストからIPアドレスを削除しました"
 
-#: kallithea/lib/auth.py:743
+#: kallithea/lib/auth.py:737
 #, python-format
 msgid "IP %s not allowed"
 msgstr "IPアドレス %s は許可されません"
 
-#: kallithea/lib/auth.py:756
+#: kallithea/lib/auth.py:750
 msgid "Invalid API key"
 msgstr "APIキーが無効です"
 
-#: kallithea/lib/auth.py:812
+#: kallithea/lib/auth.py:768
+msgid "CSRF token leak has been detected - all form tokens have been expired"
+msgstr ""
+
+#: kallithea/lib/auth.py:813
 msgid "You need to be a registered user to perform this action"
 msgstr "このアクションを実行するためには登録済みのユーザーである必要があります"
 
-#: kallithea/lib/auth.py:844
+#: kallithea/lib/auth.py:843
 msgid "You need to be signed in to view this page"
 msgstr "このページを閲覧するためにはサインインが必要です"
 
-#: kallithea/lib/base.py:490
+#: kallithea/lib/base.py:493
 msgid "Repository not found in the filesystem"
 msgstr "ファイルシステム内にリポジトリが見つかりません"
 
-#: kallithea/lib/base.py:516 kallithea/lib/helpers.py:622
+#: kallithea/lib/base.py:519 kallithea/lib/helpers.py:623
 msgid "Changeset not found"
 msgstr "リビジョンが見つかりません"
 
@@ -1068,125 +1075,125 @@
 msgid "No changes detected"
 msgstr "検出された変更はありません"
 
-#: kallithea/lib/helpers.py:609
+#: kallithea/lib/helpers.py:610
 #, python-format
 msgid "Deleted branch: %s"
 msgstr "削除されたブランチ: %s"
 
-#: kallithea/lib/helpers.py:611
+#: kallithea/lib/helpers.py:612
 #, python-format
 msgid "Created tag: %s"
 msgstr "作成したタグ: %s"
 
-#: kallithea/lib/helpers.py:671
+#: kallithea/lib/helpers.py:672
 #, python-format
 msgid "Show all combined changesets %s->%s"
 msgstr "%s から %s までのすべてのチェンジセットを表示"
 
-#: kallithea/lib/helpers.py:677
+#: kallithea/lib/helpers.py:678
 msgid "Compare view"
 msgstr "比較ビュー"
 
-#: kallithea/lib/helpers.py:696
+#: kallithea/lib/helpers.py:697
 msgid "and"
 msgstr "と"
 
-#: kallithea/lib/helpers.py:697
+#: kallithea/lib/helpers.py:698
 #, python-format
 msgid "%s more"
 msgstr "%s 以上"
 
-#: kallithea/lib/helpers.py:698 kallithea/templates/changelog/changelog.html:44
+#: kallithea/lib/helpers.py:699 kallithea/templates/changelog/changelog.html:44
 msgid "revisions"
 msgstr "リビジョン"
 
-#: kallithea/lib/helpers.py:722
+#: kallithea/lib/helpers.py:723
 #, python-format
 msgid "Fork name %s"
 msgstr "フォーク名 %s"
 
-#: kallithea/lib/helpers.py:742
+#: kallithea/lib/helpers.py:743
 #, python-format
 msgid "Pull request %s"
 msgstr "プルリクエスト #%s"
 
-#: kallithea/lib/helpers.py:752
+#: kallithea/lib/helpers.py:753
 msgid "[deleted] repository"
 msgstr "リポジトリを[削除]"
 
-#: kallithea/lib/helpers.py:754 kallithea/lib/helpers.py:766
+#: kallithea/lib/helpers.py:755 kallithea/lib/helpers.py:767
 msgid "[created] repository"
 msgstr "リポジトリを[作成]"
 
-#: kallithea/lib/helpers.py:756
+#: kallithea/lib/helpers.py:757
 msgid "[created] repository as fork"
 msgstr "フォークしてリポジトリを[作成]"
 
-#: kallithea/lib/helpers.py:758 kallithea/lib/helpers.py:768
+#: kallithea/lib/helpers.py:759 kallithea/lib/helpers.py:769
 msgid "[forked] repository"
 msgstr "リポジトリを[フォーク]"
 
-#: kallithea/lib/helpers.py:760 kallithea/lib/helpers.py:770
+#: kallithea/lib/helpers.py:761 kallithea/lib/helpers.py:771
 msgid "[updated] repository"
 msgstr "リポジトリを[更新]"
 
-#: kallithea/lib/helpers.py:762
+#: kallithea/lib/helpers.py:763
 msgid "[downloaded] archive from repository"
 msgstr "リポジトリからアーカイブを[ダウンロード]"
 
-#: kallithea/lib/helpers.py:764
+#: kallithea/lib/helpers.py:765
 msgid "[delete] repository"
 msgstr "リポジトリを[削除]"
 
-#: kallithea/lib/helpers.py:772
+#: kallithea/lib/helpers.py:773
 msgid "[created] user"
 msgstr "ユーザーを[作成]"
 
-#: kallithea/lib/helpers.py:774
+#: kallithea/lib/helpers.py:775
 msgid "[updated] user"
 msgstr "ユーザーを[更新]"
 
-#: kallithea/lib/helpers.py:776
+#: kallithea/lib/helpers.py:777
 msgid "[created] user group"
 msgstr "ユーザーグループを[作成]"
 
-#: kallithea/lib/helpers.py:778
+#: kallithea/lib/helpers.py:779
 msgid "[updated] user group"
 msgstr "ユーザーグループを[更新]"
 
-#: kallithea/lib/helpers.py:780
+#: kallithea/lib/helpers.py:781
 msgid "[commented] on revision in repository"
 msgstr "リポジトリのリビジョンに[コメント]"
 
-#: kallithea/lib/helpers.py:782
+#: kallithea/lib/helpers.py:783
 msgid "[commented] on pull request for"
 msgstr "プルリクエストに[コメント]"
 
-#: kallithea/lib/helpers.py:784
+#: kallithea/lib/helpers.py:785
 msgid "[closed] pull request for"
 msgstr "プルリクエストを[クローズ]"
 
-#: kallithea/lib/helpers.py:786
+#: kallithea/lib/helpers.py:787
 msgid "[pushed] into"
 msgstr "[プッシュ]"
 
-#: kallithea/lib/helpers.py:788
+#: kallithea/lib/helpers.py:789
 msgid "[committed via Kallithea] into repository"
 msgstr "リポジトリに[Kallithea経由でコミット]"
 
-#: kallithea/lib/helpers.py:790
+#: kallithea/lib/helpers.py:791
 msgid "[pulled from remote] into repository"
 msgstr "リポジトリに[リモートからプル]"
 
-#: kallithea/lib/helpers.py:792
+#: kallithea/lib/helpers.py:793
 msgid "[pulled] from"
 msgstr "[プル]"
 
-#: kallithea/lib/helpers.py:794
+#: kallithea/lib/helpers.py:795
 msgid "[started following] repository"
 msgstr "リポジトリの[フォローを開始]"
 
-#: kallithea/lib/helpers.py:796
+#: kallithea/lib/helpers.py:797
 msgid "[stopped following] repository"
 msgstr "リポジトリの[フォローを停止]"
 
@@ -1196,8 +1203,8 @@
 msgstr " と %s 以上"
 
 #: kallithea/lib/helpers.py:1128
-#: kallithea/templates/compare/compare_diff.html:65
-#: kallithea/templates/pullrequests/pullrequest_show.html:326
+#: kallithea/templates/compare/compare_diff.html:71
+#: kallithea/templates/pullrequests/pullrequest_show.html:337
 msgid "No files"
 msgstr "ファイルはありません"
 
@@ -1221,73 +1228,73 @@
 msgid "chmod"
 msgstr "chmod"
 
-#: kallithea/lib/helpers.py:1444
+#: kallithea/lib/helpers.py:1469
 #, python-format
 msgid ""
 "%s repository is not mapped to db perhaps it was created or renamed from "
 "the filesystem please run the application again in order to rescan "
 "repositories"
 msgstr ""
-"%s リポジトリはDB内に見つかりませんでした。おそらくファイルシステム上で作られたか名前が変更されたためです。リポジトリをもう一度チェックするためにアプ"
-"リケーションを再起動してください"
-
-#: kallithea/lib/utils2.py:415
+"%s "
+"リポジトリはDB内に見つかりませんでした。おそらくファイルシステム上で作られたか名前が変更されたためです。リポジトリをもう一度チェックするためにアプリケーションを再起動してください"
+
+#: kallithea/lib/utils2.py:434
 #, python-format
 msgid "%d year"
 msgid_plural "%d years"
 msgstr[0] "%d 年"
 
-#: kallithea/lib/utils2.py:416
+#: kallithea/lib/utils2.py:435
 #, python-format
 msgid "%d month"
 msgid_plural "%d months"
 msgstr[0] "%d ヶ月"
 
-#: kallithea/lib/utils2.py:417
+#: kallithea/lib/utils2.py:436
 #, python-format
 msgid "%d day"
 msgid_plural "%d days"
 msgstr[0] "%d 日"
 
-#: kallithea/lib/utils2.py:418
+#: kallithea/lib/utils2.py:437
 #, python-format
 msgid "%d hour"
 msgid_plural "%d hours"
 msgstr[0] "%d 時間"
 
-#: kallithea/lib/utils2.py:419
+#: kallithea/lib/utils2.py:438
 #, python-format
 msgid "%d minute"
 msgid_plural "%d minutes"
 msgstr[0] "%d 分"
 
-#: kallithea/lib/utils2.py:420
+#: kallithea/lib/utils2.py:439
 #, python-format
 msgid "%d second"
 msgid_plural "%d seconds"
 msgstr[0] "%d 秒"
 
-#: kallithea/lib/utils2.py:436
+#: kallithea/lib/utils2.py:455
 #, python-format
 msgid "in %s"
 msgstr "%s 以内"
 
-#: kallithea/lib/utils2.py:438
+#: kallithea/lib/utils2.py:457
 #, python-format
 msgid "%s ago"
 msgstr "%s 前"
 
-#: kallithea/lib/utils2.py:440
+#: kallithea/lib/utils2.py:459
 #, python-format
 msgid "in %s and %s"
 msgstr "%s と %s の間"
 
-#: kallithea/lib/utils2.py:443
+#: kallithea/lib/utils2.py:462
 #, python-format
 msgid "%s and %s ago"
 msgstr "%s と %s 前"
 
-#: kallithea/lib/utils2.py:446
+#: kallithea/lib/utils2.py:465
 msgid "just now"
 msgstr "たったいま"
 
@@ -1386,7 +1393,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1531
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1570
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1620
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1665
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1669
 msgid "Kallithea Administrator"
 msgstr "Kallithea 管理者"
 
@@ -1497,7 +1504,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2063
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2102
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2155
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2229
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2237
 msgid "Approved"
 msgstr "承認"
 
@@ -1512,7 +1519,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2064
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2103
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2156
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2230
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2238
 msgid "Rejected"
 msgstr "却下"
 
@@ -1539,7 +1546,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1379
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1418
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1471
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1518
 msgid "top level"
 msgstr "top level"
 
@@ -1686,7 +1693,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1560
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1599
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1651
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1697
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1701
 msgid "Registration disabled"
 msgstr "新規登録を無効にする"
 
@@ -1713,12 +1720,12 @@
 msgstr "ユーザーの新規登録時に自動でアカウントをアクティベートする"
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1645
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1691
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1695
 msgid "Repository creation enabled with write permission to a repository group"
 msgstr "リポジトリグループの書き込みパーミッションを使ったリポジトリ作成が有効です"
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1646
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1692
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1696
 msgid "Repository creation disabled with write permission to a repository group"
 msgstr "リポジトリグループの書き込みパーミッションを使ったリポジトリ作成は無効です"
 
@@ -1727,103 +1734,104 @@
 msgid "on line %s"
 msgstr "%s 行目"
 
-#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:169
+#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:170
 msgid "[Mention]"
 msgstr "[Mention]"
 
-#: kallithea/model/db.py:1667
+#: kallithea/model/db.py:1671
 msgid "Default user has no access to new repositories"
 msgstr "デフォルトユーザーは新しいリポジトリにアクセスできません"
 
-#: kallithea/model/db.py:1668
+#: kallithea/model/db.py:1672
 msgid "Default user has read access to new repositories"
 msgstr "デフォルトユーザーは新しいリポジトリに読み取りアクセスする権限があります"
 
-#: kallithea/model/db.py:1669
+#: kallithea/model/db.py:1673
 msgid "Default user has write access to new repositories"
 msgstr "デフォルトユーザーは新しいリポジトリに書き込みアクセスする権限があります"
 
-#: kallithea/model/db.py:1670
+#: kallithea/model/db.py:1674
 msgid "Default user has admin access to new repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1672
+#: kallithea/model/db.py:1676
 msgid "Default user has no access to new repository groups"
 msgstr ""
 
-#: kallithea/model/db.py:1673
-msgid "Default user has read access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1674
-msgid "Default user has write access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1675
-msgid "Default user has admin access to new repository groups"
-msgstr ""
-
 #: kallithea/model/db.py:1677
-msgid "Default user has no access to new user groups"
+msgid "Default user has read access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1678
-msgid "Default user has read access to new user groups"
+msgid "Default user has write access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1679
-msgid "Default user has write access to new user groups"
+msgid "Default user has admin access to new repository groups"
 msgstr ""
 
-#: kallithea/model/db.py:1680
-msgid "Default user has admin access to new user groups"
+#: kallithea/model/db.py:1681
+msgid "Default user has no access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1682
-msgid "Only admins can create repository groups"
-msgstr "管理者のみがリポジトリのグループを作成できます"
+msgid "Default user has read access to new user groups"
+msgstr ""
 
 #: kallithea/model/db.py:1683
+msgid "Default user has write access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1684
+msgid "Default user has admin access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1686
+msgid "Only admins can create repository groups"
+msgstr "管理者のみがリポジトリのグループを作成できます"
+
+#: kallithea/model/db.py:1687
 msgid "Non-admins can create repository groups"
 msgstr "非管理者がリポジトリのグループを作成できます"
 
-#: kallithea/model/db.py:1685
+#: kallithea/model/db.py:1689
 msgid "Only admins can create user groups"
 msgstr "管理者だけがユーザー グループを作成することができます"
 
-#: kallithea/model/db.py:1686
+#: kallithea/model/db.py:1690
 msgid "Non-admins can create user groups"
 msgstr "非管理者ユーザーがグループを作成することができます"
 
-#: kallithea/model/db.py:1688
+#: kallithea/model/db.py:1692
 msgid "Only admins can create top level repositories"
 msgstr "管理者だけがトップレベルにリポジトリを作成することができます"
 
-#: kallithea/model/db.py:1689
+#: kallithea/model/db.py:1693
 msgid "Non-admins can create top level repositories"
 msgstr "非管理者がトップレベルにリポジトリを作成することができます"
 
-#: kallithea/model/db.py:1694
+#: kallithea/model/db.py:1698
 msgid "Only admins can fork repositories"
 msgstr "管理者のみがリポジトリをフォークすることができます"
 
-#: kallithea/model/db.py:1695
-msgid "Non-admins can can fork repositories"
+#: kallithea/model/db.py:1699
+#, fuzzy
+msgid "Non-admins can fork repositories"
 msgstr "非管理者がリポジトリをフォークすることができます"
 
-#: kallithea/model/db.py:1698
+#: kallithea/model/db.py:1702
 msgid "User registration with manual account activation"
 msgstr "ユーザーの新規登録時に手動でアカウントをアクティベートする"
 
-#: kallithea/model/db.py:1699
+#: kallithea/model/db.py:1703
 msgid "User registration with automatic account activation"
 msgstr "ユーザーの新規登録時に自動でアカウントをアクティベートする"
 
-#: kallithea/model/db.py:2228
+#: kallithea/model/db.py:2236
 msgid "Not reviewed"
 msgstr "未レビュー"
 
-#: kallithea/model/db.py:2231
+#: kallithea/model/db.py:2239
 msgid "Under review"
 msgstr "レビュー中"
 
@@ -1845,7 +1853,7 @@
 msgid "Enter %(min)i characters or more"
 msgstr "%(min)i 文字以上必要です"
 
-#: kallithea/model/forms.py:160
+#: kallithea/model/forms.py:165
 msgid "Name must not contain only digits"
 msgstr "数字だけの名前は使えません"
 
@@ -1921,13 +1929,11 @@
 
 #: kallithea/model/notification.py:307
 #, fuzzy, python-format
-#| msgid "%(user)s wants you to review pull request %(pr_nice_id)s:"
 msgid "[Added] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
 msgstr "%(user)s がプリリクエスト #%(pr_id)s: %(pr_title)s のレビューを求めています"
 
 #: kallithea/model/notification.py:308
 #, fuzzy, python-format
-#| msgid "[commented] on pull request for"
 msgid "[Comment] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
 msgstr "プルリクエストに[コメント]"
 
@@ -1940,7 +1946,7 @@
 msgid "%(user)s wants you to review pull request %(pr_nice_id)s: %(pr_title)s"
 msgstr "%(user)s がプリリクエスト #%(pr_nice_id)s: %(pr_title)s のレビューを求めています"
 
-#: kallithea/model/scm.py:812
+#: kallithea/model/scm.py:708
 msgid "latest tip"
 msgstr "最新のtip"
 
@@ -1958,8 +1964,7 @@
 msgid ""
 "User \"%s\" still owns %s repositories and cannot be removed. Switch "
 "owners or remove those repositories: %s"
-msgstr ""
-"ユーザー \"%s\" はまだ %s 個のリポジトリの所有者のため削除することはできません。リポジトリの所有者を変更するか削除してください: %s"
+msgstr "ユーザー \"%s\" はまだ %s 個のリポジトリの所有者のため削除することはできません。リポジトリの所有者を変更するか削除してください: %s"
 
 #: kallithea/model/user.py:266
 #, python-format
@@ -1976,19 +1981,18 @@
 "User \"%s\" still owns %s user groups and cannot be removed. Switch "
 "owners or remove those user groups: %s"
 msgstr ""
-"ユーザー \"%s\" はまだ %s 個のユーザーグループの所有者のため削除することはできません。ユーザーグループの所有者を変更するか削除してください。 "
-"%s"
-
-#: kallithea/model/user.py:360
+"ユーザー \"%s\" はまだ %s "
+"個のユーザーグループの所有者のため削除することはできません。ユーザーグループの所有者を変更するか削除してください。 %s"
+
+#: kallithea/model/user.py:368
 msgid "Password reset link"
 msgstr "パスワードリセットのリンク"
 
-#: kallithea/model/user.py:408
-#| msgid "Password reset link"
+#: kallithea/model/user.py:418
 msgid "Password reset notification"
 msgstr "パスワードの再設定通知"
 
-#: kallithea/model/user.py:409
+#: kallithea/model/user.py:419
 #, python-format
 msgid ""
 "The password to your account %s has been changed using password reset "
@@ -1999,170 +2003,167 @@
 msgid "Value cannot be an empty list"
 msgstr "空のリストにはできません"
 
-#: kallithea/model/validators.py:95
+#: kallithea/model/validators.py:96
 #, python-format
 msgid "Username \"%(username)s\" already exists"
 msgstr "ユーザー名 \"%(username)s\" はすでに使われています"
 
-#: kallithea/model/validators.py:97
+#: kallithea/model/validators.py:98
 #, python-format
 msgid "Username \"%(username)s\" cannot be used"
 msgstr "ユーザー名 %(username)s は使用できません"
 
-#: kallithea/model/validators.py:99
+#: kallithea/model/validators.py:100
 msgid ""
 "Username may only contain alphanumeric characters underscores, periods or"
 " dashes and must begin with an alphanumeric character or underscore"
-msgstr ""
-"ユーザー名はアルファベット、アンダースコア(_)、ピリオド(.)、ダッシュ(-)しか使えません。また、アルファベットまたはアンダースコア(_)から始まる必"
-"要があります"
-
-#: kallithea/model/validators.py:126
+msgstr "ユーザー名はアルファベット、アンダースコア(_)、ピリオド(.)、ダッシュ(-)しか使えません。また、アルファベットまたはアンダースコア(_)から始まる必要があります"
+
+#: kallithea/model/validators.py:127
 msgid "The input is not valid"
 msgstr "入力が正しくありません"
 
-#: kallithea/model/validators.py:133
+#: kallithea/model/validators.py:134
 #, python-format
 msgid "Username %(username)s is not valid"
 msgstr "ユーザー名 %(username)s は不正です"
 
-#: kallithea/model/validators.py:152
+#: kallithea/model/validators.py:154
 msgid "Invalid user group name"
 msgstr "不正なユーザーグループ名です"
 
-#: kallithea/model/validators.py:153
+#: kallithea/model/validators.py:155
 #, python-format
 msgid "User group \"%(usergroup)s\" already exists"
 msgstr "ユーザーグループ \"%(usergroup)s\" はすでに存在します"
 
-#: kallithea/model/validators.py:155
+#: kallithea/model/validators.py:157
 msgid ""
 "user group name may only contain alphanumeric characters underscores, "
 "periods or dashes and must begin with alphanumeric character"
-msgstr ""
-"ユーザーグループ名はアルファベット、アンダースコア(_)、ピリオド(.)、ダッシュ(-)しか使えません。また、アルファベットから始まる必要があります"
-
-#: kallithea/model/validators.py:193
+msgstr "ユーザーグループ名はアルファベット、アンダースコア(_)、ピリオド(.)、ダッシュ(-)しか使えません。また、アルファベットから始まる必要があります"
+
+#: kallithea/model/validators.py:197
 msgid "Cannot assign this group as parent"
 msgstr "このグループは親にできません"
 
-#: kallithea/model/validators.py:194
+#: kallithea/model/validators.py:198
 #, python-format
 msgid "Group \"%(group_name)s\" already exists"
 msgstr "グループ \"%(group_name)s\" はすでに存在します"
 
-#: kallithea/model/validators.py:196
+#: kallithea/model/validators.py:200
 #, python-format
 msgid "Repository with name \"%(group_name)s\" already exists"
 msgstr "グループ名 \"%(group_name)s\" を持つリポジトリはすでに存在します"
 
-#: kallithea/model/validators.py:254
+#: kallithea/model/validators.py:258
 msgid "Invalid characters (non-ascii) in password"
 msgstr "パスワードに利用出来ない文字列(non-ascii)です"
 
-#: kallithea/model/validators.py:269
+#: kallithea/model/validators.py:273
 msgid "Invalid old password"
 msgstr "古いpasswordが間違っています"
 
-#: kallithea/model/validators.py:285
+#: kallithea/model/validators.py:289
 msgid "Passwords do not match"
 msgstr "パスワードが一致しません"
 
-#: kallithea/model/validators.py:300
+#: kallithea/model/validators.py:304
 msgid "Invalid username or password"
 msgstr "ユーザー名とパスワードの組み合わせが無効です"
 
-#: kallithea/model/validators.py:331
+#: kallithea/model/validators.py:335
 msgid "Token mismatch"
 msgstr "トークンが一致しません"
 
-#: kallithea/model/validators.py:345
+#: kallithea/model/validators.py:351
 #, python-format
 msgid "Repository name %(repo)s is not allowed"
 msgstr "リポジトリ名 %(repo)s は許可されていません"
 
-#: kallithea/model/validators.py:347
+#: kallithea/model/validators.py:353
 #, python-format
 msgid "Repository named %(repo)s already exists"
 msgstr "リポジトリ %(repo)s はすでに存在します"
 
-#: kallithea/model/validators.py:348
+#: kallithea/model/validators.py:354
 #, python-format
 msgid "Repository \"%(repo)s\" already exists in group \"%(group)s\""
 msgstr "リポジトリ \"%(repo)s\" は グループ \"%(group)s\" にすでに存在します"
 
-#: kallithea/model/validators.py:350
+#: kallithea/model/validators.py:356
 #, python-format
 msgid "Repository group with name \"%(repo)s\" already exists"
 msgstr "リポジトリグループ名 \"%(repo)s\" はすでに存在します"
 
-#: kallithea/model/validators.py:465
+#: kallithea/model/validators.py:470
 msgid "Invalid repository URL"
 msgstr "無効なリポジトリのURL"
 
-#: kallithea/model/validators.py:466
+#: kallithea/model/validators.py:471
 msgid ""
 "Invalid repository URL. It must be a valid http, https, ssh, svn+http or "
 "svn+https URL"
 msgstr ""
 
-#: kallithea/model/validators.py:489
+#: kallithea/model/validators.py:496
 msgid "Fork has to be the same type as parent"
 msgstr "フォークは親と同じ種別の必要があります"
 
-#: kallithea/model/validators.py:504
+#: kallithea/model/validators.py:511
 msgid "You don't have permissions to create repository in this group"
 msgstr "このグループにリポジトリを作成する権限がありません"
 
-#: kallithea/model/validators.py:506
+#: kallithea/model/validators.py:513
 msgid "no permission to create repository in root location"
 msgstr "ルートにリポジトリを作成する権限がありません"
 
-#: kallithea/model/validators.py:556
+#: kallithea/model/validators.py:563
 msgid "You don't have permissions to create a group in this location"
 msgstr "この場所にグループを作成する権限がありません"
 
-#: kallithea/model/validators.py:597
+#: kallithea/model/validators.py:604
 msgid "This username or user group name is not valid"
 msgstr "ユーザー名かユーザーグループが不正です"
 
-#: kallithea/model/validators.py:690
+#: kallithea/model/validators.py:697
 msgid "This is not a valid path"
 msgstr "不正なパスです"
 
-#: kallithea/model/validators.py:705
+#: kallithea/model/validators.py:714
 msgid "This email address is already in use"
 msgstr "このメールアドレスはすでに取得されています"
 
-#: kallithea/model/validators.py:725
+#: kallithea/model/validators.py:734
 #, python-format
 msgid "Email address \"%(email)s\" not found"
 msgstr "メールアドレス \"%(email)s\" がみつかりません"
 
-#: kallithea/model/validators.py:762
+#: kallithea/model/validators.py:771
 msgid ""
 "The LDAP Login attribute of the CN must be specified - this is the name "
 "of the attribute that is equivalent to \"username\""
 msgstr "LDAPのこのCNに対するログイン属性は必須です。 - これは \"ユーザー名\" と同じです"
 
-#: kallithea/model/validators.py:774
+#: kallithea/model/validators.py:783
 msgid "Please enter a valid IPv4 or IPv6 address"
 msgstr "有効なIPv4かIPv6のアドレスを入力してください"
 
-#: kallithea/model/validators.py:775
+#: kallithea/model/validators.py:784
 #, python-format
 msgid "The network size (bits) must be within the range of 0-32 (not %(bits)r)"
 msgstr "ネットワークサイズ (bits) は0-32の範囲にする必要があります ( %(bits)r は不正です)"
 
-#: kallithea/model/validators.py:808
+#: kallithea/model/validators.py:817
 msgid "Key name can only consist of letters, underscore, dash or numbers"
 msgstr "キー名にはアルファベット、アンダースコア(_)、ピリオド(.)、ダッシュ(-)、数字が使えます"
 
-#: kallithea/model/validators.py:822
+#: kallithea/model/validators.py:831
 msgid "Filename cannot be inside a directory"
 msgstr "ファイル名はディレクトリ内にすることはできません"
 
-#: kallithea/model/validators.py:838
+#: kallithea/model/validators.py:847
 #, python-format
 msgid "Plugins %(loaded)s and %(next_to_load)s both export the same name"
 msgstr "%(loaded)s プラグインと %(next_to_load)s プラグインで同じ名前が使われています"
@@ -2289,7 +2290,7 @@
 #: kallithea/templates/admin/user_groups/user_groups.html:50
 #: kallithea/templates/pullrequests/pullrequest_data.html:16
 #: kallithea/templates/pullrequests/pullrequest_show.html:156
-#: kallithea/templates/pullrequests/pullrequest_show.html:233
+#: kallithea/templates/pullrequests/pullrequest_show.html:244
 #: kallithea/templates/summary/summary.html:134
 msgid "Owner"
 msgstr "所有者"
@@ -2337,7 +2338,7 @@
 #: kallithea/templates/index_base.html:144
 #: kallithea/templates/admin/my_account/my_account_repos.html:61
 #: kallithea/templates/admin/my_account/my_account_watched.html:61
-#: kallithea/templates/base/base.html:140 kallithea/templates/base/root.html:47
+#: kallithea/templates/base/root.html:47
 #: kallithea/templates/bookmarks/bookmarks.html:83
 #: kallithea/templates/branches/branches.html:83
 #: kallithea/templates/journal/journal.html:202
@@ -2347,7 +2348,7 @@
 msgstr "読み込み中..."
 
 #: kallithea/templates/login.html:5 kallithea/templates/login.html:15
-#: kallithea/templates/base/base.html:326
+#: kallithea/templates/base/base.html:414
 msgid "Log In"
 msgstr "ログイン"
 
@@ -2362,7 +2363,7 @@
 #: kallithea/templates/admin/users/user_add.html:32
 #: kallithea/templates/admin/users/user_edit_profile.html:24
 #: kallithea/templates/admin/users/users.html:50
-#: kallithea/templates/base/base.html:302
+#: kallithea/templates/base/base.html:390
 #: kallithea/templates/pullrequests/pullrequest_show.html:166
 msgid "Username"
 msgstr "ユーザー名"
@@ -2370,7 +2371,7 @@
 #: kallithea/templates/login.html:33 kallithea/templates/register.html:33
 #: kallithea/templates/admin/my_account/my_account.html:37
 #: kallithea/templates/admin/users/user_add.html:41
-#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:399
 msgid "Password"
 msgstr "パスワード"
 
@@ -2382,7 +2383,7 @@
 msgid "Forgot your password ?"
 msgstr "パスワードを忘れた?"
 
-#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:322
+#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:410
 msgid "Don't have an account ?"
 msgstr "アカウントを持っていない?"
 
@@ -2420,7 +2421,6 @@
 msgstr "パスワードリセットメールを送信"
 
 #: kallithea/templates/password_reset.html:47
-#| msgid "" "
 msgid ""
 "A password reset link will be sent to the specified email address if it "
 "is registered in the system."
@@ -2442,12 +2442,10 @@
 msgstr ""
 
 #: kallithea/templates/password_reset_confirmation.html:39
-#| msgid "New password"
 msgid "New Password"
 msgstr "新しいパスワード"
 
 #: kallithea/templates/password_reset_confirmation.html:48
-#| msgid "Confirm new password"
 msgid "Confirm New Password"
 msgstr "新しいパスワードの確認"
 
@@ -2506,10 +2504,6 @@
 msgid "There are no branches yet"
 msgstr "まだブランチがありません"
 
-#: kallithea/templates/switch_to_list.html:16
-msgid "Closed Branches"
-msgstr "閉鎖済みブランチ"
-
 #: kallithea/templates/switch_to_list.html:32
 #: kallithea/templates/tags/tags_data.html:44
 msgid "There are no tags yet"
@@ -2737,12 +2731,12 @@
 msgid "Never"
 msgstr "しない"
 
-#: kallithea/templates/admin/gists/edit.html:145
+#: kallithea/templates/admin/gists/edit.html:146
 msgid "Update Gist"
 msgstr "Gistを更新"
 
-#: kallithea/templates/admin/gists/edit.html:146
-#: kallithea/templates/changeset/changeset_file_comment.html:81
+#: kallithea/templates/admin/gists/edit.html:147
+#: kallithea/templates/changeset/changeset_file_comment.html:105
 msgid "Cancel"
 msgstr "キャンセル"
 
@@ -2765,7 +2759,7 @@
 
 #: kallithea/templates/admin/gists/index.html:37
 #: kallithea/templates/admin/gists/show.html:25
-#: kallithea/templates/base/base.html:237
+#: kallithea/templates/base/base.html:321
 msgid "Create New Gist"
 msgstr "新しい Gist を作成"
 
@@ -2853,7 +2847,8 @@
 #: kallithea/templates/admin/settings/settings_hooks.html:36
 #: kallithea/templates/admin/users/user_edit_emails.html:19
 #: kallithea/templates/admin/users/user_edit_ips.html:22
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+#: kallithea/templates/changeset/changeset_file_comment.html:95
 #: kallithea/templates/data_table/_dt_elements.html:129
 #: kallithea/templates/data_table/_dt_elements.html:157
 #: kallithea/templates/data_table/_dt_elements.html:173
@@ -2873,8 +2868,6 @@
 #: kallithea/templates/base/perms_summary.html:43
 #: kallithea/templates/base/perms_summary.html:79
 #: kallithea/templates/base/perms_summary.html:81
-#: kallithea/templates/changeset/changeset_file_comment.html:83
-#: kallithea/templates/changeset/changeset_file_comment.html:192
 #: kallithea/templates/data_table/_dt_elements.html:122
 #: kallithea/templates/data_table/_dt_elements.html:123
 #: kallithea/templates/data_table/_dt_elements.html:150
@@ -2901,13 +2894,12 @@
 msgstr "作成日"
 
 #: kallithea/templates/admin/gists/show.html:86
-#: kallithea/templates/files/files_source.html:73
 msgid "Show as raw"
 msgstr "Raw形式で表示"
 
 #: kallithea/templates/admin/my_account/my_account.html:5
 #: kallithea/templates/admin/my_account/my_account.html:9
-#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:431
 msgid "My Account"
 msgstr "アカウント"
 
@@ -3088,7 +3080,7 @@
 msgstr "コメント"
 
 #: kallithea/templates/admin/notifications/notifications.html:26
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 msgid "Pull Requests"
 msgstr "プルリクエスト"
 
@@ -3106,7 +3098,7 @@
 msgstr "通知を表示"
 
 #: kallithea/templates/admin/notifications/show_notification.html:9
-#: kallithea/templates/base/base.html:342
+#: kallithea/templates/base/base.html:430
 msgid "Notifications"
 msgstr "通知"
 
@@ -3309,7 +3301,7 @@
 #: kallithea/templates/admin/repos/repo_edit.html:40
 #: kallithea/templates/admin/settings/settings.html:11
 #: kallithea/templates/admin/user_groups/user_group_edit.html:29
-#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:151
+#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:148
 #: kallithea/templates/data_table/_dt_elements.html:45
 #: kallithea/templates/data_table/_dt_elements.html:49
 msgid "Settings"
@@ -3571,6 +3563,11 @@
 msgid "Unlock Repository"
 msgstr "リポジトリのロックを解除"
 
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:56
+#, python-format
+msgid "Locked by %s on %s"
+msgstr ""
+
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:60
 msgid "Confirm to lock repository."
 msgstr "このリポジトリをロックしますか?"
@@ -3626,10 +3623,6 @@
 msgid "Invalidate Repository Cache"
 msgstr "リポジトリのキャッシュを無効化"
 
-#: kallithea/templates/admin/repos/repo_edit_caches.html:4
-msgid "Confirm to invalidate repository cache."
-msgstr "リポジトリのキャッシュを無効化してもよろしいですか?"
-
 #: kallithea/templates/admin/repos/repo_edit_caches.html:7
 msgid ""
 "Manually invalidate cache for this repository. On first access, the "
@@ -4130,16 +4123,16 @@
 msgstr ""
 "クローン URL のスキーマは、 '{scheme}://{user}@{netloc}/{repo}' "
 "のような形式にします。使える変数は下記の通りです:\n"
-"                                                        {scheme} Kallithea "
-"サーバからリクエストを送信するときに使うスキーム。 'http' または 'https'\n"
+"                                                        {scheme} "
+"Kallithea サーバからリクエストを送信するときに使うスキーム。 'http' または 'https'\n"
 "                                                        {user}   "
 "現在のユーザーのユーザー名\n"
-"                                                        {netloc} Kallithea "
-"サーバーのアドレスまたはホスト名\n"
+"                                                        {netloc} "
+"Kallithea サーバーのアドレスまたはホスト名\n"
 "                                                        {repo}   "
 "リポジトリの完全な名前\n"
-"                                                        {repoid} リポジトリの ID。 "
-"clone-by-id に使います。"
+"                                                        {repoid} リポジトリの "
+"ID。 clone-by-id に使います。"
 
 #: kallithea/templates/admin/settings/settings_visual.html:55
 msgid "Dashboard items"
@@ -4388,21 +4381,17 @@
 msgid "Files"
 msgstr "ファイル"
 
-#: kallithea/templates/base/base.html:138
-msgid "Switch To"
-msgstr "ブランチの切り替え"
-
-#: kallithea/templates/base/base.html:145
-#: kallithea/templates/base/base.html:147
+#: kallithea/templates/base/base.html:142
+#: kallithea/templates/base/base.html:144
 msgid "Options"
 msgstr "オプション"
 
-#: kallithea/templates/base/base.html:155
+#: kallithea/templates/base/base.html:152
 #: kallithea/templates/forks/forks_data.html:21
 msgid "Compare Fork"
 msgstr "フォークと比較"
 
-#: kallithea/templates/base/base.html:157
+#: kallithea/templates/base/base.html:154
 #: kallithea/templates/bookmarks/bookmarks.html:56
 #: kallithea/templates/bookmarks/bookmarks_data.html:13
 #: kallithea/templates/branches/branches.html:56
@@ -4412,111 +4401,116 @@
 msgid "Compare"
 msgstr "比較"
 
-#: kallithea/templates/base/base.html:159
-#: kallithea/templates/base/base.html:247
+#: kallithea/templates/base/base.html:156
+#: kallithea/templates/base/base.html:331
 #: kallithea/templates/search/search.html:14
 #: kallithea/templates/search/search.html:54
 msgid "Search"
 msgstr "検索"
 
-#: kallithea/templates/base/base.html:163
+#: kallithea/templates/base/base.html:160
 msgid "Unlock"
 msgstr "アンロック"
 
-#: kallithea/templates/base/base.html:165
+#: kallithea/templates/base/base.html:162
 msgid "Lock"
 msgstr "ロック"
 
-#: kallithea/templates/base/base.html:173
+#: kallithea/templates/base/base.html:170
 msgid "Follow"
 msgstr "フォロー"
 
+#: kallithea/templates/base/base.html:171
+msgid "Unfollow"
+msgstr "アンフォロー"
+
 #: kallithea/templates/base/base.html:174
-msgid "Unfollow"
-msgstr "アンフォロー"
-
-#: kallithea/templates/base/base.html:177
 #: kallithea/templates/data_table/_dt_elements.html:37
 #: kallithea/templates/data_table/_dt_elements.html:41
 #: kallithea/templates/forks/fork.html:9
 msgid "Fork"
 msgstr "フォーク"
 
-#: kallithea/templates/base/base.html:178
+#: kallithea/templates/base/base.html:175
 #: kallithea/templates/pullrequests/pullrequest.html:88
 msgid "Create Pull Request"
 msgstr "プルリクエストを作成"
 
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 #, python-format
 msgid "Show Pull Requests for %s"
 msgstr "%s のプルリクエストを表示"
 
-#: kallithea/templates/base/base.html:221
+#: kallithea/templates/base/base.html:193
+msgid "Switch To"
+msgstr "ブランチの切り替え"
+
+#: kallithea/templates/base/base.html:203
+#: kallithea/templates/base/base.html:485
+msgid "No matches found"
+msgstr "一致するものが見つかりません"
+
+#: kallithea/templates/base/base.html:305
 msgid "Show recent activity"
 msgstr "最近の活動を表示"
 
-#: kallithea/templates/base/base.html:227
-#: kallithea/templates/base/base.html:228
+#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:312
 msgid "Public journal"
 msgstr "公開ジャーナル"
 
-#: kallithea/templates/base/base.html:233
+#: kallithea/templates/base/base.html:317
 msgid "Show public gists"
 msgstr "公開 gists を表示"
 
-#: kallithea/templates/base/base.html:234
+#: kallithea/templates/base/base.html:318
 msgid "Gists"
 msgstr "Gists"
 
-#: kallithea/templates/base/base.html:238
+#: kallithea/templates/base/base.html:322
 msgid "All Public Gists"
 msgstr "すべての公開 Gists"
 
-#: kallithea/templates/base/base.html:240
+#: kallithea/templates/base/base.html:324
 msgid "My Public Gists"
 msgstr "公開 Gists"
 
-#: kallithea/templates/base/base.html:241
+#: kallithea/templates/base/base.html:325
 msgid "My Private Gists"
 msgstr "非公開 Gists"
 
-#: kallithea/templates/base/base.html:246
+#: kallithea/templates/base/base.html:330
 msgid "Search in repositories"
 msgstr "リポジトリから検索"
 
-#: kallithea/templates/base/base.html:269
-#: kallithea/templates/base/base.html:270
+#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:354
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:6
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:10
 msgid "My Pull Requests"
 msgstr "私のプルリクエスト"
 
-#: kallithea/templates/base/base.html:289
+#: kallithea/templates/base/base.html:377
 msgid "Not Logged In"
 msgstr "ログインしていません"
 
-#: kallithea/templates/base/base.html:296
+#: kallithea/templates/base/base.html:384
 msgid "Login to Your Account"
 msgstr "あなたのアカウントにログイン"
 
-#: kallithea/templates/base/base.html:319
+#: kallithea/templates/base/base.html:407
 msgid "Forgot password ?"
 msgstr "パスワードを忘れた?"
 
-#: kallithea/templates/base/base.html:346
+#: kallithea/templates/base/base.html:434
 msgid "Log Out"
 msgstr "ログアウト"
 
-#: kallithea/templates/base/base.html:395
-msgid "No matches found"
-msgstr "一致するものが見つかりません"
-
-#: kallithea/templates/base/base.html:524
+#: kallithea/templates/base/base.html:615
 msgid "Keyboard shortcuts"
 msgstr "キーボードショートカット"
 
-#: kallithea/templates/base/base.html:533
+#: kallithea/templates/base/base.html:624
 msgid "Site-wide shortcuts"
 msgstr "サイト全体"
 
@@ -4616,7 +4610,6 @@
 msgstr "マッチするファイルはありません"
 
 #: kallithea/templates/base/root.html:31
-#| msgid "on pull request"
 msgid "Open New Pull Request from {0}"
 msgstr "新しいプルリクエストを{0}から作成"
 
@@ -4625,7 +4618,6 @@
 msgstr "{0} &rarr; {1}から新しいプルリクエストを作成する"
 
 #: kallithea/templates/base/root.html:33
-#| msgid "Show Selected Changesets __S &rarr; __E"
 msgid "Show Selected Changesets {0} &rarr; {1}"
 msgstr "選択したチェンジセット{0} &rarr; {0}を表示"
 
@@ -4636,6 +4628,7 @@
 
 #: kallithea/templates/base/root.html:35
 #: kallithea/templates/changeset/diff_block.html:8
+#: kallithea/templates/changeset/diff_block.html:21
 msgid "Collapse Diff"
 msgstr "差分をたたむ"
 
@@ -4741,55 +4734,59 @@
 
 #: kallithea/templates/changelog/changelog.html:92
 #: kallithea/templates/changelog/changelog_summary_data.html:20
-#, python-format
+#, fuzzy, python-format
+#| msgid "" "Changeset status: %s\n" "Click to open associated pull request %s"
 msgid ""
-"Changeset status: %s\n"
+"Changeset status: %s by %s\n"
 "Click to open associated pull request %s"
 msgstr ""
 "チェンジセットステータス: %s\n"
 "関連するプルリクエスト %s を開く"
 
 #: kallithea/templates/changelog/changelog.html:96
-#: kallithea/templates/compare/compare_cs.html:24
-#, python-format
-msgid "Changeset status: %s"
+#: kallithea/templates/changelog/changelog_summary_data.html:24
+#, fuzzy, python-format
+#| msgid "Changeset status: %s"
+msgid "Changeset status: %s by %s"
 msgstr "チェンジセットステータス: %s"
 
-#: kallithea/templates/changelog/changelog.html:115
+#: kallithea/templates/changelog/changelog.html:116
 #: kallithea/templates/compare/compare_cs.html:63
 msgid "Expand commit message"
 msgstr "コミットメッセージを展開"
 
-#: kallithea/templates/changelog/changelog.html:124
+#: kallithea/templates/changelog/changelog.html:125
 #: kallithea/templates/compare/compare_cs.html:30
 msgid "Changeset has comments"
 msgstr "チェンジセットにコメントがあります"
 
-#: kallithea/templates/changelog/changelog.html:134
-#: kallithea/templates/changelog/changelog_summary_data.html:54
+#: kallithea/templates/changelog/changelog.html:135
+#: kallithea/templates/changelog/changelog_summary_data.html:57
 #: kallithea/templates/changeset/changeset.html:94
 #: kallithea/templates/changeset/changeset_range.html:92
 #, python-format
 msgid "Bookmark %s"
 msgstr "ブックマーク %s"
 
-#: kallithea/templates/changelog/changelog.html:140
-#: kallithea/templates/changelog/changelog_summary_data.html:60
+#: kallithea/templates/changelog/changelog.html:141
+#: kallithea/templates/changelog/changelog_summary_data.html:63
 #: kallithea/templates/changeset/changeset.html:101
 #: kallithea/templates/changeset/changeset_range.html:98
+#: kallithea/templates/compare/compare_cs.html:69
+#: kallithea/templates/pullrequests/pullrequest_show.html:203
 #, python-format
 msgid "Tag %s"
 msgstr "タグ %s"
 
-#: kallithea/templates/changelog/changelog.html:145
-#: kallithea/templates/changelog/changelog_summary_data.html:65
+#: kallithea/templates/changelog/changelog.html:146
+#: kallithea/templates/changelog/changelog_summary_data.html:68
 #: kallithea/templates/changeset/changeset.html:106
 #: kallithea/templates/changeset/changeset_range.html:102
 #, python-format
 msgid "Branch %s"
 msgstr "ブランチ %s"
 
-#: kallithea/templates/changelog/changelog.html:310
+#: kallithea/templates/changelog/changelog.html:311
 msgid "There are no changes yet"
 msgstr "まだ変更がありません"
 
@@ -4805,7 +4802,7 @@
 
 #: kallithea/templates/changelog/changelog_details.html:6
 #: kallithea/templates/changeset/changeset.html:79
-#: kallithea/templates/changeset/diff_block.html:79
+#: kallithea/templates/changeset/diff_block.html:47
 msgid "Added"
 msgstr "追加"
 
@@ -4835,21 +4832,21 @@
 msgid "Refs"
 msgstr "Refs"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:81
+#: kallithea/templates/changelog/changelog_summary_data.html:84
 msgid "Add or upload files directly via Kallithea"
 msgstr "Kallithea経由で直接ファイルを追加またはアップロード"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:84
+#: kallithea/templates/changelog/changelog_summary_data.html:87
 #: kallithea/templates/files/files_add.html:21
 #: kallithea/templates/files/files_ypjax.html:9
 msgid "Add New File"
 msgstr "新しいファイルを追加"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:90
+#: kallithea/templates/changelog/changelog_summary_data.html:93
 msgid "Push new repository"
 msgstr "新しいリポジトリをプッシュ"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:98
+#: kallithea/templates/changelog/changelog_summary_data.html:101
 msgid "Existing repository?"
 msgstr "存在するリポジトリをプッシュ"
 
@@ -4867,13 +4864,13 @@
 msgstr "子リビジョン"
 
 #: kallithea/templates/changeset/changeset.html:50
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #: kallithea/templates/changeset/changeset_range.html:48
 msgid "Changeset status"
 msgstr "チェンジセットステータス"
 
 #: kallithea/templates/changeset/changeset.html:54
-#: kallithea/templates/changeset/diff_block.html:27
+#: kallithea/templates/changeset/diff_block.html:72
 #: kallithea/templates/files/diff_2way.html:49
 msgid "Raw diff"
 msgstr "diffとして差分を表示"
@@ -4883,7 +4880,7 @@
 msgstr "パッチとして差分を表示"
 
 #: kallithea/templates/changeset/changeset.html:60
-#: kallithea/templates/changeset/diff_block.html:30
+#: kallithea/templates/changeset/diff_block.html:75
 #: kallithea/templates/files/diff_2way.html:52
 msgid "Download diff"
 msgstr "差分をダウンロード"
@@ -4913,16 +4910,16 @@
 msgstr "作成日"
 
 #: kallithea/templates/changeset/changeset.html:166
-#: kallithea/templates/compare/compare_diff.html:54
-#: kallithea/templates/pullrequests/pullrequest_show.html:318
+#: kallithea/templates/compare/compare_diff.html:60
+#: kallithea/templates/pullrequests/pullrequest_show.html:329
 #, python-format
 msgid "%s file changed"
 msgid_plural "%s files changed"
 msgstr[0] "%s ファイルに影響"
 
 #: kallithea/templates/changeset/changeset.html:168
-#: kallithea/templates/compare/compare_diff.html:56
-#: kallithea/templates/pullrequests/pullrequest_show.html:320
+#: kallithea/templates/compare/compare_diff.html:62
+#: kallithea/templates/pullrequests/pullrequest_show.html:331
 #, python-format
 msgid "%s file changed with %s insertions and %s deletions"
 msgid_plural "%s files changed with %s insertions and %s deletions"
@@ -4930,13 +4927,13 @@
 
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Show full diff anyway"
 msgstr "とにかくすべての差分を表示"
 
-#: kallithea/templates/changeset/changeset.html:247
-#: kallithea/templates/changeset/changeset.html:284
+#: kallithea/templates/changeset/changeset.html:231
+#: kallithea/templates/changeset/changeset.html:268
 msgid "No revisions"
 msgstr "リビジョンなし"
 
@@ -4954,98 +4951,86 @@
 msgid "on this changeset"
 msgstr "チェンジセットはありません"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
 msgid "Delete comment?"
 msgstr "コメントを削除しますか?"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 msgid "Status change"
 msgstr "ステータスを変更"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:59
-msgid "Commenting on line {1}."
+#, fuzzy
+msgid "Commenting on line."
 msgstr "{1} 行目にコメント"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:60
-#: kallithea/templates/changeset/changeset_file_comment.html:148
-#, python-format
-msgid "Comments parsed using %s syntax with %s support."
-msgstr "コメントには %s 構文 ( %s サポートつき ) が利用できます。"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:62
-msgid "Use @username inside this text to notify another user"
-msgstr "テキスト内で @username を使うと、そのユーザーに通知されます"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:72
-#: kallithea/templates/changeset/changeset_file_comment.html:184
-msgid "Comment preview"
-msgstr "コメントのプレビュー"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:77
+#, fuzzy
+msgid ""
+"Comments are in plain text. Use @username inside this text to notify "
+"another user."
+msgstr "テキスト内で @username を使うと、そのユーザーに通知されます。"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:67
+msgid "Set changeset status"
+msgstr "リビジョンステータスを設定"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:69
+msgid "Vote for pull request status"
+msgstr "プルリクエストステータスの投票"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:75
+msgid "No change"
+msgstr "変更なし"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:88
+#, fuzzy
+msgid "Finish pull request"
+msgstr "プルリクエスト #%s にコメント"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:91
+#, fuzzy
+msgid "Close"
+msgstr "(閉鎖済み)"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:103
 msgid "Submitting ..."
 msgstr "送信中..."
 
-#: kallithea/templates/changeset/changeset_file_comment.html:80
-#: kallithea/templates/changeset/changeset_file_comment.html:190
+#: kallithea/templates/changeset/changeset_file_comment.html:104
 msgid "Comment"
 msgstr "コメント"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:82
-#: kallithea/templates/changeset/changeset_file_comment.html:191
-msgid "Preview"
-msgstr "プレビュー"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "You need to be logged in to comment."
 msgstr "コメントにはログインする必要があります。"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "Login now"
 msgstr "今すぐログインする"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:94
+#: kallithea/templates/changeset/changeset_file_comment.html:116
 msgid "Hide"
 msgstr "隠す"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:106
+#: kallithea/templates/changeset/changeset_file_comment.html:128
 #, python-format
 msgid "%d comment"
 msgid_plural "%d comments"
 msgstr[0] "%d 個のコメント"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:107
+#: kallithea/templates/changeset/changeset_file_comment.html:129
 #, python-format
 msgid "%d inline"
 msgid_plural "%d inline"
 msgstr[0] "%d inline"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:108
+#: kallithea/templates/changeset/changeset_file_comment.html:130
 #, python-format
 msgid "%d general"
 msgid_plural "%d general"
 msgstr[0] "%d general"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:150
-msgid "Use @username inside this text to notify another user."
-msgstr "テキスト内で @username を使うと、そのユーザーに通知されます。"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:157
-msgid "Vote for pull request status"
-msgstr "プルリクエストステータスの投票"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:159
-msgid "Set changeset status"
-msgstr "リビジョンステータスを設定"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:163
-msgid "No change"
-msgstr "変更なし"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:176
-#, fuzzy
-msgid "Close"
-msgstr "(閉鎖済み)"
-
 #: kallithea/templates/changeset/changeset_range.html:5
 #, python-format
 msgid "%s Changesets"
@@ -5055,29 +5040,28 @@
 msgid "Files affected"
 msgstr "影響のあるファイル"
 
-#: kallithea/templates/changeset/diff_block.html:21
+#: kallithea/templates/changeset/diff_block.html:54
+msgid "Deleted"
+msgstr "削除"
+
+#: kallithea/templates/changeset/diff_block.html:57
+msgid "Renamed"
+msgstr "リネーム"
+
+#: kallithea/templates/changeset/diff_block.html:66
 #: kallithea/templates/files/diff_2way.html:43
 msgid "Show full diff for this file"
 msgstr "このファイルのすべての差分を表示"
 
-#: kallithea/templates/changeset/diff_block.html:24
-#: kallithea/templates/changeset/diff_block.html:98
+#: kallithea/templates/changeset/diff_block.html:69
 #: kallithea/templates/files/diff_2way.html:46
 msgid "Show full side-by-side diff for this file"
 msgstr "このファイルの差分を並べて表示"
 
-#: kallithea/templates/changeset/diff_block.html:38
+#: kallithea/templates/changeset/diff_block.html:83
 msgid "Show inline comments"
 msgstr "インラインコメントを表示"
 
-#: kallithea/templates/changeset/diff_block.html:86
-msgid "Deleted"
-msgstr "削除"
-
-#: kallithea/templates/changeset/diff_block.html:89
-msgid "Renamed"
-msgstr "リネーム"
-
 #: kallithea/templates/compare/compare_cs.html:4
 msgid "No changesets"
 msgstr "チェンジセットはありません"
@@ -5086,6 +5070,11 @@
 msgid "Ancestor"
 msgstr "祖先"
 
+#: kallithea/templates/compare/compare_cs.html:24
+#, python-format
+msgid "Changeset status: %s"
+msgstr "チェンジセットステータス: %s"
+
 #: kallithea/templates/compare/compare_cs.html:44
 msgid "First (oldest) changeset in this list"
 msgstr ""
@@ -5098,29 +5087,29 @@
 msgid "Position in this list of changesets"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:76
+#: kallithea/templates/compare/compare_cs.html:85
 msgid "Show merge diff"
 msgstr "マージの差分を表示"
 
-#: kallithea/templates/compare/compare_cs.html:86
-#: kallithea/templates/pullrequests/pullrequest_show.html:310
+#: kallithea/templates/compare/compare_cs.html:95
+#: kallithea/templates/pullrequests/pullrequest_show.html:321
 msgid "Common ancestor"
 msgstr "共通の祖先"
 
-#: kallithea/templates/compare/compare_cs.html:90
+#: kallithea/templates/compare/compare_cs.html:99
 msgid "No common ancestor found - repositories are unrelated"
 msgstr "共通の祖先が見つかりません - リポジトリ同士に関連がありません"
 
-#: kallithea/templates/compare/compare_cs.html:98
+#: kallithea/templates/compare/compare_cs.html:107
 msgid "is"
 msgstr "is"
 
-#: kallithea/templates/compare/compare_cs.html:99
+#: kallithea/templates/compare/compare_cs.html:108
 #, python-format
 msgid "%s changesets"
 msgstr "%s チェンジセット"
 
-#: kallithea/templates/compare/compare_cs.html:100
+#: kallithea/templates/compare/compare_cs.html:109
 msgid "behind"
 msgstr "behind"
 
@@ -5131,27 +5120,27 @@
 msgstr "%s 比較"
 
 #: kallithea/templates/compare/compare_diff.html:13
-#: kallithea/templates/compare/compare_diff.html:35
+#: kallithea/templates/compare/compare_diff.html:41
 msgid "Compare Revisions"
 msgstr "リビジョンを比較"
 
-#: kallithea/templates/compare/compare_diff.html:33
+#: kallithea/templates/compare/compare_diff.html:39
 msgid "Swap"
 msgstr "入れ替え"
 
-#: kallithea/templates/compare/compare_diff.html:42
+#: kallithea/templates/compare/compare_diff.html:48
 msgid "Compare revisions, branches, bookmarks, or tags."
 msgstr "リビジョン、ブランチ、ブックマークもしくはタグの比較を行います。"
 
-#: kallithea/templates/compare/compare_diff.html:47
-#: kallithea/templates/pullrequests/pullrequest_show.html:305
+#: kallithea/templates/compare/compare_diff.html:53
+#: kallithea/templates/pullrequests/pullrequest_show.html:316
 #, python-format
 msgid "Showing %s commit"
 msgid_plural "Showing %s commits"
 msgstr[0] "%s コミットを表示"
 
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
 msgid "Show full diff"
 msgstr "すべての差分を表示"
 
@@ -5207,21 +5196,26 @@
 msgstr "こんにちは %s"
 
 #: kallithea/templates/email_templates/password_reset.html:6
-#| msgid "We received a request to create a new password for your account."
 msgid "We have received a request to reset the password for your account."
 msgstr "あなたのアカウントのパスワードリセットリクエストを受け取りました。"
 
-#: kallithea/templates/email_templates/password_reset.html:7
+#: kallithea/templates/email_templates/password_reset.html:8
+msgid ""
+"This account is however managed outside this system and the password "
+"cannot be changed here."
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:10
 msgid "To set a new password, click the following link"
 msgstr "新しいパスワードを設定するために、次のリンクをクリックしてください"
 
-#: kallithea/templates/email_templates/password_reset.html:10
+#: kallithea/templates/email_templates/password_reset.html:13
 msgid ""
 "Should you not be able to use the link above, please type the following "
 "code into the password reset form"
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:12
+#: kallithea/templates/email_templates/password_reset.html:16
 msgid ""
 "If it weren't you who requested the password reset, just disregard this "
 "message."
@@ -5306,8 +5300,9 @@
 msgstr "新しいファイルを作成"
 
 #: kallithea/templates/files/files_add.html:53
-msgid "New file mode"
-msgstr "ファイルモード"
+#, fuzzy
+msgid "New file type"
+msgstr "新しいファイル"
 
 #: kallithea/templates/files/files_add.html:64
 #: kallithea/templates/files/files_delete.html:43
@@ -5436,10 +5431,21 @@
 msgid "Binary file (%s)"
 msgstr "バイナリファイル (%s)"
 
-#: kallithea/templates/files/files_source.html:73
-msgid "File is too big to display"
+#: kallithea/templates/files/files_source.html:74
+#, fuzzy
+msgid "File is too big to display."
 msgstr "表示するには大きすぎるファイルです"
 
+#: kallithea/templates/files/files_source.html:76
+#, fuzzy
+msgid "Show full annotation anyway."
+msgstr "とにかくすべての差分を表示"
+
+#: kallithea/templates/files/files_source.html:78
+#, fuzzy
+msgid "Show as raw."
+msgstr "Raw形式で表示"
+
 #: kallithea/templates/files/files_ypjax.html:5
 msgid "annotation"
 msgstr "アノテーション"
@@ -5699,39 +5705,46 @@
 msgid "Current revision - no change"
 msgstr "現在のリビジョン ー 変更なし"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:213
+#: kallithea/templates/pullrequests/pullrequest_show.html:215
+msgid ""
+"Pull requests do not change once created. Select a revision and save to "
+"replace this pull request with a new one."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:224
 msgid "Pull Request Reviewers"
 msgstr "プルリクエストレビュアー"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:238
+#: kallithea/templates/pullrequests/pullrequest_show.html:249
 msgid "Remove reviewer"
 msgstr "レビュアーを削除"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:250
-msgid "Type name of reviewer to add"
-msgstr "追加するレビュアーの名前を入力"
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:258
-msgid "Potential Reviewers"
-msgstr "レビュワー候補"
-
 #: kallithea/templates/pullrequests/pullrequest_show.html:261
+msgid "Type name of reviewer to add"
+msgstr "追加するレビュアーの名前を入力"
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:269
+msgid "Potential Reviewers"
+msgstr "レビュワー候補"
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:272
 msgid "Click to add the repository owner as reviewer:"
 msgstr "クリックしてリポジトリの所有所をレビュアーに追加:"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:284
+#: kallithea/templates/pullrequests/pullrequest_show.html:295
 msgid "Save Changes"
 msgstr "変更を保存"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:285
-msgid "Save as New Pull Request"
+#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#, fuzzy
+msgid "Save Updates as New Pull Request"
 msgstr "新しいプルリクエストとして保存"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:286
+#: kallithea/templates/pullrequests/pullrequest_show.html:297
 msgid "Cancel Changes"
 msgstr "変更をキャンセル"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#: kallithea/templates/pullrequests/pullrequest_show.html:307
 msgid "Pull Request Content"
 msgstr "プルリクエストの内容"
 
@@ -5741,8 +5754,8 @@
 msgstr "%s プルリクエスト"
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:11
-#, python-format
-msgid "Pull Requests from %s'"
+#, fuzzy, python-format
+msgid "Pull Requests from '%s'"
 msgstr "%s' からのプルリクエスト"
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:13
@@ -6016,7 +6029,7 @@
 #~ msgstr "ファイルなし"
 
 #~ msgid ""
-#~ msgstr "テキスト内で @username を使うと、その Kallithea のユーザーに通知を送信します"
+#~ msgstr "クローズしたプルリクエストに関連するチェンジセットのステータスを変更することは許可されていません"
 
 #~ msgid "Username \"%(username)s\" is forbidden"
 #~ msgstr "ユーザー名 \"%(username)s\" は許可されていません"
@@ -6186,27 +6199,6 @@
 #~ msgid "reviewer"
 #~ msgstr "レビュアー"
 
-#~ msgid ""
-#~ "Your password reset was successful, new"
-#~ " password has been sent to your "
-#~ "email"
-#~ msgstr "パスワードをリセットに成功しました。新しいパスワードをあなたのメールアドレスに送りました"
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " changeset %(short_id)s on %(branch)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Added by %(pr_username)s] %(repo_name)s pull"
-#~ " request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " pull request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
 #~ msgid "Your new password"
 #~ msgstr "新しいパスワード"
 
@@ -6227,3 +6219,25 @@
 
 #~ msgid "Created by"
 #~ msgstr "作成日"
+
+#~ msgid "This pull request can be updated with changes on %s:"
+#~ msgstr ""
+
+#~ msgid "Confirm to invalidate repository cache."
+#~ msgstr "リポジトリのキャッシュを無効化してもよろしいですか?"
+
+#~ msgid "Comments parsed using %s syntax with %s support."
+#~ msgstr "コメントには %s 構文 ( %s サポートつき ) が利用できます。"
+
+#~ msgid "Use @username inside this text to notify another user"
+#~ msgstr "テキスト内で @username を使うと、そのユーザーに通知されます"
+
+#~ msgid "Comment preview"
+#~ msgstr "コメントのプレビュー"
+
+#~ msgid "Preview"
+#~ msgstr "プレビュー"
+
+#~ msgid "New file mode"
+#~ msgstr "ファイルモード"
+
--- a/kallithea/i18n/kallithea.pot	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/i18n/kallithea.pot	Fri Nov 18 01:11:13 2016 +0100
@@ -1,14 +1,14 @@
 # Translations template for Kallithea.
-# Copyright (C) 2015 Various authors, licensing as GPLv3
+# Copyright (C) 2016 Various authors, licensing as GPLv3
 # This file is distributed under the same license as the Kallithea project.
-# FIRST AUTHOR <EMAIL@ADDRESS>, 2015.
+# FIRST AUTHOR <EMAIL@ADDRESS>, 2016.
 #
 #, fuzzy
 msgid ""
 msgstr ""
-"Project-Id-Version: Kallithea 0.3\n"
+"Project-Id-Version: Kallithea 0.3.99\n"
 "Report-Msgid-Bugs-To: translations@kallithea-scm.org\n"
-"POT-Creation-Date: 2015-09-08 10:34+0200\n"
+"POT-Creation-Date: 2016-03-14 16:51+0100\n"
 "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
 "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
 "Language-Team: LANGUAGE <LL@li.org>\n"
@@ -16,12 +16,12 @@
 "Content-Type: text/plain; charset=UTF-8\n"
 "Content-Transfer-Encoding: 8bit\n"
 
-#: kallithea/controllers/changelog.py:86
-#: kallithea/controllers/pullrequests.py:238 kallithea/lib/base.py:512
+#: kallithea/controllers/changelog.py:85
+#: kallithea/controllers/pullrequests.py:240 kallithea/lib/base.py:515
 msgid "There are no changesets yet"
 msgstr ""
 
-#: kallithea/controllers/changelog.py:166
+#: kallithea/controllers/changelog.py:164
 #: kallithea/controllers/admin/permissions.py:61
 #: kallithea/controllers/admin/permissions.py:65
 #: kallithea/controllers/admin/permissions.py:69
@@ -33,33 +33,29 @@
 msgid "None"
 msgstr ""
 
-#: kallithea/controllers/changelog.py:169 kallithea/controllers/files.py:196
+#: kallithea/controllers/changelog.py:167 kallithea/controllers/files.py:198
 msgid "(closed)"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:89
+#: kallithea/controllers/changeset.py:88
 msgid "Show whitespace"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:96 kallithea/controllers/changeset.py:103
+#: kallithea/controllers/changeset.py:95 kallithea/controllers/changeset.py:102
 #: kallithea/templates/files/diff_2way.html:55
 msgid "Ignore whitespace"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:169
+#: kallithea/controllers/changeset.py:168
 #, python-format
 msgid "Increase diff context to %(num)s lines"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:212 kallithea/controllers/files.py:96
-#: kallithea/controllers/files.py:116 kallithea/controllers/files.py:742
+#: kallithea/controllers/changeset.py:233 kallithea/controllers/files.py:97
+#: kallithea/controllers/files.py:117 kallithea/controllers/files.py:744
 msgid "Such revision does not exist for this repository"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:383
-msgid "Changing status on a changeset associated with a closed pull request is not allowed"
-msgstr ""
-
 #: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:41
 msgid "Select changeset"
 msgstr ""
@@ -109,10 +105,10 @@
 #: kallithea/controllers/feed.py:87
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Changeset was too big and was cut off..."
 msgstr ""
 
@@ -121,111 +117,111 @@
 msgid "%s committed on %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:91
+#: kallithea/controllers/files.py:92
 msgid "Click here to add new file"
 msgstr ""
 
-#: kallithea/controllers/files.py:92
+#: kallithea/controllers/files.py:93
 #, python-format
 msgid "There are no files yet. %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:193
+#: kallithea/controllers/files.py:195
 #, python-format
 msgid "%s at %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:305 kallithea/controllers/files.py:365
-#: kallithea/controllers/files.py:432
+#: kallithea/controllers/files.py:307 kallithea/controllers/files.py:367
+#: kallithea/controllers/files.py:434
 #, python-format
 msgid "This repository has been locked by %s on %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:317
-msgid "You can only delete files with revision being a valid branch "
-msgstr ""
-
-#: kallithea/controllers/files.py:328
+#: kallithea/controllers/files.py:319
+msgid "You can only delete files with revision being a valid branch"
+msgstr ""
+
+#: kallithea/controllers/files.py:330
 #, python-format
 msgid "Deleted file %s via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:350
+#: kallithea/controllers/files.py:352
 #, python-format
 msgid "Successfully deleted file %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:354 kallithea/controllers/files.py:420
-#: kallithea/controllers/files.py:501
+#: kallithea/controllers/files.py:356 kallithea/controllers/files.py:422
+#: kallithea/controllers/files.py:503
 msgid "Error occurred during commit"
 msgstr ""
 
-#: kallithea/controllers/files.py:377
-msgid "You can only edit files with revision being a valid branch "
-msgstr ""
-
-#: kallithea/controllers/files.py:391
+#: kallithea/controllers/files.py:379
+msgid "You can only edit files with revision being a valid branch"
+msgstr ""
+
+#: kallithea/controllers/files.py:393
 #, python-format
 msgid "Edited file %s via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:407
+#: kallithea/controllers/files.py:409
 msgid "No changes"
 msgstr ""
 
-#: kallithea/controllers/files.py:416 kallithea/controllers/files.py:490
+#: kallithea/controllers/files.py:418 kallithea/controllers/files.py:492
 #, python-format
 msgid "Successfully committed to %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:443
+#: kallithea/controllers/files.py:445
 msgid "Added file via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:464
+#: kallithea/controllers/files.py:466
 msgid "No content"
 msgstr ""
 
-#: kallithea/controllers/files.py:468
+#: kallithea/controllers/files.py:470
 msgid "No filename"
 msgstr ""
 
-#: kallithea/controllers/files.py:493
+#: kallithea/controllers/files.py:495
 msgid "Location must be relative path and must not contain .. in path"
 msgstr ""
 
-#: kallithea/controllers/files.py:526
+#: kallithea/controllers/files.py:528
 msgid "Downloads disabled"
 msgstr ""
 
-#: kallithea/controllers/files.py:537
-#, python-format
-msgid "Unknown revision %s"
-msgstr ""
-
 #: kallithea/controllers/files.py:539
-msgid "Empty repository"
+#, python-format
+msgid "Unknown revision %s"
 msgstr ""
 
 #: kallithea/controllers/files.py:541
+msgid "Empty repository"
+msgstr ""
+
+#: kallithea/controllers/files.py:543
 msgid "Unknown archive type"
 msgstr ""
 
-#: kallithea/controllers/files.py:771
+#: kallithea/controllers/files.py:773
 #: kallithea/templates/changeset/changeset_range.html:9
 #: kallithea/templates/email_templates/pull_request.html:15
 #: kallithea/templates/pullrequests/pullrequest.html:97
 msgid "Changesets"
 msgstr ""
 
-#: kallithea/controllers/files.py:772 kallithea/controllers/pullrequests.py:176
-#: kallithea/model/scm.py:820 kallithea/templates/switch_to_list.html:3
+#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:175
+#: kallithea/model/scm.py:716 kallithea/templates/switch_to_list.html:3
 #: kallithea/templates/branches/branches.html:10
 msgid "Branches"
 msgstr ""
 
-#: kallithea/controllers/files.py:773 kallithea/controllers/pullrequests.py:177
-#: kallithea/model/scm.py:831 kallithea/templates/switch_to_list.html:25
+#: kallithea/controllers/files.py:775 kallithea/controllers/pullrequests.py:176
+#: kallithea/model/scm.py:727 kallithea/templates/switch_to_list.html:25
 #: kallithea/templates/tags/tags.html:10
 msgid "Tags"
 msgstr ""
@@ -239,7 +235,7 @@
 msgid "Groups"
 msgstr ""
 
-#: kallithea/controllers/home.py:89
+#: kallithea/controllers/home.py:94
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:106
 #: kallithea/templates/admin/repos/repo_add.html:12
 #: kallithea/templates/admin/repos/repo_add.html:16
@@ -247,23 +243,27 @@
 #: kallithea/templates/admin/users/user_edit_advanced.html:6
 #: kallithea/templates/base/base.html:60 kallithea/templates/base/base.html:77
 #: kallithea/templates/base/base.html:124
-#: kallithea/templates/base/base.html:390
-#: kallithea/templates/base/base.html:562
+#: kallithea/templates/base/base.html:479
+#: kallithea/templates/base/base.html:653
 msgid "Repositories"
 msgstr ""
 
-#: kallithea/controllers/home.py:130
+#: kallithea/controllers/home.py:139
 #: kallithea/templates/files/files_add.html:32
 #: kallithea/templates/files/files_delete.html:23
 #: kallithea/templates/files/files_edit.html:32
 msgid "Branch"
 msgstr ""
 
-#: kallithea/controllers/home.py:136
+#: kallithea/controllers/home.py:145 kallithea/templates/switch_to_list.html:16
+msgid "Closed Branches"
+msgstr ""
+
+#: kallithea/controllers/home.py:151
 msgid "Tag"
 msgstr ""
 
-#: kallithea/controllers/home.py:142
+#: kallithea/controllers/home.py:157
 msgid "Bookmark"
 msgstr ""
 
@@ -274,156 +274,161 @@
 msgstr ""
 
 #: kallithea/controllers/journal.py:115 kallithea/controllers/journal.py:157
-#: kallithea/templates/base/base.html:222
+#: kallithea/templates/base/base.html:306
 #: kallithea/templates/journal/journal.html:4
 #: kallithea/templates/journal/journal.html:12
 msgid "Journal"
 msgstr ""
 
-#: kallithea/controllers/login.py:151 kallithea/controllers/login.py:197
+#: kallithea/controllers/login.py:144 kallithea/controllers/login.py:190
 msgid "Bad captcha"
 msgstr ""
 
-#: kallithea/controllers/login.py:157
-msgid "You have successfully registered into Kallithea"
-msgstr ""
-
-#: kallithea/controllers/login.py:202
+#: kallithea/controllers/login.py:150
+msgid "You have successfully registered with %s"
+msgstr ""
+
+#: kallithea/controllers/login.py:195
 msgid "A password reset confirmation code has been sent"
 msgstr ""
 
-#: kallithea/controllers/login.py:251
+#: kallithea/controllers/login.py:244
 msgid "Invalid password reset token"
 msgstr ""
 
-#: kallithea/controllers/login.py:256
+#: kallithea/controllers/login.py:249
 #: kallithea/controllers/admin/my_account.py:167
 msgid "Successfully updated password"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:124
+#: kallithea/controllers/pullrequests.py:123
 #, python-format
 msgid "%s (closed)"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:152
+#: kallithea/controllers/pullrequests.py:151
 #: kallithea/templates/changeset/changeset.html:12
 #: kallithea/templates/email_templates/changeset_comment.html:17
 msgid "Changeset"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:173
+#: kallithea/controllers/pullrequests.py:172
 msgid "Special"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:174
+#: kallithea/controllers/pullrequests.py:173
 msgid "Peer branches"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:175 kallithea/model/scm.py:826
+#: kallithea/controllers/pullrequests.py:174 kallithea/model/scm.py:722
 #: kallithea/templates/switch_to_list.html:38
 #: kallithea/templates/bookmarks/bookmarks.html:10
 msgid "Bookmarks"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:310
+#: kallithea/controllers/pullrequests.py:312
 #, python-format
 msgid "Error creating pull request: %s"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:356
-#: kallithea/controllers/pullrequests.py:503
+#: kallithea/controllers/pullrequests.py:358
+#: kallithea/controllers/pullrequests.py:505
 msgid "No description"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:363
+#: kallithea/controllers/pullrequests.py:365
 msgid "Successfully opened new pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:366
-#: kallithea/controllers/pullrequests.py:453
-#: kallithea/controllers/pullrequests.py:509
+#: kallithea/controllers/pullrequests.py:368
+#: kallithea/controllers/pullrequests.py:455
+#: kallithea/controllers/pullrequests.py:512
 #, python-format
 msgid "Invalid reviewer \"%s\" specified"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:369
-#: kallithea/controllers/pullrequests.py:456
+#: kallithea/controllers/pullrequests.py:371
+#: kallithea/controllers/pullrequests.py:458
 msgid "Error occurred while creating pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:401
+#: kallithea/controllers/pullrequests.py:403
 msgid "Missing changesets since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:408
+#: kallithea/controllers/pullrequests.py:410
 #, python-format
 msgid "New changesets on %s %s since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:415
+#: kallithea/controllers/pullrequests.py:417
 msgid "Ancestor didn't change - show diff since previous version:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:422
-#, python-format
-msgid "This pull request is based on another %s revision and there is no simple diff."
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:424
 #, python-format
+msgid "This pull request is based on another %s revision and there is no simple diff."
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:426
+#, python-format
 msgid "No changes found on %s %s since previous version."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:462
+#: kallithea/controllers/pullrequests.py:464
 #, python-format
 msgid "Closed, replaced by %s ."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:470
+#: kallithea/controllers/pullrequests.py:472
 msgid "Pull request update created"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:513
+#: kallithea/controllers/pullrequests.py:516
 msgid "Pull request updated"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:528
+#: kallithea/controllers/pullrequests.py:531
 msgid "Successfully deleted pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:594
+#: kallithea/controllers/pullrequests.py:597
 #, python-format
 msgid "This pull request has already been merged to %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:596
+#: kallithea/controllers/pullrequests.py:599
 msgid "This pull request has been closed and can not be updated."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:614
-#, python-format
-msgid "This pull request can be updated with changes on %s:"
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:617
+#, python-format
+msgid "The following changes are available on %s:"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:621
 msgid "No changesets found for updating this pull request."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:625
+#: kallithea/controllers/pullrequests.py:629
 #, python-format
 msgid "Note: Branch %s has another head: %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:631
+#: kallithea/controllers/pullrequests.py:635
 msgid "Git pull requests don't support updates yet."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:722
-msgid "No permission to change pull request status"
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:727
+msgid "No permission to change pull request status"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:738
+#, python-format
+msgid "Successfully deleted pull request %s"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:748
 msgid "Closing."
 msgstr ""
 
@@ -439,12 +444,12 @@
 msgid "An error occurred during search operation."
 msgstr ""
 
-#: kallithea/controllers/summary.py:180
+#: kallithea/controllers/summary.py:181
 #: kallithea/templates/summary/summary.html:384
 msgid "No data ready yet"
 msgstr ""
 
-#: kallithea/controllers/summary.py:183
+#: kallithea/controllers/summary.py:184
 #: kallithea/templates/summary/summary.html:98
 msgid "Statistics are disabled for this repository"
 msgstr ""
@@ -465,64 +470,64 @@
 msgid "Error occurred during update of defaults"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/gists.py:58
 #: kallithea/controllers/admin/my_account.py:243
+#: kallithea/controllers/admin/users.py:284
+msgid "Forever"
+msgstr ""
+
+#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/my_account.py:244
 #: kallithea/controllers/admin/users.py:285
-msgid "Forever"
+msgid "5 minutes"
 msgstr ""
 
 #: kallithea/controllers/admin/gists.py:60
-#: kallithea/controllers/admin/my_account.py:244
+#: kallithea/controllers/admin/my_account.py:245
 #: kallithea/controllers/admin/users.py:286
-msgid "5 minutes"
+msgid "1 hour"
 msgstr ""
 
 #: kallithea/controllers/admin/gists.py:61
-#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/my_account.py:246
 #: kallithea/controllers/admin/users.py:287
-msgid "1 hour"
+msgid "1 day"
 msgstr ""
 
 #: kallithea/controllers/admin/gists.py:62
-#: kallithea/controllers/admin/my_account.py:246
+#: kallithea/controllers/admin/my_account.py:247
 #: kallithea/controllers/admin/users.py:288
-msgid "1 day"
-msgstr ""
-
-#: kallithea/controllers/admin/gists.py:63
-#: kallithea/controllers/admin/my_account.py:247
-#: kallithea/controllers/admin/users.py:289
 msgid "1 month"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:67
+#: kallithea/controllers/admin/gists.py:66
 #: kallithea/controllers/admin/my_account.py:249
-#: kallithea/controllers/admin/users.py:291
+#: kallithea/controllers/admin/users.py:290
 msgid "Lifetime"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:146
+#: kallithea/controllers/admin/gists.py:145
 msgid "Error occurred during gist creation"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:184
+#: kallithea/controllers/admin/gists.py:183
 #, python-format
 msgid "Deleted gist %s"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:233
+#: kallithea/controllers/admin/gists.py:232
 msgid "Unmodified"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:262
+#: kallithea/controllers/admin/gists.py:261
 msgid "Successfully updated gist content"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:267
+#: kallithea/controllers/admin/gists.py:266
 msgid "Successfully updated gist data"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:270
+#: kallithea/controllers/admin/gists.py:269
 #, python-format
 msgid "Error occurred during update of gist %s"
 msgstr ""
@@ -537,7 +542,7 @@
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:144
-#: kallithea/controllers/admin/users.py:202
+#: kallithea/controllers/admin/users.py:201
 #, python-format
 msgid "Error occurred during update of user %s"
 msgstr ""
@@ -547,33 +552,33 @@
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:220
-#: kallithea/controllers/admin/users.py:415
+#: kallithea/controllers/admin/users.py:414
 #, python-format
 msgid "Added email %s to user"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:226
-#: kallithea/controllers/admin/users.py:421
+#: kallithea/controllers/admin/users.py:420
 msgid "An error occurred during email saving"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:235
-#: kallithea/controllers/admin/users.py:433
+#: kallithea/controllers/admin/users.py:432
 msgid "Removed email from user"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:259
-#: kallithea/controllers/admin/users.py:308
+#: kallithea/controllers/admin/users.py:307
 msgid "API key successfully created"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:271
-#: kallithea/controllers/admin/users.py:321
+#: kallithea/controllers/admin/users.py:320
 msgid "API key successfully reset"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:275
-#: kallithea/controllers/admin/users.py:325
+#: kallithea/controllers/admin/users.py:324
 msgid "API key successfully deleted"
 msgstr ""
 
@@ -623,10 +628,10 @@
 #: kallithea/templates/admin/users/user_edit_profile.html:105
 #: kallithea/templates/admin/users/users.html:10
 #: kallithea/templates/admin/users/users.html:55
-#: kallithea/templates/base/base.html:252
-#: kallithea/templates/base/base.html:253
-#: kallithea/templates/base/base.html:259
-#: kallithea/templates/base/base.html:260
+#: kallithea/templates/base/base.html:336
+#: kallithea/templates/base/base.html:337
+#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:344
 #: kallithea/templates/base/perms_summary.html:17
 msgid "Admin"
 msgstr ""
@@ -657,7 +662,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1564
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1603
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1655
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1701
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1705
 msgid "Manual activation of external account"
 msgstr ""
 
@@ -669,7 +674,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1565
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1604
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1656
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1702
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1706
 msgid "Automatic activation of external account"
 msgstr ""
 
@@ -690,240 +695,240 @@
 msgid "Error occurred during update of permissions"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:188
+#: kallithea/controllers/admin/repo_groups.py:187
 #, python-format
 msgid "Error occurred during creation of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:193
+#: kallithea/controllers/admin/repo_groups.py:192
 #, python-format
 msgid "Created repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:250
+#: kallithea/controllers/admin/repo_groups.py:249
 #, python-format
 msgid "Updated repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:266
+#: kallithea/controllers/admin/repo_groups.py:265
 #, python-format
 msgid "Error occurred during update of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:284
+#: kallithea/controllers/admin/repo_groups.py:283
 #, python-format
 msgid "This group contains %s repositories and cannot be deleted"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:291
+#: kallithea/controllers/admin/repo_groups.py:290
 #, python-format
 msgid "This group contains %s subgroups and cannot be deleted"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:297
+#: kallithea/controllers/admin/repo_groups.py:296
 #, python-format
 msgid "Removed repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:302
+#: kallithea/controllers/admin/repo_groups.py:301
 #, python-format
 msgid "Error occurred during deletion of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:405
-#: kallithea/controllers/admin/repo_groups.py:440
+#: kallithea/controllers/admin/repo_groups.py:404
+#: kallithea/controllers/admin/repo_groups.py:439
 #: kallithea/controllers/admin/user_groups.py:340
 msgid "Cannot revoke permission for yourself as admin"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:420
+#: kallithea/controllers/admin/repo_groups.py:419
 msgid "Repository group permissions updated"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:457
-#: kallithea/controllers/admin/repos.py:398
+#: kallithea/controllers/admin/repo_groups.py:456
+#: kallithea/controllers/admin/repos.py:397
 #: kallithea/controllers/admin/user_groups.py:352
 msgid "An error occurred during revoking of permission"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:152
+#: kallithea/controllers/admin/repos.py:151
 #, python-format
 msgid "Error creating repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:213
+#: kallithea/controllers/admin/repos.py:212
 #, python-format
 msgid "Created repository %s from %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:222
+#: kallithea/controllers/admin/repos.py:221
 #, python-format
 msgid "Forked repository %s as %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:225
+#: kallithea/controllers/admin/repos.py:224
 #, python-format
 msgid "Created repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:262
+#: kallithea/controllers/admin/repos.py:261
 #, python-format
 msgid "Repository %s updated successfully"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:283
+#: kallithea/controllers/admin/repos.py:282
 #, python-format
 msgid "Error occurred during update of repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:310
+#: kallithea/controllers/admin/repos.py:309
 #, python-format
 msgid "Detached %s forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:313
+#: kallithea/controllers/admin/repos.py:312
 #, python-format
 msgid "Deleted %s forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:318
+#: kallithea/controllers/admin/repos.py:317
 #, python-format
 msgid "Deleted repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:321
+#: kallithea/controllers/admin/repos.py:320
 #, python-format
 msgid "Cannot delete repository %s which still has forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:326
+#: kallithea/controllers/admin/repos.py:325
 #, python-format
 msgid "An error occurred during deletion of %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:374
+#: kallithea/controllers/admin/repos.py:373
 msgid "Repository permissions updated"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:430
+#: kallithea/controllers/admin/repos.py:429
 msgid "An error occurred during creation of field"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:444
+#: kallithea/controllers/admin/repos.py:443
 msgid "An error occurred during removal of field"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:460
+#: kallithea/controllers/admin/repos.py:459
 msgid "-- Not a fork --"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:491
+#: kallithea/controllers/admin/repos.py:490
 msgid "Updated repository visibility in public journal"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:495
+#: kallithea/controllers/admin/repos.py:494
 msgid "An error occurred during setting this repository in public journal"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:512
+#: kallithea/controllers/admin/repos.py:511
 msgid "Nothing"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:514
+#: kallithea/controllers/admin/repos.py:513
 #, python-format
 msgid "Marked repository %s as fork of %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:521
+#: kallithea/controllers/admin/repos.py:520
 msgid "An error occurred during this operation"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:537
-#: kallithea/controllers/admin/repos.py:564
+#: kallithea/controllers/admin/repos.py:536
+#: kallithea/controllers/admin/repos.py:563
 msgid "Repository has been locked"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:540
-#: kallithea/controllers/admin/repos.py:561
+#: kallithea/controllers/admin/repos.py:539
+#: kallithea/controllers/admin/repos.py:560
 msgid "Repository has been unlocked"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:543
-#: kallithea/controllers/admin/repos.py:568
+#: kallithea/controllers/admin/repos.py:542
+#: kallithea/controllers/admin/repos.py:567
 msgid "An error occurred during unlocking"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:582
+#: kallithea/controllers/admin/repos.py:581
 msgid "Cache invalidation successful"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:586
+#: kallithea/controllers/admin/repos.py:585
 msgid "An error occurred during cache invalidation"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:601
+#: kallithea/controllers/admin/repos.py:600
 msgid "Pulled from remote location"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:604
+#: kallithea/controllers/admin/repos.py:603
 msgid "An error occurred during pull from remote location"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:637
+#: kallithea/controllers/admin/repos.py:636
 msgid "An error occurred during deletion of repository stats"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:170
+#: kallithea/controllers/admin/settings.py:141
 msgid "Updated VCS settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:174
+#: kallithea/controllers/admin/settings.py:145
 msgid "Unable to activate hgsubversion support. The \"hgsubversion\" library is missing"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:180
-#: kallithea/controllers/admin/settings.py:277
+#: kallithea/controllers/admin/settings.py:151
+#: kallithea/controllers/admin/settings.py:248
 msgid "Error occurred while updating application settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:216
+#: kallithea/controllers/admin/settings.py:187
 #, python-format
 msgid "Repositories successfully rescanned. Added: %s. Removed: %s."
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:273
+#: kallithea/controllers/admin/settings.py:244
 msgid "Updated application settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:330
+#: kallithea/controllers/admin/settings.py:301
 msgid "Updated visualisation settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:335
+#: kallithea/controllers/admin/settings.py:306
 msgid "Error occurred during updating visualisation settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:361
+#: kallithea/controllers/admin/settings.py:332
 msgid "Please enter email address"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:376
+#: kallithea/controllers/admin/settings.py:347
 msgid "Send email task created"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:407
+#: kallithea/controllers/admin/settings.py:378
 msgid "Added new hook"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:421
+#: kallithea/controllers/admin/settings.py:392
 msgid "Updated hooks"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:425
+#: kallithea/controllers/admin/settings.py:396
 msgid "Error occurred during hook creation"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:451
+#: kallithea/controllers/admin/settings.py:422
 msgid "Whoosh reindex task scheduled"
 msgstr ""
 
@@ -964,76 +969,80 @@
 msgstr ""
 
 #: kallithea/controllers/admin/user_groups.py:440
-#: kallithea/controllers/admin/users.py:384
+#: kallithea/controllers/admin/users.py:383
 msgid "Updated permissions"
 msgstr ""
 
 #: kallithea/controllers/admin/user_groups.py:444
-#: kallithea/controllers/admin/users.py:388
+#: kallithea/controllers/admin/users.py:387
 msgid "An error occurred during permissions saving"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:134
+#: kallithea/controllers/admin/users.py:133
 #, python-format
 msgid "Created user %s"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:149
+#: kallithea/controllers/admin/users.py:148
 #, python-format
 msgid "Error occurred during creation of user %s"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:182
+#: kallithea/controllers/admin/users.py:181
 msgid "User updated successfully"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:218
+#: kallithea/controllers/admin/users.py:217
 msgid "Successfully deleted user"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:223
+#: kallithea/controllers/admin/users.py:222
 msgid "An error occurred during deletion of user"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:236
+#: kallithea/controllers/admin/users.py:235
 msgid "The default user cannot be edited"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:463
+#: kallithea/controllers/admin/users.py:462
 #, python-format
 msgid "Added IP address %s to user whitelist"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:469
+#: kallithea/controllers/admin/users.py:468
 msgid "An error occurred while adding IP address"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:483
+#: kallithea/controllers/admin/users.py:482
 msgid "Removed IP address from user whitelist"
 msgstr ""
 
-#: kallithea/lib/auth.py:743
+#: kallithea/lib/auth.py:737
 #, python-format
 msgid "IP %s not allowed"
 msgstr ""
 
-#: kallithea/lib/auth.py:756
+#: kallithea/lib/auth.py:750
 msgid "Invalid API key"
 msgstr ""
 
-#: kallithea/lib/auth.py:812
+#: kallithea/lib/auth.py:768
+msgid "CSRF token leak has been detected - all form tokens have been expired"
+msgstr ""
+
+#: kallithea/lib/auth.py:813
 msgid "You need to be a registered user to perform this action"
 msgstr ""
 
-#: kallithea/lib/auth.py:844
+#: kallithea/lib/auth.py:843
 msgid "You need to be signed in to view this page"
 msgstr ""
 
-#: kallithea/lib/base.py:490
+#: kallithea/lib/base.py:493
 msgid "Repository not found in the filesystem"
 msgstr ""
 
-#: kallithea/lib/base.py:516 kallithea/lib/helpers.py:622
+#: kallithea/lib/base.py:519 kallithea/lib/helpers.py:623
 msgid "Changeset not found"
 msgstr ""
 
@@ -1049,125 +1058,125 @@
 msgid "No changes detected"
 msgstr ""
 
-#: kallithea/lib/helpers.py:609
+#: kallithea/lib/helpers.py:610
 #, python-format
 msgid "Deleted branch: %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:611
+#: kallithea/lib/helpers.py:612
 #, python-format
 msgid "Created tag: %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:671
+#: kallithea/lib/helpers.py:672
 #, python-format
 msgid "Show all combined changesets %s->%s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:677
+#: kallithea/lib/helpers.py:678
 msgid "Compare view"
 msgstr ""
 
-#: kallithea/lib/helpers.py:696
-msgid "and"
-msgstr ""
-
 #: kallithea/lib/helpers.py:697
+msgid "and"
+msgstr ""
+
+#: kallithea/lib/helpers.py:698
 #, python-format
 msgid "%s more"
 msgstr ""
 
-#: kallithea/lib/helpers.py:698 kallithea/templates/changelog/changelog.html:44
+#: kallithea/lib/helpers.py:699 kallithea/templates/changelog/changelog.html:44
 msgid "revisions"
 msgstr ""
 
-#: kallithea/lib/helpers.py:722
+#: kallithea/lib/helpers.py:723
 #, python-format
 msgid "Fork name %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:742
+#: kallithea/lib/helpers.py:743
 #, python-format
 msgid "Pull request %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:752
+#: kallithea/lib/helpers.py:753
 msgid "[deleted] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:754 kallithea/lib/helpers.py:766
+#: kallithea/lib/helpers.py:755 kallithea/lib/helpers.py:767
 msgid "[created] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:756
+#: kallithea/lib/helpers.py:757
 msgid "[created] repository as fork"
 msgstr ""
 
-#: kallithea/lib/helpers.py:758 kallithea/lib/helpers.py:768
+#: kallithea/lib/helpers.py:759 kallithea/lib/helpers.py:769
 msgid "[forked] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:760 kallithea/lib/helpers.py:770
+#: kallithea/lib/helpers.py:761 kallithea/lib/helpers.py:771
 msgid "[updated] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:762
+#: kallithea/lib/helpers.py:763
 msgid "[downloaded] archive from repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:764
+#: kallithea/lib/helpers.py:765
 msgid "[delete] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:772
+#: kallithea/lib/helpers.py:773
 msgid "[created] user"
 msgstr ""
 
-#: kallithea/lib/helpers.py:774
+#: kallithea/lib/helpers.py:775
 msgid "[updated] user"
 msgstr ""
 
-#: kallithea/lib/helpers.py:776
+#: kallithea/lib/helpers.py:777
 msgid "[created] user group"
 msgstr ""
 
-#: kallithea/lib/helpers.py:778
+#: kallithea/lib/helpers.py:779
 msgid "[updated] user group"
 msgstr ""
 
-#: kallithea/lib/helpers.py:780
+#: kallithea/lib/helpers.py:781
 msgid "[commented] on revision in repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:782
+#: kallithea/lib/helpers.py:783
 msgid "[commented] on pull request for"
 msgstr ""
 
-#: kallithea/lib/helpers.py:784
+#: kallithea/lib/helpers.py:785
 msgid "[closed] pull request for"
 msgstr ""
 
-#: kallithea/lib/helpers.py:786
+#: kallithea/lib/helpers.py:787
 msgid "[pushed] into"
 msgstr ""
 
-#: kallithea/lib/helpers.py:788
+#: kallithea/lib/helpers.py:789
 msgid "[committed via Kallithea] into repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:790
+#: kallithea/lib/helpers.py:791
 msgid "[pulled from remote] into repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:792
+#: kallithea/lib/helpers.py:793
 msgid "[pulled] from"
 msgstr ""
 
-#: kallithea/lib/helpers.py:794
+#: kallithea/lib/helpers.py:795
 msgid "[started following] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:796
+#: kallithea/lib/helpers.py:797
 msgid "[stopped following] repository"
 msgstr ""
 
@@ -1177,8 +1186,8 @@
 msgstr ""
 
 #: kallithea/lib/helpers.py:1128
-#: kallithea/templates/compare/compare_diff.html:65
-#: kallithea/templates/pullrequests/pullrequest_show.html:326
+#: kallithea/templates/compare/compare_diff.html:71
+#: kallithea/templates/pullrequests/pullrequest_show.html:337
 msgid "No files"
 msgstr ""
 
@@ -1202,74 +1211,74 @@
 msgid "chmod"
 msgstr ""
 
-#: kallithea/lib/helpers.py:1444
+#: kallithea/lib/helpers.py:1469
 #, python-format
 msgid "%s repository is not mapped to db perhaps it was created or renamed from the filesystem please run the application again in order to rescan repositories"
 msgstr ""
 
-#: kallithea/lib/utils2.py:415
+#: kallithea/lib/utils2.py:434
 #, python-format
 msgid "%d year"
 msgid_plural "%d years"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:416
+#: kallithea/lib/utils2.py:435
 #, python-format
 msgid "%d month"
 msgid_plural "%d months"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:417
+#: kallithea/lib/utils2.py:436
 #, python-format
 msgid "%d day"
 msgid_plural "%d days"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:418
+#: kallithea/lib/utils2.py:437
 #, python-format
 msgid "%d hour"
 msgid_plural "%d hours"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:419
+#: kallithea/lib/utils2.py:438
 #, python-format
 msgid "%d minute"
 msgid_plural "%d minutes"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:420
+#: kallithea/lib/utils2.py:439
 #, python-format
 msgid "%d second"
 msgid_plural "%d seconds"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:436
+#: kallithea/lib/utils2.py:455
 #, python-format
 msgid "in %s"
 msgstr ""
 
-#: kallithea/lib/utils2.py:438
+#: kallithea/lib/utils2.py:457
 #, python-format
 msgid "%s ago"
 msgstr ""
 
-#: kallithea/lib/utils2.py:440
+#: kallithea/lib/utils2.py:459
 #, python-format
 msgid "in %s and %s"
 msgstr ""
 
-#: kallithea/lib/utils2.py:443
+#: kallithea/lib/utils2.py:462
 #, python-format
 msgid "%s and %s ago"
 msgstr ""
 
-#: kallithea/lib/utils2.py:446
+#: kallithea/lib/utils2.py:465
 msgid "just now"
 msgstr ""
 
@@ -1368,7 +1377,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1531
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1570
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1620
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1665
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1669
 msgid "Kallithea Administrator"
 msgstr ""
 
@@ -1479,7 +1488,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2063
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2102
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2155
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2229
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2237
 msgid "Approved"
 msgstr ""
 
@@ -1494,7 +1503,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2064
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2103
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2156
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2230
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2238
 msgid "Rejected"
 msgstr ""
 
@@ -1521,7 +1530,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1379
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1418
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1471
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1518
 msgid "top level"
 msgstr ""
 
@@ -1668,7 +1677,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1560
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1599
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1651
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1697
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1701
 msgid "Registration disabled"
 msgstr ""
 
@@ -1695,12 +1704,12 @@
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1645
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1691
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1695
 msgid "Repository creation enabled with write permission to a repository group"
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1646
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1692
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1696
 msgid "Repository creation disabled with write permission to a repository group"
 msgstr ""
 
@@ -1709,103 +1718,103 @@
 msgid "on line %s"
 msgstr ""
 
-#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:169
+#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:170
 msgid "[Mention]"
 msgstr ""
 
-#: kallithea/model/db.py:1667
+#: kallithea/model/db.py:1671
 msgid "Default user has no access to new repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1668
-msgid "Default user has read access to new repositories"
-msgstr ""
-
-#: kallithea/model/db.py:1669
-msgid "Default user has write access to new repositories"
-msgstr ""
-
-#: kallithea/model/db.py:1670
-msgid "Default user has admin access to new repositories"
-msgstr ""
-
 #: kallithea/model/db.py:1672
-msgid "Default user has no access to new repository groups"
+msgid "Default user has read access to new repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1673
-msgid "Default user has read access to new repository groups"
+msgid "Default user has write access to new repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1674
-msgid "Default user has write access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1675
-msgid "Default user has admin access to new repository groups"
+msgid "Default user has admin access to new repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1676
+msgid "Default user has no access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1677
-msgid "Default user has no access to new user groups"
+msgid "Default user has read access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1678
-msgid "Default user has read access to new user groups"
+msgid "Default user has write access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1679
-msgid "Default user has write access to new user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1680
-msgid "Default user has admin access to new user groups"
+msgid "Default user has admin access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1681
+msgid "Default user has no access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1682
-msgid "Only admins can create repository groups"
+msgid "Default user has read access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1683
-msgid "Non-admins can create repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1685
-msgid "Only admins can create user groups"
+msgid "Default user has write access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1684
+msgid "Default user has admin access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1686
-msgid "Non-admins can create user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1688
-msgid "Only admins can create top level repositories"
+msgid "Only admins can create repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1687
+msgid "Non-admins can create repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1689
+msgid "Only admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1690
+msgid "Non-admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1692
+msgid "Only admins can create top level repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1693
 msgid "Non-admins can create top level repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1694
-msgid "Only admins can fork repositories"
-msgstr ""
-
-#: kallithea/model/db.py:1695
-msgid "Non-admins can can fork repositories"
-msgstr ""
-
 #: kallithea/model/db.py:1698
-msgid "User registration with manual account activation"
+msgid "Only admins can fork repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1699
+msgid "Non-admins can fork repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1702
+msgid "User registration with manual account activation"
+msgstr ""
+
+#: kallithea/model/db.py:1703
 msgid "User registration with automatic account activation"
 msgstr ""
 
-#: kallithea/model/db.py:2228
+#: kallithea/model/db.py:2236
 msgid "Not reviewed"
 msgstr ""
 
-#: kallithea/model/db.py:2231
+#: kallithea/model/db.py:2239
 msgid "Under review"
 msgstr ""
 
@@ -1827,7 +1836,7 @@
 msgid "Enter %(min)i characters or more"
 msgstr ""
 
-#: kallithea/model/forms.py:160
+#: kallithea/model/forms.py:165
 msgid "Name must not contain only digits"
 msgstr ""
 
@@ -1920,7 +1929,7 @@
 msgid "%(user)s wants you to review pull request %(pr_nice_id)s: %(pr_title)s"
 msgstr ""
 
-#: kallithea/model/scm.py:812
+#: kallithea/model/scm.py:708
 msgid "latest tip"
 msgstr ""
 
@@ -1947,15 +1956,15 @@
 msgid "User \"%s\" still owns %s user groups and cannot be removed. Switch owners or remove those user groups: %s"
 msgstr ""
 
-#: kallithea/model/user.py:360
+#: kallithea/model/user.py:368
 msgid "Password reset link"
 msgstr ""
 
-#: kallithea/model/user.py:408
+#: kallithea/model/user.py:418
 msgid "Password reset notification"
 msgstr ""
 
-#: kallithea/model/user.py:409
+#: kallithea/model/user.py:419
 #, python-format
 msgid "The password to your account %s has been changed using password reset form."
 msgstr ""
@@ -1964,159 +1973,159 @@
 msgid "Value cannot be an empty list"
 msgstr ""
 
-#: kallithea/model/validators.py:95
+#: kallithea/model/validators.py:96
 #, python-format
 msgid "Username \"%(username)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:97
+#: kallithea/model/validators.py:98
 #, python-format
 msgid "Username \"%(username)s\" cannot be used"
 msgstr ""
 
-#: kallithea/model/validators.py:99
+#: kallithea/model/validators.py:100
 msgid "Username may only contain alphanumeric characters underscores, periods or dashes and must begin with an alphanumeric character or underscore"
 msgstr ""
 
-#: kallithea/model/validators.py:126
+#: kallithea/model/validators.py:127
 msgid "The input is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:133
+#: kallithea/model/validators.py:134
 #, python-format
 msgid "Username %(username)s is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:152
+#: kallithea/model/validators.py:154
 msgid "Invalid user group name"
 msgstr ""
 
-#: kallithea/model/validators.py:153
-#, python-format
-msgid "User group \"%(usergroup)s\" already exists"
-msgstr ""
-
 #: kallithea/model/validators.py:155
+#, python-format
+msgid "User group \"%(usergroup)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:157
 msgid "user group name may only contain alphanumeric characters underscores, periods or dashes and must begin with alphanumeric character"
 msgstr ""
 
-#: kallithea/model/validators.py:193
+#: kallithea/model/validators.py:197
 msgid "Cannot assign this group as parent"
 msgstr ""
 
-#: kallithea/model/validators.py:194
+#: kallithea/model/validators.py:198
 #, python-format
 msgid "Group \"%(group_name)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:196
+#: kallithea/model/validators.py:200
 #, python-format
 msgid "Repository with name \"%(group_name)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:254
+#: kallithea/model/validators.py:258
 msgid "Invalid characters (non-ascii) in password"
 msgstr ""
 
-#: kallithea/model/validators.py:269
+#: kallithea/model/validators.py:273
 msgid "Invalid old password"
 msgstr ""
 
-#: kallithea/model/validators.py:285
+#: kallithea/model/validators.py:289
 msgid "Passwords do not match"
 msgstr ""
 
-#: kallithea/model/validators.py:300
+#: kallithea/model/validators.py:304
 msgid "Invalid username or password"
 msgstr ""
 
-#: kallithea/model/validators.py:331
+#: kallithea/model/validators.py:335
 msgid "Token mismatch"
 msgstr ""
 
-#: kallithea/model/validators.py:345
+#: kallithea/model/validators.py:351
 #, python-format
 msgid "Repository name %(repo)s is not allowed"
 msgstr ""
 
-#: kallithea/model/validators.py:347
+#: kallithea/model/validators.py:353
 #, python-format
 msgid "Repository named %(repo)s already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:348
+#: kallithea/model/validators.py:354
 #, python-format
 msgid "Repository \"%(repo)s\" already exists in group \"%(group)s\""
 msgstr ""
 
-#: kallithea/model/validators.py:350
+#: kallithea/model/validators.py:356
 #, python-format
 msgid "Repository group with name \"%(repo)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:465
+#: kallithea/model/validators.py:470
 msgid "Invalid repository URL"
 msgstr ""
 
-#: kallithea/model/validators.py:466
+#: kallithea/model/validators.py:471
 msgid "Invalid repository URL. It must be a valid http, https, ssh, svn+http or svn+https URL"
 msgstr ""
 
-#: kallithea/model/validators.py:489
+#: kallithea/model/validators.py:496
 msgid "Fork has to be the same type as parent"
 msgstr ""
 
-#: kallithea/model/validators.py:504
+#: kallithea/model/validators.py:511
 msgid "You don't have permissions to create repository in this group"
 msgstr ""
 
-#: kallithea/model/validators.py:506
+#: kallithea/model/validators.py:513
 msgid "no permission to create repository in root location"
 msgstr ""
 
-#: kallithea/model/validators.py:556
+#: kallithea/model/validators.py:563
 msgid "You don't have permissions to create a group in this location"
 msgstr ""
 
-#: kallithea/model/validators.py:597
+#: kallithea/model/validators.py:604
 msgid "This username or user group name is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:690
+#: kallithea/model/validators.py:697
 msgid "This is not a valid path"
 msgstr ""
 
-#: kallithea/model/validators.py:705
+#: kallithea/model/validators.py:714
 msgid "This email address is already in use"
 msgstr ""
 
-#: kallithea/model/validators.py:725
+#: kallithea/model/validators.py:734
 #, python-format
 msgid "Email address \"%(email)s\" not found"
 msgstr ""
 
-#: kallithea/model/validators.py:762
+#: kallithea/model/validators.py:771
 msgid "The LDAP Login attribute of the CN must be specified - this is the name of the attribute that is equivalent to \"username\""
 msgstr ""
 
-#: kallithea/model/validators.py:774
+#: kallithea/model/validators.py:783
 msgid "Please enter a valid IPv4 or IPv6 address"
 msgstr ""
 
-#: kallithea/model/validators.py:775
+#: kallithea/model/validators.py:784
 #, python-format
 msgid "The network size (bits) must be within the range of 0-32 (not %(bits)r)"
 msgstr ""
 
-#: kallithea/model/validators.py:808
+#: kallithea/model/validators.py:817
 msgid "Key name can only consist of letters, underscore, dash or numbers"
 msgstr ""
 
-#: kallithea/model/validators.py:822
+#: kallithea/model/validators.py:831
 msgid "Filename cannot be inside a directory"
 msgstr ""
 
-#: kallithea/model/validators.py:838
+#: kallithea/model/validators.py:847
 #, python-format
 msgid "Plugins %(loaded)s and %(next_to_load)s both export the same name"
 msgstr ""
@@ -2243,7 +2252,7 @@
 #: kallithea/templates/admin/user_groups/user_groups.html:50
 #: kallithea/templates/pullrequests/pullrequest_data.html:16
 #: kallithea/templates/pullrequests/pullrequest_show.html:156
-#: kallithea/templates/pullrequests/pullrequest_show.html:233
+#: kallithea/templates/pullrequests/pullrequest_show.html:244
 #: kallithea/templates/summary/summary.html:134
 msgid "Owner"
 msgstr ""
@@ -2291,7 +2300,7 @@
 #: kallithea/templates/index_base.html:144
 #: kallithea/templates/admin/my_account/my_account_repos.html:61
 #: kallithea/templates/admin/my_account/my_account_watched.html:61
-#: kallithea/templates/base/base.html:140 kallithea/templates/base/root.html:47
+#: kallithea/templates/base/root.html:47
 #: kallithea/templates/bookmarks/bookmarks.html:83
 #: kallithea/templates/branches/branches.html:83
 #: kallithea/templates/journal/journal.html:202
@@ -2301,7 +2310,7 @@
 msgstr ""
 
 #: kallithea/templates/login.html:5 kallithea/templates/login.html:15
-#: kallithea/templates/base/base.html:326
+#: kallithea/templates/base/base.html:414
 msgid "Log In"
 msgstr ""
 
@@ -2316,7 +2325,7 @@
 #: kallithea/templates/admin/users/user_add.html:32
 #: kallithea/templates/admin/users/user_edit_profile.html:24
 #: kallithea/templates/admin/users/users.html:50
-#: kallithea/templates/base/base.html:302
+#: kallithea/templates/base/base.html:390
 #: kallithea/templates/pullrequests/pullrequest_show.html:166
 msgid "Username"
 msgstr ""
@@ -2324,7 +2333,7 @@
 #: kallithea/templates/login.html:33 kallithea/templates/register.html:33
 #: kallithea/templates/admin/my_account/my_account.html:37
 #: kallithea/templates/admin/users/user_add.html:41
-#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:399
 msgid "Password"
 msgstr ""
 
@@ -2336,7 +2345,7 @@
 msgid "Forgot your password ?"
 msgstr ""
 
-#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:322
+#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:410
 msgid "Don't have an account ?"
 msgstr ""
 
@@ -2453,10 +2462,6 @@
 msgid "There are no branches yet"
 msgstr ""
 
-#: kallithea/templates/switch_to_list.html:16
-msgid "Closed Branches"
-msgstr ""
-
 #: kallithea/templates/switch_to_list.html:32
 #: kallithea/templates/tags/tags_data.html:44
 msgid "There are no tags yet"
@@ -2677,12 +2682,12 @@
 msgid "Never"
 msgstr ""
 
-#: kallithea/templates/admin/gists/edit.html:145
+#: kallithea/templates/admin/gists/edit.html:146
 msgid "Update Gist"
 msgstr ""
 
-#: kallithea/templates/admin/gists/edit.html:146
-#: kallithea/templates/changeset/changeset_file_comment.html:81
+#: kallithea/templates/admin/gists/edit.html:147
+#: kallithea/templates/changeset/changeset_file_comment.html:105
 msgid "Cancel"
 msgstr ""
 
@@ -2705,7 +2710,7 @@
 
 #: kallithea/templates/admin/gists/index.html:37
 #: kallithea/templates/admin/gists/show.html:25
-#: kallithea/templates/base/base.html:237
+#: kallithea/templates/base/base.html:321
 msgid "Create New Gist"
 msgstr ""
 
@@ -2793,7 +2798,8 @@
 #: kallithea/templates/admin/settings/settings_hooks.html:36
 #: kallithea/templates/admin/users/user_edit_emails.html:19
 #: kallithea/templates/admin/users/user_edit_ips.html:22
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+#: kallithea/templates/changeset/changeset_file_comment.html:95
 #: kallithea/templates/data_table/_dt_elements.html:129
 #: kallithea/templates/data_table/_dt_elements.html:157
 #: kallithea/templates/data_table/_dt_elements.html:173
@@ -2813,8 +2819,6 @@
 #: kallithea/templates/base/perms_summary.html:43
 #: kallithea/templates/base/perms_summary.html:79
 #: kallithea/templates/base/perms_summary.html:81
-#: kallithea/templates/changeset/changeset_file_comment.html:83
-#: kallithea/templates/changeset/changeset_file_comment.html:192
 #: kallithea/templates/data_table/_dt_elements.html:122
 #: kallithea/templates/data_table/_dt_elements.html:123
 #: kallithea/templates/data_table/_dt_elements.html:150
@@ -2841,13 +2845,12 @@
 msgstr ""
 
 #: kallithea/templates/admin/gists/show.html:86
-#: kallithea/templates/files/files_source.html:73
 msgid "Show as raw"
 msgstr ""
 
 #: kallithea/templates/admin/my_account/my_account.html:5
 #: kallithea/templates/admin/my_account/my_account.html:9
-#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:431
 msgid "My Account"
 msgstr ""
 
@@ -3028,7 +3031,7 @@
 msgstr ""
 
 #: kallithea/templates/admin/notifications/notifications.html:26
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 msgid "Pull Requests"
 msgstr ""
 
@@ -3046,7 +3049,7 @@
 msgstr ""
 
 #: kallithea/templates/admin/notifications/show_notification.html:9
-#: kallithea/templates/base/base.html:342
+#: kallithea/templates/base/base.html:430
 msgid "Notifications"
 msgstr ""
 
@@ -3228,7 +3231,7 @@
 #: kallithea/templates/admin/repos/repo_edit.html:40
 #: kallithea/templates/admin/settings/settings.html:11
 #: kallithea/templates/admin/user_groups/user_group_edit.html:29
-#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:151
+#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:148
 #: kallithea/templates/data_table/_dt_elements.html:45
 #: kallithea/templates/data_table/_dt_elements.html:49
 msgid "Settings"
@@ -3476,6 +3479,11 @@
 msgid "Unlock Repository"
 msgstr ""
 
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:56
+#, python-format
+msgid "Locked by %s on %s"
+msgstr ""
+
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:60
 msgid "Confirm to lock repository."
 msgstr ""
@@ -3525,10 +3533,6 @@
 msgid "Invalidate Repository Cache"
 msgstr ""
 
-#: kallithea/templates/admin/repos/repo_edit_caches.html:4
-msgid "Confirm to invalidate repository cache."
-msgstr ""
-
 #: kallithea/templates/admin/repos/repo_edit_caches.html:7
 msgid "Manually invalidate cache for this repository. On first access, the repository will be cached again."
 msgstr ""
@@ -3966,7 +3970,7 @@
 "                                                        {user}   current user username,\n"
 "                                                        {netloc} network location/server host of running Kallithea server,\n"
 "                                                        {repo}   full repository name,\n"
-"                                                        {repoid} ID of repository, can be used to contruct clone-by-id"
+"                                                        {repoid} ID of repository, can be used to construct clone-by-id"
 msgstr ""
 
 #: kallithea/templates/admin/settings/settings_visual.html:55
@@ -4210,21 +4214,17 @@
 msgid "Files"
 msgstr ""
 
-#: kallithea/templates/base/base.html:138
-msgid "Switch To"
-msgstr ""
-
-#: kallithea/templates/base/base.html:145
-#: kallithea/templates/base/base.html:147
+#: kallithea/templates/base/base.html:142
+#: kallithea/templates/base/base.html:144
 msgid "Options"
 msgstr ""
 
-#: kallithea/templates/base/base.html:155
+#: kallithea/templates/base/base.html:152
 #: kallithea/templates/forks/forks_data.html:21
 msgid "Compare Fork"
 msgstr ""
 
-#: kallithea/templates/base/base.html:157
+#: kallithea/templates/base/base.html:154
 #: kallithea/templates/bookmarks/bookmarks.html:56
 #: kallithea/templates/bookmarks/bookmarks_data.html:13
 #: kallithea/templates/branches/branches.html:56
@@ -4234,111 +4234,116 @@
 msgid "Compare"
 msgstr ""
 
-#: kallithea/templates/base/base.html:159
-#: kallithea/templates/base/base.html:247
+#: kallithea/templates/base/base.html:156
+#: kallithea/templates/base/base.html:331
 #: kallithea/templates/search/search.html:14
 #: kallithea/templates/search/search.html:54
 msgid "Search"
 msgstr ""
 
-#: kallithea/templates/base/base.html:163
+#: kallithea/templates/base/base.html:160
 msgid "Unlock"
 msgstr ""
 
-#: kallithea/templates/base/base.html:165
+#: kallithea/templates/base/base.html:162
 msgid "Lock"
 msgstr ""
 
-#: kallithea/templates/base/base.html:173
+#: kallithea/templates/base/base.html:170
 msgid "Follow"
 msgstr ""
 
+#: kallithea/templates/base/base.html:171
+msgid "Unfollow"
+msgstr ""
+
 #: kallithea/templates/base/base.html:174
-msgid "Unfollow"
-msgstr ""
-
-#: kallithea/templates/base/base.html:177
 #: kallithea/templates/data_table/_dt_elements.html:37
 #: kallithea/templates/data_table/_dt_elements.html:41
 #: kallithea/templates/forks/fork.html:9
 msgid "Fork"
 msgstr ""
 
-#: kallithea/templates/base/base.html:178
+#: kallithea/templates/base/base.html:175
 #: kallithea/templates/pullrequests/pullrequest.html:88
 msgid "Create Pull Request"
 msgstr ""
 
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 #, python-format
 msgid "Show Pull Requests for %s"
 msgstr ""
 
-#: kallithea/templates/base/base.html:221
+#: kallithea/templates/base/base.html:193
+msgid "Switch To"
+msgstr ""
+
+#: kallithea/templates/base/base.html:203
+#: kallithea/templates/base/base.html:485
+msgid "No matches found"
+msgstr ""
+
+#: kallithea/templates/base/base.html:305
 msgid "Show recent activity"
 msgstr ""
 
-#: kallithea/templates/base/base.html:227
-#: kallithea/templates/base/base.html:228
+#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:312
 msgid "Public journal"
 msgstr ""
 
-#: kallithea/templates/base/base.html:233
+#: kallithea/templates/base/base.html:317
 msgid "Show public gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:234
+#: kallithea/templates/base/base.html:318
 msgid "Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:238
+#: kallithea/templates/base/base.html:322
 msgid "All Public Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:240
+#: kallithea/templates/base/base.html:324
 msgid "My Public Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:241
+#: kallithea/templates/base/base.html:325
 msgid "My Private Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:246
+#: kallithea/templates/base/base.html:330
 msgid "Search in repositories"
 msgstr ""
 
-#: kallithea/templates/base/base.html:269
-#: kallithea/templates/base/base.html:270
+#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:354
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:6
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:10
 msgid "My Pull Requests"
 msgstr ""
 
-#: kallithea/templates/base/base.html:289
+#: kallithea/templates/base/base.html:377
 msgid "Not Logged In"
 msgstr ""
 
-#: kallithea/templates/base/base.html:296
+#: kallithea/templates/base/base.html:384
 msgid "Login to Your Account"
 msgstr ""
 
-#: kallithea/templates/base/base.html:319
+#: kallithea/templates/base/base.html:407
 msgid "Forgot password ?"
 msgstr ""
 
-#: kallithea/templates/base/base.html:346
+#: kallithea/templates/base/base.html:434
 msgid "Log Out"
 msgstr ""
 
-#: kallithea/templates/base/base.html:395
-msgid "No matches found"
-msgstr ""
-
-#: kallithea/templates/base/base.html:524
+#: kallithea/templates/base/base.html:615
 msgid "Keyboard shortcuts"
 msgstr ""
 
-#: kallithea/templates/base/base.html:533
+#: kallithea/templates/base/base.html:624
 msgid "Site-wide shortcuts"
 msgstr ""
 
@@ -4453,6 +4458,7 @@
 
 #: kallithea/templates/base/root.html:35
 #: kallithea/templates/changeset/diff_block.html:8
+#: kallithea/templates/changeset/diff_block.html:21
 msgid "Collapse Diff"
 msgstr ""
 
@@ -4561,51 +4567,53 @@
 #: kallithea/templates/changelog/changelog_summary_data.html:20
 #, python-format
 msgid ""
-"Changeset status: %s\n"
+"Changeset status: %s by %s\n"
 "Click to open associated pull request %s"
 msgstr ""
 
 #: kallithea/templates/changelog/changelog.html:96
-#: kallithea/templates/compare/compare_cs.html:24
-#, python-format
-msgid "Changeset status: %s"
-msgstr ""
-
-#: kallithea/templates/changelog/changelog.html:115
+#: kallithea/templates/changelog/changelog_summary_data.html:24
+#, python-format
+msgid "Changeset status: %s by %s"
+msgstr ""
+
+#: kallithea/templates/changelog/changelog.html:116
 #: kallithea/templates/compare/compare_cs.html:63
 msgid "Expand commit message"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:124
+#: kallithea/templates/changelog/changelog.html:125
 #: kallithea/templates/compare/compare_cs.html:30
 msgid "Changeset has comments"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:134
-#: kallithea/templates/changelog/changelog_summary_data.html:54
+#: kallithea/templates/changelog/changelog.html:135
+#: kallithea/templates/changelog/changelog_summary_data.html:57
 #: kallithea/templates/changeset/changeset.html:94
 #: kallithea/templates/changeset/changeset_range.html:92
 #, python-format
 msgid "Bookmark %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:140
-#: kallithea/templates/changelog/changelog_summary_data.html:60
+#: kallithea/templates/changelog/changelog.html:141
+#: kallithea/templates/changelog/changelog_summary_data.html:63
 #: kallithea/templates/changeset/changeset.html:101
 #: kallithea/templates/changeset/changeset_range.html:98
+#: kallithea/templates/compare/compare_cs.html:69
+#: kallithea/templates/pullrequests/pullrequest_show.html:203
 #, python-format
 msgid "Tag %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:145
-#: kallithea/templates/changelog/changelog_summary_data.html:65
+#: kallithea/templates/changelog/changelog.html:146
+#: kallithea/templates/changelog/changelog_summary_data.html:68
 #: kallithea/templates/changeset/changeset.html:106
 #: kallithea/templates/changeset/changeset_range.html:102
 #, python-format
 msgid "Branch %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:310
+#: kallithea/templates/changelog/changelog.html:311
 msgid "There are no changes yet"
 msgstr ""
 
@@ -4621,7 +4629,7 @@
 
 #: kallithea/templates/changelog/changelog_details.html:6
 #: kallithea/templates/changeset/changeset.html:79
-#: kallithea/templates/changeset/diff_block.html:79
+#: kallithea/templates/changeset/diff_block.html:47
 msgid "Added"
 msgstr ""
 
@@ -4651,21 +4659,21 @@
 msgid "Refs"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:81
+#: kallithea/templates/changelog/changelog_summary_data.html:84
 msgid "Add or upload files directly via Kallithea"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:84
+#: kallithea/templates/changelog/changelog_summary_data.html:87
 #: kallithea/templates/files/files_add.html:21
 #: kallithea/templates/files/files_ypjax.html:9
 msgid "Add New File"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:90
+#: kallithea/templates/changelog/changelog_summary_data.html:93
 msgid "Push new repository"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:98
+#: kallithea/templates/changelog/changelog_summary_data.html:101
 msgid "Existing repository?"
 msgstr ""
 
@@ -4683,13 +4691,13 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:50
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #: kallithea/templates/changeset/changeset_range.html:48
 msgid "Changeset status"
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:54
-#: kallithea/templates/changeset/diff_block.html:27
+#: kallithea/templates/changeset/diff_block.html:72
 #: kallithea/templates/files/diff_2way.html:49
 msgid "Raw diff"
 msgstr ""
@@ -4699,7 +4707,7 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:60
-#: kallithea/templates/changeset/diff_block.html:30
+#: kallithea/templates/changeset/diff_block.html:75
 #: kallithea/templates/files/diff_2way.html:52
 msgid "Download diff"
 msgstr ""
@@ -4726,8 +4734,8 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:166
-#: kallithea/templates/compare/compare_diff.html:54
-#: kallithea/templates/pullrequests/pullrequest_show.html:318
+#: kallithea/templates/compare/compare_diff.html:60
+#: kallithea/templates/pullrequests/pullrequest_show.html:329
 #, python-format
 msgid "%s file changed"
 msgid_plural "%s files changed"
@@ -4735,8 +4743,8 @@
 msgstr[1] ""
 
 #: kallithea/templates/changeset/changeset.html:168
-#: kallithea/templates/compare/compare_diff.html:56
-#: kallithea/templates/pullrequests/pullrequest_show.html:320
+#: kallithea/templates/compare/compare_diff.html:62
+#: kallithea/templates/pullrequests/pullrequest_show.html:331
 #, python-format
 msgid "%s file changed with %s insertions and %s deletions"
 msgid_plural "%s files changed with %s insertions and %s deletions"
@@ -4745,13 +4753,13 @@
 
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Show full diff anyway"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset.html:247
-#: kallithea/templates/changeset/changeset.html:284
+#: kallithea/templates/changeset/changeset.html:231
+#: kallithea/templates/changeset/changeset.html:268
 msgid "No revisions"
 msgstr ""
 
@@ -4767,100 +4775,83 @@
 msgid "on this changeset"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
 msgid "Delete comment?"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 msgid "Status change"
 msgstr ""
 
 #: kallithea/templates/changeset/changeset_file_comment.html:59
-msgid "Commenting on line {1}."
+msgid "Commenting on line."
 msgstr ""
 
 #: kallithea/templates/changeset/changeset_file_comment.html:60
-#: kallithea/templates/changeset/changeset_file_comment.html:148
-#, python-format
-msgid "Comments parsed using %s syntax with %s support."
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:62
-msgid "Use @username inside this text to notify another user"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:72
-#: kallithea/templates/changeset/changeset_file_comment.html:184
-msgid "Comment preview"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:77
+msgid "Comments are in plain text. Use @username inside this text to notify another user."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:67
+msgid "Set changeset status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:69
+msgid "Vote for pull request status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:75
+msgid "No change"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:88
+msgid "Finish pull request"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:91
+msgid "Close"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:103
 msgid "Submitting ..."
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:80
-#: kallithea/templates/changeset/changeset_file_comment.html:190
+#: kallithea/templates/changeset/changeset_file_comment.html:104
 msgid "Comment"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:82
-#: kallithea/templates/changeset/changeset_file_comment.html:191
-msgid "Preview"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "You need to be logged in to comment."
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "Login now"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:94
+#: kallithea/templates/changeset/changeset_file_comment.html:116
 msgid "Hide"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:106
+#: kallithea/templates/changeset/changeset_file_comment.html:128
 #, python-format
 msgid "%d comment"
 msgid_plural "%d comments"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:107
+#: kallithea/templates/changeset/changeset_file_comment.html:129
 #, python-format
 msgid "%d inline"
 msgid_plural "%d inline"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:108
+#: kallithea/templates/changeset/changeset_file_comment.html:130
 #, python-format
 msgid "%d general"
 msgid_plural "%d general"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:150
-msgid "Use @username inside this text to notify another user."
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:157
-msgid "Vote for pull request status"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:159
-msgid "Set changeset status"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:163
-msgid "No change"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:176
-msgid "Close"
-msgstr ""
-
 #: kallithea/templates/changeset/changeset_range.html:5
 #, python-format
 msgid "%s Changesets"
@@ -4870,29 +4861,28 @@
 msgid "Files affected"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:21
+#: kallithea/templates/changeset/diff_block.html:54
+msgid "Deleted"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:57
+msgid "Renamed"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:66
 #: kallithea/templates/files/diff_2way.html:43
 msgid "Show full diff for this file"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:24
-#: kallithea/templates/changeset/diff_block.html:98
+#: kallithea/templates/changeset/diff_block.html:69
 #: kallithea/templates/files/diff_2way.html:46
 msgid "Show full side-by-side diff for this file"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:38
+#: kallithea/templates/changeset/diff_block.html:83
 msgid "Show inline comments"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:86
-msgid "Deleted"
-msgstr ""
-
-#: kallithea/templates/changeset/diff_block.html:89
-msgid "Renamed"
-msgstr ""
-
 #: kallithea/templates/compare/compare_cs.html:4
 msgid "No changesets"
 msgstr ""
@@ -4901,6 +4891,11 @@
 msgid "Ancestor"
 msgstr ""
 
+#: kallithea/templates/compare/compare_cs.html:24
+#, python-format
+msgid "Changeset status: %s"
+msgstr ""
+
 #: kallithea/templates/compare/compare_cs.html:44
 msgid "First (oldest) changeset in this list"
 msgstr ""
@@ -4913,29 +4908,29 @@
 msgid "Position in this list of changesets"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:76
+#: kallithea/templates/compare/compare_cs.html:85
 msgid "Show merge diff"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:86
-#: kallithea/templates/pullrequests/pullrequest_show.html:310
+#: kallithea/templates/compare/compare_cs.html:95
+#: kallithea/templates/pullrequests/pullrequest_show.html:321
 msgid "Common ancestor"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:90
-msgid "No common ancestor found - repositories are unrelated"
-msgstr ""
-
-#: kallithea/templates/compare/compare_cs.html:98
-msgid "is"
-msgstr ""
-
 #: kallithea/templates/compare/compare_cs.html:99
+msgid "No common ancestor found - repositories are unrelated"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:107
+msgid "is"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:108
 #, python-format
 msgid "%s changesets"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:100
+#: kallithea/templates/compare/compare_cs.html:109
 msgid "behind"
 msgstr ""
 
@@ -4946,28 +4941,28 @@
 msgstr ""
 
 #: kallithea/templates/compare/compare_diff.html:13
-#: kallithea/templates/compare/compare_diff.html:35
+#: kallithea/templates/compare/compare_diff.html:41
 msgid "Compare Revisions"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:33
+#: kallithea/templates/compare/compare_diff.html:39
 msgid "Swap"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:42
+#: kallithea/templates/compare/compare_diff.html:48
 msgid "Compare revisions, branches, bookmarks, or tags."
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:47
-#: kallithea/templates/pullrequests/pullrequest_show.html:305
+#: kallithea/templates/compare/compare_diff.html:53
+#: kallithea/templates/pullrequests/pullrequest_show.html:316
 #, python-format
 msgid "Showing %s commit"
 msgid_plural "Showing %s commits"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
 msgid "Show full diff"
 msgstr ""
 
@@ -5026,15 +5021,19 @@
 msgid "We have received a request to reset the password for your account."
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:7
-msgid "To set a new password, click the following link"
+#: kallithea/templates/email_templates/password_reset.html:8
+msgid "This account is however managed outside this system and the password cannot be changed here."
 msgstr ""
 
 #: kallithea/templates/email_templates/password_reset.html:10
+msgid "To set a new password, click the following link"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:13
 msgid "Should you not be able to use the link above, please type the following code into the password reset form"
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:12
+#: kallithea/templates/email_templates/password_reset.html:16
 msgid "If it weren't you who requested the password reset, just disregard this message."
 msgstr ""
 
@@ -5115,7 +5114,7 @@
 msgstr ""
 
 #: kallithea/templates/files/files_add.html:53
-msgid "New file mode"
+msgid "New file type"
 msgstr ""
 
 #: kallithea/templates/files/files_add.html:64
@@ -5246,8 +5245,16 @@
 msgid "Binary file (%s)"
 msgstr ""
 
-#: kallithea/templates/files/files_source.html:73
-msgid "File is too big to display"
+#: kallithea/templates/files/files_source.html:74
+msgid "File is too big to display."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:76
+msgid "Show full annotation anyway."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:78
+msgid "Show as raw."
 msgstr ""
 
 #: kallithea/templates/files/files_ypjax.html:5
@@ -5508,39 +5515,43 @@
 msgid "Current revision - no change"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:213
+#: kallithea/templates/pullrequests/pullrequest_show.html:215
+msgid "Pull requests do not change once created. Select a revision and save to replace this pull request with a new one."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:224
 msgid "Pull Request Reviewers"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:238
+#: kallithea/templates/pullrequests/pullrequest_show.html:249
 msgid "Remove reviewer"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:250
-msgid "Type name of reviewer to add"
-msgstr ""
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:258
-msgid "Potential Reviewers"
-msgstr ""
-
 #: kallithea/templates/pullrequests/pullrequest_show.html:261
+msgid "Type name of reviewer to add"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:269
+msgid "Potential Reviewers"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:272
 msgid "Click to add the repository owner as reviewer:"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:284
+#: kallithea/templates/pullrequests/pullrequest_show.html:295
 msgid "Save Changes"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:285
-msgid "Save as New Pull Request"
-msgstr ""
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:286
-msgid "Cancel Changes"
-msgstr ""
-
 #: kallithea/templates/pullrequests/pullrequest_show.html:296
+msgid "Save Updates as New Pull Request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:297
+msgid "Cancel Changes"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:307
 msgid "Pull Request Content"
 msgstr ""
 
@@ -5551,7 +5562,7 @@
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:11
 #, python-format
-msgid "Pull Requests from %s'"
+msgid "Pull Requests from '%s'"
 msgstr ""
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:13
--- a/kallithea/i18n/nl_BE/LC_MESSAGES/kallithea.po	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/i18n/nl_BE/LC_MESSAGES/kallithea.po	Fri Nov 18 01:11:13 2016 +0100
@@ -7,7 +7,7 @@
 msgstr ""
 "Project-Id-Version: Kallithea 0.3\n"
 "Report-Msgid-Bugs-To: translations@kallithea-scm.org\n"
-"POT-Creation-Date: 2015-09-08 10:34+0200\n"
+"POT-Creation-Date: 2016-03-14 16:51+0100\n"
 "PO-Revision-Date: 2015-05-28 22:41+0200\n"
 "Last-Translator: Sam Jaques <sam.jaques@me.com>\n"
 "Language-Team: Dutch (Belgium) "
@@ -19,12 +19,12 @@
 "Plural-Forms: nplurals=2; plural=(n != 1);\n"
 "X-Generator: Weblate 2.3-dev\n"
 
-#: kallithea/controllers/changelog.py:86
-#: kallithea/controllers/pullrequests.py:238 kallithea/lib/base.py:512
+#: kallithea/controllers/changelog.py:85
+#: kallithea/controllers/pullrequests.py:240 kallithea/lib/base.py:515
 msgid "There are no changesets yet"
 msgstr "Er zijn nog geen changesets"
 
-#: kallithea/controllers/changelog.py:166
+#: kallithea/controllers/changelog.py:164
 #: kallithea/controllers/admin/permissions.py:61
 #: kallithea/controllers/admin/permissions.py:65
 #: kallithea/controllers/admin/permissions.py:69
@@ -36,38 +36,30 @@
 msgid "None"
 msgstr "Geen"
 
-#: kallithea/controllers/changelog.py:169 kallithea/controllers/files.py:196
+#: kallithea/controllers/changelog.py:167 kallithea/controllers/files.py:198
 msgid "(closed)"
 msgstr "(gesloten)"
 
-#: kallithea/controllers/changeset.py:89
+#: kallithea/controllers/changeset.py:88
 msgid "Show whitespace"
 msgstr "Toon witruimtes"
 
-#: kallithea/controllers/changeset.py:96 kallithea/controllers/changeset.py:103
+#: kallithea/controllers/changeset.py:95 kallithea/controllers/changeset.py:102
 #: kallithea/templates/files/diff_2way.html:55
 #, fuzzy
 msgid "Ignore whitespace"
 msgstr "Negeer witruimtes"
 
-#: kallithea/controllers/changeset.py:169
+#: kallithea/controllers/changeset.py:168
 #, fuzzy, python-format
 msgid "Increase diff context to %(num)s lines"
 msgstr "vergroot de diff context met %(num)s lijnen"
 
-#: kallithea/controllers/changeset.py:212 kallithea/controllers/files.py:96
-#: kallithea/controllers/files.py:116 kallithea/controllers/files.py:742
+#: kallithea/controllers/changeset.py:233 kallithea/controllers/files.py:97
+#: kallithea/controllers/files.py:117 kallithea/controllers/files.py:744
 msgid "Such revision does not exist for this repository"
 msgstr "Deze revisie bestaat niet in deze repository"
 
-#: kallithea/controllers/changeset.py:383
-msgid ""
-"Changing status on a changeset associated with a closed pull request is "
-"not allowed"
-msgstr ""
-"Het is niet toegestaan de status te wijzigen van een changeset "
-"geassocieerd met een gesloten pull request"
-
 #: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:41
 msgid "Select changeset"
 msgstr "Selecteer de changeset"
@@ -119,10 +111,10 @@
 #: kallithea/controllers/feed.py:87
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Changeset was too big and was cut off..."
 msgstr ""
 
@@ -131,111 +123,111 @@
 msgid "%s committed on %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:91
+#: kallithea/controllers/files.py:92
 msgid "Click here to add new file"
 msgstr ""
 
-#: kallithea/controllers/files.py:92
+#: kallithea/controllers/files.py:93
 #, python-format
 msgid "There are no files yet. %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:193
+#: kallithea/controllers/files.py:195
 #, python-format
 msgid "%s at %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:305 kallithea/controllers/files.py:365
-#: kallithea/controllers/files.py:432
+#: kallithea/controllers/files.py:307 kallithea/controllers/files.py:367
+#: kallithea/controllers/files.py:434
 #, python-format
 msgid "This repository has been locked by %s on %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:317
-msgid "You can only delete files with revision being a valid branch "
-msgstr ""
-
-#: kallithea/controllers/files.py:328
+#: kallithea/controllers/files.py:319
+msgid "You can only delete files with revision being a valid branch"
+msgstr ""
+
+#: kallithea/controllers/files.py:330
 #, python-format
 msgid "Deleted file %s via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:350
+#: kallithea/controllers/files.py:352
 #, python-format
 msgid "Successfully deleted file %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:354 kallithea/controllers/files.py:420
-#: kallithea/controllers/files.py:501
+#: kallithea/controllers/files.py:356 kallithea/controllers/files.py:422
+#: kallithea/controllers/files.py:503
 msgid "Error occurred during commit"
 msgstr ""
 
-#: kallithea/controllers/files.py:377
-msgid "You can only edit files with revision being a valid branch "
-msgstr ""
-
-#: kallithea/controllers/files.py:391
+#: kallithea/controllers/files.py:379
+msgid "You can only edit files with revision being a valid branch"
+msgstr ""
+
+#: kallithea/controllers/files.py:393
 #, python-format
 msgid "Edited file %s via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:407
+#: kallithea/controllers/files.py:409
 msgid "No changes"
 msgstr ""
 
-#: kallithea/controllers/files.py:416 kallithea/controllers/files.py:490
+#: kallithea/controllers/files.py:418 kallithea/controllers/files.py:492
 #, python-format
 msgid "Successfully committed to %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:443
+#: kallithea/controllers/files.py:445
 msgid "Added file via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:464
+#: kallithea/controllers/files.py:466
 msgid "No content"
 msgstr ""
 
-#: kallithea/controllers/files.py:468
+#: kallithea/controllers/files.py:470
 msgid "No filename"
 msgstr ""
 
-#: kallithea/controllers/files.py:493
+#: kallithea/controllers/files.py:495
 msgid "Location must be relative path and must not contain .. in path"
 msgstr ""
 
-#: kallithea/controllers/files.py:526
+#: kallithea/controllers/files.py:528
 msgid "Downloads disabled"
 msgstr ""
 
-#: kallithea/controllers/files.py:537
-#, python-format
-msgid "Unknown revision %s"
-msgstr ""
-
 #: kallithea/controllers/files.py:539
-msgid "Empty repository"
+#, python-format
+msgid "Unknown revision %s"
 msgstr ""
 
 #: kallithea/controllers/files.py:541
+msgid "Empty repository"
+msgstr ""
+
+#: kallithea/controllers/files.py:543
 msgid "Unknown archive type"
 msgstr ""
 
-#: kallithea/controllers/files.py:771
+#: kallithea/controllers/files.py:773
 #: kallithea/templates/changeset/changeset_range.html:9
 #: kallithea/templates/email_templates/pull_request.html:15
 #: kallithea/templates/pullrequests/pullrequest.html:97
 msgid "Changesets"
 msgstr ""
 
-#: kallithea/controllers/files.py:772 kallithea/controllers/pullrequests.py:176
-#: kallithea/model/scm.py:820 kallithea/templates/switch_to_list.html:3
+#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:175
+#: kallithea/model/scm.py:716 kallithea/templates/switch_to_list.html:3
 #: kallithea/templates/branches/branches.html:10
 msgid "Branches"
 msgstr ""
 
-#: kallithea/controllers/files.py:773 kallithea/controllers/pullrequests.py:177
-#: kallithea/model/scm.py:831 kallithea/templates/switch_to_list.html:25
+#: kallithea/controllers/files.py:775 kallithea/controllers/pullrequests.py:176
+#: kallithea/model/scm.py:727 kallithea/templates/switch_to_list.html:25
 #: kallithea/templates/tags/tags.html:10
 msgid "Tags"
 msgstr ""
@@ -249,7 +241,7 @@
 msgid "Groups"
 msgstr ""
 
-#: kallithea/controllers/home.py:89
+#: kallithea/controllers/home.py:94
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:106
 #: kallithea/templates/admin/repos/repo_add.html:12
 #: kallithea/templates/admin/repos/repo_add.html:16
@@ -257,23 +249,27 @@
 #: kallithea/templates/admin/users/user_edit_advanced.html:6
 #: kallithea/templates/base/base.html:60 kallithea/templates/base/base.html:77
 #: kallithea/templates/base/base.html:124
-#: kallithea/templates/base/base.html:390
-#: kallithea/templates/base/base.html:562
+#: kallithea/templates/base/base.html:479
+#: kallithea/templates/base/base.html:653
 msgid "Repositories"
 msgstr ""
 
-#: kallithea/controllers/home.py:130
+#: kallithea/controllers/home.py:139
 #: kallithea/templates/files/files_add.html:32
 #: kallithea/templates/files/files_delete.html:23
 #: kallithea/templates/files/files_edit.html:32
 msgid "Branch"
 msgstr ""
 
-#: kallithea/controllers/home.py:136
+#: kallithea/controllers/home.py:145 kallithea/templates/switch_to_list.html:16
+msgid "Closed Branches"
+msgstr ""
+
+#: kallithea/controllers/home.py:151
 msgid "Tag"
 msgstr ""
 
-#: kallithea/controllers/home.py:142
+#: kallithea/controllers/home.py:157
 msgid "Bookmark"
 msgstr ""
 
@@ -284,158 +280,163 @@
 msgstr ""
 
 #: kallithea/controllers/journal.py:115 kallithea/controllers/journal.py:157
-#: kallithea/templates/base/base.html:222
+#: kallithea/templates/base/base.html:306
 #: kallithea/templates/journal/journal.html:4
 #: kallithea/templates/journal/journal.html:12
 msgid "Journal"
 msgstr ""
 
-#: kallithea/controllers/login.py:151 kallithea/controllers/login.py:197
+#: kallithea/controllers/login.py:144 kallithea/controllers/login.py:190
 msgid "Bad captcha"
 msgstr ""
 
-#: kallithea/controllers/login.py:157
-msgid "You have successfully registered into Kallithea"
-msgstr ""
-
-#: kallithea/controllers/login.py:202
+#: kallithea/controllers/login.py:150
+msgid "You have successfully registered with %s"
+msgstr ""
+
+#: kallithea/controllers/login.py:195
 msgid "A password reset confirmation code has been sent"
 msgstr ""
 
-#: kallithea/controllers/login.py:251
+#: kallithea/controllers/login.py:244
 msgid "Invalid password reset token"
 msgstr ""
 
-#: kallithea/controllers/login.py:256
+#: kallithea/controllers/login.py:249
 #: kallithea/controllers/admin/my_account.py:167
 msgid "Successfully updated password"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:124
+#: kallithea/controllers/pullrequests.py:123
 #, fuzzy, python-format
 msgid "%s (closed)"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:152
+#: kallithea/controllers/pullrequests.py:151
 #: kallithea/templates/changeset/changeset.html:12
 #: kallithea/templates/email_templates/changeset_comment.html:17
 msgid "Changeset"
 msgstr ""
 
+#: kallithea/controllers/pullrequests.py:172
+msgid "Special"
+msgstr ""
+
 #: kallithea/controllers/pullrequests.py:173
-msgid "Special"
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:174
 msgid "Peer branches"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:175 kallithea/model/scm.py:826
+#: kallithea/controllers/pullrequests.py:174 kallithea/model/scm.py:722
 #: kallithea/templates/switch_to_list.html:38
 #: kallithea/templates/bookmarks/bookmarks.html:10
 msgid "Bookmarks"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:310
+#: kallithea/controllers/pullrequests.py:312
 #, python-format
 msgid "Error creating pull request: %s"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:356
-#: kallithea/controllers/pullrequests.py:503
+#: kallithea/controllers/pullrequests.py:358
+#: kallithea/controllers/pullrequests.py:505
 msgid "No description"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:363
+#: kallithea/controllers/pullrequests.py:365
 msgid "Successfully opened new pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:366
-#: kallithea/controllers/pullrequests.py:453
-#: kallithea/controllers/pullrequests.py:509
+#: kallithea/controllers/pullrequests.py:368
+#: kallithea/controllers/pullrequests.py:455
+#: kallithea/controllers/pullrequests.py:512
 #, python-format
 msgid "Invalid reviewer \"%s\" specified"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:369
-#: kallithea/controllers/pullrequests.py:456
+#: kallithea/controllers/pullrequests.py:371
+#: kallithea/controllers/pullrequests.py:458
 msgid "Error occurred while creating pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:401
+#: kallithea/controllers/pullrequests.py:403
 msgid "Missing changesets since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:408
+#: kallithea/controllers/pullrequests.py:410
 #, python-format
 msgid "New changesets on %s %s since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:415
+#: kallithea/controllers/pullrequests.py:417
 msgid "Ancestor didn't change - show diff since previous version:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:422
+#: kallithea/controllers/pullrequests.py:424
 #, python-format
 msgid ""
 "This pull request is based on another %s revision and there is no simple "
 "diff."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:424
+#: kallithea/controllers/pullrequests.py:426
 #, python-format
 msgid "No changes found on %s %s since previous version."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:462
+#: kallithea/controllers/pullrequests.py:464
 #, python-format
 msgid "Closed, replaced by %s ."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:470
+#: kallithea/controllers/pullrequests.py:472
 msgid "Pull request update created"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:513
+#: kallithea/controllers/pullrequests.py:516
 msgid "Pull request updated"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:528
+#: kallithea/controllers/pullrequests.py:531
 msgid "Successfully deleted pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:594
+#: kallithea/controllers/pullrequests.py:597
 #, python-format
 msgid "This pull request has already been merged to %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:596
+#: kallithea/controllers/pullrequests.py:599
 msgid "This pull request has been closed and can not be updated."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:614
-#, python-format
-msgid "This pull request can be updated with changes on %s:"
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:617
+#, python-format
+msgid "The following changes are available on %s:"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:621
 msgid "No changesets found for updating this pull request."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:625
+#: kallithea/controllers/pullrequests.py:629
 #, python-format
 msgid "Note: Branch %s has another head: %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:631
+#: kallithea/controllers/pullrequests.py:635
 msgid "Git pull requests don't support updates yet."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:722
-msgid "No permission to change pull request status"
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:727
+msgid "No permission to change pull request status"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:738
+#, python-format
+msgid "Successfully deleted pull request %s"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:748
 msgid "Closing."
 msgstr ""
 
@@ -451,12 +452,12 @@
 msgid "An error occurred during search operation."
 msgstr ""
 
-#: kallithea/controllers/summary.py:180
+#: kallithea/controllers/summary.py:181
 #: kallithea/templates/summary/summary.html:384
 msgid "No data ready yet"
 msgstr ""
 
-#: kallithea/controllers/summary.py:183
+#: kallithea/controllers/summary.py:184
 #: kallithea/templates/summary/summary.html:98
 msgid "Statistics are disabled for this repository"
 msgstr ""
@@ -477,64 +478,64 @@
 msgid "Error occurred during update of defaults"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/gists.py:58
 #: kallithea/controllers/admin/my_account.py:243
+#: kallithea/controllers/admin/users.py:284
+msgid "Forever"
+msgstr ""
+
+#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/my_account.py:244
 #: kallithea/controllers/admin/users.py:285
-msgid "Forever"
+msgid "5 minutes"
 msgstr ""
 
 #: kallithea/controllers/admin/gists.py:60
-#: kallithea/controllers/admin/my_account.py:244
+#: kallithea/controllers/admin/my_account.py:245
 #: kallithea/controllers/admin/users.py:286
-msgid "5 minutes"
+msgid "1 hour"
 msgstr ""
 
 #: kallithea/controllers/admin/gists.py:61
-#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/my_account.py:246
 #: kallithea/controllers/admin/users.py:287
-msgid "1 hour"
+msgid "1 day"
 msgstr ""
 
 #: kallithea/controllers/admin/gists.py:62
-#: kallithea/controllers/admin/my_account.py:246
+#: kallithea/controllers/admin/my_account.py:247
 #: kallithea/controllers/admin/users.py:288
-msgid "1 day"
-msgstr ""
-
-#: kallithea/controllers/admin/gists.py:63
-#: kallithea/controllers/admin/my_account.py:247
-#: kallithea/controllers/admin/users.py:289
 msgid "1 month"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:67
+#: kallithea/controllers/admin/gists.py:66
 #: kallithea/controllers/admin/my_account.py:249
-#: kallithea/controllers/admin/users.py:291
+#: kallithea/controllers/admin/users.py:290
 msgid "Lifetime"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:146
+#: kallithea/controllers/admin/gists.py:145
 msgid "Error occurred during gist creation"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:184
+#: kallithea/controllers/admin/gists.py:183
 #, python-format
 msgid "Deleted gist %s"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:233
+#: kallithea/controllers/admin/gists.py:232
 msgid "Unmodified"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:262
+#: kallithea/controllers/admin/gists.py:261
 msgid "Successfully updated gist content"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:267
+#: kallithea/controllers/admin/gists.py:266
 msgid "Successfully updated gist data"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:270
+#: kallithea/controllers/admin/gists.py:269
 #, python-format
 msgid "Error occurred during update of gist %s"
 msgstr ""
@@ -549,7 +550,7 @@
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:144
-#: kallithea/controllers/admin/users.py:202
+#: kallithea/controllers/admin/users.py:201
 #, python-format
 msgid "Error occurred during update of user %s"
 msgstr ""
@@ -559,33 +560,33 @@
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:220
-#: kallithea/controllers/admin/users.py:415
+#: kallithea/controllers/admin/users.py:414
 #, python-format
 msgid "Added email %s to user"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:226
-#: kallithea/controllers/admin/users.py:421
+#: kallithea/controllers/admin/users.py:420
 msgid "An error occurred during email saving"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:235
-#: kallithea/controllers/admin/users.py:433
+#: kallithea/controllers/admin/users.py:432
 msgid "Removed email from user"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:259
-#: kallithea/controllers/admin/users.py:308
+#: kallithea/controllers/admin/users.py:307
 msgid "API key successfully created"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:271
-#: kallithea/controllers/admin/users.py:321
+#: kallithea/controllers/admin/users.py:320
 msgid "API key successfully reset"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:275
-#: kallithea/controllers/admin/users.py:325
+#: kallithea/controllers/admin/users.py:324
 msgid "API key successfully deleted"
 msgstr ""
 
@@ -635,10 +636,10 @@
 #: kallithea/templates/admin/users/user_edit_profile.html:105
 #: kallithea/templates/admin/users/users.html:10
 #: kallithea/templates/admin/users/users.html:55
-#: kallithea/templates/base/base.html:252
-#: kallithea/templates/base/base.html:253
-#: kallithea/templates/base/base.html:259
-#: kallithea/templates/base/base.html:260
+#: kallithea/templates/base/base.html:336
+#: kallithea/templates/base/base.html:337
+#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:344
 #: kallithea/templates/base/perms_summary.html:17
 msgid "Admin"
 msgstr ""
@@ -669,7 +670,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1564
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1603
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1655
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1701
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1705
 msgid "Manual activation of external account"
 msgstr ""
 
@@ -681,7 +682,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1565
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1604
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1656
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1702
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1706
 msgid "Automatic activation of external account"
 msgstr ""
 
@@ -702,244 +703,244 @@
 msgid "Error occurred during update of permissions"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:188
+#: kallithea/controllers/admin/repo_groups.py:187
 #, python-format
 msgid "Error occurred during creation of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:193
+#: kallithea/controllers/admin/repo_groups.py:192
 #, python-format
 msgid "Created repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:250
+#: kallithea/controllers/admin/repo_groups.py:249
 #, python-format
 msgid "Updated repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:266
+#: kallithea/controllers/admin/repo_groups.py:265
 #, python-format
 msgid "Error occurred during update of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:284
+#: kallithea/controllers/admin/repo_groups.py:283
 #, python-format
 msgid "This group contains %s repositories and cannot be deleted"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:291
+#: kallithea/controllers/admin/repo_groups.py:290
 #, python-format
 msgid "This group contains %s subgroups and cannot be deleted"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:297
+#: kallithea/controllers/admin/repo_groups.py:296
 #, python-format
 msgid "Removed repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:302
+#: kallithea/controllers/admin/repo_groups.py:301
 #, python-format
 msgid "Error occurred during deletion of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:405
-#: kallithea/controllers/admin/repo_groups.py:440
+#: kallithea/controllers/admin/repo_groups.py:404
+#: kallithea/controllers/admin/repo_groups.py:439
 #: kallithea/controllers/admin/user_groups.py:340
 msgid "Cannot revoke permission for yourself as admin"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:420
+#: kallithea/controllers/admin/repo_groups.py:419
 msgid "Repository group permissions updated"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:457
-#: kallithea/controllers/admin/repos.py:398
+#: kallithea/controllers/admin/repo_groups.py:456
+#: kallithea/controllers/admin/repos.py:397
 #: kallithea/controllers/admin/user_groups.py:352
 msgid "An error occurred during revoking of permission"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:152
+#: kallithea/controllers/admin/repos.py:151
 #, python-format
 msgid "Error creating repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:213
+#: kallithea/controllers/admin/repos.py:212
 #, python-format
 msgid "Created repository %s from %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:222
+#: kallithea/controllers/admin/repos.py:221
 #, python-format
 msgid "Forked repository %s as %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:225
+#: kallithea/controllers/admin/repos.py:224
 #, python-format
 msgid "Created repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:262
+#: kallithea/controllers/admin/repos.py:261
 #, python-format
 msgid "Repository %s updated successfully"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:283
+#: kallithea/controllers/admin/repos.py:282
 #, python-format
 msgid "Error occurred during update of repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:310
+#: kallithea/controllers/admin/repos.py:309
 #, python-format
 msgid "Detached %s forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:313
+#: kallithea/controllers/admin/repos.py:312
 #, python-format
 msgid "Deleted %s forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:318
+#: kallithea/controllers/admin/repos.py:317
 #, python-format
 msgid "Deleted repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:321
+#: kallithea/controllers/admin/repos.py:320
 #, python-format
 msgid "Cannot delete repository %s which still has forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:326
+#: kallithea/controllers/admin/repos.py:325
 #, python-format
 msgid "An error occurred during deletion of %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:374
+#: kallithea/controllers/admin/repos.py:373
 msgid "Repository permissions updated"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:430
+#: kallithea/controllers/admin/repos.py:429
 msgid "An error occurred during creation of field"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:444
+#: kallithea/controllers/admin/repos.py:443
 msgid "An error occurred during removal of field"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:460
+#: kallithea/controllers/admin/repos.py:459
 msgid "-- Not a fork --"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:491
+#: kallithea/controllers/admin/repos.py:490
 msgid "Updated repository visibility in public journal"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:495
+#: kallithea/controllers/admin/repos.py:494
 msgid "An error occurred during setting this repository in public journal"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:512
+#: kallithea/controllers/admin/repos.py:511
 msgid "Nothing"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:514
+#: kallithea/controllers/admin/repos.py:513
 #, python-format
 msgid "Marked repository %s as fork of %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:521
+#: kallithea/controllers/admin/repos.py:520
 msgid "An error occurred during this operation"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:537
-#: kallithea/controllers/admin/repos.py:564
+#: kallithea/controllers/admin/repos.py:536
+#: kallithea/controllers/admin/repos.py:563
 #, fuzzy
 msgid "Repository has been locked"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:540
-#: kallithea/controllers/admin/repos.py:561
+#: kallithea/controllers/admin/repos.py:539
+#: kallithea/controllers/admin/repos.py:560
 #, fuzzy
 msgid "Repository has been unlocked"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:543
-#: kallithea/controllers/admin/repos.py:568
+#: kallithea/controllers/admin/repos.py:542
+#: kallithea/controllers/admin/repos.py:567
 msgid "An error occurred during unlocking"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:582
+#: kallithea/controllers/admin/repos.py:581
 msgid "Cache invalidation successful"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:586
+#: kallithea/controllers/admin/repos.py:585
 msgid "An error occurred during cache invalidation"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:601
+#: kallithea/controllers/admin/repos.py:600
 msgid "Pulled from remote location"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:604
+#: kallithea/controllers/admin/repos.py:603
 msgid "An error occurred during pull from remote location"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:637
+#: kallithea/controllers/admin/repos.py:636
 msgid "An error occurred during deletion of repository stats"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:170
+#: kallithea/controllers/admin/settings.py:141
 msgid "Updated VCS settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:174
+#: kallithea/controllers/admin/settings.py:145
 msgid ""
 "Unable to activate hgsubversion support. The \"hgsubversion\" library is "
 "missing"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:180
-#: kallithea/controllers/admin/settings.py:277
+#: kallithea/controllers/admin/settings.py:151
+#: kallithea/controllers/admin/settings.py:248
 msgid "Error occurred while updating application settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:216
+#: kallithea/controllers/admin/settings.py:187
 #, python-format
 msgid "Repositories successfully rescanned. Added: %s. Removed: %s."
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:273
+#: kallithea/controllers/admin/settings.py:244
 msgid "Updated application settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:330
+#: kallithea/controllers/admin/settings.py:301
 msgid "Updated visualisation settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:335
+#: kallithea/controllers/admin/settings.py:306
 msgid "Error occurred during updating visualisation settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:361
+#: kallithea/controllers/admin/settings.py:332
 msgid "Please enter email address"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:376
+#: kallithea/controllers/admin/settings.py:347
 msgid "Send email task created"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:407
+#: kallithea/controllers/admin/settings.py:378
 msgid "Added new hook"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:421
+#: kallithea/controllers/admin/settings.py:392
 msgid "Updated hooks"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:425
+#: kallithea/controllers/admin/settings.py:396
 msgid "Error occurred during hook creation"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:451
+#: kallithea/controllers/admin/settings.py:422
 msgid "Whoosh reindex task scheduled"
 msgstr ""
 
@@ -980,76 +981,80 @@
 msgstr ""
 
 #: kallithea/controllers/admin/user_groups.py:440
-#: kallithea/controllers/admin/users.py:384
+#: kallithea/controllers/admin/users.py:383
 msgid "Updated permissions"
 msgstr ""
 
 #: kallithea/controllers/admin/user_groups.py:444
-#: kallithea/controllers/admin/users.py:388
+#: kallithea/controllers/admin/users.py:387
 msgid "An error occurred during permissions saving"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:134
+#: kallithea/controllers/admin/users.py:133
 #, python-format
 msgid "Created user %s"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:149
+#: kallithea/controllers/admin/users.py:148
 #, python-format
 msgid "Error occurred during creation of user %s"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:182
+#: kallithea/controllers/admin/users.py:181
 msgid "User updated successfully"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:218
+#: kallithea/controllers/admin/users.py:217
 msgid "Successfully deleted user"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:223
+#: kallithea/controllers/admin/users.py:222
 msgid "An error occurred during deletion of user"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:236
+#: kallithea/controllers/admin/users.py:235
 msgid "The default user cannot be edited"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:463
+#: kallithea/controllers/admin/users.py:462
 #, python-format
 msgid "Added IP address %s to user whitelist"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:469
+#: kallithea/controllers/admin/users.py:468
 msgid "An error occurred while adding IP address"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:483
+#: kallithea/controllers/admin/users.py:482
 msgid "Removed IP address from user whitelist"
 msgstr ""
 
-#: kallithea/lib/auth.py:743
+#: kallithea/lib/auth.py:737
 #, python-format
 msgid "IP %s not allowed"
 msgstr ""
 
-#: kallithea/lib/auth.py:756
+#: kallithea/lib/auth.py:750
 msgid "Invalid API key"
 msgstr ""
 
-#: kallithea/lib/auth.py:812
+#: kallithea/lib/auth.py:768
+msgid "CSRF token leak has been detected - all form tokens have been expired"
+msgstr ""
+
+#: kallithea/lib/auth.py:813
 msgid "You need to be a registered user to perform this action"
 msgstr ""
 
-#: kallithea/lib/auth.py:844
+#: kallithea/lib/auth.py:843
 msgid "You need to be signed in to view this page"
 msgstr ""
 
-#: kallithea/lib/base.py:490
+#: kallithea/lib/base.py:493
 msgid "Repository not found in the filesystem"
 msgstr ""
 
-#: kallithea/lib/base.py:516 kallithea/lib/helpers.py:622
+#: kallithea/lib/base.py:519 kallithea/lib/helpers.py:623
 msgid "Changeset not found"
 msgstr ""
 
@@ -1065,125 +1070,125 @@
 msgid "No changes detected"
 msgstr ""
 
-#: kallithea/lib/helpers.py:609
+#: kallithea/lib/helpers.py:610
 #, python-format
 msgid "Deleted branch: %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:611
+#: kallithea/lib/helpers.py:612
 #, python-format
 msgid "Created tag: %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:671
+#: kallithea/lib/helpers.py:672
 #, python-format
 msgid "Show all combined changesets %s->%s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:677
+#: kallithea/lib/helpers.py:678
 msgid "Compare view"
 msgstr ""
 
-#: kallithea/lib/helpers.py:696
-msgid "and"
-msgstr ""
-
 #: kallithea/lib/helpers.py:697
+msgid "and"
+msgstr ""
+
+#: kallithea/lib/helpers.py:698
 #, python-format
 msgid "%s more"
 msgstr ""
 
-#: kallithea/lib/helpers.py:698 kallithea/templates/changelog/changelog.html:44
+#: kallithea/lib/helpers.py:699 kallithea/templates/changelog/changelog.html:44
 msgid "revisions"
 msgstr ""
 
-#: kallithea/lib/helpers.py:722
+#: kallithea/lib/helpers.py:723
 #, python-format
 msgid "Fork name %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:742
+#: kallithea/lib/helpers.py:743
 #, python-format
 msgid "Pull request %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:752
+#: kallithea/lib/helpers.py:753
 msgid "[deleted] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:754 kallithea/lib/helpers.py:766
+#: kallithea/lib/helpers.py:755 kallithea/lib/helpers.py:767
 msgid "[created] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:756
+#: kallithea/lib/helpers.py:757
 msgid "[created] repository as fork"
 msgstr ""
 
-#: kallithea/lib/helpers.py:758 kallithea/lib/helpers.py:768
+#: kallithea/lib/helpers.py:759 kallithea/lib/helpers.py:769
 msgid "[forked] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:760 kallithea/lib/helpers.py:770
+#: kallithea/lib/helpers.py:761 kallithea/lib/helpers.py:771
 msgid "[updated] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:762
+#: kallithea/lib/helpers.py:763
 msgid "[downloaded] archive from repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:764
+#: kallithea/lib/helpers.py:765
 msgid "[delete] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:772
+#: kallithea/lib/helpers.py:773
 msgid "[created] user"
 msgstr ""
 
-#: kallithea/lib/helpers.py:774
+#: kallithea/lib/helpers.py:775
 msgid "[updated] user"
 msgstr ""
 
-#: kallithea/lib/helpers.py:776
+#: kallithea/lib/helpers.py:777
 msgid "[created] user group"
 msgstr ""
 
-#: kallithea/lib/helpers.py:778
+#: kallithea/lib/helpers.py:779
 msgid "[updated] user group"
 msgstr ""
 
-#: kallithea/lib/helpers.py:780
+#: kallithea/lib/helpers.py:781
 msgid "[commented] on revision in repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:782
+#: kallithea/lib/helpers.py:783
 msgid "[commented] on pull request for"
 msgstr ""
 
-#: kallithea/lib/helpers.py:784
+#: kallithea/lib/helpers.py:785
 msgid "[closed] pull request for"
 msgstr ""
 
-#: kallithea/lib/helpers.py:786
+#: kallithea/lib/helpers.py:787
 msgid "[pushed] into"
 msgstr ""
 
-#: kallithea/lib/helpers.py:788
+#: kallithea/lib/helpers.py:789
 msgid "[committed via Kallithea] into repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:790
+#: kallithea/lib/helpers.py:791
 msgid "[pulled from remote] into repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:792
+#: kallithea/lib/helpers.py:793
 msgid "[pulled] from"
 msgstr ""
 
-#: kallithea/lib/helpers.py:794
+#: kallithea/lib/helpers.py:795
 msgid "[started following] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:796
+#: kallithea/lib/helpers.py:797
 msgid "[stopped following] repository"
 msgstr ""
 
@@ -1193,8 +1198,8 @@
 msgstr ""
 
 #: kallithea/lib/helpers.py:1128
-#: kallithea/templates/compare/compare_diff.html:65
-#: kallithea/templates/pullrequests/pullrequest_show.html:326
+#: kallithea/templates/compare/compare_diff.html:71
+#: kallithea/templates/pullrequests/pullrequest_show.html:337
 msgid "No files"
 msgstr ""
 
@@ -1218,7 +1223,7 @@
 msgid "chmod"
 msgstr ""
 
-#: kallithea/lib/helpers.py:1444
+#: kallithea/lib/helpers.py:1469
 #, python-format
 msgid ""
 "%s repository is not mapped to db perhaps it was created or renamed from "
@@ -1226,69 +1231,69 @@
 "repositories"
 msgstr ""
 
-#: kallithea/lib/utils2.py:415
+#: kallithea/lib/utils2.py:434
 #, python-format
 msgid "%d year"
 msgid_plural "%d years"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:416
+#: kallithea/lib/utils2.py:435
 #, python-format
 msgid "%d month"
 msgid_plural "%d months"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:417
+#: kallithea/lib/utils2.py:436
 #, python-format
 msgid "%d day"
 msgid_plural "%d days"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:418
+#: kallithea/lib/utils2.py:437
 #, python-format
 msgid "%d hour"
 msgid_plural "%d hours"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:419
+#: kallithea/lib/utils2.py:438
 #, python-format
 msgid "%d minute"
 msgid_plural "%d minutes"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:420
+#: kallithea/lib/utils2.py:439
 #, python-format
 msgid "%d second"
 msgid_plural "%d seconds"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/lib/utils2.py:436
+#: kallithea/lib/utils2.py:455
 #, python-format
 msgid "in %s"
 msgstr ""
 
-#: kallithea/lib/utils2.py:438
+#: kallithea/lib/utils2.py:457
 #, python-format
 msgid "%s ago"
 msgstr ""
 
-#: kallithea/lib/utils2.py:440
+#: kallithea/lib/utils2.py:459
 #, python-format
 msgid "in %s and %s"
 msgstr ""
 
-#: kallithea/lib/utils2.py:443
+#: kallithea/lib/utils2.py:462
 #, python-format
 msgid "%s and %s ago"
 msgstr ""
 
-#: kallithea/lib/utils2.py:446
+#: kallithea/lib/utils2.py:465
 msgid "just now"
 msgstr ""
 
@@ -1387,7 +1392,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1531
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1570
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1620
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1665
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1669
 msgid "Kallithea Administrator"
 msgstr ""
 
@@ -1498,7 +1503,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2063
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2102
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2155
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2229
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2237
 msgid "Approved"
 msgstr ""
 
@@ -1513,7 +1518,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2064
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2103
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2156
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2230
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2238
 msgid "Rejected"
 msgstr ""
 
@@ -1540,7 +1545,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1379
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1418
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1471
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1518
 msgid "top level"
 msgstr ""
 
@@ -1687,7 +1692,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1560
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1599
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1651
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1697
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1701
 msgid "Registration disabled"
 msgstr ""
 
@@ -1714,12 +1719,12 @@
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1645
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1691
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1695
 msgid "Repository creation enabled with write permission to a repository group"
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1646
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1692
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1696
 msgid "Repository creation disabled with write permission to a repository group"
 msgstr ""
 
@@ -1728,104 +1733,104 @@
 msgid "on line %s"
 msgstr ""
 
-#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:169
+#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:170
 msgid "[Mention]"
 msgstr ""
 
-#: kallithea/model/db.py:1667
+#: kallithea/model/db.py:1671
 msgid "Default user has no access to new repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1668
-msgid "Default user has read access to new repositories"
-msgstr ""
-
-#: kallithea/model/db.py:1669
-msgid "Default user has write access to new repositories"
-msgstr ""
-
-#: kallithea/model/db.py:1670
-msgid "Default user has admin access to new repositories"
-msgstr ""
-
 #: kallithea/model/db.py:1672
-msgid "Default user has no access to new repository groups"
+msgid "Default user has read access to new repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1673
-msgid "Default user has read access to new repository groups"
+msgid "Default user has write access to new repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1674
-msgid "Default user has write access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1675
-msgid "Default user has admin access to new repository groups"
+msgid "Default user has admin access to new repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1676
+msgid "Default user has no access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1677
-msgid "Default user has no access to new user groups"
+msgid "Default user has read access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1678
-msgid "Default user has read access to new user groups"
+msgid "Default user has write access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1679
-msgid "Default user has write access to new user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1680
-msgid "Default user has admin access to new user groups"
+msgid "Default user has admin access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1681
+msgid "Default user has no access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1682
-msgid "Only admins can create repository groups"
+msgid "Default user has read access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1683
-msgid "Non-admins can create repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1685
-msgid "Only admins can create user groups"
+msgid "Default user has write access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1684
+msgid "Default user has admin access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1686
-msgid "Non-admins can create user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1688
-msgid "Only admins can create top level repositories"
+msgid "Only admins can create repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1687
+msgid "Non-admins can create repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1689
+msgid "Only admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1690
+msgid "Non-admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1692
+msgid "Only admins can create top level repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1693
 msgid "Non-admins can create top level repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1694
-msgid "Only admins can fork repositories"
-msgstr ""
-
-#: kallithea/model/db.py:1695
-msgid "Non-admins can can fork repositories"
-msgstr ""
-
 #: kallithea/model/db.py:1698
-msgid "User registration with manual account activation"
+msgid "Only admins can fork repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1699
+msgid "Non-admins can fork repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1702
+msgid "User registration with manual account activation"
+msgstr ""
+
+#: kallithea/model/db.py:1703
 msgid "User registration with automatic account activation"
 msgstr ""
 
-#: kallithea/model/db.py:2228
+#: kallithea/model/db.py:2236
 #, fuzzy
 msgid "Not reviewed"
 msgstr ""
 
-#: kallithea/model/db.py:2231
+#: kallithea/model/db.py:2239
 #, fuzzy
 msgid "Under review"
 msgstr ""
@@ -1848,7 +1853,7 @@
 msgid "Enter %(min)i characters or more"
 msgstr ""
 
-#: kallithea/model/forms.py:160
+#: kallithea/model/forms.py:165
 msgid "Name must not contain only digits"
 msgstr ""
 
@@ -1941,7 +1946,7 @@
 msgid "%(user)s wants you to review pull request %(pr_nice_id)s: %(pr_title)s"
 msgstr ""
 
-#: kallithea/model/scm.py:812
+#: kallithea/model/scm.py:708
 msgid "latest tip"
 msgstr ""
 
@@ -1974,15 +1979,15 @@
 "owners or remove those user groups: %s"
 msgstr ""
 
-#: kallithea/model/user.py:360
+#: kallithea/model/user.py:368
 msgid "Password reset link"
 msgstr ""
 
-#: kallithea/model/user.py:408
+#: kallithea/model/user.py:418
 msgid "Password reset notification"
 msgstr ""
 
-#: kallithea/model/user.py:409
+#: kallithea/model/user.py:419
 #, python-format
 msgid ""
 "The password to your account %s has been changed using password reset "
@@ -1993,167 +1998,167 @@
 msgid "Value cannot be an empty list"
 msgstr ""
 
-#: kallithea/model/validators.py:95
+#: kallithea/model/validators.py:96
 #, python-format
 msgid "Username \"%(username)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:97
+#: kallithea/model/validators.py:98
 #, python-format
 msgid "Username \"%(username)s\" cannot be used"
 msgstr ""
 
-#: kallithea/model/validators.py:99
+#: kallithea/model/validators.py:100
 msgid ""
 "Username may only contain alphanumeric characters underscores, periods or"
 " dashes and must begin with an alphanumeric character or underscore"
 msgstr ""
 
-#: kallithea/model/validators.py:126
+#: kallithea/model/validators.py:127
 msgid "The input is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:133
+#: kallithea/model/validators.py:134
 #, python-format
 msgid "Username %(username)s is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:152
+#: kallithea/model/validators.py:154
 msgid "Invalid user group name"
 msgstr ""
 
-#: kallithea/model/validators.py:153
-#, python-format
-msgid "User group \"%(usergroup)s\" already exists"
-msgstr ""
-
 #: kallithea/model/validators.py:155
+#, python-format
+msgid "User group \"%(usergroup)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:157
 msgid ""
 "user group name may only contain alphanumeric characters underscores, "
 "periods or dashes and must begin with alphanumeric character"
 msgstr ""
 
-#: kallithea/model/validators.py:193
+#: kallithea/model/validators.py:197
 msgid "Cannot assign this group as parent"
 msgstr ""
 
-#: kallithea/model/validators.py:194
+#: kallithea/model/validators.py:198
 #, python-format
 msgid "Group \"%(group_name)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:196
+#: kallithea/model/validators.py:200
 #, python-format
 msgid "Repository with name \"%(group_name)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:254
+#: kallithea/model/validators.py:258
 msgid "Invalid characters (non-ascii) in password"
 msgstr ""
 
-#: kallithea/model/validators.py:269
+#: kallithea/model/validators.py:273
 msgid "Invalid old password"
 msgstr ""
 
-#: kallithea/model/validators.py:285
+#: kallithea/model/validators.py:289
 msgid "Passwords do not match"
 msgstr ""
 
-#: kallithea/model/validators.py:300
+#: kallithea/model/validators.py:304
 msgid "Invalid username or password"
 msgstr ""
 
-#: kallithea/model/validators.py:331
+#: kallithea/model/validators.py:335
 msgid "Token mismatch"
 msgstr ""
 
-#: kallithea/model/validators.py:345
+#: kallithea/model/validators.py:351
 #, python-format
 msgid "Repository name %(repo)s is not allowed"
 msgstr ""
 
-#: kallithea/model/validators.py:347
+#: kallithea/model/validators.py:353
 #, python-format
 msgid "Repository named %(repo)s already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:348
+#: kallithea/model/validators.py:354
 #, python-format
 msgid "Repository \"%(repo)s\" already exists in group \"%(group)s\""
 msgstr ""
 
-#: kallithea/model/validators.py:350
+#: kallithea/model/validators.py:356
 #, python-format
 msgid "Repository group with name \"%(repo)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:465
+#: kallithea/model/validators.py:470
 msgid "Invalid repository URL"
 msgstr ""
 
-#: kallithea/model/validators.py:466
+#: kallithea/model/validators.py:471
 msgid ""
 "Invalid repository URL. It must be a valid http, https, ssh, svn+http or "
 "svn+https URL"
 msgstr ""
 
-#: kallithea/model/validators.py:489
+#: kallithea/model/validators.py:496
 msgid "Fork has to be the same type as parent"
 msgstr ""
 
-#: kallithea/model/validators.py:504
+#: kallithea/model/validators.py:511
 msgid "You don't have permissions to create repository in this group"
 msgstr ""
 
-#: kallithea/model/validators.py:506
+#: kallithea/model/validators.py:513
 msgid "no permission to create repository in root location"
 msgstr ""
 
-#: kallithea/model/validators.py:556
+#: kallithea/model/validators.py:563
 msgid "You don't have permissions to create a group in this location"
 msgstr ""
 
-#: kallithea/model/validators.py:597
+#: kallithea/model/validators.py:604
 msgid "This username or user group name is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:690
+#: kallithea/model/validators.py:697
 msgid "This is not a valid path"
 msgstr ""
 
-#: kallithea/model/validators.py:705
+#: kallithea/model/validators.py:714
 msgid "This email address is already in use"
 msgstr ""
 
-#: kallithea/model/validators.py:725
+#: kallithea/model/validators.py:734
 #, python-format
 msgid "Email address \"%(email)s\" not found"
 msgstr ""
 
-#: kallithea/model/validators.py:762
+#: kallithea/model/validators.py:771
 msgid ""
 "The LDAP Login attribute of the CN must be specified - this is the name "
 "of the attribute that is equivalent to \"username\""
 msgstr ""
 
-#: kallithea/model/validators.py:774
+#: kallithea/model/validators.py:783
 msgid "Please enter a valid IPv4 or IPv6 address"
 msgstr ""
 
-#: kallithea/model/validators.py:775
+#: kallithea/model/validators.py:784
 #, python-format
 msgid "The network size (bits) must be within the range of 0-32 (not %(bits)r)"
 msgstr ""
 
-#: kallithea/model/validators.py:808
+#: kallithea/model/validators.py:817
 msgid "Key name can only consist of letters, underscore, dash or numbers"
 msgstr ""
 
-#: kallithea/model/validators.py:822
+#: kallithea/model/validators.py:831
 msgid "Filename cannot be inside a directory"
 msgstr ""
 
-#: kallithea/model/validators.py:838
+#: kallithea/model/validators.py:847
 #, python-format
 msgid "Plugins %(loaded)s and %(next_to_load)s both export the same name"
 msgstr ""
@@ -2280,7 +2285,7 @@
 #: kallithea/templates/admin/user_groups/user_groups.html:50
 #: kallithea/templates/pullrequests/pullrequest_data.html:16
 #: kallithea/templates/pullrequests/pullrequest_show.html:156
-#: kallithea/templates/pullrequests/pullrequest_show.html:233
+#: kallithea/templates/pullrequests/pullrequest_show.html:244
 #: kallithea/templates/summary/summary.html:134
 msgid "Owner"
 msgstr ""
@@ -2328,7 +2333,7 @@
 #: kallithea/templates/index_base.html:144
 #: kallithea/templates/admin/my_account/my_account_repos.html:61
 #: kallithea/templates/admin/my_account/my_account_watched.html:61
-#: kallithea/templates/base/base.html:140 kallithea/templates/base/root.html:47
+#: kallithea/templates/base/root.html:47
 #: kallithea/templates/bookmarks/bookmarks.html:83
 #: kallithea/templates/branches/branches.html:83
 #: kallithea/templates/journal/journal.html:202
@@ -2338,7 +2343,7 @@
 msgstr ""
 
 #: kallithea/templates/login.html:5 kallithea/templates/login.html:15
-#: kallithea/templates/base/base.html:326
+#: kallithea/templates/base/base.html:414
 msgid "Log In"
 msgstr ""
 
@@ -2353,7 +2358,7 @@
 #: kallithea/templates/admin/users/user_add.html:32
 #: kallithea/templates/admin/users/user_edit_profile.html:24
 #: kallithea/templates/admin/users/users.html:50
-#: kallithea/templates/base/base.html:302
+#: kallithea/templates/base/base.html:390
 #: kallithea/templates/pullrequests/pullrequest_show.html:166
 msgid "Username"
 msgstr ""
@@ -2361,7 +2366,7 @@
 #: kallithea/templates/login.html:33 kallithea/templates/register.html:33
 #: kallithea/templates/admin/my_account/my_account.html:37
 #: kallithea/templates/admin/users/user_add.html:41
-#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:399
 msgid "Password"
 msgstr ""
 
@@ -2373,7 +2378,7 @@
 msgid "Forgot your password ?"
 msgstr ""
 
-#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:322
+#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:410
 msgid "Don't have an account ?"
 msgstr ""
 
@@ -2494,10 +2499,6 @@
 msgid "There are no branches yet"
 msgstr ""
 
-#: kallithea/templates/switch_to_list.html:16
-msgid "Closed Branches"
-msgstr ""
-
 #: kallithea/templates/switch_to_list.html:32
 #: kallithea/templates/tags/tags_data.html:44
 msgid "There are no tags yet"
@@ -2724,12 +2725,12 @@
 msgid "Never"
 msgstr ""
 
-#: kallithea/templates/admin/gists/edit.html:145
+#: kallithea/templates/admin/gists/edit.html:146
 msgid "Update Gist"
 msgstr ""
 
-#: kallithea/templates/admin/gists/edit.html:146
-#: kallithea/templates/changeset/changeset_file_comment.html:81
+#: kallithea/templates/admin/gists/edit.html:147
+#: kallithea/templates/changeset/changeset_file_comment.html:105
 msgid "Cancel"
 msgstr ""
 
@@ -2752,7 +2753,7 @@
 
 #: kallithea/templates/admin/gists/index.html:37
 #: kallithea/templates/admin/gists/show.html:25
-#: kallithea/templates/base/base.html:237
+#: kallithea/templates/base/base.html:321
 msgid "Create New Gist"
 msgstr ""
 
@@ -2840,7 +2841,8 @@
 #: kallithea/templates/admin/settings/settings_hooks.html:36
 #: kallithea/templates/admin/users/user_edit_emails.html:19
 #: kallithea/templates/admin/users/user_edit_ips.html:22
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+#: kallithea/templates/changeset/changeset_file_comment.html:95
 #: kallithea/templates/data_table/_dt_elements.html:129
 #: kallithea/templates/data_table/_dt_elements.html:157
 #: kallithea/templates/data_table/_dt_elements.html:173
@@ -2860,8 +2862,6 @@
 #: kallithea/templates/base/perms_summary.html:43
 #: kallithea/templates/base/perms_summary.html:79
 #: kallithea/templates/base/perms_summary.html:81
-#: kallithea/templates/changeset/changeset_file_comment.html:83
-#: kallithea/templates/changeset/changeset_file_comment.html:192
 #: kallithea/templates/data_table/_dt_elements.html:122
 #: kallithea/templates/data_table/_dt_elements.html:123
 #: kallithea/templates/data_table/_dt_elements.html:150
@@ -2888,13 +2888,12 @@
 msgstr ""
 
 #: kallithea/templates/admin/gists/show.html:86
-#: kallithea/templates/files/files_source.html:73
 msgid "Show as raw"
 msgstr ""
 
 #: kallithea/templates/admin/my_account/my_account.html:5
 #: kallithea/templates/admin/my_account/my_account.html:9
-#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:431
 msgid "My Account"
 msgstr ""
 
@@ -3075,7 +3074,7 @@
 msgstr ""
 
 #: kallithea/templates/admin/notifications/notifications.html:26
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 msgid "Pull Requests"
 msgstr ""
 
@@ -3093,7 +3092,7 @@
 msgstr ""
 
 #: kallithea/templates/admin/notifications/show_notification.html:9
-#: kallithea/templates/base/base.html:342
+#: kallithea/templates/base/base.html:430
 msgid "Notifications"
 msgstr ""
 
@@ -3291,7 +3290,7 @@
 #: kallithea/templates/admin/repos/repo_edit.html:40
 #: kallithea/templates/admin/settings/settings.html:11
 #: kallithea/templates/admin/user_groups/user_group_edit.html:29
-#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:151
+#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:148
 #: kallithea/templates/data_table/_dt_elements.html:45
 #: kallithea/templates/data_table/_dt_elements.html:49
 msgid "Settings"
@@ -3554,6 +3553,11 @@
 msgid "Unlock Repository"
 msgstr ""
 
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:56
+#, python-format
+msgid "Locked by %s on %s"
+msgstr ""
+
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:60
 msgid "Confirm to lock repository."
 msgstr ""
@@ -3611,10 +3615,6 @@
 msgid "Invalidate Repository Cache"
 msgstr ""
 
-#: kallithea/templates/admin/repos/repo_edit_caches.html:4
-msgid "Confirm to invalidate repository cache."
-msgstr ""
-
 #: kallithea/templates/admin/repos/repo_edit_caches.html:7
 msgid ""
 "Manually invalidate cache for this repository. On first access, the "
@@ -4345,21 +4345,17 @@
 msgid "Files"
 msgstr ""
 
-#: kallithea/templates/base/base.html:138
-msgid "Switch To"
-msgstr ""
-
-#: kallithea/templates/base/base.html:145
-#: kallithea/templates/base/base.html:147
+#: kallithea/templates/base/base.html:142
+#: kallithea/templates/base/base.html:144
 msgid "Options"
 msgstr ""
 
-#: kallithea/templates/base/base.html:155
+#: kallithea/templates/base/base.html:152
 #: kallithea/templates/forks/forks_data.html:21
 msgid "Compare Fork"
 msgstr ""
 
-#: kallithea/templates/base/base.html:157
+#: kallithea/templates/base/base.html:154
 #: kallithea/templates/bookmarks/bookmarks.html:56
 #: kallithea/templates/bookmarks/bookmarks_data.html:13
 #: kallithea/templates/branches/branches.html:56
@@ -4369,111 +4365,116 @@
 msgid "Compare"
 msgstr ""
 
-#: kallithea/templates/base/base.html:159
-#: kallithea/templates/base/base.html:247
+#: kallithea/templates/base/base.html:156
+#: kallithea/templates/base/base.html:331
 #: kallithea/templates/search/search.html:14
 #: kallithea/templates/search/search.html:54
 msgid "Search"
 msgstr ""
 
-#: kallithea/templates/base/base.html:163
+#: kallithea/templates/base/base.html:160
 msgid "Unlock"
 msgstr ""
 
-#: kallithea/templates/base/base.html:165
+#: kallithea/templates/base/base.html:162
 msgid "Lock"
 msgstr ""
 
-#: kallithea/templates/base/base.html:173
+#: kallithea/templates/base/base.html:170
 msgid "Follow"
 msgstr ""
 
+#: kallithea/templates/base/base.html:171
+msgid "Unfollow"
+msgstr ""
+
 #: kallithea/templates/base/base.html:174
-msgid "Unfollow"
-msgstr ""
-
-#: kallithea/templates/base/base.html:177
 #: kallithea/templates/data_table/_dt_elements.html:37
 #: kallithea/templates/data_table/_dt_elements.html:41
 #: kallithea/templates/forks/fork.html:9
 msgid "Fork"
 msgstr ""
 
-#: kallithea/templates/base/base.html:178
+#: kallithea/templates/base/base.html:175
 #: kallithea/templates/pullrequests/pullrequest.html:88
 msgid "Create Pull Request"
 msgstr ""
 
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 #, python-format
 msgid "Show Pull Requests for %s"
 msgstr ""
 
-#: kallithea/templates/base/base.html:221
+#: kallithea/templates/base/base.html:193
+msgid "Switch To"
+msgstr ""
+
+#: kallithea/templates/base/base.html:203
+#: kallithea/templates/base/base.html:485
+msgid "No matches found"
+msgstr ""
+
+#: kallithea/templates/base/base.html:305
 msgid "Show recent activity"
 msgstr ""
 
-#: kallithea/templates/base/base.html:227
-#: kallithea/templates/base/base.html:228
+#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:312
 msgid "Public journal"
 msgstr ""
 
-#: kallithea/templates/base/base.html:233
+#: kallithea/templates/base/base.html:317
 msgid "Show public gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:234
+#: kallithea/templates/base/base.html:318
 msgid "Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:238
+#: kallithea/templates/base/base.html:322
 msgid "All Public Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:240
+#: kallithea/templates/base/base.html:324
 msgid "My Public Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:241
+#: kallithea/templates/base/base.html:325
 msgid "My Private Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:246
+#: kallithea/templates/base/base.html:330
 msgid "Search in repositories"
 msgstr ""
 
-#: kallithea/templates/base/base.html:269
-#: kallithea/templates/base/base.html:270
+#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:354
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:6
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:10
 msgid "My Pull Requests"
 msgstr ""
 
-#: kallithea/templates/base/base.html:289
+#: kallithea/templates/base/base.html:377
 msgid "Not Logged In"
 msgstr ""
 
-#: kallithea/templates/base/base.html:296
+#: kallithea/templates/base/base.html:384
 msgid "Login to Your Account"
 msgstr ""
 
-#: kallithea/templates/base/base.html:319
+#: kallithea/templates/base/base.html:407
 msgid "Forgot password ?"
 msgstr ""
 
-#: kallithea/templates/base/base.html:346
+#: kallithea/templates/base/base.html:434
 msgid "Log Out"
 msgstr ""
 
-#: kallithea/templates/base/base.html:395
-msgid "No matches found"
-msgstr ""
-
-#: kallithea/templates/base/base.html:524
+#: kallithea/templates/base/base.html:615
 msgid "Keyboard shortcuts"
 msgstr ""
 
-#: kallithea/templates/base/base.html:533
+#: kallithea/templates/base/base.html:624
 msgid "Site-wide shortcuts"
 msgstr ""
 
@@ -4575,7 +4576,6 @@
 
 #: kallithea/templates/base/root.html:31
 #, fuzzy
-#| msgid "on pull request"
 msgid "Open New Pull Request from {0}"
 msgstr "Statuswijziging -> %s"
 
@@ -4585,7 +4585,6 @@
 
 #: kallithea/templates/base/root.html:33
 #, fuzzy
-#| msgid "Show Selected Changeset __S"
 msgid "Show Selected Changesets {0} &rarr; {1}"
 msgstr "Selecteer de changeset"
 
@@ -4595,6 +4594,7 @@
 
 #: kallithea/templates/base/root.html:35
 #: kallithea/templates/changeset/diff_block.html:8
+#: kallithea/templates/changeset/diff_block.html:21
 msgid "Collapse Diff"
 msgstr ""
 
@@ -4704,51 +4704,54 @@
 #: kallithea/templates/changelog/changelog_summary_data.html:20
 #, python-format
 msgid ""
-"Changeset status: %s\n"
+"Changeset status: %s by %s\n"
 "Click to open associated pull request %s"
 msgstr ""
 
 #: kallithea/templates/changelog/changelog.html:96
-#: kallithea/templates/compare/compare_cs.html:24
-#, python-format
-msgid "Changeset status: %s"
-msgstr ""
-
-#: kallithea/templates/changelog/changelog.html:115
+#: kallithea/templates/changelog/changelog_summary_data.html:24
+#, fuzzy, python-format
+#| msgid "Set changeset status"
+msgid "Changeset status: %s by %s"
+msgstr "Selecteer de changeset"
+
+#: kallithea/templates/changelog/changelog.html:116
 #: kallithea/templates/compare/compare_cs.html:63
 msgid "Expand commit message"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:124
+#: kallithea/templates/changelog/changelog.html:125
 #: kallithea/templates/compare/compare_cs.html:30
 msgid "Changeset has comments"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:134
-#: kallithea/templates/changelog/changelog_summary_data.html:54
+#: kallithea/templates/changelog/changelog.html:135
+#: kallithea/templates/changelog/changelog_summary_data.html:57
 #: kallithea/templates/changeset/changeset.html:94
 #: kallithea/templates/changeset/changeset_range.html:92
 #, python-format
 msgid "Bookmark %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:140
-#: kallithea/templates/changelog/changelog_summary_data.html:60
+#: kallithea/templates/changelog/changelog.html:141
+#: kallithea/templates/changelog/changelog_summary_data.html:63
 #: kallithea/templates/changeset/changeset.html:101
 #: kallithea/templates/changeset/changeset_range.html:98
+#: kallithea/templates/compare/compare_cs.html:69
+#: kallithea/templates/pullrequests/pullrequest_show.html:203
 #, python-format
 msgid "Tag %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:145
-#: kallithea/templates/changelog/changelog_summary_data.html:65
+#: kallithea/templates/changelog/changelog.html:146
+#: kallithea/templates/changelog/changelog_summary_data.html:68
 #: kallithea/templates/changeset/changeset.html:106
 #: kallithea/templates/changeset/changeset_range.html:102
 #, python-format
 msgid "Branch %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:310
+#: kallithea/templates/changelog/changelog.html:311
 msgid "There are no changes yet"
 msgstr ""
 
@@ -4764,7 +4767,7 @@
 
 #: kallithea/templates/changelog/changelog_details.html:6
 #: kallithea/templates/changeset/changeset.html:79
-#: kallithea/templates/changeset/diff_block.html:79
+#: kallithea/templates/changeset/diff_block.html:47
 msgid "Added"
 msgstr ""
 
@@ -4794,21 +4797,21 @@
 msgid "Refs"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:81
+#: kallithea/templates/changelog/changelog_summary_data.html:84
 msgid "Add or upload files directly via Kallithea"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:84
+#: kallithea/templates/changelog/changelog_summary_data.html:87
 #: kallithea/templates/files/files_add.html:21
 #: kallithea/templates/files/files_ypjax.html:9
 msgid "Add New File"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:90
+#: kallithea/templates/changelog/changelog_summary_data.html:93
 msgid "Push new repository"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:98
+#: kallithea/templates/changelog/changelog_summary_data.html:101
 msgid "Existing repository?"
 msgstr ""
 
@@ -4826,13 +4829,13 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:50
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #: kallithea/templates/changeset/changeset_range.html:48
 msgid "Changeset status"
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:54
-#: kallithea/templates/changeset/diff_block.html:27
+#: kallithea/templates/changeset/diff_block.html:72
 #: kallithea/templates/files/diff_2way.html:49
 msgid "Raw diff"
 msgstr ""
@@ -4842,7 +4845,7 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:60
-#: kallithea/templates/changeset/diff_block.html:30
+#: kallithea/templates/changeset/diff_block.html:75
 #: kallithea/templates/files/diff_2way.html:52
 msgid "Download diff"
 msgstr ""
@@ -4869,8 +4872,8 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:166
-#: kallithea/templates/compare/compare_diff.html:54
-#: kallithea/templates/pullrequests/pullrequest_show.html:318
+#: kallithea/templates/compare/compare_diff.html:60
+#: kallithea/templates/pullrequests/pullrequest_show.html:329
 #, python-format
 msgid "%s file changed"
 msgid_plural "%s files changed"
@@ -4878,8 +4881,8 @@
 msgstr[1] ""
 
 #: kallithea/templates/changeset/changeset.html:168
-#: kallithea/templates/compare/compare_diff.html:56
-#: kallithea/templates/pullrequests/pullrequest_show.html:320
+#: kallithea/templates/compare/compare_diff.html:62
+#: kallithea/templates/pullrequests/pullrequest_show.html:331
 #, python-format
 msgid "%s file changed with %s insertions and %s deletions"
 msgid_plural "%s files changed with %s insertions and %s deletions"
@@ -4888,13 +4891,13 @@
 
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Show full diff anyway"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset.html:247
-#: kallithea/templates/changeset/changeset.html:284
+#: kallithea/templates/changeset/changeset.html:231
+#: kallithea/templates/changeset/changeset.html:268
 msgid "No revisions"
 msgstr ""
 
@@ -4912,104 +4915,90 @@
 msgid "on this changeset"
 msgstr "Selecteer de changeset"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
 #, fuzzy
 msgid "Delete comment?"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #, fuzzy
 msgid "Status change"
 msgstr "Statuswijziging -> %s"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:59
-msgid "Commenting on line {1}."
+msgid "Commenting on line."
 msgstr ""
 
 #: kallithea/templates/changeset/changeset_file_comment.html:60
-#: kallithea/templates/changeset/changeset_file_comment.html:148
-#, python-format
-msgid "Comments parsed using %s syntax with %s support."
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:62
-msgid "Use @username inside this text to notify another user"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:72
-#: kallithea/templates/changeset/changeset_file_comment.html:184
-msgid "Comment preview"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:77
+msgid ""
+"Comments are in plain text. Use @username inside this text to notify "
+"another user."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:67
+#, fuzzy
+msgid "Set changeset status"
+msgstr "Selecteer de changeset"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:69
+msgid "Vote for pull request status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:75
+msgid "No change"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:88
+#, fuzzy
+msgid "Finish pull request"
+msgstr "Statuswijziging -> %s"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:91
+#, fuzzy
+msgid "Close"
+msgstr "(gesloten)"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:103
 msgid "Submitting ..."
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:80
-#: kallithea/templates/changeset/changeset_file_comment.html:190
+#: kallithea/templates/changeset/changeset_file_comment.html:104
 msgid "Comment"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:82
-#: kallithea/templates/changeset/changeset_file_comment.html:191
-msgid "Preview"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "You need to be logged in to comment."
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "Login now"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:94
+#: kallithea/templates/changeset/changeset_file_comment.html:116
 msgid "Hide"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:106
+#: kallithea/templates/changeset/changeset_file_comment.html:128
 #, python-format
 msgid "%d comment"
 msgid_plural "%d comments"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:107
+#: kallithea/templates/changeset/changeset_file_comment.html:129
 #, fuzzy, python-format
 msgid "%d inline"
 msgid_plural "%d inline"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:108
+#: kallithea/templates/changeset/changeset_file_comment.html:130
 #, python-format
 msgid "%d general"
 msgid_plural "%d general"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:150
-msgid "Use @username inside this text to notify another user."
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:157
-msgid "Vote for pull request status"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:159
-#, fuzzy
-msgid "Set changeset status"
-msgstr "Selecteer de changeset"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:163
-msgid "No change"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:176
-#, fuzzy
-msgid "Close"
-msgstr "(gesloten)"
-
 #: kallithea/templates/changeset/changeset_range.html:5
 #, python-format
 msgid "%s Changesets"
@@ -5019,29 +5008,28 @@
 msgid "Files affected"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:21
+#: kallithea/templates/changeset/diff_block.html:54
+msgid "Deleted"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:57
+msgid "Renamed"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:66
 #: kallithea/templates/files/diff_2way.html:43
 msgid "Show full diff for this file"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:24
-#: kallithea/templates/changeset/diff_block.html:98
+#: kallithea/templates/changeset/diff_block.html:69
 #: kallithea/templates/files/diff_2way.html:46
 msgid "Show full side-by-side diff for this file"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:38
+#: kallithea/templates/changeset/diff_block.html:83
 msgid "Show inline comments"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:86
-msgid "Deleted"
-msgstr ""
-
-#: kallithea/templates/changeset/diff_block.html:89
-msgid "Renamed"
-msgstr ""
-
 #: kallithea/templates/compare/compare_cs.html:4
 msgid "No changesets"
 msgstr ""
@@ -5050,6 +5038,11 @@
 msgid "Ancestor"
 msgstr ""
 
+#: kallithea/templates/compare/compare_cs.html:24
+#, python-format
+msgid "Changeset status: %s"
+msgstr ""
+
 #: kallithea/templates/compare/compare_cs.html:44
 msgid "First (oldest) changeset in this list"
 msgstr ""
@@ -5062,29 +5055,29 @@
 msgid "Position in this list of changesets"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:76
+#: kallithea/templates/compare/compare_cs.html:85
 msgid "Show merge diff"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:86
-#: kallithea/templates/pullrequests/pullrequest_show.html:310
+#: kallithea/templates/compare/compare_cs.html:95
+#: kallithea/templates/pullrequests/pullrequest_show.html:321
 msgid "Common ancestor"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:90
-msgid "No common ancestor found - repositories are unrelated"
-msgstr ""
-
-#: kallithea/templates/compare/compare_cs.html:98
-msgid "is"
-msgstr ""
-
 #: kallithea/templates/compare/compare_cs.html:99
+msgid "No common ancestor found - repositories are unrelated"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:107
+msgid "is"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:108
 #, fuzzy, python-format
 msgid "%s changesets"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:100
+#: kallithea/templates/compare/compare_cs.html:109
 msgid "behind"
 msgstr ""
 
@@ -5095,28 +5088,28 @@
 msgstr ""
 
 #: kallithea/templates/compare/compare_diff.html:13
-#: kallithea/templates/compare/compare_diff.html:35
+#: kallithea/templates/compare/compare_diff.html:41
 msgid "Compare Revisions"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:33
+#: kallithea/templates/compare/compare_diff.html:39
 msgid "Swap"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:42
+#: kallithea/templates/compare/compare_diff.html:48
 msgid "Compare revisions, branches, bookmarks, or tags."
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:47
-#: kallithea/templates/pullrequests/pullrequest_show.html:305
+#: kallithea/templates/compare/compare_diff.html:53
+#: kallithea/templates/pullrequests/pullrequest_show.html:316
 #, python-format
 msgid "Showing %s commit"
 msgid_plural "Showing %s commits"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
 msgid "Show full diff"
 msgstr ""
 
@@ -5175,17 +5168,23 @@
 msgid "We have received a request to reset the password for your account."
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:7
-msgid "To set a new password, click the following link"
+#: kallithea/templates/email_templates/password_reset.html:8
+msgid ""
+"This account is however managed outside this system and the password "
+"cannot be changed here."
 msgstr ""
 
 #: kallithea/templates/email_templates/password_reset.html:10
+msgid "To set a new password, click the following link"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:13
 msgid ""
 "Should you not be able to use the link above, please type the following "
 "code into the password reset form"
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:12
+#: kallithea/templates/email_templates/password_reset.html:16
 msgid ""
 "If it weren't you who requested the password reset, just disregard this "
 "message."
@@ -5268,7 +5267,7 @@
 msgstr ""
 
 #: kallithea/templates/files/files_add.html:53
-msgid "New file mode"
+msgid "New file type"
 msgstr ""
 
 #: kallithea/templates/files/files_add.html:64
@@ -5400,8 +5399,16 @@
 msgid "Binary file (%s)"
 msgstr ""
 
-#: kallithea/templates/files/files_source.html:73
-msgid "File is too big to display"
+#: kallithea/templates/files/files_source.html:74
+msgid "File is too big to display."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:76
+msgid "Show full annotation anyway."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:78
+msgid "Show as raw."
 msgstr ""
 
 #: kallithea/templates/files/files_ypjax.html:5
@@ -5664,42 +5671,48 @@
 msgid "Current revision - no change"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:213
+#: kallithea/templates/pullrequests/pullrequest_show.html:215
+msgid ""
+"Pull requests do not change once created. Select a revision and save to "
+"replace this pull request with a new one."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:224
 msgid "Pull Request Reviewers"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:238
+#: kallithea/templates/pullrequests/pullrequest_show.html:249
 #, fuzzy
 msgid "Remove reviewer"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:250
-msgid "Type name of reviewer to add"
-msgstr ""
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:258
-#, fuzzy
-msgid "Potential Reviewers"
-msgstr ""
-
 #: kallithea/templates/pullrequests/pullrequest_show.html:261
+msgid "Type name of reviewer to add"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:269
+#, fuzzy
+msgid "Potential Reviewers"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:272
 msgid "Click to add the repository owner as reviewer:"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:284
+#: kallithea/templates/pullrequests/pullrequest_show.html:295
 msgid "Save Changes"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:285
-msgid "Save as New Pull Request"
-msgstr ""
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:286
+#: kallithea/templates/pullrequests/pullrequest_show.html:296
+msgid "Save Updates as New Pull Request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:297
 #, fuzzy
 msgid "Cancel Changes"
 msgstr "Selecteer de changeset"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#: kallithea/templates/pullrequests/pullrequest_show.html:307
 msgid "Pull Request Content"
 msgstr ""
 
@@ -5709,9 +5722,9 @@
 msgstr ""
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:11
-#, python-format
-msgid "Pull Requests from %s'"
-msgstr ""
+#, fuzzy, python-format
+msgid "Pull Requests from '%s'"
+msgstr "Statuswijziging -> %s"
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:13
 #, python-format
@@ -6281,39 +6294,12 @@
 #~ msgid "Your password reset link was sent"
 #~ msgstr ""
 
-#~ msgid ""
-#~ "Your password reset was successful, new"
-#~ " password has been sent to your "
-#~ "email"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " changeset %(short_id)s on %(branch)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Added by %(pr_username)s] %(repo_name)s pull"
-#~ " request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " pull request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
 #~ msgid "Your new password"
 #~ msgstr ""
 
 #~ msgid "Your new Kallithea password:%s"
 #~ msgstr ""
 
-#~ msgid ""
-#~ "Password reset link will be sent "
-#~ "to the email address matching your "
-#~ "username."
-#~ msgstr ""
-
 #~ msgid "Open New Pull Request for Selected Changesets"
 #~ msgstr ""
 
@@ -6332,3 +6318,53 @@
 #~ msgid "Created by"
 #~ msgstr ""
 
+#~ msgid "You can only delete files with revision being a valid branch "
+#~ msgstr ""
+
+#~ msgid "You can only edit files with revision being a valid branch "
+#~ msgstr ""
+
+#~ msgid "This pull request can be updated with changes on %s:"
+#~ msgstr ""
+
+#~ msgid "Non-admins can can fork repositories"
+#~ msgstr ""
+
+#~ msgid "Confirm to invalidate repository cache."
+#~ msgstr ""
+
+#~ msgid "Commenting on line {1}."
+#~ msgstr ""
+
+#~ msgid "Comments parsed using %s syntax with %s support."
+#~ msgstr ""
+
+#~ msgid "Use @username inside this text to notify another user"
+#~ msgstr ""
+
+#~ msgid "Comment preview"
+#~ msgstr ""
+
+#~ msgid "Preview"
+#~ msgstr ""
+
+#~ msgid "Use @username inside this text to notify another user."
+#~ msgstr ""
+
+#~ msgid "New file mode"
+#~ msgstr ""
+
+#~ msgid "File is too big to display"
+#~ msgstr ""
+
+#~ msgid "Save as New Pull Request"
+#~ msgstr ""
+
+#~ msgid "Pull Requests from %s'"
+#~ msgstr ""
+
+#~ msgid ""
+#~ "Changeset status: %s\n"
+#~ "Click to open associated pull request %s"
+#~ msgstr ""
+
--- a/kallithea/i18n/pl/LC_MESSAGES/kallithea.po	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/i18n/pl/LC_MESSAGES/kallithea.po	Fri Nov 18 01:11:13 2016 +0100
@@ -11,7 +11,7 @@
 msgstr ""
 "Project-Id-Version: Kallithea 0.3\n"
 "Report-Msgid-Bugs-To: translations@kallithea-scm.org\n"
-"POT-Creation-Date: 2015-09-08 10:34+0200\n"
+"POT-Creation-Date: 2016-03-14 16:51+0100\n"
 "PO-Revision-Date: 2015-04-04 09:08+0200\n"
 "Last-Translator: Andrew Shadura <andrew@shadura.me>\n"
 "Language-Team: Polish "
@@ -24,12 +24,12 @@
 "|| n%100>=20) ? 1 : 2;\n"
 "X-Generator: Weblate 2.3-dev\n"
 
-#: kallithea/controllers/changelog.py:86
-#: kallithea/controllers/pullrequests.py:238 kallithea/lib/base.py:512
+#: kallithea/controllers/changelog.py:85
+#: kallithea/controllers/pullrequests.py:240 kallithea/lib/base.py:515
 msgid "There are no changesets yet"
 msgstr "Brak zestawienia zmian"
 
-#: kallithea/controllers/changelog.py:166
+#: kallithea/controllers/changelog.py:164
 #: kallithea/controllers/admin/permissions.py:61
 #: kallithea/controllers/admin/permissions.py:65
 #: kallithea/controllers/admin/permissions.py:69
@@ -41,37 +41,29 @@
 msgid "None"
 msgstr "Brak"
 
-#: kallithea/controllers/changelog.py:169 kallithea/controllers/files.py:196
+#: kallithea/controllers/changelog.py:167 kallithea/controllers/files.py:198
 msgid "(closed)"
 msgstr "(zamknięty)"
 
-#: kallithea/controllers/changeset.py:89
+#: kallithea/controllers/changeset.py:88
 msgid "Show whitespace"
 msgstr "pokazuj spacje"
 
-#: kallithea/controllers/changeset.py:96 kallithea/controllers/changeset.py:103
+#: kallithea/controllers/changeset.py:95 kallithea/controllers/changeset.py:102
 #: kallithea/templates/files/diff_2way.html:55
 msgid "Ignore whitespace"
 msgstr "Ignoruj pokazywanie spacji"
 
-#: kallithea/controllers/changeset.py:169
+#: kallithea/controllers/changeset.py:168
 #, python-format
 msgid "Increase diff context to %(num)s lines"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:212 kallithea/controllers/files.py:96
-#: kallithea/controllers/files.py:116 kallithea/controllers/files.py:742
+#: kallithea/controllers/changeset.py:233 kallithea/controllers/files.py:97
+#: kallithea/controllers/files.py:117 kallithea/controllers/files.py:744
 msgid "Such revision does not exist for this repository"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:383
-msgid ""
-"Changing status on a changeset associated with a closed pull request is "
-"not allowed"
-msgstr ""
-"Zmiana statusu na grupy zmian powiązania łączy zamkniętego wniosku jest "
-"niedozwolona"
-
 #: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:41
 msgid "Select changeset"
 msgstr "Wybrane zmiany"
@@ -128,10 +120,10 @@
 #: kallithea/controllers/feed.py:87
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Changeset was too big and was cut off..."
 msgstr "Lista zmian była zbyt duża i została ucięta..."
 
@@ -140,111 +132,113 @@
 msgid "%s committed on %s"
 msgstr "%s zakomitowal w %s"
 
-#: kallithea/controllers/files.py:91
+#: kallithea/controllers/files.py:92
 msgid "Click here to add new file"
 msgstr "Kliknij tutaj, by dodać nowy plik"
 
-#: kallithea/controllers/files.py:92
+#: kallithea/controllers/files.py:93
 #, python-format
 msgid "There are no files yet. %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:193
+#: kallithea/controllers/files.py:195
 #, fuzzy, python-format
 msgid "%s at %s"
 msgstr "w %s i %s"
 
-#: kallithea/controllers/files.py:305 kallithea/controllers/files.py:365
-#: kallithea/controllers/files.py:432
+#: kallithea/controllers/files.py:307 kallithea/controllers/files.py:367
+#: kallithea/controllers/files.py:434
 #, python-format
 msgid "This repository has been locked by %s on %s"
 msgstr "Repozytorium zostało zablokowane przez %s na %s"
 
-#: kallithea/controllers/files.py:317
-msgid "You can only delete files with revision being a valid branch "
-msgstr ""
-
-#: kallithea/controllers/files.py:328
+#: kallithea/controllers/files.py:319
+#, fuzzy
+msgid "You can only delete files with revision being a valid branch"
+msgstr "Można tylko edytować pliki z rewizji obecnej gałęzi "
+
+#: kallithea/controllers/files.py:330
 #, python-format
 msgid "Deleted file %s via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:350
+#: kallithea/controllers/files.py:352
 #, python-format
 msgid "Successfully deleted file %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:354 kallithea/controllers/files.py:420
-#: kallithea/controllers/files.py:501
+#: kallithea/controllers/files.py:356 kallithea/controllers/files.py:422
+#: kallithea/controllers/files.py:503
 msgid "Error occurred during commit"
 msgstr "Wystąpił błąd w trakcie zatwierdzania"
 
-#: kallithea/controllers/files.py:377
-msgid "You can only edit files with revision being a valid branch "
+#: kallithea/controllers/files.py:379
+#, fuzzy
+msgid "You can only edit files with revision being a valid branch"
 msgstr "Można tylko edytować pliki z rewizji obecnej gałęzi "
 
-#: kallithea/controllers/files.py:391
+#: kallithea/controllers/files.py:393
 #, python-format
 msgid "Edited file %s via Kallithea"
 msgstr "Edytowanie %s w Kallithea"
 
-#: kallithea/controllers/files.py:407
+#: kallithea/controllers/files.py:409
 msgid "No changes"
 msgstr "Bez zmian"
 
-#: kallithea/controllers/files.py:416 kallithea/controllers/files.py:490
+#: kallithea/controllers/files.py:418 kallithea/controllers/files.py:492
 #, python-format
 msgid "Successfully committed to %s"
 msgstr "Committ wykonany do %s"
 
-#: kallithea/controllers/files.py:443
+#: kallithea/controllers/files.py:445
 msgid "Added file via Kallithea"
 msgstr "Dodano %s poprzez Kallithea"
 
-#: kallithea/controllers/files.py:464
+#: kallithea/controllers/files.py:466
 msgid "No content"
 msgstr "Brak treści"
 
-#: kallithea/controllers/files.py:468
+#: kallithea/controllers/files.py:470
 msgid "No filename"
 msgstr "Brak nazwy pliku"
 
-#: kallithea/controllers/files.py:493
+#: kallithea/controllers/files.py:495
 msgid "Location must be relative path and must not contain .. in path"
 msgstr "Lokalizacja musi być ścieżką względną i nie może zawierać .. ścieżki"
 
-#: kallithea/controllers/files.py:526
+#: kallithea/controllers/files.py:528
 msgid "Downloads disabled"
 msgstr "Pobieranie wyłączone"
 
-#: kallithea/controllers/files.py:537
+#: kallithea/controllers/files.py:539
 #, python-format
 msgid "Unknown revision %s"
 msgstr "Nieznana wersja %s"
 
-#: kallithea/controllers/files.py:539
+#: kallithea/controllers/files.py:541
 msgid "Empty repository"
 msgstr "Puste repozytorium"
 
-#: kallithea/controllers/files.py:541
+#: kallithea/controllers/files.py:543
 msgid "Unknown archive type"
 msgstr "Nieznany typ archiwum"
 
-#: kallithea/controllers/files.py:771
+#: kallithea/controllers/files.py:773
 #: kallithea/templates/changeset/changeset_range.html:9
 #: kallithea/templates/email_templates/pull_request.html:15
 #: kallithea/templates/pullrequests/pullrequest.html:97
 msgid "Changesets"
 msgstr "Różnice"
 
-#: kallithea/controllers/files.py:772 kallithea/controllers/pullrequests.py:176
-#: kallithea/model/scm.py:820 kallithea/templates/switch_to_list.html:3
+#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:175
+#: kallithea/model/scm.py:716 kallithea/templates/switch_to_list.html:3
 #: kallithea/templates/branches/branches.html:10
 msgid "Branches"
 msgstr "Gałęzie"
 
-#: kallithea/controllers/files.py:773 kallithea/controllers/pullrequests.py:177
-#: kallithea/model/scm.py:831 kallithea/templates/switch_to_list.html:25
+#: kallithea/controllers/files.py:775 kallithea/controllers/pullrequests.py:176
+#: kallithea/model/scm.py:727 kallithea/templates/switch_to_list.html:25
 #: kallithea/templates/tags/tags.html:10
 msgid "Tags"
 msgstr "Etykiety"
@@ -258,7 +252,7 @@
 msgid "Groups"
 msgstr ""
 
-#: kallithea/controllers/home.py:89
+#: kallithea/controllers/home.py:94
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:106
 #: kallithea/templates/admin/repos/repo_add.html:12
 #: kallithea/templates/admin/repos/repo_add.html:16
@@ -266,23 +260,27 @@
 #: kallithea/templates/admin/users/user_edit_advanced.html:6
 #: kallithea/templates/base/base.html:60 kallithea/templates/base/base.html:77
 #: kallithea/templates/base/base.html:124
-#: kallithea/templates/base/base.html:390
-#: kallithea/templates/base/base.html:562
+#: kallithea/templates/base/base.html:479
+#: kallithea/templates/base/base.html:653
 msgid "Repositories"
 msgstr "Repozytoria"
 
-#: kallithea/controllers/home.py:130
+#: kallithea/controllers/home.py:139
 #: kallithea/templates/files/files_add.html:32
 #: kallithea/templates/files/files_delete.html:23
 #: kallithea/templates/files/files_edit.html:32
 msgid "Branch"
 msgstr "gałąź"
 
-#: kallithea/controllers/home.py:136
+#: kallithea/controllers/home.py:145 kallithea/templates/switch_to_list.html:16
+msgid "Closed Branches"
+msgstr "Zamknięte Gałęzie"
+
+#: kallithea/controllers/home.py:151
 msgid "Tag"
 msgstr "Tag"
 
-#: kallithea/controllers/home.py:142
+#: kallithea/controllers/home.py:157
 msgid "Bookmark"
 msgstr "Bookmark"
 
@@ -293,164 +291,167 @@
 msgstr "Dziennik Publiczny"
 
 #: kallithea/controllers/journal.py:115 kallithea/controllers/journal.py:157
-#: kallithea/templates/base/base.html:222
+#: kallithea/templates/base/base.html:306
 #: kallithea/templates/journal/journal.html:4
 #: kallithea/templates/journal/journal.html:12
 msgid "Journal"
 msgstr "Dziennik"
 
-#: kallithea/controllers/login.py:151 kallithea/controllers/login.py:197
+#: kallithea/controllers/login.py:144 kallithea/controllers/login.py:190
 msgid "Bad captcha"
 msgstr ""
 
-#: kallithea/controllers/login.py:157
-msgid "You have successfully registered into Kallithea"
-msgstr "Udało Ci się zarejestrować na stronie"
-
-#: kallithea/controllers/login.py:202
-#, fuzzy
-#| msgid "Your password reset link was sent"
+#: kallithea/controllers/login.py:150
+msgid "You have successfully registered with %s"
+msgstr "Udało Ci się zarejestrować w %s"
+
+#: kallithea/controllers/login.py:195
+#, fuzzy
 msgid "A password reset confirmation code has been sent"
 msgstr "Twój link zresetowania hasła został wysłany"
 
-#: kallithea/controllers/login.py:251
-#, fuzzy
-#| msgid "Password reset link"
+#: kallithea/controllers/login.py:244
+#, fuzzy
 msgid "Invalid password reset token"
 msgstr "łącze resetowania hasła"
 
-#: kallithea/controllers/login.py:256
+#: kallithea/controllers/login.py:249
 #: kallithea/controllers/admin/my_account.py:167
 msgid "Successfully updated password"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:124
+#: kallithea/controllers/pullrequests.py:123
 #, python-format
 msgid "%s (closed)"
 msgstr "%s (zamknięty)"
 
-#: kallithea/controllers/pullrequests.py:152
+#: kallithea/controllers/pullrequests.py:151
 #: kallithea/templates/changeset/changeset.html:12
 #: kallithea/templates/email_templates/changeset_comment.html:17
 msgid "Changeset"
 msgstr "Grupy zmian"
 
-#: kallithea/controllers/pullrequests.py:173
+#: kallithea/controllers/pullrequests.py:172
 msgid "Special"
 msgstr "Specjalne"
 
-#: kallithea/controllers/pullrequests.py:174
+#: kallithea/controllers/pullrequests.py:173
 msgid "Peer branches"
 msgstr "gałęzie"
 
-#: kallithea/controllers/pullrequests.py:175 kallithea/model/scm.py:826
+#: kallithea/controllers/pullrequests.py:174 kallithea/model/scm.py:722
 #: kallithea/templates/switch_to_list.html:38
 #: kallithea/templates/bookmarks/bookmarks.html:10
 msgid "Bookmarks"
 msgstr "Zakładki"
 
-#: kallithea/controllers/pullrequests.py:310
+#: kallithea/controllers/pullrequests.py:312
 #, python-format
 msgid "Error creating pull request: %s"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:356
-#: kallithea/controllers/pullrequests.py:503
+#: kallithea/controllers/pullrequests.py:358
+#: kallithea/controllers/pullrequests.py:505
 msgid "No description"
 msgstr "Brak opisu"
 
-#: kallithea/controllers/pullrequests.py:363
+#: kallithea/controllers/pullrequests.py:365
 msgid "Successfully opened new pull request"
 msgstr "Prośba o wykonanie połączenia gałęzi została wykonana prawidłowo"
 
-#: kallithea/controllers/pullrequests.py:366
-#: kallithea/controllers/pullrequests.py:453
-#: kallithea/controllers/pullrequests.py:509
+#: kallithea/controllers/pullrequests.py:368
+#: kallithea/controllers/pullrequests.py:455
+#: kallithea/controllers/pullrequests.py:512
 #, python-format
 msgid "Invalid reviewer \"%s\" specified"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:369
-#: kallithea/controllers/pullrequests.py:456
+#: kallithea/controllers/pullrequests.py:371
+#: kallithea/controllers/pullrequests.py:458
 msgid "Error occurred while creating pull request"
 msgstr "Wystąpił błąd podczas prośby o połączenie gałęzi"
 
-#: kallithea/controllers/pullrequests.py:401
+#: kallithea/controllers/pullrequests.py:403
 msgid "Missing changesets since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:408
+#: kallithea/controllers/pullrequests.py:410
 #, python-format
 msgid "New changesets on %s %s since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:415
+#: kallithea/controllers/pullrequests.py:417
 msgid "Ancestor didn't change - show diff since previous version:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:422
+#: kallithea/controllers/pullrequests.py:424
 #, python-format
 msgid ""
 "This pull request is based on another %s revision and there is no simple "
 "diff."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:424
+#: kallithea/controllers/pullrequests.py:426
 #, python-format
 msgid "No changes found on %s %s since previous version."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:462
+#: kallithea/controllers/pullrequests.py:464
 #, python-format
 msgid "Closed, replaced by %s ."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:470
+#: kallithea/controllers/pullrequests.py:472
 msgid "Pull request update created"
 msgstr "Recenzje wniosków połączenia gałęzi"
 
-#: kallithea/controllers/pullrequests.py:513
+#: kallithea/controllers/pullrequests.py:516
 #, fuzzy
 msgid "Pull request updated"
 msgstr "Połączone gałęzie"
 
-#: kallithea/controllers/pullrequests.py:528
+#: kallithea/controllers/pullrequests.py:531
 msgid "Successfully deleted pull request"
 msgstr "Prośba o skasowanie połączenia gałęzi została wykonana prawidłowo"
 
-#: kallithea/controllers/pullrequests.py:594
+#: kallithea/controllers/pullrequests.py:597
 #, python-format
 msgid "This pull request has already been merged to %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:596
+#: kallithea/controllers/pullrequests.py:599
 msgid "This pull request has been closed and can not be updated."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:614
-#, python-format
-msgid "This pull request can be updated with changes on %s:"
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:617
+#, python-format
+msgid "The following changes are available on %s:"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:621
 msgid "No changesets found for updating this pull request."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:625
+#: kallithea/controllers/pullrequests.py:629
 #, python-format
 msgid "Note: Branch %s has another head: %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:631
+#: kallithea/controllers/pullrequests.py:635
 msgid "Git pull requests don't support updates yet."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:722
+#: kallithea/controllers/pullrequests.py:727
 #, fuzzy
 msgid "No permission to change pull request status"
 msgstr "Zagłosuj na żądanie na grupę zmian"
 
-#: kallithea/controllers/pullrequests.py:727
+#: kallithea/controllers/pullrequests.py:738
+#, fuzzy, python-format
+msgid "Successfully deleted pull request %s"
+msgstr "Prośba o skasowanie połączenia gałęzi została wykonana prawidłowo"
+
+#: kallithea/controllers/pullrequests.py:748
 msgid "Closing."
 msgstr "Zamknięcie."
 
@@ -466,13 +467,13 @@
 msgid "An error occurred during search operation."
 msgstr "Wystąpił błąd podczas operacji wyszukiwania."
 
-#: kallithea/controllers/summary.py:180
+#: kallithea/controllers/summary.py:181
 #: kallithea/templates/summary/summary.html:384
 #, fuzzy
 msgid "No data ready yet"
 msgstr "Żadne dane nie zostały załadowane"
 
-#: kallithea/controllers/summary.py:183
+#: kallithea/controllers/summary.py:184
 #: kallithea/templates/summary/summary.html:98
 msgid "Statistics are disabled for this repository"
 msgstr "Statystyki są wyłączone dla tego repozytorium"
@@ -493,66 +494,66 @@
 msgid "Error occurred during update of defaults"
 msgstr "wystąpił błąd podczas aktualizacji wartości domyślnych"
 
-#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/gists.py:58
 #: kallithea/controllers/admin/my_account.py:243
-#: kallithea/controllers/admin/users.py:285
+#: kallithea/controllers/admin/users.py:284
 #, fuzzy
 msgid "Forever"
 msgstr "na zawsze"
 
-#: kallithea/controllers/admin/gists.py:60
+#: kallithea/controllers/admin/gists.py:59
 #: kallithea/controllers/admin/my_account.py:244
-#: kallithea/controllers/admin/users.py:286
+#: kallithea/controllers/admin/users.py:285
 msgid "5 minutes"
 msgstr "5 minut"
 
+#: kallithea/controllers/admin/gists.py:60
+#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/users.py:286
+msgid "1 hour"
+msgstr "1 godzina"
+
 #: kallithea/controllers/admin/gists.py:61
-#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/my_account.py:246
 #: kallithea/controllers/admin/users.py:287
-msgid "1 hour"
-msgstr "1 godzina"
-
-#: kallithea/controllers/admin/gists.py:62
-#: kallithea/controllers/admin/my_account.py:246
-#: kallithea/controllers/admin/users.py:288
 msgid "1 day"
 msgstr "1 dzień"
 
-#: kallithea/controllers/admin/gists.py:63
+#: kallithea/controllers/admin/gists.py:62
 #: kallithea/controllers/admin/my_account.py:247
-#: kallithea/controllers/admin/users.py:289
+#: kallithea/controllers/admin/users.py:288
 msgid "1 month"
 msgstr "1 miesiąc"
 
-#: kallithea/controllers/admin/gists.py:67
+#: kallithea/controllers/admin/gists.py:66
 #: kallithea/controllers/admin/my_account.py:249
-#: kallithea/controllers/admin/users.py:291
+#: kallithea/controllers/admin/users.py:290
 msgid "Lifetime"
 msgstr "Czas życia"
 
-#: kallithea/controllers/admin/gists.py:146
+#: kallithea/controllers/admin/gists.py:145
 msgid "Error occurred during gist creation"
 msgstr "Wystąpił błąd podczas tworzenia git"
 
-#: kallithea/controllers/admin/gists.py:184
+#: kallithea/controllers/admin/gists.py:183
 #, python-format
 msgid "Deleted gist %s"
 msgstr "Usuń gist %s"
 
-#: kallithea/controllers/admin/gists.py:233
+#: kallithea/controllers/admin/gists.py:232
 #, fuzzy
 msgid "Unmodified"
 msgstr "Ostatnio modyfikowany"
 
-#: kallithea/controllers/admin/gists.py:262
+#: kallithea/controllers/admin/gists.py:261
 msgid "Successfully updated gist content"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:267
+#: kallithea/controllers/admin/gists.py:266
 msgid "Successfully updated gist data"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:270
+#: kallithea/controllers/admin/gists.py:269
 #, python-format
 msgid "Error occurred during update of gist %s"
 msgstr ""
@@ -569,7 +570,7 @@
 msgstr "Twoje konto zostało pomyślnie zaktualizowane"
 
 #: kallithea/controllers/admin/my_account.py:144
-#: kallithea/controllers/admin/users.py:202
+#: kallithea/controllers/admin/users.py:201
 #, python-format
 msgid "Error occurred during update of user %s"
 msgstr "wystąpił błąd podczas aktualizacji użytkownika %s"
@@ -579,33 +580,33 @@
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:220
-#: kallithea/controllers/admin/users.py:415
+#: kallithea/controllers/admin/users.py:414
 #, python-format
 msgid "Added email %s to user"
 msgstr "Dodano e-mail %s do użytkownika"
 
 #: kallithea/controllers/admin/my_account.py:226
-#: kallithea/controllers/admin/users.py:421
+#: kallithea/controllers/admin/users.py:420
 msgid "An error occurred during email saving"
 msgstr "Wystąpił błąd podczas zapisywania e-maila"
 
 #: kallithea/controllers/admin/my_account.py:235
-#: kallithea/controllers/admin/users.py:433
+#: kallithea/controllers/admin/users.py:432
 msgid "Removed email from user"
 msgstr "Usunięto e-mail użytkownikowi"
 
 #: kallithea/controllers/admin/my_account.py:259
-#: kallithea/controllers/admin/users.py:308
+#: kallithea/controllers/admin/users.py:307
 msgid "API key successfully created"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:271
-#: kallithea/controllers/admin/users.py:321
+#: kallithea/controllers/admin/users.py:320
 msgid "API key successfully reset"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:275
-#: kallithea/controllers/admin/users.py:325
+#: kallithea/controllers/admin/users.py:324
 msgid "API key successfully deleted"
 msgstr ""
 
@@ -655,10 +656,10 @@
 #: kallithea/templates/admin/users/user_edit_profile.html:105
 #: kallithea/templates/admin/users/users.html:10
 #: kallithea/templates/admin/users/users.html:55
-#: kallithea/templates/base/base.html:252
-#: kallithea/templates/base/base.html:253
-#: kallithea/templates/base/base.html:259
-#: kallithea/templates/base/base.html:260
+#: kallithea/templates/base/base.html:336
+#: kallithea/templates/base/base.html:337
+#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:344
 #: kallithea/templates/base/perms_summary.html:17
 msgid "Admin"
 msgstr "Administracja"
@@ -689,7 +690,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1564
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1603
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1655
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1701
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1705
 msgid "Manual activation of external account"
 msgstr "Ręczna aktywacja nowego konta"
 
@@ -701,7 +702,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1565
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1604
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1656
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1702
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1706
 msgid "Automatic activation of external account"
 msgstr "Automatyczna aktywacja nowego konta"
 
@@ -722,246 +723,246 @@
 msgid "Error occurred during update of permissions"
 msgstr "Wystąpił błąd podczas aktualizacji uprawnień"
 
-#: kallithea/controllers/admin/repo_groups.py:188
+#: kallithea/controllers/admin/repo_groups.py:187
 #, python-format
 msgid "Error occurred during creation of repository group %s"
 msgstr "Wystąpił błąd podczas tworzenia grupy repo %s"
 
-#: kallithea/controllers/admin/repo_groups.py:193
+#: kallithea/controllers/admin/repo_groups.py:192
 #, python-format
 msgid "Created repository group %s"
 msgstr "Utworzono grupę repo %s"
 
-#: kallithea/controllers/admin/repo_groups.py:250
+#: kallithea/controllers/admin/repo_groups.py:249
 #, python-format
 msgid "Updated repository group %s"
 msgstr "Zaktualizowano grupę repo %s"
 
-#: kallithea/controllers/admin/repo_groups.py:266
+#: kallithea/controllers/admin/repo_groups.py:265
 #, python-format
 msgid "Error occurred during update of repository group %s"
 msgstr "Wystąpił błąd podczas aktualizacji grupy repo %s"
 
-#: kallithea/controllers/admin/repo_groups.py:284
+#: kallithea/controllers/admin/repo_groups.py:283
 #, python-format
 msgid "This group contains %s repositories and cannot be deleted"
 msgstr "Ta grupa zawiera %s repozytorium i nie może być usunięta"
 
-#: kallithea/controllers/admin/repo_groups.py:291
+#: kallithea/controllers/admin/repo_groups.py:290
 #, python-format
 msgid "This group contains %s subgroups and cannot be deleted"
 msgstr "Ta grupa zawiera %s repozytorium i nie może być usunięta"
 
-#: kallithea/controllers/admin/repo_groups.py:297
+#: kallithea/controllers/admin/repo_groups.py:296
 #, python-format
 msgid "Removed repository group %s"
 msgstr "Usunięto grupę repo %s"
 
-#: kallithea/controllers/admin/repo_groups.py:302
+#: kallithea/controllers/admin/repo_groups.py:301
 #, python-format
 msgid "Error occurred during deletion of repository group %s"
 msgstr "Wystąpił błąd podczas usuwania z repozytorium grupy %s"
 
-#: kallithea/controllers/admin/repo_groups.py:405
-#: kallithea/controllers/admin/repo_groups.py:440
+#: kallithea/controllers/admin/repo_groups.py:404
+#: kallithea/controllers/admin/repo_groups.py:439
 #: kallithea/controllers/admin/user_groups.py:340
 msgid "Cannot revoke permission for yourself as admin"
 msgstr "Nie można cofnąć zezwolenia dla admina jako admin"
 
-#: kallithea/controllers/admin/repo_groups.py:420
+#: kallithea/controllers/admin/repo_groups.py:419
 msgid "Repository group permissions updated"
 msgstr "Aktualizacja uprawnień grup repozytorium"
 
-#: kallithea/controllers/admin/repo_groups.py:457
-#: kallithea/controllers/admin/repos.py:398
+#: kallithea/controllers/admin/repo_groups.py:456
+#: kallithea/controllers/admin/repos.py:397
 #: kallithea/controllers/admin/user_groups.py:352
 msgid "An error occurred during revoking of permission"
 msgstr "Wystąpił błąd podczas cofania zezwolenia"
 
-#: kallithea/controllers/admin/repos.py:152
+#: kallithea/controllers/admin/repos.py:151
 #, python-format
 msgid "Error creating repository %s"
 msgstr "utworzone repozytorium %s"
 
-#: kallithea/controllers/admin/repos.py:213
+#: kallithea/controllers/admin/repos.py:212
 #, python-format
 msgid "Created repository %s from %s"
 msgstr "utworzone repozytorium %s z %s"
 
-#: kallithea/controllers/admin/repos.py:222
+#: kallithea/controllers/admin/repos.py:221
 #, python-format
 msgid "Forked repository %s as %s"
 msgstr "Gałęzi %s w repozytorium %s"
 
-#: kallithea/controllers/admin/repos.py:225
+#: kallithea/controllers/admin/repos.py:224
 #, python-format
 msgid "Created repository %s"
 msgstr "Utworzone repozytorium %s"
 
-#: kallithea/controllers/admin/repos.py:262
+#: kallithea/controllers/admin/repos.py:261
 #, python-format
 msgid "Repository %s updated successfully"
 msgstr "Repozytorium %s zostało pomyślnie zaktualizowane"
 
-#: kallithea/controllers/admin/repos.py:283
+#: kallithea/controllers/admin/repos.py:282
 #, python-format
 msgid "Error occurred during update of repository %s"
 msgstr "Wystąpił błąd podczas aktualizacji repozytorium %s"
 
-#: kallithea/controllers/admin/repos.py:310
+#: kallithea/controllers/admin/repos.py:309
 #, python-format
 msgid "Detached %s forks"
 msgstr "Oderwane rozgałęzienie %s"
 
-#: kallithea/controllers/admin/repos.py:313
+#: kallithea/controllers/admin/repos.py:312
 #, python-format
 msgid "Deleted %s forks"
 msgstr "Usunięte repozytorium %s"
 
-#: kallithea/controllers/admin/repos.py:318
+#: kallithea/controllers/admin/repos.py:317
 #, python-format
 msgid "Deleted repository %s"
 msgstr "Usunięte repozytorium %s"
 
-#: kallithea/controllers/admin/repos.py:321
+#: kallithea/controllers/admin/repos.py:320
 #, fuzzy, python-format
 msgid "Cannot delete repository %s which still has forks"
 msgstr "Nie można usunąć %s nadal zawiera załączniki rozgałęzienia"
 
-#: kallithea/controllers/admin/repos.py:326
+#: kallithea/controllers/admin/repos.py:325
 #, python-format
 msgid "An error occurred during deletion of %s"
 msgstr "Wystąpił błąd podczas usuwania %s"
 
-#: kallithea/controllers/admin/repos.py:374
+#: kallithea/controllers/admin/repos.py:373
 msgid "Repository permissions updated"
 msgstr "Uprawnienia repozytorium zostały zaktualizowane"
 
-#: kallithea/controllers/admin/repos.py:430
+#: kallithea/controllers/admin/repos.py:429
 msgid "An error occurred during creation of field"
 msgstr "Wystąpił błąd podczas tworzenia użytkownika %s"
 
-#: kallithea/controllers/admin/repos.py:444
+#: kallithea/controllers/admin/repos.py:443
 msgid "An error occurred during removal of field"
 msgstr "Wystąpił błąd podczas zapisywania e-maila"
 
-#: kallithea/controllers/admin/repos.py:460
+#: kallithea/controllers/admin/repos.py:459
 msgid "-- Not a fork --"
 msgstr "-- Brak rozgalezienia --"
 
-#: kallithea/controllers/admin/repos.py:491
+#: kallithea/controllers/admin/repos.py:490
 msgid "Updated repository visibility in public journal"
 msgstr "Zaktualizowano widoczność stron w publicznym dzienniku"
 
-#: kallithea/controllers/admin/repos.py:495
+#: kallithea/controllers/admin/repos.py:494
 msgid "An error occurred during setting this repository in public journal"
 msgstr "Wystąpił błąd podczas ustawiania tego repozytorium w dzienniku publicznym"
 
-#: kallithea/controllers/admin/repos.py:512
+#: kallithea/controllers/admin/repos.py:511
 msgid "Nothing"
 msgstr "Brak"
 
-#: kallithea/controllers/admin/repos.py:514
+#: kallithea/controllers/admin/repos.py:513
 #, python-format
 msgid "Marked repository %s as fork of %s"
 msgstr "Oznaczono %s repo jako rozwidlenie %s"
 
-#: kallithea/controllers/admin/repos.py:521
+#: kallithea/controllers/admin/repos.py:520
 msgid "An error occurred during this operation"
 msgstr "Wystąpił błąd podczas tej operacji"
 
-#: kallithea/controllers/admin/repos.py:537
-#: kallithea/controllers/admin/repos.py:564
+#: kallithea/controllers/admin/repos.py:536
+#: kallithea/controllers/admin/repos.py:563
 #, fuzzy
 msgid "Repository has been locked"
 msgstr "Repozytorium nie jest zablokowane"
 
-#: kallithea/controllers/admin/repos.py:540
-#: kallithea/controllers/admin/repos.py:561
+#: kallithea/controllers/admin/repos.py:539
+#: kallithea/controllers/admin/repos.py:560
 #, fuzzy
 msgid "Repository has been unlocked"
 msgstr "Repozytorium nie jest zablokowane"
 
-#: kallithea/controllers/admin/repos.py:543
-#: kallithea/controllers/admin/repos.py:568
+#: kallithea/controllers/admin/repos.py:542
+#: kallithea/controllers/admin/repos.py:567
 msgid "An error occurred during unlocking"
 msgstr "Wystąpił błąd podczas odblokowywania"
 
-#: kallithea/controllers/admin/repos.py:582
+#: kallithea/controllers/admin/repos.py:581
 msgid "Cache invalidation successful"
 msgstr "Cache wyczyszczony poprawnie"
 
-#: kallithea/controllers/admin/repos.py:586
+#: kallithea/controllers/admin/repos.py:585
 msgid "An error occurred during cache invalidation"
 msgstr "Wystąpił błąd podczas unieważniania cache"
 
-#: kallithea/controllers/admin/repos.py:601
+#: kallithea/controllers/admin/repos.py:600
 msgid "Pulled from remote location"
 msgstr "Pobieranie z lokalizacji zdalnej"
 
-#: kallithea/controllers/admin/repos.py:604
+#: kallithea/controllers/admin/repos.py:603
 msgid "An error occurred during pull from remote location"
 msgstr "Wystąpił błąd podczas pobierania z lokalizacji zdalnej"
 
-#: kallithea/controllers/admin/repos.py:637
+#: kallithea/controllers/admin/repos.py:636
 msgid "An error occurred during deletion of repository stats"
 msgstr "Wystąpił błąd podczas usuwania z repozytorium statystyk"
 
-#: kallithea/controllers/admin/settings.py:170
+#: kallithea/controllers/admin/settings.py:141
 msgid "Updated VCS settings"
 msgstr "Aktualizacja ustawień VCS"
 
-#: kallithea/controllers/admin/settings.py:174
+#: kallithea/controllers/admin/settings.py:145
 msgid ""
 "Unable to activate hgsubversion support. The \"hgsubversion\" library is "
 "missing"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:180
-#: kallithea/controllers/admin/settings.py:277
+#: kallithea/controllers/admin/settings.py:151
+#: kallithea/controllers/admin/settings.py:248
 msgid "Error occurred while updating application settings"
 msgstr "Wystąpił błąd podczas aktualizacji ustawień aplikacji"
 
-#: kallithea/controllers/admin/settings.py:216
+#: kallithea/controllers/admin/settings.py:187
 #, python-format
 msgid "Repositories successfully rescanned. Added: %s. Removed: %s."
 msgstr ""
 "Repozytoria z powodzeniem zostały ponownie zeskanowane dodano: %s, "
 "usunięto: %s."
 
-#: kallithea/controllers/admin/settings.py:273
+#: kallithea/controllers/admin/settings.py:244
 msgid "Updated application settings"
 msgstr "Aktualizacja ustawień aplikacji"
 
-#: kallithea/controllers/admin/settings.py:330
+#: kallithea/controllers/admin/settings.py:301
 msgid "Updated visualisation settings"
 msgstr "Aktualizacja ustawień wizualizacji"
 
-#: kallithea/controllers/admin/settings.py:335
+#: kallithea/controllers/admin/settings.py:306
 msgid "Error occurred during updating visualisation settings"
 msgstr "Wystąpił błąd podczas aktualizacji ustawień wizualizacji"
 
-#: kallithea/controllers/admin/settings.py:361
+#: kallithea/controllers/admin/settings.py:332
 msgid "Please enter email address"
 msgstr "Proszę podać adres email"
 
-#: kallithea/controllers/admin/settings.py:376
+#: kallithea/controllers/admin/settings.py:347
 msgid "Send email task created"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:407
+#: kallithea/controllers/admin/settings.py:378
 msgid "Added new hook"
 msgstr "Dodano nowy hook"
 
-#: kallithea/controllers/admin/settings.py:421
+#: kallithea/controllers/admin/settings.py:392
 msgid "Updated hooks"
 msgstr "Aktualizacja hooku"
 
-#: kallithea/controllers/admin/settings.py:425
+#: kallithea/controllers/admin/settings.py:396
 msgid "Error occurred during hook creation"
 msgstr "Wystąpił błąd podczas tworzenia hooku"
 
-#: kallithea/controllers/admin/settings.py:451
+#: kallithea/controllers/admin/settings.py:422
 msgid "Whoosh reindex task scheduled"
 msgstr "Zadanie ponownej indeksacji whoosh zostało zaplanowane"
 
@@ -1002,76 +1003,80 @@
 msgstr "Aktualizacja uprawnień grupy użytkowników"
 
 #: kallithea/controllers/admin/user_groups.py:440
-#: kallithea/controllers/admin/users.py:384
+#: kallithea/controllers/admin/users.py:383
 msgid "Updated permissions"
 msgstr "Aktualizacja uprawnień"
 
 #: kallithea/controllers/admin/user_groups.py:444
-#: kallithea/controllers/admin/users.py:388
+#: kallithea/controllers/admin/users.py:387
 msgid "An error occurred during permissions saving"
 msgstr "Wystąpił błąd podczas zapisywania uprawnień"
 
-#: kallithea/controllers/admin/users.py:134
+#: kallithea/controllers/admin/users.py:133
 #, python-format
 msgid "Created user %s"
 msgstr "Utworzono użytkownika %s"
 
-#: kallithea/controllers/admin/users.py:149
+#: kallithea/controllers/admin/users.py:148
 #, python-format
 msgid "Error occurred during creation of user %s"
 msgstr "Wystąpił błąd podczas tworzenia użytkownika %s"
 
-#: kallithea/controllers/admin/users.py:182
+#: kallithea/controllers/admin/users.py:181
 msgid "User updated successfully"
 msgstr "Użytkownik został zaktualizowany"
 
-#: kallithea/controllers/admin/users.py:218
+#: kallithea/controllers/admin/users.py:217
 msgid "Successfully deleted user"
 msgstr "Użytkownik został usunięty"
 
-#: kallithea/controllers/admin/users.py:223
+#: kallithea/controllers/admin/users.py:222
 msgid "An error occurred during deletion of user"
 msgstr "Wystąpił błąd podczas usuwania użytkownika"
 
-#: kallithea/controllers/admin/users.py:236
+#: kallithea/controllers/admin/users.py:235
 msgid "The default user cannot be edited"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:463
+#: kallithea/controllers/admin/users.py:462
 #, python-format
 msgid "Added IP address %s to user whitelist"
 msgstr "Dodano ip %s do listy dozwolonych adresów użytkownia"
 
-#: kallithea/controllers/admin/users.py:469
+#: kallithea/controllers/admin/users.py:468
 msgid "An error occurred while adding IP address"
 msgstr "Wystąpił błąd podczas zapisywania e-maila"
 
-#: kallithea/controllers/admin/users.py:483
+#: kallithea/controllers/admin/users.py:482
 msgid "Removed IP address from user whitelist"
 msgstr "Usunięto adres ip z listy dozwolonych adresów dla użytkownika"
 
-#: kallithea/lib/auth.py:743
+#: kallithea/lib/auth.py:737
 #, python-format
 msgid "IP %s not allowed"
 msgstr "Obserwatorzy %s"
 
-#: kallithea/lib/auth.py:756
+#: kallithea/lib/auth.py:750
 msgid "Invalid API key"
 msgstr ""
 
-#: kallithea/lib/auth.py:812
+#: kallithea/lib/auth.py:768
+msgid "CSRF token leak has been detected - all form tokens have been expired"
+msgstr ""
+
+#: kallithea/lib/auth.py:813
 msgid "You need to be a registered user to perform this action"
 msgstr "Musisz być zarejestrowanym użytkownikiem, żeby wykonać to działanie"
 
-#: kallithea/lib/auth.py:844
+#: kallithea/lib/auth.py:843
 msgid "You need to be signed in to view this page"
 msgstr "Musisz być zalogowany, żeby oglądać stronę"
 
-#: kallithea/lib/base.py:490
+#: kallithea/lib/base.py:493
 msgid "Repository not found in the filesystem"
 msgstr ""
 
-#: kallithea/lib/base.py:516 kallithea/lib/helpers.py:622
+#: kallithea/lib/base.py:519 kallithea/lib/helpers.py:623
 msgid "Changeset not found"
 msgstr "Nie znaleziono changeset"
 
@@ -1089,126 +1094,126 @@
 msgid "No changes detected"
 msgstr "Nie wykryto zmian"
 
-#: kallithea/lib/helpers.py:609
+#: kallithea/lib/helpers.py:610
 #, python-format
 msgid "Deleted branch: %s"
 msgstr "Usunięta gałąź: %s"
 
-#: kallithea/lib/helpers.py:611
+#: kallithea/lib/helpers.py:612
 #, python-format
 msgid "Created tag: %s"
 msgstr "Utworzony tag: %s"
 
-#: kallithea/lib/helpers.py:671
+#: kallithea/lib/helpers.py:672
 #, python-format
 msgid "Show all combined changesets %s->%s"
 msgstr "Pokaż wszystkie zestawienia zmian changesets %s->%s"
 
-#: kallithea/lib/helpers.py:677
+#: kallithea/lib/helpers.py:678
 #, fuzzy
 msgid "Compare view"
 msgstr "Wyświetl porównanie"
 
-#: kallithea/lib/helpers.py:696
+#: kallithea/lib/helpers.py:697
 msgid "and"
 msgstr "i"
 
-#: kallithea/lib/helpers.py:697
+#: kallithea/lib/helpers.py:698
 #, python-format
 msgid "%s more"
 msgstr "%s więcej"
 
-#: kallithea/lib/helpers.py:698 kallithea/templates/changelog/changelog.html:44
+#: kallithea/lib/helpers.py:699 kallithea/templates/changelog/changelog.html:44
 msgid "revisions"
 msgstr "rewizja"
 
-#: kallithea/lib/helpers.py:722
+#: kallithea/lib/helpers.py:723
 #, fuzzy, python-format
 msgid "Fork name %s"
 msgstr "nazwa rozgałęzienia %s"
 
-#: kallithea/lib/helpers.py:742
+#: kallithea/lib/helpers.py:743
 #, fuzzy, python-format
 msgid "Pull request %s"
 msgstr "Połączonych gałęzi #%s"
 
-#: kallithea/lib/helpers.py:752
+#: kallithea/lib/helpers.py:753
 msgid "[deleted] repository"
 msgstr "[usunięte] repozytorium"
 
-#: kallithea/lib/helpers.py:754 kallithea/lib/helpers.py:766
+#: kallithea/lib/helpers.py:755 kallithea/lib/helpers.py:767
 msgid "[created] repository"
 msgstr "[utworzone] repozytorium"
 
-#: kallithea/lib/helpers.py:756
+#: kallithea/lib/helpers.py:757
 msgid "[created] repository as fork"
 msgstr "[utworzone] repozytorium jako rozgałęzienie"
 
-#: kallithea/lib/helpers.py:758 kallithea/lib/helpers.py:768
+#: kallithea/lib/helpers.py:759 kallithea/lib/helpers.py:769
 msgid "[forked] repository"
 msgstr "[rozgałęzione] repozytorium"
 
-#: kallithea/lib/helpers.py:760 kallithea/lib/helpers.py:770
+#: kallithea/lib/helpers.py:761 kallithea/lib/helpers.py:771
 msgid "[updated] repository"
 msgstr "[zaktualizowane] repozytorium"
 
-#: kallithea/lib/helpers.py:762
+#: kallithea/lib/helpers.py:763
 msgid "[downloaded] archive from repository"
 msgstr "[pobierz] archiwum z repozytorium"
 
-#: kallithea/lib/helpers.py:764
+#: kallithea/lib/helpers.py:765
 msgid "[delete] repository"
 msgstr "[skasowane] repozytorium"
 
-#: kallithea/lib/helpers.py:772
+#: kallithea/lib/helpers.py:773
 msgid "[created] user"
 msgstr "[utworzony] użytkownik"
 
-#: kallithea/lib/helpers.py:774
+#: kallithea/lib/helpers.py:775
 msgid "[updated] user"
 msgstr "[zaktualizowany] użytkownik"
 
-#: kallithea/lib/helpers.py:776
+#: kallithea/lib/helpers.py:777
 msgid "[created] user group"
 msgstr "[utworzona] grupa użytkowników"
 
-#: kallithea/lib/helpers.py:778
+#: kallithea/lib/helpers.py:779
 msgid "[updated] user group"
 msgstr "[zaktualizowana] grupa użytkowników"
 
-#: kallithea/lib/helpers.py:780
+#: kallithea/lib/helpers.py:781
 msgid "[commented] on revision in repository"
 msgstr "[komentarz] do zmiany w repozytorium"
 
-#: kallithea/lib/helpers.py:782
+#: kallithea/lib/helpers.py:783
 msgid "[commented] on pull request for"
 msgstr "[komentarz] wniosek o połączenie gałęzi"
 
-#: kallithea/lib/helpers.py:784
+#: kallithea/lib/helpers.py:785
 msgid "[closed] pull request for"
 msgstr "[zamknięty] wniosek o połączenie gałęzi"
 
-#: kallithea/lib/helpers.py:786
+#: kallithea/lib/helpers.py:787
 msgid "[pushed] into"
 msgstr "[wysłane zmiany] w"
 
-#: kallithea/lib/helpers.py:788
+#: kallithea/lib/helpers.py:789
 msgid "[committed via Kallithea] into repository"
 msgstr "[synchronizacja przez Kallithea] z repozytorium"
 
-#: kallithea/lib/helpers.py:790
+#: kallithea/lib/helpers.py:791
 msgid "[pulled from remote] into repository"
 msgstr "[pobieranie z zdalnego] do repozytorium"
 
-#: kallithea/lib/helpers.py:792
+#: kallithea/lib/helpers.py:793
 msgid "[pulled] from"
 msgstr "[pobrano]"
 
-#: kallithea/lib/helpers.py:794
+#: kallithea/lib/helpers.py:795
 msgid "[started following] repository"
 msgstr "[start następnego] repozytorium"
 
-#: kallithea/lib/helpers.py:796
+#: kallithea/lib/helpers.py:797
 msgid "[stopped following] repository"
 msgstr "[zatrzymany po] repozytorium"
 
@@ -1218,8 +1223,8 @@
 msgstr " i %s więcej"
 
 #: kallithea/lib/helpers.py:1128
-#: kallithea/templates/compare/compare_diff.html:65
-#: kallithea/templates/pullrequests/pullrequest_show.html:326
+#: kallithea/templates/compare/compare_diff.html:71
+#: kallithea/templates/pullrequests/pullrequest_show.html:337
 msgid "No files"
 msgstr "Brak plików"
 
@@ -1243,7 +1248,7 @@
 msgid "chmod"
 msgstr "chmod"
 
-#: kallithea/lib/helpers.py:1444
+#: kallithea/lib/helpers.py:1469
 #, python-format
 msgid ""
 "%s repository is not mapped to db perhaps it was created or renamed from "
@@ -1254,7 +1259,7 @@
 "zmienione z systemie plików proszę uruchomić aplikację ponownie, aby "
 "ponownie przeskanować repozytoria"
 
-#: kallithea/lib/utils2.py:415
+#: kallithea/lib/utils2.py:434
 #, python-format
 msgid "%d year"
 msgid_plural "%d years"
@@ -1262,7 +1267,7 @@
 msgstr[1] "%d lata"
 msgstr[2] "%d lat"
 
-#: kallithea/lib/utils2.py:416
+#: kallithea/lib/utils2.py:435
 #, python-format
 msgid "%d month"
 msgid_plural "%d months"
@@ -1270,7 +1275,7 @@
 msgstr[1] "%d miesięcy"
 msgstr[2] "%d miesięcy"
 
-#: kallithea/lib/utils2.py:417
+#: kallithea/lib/utils2.py:436
 #, python-format
 msgid "%d day"
 msgid_plural "%d days"
@@ -1278,7 +1283,7 @@
 msgstr[1] "%d dni"
 msgstr[2] "%d dni"
 
-#: kallithea/lib/utils2.py:418
+#: kallithea/lib/utils2.py:437
 #, python-format
 msgid "%d hour"
 msgid_plural "%d hours"
@@ -1286,7 +1291,7 @@
 msgstr[1] "%d godziny"
 msgstr[2] "%d godzin"
 
-#: kallithea/lib/utils2.py:419
+#: kallithea/lib/utils2.py:438
 #, python-format
 msgid "%d minute"
 msgid_plural "%d minutes"
@@ -1294,7 +1299,7 @@
 msgstr[1] "%d minuty"
 msgstr[2] "%d minut"
 
-#: kallithea/lib/utils2.py:420
+#: kallithea/lib/utils2.py:439
 #, python-format
 msgid "%d second"
 msgid_plural "%d seconds"
@@ -1302,27 +1307,27 @@
 msgstr[1] "%d sekund"
 msgstr[2] "%d sekund"
 
-#: kallithea/lib/utils2.py:436
+#: kallithea/lib/utils2.py:455
 #, python-format
 msgid "in %s"
 msgstr "w %s"
 
-#: kallithea/lib/utils2.py:438
+#: kallithea/lib/utils2.py:457
 #, python-format
 msgid "%s ago"
 msgstr "%s temu"
 
-#: kallithea/lib/utils2.py:440
+#: kallithea/lib/utils2.py:459
 #, python-format
 msgid "in %s and %s"
 msgstr "w %s i %s"
 
-#: kallithea/lib/utils2.py:443
+#: kallithea/lib/utils2.py:462
 #, python-format
 msgid "%s and %s ago"
 msgstr "%s i %s temu"
 
-#: kallithea/lib/utils2.py:446
+#: kallithea/lib/utils2.py:465
 msgid "just now"
 msgstr "przed chwilą"
 
@@ -1421,7 +1426,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1531
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1570
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1620
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1665
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1669
 msgid "Kallithea Administrator"
 msgstr "Administrator Repo"
 
@@ -1532,7 +1537,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2063
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2102
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2155
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2229
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2237
 msgid "Approved"
 msgstr "Zaakceptowano"
 
@@ -1547,7 +1552,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2064
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2103
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2156
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2230
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2238
 msgid "Rejected"
 msgstr "Odrzucono"
 
@@ -1574,7 +1579,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1379
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1418
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1471
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1518
 msgid "top level"
 msgstr "najwyższy poziom"
 
@@ -1721,7 +1726,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1560
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1599
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1651
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1697
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1701
 msgid "Registration disabled"
 msgstr "Rejestracja wyłączona"
 
@@ -1748,12 +1753,12 @@
 msgstr "Rejestracja użytkownika z automatyczną aktywacją konta"
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1645
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1691
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1695
 msgid "Repository creation enabled with write permission to a repository group"
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1646
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1692
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1696
 msgid "Repository creation disabled with write permission to a repository group"
 msgstr ""
 
@@ -1762,114 +1767,114 @@
 msgid "on line %s"
 msgstr "widziany %s"
 
-#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:169
+#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:170
 msgid "[Mention]"
 msgstr "[Wymieniony]"
 
-#: kallithea/model/db.py:1667
+#: kallithea/model/db.py:1671
 msgid "Default user has no access to new repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1668
+#: kallithea/model/db.py:1672
 #, fuzzy
 msgid "Default user has read access to new repositories"
 msgstr "Nieautoryzowany dostęp do zasobów"
 
-#: kallithea/model/db.py:1669
+#: kallithea/model/db.py:1673
 #, fuzzy
 msgid "Default user has write access to new repositories"
 msgstr "Nieautoryzowany dostęp do zasobów"
 
-#: kallithea/model/db.py:1670
+#: kallithea/model/db.py:1674
 msgid "Default user has admin access to new repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1672
+#: kallithea/model/db.py:1676
 msgid "Default user has no access to new repository groups"
 msgstr ""
 
-#: kallithea/model/db.py:1673
-msgid "Default user has read access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1674
-msgid "Default user has write access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1675
-msgid "Default user has admin access to new repository groups"
-msgstr ""
-
 #: kallithea/model/db.py:1677
-msgid "Default user has no access to new user groups"
+msgid "Default user has read access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1678
-msgid "Default user has read access to new user groups"
+msgid "Default user has write access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1679
-msgid "Default user has write access to new user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1680
-msgid "Default user has admin access to new user groups"
+msgid "Default user has admin access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1681
+msgid "Default user has no access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1682
+msgid "Default user has read access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1683
+msgid "Default user has write access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1684
+msgid "Default user has admin access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1686
 #, fuzzy
 msgid "Only admins can create repository groups"
 msgstr "Utworzono grupę repo %s"
 
-#: kallithea/model/db.py:1683
+#: kallithea/model/db.py:1687
 #, fuzzy
 msgid "Non-admins can create repository groups"
 msgstr "Utworzono grupę repo %s"
 
-#: kallithea/model/db.py:1685
+#: kallithea/model/db.py:1689
 #, fuzzy
 msgid "Only admins can create user groups"
 msgstr "Tworzenie grup użytkowników"
 
-#: kallithea/model/db.py:1686
+#: kallithea/model/db.py:1690
 #, fuzzy
 msgid "Non-admins can create user groups"
 msgstr "Tworzenie grup użytkowników"
 
-#: kallithea/model/db.py:1688
+#: kallithea/model/db.py:1692
 msgid "Only admins can create top level repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1689
+#: kallithea/model/db.py:1693
 msgid "Non-admins can create top level repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1694
+#: kallithea/model/db.py:1698
 #, fuzzy
 msgid "Only admins can fork repositories"
 msgstr "Ogólna liczba repozytoriów"
 
-#: kallithea/model/db.py:1695
-#, fuzzy
-msgid "Non-admins can can fork repositories"
+#: kallithea/model/db.py:1699
+#, fuzzy
+msgid "Non-admins can fork repositories"
 msgstr "Unieważnia cache dla wszystkich repozytoriów"
 
-#: kallithea/model/db.py:1698
+#: kallithea/model/db.py:1702
 #, fuzzy
 msgid "User registration with manual account activation"
 msgstr "Rejestracja użytkownika z ręczną aktywacją konta"
 
-#: kallithea/model/db.py:1699
+#: kallithea/model/db.py:1703
 #, fuzzy
 msgid "User registration with automatic account activation"
 msgstr "Rejestracja użytkownika z automatyczną aktywacją konta"
 
-#: kallithea/model/db.py:2228
+#: kallithea/model/db.py:2236
 #, fuzzy
 msgid "Not reviewed"
 msgstr "Brak Korekty"
 
-#: kallithea/model/db.py:2231
+#: kallithea/model/db.py:2239
 #, fuzzy
 msgid "Under review"
 msgstr "Objęty Przeglądem"
@@ -1892,7 +1897,7 @@
 msgid "Enter %(min)i characters or more"
 msgstr "Wpisz %(min)i lub więcej znaków"
 
-#: kallithea/model/forms.py:160
+#: kallithea/model/forms.py:165
 msgid "Name must not contain only digits"
 msgstr ""
 
@@ -1968,14 +1973,11 @@
 
 #: kallithea/model/notification.py:307
 #, fuzzy, python-format
-#| msgid "%(user)s wants you to review pull request %(pr_nice_id)s:
-#| %(pr_title)s"
 msgid "[Added] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
 msgstr "%(user)s chce żeby przejrzeć nowe gałęzie #%(pr_id)s: %(pr_title)s"
 
 #: kallithea/model/notification.py:308
 #, fuzzy, python-format
-#| msgid "[commented] on pull request for"
 msgid "[Comment] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
 msgstr "[komentarz] wniosek o połączenie gałęzi"
 
@@ -1989,7 +1991,7 @@
 msgid "%(user)s wants you to review pull request %(pr_nice_id)s: %(pr_title)s"
 msgstr "%(user)s chce żeby przejrzeć nowe gałęzie #%(pr_id)s: %(pr_title)s"
 
-#: kallithea/model/scm.py:812
+#: kallithea/model/scm.py:708
 msgid "latest tip"
 msgstr "ostatni tip"
 
@@ -2031,17 +2033,16 @@
 "użytkownik \"%s\" wciąż posiada repozytoria następujące %s i nie może "
 "zostać usunięty. Zmień właściciela lub usuń te repozytoria. %s"
 
-#: kallithea/model/user.py:360
+#: kallithea/model/user.py:368
 msgid "Password reset link"
 msgstr "łącze resetowania hasła"
 
-#: kallithea/model/user.py:408
-#, fuzzy
-#| msgid "Password reset link"
+#: kallithea/model/user.py:418
+#, fuzzy
 msgid "Password reset notification"
 msgstr "łącze resetowania hasła"
 
-#: kallithea/model/user.py:409
+#: kallithea/model/user.py:419
 #, python-format
 msgid ""
 "The password to your account %s has been changed using password reset "
@@ -2052,17 +2053,17 @@
 msgid "Value cannot be an empty list"
 msgstr "Wartość listy nie może być pusta"
 
-#: kallithea/model/validators.py:95
+#: kallithea/model/validators.py:96
 #, python-format
 msgid "Username \"%(username)s\" already exists"
 msgstr "Użytkownik \"%(username)s\" już istnieje"
 
-#: kallithea/model/validators.py:97
+#: kallithea/model/validators.py:98
 #, fuzzy, python-format
 msgid "Username \"%(username)s\" cannot be used"
 msgstr "Nazwa użytkownika %(username)s jest nieprawidłowa"
 
-#: kallithea/model/validators.py:99
+#: kallithea/model/validators.py:100
 #, fuzzy
 msgid ""
 "Username may only contain alphanumeric characters underscores, periods or"
@@ -2072,25 +2073,25 @@
 " kropki lub myślniki i muszą zaczynać się znakiem alfanumerycznym lub "
 "podkreśleniem"
 
-#: kallithea/model/validators.py:126
+#: kallithea/model/validators.py:127
 msgid "The input is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:133
+#: kallithea/model/validators.py:134
 #, python-format
 msgid "Username %(username)s is not valid"
 msgstr "Nazwa użytkownika %(username)s jest nieprawidłowa"
 
-#: kallithea/model/validators.py:152
+#: kallithea/model/validators.py:154
 msgid "Invalid user group name"
 msgstr "Niewłaściwa nazwa grupy"
 
-#: kallithea/model/validators.py:153
+#: kallithea/model/validators.py:155
 #, python-format
 msgid "User group \"%(usergroup)s\" already exists"
 msgstr "Nazwa grupy \"%(usergroup)s\" już istnieje"
 
-#: kallithea/model/validators.py:155
+#: kallithea/model/validators.py:157
 msgid ""
 "user group name may only contain alphanumeric characters underscores, "
 "periods or dashes and must begin with alphanumeric character"
@@ -2098,107 +2099,107 @@
 "nazwa grupy może zawierać tylko znaki alfanumeryczne, podkreślenia, "
 "kropki lub myślniki i musi zaczynać się znakiem alfanumerycznym"
 
-#: kallithea/model/validators.py:193
+#: kallithea/model/validators.py:197
 msgid "Cannot assign this group as parent"
 msgstr "Nie można przypisać do tej grupy jako rodzic"
 
-#: kallithea/model/validators.py:194
+#: kallithea/model/validators.py:198
 #, python-format
 msgid "Group \"%(group_name)s\" already exists"
 msgstr "Nazwa grupy \"%(group_name)s\" już istnieje"
 
-#: kallithea/model/validators.py:196
+#: kallithea/model/validators.py:200
 #, python-format
 msgid "Repository with name \"%(group_name)s\" already exists"
 msgstr "Repozytorium o nazwie \"%(group_name)s\" już istnieje"
 
-#: kallithea/model/validators.py:254
+#: kallithea/model/validators.py:258
 msgid "Invalid characters (non-ascii) in password"
 msgstr "Nieprawidłowe znaki (nie-ascii) w haśle"
 
-#: kallithea/model/validators.py:269
+#: kallithea/model/validators.py:273
 msgid "Invalid old password"
 msgstr ""
 
-#: kallithea/model/validators.py:285
+#: kallithea/model/validators.py:289
 msgid "Passwords do not match"
 msgstr "Hasła różnią się"
 
-#: kallithea/model/validators.py:300
+#: kallithea/model/validators.py:304
 #, fuzzy
 msgid "Invalid username or password"
 msgstr "nieprawidłowe hasło"
 
-#: kallithea/model/validators.py:331
+#: kallithea/model/validators.py:335
 msgid "Token mismatch"
 msgstr "Niezgodność tokenu"
 
-#: kallithea/model/validators.py:345
+#: kallithea/model/validators.py:351
 #, fuzzy, python-format
 msgid "Repository name %(repo)s is not allowed"
 msgstr "Nazwa repozytorium  %(repo)s jest zabroniona"
 
-#: kallithea/model/validators.py:347
+#: kallithea/model/validators.py:353
 #, python-format
 msgid "Repository named %(repo)s already exists"
 msgstr "Repozytorium o nazwie %(repo)s już istnieje"
 
-#: kallithea/model/validators.py:348
+#: kallithea/model/validators.py:354
 #, python-format
 msgid "Repository \"%(repo)s\" already exists in group \"%(group)s\""
 msgstr "Repozytorium  \"%(repo)s\" już istnieje w grupie \"%(group)s\""
 
-#: kallithea/model/validators.py:350
+#: kallithea/model/validators.py:356
 #, python-format
 msgid "Repository group with name \"%(repo)s\" already exists"
 msgstr "Grupa repozytoriów z nazwą \"%(repo)s\" już istnieje"
 
-#: kallithea/model/validators.py:465
+#: kallithea/model/validators.py:470
 #, fuzzy
 msgid "Invalid repository URL"
 msgstr "prywatne repozytorium"
 
-#: kallithea/model/validators.py:466
+#: kallithea/model/validators.py:471
 msgid ""
 "Invalid repository URL. It must be a valid http, https, ssh, svn+http or "
 "svn+https URL"
 msgstr ""
 
-#: kallithea/model/validators.py:489
+#: kallithea/model/validators.py:496
 msgid "Fork has to be the same type as parent"
 msgstr "Fork musi być tego samego typu, jak rodzic"
 
-#: kallithea/model/validators.py:504
+#: kallithea/model/validators.py:511
 msgid "You don't have permissions to create repository in this group"
 msgstr "Nie masz uprawnień do tworzenia repozytorium w tej grupie"
 
-#: kallithea/model/validators.py:506
+#: kallithea/model/validators.py:513
 msgid "no permission to create repository in root location"
 msgstr "nie masz uprawnień do tworzenia repozytorium w tej grupie"
 
-#: kallithea/model/validators.py:556
+#: kallithea/model/validators.py:563
 msgid "You don't have permissions to create a group in this location"
 msgstr "Nie masz uprawnień do tworzenia repozytorium w tej grupie"
 
-#: kallithea/model/validators.py:597
+#: kallithea/model/validators.py:604
 msgid "This username or user group name is not valid"
 msgstr "Ta nazwa użytkownika lub grupy użytkowników nie jest prawidłowa"
 
-#: kallithea/model/validators.py:690
+#: kallithea/model/validators.py:697
 msgid "This is not a valid path"
 msgstr "To nie jest prawidłowa ścieżka"
 
-#: kallithea/model/validators.py:705
+#: kallithea/model/validators.py:714
 #, fuzzy
 msgid "This email address is already in use"
 msgstr "Ten adres e-mail jest już zajęty"
 
-#: kallithea/model/validators.py:725
+#: kallithea/model/validators.py:734
 #, fuzzy, python-format
 msgid "Email address \"%(email)s\" not found"
 msgstr "e-mail \"%(email)s\" nie istnieje."
 
-#: kallithea/model/validators.py:762
+#: kallithea/model/validators.py:771
 msgid ""
 "The LDAP Login attribute of the CN must be specified - this is the name "
 "of the attribute that is equivalent to \"username\""
@@ -2206,26 +2207,26 @@
 "Atrybut logowania CN do LDAP należy określić, jest to nazwa atrybutu, "
 "który jest odpowiednikiem  \"username\""
 
-#: kallithea/model/validators.py:774
+#: kallithea/model/validators.py:783
 msgid "Please enter a valid IPv4 or IPv6 address"
 msgstr "Proszę podać poprawny adres IPv4 lub IPv6"
 
-#: kallithea/model/validators.py:775
+#: kallithea/model/validators.py:784
 #, python-format
 msgid "The network size (bits) must be within the range of 0-32 (not %(bits)r)"
 msgstr "Rozmiar sieci (bits) może mieścić się w zakresie od 0-32 (nie %(bits)r)"
 
-#: kallithea/model/validators.py:808
+#: kallithea/model/validators.py:817
 msgid "Key name can only consist of letters, underscore, dash or numbers"
 msgstr ""
 "Klucz nazwy może składać się tylko z liter, podkreślenia, myślnika lub "
 "numerów"
 
-#: kallithea/model/validators.py:822
+#: kallithea/model/validators.py:831
 msgid "Filename cannot be inside a directory"
 msgstr "Nazwa pliku nie może znajdować się w katalogu"
 
-#: kallithea/model/validators.py:838
+#: kallithea/model/validators.py:847
 #, python-format
 msgid "Plugins %(loaded)s and %(next_to_load)s both export the same name"
 msgstr ""
@@ -2352,7 +2353,7 @@
 #: kallithea/templates/admin/user_groups/user_groups.html:50
 #: kallithea/templates/pullrequests/pullrequest_data.html:16
 #: kallithea/templates/pullrequests/pullrequest_show.html:156
-#: kallithea/templates/pullrequests/pullrequest_show.html:233
+#: kallithea/templates/pullrequests/pullrequest_show.html:244
 #: kallithea/templates/summary/summary.html:134
 msgid "Owner"
 msgstr "Właściciel"
@@ -2400,7 +2401,7 @@
 #: kallithea/templates/index_base.html:144
 #: kallithea/templates/admin/my_account/my_account_repos.html:61
 #: kallithea/templates/admin/my_account/my_account_watched.html:61
-#: kallithea/templates/base/base.html:140 kallithea/templates/base/root.html:47
+#: kallithea/templates/base/root.html:47
 #: kallithea/templates/bookmarks/bookmarks.html:83
 #: kallithea/templates/branches/branches.html:83
 #: kallithea/templates/journal/journal.html:202
@@ -2410,7 +2411,7 @@
 msgstr "Wczytywanie..."
 
 #: kallithea/templates/login.html:5 kallithea/templates/login.html:15
-#: kallithea/templates/base/base.html:326
+#: kallithea/templates/base/base.html:414
 msgid "Log In"
 msgstr "Zaloguj się"
 
@@ -2425,7 +2426,7 @@
 #: kallithea/templates/admin/users/user_add.html:32
 #: kallithea/templates/admin/users/user_edit_profile.html:24
 #: kallithea/templates/admin/users/users.html:50
-#: kallithea/templates/base/base.html:302
+#: kallithea/templates/base/base.html:390
 #: kallithea/templates/pullrequests/pullrequest_show.html:166
 msgid "Username"
 msgstr "Nazwa użytkownika"
@@ -2433,7 +2434,7 @@
 #: kallithea/templates/login.html:33 kallithea/templates/register.html:33
 #: kallithea/templates/admin/my_account/my_account.html:37
 #: kallithea/templates/admin/users/user_add.html:41
-#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:399
 msgid "Password"
 msgstr "Hasło"
 
@@ -2445,7 +2446,7 @@
 msgid "Forgot your password ?"
 msgstr "Zapomniałeś hasła?"
 
-#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:322
+#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:410
 msgid "Don't have an account ?"
 msgstr "Nie masz konta?"
 
@@ -2486,8 +2487,6 @@
 
 #: kallithea/templates/password_reset.html:47
 #, fuzzy
-#| msgid "" "Password reset link will be sent to the email address matching
-#| your " "username."
 msgid ""
 "A password reset link will be sent to the specified email address if it "
 "is registered in the system."
@@ -2510,13 +2509,11 @@
 
 #: kallithea/templates/password_reset_confirmation.html:39
 #, fuzzy
-#| msgid "New password"
 msgid "New Password"
 msgstr "Nowe hasło"
 
 #: kallithea/templates/password_reset_confirmation.html:48
 #, fuzzy
-#| msgid "Your new password"
 msgid "Confirm New Password"
 msgstr "Nowe hasło"
 
@@ -2575,10 +2572,6 @@
 msgid "There are no branches yet"
 msgstr "Nie ma jeszcze gałęzi"
 
-#: kallithea/templates/switch_to_list.html:16
-msgid "Closed Branches"
-msgstr "Zamknięte Gałęzie"
-
 #: kallithea/templates/switch_to_list.html:32
 #: kallithea/templates/tags/tags_data.html:44
 msgid "There are no tags yet"
@@ -2812,12 +2805,12 @@
 msgid "Never"
 msgstr "nigdy"
 
-#: kallithea/templates/admin/gists/edit.html:145
+#: kallithea/templates/admin/gists/edit.html:146
 msgid "Update Gist"
 msgstr "Zaktualizuj Gist"
 
-#: kallithea/templates/admin/gists/edit.html:146
-#: kallithea/templates/changeset/changeset_file_comment.html:81
+#: kallithea/templates/admin/gists/edit.html:147
+#: kallithea/templates/changeset/changeset_file_comment.html:105
 msgid "Cancel"
 msgstr "Anuluj"
 
@@ -2840,7 +2833,7 @@
 
 #: kallithea/templates/admin/gists/index.html:37
 #: kallithea/templates/admin/gists/show.html:25
-#: kallithea/templates/base/base.html:237
+#: kallithea/templates/base/base.html:321
 msgid "Create New Gist"
 msgstr "Utwórz Nowy Gist"
 
@@ -2928,7 +2921,8 @@
 #: kallithea/templates/admin/settings/settings_hooks.html:36
 #: kallithea/templates/admin/users/user_edit_emails.html:19
 #: kallithea/templates/admin/users/user_edit_ips.html:22
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+#: kallithea/templates/changeset/changeset_file_comment.html:95
 #: kallithea/templates/data_table/_dt_elements.html:129
 #: kallithea/templates/data_table/_dt_elements.html:157
 #: kallithea/templates/data_table/_dt_elements.html:173
@@ -2948,8 +2942,6 @@
 #: kallithea/templates/base/perms_summary.html:43
 #: kallithea/templates/base/perms_summary.html:79
 #: kallithea/templates/base/perms_summary.html:81
-#: kallithea/templates/changeset/changeset_file_comment.html:83
-#: kallithea/templates/changeset/changeset_file_comment.html:192
 #: kallithea/templates/data_table/_dt_elements.html:122
 #: kallithea/templates/data_table/_dt_elements.html:123
 #: kallithea/templates/data_table/_dt_elements.html:150
@@ -2976,13 +2968,12 @@
 msgstr "utworzono"
 
 #: kallithea/templates/admin/gists/show.html:86
-#: kallithea/templates/files/files_source.html:73
 msgid "Show as raw"
 msgstr "wyświetl jako raw"
 
 #: kallithea/templates/admin/my_account/my_account.html:5
 #: kallithea/templates/admin/my_account/my_account.html:9
-#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:431
 msgid "My Account"
 msgstr "Moje konto"
 
@@ -3175,7 +3166,7 @@
 msgstr "Komentarze"
 
 #: kallithea/templates/admin/notifications/notifications.html:26
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 msgid "Pull Requests"
 msgstr "Połączone gałęzie"
 
@@ -3195,7 +3186,7 @@
 msgstr "Pokaż powiadomienia"
 
 #: kallithea/templates/admin/notifications/show_notification.html:9
-#: kallithea/templates/base/base.html:342
+#: kallithea/templates/base/base.html:430
 msgid "Notifications"
 msgstr "Powiadomienia"
 
@@ -3410,7 +3401,7 @@
 #: kallithea/templates/admin/repos/repo_edit.html:40
 #: kallithea/templates/admin/settings/settings.html:11
 #: kallithea/templates/admin/user_groups/user_group_edit.html:29
-#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:151
+#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:148
 #: kallithea/templates/data_table/_dt_elements.html:45
 #: kallithea/templates/data_table/_dt_elements.html:49
 msgid "Settings"
@@ -3695,6 +3686,11 @@
 msgid "Unlock Repository"
 msgstr "Odblokowane repozytorium"
 
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:56
+#, python-format
+msgid "Locked by %s on %s"
+msgstr ""
+
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:60
 #, fuzzy
 msgid "Confirm to lock repository."
@@ -3756,11 +3752,6 @@
 msgid "Invalidate Repository Cache"
 msgstr "Unieważnij pamięć podręczną repozytorium"
 
-#: kallithea/templates/admin/repos/repo_edit_caches.html:4
-#, fuzzy
-msgid "Confirm to invalidate repository cache."
-msgstr "Potwierdź unieważnienie pamięci podręcznej repozytorium"
-
 #: kallithea/templates/admin/repos/repo_edit_caches.html:7
 #, fuzzy
 msgid ""
@@ -4522,22 +4513,18 @@
 msgid "Files"
 msgstr "Pliki"
 
-#: kallithea/templates/base/base.html:138
-msgid "Switch To"
-msgstr "Przełącz do"
-
-#: kallithea/templates/base/base.html:145
-#: kallithea/templates/base/base.html:147
+#: kallithea/templates/base/base.html:142
+#: kallithea/templates/base/base.html:144
 msgid "Options"
 msgstr "Opcje"
 
-#: kallithea/templates/base/base.html:155
+#: kallithea/templates/base/base.html:152
 #: kallithea/templates/forks/forks_data.html:21
 #, fuzzy
 msgid "Compare Fork"
 msgstr "Porównaj rozwidlenie"
 
-#: kallithea/templates/base/base.html:157
+#: kallithea/templates/base/base.html:154
 #: kallithea/templates/bookmarks/bookmarks.html:56
 #: kallithea/templates/bookmarks/bookmarks_data.html:13
 #: kallithea/templates/branches/branches.html:56
@@ -4547,117 +4534,122 @@
 msgid "Compare"
 msgstr "Porównaj"
 
-#: kallithea/templates/base/base.html:159
-#: kallithea/templates/base/base.html:247
+#: kallithea/templates/base/base.html:156
+#: kallithea/templates/base/base.html:331
 #: kallithea/templates/search/search.html:14
 #: kallithea/templates/search/search.html:54
 msgid "Search"
 msgstr "Szukaj"
 
-#: kallithea/templates/base/base.html:163
+#: kallithea/templates/base/base.html:160
 msgid "Unlock"
 msgstr "Odblokowany"
 
-#: kallithea/templates/base/base.html:165
+#: kallithea/templates/base/base.html:162
 msgid "Lock"
 msgstr "zablokowane"
 
-#: kallithea/templates/base/base.html:173
+#: kallithea/templates/base/base.html:170
 msgid "Follow"
 msgstr "Obserwuj"
 
+#: kallithea/templates/base/base.html:171
+msgid "Unfollow"
+msgstr "Nie obserwuj"
+
 #: kallithea/templates/base/base.html:174
-msgid "Unfollow"
-msgstr "Nie obserwuj"
-
-#: kallithea/templates/base/base.html:177
 #: kallithea/templates/data_table/_dt_elements.html:37
 #: kallithea/templates/data_table/_dt_elements.html:41
 #: kallithea/templates/forks/fork.html:9
 msgid "Fork"
 msgstr "Gałąź"
 
-#: kallithea/templates/base/base.html:178
+#: kallithea/templates/base/base.html:175
 #: kallithea/templates/pullrequests/pullrequest.html:88
 msgid "Create Pull Request"
 msgstr "Stwórz nowe żądanie połączenia gałęzi"
 
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 #, python-format
 msgid "Show Pull Requests for %s"
 msgstr "Pokaż Prośby Pobrania %s"
 
-#: kallithea/templates/base/base.html:221
+#: kallithea/templates/base/base.html:193
+msgid "Switch To"
+msgstr "Przełącz do"
+
+#: kallithea/templates/base/base.html:203
+#: kallithea/templates/base/base.html:485
+msgid "No matches found"
+msgstr ""
+
+#: kallithea/templates/base/base.html:305
 msgid "Show recent activity"
 msgstr "Pokaż ostatnią aktywność"
 
-#: kallithea/templates/base/base.html:227
-#: kallithea/templates/base/base.html:228
+#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:312
 msgid "Public journal"
 msgstr "Dziennik publiczny"
 
-#: kallithea/templates/base/base.html:233
+#: kallithea/templates/base/base.html:317
 msgid "Show public gists"
 msgstr "Wyświetl publiczne gists"
 
-#: kallithea/templates/base/base.html:234
+#: kallithea/templates/base/base.html:318
 msgid "Gists"
 msgstr "Gists"
 
-#: kallithea/templates/base/base.html:238
+#: kallithea/templates/base/base.html:322
 #, fuzzy
 msgid "All Public Gists"
 msgstr "Wszystkie publiczne gists"
 
-#: kallithea/templates/base/base.html:240
+#: kallithea/templates/base/base.html:324
 #, fuzzy
 msgid "My Public Gists"
 msgstr "Moje publiczne gists"
 
-#: kallithea/templates/base/base.html:241
+#: kallithea/templates/base/base.html:325
 #, fuzzy
 msgid "My Private Gists"
 msgstr "Moje prywatne gists"
 
-#: kallithea/templates/base/base.html:246
+#: kallithea/templates/base/base.html:330
 msgid "Search in repositories"
 msgstr "Szukaj we wszystkich repozytoriach"
 
-#: kallithea/templates/base/base.html:269
-#: kallithea/templates/base/base.html:270
+#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:354
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:6
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:10
 #, fuzzy
 msgid "My Pull Requests"
 msgstr "Połączone gałęzie"
 
-#: kallithea/templates/base/base.html:289
+#: kallithea/templates/base/base.html:377
 #, fuzzy
 msgid "Not Logged In"
 msgstr "Zaloguj się"
 
-#: kallithea/templates/base/base.html:296
+#: kallithea/templates/base/base.html:384
 #, fuzzy
 msgid "Login to Your Account"
 msgstr "Zaloguj się do swojego konta"
 
-#: kallithea/templates/base/base.html:319
+#: kallithea/templates/base/base.html:407
 msgid "Forgot password ?"
 msgstr "Nie pamiętasz hasła?"
 
-#: kallithea/templates/base/base.html:346
+#: kallithea/templates/base/base.html:434
 msgid "Log Out"
 msgstr "Wyloguj się"
 
-#: kallithea/templates/base/base.html:395
-msgid "No matches found"
-msgstr ""
-
-#: kallithea/templates/base/base.html:524
+#: kallithea/templates/base/base.html:615
 msgid "Keyboard shortcuts"
 msgstr ""
 
-#: kallithea/templates/base/base.html:533
+#: kallithea/templates/base/base.html:624
 msgid "Site-wide shortcuts"
 msgstr ""
 
@@ -4766,7 +4758,6 @@
 
 #: kallithea/templates/base/root.html:31
 #, fuzzy
-#| msgid "on pull request"
 msgid "Open New Pull Request from {0}"
 msgstr "Komentarz połączenia gałęzi %s"
 
@@ -4776,7 +4767,6 @@
 
 #: kallithea/templates/base/root.html:33
 #, fuzzy
-#| msgid "Show Selected Changesets __S &rarr; __E"
 msgid "Show Selected Changesets {0} &rarr; {1}"
 msgstr "Pokaż wybrane zmiany __S -> __E"
 
@@ -4787,6 +4777,7 @@
 
 #: kallithea/templates/base/root.html:35
 #: kallithea/templates/changeset/diff_block.html:8
+#: kallithea/templates/changeset/diff_block.html:21
 #, fuzzy
 msgid "Collapse Diff"
 msgstr "Pliki różnic"
@@ -4901,52 +4892,56 @@
 #: kallithea/templates/changelog/changelog.html:92
 #: kallithea/templates/changelog/changelog_summary_data.html:20
 #, fuzzy, python-format
+#| msgid "" "Changeset status: %s\n" "Click to open associated pull request %s"
 msgid ""
-"Changeset status: %s\n"
+"Changeset status: %s by %s\n"
 "Click to open associated pull request %s"
 msgstr "Status grupy zmian: %s⏎ Kliknij, aby otworzyć prośby pobrania #%s"
 
 #: kallithea/templates/changelog/changelog.html:96
-#: kallithea/templates/compare/compare_cs.html:24
-#, python-format
-msgid "Changeset status: %s"
+#: kallithea/templates/changelog/changelog_summary_data.html:24
+#, fuzzy, python-format
+#| msgid "Changeset status: %s"
+msgid "Changeset status: %s by %s"
 msgstr "Status grupy zmian: %s"
 
-#: kallithea/templates/changelog/changelog.html:115
+#: kallithea/templates/changelog/changelog.html:116
 #: kallithea/templates/compare/compare_cs.html:63
 msgid "Expand commit message"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:124
+#: kallithea/templates/changelog/changelog.html:125
 #: kallithea/templates/compare/compare_cs.html:30
 msgid "Changeset has comments"
 msgstr "Komentarze Grupy zmian"
 
-#: kallithea/templates/changelog/changelog.html:134
-#: kallithea/templates/changelog/changelog_summary_data.html:54
+#: kallithea/templates/changelog/changelog.html:135
+#: kallithea/templates/changelog/changelog_summary_data.html:57
 #: kallithea/templates/changeset/changeset.html:94
 #: kallithea/templates/changeset/changeset_range.html:92
 #, python-format
 msgid "Bookmark %s"
 msgstr "Zakładki %s"
 
-#: kallithea/templates/changelog/changelog.html:140
-#: kallithea/templates/changelog/changelog_summary_data.html:60
+#: kallithea/templates/changelog/changelog.html:141
+#: kallithea/templates/changelog/changelog_summary_data.html:63
 #: kallithea/templates/changeset/changeset.html:101
 #: kallithea/templates/changeset/changeset_range.html:98
+#: kallithea/templates/compare/compare_cs.html:69
+#: kallithea/templates/pullrequests/pullrequest_show.html:203
 #, python-format
 msgid "Tag %s"
 msgstr "Tagi %s"
 
-#: kallithea/templates/changelog/changelog.html:145
-#: kallithea/templates/changelog/changelog_summary_data.html:65
+#: kallithea/templates/changelog/changelog.html:146
+#: kallithea/templates/changelog/changelog_summary_data.html:68
 #: kallithea/templates/changeset/changeset.html:106
 #: kallithea/templates/changeset/changeset_range.html:102
 #, python-format
 msgid "Branch %s"
 msgstr "Gałęzie %s"
 
-#: kallithea/templates/changelog/changelog.html:310
+#: kallithea/templates/changelog/changelog.html:311
 msgid "There are no changes yet"
 msgstr "Nie ma jeszcze zmian"
 
@@ -4962,7 +4957,7 @@
 
 #: kallithea/templates/changelog/changelog_details.html:6
 #: kallithea/templates/changeset/changeset.html:79
-#: kallithea/templates/changeset/diff_block.html:79
+#: kallithea/templates/changeset/diff_block.html:47
 msgid "Added"
 msgstr "Dodana"
 
@@ -4992,22 +4987,22 @@
 msgid "Refs"
 msgstr "Gałąź/Etykieta"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:81
+#: kallithea/templates/changelog/changelog_summary_data.html:84
 msgid "Add or upload files directly via Kallithea"
 msgstr "Dodaj lub prześlij pliki bezpośrednio przez stronę"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:84
+#: kallithea/templates/changelog/changelog_summary_data.html:87
 #: kallithea/templates/files/files_add.html:21
 #: kallithea/templates/files/files_ypjax.html:9
 msgid "Add New File"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:90
+#: kallithea/templates/changelog/changelog_summary_data.html:93
 #, fuzzy
 msgid "Push new repository"
 msgstr "Wyślij zmiany do nowego repo"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:98
+#: kallithea/templates/changelog/changelog_summary_data.html:101
 msgid "Existing repository?"
 msgstr "Istniejące repozytorium?"
 
@@ -5025,13 +5020,13 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:50
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #: kallithea/templates/changeset/changeset_range.html:48
 msgid "Changeset status"
 msgstr "Status grupy zmian"
 
 #: kallithea/templates/changeset/changeset.html:54
-#: kallithea/templates/changeset/diff_block.html:27
+#: kallithea/templates/changeset/diff_block.html:72
 #: kallithea/templates/files/diff_2way.html:49
 msgid "Raw diff"
 msgstr "Raw różnic"
@@ -5041,7 +5036,7 @@
 msgstr "Poprawka różnic"
 
 #: kallithea/templates/changeset/changeset.html:60
-#: kallithea/templates/changeset/diff_block.html:30
+#: kallithea/templates/changeset/diff_block.html:75
 #: kallithea/templates/files/diff_2way.html:52
 msgid "Download diff"
 msgstr "Pobierz różnice"
@@ -5072,8 +5067,8 @@
 msgstr "utworzono"
 
 #: kallithea/templates/changeset/changeset.html:166
-#: kallithea/templates/compare/compare_diff.html:54
-#: kallithea/templates/pullrequests/pullrequest_show.html:318
+#: kallithea/templates/compare/compare_diff.html:60
+#: kallithea/templates/pullrequests/pullrequest_show.html:329
 #, python-format
 msgid "%s file changed"
 msgid_plural "%s files changed"
@@ -5082,8 +5077,8 @@
 msgstr[2] "%s plików zostało zmienionych"
 
 #: kallithea/templates/changeset/changeset.html:168
-#: kallithea/templates/compare/compare_diff.html:56
-#: kallithea/templates/pullrequests/pullrequest_show.html:320
+#: kallithea/templates/compare/compare_diff.html:62
+#: kallithea/templates/pullrequests/pullrequest_show.html:331
 #, python-format
 msgid "%s file changed with %s insertions and %s deletions"
 msgid_plural "%s files changed with %s insertions and %s deletions"
@@ -5093,14 +5088,14 @@
 
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 #, fuzzy
 msgid "Show full diff anyway"
 msgstr "Pokaż pełną historię"
 
-#: kallithea/templates/changeset/changeset.html:247
-#: kallithea/templates/changeset/changeset.html:284
+#: kallithea/templates/changeset/changeset.html:231
+#: kallithea/templates/changeset/changeset.html:268
 #, fuzzy
 msgid "No revisions"
 msgstr "rewizja"
@@ -5120,66 +5115,76 @@
 msgid "on this changeset"
 msgstr "Brak zestawienia zmian"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
 #, fuzzy
 msgid "Delete comment?"
 msgstr "%d komentarz"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #, fuzzy
 msgid "Status change"
 msgstr "Ostatnia aktywność"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:59
-msgid "Commenting on line {1}."
+#, fuzzy
+msgid "Commenting on line."
 msgstr "Komentując linię {1}."
 
 #: kallithea/templates/changeset/changeset_file_comment.html:60
-#: kallithea/templates/changeset/changeset_file_comment.html:148
-#, python-format
-msgid "Comments parsed using %s syntax with %s support."
-msgstr "Komentarze analizowane za pomocą %s składni od %s wsparcia."
-
-#: kallithea/templates/changeset/changeset_file_comment.html:62
-#, fuzzy
-msgid "Use @username inside this text to notify another user"
+#, fuzzy
+msgid ""
+"Comments are in plain text. Use @username inside this text to notify "
+"another user."
 msgstr ""
 "Użyj @username wewnątrz tego tekstu, aby wysłać powiadomienie do "
 "użytkownika strony"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:72
-#: kallithea/templates/changeset/changeset_file_comment.html:184
-msgid "Comment preview"
-msgstr "Podgląd komentarza"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:77
+#: kallithea/templates/changeset/changeset_file_comment.html:67
+#, fuzzy
+msgid "Set changeset status"
+msgstr "Zmiana statusu grupy zmian"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:69
+msgid "Vote for pull request status"
+msgstr "Zagłosuj na żądanie na grupę zmian"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:75
+#, fuzzy
+msgid "No change"
+msgstr "Bez zmian"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:88
+#, fuzzy
+msgid "Finish pull request"
+msgstr "Komentarz połączenia gałęzi %s"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:91
+#, fuzzy
+msgid "Close"
+msgstr "(zamknięty)"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:103
 #, fuzzy
 msgid "Submitting ..."
 msgstr "Przesyłanie..."
 
-#: kallithea/templates/changeset/changeset_file_comment.html:80
-#: kallithea/templates/changeset/changeset_file_comment.html:190
+#: kallithea/templates/changeset/changeset_file_comment.html:104
 msgid "Comment"
 msgstr "Komentarz"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:82
-#: kallithea/templates/changeset/changeset_file_comment.html:191
-msgid "Preview"
-msgstr "Podgląd"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "You need to be logged in to comment."
 msgstr "Musisz być zalogowany żeby komentarz."
 
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "Login now"
 msgstr "Zaloguj się teraz"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:94
+#: kallithea/templates/changeset/changeset_file_comment.html:116
 msgid "Hide"
 msgstr "Ukryj"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:106
+#: kallithea/templates/changeset/changeset_file_comment.html:128
 #, python-format
 msgid "%d comment"
 msgid_plural "%d comments"
@@ -5187,7 +5192,7 @@
 msgstr[1] "%d komentarzy"
 msgstr[2] "%d komentarzy"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:107
+#: kallithea/templates/changeset/changeset_file_comment.html:129
 #, fuzzy, python-format
 msgid "%d inline"
 msgid_plural "%d inline"
@@ -5195,7 +5200,7 @@
 msgstr[1] "(%d linii)"
 msgstr[2] "(%d linii)"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:108
+#: kallithea/templates/changeset/changeset_file_comment.html:130
 #, fuzzy, python-format
 msgid "%d general"
 msgid_plural "%d general"
@@ -5203,32 +5208,6 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:150
-#, fuzzy
-msgid "Use @username inside this text to notify another user."
-msgstr ""
-"Użyj @username wewnątrz tego tekstu, aby wysłać powiadomienie do "
-"użytkownika strony"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:157
-msgid "Vote for pull request status"
-msgstr "Zagłosuj na żądanie na grupę zmian"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:159
-#, fuzzy
-msgid "Set changeset status"
-msgstr "Zmiana statusu grupy zmian"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:163
-#, fuzzy
-msgid "No change"
-msgstr "Bez zmian"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:176
-#, fuzzy
-msgid "Close"
-msgstr "(zamknięty)"
-
 #: kallithea/templates/changeset/changeset_range.html:5
 #, python-format
 msgid "%s Changesets"
@@ -5238,31 +5217,30 @@
 msgid "Files affected"
 msgstr "Pliki naruszone"
 
-#: kallithea/templates/changeset/diff_block.html:21
+#: kallithea/templates/changeset/diff_block.html:54
+#, fuzzy
+msgid "Deleted"
+msgstr "usuń"
+
+#: kallithea/templates/changeset/diff_block.html:57
+#, fuzzy
+msgid "Renamed"
+msgstr "zmień nazwę"
+
+#: kallithea/templates/changeset/diff_block.html:66
 #: kallithea/templates/files/diff_2way.html:43
 msgid "Show full diff for this file"
 msgstr "Pokaż pełną edycję tego pliku"
 
-#: kallithea/templates/changeset/diff_block.html:24
-#: kallithea/templates/changeset/diff_block.html:98
+#: kallithea/templates/changeset/diff_block.html:69
 #: kallithea/templates/files/diff_2way.html:46
 msgid "Show full side-by-side diff for this file"
 msgstr "Pokaż pełną listę zmian i różnic obok siebie"
 
-#: kallithea/templates/changeset/diff_block.html:38
+#: kallithea/templates/changeset/diff_block.html:83
 msgid "Show inline comments"
 msgstr "Pokaż online komentarz"
 
-#: kallithea/templates/changeset/diff_block.html:86
-#, fuzzy
-msgid "Deleted"
-msgstr "usuń"
-
-#: kallithea/templates/changeset/diff_block.html:89
-#, fuzzy
-msgid "Renamed"
-msgstr "zmień nazwę"
-
 #: kallithea/templates/compare/compare_cs.html:4
 msgid "No changesets"
 msgstr "Brak zestawienia zmian"
@@ -5271,6 +5249,11 @@
 msgid "Ancestor"
 msgstr "Przodek"
 
+#: kallithea/templates/compare/compare_cs.html:24
+#, python-format
+msgid "Changeset status: %s"
+msgstr "Status grupy zmian: %s"
+
 #: kallithea/templates/compare/compare_cs.html:44
 msgid "First (oldest) changeset in this list"
 msgstr ""
@@ -5283,32 +5266,32 @@
 msgid "Position in this list of changesets"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:76
+#: kallithea/templates/compare/compare_cs.html:85
 #, fuzzy
 msgid "Show merge diff"
 msgstr "Pokaż pełną historię"
 
-#: kallithea/templates/compare/compare_cs.html:86
-#: kallithea/templates/pullrequests/pullrequest_show.html:310
+#: kallithea/templates/compare/compare_cs.html:95
+#: kallithea/templates/pullrequests/pullrequest_show.html:321
 #, fuzzy
 msgid "Common ancestor"
 msgstr "Skomentuj grupę zmian"
 
-#: kallithea/templates/compare/compare_cs.html:90
+#: kallithea/templates/compare/compare_cs.html:99
 msgid "No common ancestor found - repositories are unrelated"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:98
+#: kallithea/templates/compare/compare_cs.html:107
 #, fuzzy
 msgid "is"
 msgstr "Gist"
 
-#: kallithea/templates/compare/compare_cs.html:99
+#: kallithea/templates/compare/compare_cs.html:108
 #, fuzzy, python-format
 msgid "%s changesets"
 msgstr "%s Zestawienie zmian"
 
-#: kallithea/templates/compare/compare_cs.html:100
+#: kallithea/templates/compare/compare_cs.html:109
 #, fuzzy
 msgid "behind"
 msgstr "Indeksuj ponownie"
@@ -5320,20 +5303,20 @@
 msgstr "%s Porównaj"
 
 #: kallithea/templates/compare/compare_diff.html:13
-#: kallithea/templates/compare/compare_diff.html:35
+#: kallithea/templates/compare/compare_diff.html:41
 msgid "Compare Revisions"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:33
+#: kallithea/templates/compare/compare_diff.html:39
 msgid "Swap"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:42
+#: kallithea/templates/compare/compare_diff.html:48
 msgid "Compare revisions, branches, bookmarks, or tags."
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:47
-#: kallithea/templates/pullrequests/pullrequest_show.html:305
+#: kallithea/templates/compare/compare_diff.html:53
+#: kallithea/templates/pullrequests/pullrequest_show.html:316
 #, python-format
 msgid "Showing %s commit"
 msgid_plural "Showing %s commits"
@@ -5341,8 +5324,8 @@
 msgstr[1] "Pokaż %s komentarze"
 msgstr[2] "Pokaż %s komentarze"
 
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
 msgid "Show full diff"
 msgstr "Pokaż pełną historię"
 
@@ -5399,21 +5382,26 @@
 
 #: kallithea/templates/email_templates/password_reset.html:6
 #, fuzzy
-#| msgid "We received a request to create a new password for your account."
 msgid "We have received a request to reset the password for your account."
 msgstr "Otrzymaliśmy prośbę o utworzenie nowego hasła do twojego konta."
 
-#: kallithea/templates/email_templates/password_reset.html:7
-msgid "To set a new password, click the following link"
+#: kallithea/templates/email_templates/password_reset.html:8
+msgid ""
+"This account is however managed outside this system and the password "
+"cannot be changed here."
 msgstr ""
 
 #: kallithea/templates/email_templates/password_reset.html:10
+msgid "To set a new password, click the following link"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:13
 msgid ""
 "Should you not be able to use the link above, please type the following "
 "code into the password reset form"
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:12
+#: kallithea/templates/email_templates/password_reset.html:16
 msgid ""
 "If it weren't you who requested the password reset, just disregard this "
 "message."
@@ -5498,8 +5486,9 @@
 msgstr ""
 
 #: kallithea/templates/files/files_add.html:53
-msgid "New file mode"
-msgstr "Nowy tryb pliku"
+#, fuzzy
+msgid "New file type"
+msgstr "nowy plik"
 
 #: kallithea/templates/files/files_add.html:64
 #: kallithea/templates/files/files_delete.html:43
@@ -5635,10 +5624,21 @@
 msgid "Binary file (%s)"
 msgstr "Plik binarny (%s)"
 
-#: kallithea/templates/files/files_source.html:73
-msgid "File is too big to display"
+#: kallithea/templates/files/files_source.html:74
+#, fuzzy
+msgid "File is too big to display."
 msgstr "Plik jest za duży do wyświetlenia"
 
+#: kallithea/templates/files/files_source.html:76
+#, fuzzy
+msgid "Show full annotation anyway."
+msgstr "Pokaż pełną historię"
+
+#: kallithea/templates/files/files_source.html:78
+#, fuzzy
+msgid "Show as raw."
+msgstr "wyświetl jako raw"
+
 #: kallithea/templates/files/files_ypjax.html:5
 msgid "annotation"
 msgstr "adnotacja"
@@ -5909,44 +5909,50 @@
 msgid "Current revision - no change"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:213
+#: kallithea/templates/pullrequests/pullrequest_show.html:215
+msgid ""
+"Pull requests do not change once created. Select a revision and save to "
+"replace this pull request with a new one."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:224
 #, fuzzy
 msgid "Pull Request Reviewers"
 msgstr "Recenzje wniosków połączenia gałęzi"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:238
+#: kallithea/templates/pullrequests/pullrequest_show.html:249
 #, fuzzy
 msgid "Remove reviewer"
 msgstr "recenzent"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:250
+#: kallithea/templates/pullrequests/pullrequest_show.html:261
 msgid "Type name of reviewer to add"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:258
+#: kallithea/templates/pullrequests/pullrequest_show.html:269
 #, fuzzy
 msgid "Potential Reviewers"
 msgstr "Podgląd komentarza"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:261
+#: kallithea/templates/pullrequests/pullrequest_show.html:272
 msgid "Click to add the repository owner as reviewer:"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:284
+#: kallithea/templates/pullrequests/pullrequest_show.html:295
 msgid "Save Changes"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:285
-#, fuzzy
-msgid "Save as New Pull Request"
+#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#, fuzzy
+msgid "Save Updates as New Pull Request"
 msgstr "Otwórz nową prośbę o połączenie gałęzi"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:286
+#: kallithea/templates/pullrequests/pullrequest_show.html:297
 #, fuzzy
 msgid "Cancel Changes"
 msgstr "Ostatnia aktywność"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#: kallithea/templates/pullrequests/pullrequest_show.html:307
 #, fuzzy
 msgid "Pull Request Content"
 msgstr "Wniosek połączenia zmienił status"
@@ -5958,7 +5964,7 @@
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:11
 #, fuzzy, python-format
-msgid "Pull Requests from %s'"
+msgid "Pull Requests from '%s'"
 msgstr "Połączonych gałęzi #%s"
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:13
@@ -6462,27 +6468,6 @@
 #~ msgid "reviewer"
 #~ msgstr "recenzent"
 
-#~ msgid ""
-#~ "Your password reset was successful, new"
-#~ " password has been sent to your "
-#~ "email"
-#~ msgstr "Twoje hasło zostało zresetowane, nowe hasło zostanie wysłane na e-mail"
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " changeset %(short_id)s on %(branch)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Added by %(pr_username)s] %(repo_name)s pull"
-#~ " request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " pull request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
 #~ msgid "Your new Kallithea password:%s"
 #~ msgstr "Nowe hasło do strony: %s"
 
@@ -6501,3 +6486,27 @@
 #~ msgid "Created by"
 #~ msgstr "utworzono"
 
+#~ msgid "You can only delete files with revision being a valid branch "
+#~ msgstr ""
+
+#~ msgid "This pull request can be updated with changes on %s:"
+#~ msgstr ""
+
+#~ msgid "Confirm to invalidate repository cache."
+#~ msgstr "Potwierdź unieważnienie pamięci podręcznej repozytorium"
+
+#~ msgid "Comments parsed using %s syntax with %s support."
+#~ msgstr "Komentarze analizowane za pomocą %s składni od %s wsparcia."
+
+#~ msgid "Use @username inside this text to notify another user"
+#~ msgstr ""
+
+#~ msgid "Comment preview"
+#~ msgstr "Podgląd komentarza"
+
+#~ msgid "Preview"
+#~ msgstr "Podgląd"
+
+#~ msgid "New file mode"
+#~ msgstr "Nowy tryb pliku"
+
--- a/kallithea/i18n/pt_BR/LC_MESSAGES/kallithea.po	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/i18n/pt_BR/LC_MESSAGES/kallithea.po	Fri Nov 18 01:11:13 2016 +0100
@@ -8,7 +8,7 @@
 msgstr ""
 "Project-Id-Version: Kallithea 0.3\n"
 "Report-Msgid-Bugs-To: translations@kallithea-scm.org\n"
-"POT-Creation-Date: 2015-09-08 10:34+0200\n"
+"POT-Creation-Date: 2016-03-14 16:51+0100\n"
 "PO-Revision-Date: 2014-02-13 14:34+0000\n"
 "Last-Translator: marcinkuzminski <marcin@python-blog.com>\n"
 "Language-Team: Portuguese (Brazil) "
@@ -18,12 +18,12 @@
 "Content-Type: text/plain; charset=UTF-8\n"
 "Content-Transfer-Encoding: 8bit\n"
 
-#: kallithea/controllers/changelog.py:86
-#: kallithea/controllers/pullrequests.py:238 kallithea/lib/base.py:512
+#: kallithea/controllers/changelog.py:85
+#: kallithea/controllers/pullrequests.py:240 kallithea/lib/base.py:515
 msgid "There are no changesets yet"
 msgstr "Não há nenhum changeset ainda"
 
-#: kallithea/controllers/changelog.py:166
+#: kallithea/controllers/changelog.py:164
 #: kallithea/controllers/admin/permissions.py:61
 #: kallithea/controllers/admin/permissions.py:65
 #: kallithea/controllers/admin/permissions.py:69
@@ -35,35 +35,29 @@
 msgid "None"
 msgstr "Nenhum"
 
-#: kallithea/controllers/changelog.py:169 kallithea/controllers/files.py:196
+#: kallithea/controllers/changelog.py:167 kallithea/controllers/files.py:198
 msgid "(closed)"
 msgstr "(fechado)"
 
-#: kallithea/controllers/changeset.py:89
+#: kallithea/controllers/changeset.py:88
 msgid "Show whitespace"
 msgstr "Mostrar espaços em branco"
 
-#: kallithea/controllers/changeset.py:96 kallithea/controllers/changeset.py:103
+#: kallithea/controllers/changeset.py:95 kallithea/controllers/changeset.py:102
 #: kallithea/templates/files/diff_2way.html:55
 msgid "Ignore whitespace"
 msgstr "Ignorar espaços em branco"
 
-#: kallithea/controllers/changeset.py:169
+#: kallithea/controllers/changeset.py:168
 #, python-format
 msgid "Increase diff context to %(num)s lines"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:212 kallithea/controllers/files.py:96
-#: kallithea/controllers/files.py:116 kallithea/controllers/files.py:742
+#: kallithea/controllers/changeset.py:233 kallithea/controllers/files.py:97
+#: kallithea/controllers/files.py:117 kallithea/controllers/files.py:744
 msgid "Such revision does not exist for this repository"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:383
-msgid ""
-"Changing status on a changeset associated with a closed pull request is "
-"not allowed"
-msgstr "Mudar o estado de um changeset associado a um pull request não é permitido"
-
 #: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:41
 msgid "Select changeset"
 msgstr ""
@@ -120,10 +114,10 @@
 #: kallithea/controllers/feed.py:87
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Changeset was too big and was cut off..."
 msgstr "Conjunto de mudanças era grande demais e foi cortado..."
 
@@ -132,111 +126,113 @@
 msgid "%s committed on %s"
 msgstr "%s commitados em %s"
 
-#: kallithea/controllers/files.py:91
+#: kallithea/controllers/files.py:92
 msgid "Click here to add new file"
 msgstr "Clique aqui para adicionar um novo arquivo"
 
-#: kallithea/controllers/files.py:92
+#: kallithea/controllers/files.py:93
 #, python-format
 msgid "There are no files yet. %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:193
+#: kallithea/controllers/files.py:195
 #, fuzzy, python-format
 msgid "%s at %s"
 msgstr "em %s e %s"
 
-#: kallithea/controllers/files.py:305 kallithea/controllers/files.py:365
-#: kallithea/controllers/files.py:432
+#: kallithea/controllers/files.py:307 kallithea/controllers/files.py:367
+#: kallithea/controllers/files.py:434
 #, python-format
 msgid "This repository has been locked by %s on %s"
 msgstr "Este repositório foi travado por %s em %s"
 
-#: kallithea/controllers/files.py:317
-msgid "You can only delete files with revision being a valid branch "
-msgstr ""
-
-#: kallithea/controllers/files.py:328
+#: kallithea/controllers/files.py:319
+#, fuzzy
+msgid "You can only delete files with revision being a valid branch"
+msgstr "Só é possível editar arquivos quando a revisão é um ramo válido"
+
+#: kallithea/controllers/files.py:330
 #, python-format
 msgid "Deleted file %s via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:350
+#: kallithea/controllers/files.py:352
 #, python-format
 msgid "Successfully deleted file %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:354 kallithea/controllers/files.py:420
-#: kallithea/controllers/files.py:501
+#: kallithea/controllers/files.py:356 kallithea/controllers/files.py:422
+#: kallithea/controllers/files.py:503
 msgid "Error occurred during commit"
 msgstr "Ocorreu um erro ao realizar commit"
 
-#: kallithea/controllers/files.py:377
-msgid "You can only edit files with revision being a valid branch "
+#: kallithea/controllers/files.py:379
+#, fuzzy
+msgid "You can only edit files with revision being a valid branch"
 msgstr "Só é possível editar arquivos quando a revisão é um ramo válido"
 
-#: kallithea/controllers/files.py:391
+#: kallithea/controllers/files.py:393
 #, python-format
 msgid "Edited file %s via Kallithea"
 msgstr "Arquivo %s editado via Kallithea"
 
-#: kallithea/controllers/files.py:407
+#: kallithea/controllers/files.py:409
 msgid "No changes"
 msgstr "Sem modificações"
 
-#: kallithea/controllers/files.py:416 kallithea/controllers/files.py:490
+#: kallithea/controllers/files.py:418 kallithea/controllers/files.py:492
 #, python-format
 msgid "Successfully committed to %s"
 msgstr "Commit realizado com sucesso para %s"
 
-#: kallithea/controllers/files.py:443
+#: kallithea/controllers/files.py:445
 msgid "Added file via Kallithea"
 msgstr "Arquivo adicionado via Kallithea"
 
-#: kallithea/controllers/files.py:464
+#: kallithea/controllers/files.py:466
 msgid "No content"
 msgstr "Nenhum conteúdo"
 
-#: kallithea/controllers/files.py:468
+#: kallithea/controllers/files.py:470
 msgid "No filename"
 msgstr "Nenhum nome de arquivo"
 
-#: kallithea/controllers/files.py:493
+#: kallithea/controllers/files.py:495
 msgid "Location must be relative path and must not contain .. in path"
 msgstr "O caminho deve ser relativo e não pode conter .."
 
-#: kallithea/controllers/files.py:526
+#: kallithea/controllers/files.py:528
 msgid "Downloads disabled"
 msgstr "Downloads desabilitados"
 
-#: kallithea/controllers/files.py:537
+#: kallithea/controllers/files.py:539
 #, python-format
 msgid "Unknown revision %s"
 msgstr "Revisão desconhecida %s"
 
-#: kallithea/controllers/files.py:539
+#: kallithea/controllers/files.py:541
 msgid "Empty repository"
 msgstr "Repositório vazio"
 
-#: kallithea/controllers/files.py:541
+#: kallithea/controllers/files.py:543
 msgid "Unknown archive type"
 msgstr "Tipo de arquivo desconhecido"
 
-#: kallithea/controllers/files.py:771
+#: kallithea/controllers/files.py:773
 #: kallithea/templates/changeset/changeset_range.html:9
 #: kallithea/templates/email_templates/pull_request.html:15
 #: kallithea/templates/pullrequests/pullrequest.html:97
 msgid "Changesets"
 msgstr "Conjuntos de mudanças"
 
-#: kallithea/controllers/files.py:772 kallithea/controllers/pullrequests.py:176
-#: kallithea/model/scm.py:820 kallithea/templates/switch_to_list.html:3
+#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:175
+#: kallithea/model/scm.py:716 kallithea/templates/switch_to_list.html:3
 #: kallithea/templates/branches/branches.html:10
 msgid "Branches"
 msgstr "Ramos"
 
-#: kallithea/controllers/files.py:773 kallithea/controllers/pullrequests.py:177
-#: kallithea/model/scm.py:831 kallithea/templates/switch_to_list.html:25
+#: kallithea/controllers/files.py:775 kallithea/controllers/pullrequests.py:176
+#: kallithea/model/scm.py:727 kallithea/templates/switch_to_list.html:25
 #: kallithea/templates/tags/tags.html:10
 msgid "Tags"
 msgstr "Etiquetas"
@@ -250,7 +246,7 @@
 msgid "Groups"
 msgstr ""
 
-#: kallithea/controllers/home.py:89
+#: kallithea/controllers/home.py:94
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:106
 #: kallithea/templates/admin/repos/repo_add.html:12
 #: kallithea/templates/admin/repos/repo_add.html:16
@@ -258,23 +254,27 @@
 #: kallithea/templates/admin/users/user_edit_advanced.html:6
 #: kallithea/templates/base/base.html:60 kallithea/templates/base/base.html:77
 #: kallithea/templates/base/base.html:124
-#: kallithea/templates/base/base.html:390
-#: kallithea/templates/base/base.html:562
+#: kallithea/templates/base/base.html:479
+#: kallithea/templates/base/base.html:653
 msgid "Repositories"
 msgstr "Repositórios"
 
-#: kallithea/controllers/home.py:130
+#: kallithea/controllers/home.py:139
 #: kallithea/templates/files/files_add.html:32
 #: kallithea/templates/files/files_delete.html:23
 #: kallithea/templates/files/files_edit.html:32
 msgid "Branch"
 msgstr "Ramo"
 
-#: kallithea/controllers/home.py:136
+#: kallithea/controllers/home.py:145 kallithea/templates/switch_to_list.html:16
+msgid "Closed Branches"
+msgstr "Ramos Fechados"
+
+#: kallithea/controllers/home.py:151
 msgid "Tag"
 msgstr ""
 
-#: kallithea/controllers/home.py:142
+#: kallithea/controllers/home.py:157
 msgid "Bookmark"
 msgstr ""
 
@@ -285,167 +285,170 @@
 msgstr "Diário Público"
 
 #: kallithea/controllers/journal.py:115 kallithea/controllers/journal.py:157
-#: kallithea/templates/base/base.html:222
+#: kallithea/templates/base/base.html:306
 #: kallithea/templates/journal/journal.html:4
 #: kallithea/templates/journal/journal.html:12
 msgid "Journal"
 msgstr "Diário"
 
-#: kallithea/controllers/login.py:151 kallithea/controllers/login.py:197
+#: kallithea/controllers/login.py:144 kallithea/controllers/login.py:190
 msgid "Bad captcha"
 msgstr ""
 
-#: kallithea/controllers/login.py:157
-msgid "You have successfully registered into Kallithea"
-msgstr "Você foi registrado no Kallithea com sucesso"
-
-#: kallithea/controllers/login.py:202
-#, fuzzy
-#| msgid "Your password reset link was sent"
+#: kallithea/controllers/login.py:150
+msgid "You have successfully registered with %s"
+msgstr "Você foi registrado no %s com sucesso"
+
+#: kallithea/controllers/login.py:195
+#, fuzzy
 msgid "A password reset confirmation code has been sent"
 msgstr "Seu link de reinicialização de senha foi enviado"
 
-#: kallithea/controllers/login.py:251
-#, fuzzy
-#| msgid "Password reset link"
+#: kallithea/controllers/login.py:244
+#, fuzzy
 msgid "Invalid password reset token"
 msgstr "Link para trocar senha"
 
-#: kallithea/controllers/login.py:256
+#: kallithea/controllers/login.py:249
 #: kallithea/controllers/admin/my_account.py:167
 msgid "Successfully updated password"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:124
+#: kallithea/controllers/pullrequests.py:123
 #, fuzzy, python-format
 msgid "%s (closed)"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:152
+#: kallithea/controllers/pullrequests.py:151
 #: kallithea/templates/changeset/changeset.html:12
 #: kallithea/templates/email_templates/changeset_comment.html:17
 msgid "Changeset"
 msgstr "Conjunto de Mudanças"
 
-#: kallithea/controllers/pullrequests.py:173
+#: kallithea/controllers/pullrequests.py:172
 msgid "Special"
 msgstr "Especial"
 
-#: kallithea/controllers/pullrequests.py:174
+#: kallithea/controllers/pullrequests.py:173
 msgid "Peer branches"
 msgstr "Ramos pares"
 
-#: kallithea/controllers/pullrequests.py:175 kallithea/model/scm.py:826
+#: kallithea/controllers/pullrequests.py:174 kallithea/model/scm.py:722
 #: kallithea/templates/switch_to_list.html:38
 #: kallithea/templates/bookmarks/bookmarks.html:10
 msgid "Bookmarks"
 msgstr "Marcadores"
 
-#: kallithea/controllers/pullrequests.py:310
+#: kallithea/controllers/pullrequests.py:312
 #, python-format
 msgid "Error creating pull request: %s"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:356
-#: kallithea/controllers/pullrequests.py:503
+#: kallithea/controllers/pullrequests.py:358
+#: kallithea/controllers/pullrequests.py:505
 #, fuzzy
 msgid "No description"
 msgstr "Descrição"
 
-#: kallithea/controllers/pullrequests.py:363
+#: kallithea/controllers/pullrequests.py:365
 msgid "Successfully opened new pull request"
 msgstr "Novo pull request criado com sucesso"
 
-#: kallithea/controllers/pullrequests.py:366
-#: kallithea/controllers/pullrequests.py:453
-#: kallithea/controllers/pullrequests.py:509
+#: kallithea/controllers/pullrequests.py:368
+#: kallithea/controllers/pullrequests.py:455
+#: kallithea/controllers/pullrequests.py:512
 #, python-format
 msgid "Invalid reviewer \"%s\" specified"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:369
-#: kallithea/controllers/pullrequests.py:456
+#: kallithea/controllers/pullrequests.py:371
+#: kallithea/controllers/pullrequests.py:458
 #, fuzzy
 msgid "Error occurred while creating pull request"
 msgstr "Ocorreu um erro durante o envio do pull request"
 
-#: kallithea/controllers/pullrequests.py:401
+#: kallithea/controllers/pullrequests.py:403
 msgid "Missing changesets since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:408
+#: kallithea/controllers/pullrequests.py:410
 #, python-format
 msgid "New changesets on %s %s since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:415
+#: kallithea/controllers/pullrequests.py:417
 msgid "Ancestor didn't change - show diff since previous version:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:422
+#: kallithea/controllers/pullrequests.py:424
 #, python-format
 msgid ""
 "This pull request is based on another %s revision and there is no simple "
 "diff."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:424
+#: kallithea/controllers/pullrequests.py:426
 #, python-format
 msgid "No changes found on %s %s since previous version."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:462
+#: kallithea/controllers/pullrequests.py:464
 #, python-format
 msgid "Closed, replaced by %s ."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:470
+#: kallithea/controllers/pullrequests.py:472
 #, fuzzy
 msgid "Pull request update created"
 msgstr "Revisores do pull request"
 
-#: kallithea/controllers/pullrequests.py:513
+#: kallithea/controllers/pullrequests.py:516
 #, fuzzy
 msgid "Pull request updated"
 msgstr "Pull requests para %s"
 
-#: kallithea/controllers/pullrequests.py:528
+#: kallithea/controllers/pullrequests.py:531
 msgid "Successfully deleted pull request"
 msgstr "Pull request excluído com sucesso"
 
-#: kallithea/controllers/pullrequests.py:594
+#: kallithea/controllers/pullrequests.py:597
 #, python-format
 msgid "This pull request has already been merged to %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:596
+#: kallithea/controllers/pullrequests.py:599
 msgid "This pull request has been closed and can not be updated."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:614
-#, python-format
-msgid "This pull request can be updated with changes on %s:"
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:617
+#, python-format
+msgid "The following changes are available on %s:"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:621
 msgid "No changesets found for updating this pull request."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:625
+#: kallithea/controllers/pullrequests.py:629
 #, python-format
 msgid "Note: Branch %s has another head: %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:631
+#: kallithea/controllers/pullrequests.py:635
 msgid "Git pull requests don't support updates yet."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:722
+#: kallithea/controllers/pullrequests.py:727
 #, fuzzy
 msgid "No permission to change pull request status"
 msgstr "Vote para estado do pull request"
 
-#: kallithea/controllers/pullrequests.py:727
+#: kallithea/controllers/pullrequests.py:738
+#, fuzzy, python-format
+msgid "Successfully deleted pull request %s"
+msgstr "Pull request excluído com sucesso"
+
+#: kallithea/controllers/pullrequests.py:748
 #, fuzzy
 msgid "Closing."
 msgstr "carregando ..."
@@ -463,13 +466,13 @@
 msgid "An error occurred during search operation."
 msgstr "Ocorreu um erro durante essa operação de busca"
 
-#: kallithea/controllers/summary.py:180
+#: kallithea/controllers/summary.py:181
 #: kallithea/templates/summary/summary.html:384
 #, fuzzy
 msgid "No data ready yet"
 msgstr "Ainda não há dados carregados"
 
-#: kallithea/controllers/summary.py:183
+#: kallithea/controllers/summary.py:184
 #: kallithea/templates/summary/summary.html:98
 msgid "Statistics are disabled for this repository"
 msgstr "As estatísticas estão desabillitadas para este repositório"
@@ -490,66 +493,66 @@
 msgid "Error occurred during update of defaults"
 msgstr "Ocorreu um erro durnge a atualização dos padrões"
 
-#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/gists.py:58
 #: kallithea/controllers/admin/my_account.py:243
-#: kallithea/controllers/admin/users.py:285
+#: kallithea/controllers/admin/users.py:284
 #, fuzzy
 msgid "Forever"
 msgstr "para sempre"
 
-#: kallithea/controllers/admin/gists.py:60
+#: kallithea/controllers/admin/gists.py:59
 #: kallithea/controllers/admin/my_account.py:244
-#: kallithea/controllers/admin/users.py:286
+#: kallithea/controllers/admin/users.py:285
 msgid "5 minutes"
 msgstr "cinco minutos"
 
+#: kallithea/controllers/admin/gists.py:60
+#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/users.py:286
+msgid "1 hour"
+msgstr "uma hora"
+
 #: kallithea/controllers/admin/gists.py:61
-#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/my_account.py:246
 #: kallithea/controllers/admin/users.py:287
-msgid "1 hour"
-msgstr "uma hora"
-
-#: kallithea/controllers/admin/gists.py:62
-#: kallithea/controllers/admin/my_account.py:246
-#: kallithea/controllers/admin/users.py:288
 msgid "1 day"
 msgstr "um dia"
 
-#: kallithea/controllers/admin/gists.py:63
+#: kallithea/controllers/admin/gists.py:62
 #: kallithea/controllers/admin/my_account.py:247
-#: kallithea/controllers/admin/users.py:289
+#: kallithea/controllers/admin/users.py:288
 msgid "1 month"
 msgstr "um mês"
 
-#: kallithea/controllers/admin/gists.py:67
+#: kallithea/controllers/admin/gists.py:66
 #: kallithea/controllers/admin/my_account.py:249
-#: kallithea/controllers/admin/users.py:291
+#: kallithea/controllers/admin/users.py:290
 msgid "Lifetime"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:146
+#: kallithea/controllers/admin/gists.py:145
 msgid "Error occurred during gist creation"
 msgstr "Ocorreu um erro durante a criação de um gist"
 
-#: kallithea/controllers/admin/gists.py:184
+#: kallithea/controllers/admin/gists.py:183
 #, python-format
 msgid "Deleted gist %s"
 msgstr "Gist %s excluído"
 
-#: kallithea/controllers/admin/gists.py:233
+#: kallithea/controllers/admin/gists.py:232
 #, fuzzy
 msgid "Unmodified"
 msgstr "Última alteração"
 
-#: kallithea/controllers/admin/gists.py:262
+#: kallithea/controllers/admin/gists.py:261
 msgid "Successfully updated gist content"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:267
+#: kallithea/controllers/admin/gists.py:266
 msgid "Successfully updated gist data"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:270
+#: kallithea/controllers/admin/gists.py:269
 #, python-format
 msgid "Error occurred during update of gist %s"
 msgstr ""
@@ -564,7 +567,7 @@
 msgstr "Sua conta foi atualizada com sucesso"
 
 #: kallithea/controllers/admin/my_account.py:144
-#: kallithea/controllers/admin/users.py:202
+#: kallithea/controllers/admin/users.py:201
 #, python-format
 msgid "Error occurred during update of user %s"
 msgstr "Ocorreu um erro durante a atualização do usuário %s"
@@ -574,33 +577,33 @@
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:220
-#: kallithea/controllers/admin/users.py:415
+#: kallithea/controllers/admin/users.py:414
 #, python-format
 msgid "Added email %s to user"
 msgstr "Email %s adicionado ao usuário"
 
 #: kallithea/controllers/admin/my_account.py:226
-#: kallithea/controllers/admin/users.py:421
+#: kallithea/controllers/admin/users.py:420
 msgid "An error occurred during email saving"
 msgstr "Ocorreu um erro durante o salvamento do email"
 
 #: kallithea/controllers/admin/my_account.py:235
-#: kallithea/controllers/admin/users.py:433
+#: kallithea/controllers/admin/users.py:432
 msgid "Removed email from user"
 msgstr "Email removido do usuário"
 
 #: kallithea/controllers/admin/my_account.py:259
-#: kallithea/controllers/admin/users.py:308
+#: kallithea/controllers/admin/users.py:307
 msgid "API key successfully created"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:271
-#: kallithea/controllers/admin/users.py:321
+#: kallithea/controllers/admin/users.py:320
 msgid "API key successfully reset"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:275
-#: kallithea/controllers/admin/users.py:325
+#: kallithea/controllers/admin/users.py:324
 msgid "API key successfully deleted"
 msgstr ""
 
@@ -650,10 +653,10 @@
 #: kallithea/templates/admin/users/user_edit_profile.html:105
 #: kallithea/templates/admin/users/users.html:10
 #: kallithea/templates/admin/users/users.html:55
-#: kallithea/templates/base/base.html:252
-#: kallithea/templates/base/base.html:253
-#: kallithea/templates/base/base.html:259
-#: kallithea/templates/base/base.html:260
+#: kallithea/templates/base/base.html:336
+#: kallithea/templates/base/base.html:337
+#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:344
 #: kallithea/templates/base/perms_summary.html:17
 msgid "Admin"
 msgstr "Administrador"
@@ -684,7 +687,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1564
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1603
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1655
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1701
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1705
 msgid "Manual activation of external account"
 msgstr "Ativação manual de conta externa"
 
@@ -696,7 +699,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1565
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1604
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1656
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1702
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1706
 msgid "Automatic activation of external account"
 msgstr "Ativação automática de conta externa"
 
@@ -717,244 +720,244 @@
 msgid "Error occurred during update of permissions"
 msgstr "Ocorreu um erro durante a atualização das permissões"
 
-#: kallithea/controllers/admin/repo_groups.py:188
+#: kallithea/controllers/admin/repo_groups.py:187
 #, python-format
 msgid "Error occurred during creation of repository group %s"
 msgstr "Ocorreu um erro durante a criação do grupo de repositórios %s"
 
-#: kallithea/controllers/admin/repo_groups.py:193
+#: kallithea/controllers/admin/repo_groups.py:192
 #, python-format
 msgid "Created repository group %s"
 msgstr "Grupo de repositórios %s criado"
 
-#: kallithea/controllers/admin/repo_groups.py:250
+#: kallithea/controllers/admin/repo_groups.py:249
 #, python-format
 msgid "Updated repository group %s"
 msgstr "Grupo de repositórios %s atualizado"
 
-#: kallithea/controllers/admin/repo_groups.py:266
+#: kallithea/controllers/admin/repo_groups.py:265
 #, python-format
 msgid "Error occurred during update of repository group %s"
 msgstr "Ocorreu um erro durante a atualização do grupo de repositórios %s"
 
-#: kallithea/controllers/admin/repo_groups.py:284
+#: kallithea/controllers/admin/repo_groups.py:283
 #, python-format
 msgid "This group contains %s repositories and cannot be deleted"
 msgstr "Esse grupo contém %s repositórios e não pode ser excluído"
 
-#: kallithea/controllers/admin/repo_groups.py:291
+#: kallithea/controllers/admin/repo_groups.py:290
 #, python-format
 msgid "This group contains %s subgroups and cannot be deleted"
 msgstr "Este grupo contém %s subgrupos e não pode ser excluído"
 
-#: kallithea/controllers/admin/repo_groups.py:297
+#: kallithea/controllers/admin/repo_groups.py:296
 #, python-format
 msgid "Removed repository group %s"
 msgstr "Grupo de repositórios %s excluído"
 
-#: kallithea/controllers/admin/repo_groups.py:302
+#: kallithea/controllers/admin/repo_groups.py:301
 #, python-format
 msgid "Error occurred during deletion of repository group %s"
 msgstr "Ocorreu um erro durante a exclusão do grupo de repositórios %s"
 
-#: kallithea/controllers/admin/repo_groups.py:405
-#: kallithea/controllers/admin/repo_groups.py:440
+#: kallithea/controllers/admin/repo_groups.py:404
+#: kallithea/controllers/admin/repo_groups.py:439
 #: kallithea/controllers/admin/user_groups.py:340
 msgid "Cannot revoke permission for yourself as admin"
 msgstr "Você não pode revocar sua própria permissão de administrador"
 
-#: kallithea/controllers/admin/repo_groups.py:420
+#: kallithea/controllers/admin/repo_groups.py:419
 msgid "Repository group permissions updated"
 msgstr "Permissões atualizadas do Grupo de Repositórios"
 
-#: kallithea/controllers/admin/repo_groups.py:457
-#: kallithea/controllers/admin/repos.py:398
+#: kallithea/controllers/admin/repo_groups.py:456
+#: kallithea/controllers/admin/repos.py:397
 #: kallithea/controllers/admin/user_groups.py:352
 msgid "An error occurred during revoking of permission"
 msgstr "Ocorreu um erro durante a revocação das permissões"
 
-#: kallithea/controllers/admin/repos.py:152
+#: kallithea/controllers/admin/repos.py:151
 #, python-format
 msgid "Error creating repository %s"
 msgstr "Erro ao criar repositório %s"
 
-#: kallithea/controllers/admin/repos.py:213
+#: kallithea/controllers/admin/repos.py:212
 #, python-format
 msgid "Created repository %s from %s"
 msgstr "Repositório %s criado de %s"
 
-#: kallithea/controllers/admin/repos.py:222
+#: kallithea/controllers/admin/repos.py:221
 #, python-format
 msgid "Forked repository %s as %s"
 msgstr "Repositório %s bifurcado como %s"
 
-#: kallithea/controllers/admin/repos.py:225
+#: kallithea/controllers/admin/repos.py:224
 #, python-format
 msgid "Created repository %s"
 msgstr "Repositório %s criado"
 
-#: kallithea/controllers/admin/repos.py:262
+#: kallithea/controllers/admin/repos.py:261
 #, python-format
 msgid "Repository %s updated successfully"
 msgstr "Repositório %s atualizado com sucesso"
 
-#: kallithea/controllers/admin/repos.py:283
+#: kallithea/controllers/admin/repos.py:282
 #, python-format
 msgid "Error occurred during update of repository %s"
 msgstr "Ocorreu um erro durante a atualização do repositório %s"
 
-#: kallithea/controllers/admin/repos.py:310
+#: kallithea/controllers/admin/repos.py:309
 #, python-format
 msgid "Detached %s forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:313
+#: kallithea/controllers/admin/repos.py:312
 #, python-format
 msgid "Deleted %s forks"
 msgstr "%s bifurcações excluídas"
 
-#: kallithea/controllers/admin/repos.py:318
+#: kallithea/controllers/admin/repos.py:317
 #, python-format
 msgid "Deleted repository %s"
 msgstr "Repositório %s excluído"
 
-#: kallithea/controllers/admin/repos.py:321
+#: kallithea/controllers/admin/repos.py:320
 #, fuzzy, python-format
 msgid "Cannot delete repository %s which still has forks"
 msgstr "Nao é possível excluir %s pois ele ainda contém bifurcações vinculadas"
 
-#: kallithea/controllers/admin/repos.py:326
+#: kallithea/controllers/admin/repos.py:325
 #, python-format
 msgid "An error occurred during deletion of %s"
 msgstr "Ocorreu um erro durante a exclusão de %s"
 
-#: kallithea/controllers/admin/repos.py:374
+#: kallithea/controllers/admin/repos.py:373
 msgid "Repository permissions updated"
 msgstr "Permissões do repositório atualizadas"
 
-#: kallithea/controllers/admin/repos.py:430
+#: kallithea/controllers/admin/repos.py:429
 msgid "An error occurred during creation of field"
 msgstr "Ocorreu um erro durante a criação do campo"
 
-#: kallithea/controllers/admin/repos.py:444
+#: kallithea/controllers/admin/repos.py:443
 msgid "An error occurred during removal of field"
 msgstr "Ocorreu um erro durante a remoção do campo"
 
-#: kallithea/controllers/admin/repos.py:460
+#: kallithea/controllers/admin/repos.py:459
 msgid "-- Not a fork --"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:491
+#: kallithea/controllers/admin/repos.py:490
 msgid "Updated repository visibility in public journal"
 msgstr "Atualizada a visibilidade do repositório no diário público"
 
-#: kallithea/controllers/admin/repos.py:495
+#: kallithea/controllers/admin/repos.py:494
 msgid "An error occurred during setting this repository in public journal"
 msgstr "Ocorreu um erro ao ajustar esse repositório no diário público"
 
-#: kallithea/controllers/admin/repos.py:512
+#: kallithea/controllers/admin/repos.py:511
 msgid "Nothing"
 msgstr "Nada"
 
-#: kallithea/controllers/admin/repos.py:514
+#: kallithea/controllers/admin/repos.py:513
 #, python-format
 msgid "Marked repository %s as fork of %s"
 msgstr "Marcado repositório %s como bifurcação de %s"
 
-#: kallithea/controllers/admin/repos.py:521
+#: kallithea/controllers/admin/repos.py:520
 msgid "An error occurred during this operation"
 msgstr "Ocorreu um erro durante essa operação"
 
-#: kallithea/controllers/admin/repos.py:537
-#: kallithea/controllers/admin/repos.py:564
+#: kallithea/controllers/admin/repos.py:536
+#: kallithea/controllers/admin/repos.py:563
 #, fuzzy
 msgid "Repository has been locked"
 msgstr "Repositório não está travado"
 
-#: kallithea/controllers/admin/repos.py:540
-#: kallithea/controllers/admin/repos.py:561
+#: kallithea/controllers/admin/repos.py:539
+#: kallithea/controllers/admin/repos.py:560
 #, fuzzy
 msgid "Repository has been unlocked"
 msgstr "Repositório não está travado"
 
-#: kallithea/controllers/admin/repos.py:543
-#: kallithea/controllers/admin/repos.py:568
+#: kallithea/controllers/admin/repos.py:542
+#: kallithea/controllers/admin/repos.py:567
 msgid "An error occurred during unlocking"
 msgstr "Ocorreu um erro durante o destravamento"
 
-#: kallithea/controllers/admin/repos.py:582
+#: kallithea/controllers/admin/repos.py:581
 msgid "Cache invalidation successful"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:586
+#: kallithea/controllers/admin/repos.py:585
 msgid "An error occurred during cache invalidation"
 msgstr "Ocorreu um erro ao invalidar o cache"
 
-#: kallithea/controllers/admin/repos.py:601
+#: kallithea/controllers/admin/repos.py:600
 msgid "Pulled from remote location"
 msgstr "Realizado pull de localização remota"
 
-#: kallithea/controllers/admin/repos.py:604
+#: kallithea/controllers/admin/repos.py:603
 msgid "An error occurred during pull from remote location"
 msgstr "Ocorreu um erro ao realizar pull de localização remota"
 
-#: kallithea/controllers/admin/repos.py:637
+#: kallithea/controllers/admin/repos.py:636
 msgid "An error occurred during deletion of repository stats"
 msgstr "Ocorreu um erro ao excluir estatísticas de repositório"
 
-#: kallithea/controllers/admin/settings.py:170
+#: kallithea/controllers/admin/settings.py:141
 msgid "Updated VCS settings"
 msgstr "Configurações de VCS atualizadas"
 
-#: kallithea/controllers/admin/settings.py:174
+#: kallithea/controllers/admin/settings.py:145
 msgid ""
 "Unable to activate hgsubversion support. The \"hgsubversion\" library is "
 "missing"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:180
-#: kallithea/controllers/admin/settings.py:277
+#: kallithea/controllers/admin/settings.py:151
+#: kallithea/controllers/admin/settings.py:248
 msgid "Error occurred while updating application settings"
 msgstr "Ocorreu um erro durante a atualização das configurações da aplicação"
 
-#: kallithea/controllers/admin/settings.py:216
+#: kallithea/controllers/admin/settings.py:187
 #, fuzzy, python-format
 msgid "Repositories successfully rescanned. Added: %s. Removed: %s."
 msgstr "Repositórios varridos com sucesso adicionados: %s ; removidos: %s"
 
-#: kallithea/controllers/admin/settings.py:273
+#: kallithea/controllers/admin/settings.py:244
 msgid "Updated application settings"
 msgstr "Configurações da aplicação atualizadas"
 
-#: kallithea/controllers/admin/settings.py:330
+#: kallithea/controllers/admin/settings.py:301
 msgid "Updated visualisation settings"
 msgstr "Configurações de visualização atualizadas"
 
-#: kallithea/controllers/admin/settings.py:335
+#: kallithea/controllers/admin/settings.py:306
 msgid "Error occurred during updating visualisation settings"
 msgstr "Ocorreu um erro durante a atualização das configurações de visualização"
 
-#: kallithea/controllers/admin/settings.py:361
+#: kallithea/controllers/admin/settings.py:332
 msgid "Please enter email address"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:376
+#: kallithea/controllers/admin/settings.py:347
 msgid "Send email task created"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:407
+#: kallithea/controllers/admin/settings.py:378
 msgid "Added new hook"
 msgstr "Adicionado novo gancho"
 
-#: kallithea/controllers/admin/settings.py:421
+#: kallithea/controllers/admin/settings.py:392
 msgid "Updated hooks"
 msgstr "Atualizados os ganchos"
 
-#: kallithea/controllers/admin/settings.py:425
+#: kallithea/controllers/admin/settings.py:396
 msgid "Error occurred during hook creation"
 msgstr "Ocorreu um erro durante a criação do hook"
 
-#: kallithea/controllers/admin/settings.py:451
+#: kallithea/controllers/admin/settings.py:422
 msgid "Whoosh reindex task scheduled"
 msgstr "Tarefa de reindexação do whoosh agendada"
 
@@ -995,76 +998,80 @@
 msgstr "Permissões do Grupo de Usuários atualizadas"
 
 #: kallithea/controllers/admin/user_groups.py:440
-#: kallithea/controllers/admin/users.py:384
+#: kallithea/controllers/admin/users.py:383
 msgid "Updated permissions"
 msgstr "Permissões atualizadas"
 
 #: kallithea/controllers/admin/user_groups.py:444
-#: kallithea/controllers/admin/users.py:388
+#: kallithea/controllers/admin/users.py:387
 msgid "An error occurred during permissions saving"
 msgstr "Ocorreu um erro durante o salvamento das permissões"
 
-#: kallithea/controllers/admin/users.py:134
+#: kallithea/controllers/admin/users.py:133
 #, python-format
 msgid "Created user %s"
 msgstr "Usuário %s criado"
 
-#: kallithea/controllers/admin/users.py:149
+#: kallithea/controllers/admin/users.py:148
 #, python-format
 msgid "Error occurred during creation of user %s"
 msgstr "Ocorreu um erro durante a criação do usuário %s"
 
-#: kallithea/controllers/admin/users.py:182
+#: kallithea/controllers/admin/users.py:181
 msgid "User updated successfully"
 msgstr "Usuário atualizado com sucesso"
 
-#: kallithea/controllers/admin/users.py:218
+#: kallithea/controllers/admin/users.py:217
 msgid "Successfully deleted user"
 msgstr "Usuário excluído com sucesso"
 
-#: kallithea/controllers/admin/users.py:223
+#: kallithea/controllers/admin/users.py:222
 msgid "An error occurred during deletion of user"
 msgstr "Ocorreu um erro ao excluir o usuário"
 
-#: kallithea/controllers/admin/users.py:236
+#: kallithea/controllers/admin/users.py:235
 msgid "The default user cannot be edited"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:463
+#: kallithea/controllers/admin/users.py:462
 #, python-format
 msgid "Added IP address %s to user whitelist"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:469
+#: kallithea/controllers/admin/users.py:468
 msgid "An error occurred while adding IP address"
 msgstr "Ocorreu um erro durante o salvamento do IP"
 
-#: kallithea/controllers/admin/users.py:483
+#: kallithea/controllers/admin/users.py:482
 msgid "Removed IP address from user whitelist"
 msgstr ""
 
-#: kallithea/lib/auth.py:743
+#: kallithea/lib/auth.py:737
 #, python-format
 msgid "IP %s not allowed"
 msgstr "IP %s não permitido"
 
-#: kallithea/lib/auth.py:756
+#: kallithea/lib/auth.py:750
 msgid "Invalid API key"
 msgstr ""
 
-#: kallithea/lib/auth.py:812
+#: kallithea/lib/auth.py:768
+msgid "CSRF token leak has been detected - all form tokens have been expired"
+msgstr ""
+
+#: kallithea/lib/auth.py:813
 msgid "You need to be a registered user to perform this action"
 msgstr "Você precisa ser um usuário registrado para realizar essa ação"
 
-#: kallithea/lib/auth.py:844
+#: kallithea/lib/auth.py:843
 msgid "You need to be signed in to view this page"
 msgstr "Você precisa estar logado para ver essa página"
 
-#: kallithea/lib/base.py:490
+#: kallithea/lib/base.py:493
 msgid "Repository not found in the filesystem"
 msgstr ""
 
-#: kallithea/lib/base.py:516 kallithea/lib/helpers.py:622
+#: kallithea/lib/base.py:519 kallithea/lib/helpers.py:623
 msgid "Changeset not found"
 msgstr "Conjunto de alterações não encontrado"
 
@@ -1082,126 +1089,126 @@
 msgid "No changes detected"
 msgstr "Nenhuma alteração detectada"
 
-#: kallithea/lib/helpers.py:609
+#: kallithea/lib/helpers.py:610
 #, python-format
 msgid "Deleted branch: %s"
 msgstr "Excluído ramo: %s"
 
-#: kallithea/lib/helpers.py:611
+#: kallithea/lib/helpers.py:612
 #, python-format
 msgid "Created tag: %s"
 msgstr "Tag criada: %s"
 
-#: kallithea/lib/helpers.py:671
+#: kallithea/lib/helpers.py:672
 #, python-format
 msgid "Show all combined changesets %s->%s"
 msgstr "Ver todos os conjuntos de mudanças combinados %s->%s"
 
-#: kallithea/lib/helpers.py:677
+#: kallithea/lib/helpers.py:678
 #, fuzzy
 msgid "Compare view"
 msgstr "comparar exibir"
 
-#: kallithea/lib/helpers.py:696
+#: kallithea/lib/helpers.py:697
 msgid "and"
 msgstr "e"
 
-#: kallithea/lib/helpers.py:697
+#: kallithea/lib/helpers.py:698
 #, python-format
 msgid "%s more"
 msgstr "%s mais"
 
-#: kallithea/lib/helpers.py:698 kallithea/templates/changelog/changelog.html:44
+#: kallithea/lib/helpers.py:699 kallithea/templates/changelog/changelog.html:44
 msgid "revisions"
 msgstr "revisões"
 
-#: kallithea/lib/helpers.py:722
+#: kallithea/lib/helpers.py:723
 #, fuzzy, python-format
 msgid "Fork name %s"
 msgstr "nome da bifurcação %s"
 
-#: kallithea/lib/helpers.py:742
+#: kallithea/lib/helpers.py:743
 #, fuzzy, python-format
 msgid "Pull request %s"
 msgstr "Pull request #%s"
 
-#: kallithea/lib/helpers.py:752
+#: kallithea/lib/helpers.py:753
 msgid "[deleted] repository"
 msgstr "repositório [excluído]"
 
-#: kallithea/lib/helpers.py:754 kallithea/lib/helpers.py:766
+#: kallithea/lib/helpers.py:755 kallithea/lib/helpers.py:767
 msgid "[created] repository"
 msgstr "repositório [criado]"
 
-#: kallithea/lib/helpers.py:756
+#: kallithea/lib/helpers.py:757
 msgid "[created] repository as fork"
 msgstr "repositório [criado] como uma bifurcação"
 
-#: kallithea/lib/helpers.py:758 kallithea/lib/helpers.py:768
+#: kallithea/lib/helpers.py:759 kallithea/lib/helpers.py:769
 msgid "[forked] repository"
 msgstr "repositório [bifurcado]"
 
-#: kallithea/lib/helpers.py:760 kallithea/lib/helpers.py:770
+#: kallithea/lib/helpers.py:761 kallithea/lib/helpers.py:771
 msgid "[updated] repository"
 msgstr "repositório [atualizado]"
 
-#: kallithea/lib/helpers.py:762
+#: kallithea/lib/helpers.py:763
 msgid "[downloaded] archive from repository"
 msgstr "[baixado] archive do repositório"
 
-#: kallithea/lib/helpers.py:764
+#: kallithea/lib/helpers.py:765
 msgid "[delete] repository"
 msgstr "[excluir] repositório"
 
-#: kallithea/lib/helpers.py:772
+#: kallithea/lib/helpers.py:773
 msgid "[created] user"
 msgstr "usuário [criado]"
 
-#: kallithea/lib/helpers.py:774
+#: kallithea/lib/helpers.py:775
 msgid "[updated] user"
 msgstr "usuário [atualizado]"
 
-#: kallithea/lib/helpers.py:776
+#: kallithea/lib/helpers.py:777
 msgid "[created] user group"
 msgstr "[criado] grupo de usuários"
 
-#: kallithea/lib/helpers.py:778
+#: kallithea/lib/helpers.py:779
 msgid "[updated] user group"
 msgstr "[atualizado] grupo de usuários"
 
-#: kallithea/lib/helpers.py:780
+#: kallithea/lib/helpers.py:781
 msgid "[commented] on revision in repository"
 msgstr "[comentado] em revisão no repositório"
 
-#: kallithea/lib/helpers.py:782
+#: kallithea/lib/helpers.py:783
 msgid "[commented] on pull request for"
 msgstr "[comentado] no pull request para"
 
-#: kallithea/lib/helpers.py:784
+#: kallithea/lib/helpers.py:785
 msgid "[closed] pull request for"
 msgstr "[fechado] pull request para"
 
-#: kallithea/lib/helpers.py:786
+#: kallithea/lib/helpers.py:787
 msgid "[pushed] into"
 msgstr "[realizado push] para"
 
-#: kallithea/lib/helpers.py:788
+#: kallithea/lib/helpers.py:789
 msgid "[committed via Kallithea] into repository"
 msgstr "[commitado via Kallithea] no repositório"
 
-#: kallithea/lib/helpers.py:790
+#: kallithea/lib/helpers.py:791
 msgid "[pulled from remote] into repository"
 msgstr "[pulled do remote] no repositório"
 
-#: kallithea/lib/helpers.py:792
+#: kallithea/lib/helpers.py:793
 msgid "[pulled] from"
 msgstr "[realizado pull] a partir de"
 
-#: kallithea/lib/helpers.py:794
+#: kallithea/lib/helpers.py:795
 msgid "[started following] repository"
 msgstr "[passou a seguir] o repositório"
 
-#: kallithea/lib/helpers.py:796
+#: kallithea/lib/helpers.py:797
 msgid "[stopped following] repository"
 msgstr "[parou de seguir] o repositório"
 
@@ -1211,8 +1218,8 @@
 msgstr " e mais %s"
 
 #: kallithea/lib/helpers.py:1128
-#: kallithea/templates/compare/compare_diff.html:65
-#: kallithea/templates/pullrequests/pullrequest_show.html:326
+#: kallithea/templates/compare/compare_diff.html:71
+#: kallithea/templates/pullrequests/pullrequest_show.html:337
 msgid "No files"
 msgstr "Nenhum arquivo"
 
@@ -1236,7 +1243,7 @@
 msgid "chmod"
 msgstr "chmod"
 
-#: kallithea/lib/helpers.py:1444
+#: kallithea/lib/helpers.py:1469
 #, python-format
 msgid ""
 "%s repository is not mapped to db perhaps it was created or renamed from "
@@ -1247,69 +1254,69 @@
 "renomeado a partir do sistema de arquivos. Por favor, execute a aplicação"
 " outra vez para varrer novamente por repositórios"
 
-#: kallithea/lib/utils2.py:415
+#: kallithea/lib/utils2.py:434
 #, python-format
 msgid "%d year"
 msgid_plural "%d years"
 msgstr[0] "%d ano"
 msgstr[1] "%d anos"
 
-#: kallithea/lib/utils2.py:416
+#: kallithea/lib/utils2.py:435
 #, python-format
 msgid "%d month"
 msgid_plural "%d months"
 msgstr[0] "%d mês"
 msgstr[1] "%d meses"
 
-#: kallithea/lib/utils2.py:417
+#: kallithea/lib/utils2.py:436
 #, python-format
 msgid "%d day"
 msgid_plural "%d days"
 msgstr[0] "%d dia"
 msgstr[1] "%d dias"
 
-#: kallithea/lib/utils2.py:418
+#: kallithea/lib/utils2.py:437
 #, python-format
 msgid "%d hour"
 msgid_plural "%d hours"
 msgstr[0] "%d hora"
 msgstr[1] "%d horas"
 
-#: kallithea/lib/utils2.py:419
+#: kallithea/lib/utils2.py:438
 #, python-format
 msgid "%d minute"
 msgid_plural "%d minutes"
 msgstr[0] "%d minuto"
 msgstr[1] "%d minutos"
 
-#: kallithea/lib/utils2.py:420
+#: kallithea/lib/utils2.py:439
 #, python-format
 msgid "%d second"
 msgid_plural "%d seconds"
 msgstr[0] "%d segundo"
 msgstr[1] "%d segundos"
 
-#: kallithea/lib/utils2.py:436
+#: kallithea/lib/utils2.py:455
 #, python-format
 msgid "in %s"
 msgstr "em %s"
 
-#: kallithea/lib/utils2.py:438
+#: kallithea/lib/utils2.py:457
 #, python-format
 msgid "%s ago"
 msgstr "%s atrás"
 
-#: kallithea/lib/utils2.py:440
+#: kallithea/lib/utils2.py:459
 #, python-format
 msgid "in %s and %s"
 msgstr "em %s e %s"
 
-#: kallithea/lib/utils2.py:443
+#: kallithea/lib/utils2.py:462
 #, python-format
 msgid "%s and %s ago"
 msgstr "%s e %s atrás"
 
-#: kallithea/lib/utils2.py:446
+#: kallithea/lib/utils2.py:465
 msgid "just now"
 msgstr "agora há pouco"
 
@@ -1408,7 +1415,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1531
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1570
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1620
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1665
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1669
 msgid "Kallithea Administrator"
 msgstr "Administrador do Kallithea"
 
@@ -1519,7 +1526,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2063
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2102
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2155
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2229
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2237
 msgid "Approved"
 msgstr "Aprovado"
 
@@ -1534,7 +1541,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2064
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2103
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2156
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2230
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2238
 msgid "Rejected"
 msgstr "Rejeitado"
 
@@ -1561,7 +1568,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1379
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1418
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1471
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1518
 msgid "top level"
 msgstr "nível superior"
 
@@ -1708,7 +1715,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1560
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1599
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1651
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1697
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1701
 msgid "Registration disabled"
 msgstr "Registro desatilitado"
 
@@ -1735,12 +1742,12 @@
 msgstr "Registro de Usuário com ativação automática de conta"
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1645
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1691
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1695
 msgid "Repository creation enabled with write permission to a repository group"
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1646
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1692
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1696
 msgid "Repository creation disabled with write permission to a repository group"
 msgstr ""
 
@@ -1749,114 +1756,114 @@
 msgid "on line %s"
 msgstr "na linha %s"
 
-#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:169
+#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:170
 msgid "[Mention]"
 msgstr "[Menção]"
 
-#: kallithea/model/db.py:1667
+#: kallithea/model/db.py:1671
 msgid "Default user has no access to new repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1668
+#: kallithea/model/db.py:1672
 #, fuzzy
 msgid "Default user has read access to new repositories"
 msgstr "Acesso não autorizado ao recurso"
 
-#: kallithea/model/db.py:1669
+#: kallithea/model/db.py:1673
 #, fuzzy
 msgid "Default user has write access to new repositories"
 msgstr "Acesso não autorizado ao recurso"
 
-#: kallithea/model/db.py:1670
+#: kallithea/model/db.py:1674
 msgid "Default user has admin access to new repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1672
+#: kallithea/model/db.py:1676
 msgid "Default user has no access to new repository groups"
 msgstr ""
 
-#: kallithea/model/db.py:1673
-msgid "Default user has read access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1674
-msgid "Default user has write access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1675
-msgid "Default user has admin access to new repository groups"
-msgstr ""
-
 #: kallithea/model/db.py:1677
-msgid "Default user has no access to new user groups"
+msgid "Default user has read access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1678
-msgid "Default user has read access to new user groups"
+msgid "Default user has write access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1679
-msgid "Default user has write access to new user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1680
-msgid "Default user has admin access to new user groups"
+msgid "Default user has admin access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1681
+msgid "Default user has no access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1682
+msgid "Default user has read access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1683
+msgid "Default user has write access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1684
+msgid "Default user has admin access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1686
 #, fuzzy
 msgid "Only admins can create repository groups"
 msgstr "Grupo de repositórios %s criado"
 
-#: kallithea/model/db.py:1683
+#: kallithea/model/db.py:1687
 #, fuzzy
 msgid "Non-admins can create repository groups"
 msgstr "Grupo de repositórios %s criado"
 
-#: kallithea/model/db.py:1685
+#: kallithea/model/db.py:1689
 #, fuzzy
 msgid "Only admins can create user groups"
 msgstr "Criar grupos de usuários"
 
-#: kallithea/model/db.py:1686
+#: kallithea/model/db.py:1690
 #, fuzzy
 msgid "Non-admins can create user groups"
 msgstr "Criar grupos de usuários"
 
-#: kallithea/model/db.py:1688
+#: kallithea/model/db.py:1692
 msgid "Only admins can create top level repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1689
+#: kallithea/model/db.py:1693
 msgid "Non-admins can create top level repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1694
+#: kallithea/model/db.py:1698
 #, fuzzy
 msgid "Only admins can fork repositories"
 msgstr "Criar repositórios"
 
-#: kallithea/model/db.py:1695
-#, fuzzy
-msgid "Non-admins can can fork repositories"
+#: kallithea/model/db.py:1699
+#, fuzzy
+msgid "Non-admins can fork repositories"
 msgstr "Invalidar o cache para todos os repositórios"
 
-#: kallithea/model/db.py:1698
+#: kallithea/model/db.py:1702
 #, fuzzy
 msgid "User registration with manual account activation"
 msgstr "Registro de Usuário com ativação manual de conta"
 
-#: kallithea/model/db.py:1699
+#: kallithea/model/db.py:1703
 #, fuzzy
 msgid "User registration with automatic account activation"
 msgstr "Registro de Usuário com ativação automática de conta"
 
-#: kallithea/model/db.py:2228
+#: kallithea/model/db.py:2236
 #, fuzzy
 msgid "Not reviewed"
 msgstr "Não Revisado"
 
-#: kallithea/model/db.py:2231
+#: kallithea/model/db.py:2239
 #, fuzzy
 msgid "Under review"
 msgstr "Sob Revisão"
@@ -1879,7 +1886,7 @@
 msgid "Enter %(min)i characters or more"
 msgstr "Entre com %(min)i caracteres ou mais"
 
-#: kallithea/model/forms.py:160
+#: kallithea/model/forms.py:165
 msgid "Name must not contain only digits"
 msgstr ""
 
@@ -1955,14 +1962,11 @@
 
 #: kallithea/model/notification.py:307
 #, fuzzy, python-format
-#| msgid "%(user)s wants you to review pull request %(pr_nice_id)s:
-#| %(pr_title)s"
 msgid "[Added] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
 msgstr "%(user)s solicita sua revisão no pull request $%(pr_id)s: %(pr_title)s"
 
 #: kallithea/model/notification.py:308
 #, fuzzy, python-format
-#| msgid "[commented] on pull request for"
 msgid "[Comment] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
 msgstr "[comentado] no pull request para"
 
@@ -1976,7 +1980,7 @@
 msgid "%(user)s wants you to review pull request %(pr_nice_id)s: %(pr_title)s"
 msgstr "%(user)s solicita sua revisão no pull request $%(pr_id)s: %(pr_title)s"
 
-#: kallithea/model/scm.py:812
+#: kallithea/model/scm.py:708
 msgid "latest tip"
 msgstr "tip mais recente"
 
@@ -2018,17 +2022,16 @@
 "usuário \"%s\" ainda é dono de %s repositórios e não pode ser removido. "
 "Troque os donos ou remova esses repositórios. %s"
 
-#: kallithea/model/user.py:360
+#: kallithea/model/user.py:368
 msgid "Password reset link"
 msgstr "Link para trocar senha"
 
-#: kallithea/model/user.py:408
-#, fuzzy
-#| msgid "Password reset link"
+#: kallithea/model/user.py:418
+#, fuzzy
 msgid "Password reset notification"
 msgstr "Link para trocar senha"
 
-#: kallithea/model/user.py:409
+#: kallithea/model/user.py:419
 #, python-format
 msgid ""
 "The password to your account %s has been changed using password reset "
@@ -2039,17 +2042,17 @@
 msgid "Value cannot be an empty list"
 msgstr "O valor não pode ser uma lista vazia"
 
-#: kallithea/model/validators.py:95
+#: kallithea/model/validators.py:96
 #, python-format
 msgid "Username \"%(username)s\" already exists"
 msgstr "O username \\\"%(username)s\\\" já existe"
 
-#: kallithea/model/validators.py:97
+#: kallithea/model/validators.py:98
 #, fuzzy, python-format
 msgid "Username \"%(username)s\" cannot be used"
 msgstr "O username \"%(username)s\" não é válido"
 
-#: kallithea/model/validators.py:99
+#: kallithea/model/validators.py:100
 #, fuzzy
 msgid ""
 "Username may only contain alphanumeric characters underscores, periods or"
@@ -2058,25 +2061,25 @@
 "Nome de usuário pode conter somente caracteres alfanuméricos, sublinha, "
 "pontos e hífens e deve iniciar com caractere alfanumérico"
 
-#: kallithea/model/validators.py:126
+#: kallithea/model/validators.py:127
 msgid "The input is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:133
+#: kallithea/model/validators.py:134
 #, python-format
 msgid "Username %(username)s is not valid"
 msgstr "O username \"%(username)s\" não é válido"
 
-#: kallithea/model/validators.py:152
+#: kallithea/model/validators.py:154
 msgid "Invalid user group name"
 msgstr "Nome inválido de grupo de usuários"
 
-#: kallithea/model/validators.py:153
+#: kallithea/model/validators.py:155
 #, python-format
 msgid "User group \"%(usergroup)s\" already exists"
 msgstr "O grupo de usuários \"%(usergroup)s\" já existe"
 
-#: kallithea/model/validators.py:155
+#: kallithea/model/validators.py:157
 msgid ""
 "user group name may only contain alphanumeric characters underscores, "
 "periods or dashes and must begin with alphanumeric character"
@@ -2085,107 +2088,107 @@
 "underscores, pontos ou hífens, e deve começar om um caractere alfa-"
 "numérico"
 
-#: kallithea/model/validators.py:193
+#: kallithea/model/validators.py:197
 msgid "Cannot assign this group as parent"
 msgstr "Não é possível associar esse grupo como progenitor"
 
-#: kallithea/model/validators.py:194
+#: kallithea/model/validators.py:198
 #, python-format
 msgid "Group \"%(group_name)s\" already exists"
 msgstr "O grupo \\\"%(group_name)s\\\" já existe"
 
-#: kallithea/model/validators.py:196
+#: kallithea/model/validators.py:200
 #, python-format
 msgid "Repository with name \"%(group_name)s\" already exists"
 msgstr "Um repositório com o nome \"%(group_name)s\" já existe"
 
-#: kallithea/model/validators.py:254
+#: kallithea/model/validators.py:258
 msgid "Invalid characters (non-ascii) in password"
 msgstr "Caracteres inválidos (não-ascii) na senha"
 
-#: kallithea/model/validators.py:269
+#: kallithea/model/validators.py:273
 msgid "Invalid old password"
 msgstr ""
 
-#: kallithea/model/validators.py:285
+#: kallithea/model/validators.py:289
 msgid "Passwords do not match"
 msgstr "Senhas não conferem"
 
-#: kallithea/model/validators.py:300
+#: kallithea/model/validators.py:304
 #, fuzzy
 msgid "Invalid username or password"
 msgstr "senha inválida"
 
-#: kallithea/model/validators.py:331
+#: kallithea/model/validators.py:335
 msgid "Token mismatch"
 msgstr "Descompasso de Token"
 
-#: kallithea/model/validators.py:345
+#: kallithea/model/validators.py:351
 #, fuzzy, python-format
 msgid "Repository name %(repo)s is not allowed"
 msgstr "O nome de repositório %(repo)s não é permitido"
 
-#: kallithea/model/validators.py:347
+#: kallithea/model/validators.py:353
 #, python-format
 msgid "Repository named %(repo)s already exists"
 msgstr "Um repositório chamado %(repo)s já existe"
 
-#: kallithea/model/validators.py:348
+#: kallithea/model/validators.py:354
 #, python-format
 msgid "Repository \"%(repo)s\" already exists in group \"%(group)s\""
 msgstr "Um repositório \"%(repo)s\" já existe no grupo \"%(group)s\""
 
-#: kallithea/model/validators.py:350
+#: kallithea/model/validators.py:356
 #, python-format
 msgid "Repository group with name \"%(repo)s\" already exists"
 msgstr "Um Grupo de Repositórios chamado \"%(repo)s\" já existe"
 
-#: kallithea/model/validators.py:465
+#: kallithea/model/validators.py:470
 #, fuzzy
 msgid "Invalid repository URL"
 msgstr "repositório privado"
 
-#: kallithea/model/validators.py:466
+#: kallithea/model/validators.py:471
 msgid ""
 "Invalid repository URL. It must be a valid http, https, ssh, svn+http or "
 "svn+https URL"
 msgstr ""
 
-#: kallithea/model/validators.py:489
+#: kallithea/model/validators.py:496
 msgid "Fork has to be the same type as parent"
 msgstr "A bifurcação deve ser do mesmo tipo que o pai"
 
-#: kallithea/model/validators.py:504
+#: kallithea/model/validators.py:511
 msgid "You don't have permissions to create repository in this group"
 msgstr "Você não tem permissão para criar um repositório neste grupo"
 
-#: kallithea/model/validators.py:506
+#: kallithea/model/validators.py:513
 msgid "no permission to create repository in root location"
 msgstr "você não tem permissão para criar um repositório na raiz"
 
-#: kallithea/model/validators.py:556
+#: kallithea/model/validators.py:563
 msgid "You don't have permissions to create a group in this location"
 msgstr "Você não tem permissão para criar um grupo neste local"
 
-#: kallithea/model/validators.py:597
+#: kallithea/model/validators.py:604
 msgid "This username or user group name is not valid"
 msgstr "Este nome de usuário ou de grupo de usuários não é válido"
 
-#: kallithea/model/validators.py:690
+#: kallithea/model/validators.py:697
 msgid "This is not a valid path"
 msgstr "Esse não é um caminho válido"
 
-#: kallithea/model/validators.py:705
+#: kallithea/model/validators.py:714
 #, fuzzy
 msgid "This email address is already in use"
 msgstr "Esse endereço de e-mail já está tomado"
 
-#: kallithea/model/validators.py:725
+#: kallithea/model/validators.py:734
 #, fuzzy, python-format
 msgid "Email address \"%(email)s\" not found"
 msgstr "o e-mail \"%(email)s\" não existe."
 
-#: kallithea/model/validators.py:762
+#: kallithea/model/validators.py:771
 msgid ""
 "The LDAP Login attribute of the CN must be specified - this is the name "
 "of the attribute that is equivalent to \"username\""
@@ -2193,24 +2196,24 @@
 "O atributo de login LDAP do CN deve ser especificado - isto é o nome do "
 "atributo que é equivalente ao 'nome de usuário'"
 
-#: kallithea/model/validators.py:774
+#: kallithea/model/validators.py:783
 msgid "Please enter a valid IPv4 or IPv6 address"
 msgstr "Por favor, forneça um endereço válido IPv4 ou IPv6"
 
-#: kallithea/model/validators.py:775
+#: kallithea/model/validators.py:784
 #, python-format
 msgid "The network size (bits) must be within the range of 0-32 (not %(bits)r)"
 msgstr "O tamanho da rede (bits) deve estar no intervalo 0-32 (não %(bits)r)"
 
-#: kallithea/model/validators.py:808
+#: kallithea/model/validators.py:817
 msgid "Key name can only consist of letters, underscore, dash or numbers"
 msgstr "O nome da chave só pode conter letras, underscore, hífen ou dígitos"
 
-#: kallithea/model/validators.py:822
+#: kallithea/model/validators.py:831
 msgid "Filename cannot be inside a directory"
 msgstr "O nome de arquivo não pode estar dentro de um diretório"
 
-#: kallithea/model/validators.py:838
+#: kallithea/model/validators.py:847
 #, python-format
 msgid "Plugins %(loaded)s and %(next_to_load)s both export the same name"
 msgstr ""
@@ -2337,7 +2340,7 @@
 #: kallithea/templates/admin/user_groups/user_groups.html:50
 #: kallithea/templates/pullrequests/pullrequest_data.html:16
 #: kallithea/templates/pullrequests/pullrequest_show.html:156
-#: kallithea/templates/pullrequests/pullrequest_show.html:233
+#: kallithea/templates/pullrequests/pullrequest_show.html:244
 #: kallithea/templates/summary/summary.html:134
 msgid "Owner"
 msgstr "Dono"
@@ -2385,7 +2388,7 @@
 #: kallithea/templates/index_base.html:144
 #: kallithea/templates/admin/my_account/my_account_repos.html:61
 #: kallithea/templates/admin/my_account/my_account_watched.html:61
-#: kallithea/templates/base/base.html:140 kallithea/templates/base/root.html:47
+#: kallithea/templates/base/root.html:47
 #: kallithea/templates/bookmarks/bookmarks.html:83
 #: kallithea/templates/branches/branches.html:83
 #: kallithea/templates/journal/journal.html:202
@@ -2395,7 +2398,7 @@
 msgstr "Carregando..."
 
 #: kallithea/templates/login.html:5 kallithea/templates/login.html:15
-#: kallithea/templates/base/base.html:326
+#: kallithea/templates/base/base.html:414
 msgid "Log In"
 msgstr "Entrar"
 
@@ -2410,7 +2413,7 @@
 #: kallithea/templates/admin/users/user_add.html:32
 #: kallithea/templates/admin/users/user_edit_profile.html:24
 #: kallithea/templates/admin/users/users.html:50
-#: kallithea/templates/base/base.html:302
+#: kallithea/templates/base/base.html:390
 #: kallithea/templates/pullrequests/pullrequest_show.html:166
 msgid "Username"
 msgstr "Nome de usuário"
@@ -2418,7 +2421,7 @@
 #: kallithea/templates/login.html:33 kallithea/templates/register.html:33
 #: kallithea/templates/admin/my_account/my_account.html:37
 #: kallithea/templates/admin/users/user_add.html:41
-#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:399
 msgid "Password"
 msgstr "Senha"
 
@@ -2430,7 +2433,7 @@
 msgid "Forgot your password ?"
 msgstr "Esqueceu sua senha ?"
 
-#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:322
+#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:410
 msgid "Don't have an account ?"
 msgstr "Não possui uma conta ?"
 
@@ -2471,8 +2474,6 @@
 
 #: kallithea/templates/password_reset.html:47
 #, fuzzy
-#| msgid "" "Password reset link will be sent to the email address matching
-#| your " "username."
 msgid ""
 "A password reset link will be sent to the specified email address if it "
 "is registered in the system."
@@ -2497,13 +2498,11 @@
 
 #: kallithea/templates/password_reset_confirmation.html:39
 #, fuzzy
-#| msgid "New password"
 msgid "New Password"
 msgstr "Nova senha"
 
 #: kallithea/templates/password_reset_confirmation.html:48
 #, fuzzy
-#| msgid "Your new password"
 msgid "Confirm New Password"
 msgstr "Sua nova senha"
 
@@ -2562,10 +2561,6 @@
 msgid "There are no branches yet"
 msgstr "Ainda não há ramos"
 
-#: kallithea/templates/switch_to_list.html:16
-msgid "Closed Branches"
-msgstr "Ramos Fechados"
-
 #: kallithea/templates/switch_to_list.html:32
 #: kallithea/templates/tags/tags_data.html:44
 msgid "There are no tags yet"
@@ -2798,12 +2793,12 @@
 msgid "Never"
 msgstr "nunca"
 
-#: kallithea/templates/admin/gists/edit.html:145
+#: kallithea/templates/admin/gists/edit.html:146
 msgid "Update Gist"
 msgstr ""
 
-#: kallithea/templates/admin/gists/edit.html:146
-#: kallithea/templates/changeset/changeset_file_comment.html:81
+#: kallithea/templates/admin/gists/edit.html:147
+#: kallithea/templates/changeset/changeset_file_comment.html:105
 msgid "Cancel"
 msgstr "Cancelar"
 
@@ -2826,7 +2821,7 @@
 
 #: kallithea/templates/admin/gists/index.html:37
 #: kallithea/templates/admin/gists/show.html:25
-#: kallithea/templates/base/base.html:237
+#: kallithea/templates/base/base.html:321
 msgid "Create New Gist"
 msgstr ""
 
@@ -2914,7 +2909,8 @@
 #: kallithea/templates/admin/settings/settings_hooks.html:36
 #: kallithea/templates/admin/users/user_edit_emails.html:19
 #: kallithea/templates/admin/users/user_edit_ips.html:22
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+#: kallithea/templates/changeset/changeset_file_comment.html:95
 #: kallithea/templates/data_table/_dt_elements.html:129
 #: kallithea/templates/data_table/_dt_elements.html:157
 #: kallithea/templates/data_table/_dt_elements.html:173
@@ -2934,8 +2930,6 @@
 #: kallithea/templates/base/perms_summary.html:43
 #: kallithea/templates/base/perms_summary.html:79
 #: kallithea/templates/base/perms_summary.html:81
-#: kallithea/templates/changeset/changeset_file_comment.html:83
-#: kallithea/templates/changeset/changeset_file_comment.html:192
 #: kallithea/templates/data_table/_dt_elements.html:122
 #: kallithea/templates/data_table/_dt_elements.html:123
 #: kallithea/templates/data_table/_dt_elements.html:150
@@ -2962,13 +2956,12 @@
 msgstr "criado"
 
 #: kallithea/templates/admin/gists/show.html:86
-#: kallithea/templates/files/files_source.html:73
 msgid "Show as raw"
 msgstr "Mostrar original"
 
 #: kallithea/templates/admin/my_account/my_account.html:5
 #: kallithea/templates/admin/my_account/my_account.html:9
-#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:431
 msgid "My Account"
 msgstr "Minha Conta"
 
@@ -3159,7 +3152,7 @@
 msgstr "Comentários"
 
 #: kallithea/templates/admin/notifications/notifications.html:26
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 msgid "Pull Requests"
 msgstr "Pull Requests"
 
@@ -3179,7 +3172,7 @@
 msgstr "Mostrar notificação"
 
 #: kallithea/templates/admin/notifications/show_notification.html:9
-#: kallithea/templates/base/base.html:342
+#: kallithea/templates/base/base.html:430
 msgid "Notifications"
 msgstr "Notificações"
 
@@ -3392,7 +3385,7 @@
 #: kallithea/templates/admin/repos/repo_edit.html:40
 #: kallithea/templates/admin/settings/settings.html:11
 #: kallithea/templates/admin/user_groups/user_group_edit.html:29
-#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:151
+#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:148
 #: kallithea/templates/data_table/_dt_elements.html:45
 #: kallithea/templates/data_table/_dt_elements.html:49
 msgid "Settings"
@@ -3680,6 +3673,11 @@
 msgid "Unlock Repository"
 msgstr "Repositório público"
 
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:56
+#, python-format
+msgid "Locked by %s on %s"
+msgstr ""
+
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:60
 #, fuzzy
 msgid "Confirm to lock repository."
@@ -3740,11 +3738,6 @@
 msgid "Invalidate Repository Cache"
 msgstr "Invalidar cache do repositório"
 
-#: kallithea/templates/admin/repos/repo_edit_caches.html:4
-#, fuzzy
-msgid "Confirm to invalidate repository cache."
-msgstr "Confirma invalidar cache do repositório"
-
 #: kallithea/templates/admin/repos/repo_edit_caches.html:7
 #, fuzzy
 msgid ""
@@ -4506,22 +4499,18 @@
 msgid "Files"
 msgstr "Arquivos"
 
-#: kallithea/templates/base/base.html:138
-msgid "Switch To"
-msgstr "Trocar Para"
-
-#: kallithea/templates/base/base.html:145
-#: kallithea/templates/base/base.html:147
+#: kallithea/templates/base/base.html:142
+#: kallithea/templates/base/base.html:144
 msgid "Options"
 msgstr "Opções"
 
-#: kallithea/templates/base/base.html:155
+#: kallithea/templates/base/base.html:152
 #: kallithea/templates/forks/forks_data.html:21
 #, fuzzy
 msgid "Compare Fork"
 msgstr "Compare bifurcação"
 
-#: kallithea/templates/base/base.html:157
+#: kallithea/templates/base/base.html:154
 #: kallithea/templates/bookmarks/bookmarks.html:56
 #: kallithea/templates/bookmarks/bookmarks_data.html:13
 #: kallithea/templates/branches/branches.html:56
@@ -4531,117 +4520,122 @@
 msgid "Compare"
 msgstr "Compare"
 
-#: kallithea/templates/base/base.html:159
-#: kallithea/templates/base/base.html:247
+#: kallithea/templates/base/base.html:156
+#: kallithea/templates/base/base.html:331
 #: kallithea/templates/search/search.html:14
 #: kallithea/templates/search/search.html:54
 msgid "Search"
 msgstr "Pesquisar"
 
-#: kallithea/templates/base/base.html:163
+#: kallithea/templates/base/base.html:160
 msgid "Unlock"
 msgstr "Destravar"
 
-#: kallithea/templates/base/base.html:165
+#: kallithea/templates/base/base.html:162
 msgid "Lock"
 msgstr "Travar"
 
-#: kallithea/templates/base/base.html:173
+#: kallithea/templates/base/base.html:170
 msgid "Follow"
 msgstr "Seguir"
 
+#: kallithea/templates/base/base.html:171
+msgid "Unfollow"
+msgstr "Parar de seguir"
+
 #: kallithea/templates/base/base.html:174
-msgid "Unfollow"
-msgstr "Parar de seguir"
-
-#: kallithea/templates/base/base.html:177
 #: kallithea/templates/data_table/_dt_elements.html:37
 #: kallithea/templates/data_table/_dt_elements.html:41
 #: kallithea/templates/forks/fork.html:9
 msgid "Fork"
 msgstr "Bifurcação"
 
-#: kallithea/templates/base/base.html:178
+#: kallithea/templates/base/base.html:175
 #: kallithea/templates/pullrequests/pullrequest.html:88
 msgid "Create Pull Request"
 msgstr "Criar Pull Request"
 
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 #, python-format
 msgid "Show Pull Requests for %s"
 msgstr "Mostrar Pull Requests para %s"
 
-#: kallithea/templates/base/base.html:221
+#: kallithea/templates/base/base.html:193
+msgid "Switch To"
+msgstr "Trocar Para"
+
+#: kallithea/templates/base/base.html:203
+#: kallithea/templates/base/base.html:485
+msgid "No matches found"
+msgstr ""
+
+#: kallithea/templates/base/base.html:305
 msgid "Show recent activity"
 msgstr "Mostrar atividade recente"
 
-#: kallithea/templates/base/base.html:227
-#: kallithea/templates/base/base.html:228
+#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:312
 msgid "Public journal"
 msgstr "Diário público"
 
-#: kallithea/templates/base/base.html:233
+#: kallithea/templates/base/base.html:317
 msgid "Show public gists"
 msgstr "Mostrar gists públicos"
 
-#: kallithea/templates/base/base.html:234
+#: kallithea/templates/base/base.html:318
 msgid "Gists"
 msgstr "Gists"
 
-#: kallithea/templates/base/base.html:238
+#: kallithea/templates/base/base.html:322
 #, fuzzy
 msgid "All Public Gists"
 msgstr "Todos os gists públicos"
 
-#: kallithea/templates/base/base.html:240
+#: kallithea/templates/base/base.html:324
 #, fuzzy
 msgid "My Public Gists"
 msgstr "Meus gists públicos"
 
-#: kallithea/templates/base/base.html:241
+#: kallithea/templates/base/base.html:325
 #, fuzzy
 msgid "My Private Gists"
 msgstr "Meus gists privados"
 
-#: kallithea/templates/base/base.html:246
+#: kallithea/templates/base/base.html:330
 msgid "Search in repositories"
 msgstr "Buscar nos repositórios"
 
-#: kallithea/templates/base/base.html:269
-#: kallithea/templates/base/base.html:270
+#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:354
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:6
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:10
 #, fuzzy
 msgid "My Pull Requests"
 msgstr "Pull requests"
 
-#: kallithea/templates/base/base.html:289
+#: kallithea/templates/base/base.html:377
 #, fuzzy
 msgid "Not Logged In"
 msgstr "Não logado"
 
-#: kallithea/templates/base/base.html:296
+#: kallithea/templates/base/base.html:384
 #, fuzzy
 msgid "Login to Your Account"
 msgstr "Entrar com sua conta"
 
-#: kallithea/templates/base/base.html:319
+#: kallithea/templates/base/base.html:407
 msgid "Forgot password ?"
 msgstr "Esqueceu a senha ?"
 
-#: kallithea/templates/base/base.html:346
+#: kallithea/templates/base/base.html:434
 msgid "Log Out"
 msgstr "Sair"
 
-#: kallithea/templates/base/base.html:395
-msgid "No matches found"
-msgstr ""
-
-#: kallithea/templates/base/base.html:524
+#: kallithea/templates/base/base.html:615
 msgid "Keyboard shortcuts"
 msgstr ""
 
-#: kallithea/templates/base/base.html:533
+#: kallithea/templates/base/base.html:624
 msgid "Site-wide shortcuts"
 msgstr ""
 
@@ -4750,7 +4744,6 @@
 
 #: kallithea/templates/base/root.html:31
 #, fuzzy
-#| msgid "on pull request"
 msgid "Open New Pull Request from {0}"
 msgstr "Comentar no pull request #%s"
 
@@ -4760,7 +4753,6 @@
 
 #: kallithea/templates/base/root.html:33
 #, fuzzy
-#| msgid "Show Selected Changesets __S &rarr; __E"
 msgid "Show Selected Changesets {0} &rarr; {1}"
 msgstr "Mostrar changesets selecionados __S -> __E"
 
@@ -4771,6 +4763,7 @@
 
 #: kallithea/templates/base/root.html:35
 #: kallithea/templates/changeset/diff_block.html:8
+#: kallithea/templates/changeset/diff_block.html:21
 #, fuzzy
 msgid "Collapse Diff"
 msgstr "Colapsar diff"
@@ -4884,54 +4877,58 @@
 #: kallithea/templates/changelog/changelog.html:92
 #: kallithea/templates/changelog/changelog_summary_data.html:20
 #, fuzzy, python-format
+#| msgid "" "Changeset status: %s\n" "Click to open associated pull request %s"
 msgid ""
-"Changeset status: %s\n"
+"Changeset status: %s by %s\n"
 "Click to open associated pull request %s"
 msgstr ""
 "Estado do changeset: %s\n"
 "Clique para abrir os pull request #%s associado"
 
 #: kallithea/templates/changelog/changelog.html:96
-#: kallithea/templates/compare/compare_cs.html:24
-#, python-format
-msgid "Changeset status: %s"
+#: kallithea/templates/changelog/changelog_summary_data.html:24
+#, fuzzy, python-format
+#| msgid "Changeset status: %s"
+msgid "Changeset status: %s by %s"
 msgstr "Estado do changeset: %s"
 
-#: kallithea/templates/changelog/changelog.html:115
+#: kallithea/templates/changelog/changelog.html:116
 #: kallithea/templates/compare/compare_cs.html:63
 msgid "Expand commit message"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:124
+#: kallithea/templates/changelog/changelog.html:125
 #: kallithea/templates/compare/compare_cs.html:30
 msgid "Changeset has comments"
 msgstr "O changeset tem comentários"
 
-#: kallithea/templates/changelog/changelog.html:134
-#: kallithea/templates/changelog/changelog_summary_data.html:54
+#: kallithea/templates/changelog/changelog.html:135
+#: kallithea/templates/changelog/changelog_summary_data.html:57
 #: kallithea/templates/changeset/changeset.html:94
 #: kallithea/templates/changeset/changeset_range.html:92
 #, python-format
 msgid "Bookmark %s"
 msgstr "Bookmark %s"
 
-#: kallithea/templates/changelog/changelog.html:140
-#: kallithea/templates/changelog/changelog_summary_data.html:60
+#: kallithea/templates/changelog/changelog.html:141
+#: kallithea/templates/changelog/changelog_summary_data.html:63
 #: kallithea/templates/changeset/changeset.html:101
 #: kallithea/templates/changeset/changeset_range.html:98
+#: kallithea/templates/compare/compare_cs.html:69
+#: kallithea/templates/pullrequests/pullrequest_show.html:203
 #, python-format
 msgid "Tag %s"
 msgstr "Tag %s"
 
-#: kallithea/templates/changelog/changelog.html:145
-#: kallithea/templates/changelog/changelog_summary_data.html:65
+#: kallithea/templates/changelog/changelog.html:146
+#: kallithea/templates/changelog/changelog_summary_data.html:68
 #: kallithea/templates/changeset/changeset.html:106
 #: kallithea/templates/changeset/changeset_range.html:102
 #, python-format
 msgid "Branch %s"
 msgstr "Ramo %s"
 
-#: kallithea/templates/changelog/changelog.html:310
+#: kallithea/templates/changelog/changelog.html:311
 msgid "There are no changes yet"
 msgstr "Ainda não há alteações"
 
@@ -4947,7 +4944,7 @@
 
 #: kallithea/templates/changelog/changelog_details.html:6
 #: kallithea/templates/changeset/changeset.html:79
-#: kallithea/templates/changeset/diff_block.html:79
+#: kallithea/templates/changeset/diff_block.html:47
 msgid "Added"
 msgstr "Adicionado"
 
@@ -4977,22 +4974,22 @@
 msgid "Refs"
 msgstr "Refs"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:81
+#: kallithea/templates/changelog/changelog_summary_data.html:84
 msgid "Add or upload files directly via Kallithea"
 msgstr "Adicionar ou enviar arquivos diretamente pelo Kallithea"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:84
+#: kallithea/templates/changelog/changelog_summary_data.html:87
 #: kallithea/templates/files/files_add.html:21
 #: kallithea/templates/files/files_ypjax.html:9
 msgid "Add New File"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:90
+#: kallithea/templates/changelog/changelog_summary_data.html:93
 #, fuzzy
 msgid "Push new repository"
 msgstr "Fazer push de novo repositório"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:98
+#: kallithea/templates/changelog/changelog_summary_data.html:101
 msgid "Existing repository?"
 msgstr "Repositório existente?"
 
@@ -5010,13 +5007,13 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:50
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #: kallithea/templates/changeset/changeset_range.html:48
 msgid "Changeset status"
 msgstr "Estado do changeset"
 
 #: kallithea/templates/changeset/changeset.html:54
-#: kallithea/templates/changeset/diff_block.html:27
+#: kallithea/templates/changeset/diff_block.html:72
 #: kallithea/templates/files/diff_2way.html:49
 msgid "Raw diff"
 msgstr "Diff cru"
@@ -5026,7 +5023,7 @@
 msgstr "D"
 
 #: kallithea/templates/changeset/changeset.html:60
-#: kallithea/templates/changeset/diff_block.html:30
+#: kallithea/templates/changeset/diff_block.html:75
 #: kallithea/templates/files/diff_2way.html:52
 msgid "Download diff"
 msgstr "Baixar diff"
@@ -5057,8 +5054,8 @@
 msgstr "criado"
 
 #: kallithea/templates/changeset/changeset.html:166
-#: kallithea/templates/compare/compare_diff.html:54
-#: kallithea/templates/pullrequests/pullrequest_show.html:318
+#: kallithea/templates/compare/compare_diff.html:60
+#: kallithea/templates/pullrequests/pullrequest_show.html:329
 #, python-format
 msgid "%s file changed"
 msgid_plural "%s files changed"
@@ -5066,8 +5063,8 @@
 msgstr[1] "%s arquivos modificados"
 
 #: kallithea/templates/changeset/changeset.html:168
-#: kallithea/templates/compare/compare_diff.html:56
-#: kallithea/templates/pullrequests/pullrequest_show.html:320
+#: kallithea/templates/compare/compare_diff.html:62
+#: kallithea/templates/pullrequests/pullrequest_show.html:331
 #, python-format
 msgid "%s file changed with %s insertions and %s deletions"
 msgid_plural "%s files changed with %s insertions and %s deletions"
@@ -5076,14 +5073,14 @@
 
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 #, fuzzy
 msgid "Show full diff anyway"
 msgstr "Mostrar diff completo"
 
-#: kallithea/templates/changeset/changeset.html:247
-#: kallithea/templates/changeset/changeset.html:284
+#: kallithea/templates/changeset/changeset.html:231
+#: kallithea/templates/changeset/changeset.html:268
 #, fuzzy
 msgid "No revisions"
 msgstr "revisões"
@@ -5103,112 +5100,96 @@
 msgid "on this changeset"
 msgstr "Nenhum changeset"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
 #, fuzzy
 msgid "Delete comment?"
 msgstr "%d comentário"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #, fuzzy
 msgid "Status change"
 msgstr "Mudanças mais recentes"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:59
-msgid "Commenting on line {1}."
+#, fuzzy
+msgid "Commenting on line."
 msgstr "Comentando a linha {1}."
 
 #: kallithea/templates/changeset/changeset_file_comment.html:60
-#: kallithea/templates/changeset/changeset_file_comment.html:148
-#, python-format
-msgid "Comments parsed using %s syntax with %s support."
-msgstr "Comentários interpretados usando a sintaxe %s com suporte a %s."
-
-#: kallithea/templates/changeset/changeset_file_comment.html:62
-#, fuzzy
-msgid "Use @username inside this text to notify another user"
+#, fuzzy
+msgid ""
+"Comments are in plain text. Use @username inside this text to notify "
+"another user."
 msgstr ""
 "Use @nomedeusuário dentro desse texto para enviar notificação a este "
 "usuário do Kallithea"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:72
-#: kallithea/templates/changeset/changeset_file_comment.html:184
-msgid "Comment preview"
-msgstr "Visualizar comentário"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:77
+#: kallithea/templates/changeset/changeset_file_comment.html:67
+#, fuzzy
+msgid "Set changeset status"
+msgstr "Altere o estado do changeset"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:69
+msgid "Vote for pull request status"
+msgstr "Vote para estado do pull request"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:75
+#, fuzzy
+msgid "No change"
+msgstr "Sem modificações"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:88
+#, fuzzy
+msgid "Finish pull request"
+msgstr "Comentar no pull request #%s"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:91
+#, fuzzy
+msgid "Close"
+msgstr "(fechado)"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:103
 #, fuzzy
 msgid "Submitting ..."
 msgstr "Enviando..."
 
-#: kallithea/templates/changeset/changeset_file_comment.html:80
-#: kallithea/templates/changeset/changeset_file_comment.html:190
+#: kallithea/templates/changeset/changeset_file_comment.html:104
 msgid "Comment"
 msgstr "Comentário"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:82
-#: kallithea/templates/changeset/changeset_file_comment.html:191
-msgid "Preview"
-msgstr "Visualizar"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "You need to be logged in to comment."
 msgstr "Você precisa estar logado para comentar."
 
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "Login now"
 msgstr "Entrar agora"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:94
+#: kallithea/templates/changeset/changeset_file_comment.html:116
 msgid "Hide"
 msgstr "Ocultar"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:106
+#: kallithea/templates/changeset/changeset_file_comment.html:128
 #, python-format
 msgid "%d comment"
 msgid_plural "%d comments"
 msgstr[0] "%d comentário"
 msgstr[1] "%d comentários"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:107
+#: kallithea/templates/changeset/changeset_file_comment.html:129
 #, fuzzy, python-format
 msgid "%d inline"
 msgid_plural "%d inline"
 msgstr[0] "(%d em linha)"
 msgstr[1] "(%d em linha)"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:108
+#: kallithea/templates/changeset/changeset_file_comment.html:130
 #, fuzzy, python-format
 msgid "%d general"
 msgid_plural "%d general"
 msgstr[0] ""
 msgstr[1] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:150
-#, fuzzy
-msgid "Use @username inside this text to notify another user."
-msgstr ""
-"Use @nomedeusuário dentro desse texto para enviar notificação a este "
-"usuário do Kallithea"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:157
-msgid "Vote for pull request status"
-msgstr "Vote para estado do pull request"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:159
-#, fuzzy
-msgid "Set changeset status"
-msgstr "Altere o estado do changeset"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:163
-#, fuzzy
-msgid "No change"
-msgstr "Sem modificações"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:176
-#, fuzzy
-msgid "Close"
-msgstr "(fechado)"
-
 #: kallithea/templates/changeset/changeset_range.html:5
 #, python-format
 msgid "%s Changesets"
@@ -5218,31 +5199,30 @@
 msgid "Files affected"
 msgstr "Arquivos afetados"
 
-#: kallithea/templates/changeset/diff_block.html:21
+#: kallithea/templates/changeset/diff_block.html:54
+#, fuzzy
+msgid "Deleted"
+msgstr "excluir"
+
+#: kallithea/templates/changeset/diff_block.html:57
+#, fuzzy
+msgid "Renamed"
+msgstr "renomear"
+
+#: kallithea/templates/changeset/diff_block.html:66
 #: kallithea/templates/files/diff_2way.html:43
 msgid "Show full diff for this file"
 msgstr "Mostrar diff completo para este arquivo"
 
-#: kallithea/templates/changeset/diff_block.html:24
-#: kallithea/templates/changeset/diff_block.html:98
+#: kallithea/templates/changeset/diff_block.html:69
 #: kallithea/templates/files/diff_2way.html:46
 msgid "Show full side-by-side diff for this file"
 msgstr "Mostrar diff completo lado-a-lado para este arquivo"
 
-#: kallithea/templates/changeset/diff_block.html:38
+#: kallithea/templates/changeset/diff_block.html:83
 msgid "Show inline comments"
 msgstr "Mostrar comentários inline"
 
-#: kallithea/templates/changeset/diff_block.html:86
-#, fuzzy
-msgid "Deleted"
-msgstr "excluir"
-
-#: kallithea/templates/changeset/diff_block.html:89
-#, fuzzy
-msgid "Renamed"
-msgstr "renomear"
-
 #: kallithea/templates/compare/compare_cs.html:4
 msgid "No changesets"
 msgstr "Nenhum changeset"
@@ -5251,6 +5231,11 @@
 msgid "Ancestor"
 msgstr "Antecessor"
 
+#: kallithea/templates/compare/compare_cs.html:24
+#, python-format
+msgid "Changeset status: %s"
+msgstr "Estado do changeset: %s"
+
 #: kallithea/templates/compare/compare_cs.html:44
 msgid "First (oldest) changeset in this list"
 msgstr ""
@@ -5263,32 +5248,32 @@
 msgid "Position in this list of changesets"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:76
+#: kallithea/templates/compare/compare_cs.html:85
 #, fuzzy
 msgid "Show merge diff"
 msgstr "Mostrar diff completo"
 
-#: kallithea/templates/compare/compare_cs.html:86
-#: kallithea/templates/pullrequests/pullrequest_show.html:310
+#: kallithea/templates/compare/compare_cs.html:95
+#: kallithea/templates/pullrequests/pullrequest_show.html:321
 #, fuzzy
 msgid "Common ancestor"
 msgstr "Comentário no changeset"
 
-#: kallithea/templates/compare/compare_cs.html:90
+#: kallithea/templates/compare/compare_cs.html:99
 msgid "No common ancestor found - repositories are unrelated"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:98
+#: kallithea/templates/compare/compare_cs.html:107
 #, fuzzy
 msgid "is"
 msgstr "Gist"
 
-#: kallithea/templates/compare/compare_cs.html:99
+#: kallithea/templates/compare/compare_cs.html:108
 #, fuzzy, python-format
 msgid "%s changesets"
 msgstr "%s Changesets"
 
-#: kallithea/templates/compare/compare_cs.html:100
+#: kallithea/templates/compare/compare_cs.html:109
 #, fuzzy
 msgid "behind"
 msgstr "Reindexar"
@@ -5300,28 +5285,28 @@
 msgstr "%s Comparar"
 
 #: kallithea/templates/compare/compare_diff.html:13
-#: kallithea/templates/compare/compare_diff.html:35
+#: kallithea/templates/compare/compare_diff.html:41
 msgid "Compare Revisions"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:33
+#: kallithea/templates/compare/compare_diff.html:39
 msgid "Swap"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:42
+#: kallithea/templates/compare/compare_diff.html:48
 msgid "Compare revisions, branches, bookmarks, or tags."
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:47
-#: kallithea/templates/pullrequests/pullrequest_show.html:305
+#: kallithea/templates/compare/compare_diff.html:53
+#: kallithea/templates/pullrequests/pullrequest_show.html:316
 #, python-format
 msgid "Showing %s commit"
 msgid_plural "Showing %s commits"
 msgstr[0] "Mostrando %s commit"
 msgstr[1] "Mostrando %s commits"
 
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
 msgid "Show full diff"
 msgstr "Mostrar diff completo"
 
@@ -5378,21 +5363,26 @@
 
 #: kallithea/templates/email_templates/password_reset.html:6
 #, fuzzy
-#| msgid "We received a request to create a new password for your account."
 msgid "We have received a request to reset the password for your account."
 msgstr "Recebemos uma requisição para criar uma nova senha para sua conta."
 
-#: kallithea/templates/email_templates/password_reset.html:7
-msgid "To set a new password, click the following link"
+#: kallithea/templates/email_templates/password_reset.html:8
+msgid ""
+"This account is however managed outside this system and the password "
+"cannot be changed here."
 msgstr ""
 
 #: kallithea/templates/email_templates/password_reset.html:10
+msgid "To set a new password, click the following link"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:13
 msgid ""
 "Should you not be able to use the link above, please type the following "
 "code into the password reset form"
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:12
+#: kallithea/templates/email_templates/password_reset.html:16
 msgid ""
 "If it weren't you who requested the password reset, just disregard this "
 "message."
@@ -5477,8 +5467,9 @@
 msgstr ""
 
 #: kallithea/templates/files/files_add.html:53
-msgid "New file mode"
-msgstr ""
+#, fuzzy
+msgid "New file type"
+msgstr "novo arquivo"
 
 #: kallithea/templates/files/files_add.html:64
 #: kallithea/templates/files/files_delete.html:43
@@ -5613,10 +5604,21 @@
 msgid "Binary file (%s)"
 msgstr "Arquivo binário (%s)"
 
-#: kallithea/templates/files/files_source.html:73
-msgid "File is too big to display"
+#: kallithea/templates/files/files_source.html:74
+#, fuzzy
+msgid "File is too big to display."
 msgstr "Arquivo é grande demais para exibir"
 
+#: kallithea/templates/files/files_source.html:76
+#, fuzzy
+msgid "Show full annotation anyway."
+msgstr "Mostrar diff completo"
+
+#: kallithea/templates/files/files_source.html:78
+#, fuzzy
+msgid "Show as raw."
+msgstr "Mostrar original"
+
 #: kallithea/templates/files/files_ypjax.html:5
 msgid "annotation"
 msgstr "anotação"
@@ -5886,44 +5888,50 @@
 msgid "Current revision - no change"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:213
+#: kallithea/templates/pullrequests/pullrequest_show.html:215
+msgid ""
+"Pull requests do not change once created. Select a revision and save to "
+"replace this pull request with a new one."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:224
 #, fuzzy
 msgid "Pull Request Reviewers"
 msgstr "Revisores do pull request"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:238
+#: kallithea/templates/pullrequests/pullrequest_show.html:249
 #, fuzzy
 msgid "Remove reviewer"
 msgstr "revisor"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:250
+#: kallithea/templates/pullrequests/pullrequest_show.html:261
 msgid "Type name of reviewer to add"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:258
+#: kallithea/templates/pullrequests/pullrequest_show.html:269
 #, fuzzy
 msgid "Potential Reviewers"
 msgstr "Visualizar comentário"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:261
+#: kallithea/templates/pullrequests/pullrequest_show.html:272
 msgid "Click to add the repository owner as reviewer:"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:284
+#: kallithea/templates/pullrequests/pullrequest_show.html:295
 msgid "Save Changes"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:285
-#, fuzzy
-msgid "Save as New Pull Request"
+#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#, fuzzy
+msgid "Save Updates as New Pull Request"
 msgstr "Crie novo pull request"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:286
+#: kallithea/templates/pullrequests/pullrequest_show.html:297
 #, fuzzy
 msgid "Cancel Changes"
 msgstr "Mudanças mais recentes"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#: kallithea/templates/pullrequests/pullrequest_show.html:307
 #, fuzzy
 msgid "Pull Request Content"
 msgstr "O pull request mudou de estado"
@@ -5935,7 +5943,7 @@
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:11
 #, fuzzy, python-format
-msgid "Pull Requests from %s'"
+msgid "Pull Requests from '%s'"
 msgstr "Pull requests de %s"
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:13
@@ -6443,30 +6451,6 @@
 #~ msgid "reviewer"
 #~ msgstr "revisor"
 
-#~ msgid ""
-#~ "Your password reset was successful, new"
-#~ " password has been sent to your "
-#~ "email"
-#~ msgstr ""
-#~ "Sua reinicialização de senha foi bem "
-#~ "sucedida, sua senha foi enviada ao "
-#~ "seu e-mail"
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " changeset %(short_id)s on %(branch)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Added by %(pr_username)s] %(repo_name)s pull"
-#~ " request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " pull request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
 #~ msgid "Your new Kallithea password:%s"
 #~ msgstr "Sua nova senha no Kallithea: %s"
 
@@ -6485,3 +6469,27 @@
 #~ msgid "Created by"
 #~ msgstr "criado"
 
+#~ msgid "You can only delete files with revision being a valid branch "
+#~ msgstr ""
+
+#~ msgid "This pull request can be updated with changes on %s:"
+#~ msgstr ""
+
+#~ msgid "Confirm to invalidate repository cache."
+#~ msgstr "Confirma invalidar cache do repositório"
+
+#~ msgid "Comments parsed using %s syntax with %s support."
+#~ msgstr "Comentários interpretados usando a sintaxe %s com suporte a %s."
+
+#~ msgid "Use @username inside this text to notify another user"
+#~ msgstr ""
+
+#~ msgid "Comment preview"
+#~ msgstr "Visualizar comentário"
+
+#~ msgid "Preview"
+#~ msgstr "Visualizar"
+
+#~ msgid "New file mode"
+#~ msgstr ""
+
--- a/kallithea/i18n/ru/LC_MESSAGES/kallithea.po	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/i18n/ru/LC_MESSAGES/kallithea.po	Fri Nov 18 01:11:13 2016 +0100
@@ -12,14 +12,14 @@
 # SkryabinD <skryabind@gmail.com>, 2014
 # softforwinxp <softforwinxp@gmail.com>, 2013
 # zhmylove <zhmylove@narod.ru>, 2013
-# Andrew Shadura <andrew@shadura.me>, 2015
+# Andrew Shadura <andrew@shadura.me>, 2015, 2016.
 #
 msgid ""
 msgstr ""
 "Project-Id-Version: Kallithea 0.3\n"
 "Report-Msgid-Bugs-To: translations@kallithea-scm.org\n"
-"POT-Creation-Date: 2015-09-08 10:34+0200\n"
-"PO-Revision-Date: 2015-04-13 20:18+0200\n"
+"POT-Creation-Date: 2016-03-14 16:51+0100\n"
+"PO-Revision-Date: 2016-02-22 19:33+0100\n"
 "Last-Translator: Andrew Shadura <andrew@shadura.me>\n"
 "Language-Team: Russian "
 "<https://hosted.weblate.org/projects/kallithea/kallithea/ru/>\n"
@@ -31,12 +31,12 @@
 "4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
 "X-Generator: Weblate 2.3-dev\n"
 
-#: kallithea/controllers/changelog.py:86
-#: kallithea/controllers/pullrequests.py:238 kallithea/lib/base.py:512
+#: kallithea/controllers/changelog.py:85
+#: kallithea/controllers/pullrequests.py:240 kallithea/lib/base.py:515
 msgid "There are no changesets yet"
 msgstr "Ещё не было изменений"
 
-#: kallithea/controllers/changelog.py:166
+#: kallithea/controllers/changelog.py:164
 #: kallithea/controllers/admin/permissions.py:61
 #: kallithea/controllers/admin/permissions.py:65
 #: kallithea/controllers/admin/permissions.py:69
@@ -48,37 +48,29 @@
 msgid "None"
 msgstr "Ничего"
 
-#: kallithea/controllers/changelog.py:169 kallithea/controllers/files.py:196
+#: kallithea/controllers/changelog.py:167 kallithea/controllers/files.py:198
 msgid "(closed)"
 msgstr "(закрыто)"
 
-#: kallithea/controllers/changeset.py:89
+#: kallithea/controllers/changeset.py:88
 msgid "Show whitespace"
 msgstr "Отображать пробелы"
 
-#: kallithea/controllers/changeset.py:96 kallithea/controllers/changeset.py:103
+#: kallithea/controllers/changeset.py:95 kallithea/controllers/changeset.py:102
 #: kallithea/templates/files/diff_2way.html:55
 msgid "Ignore whitespace"
 msgstr "Игнорировать пробелы"
 
-#: kallithea/controllers/changeset.py:169
-#, fuzzy, python-format
+#: kallithea/controllers/changeset.py:168
+#, python-format
 msgid "Increase diff context to %(num)s lines"
-msgstr "увеличить контекст до %(num)s строк"
-
-#: kallithea/controllers/changeset.py:212 kallithea/controllers/files.py:96
-#: kallithea/controllers/files.py:116 kallithea/controllers/files.py:742
+msgstr "Увеличить контекст до %(num)s строк"
+
+#: kallithea/controllers/changeset.py:233 kallithea/controllers/files.py:97
+#: kallithea/controllers/files.py:117 kallithea/controllers/files.py:744
 msgid "Such revision does not exist for this repository"
 msgstr "Нет такой ревизии в этом репозитории"
 
-#: kallithea/controllers/changeset.py:383
-msgid ""
-"Changing status on a changeset associated with a closed pull request is "
-"not allowed"
-msgstr ""
-"Нельзя редактировать статус изменений, связанных с закрытыми pull-"
-"request'ами"
-
 #: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:41
 msgid "Select changeset"
 msgstr "Выбрать набор изменений"
@@ -88,13 +80,12 @@
 msgstr "Невозможно сравнивать репозитории без общего предка"
 
 #: kallithea/controllers/error.py:71
-#, fuzzy
 msgid "No response"
-msgstr "версии"
+msgstr "Нет ответа"
 
 #: kallithea/controllers/error.py:72
 msgid "Unknown error"
-msgstr ""
+msgstr "Неизвестная ошибка"
 
 #: kallithea/controllers/error.py:100
 msgid "The request could not be understood by the server due to malformed syntax."
@@ -131,10 +122,10 @@
 #: kallithea/controllers/feed.py:87
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Changeset was too big and was cut off..."
 msgstr "Изменения оказались слишком большими и были вырезаны..."
 
@@ -143,115 +134,115 @@
 msgid "%s committed on %s"
 msgstr "%s выполнил коммит в %s"
 
-#: kallithea/controllers/files.py:91
+#: kallithea/controllers/files.py:92
 msgid "Click here to add new file"
 msgstr "Нажмите чтобы добавить новый файл"
 
-#: kallithea/controllers/files.py:92
+#: kallithea/controllers/files.py:93
 #, python-format
 msgid "There are no files yet. %s"
 msgstr "Нет файлов. %s"
 
-#: kallithea/controllers/files.py:193
+#: kallithea/controllers/files.py:195
 #, python-format
 msgid "%s at %s"
 msgstr "%s (%s)"
 
-#: kallithea/controllers/files.py:305 kallithea/controllers/files.py:365
-#: kallithea/controllers/files.py:432
+#: kallithea/controllers/files.py:307 kallithea/controllers/files.py:367
+#: kallithea/controllers/files.py:434
 #, python-format
 msgid "This repository has been locked by %s on %s"
 msgstr "Репозиторий заблокировал %s в %s"
 
-#: kallithea/controllers/files.py:317
-msgid "You can only delete files with revision being a valid branch "
+#: kallithea/controllers/files.py:319
+msgid "You can only delete files with revision being a valid branch"
 msgstr "Вы можете удалять файлы только в ревизии, связанной с существующей веткой "
 
-#: kallithea/controllers/files.py:328
+#: kallithea/controllers/files.py:330
 #, python-format
 msgid "Deleted file %s via Kallithea"
 msgstr "Файл %s удалён с помощью Kallithea"
 
-#: kallithea/controllers/files.py:350
+#: kallithea/controllers/files.py:352
 #, python-format
 msgid "Successfully deleted file %s"
 msgstr "Файл %s удалён"
 
-#: kallithea/controllers/files.py:354 kallithea/controllers/files.py:420
-#: kallithea/controllers/files.py:501
+#: kallithea/controllers/files.py:356 kallithea/controllers/files.py:422
+#: kallithea/controllers/files.py:503
 msgid "Error occurred during commit"
 msgstr "Во время коммита произошла ошибка"
 
-#: kallithea/controllers/files.py:377
-msgid "You can only edit files with revision being a valid branch "
+#: kallithea/controllers/files.py:379
+msgid "You can only edit files with revision being a valid branch"
 msgstr ""
 "Вы можете редактировать файлы только в ревизии, связанной с существующей "
 "веткой "
 
-#: kallithea/controllers/files.py:391
+#: kallithea/controllers/files.py:393
 #, python-format
 msgid "Edited file %s via Kallithea"
 msgstr "Файл %s отредактирован с помощью Kallithea"
 
-#: kallithea/controllers/files.py:407
+#: kallithea/controllers/files.py:409
 msgid "No changes"
 msgstr "Без изменений"
 
-#: kallithea/controllers/files.py:416 kallithea/controllers/files.py:490
+#: kallithea/controllers/files.py:418 kallithea/controllers/files.py:492
 #, python-format
 msgid "Successfully committed to %s"
 msgstr "Изменения применены в %s"
 
-#: kallithea/controllers/files.py:443
+#: kallithea/controllers/files.py:445
 msgid "Added file via Kallithea"
 msgstr "Файл добавлен с помощью Kallithea"
 
-#: kallithea/controllers/files.py:464
+#: kallithea/controllers/files.py:466
 msgid "No content"
 msgstr "Пусто"
 
-#: kallithea/controllers/files.py:468
+#: kallithea/controllers/files.py:470
 msgid "No filename"
 msgstr "Безымянный"
 
-#: kallithea/controllers/files.py:493
+#: kallithea/controllers/files.py:495
 msgid "Location must be relative path and must not contain .. in path"
 msgstr ""
 "Расположение должно быть относительным путем, и не должно содержать "
 "\"..\" в пути"
 
-#: kallithea/controllers/files.py:526
+#: kallithea/controllers/files.py:528
 msgid "Downloads disabled"
 msgstr "Возможность скачивать отключена"
 
-#: kallithea/controllers/files.py:537
+#: kallithea/controllers/files.py:539
 #, python-format
 msgid "Unknown revision %s"
 msgstr "Неизвестная ревизия %s"
 
-#: kallithea/controllers/files.py:539
+#: kallithea/controllers/files.py:541
 msgid "Empty repository"
 msgstr "Пустой репозиторий"
 
-#: kallithea/controllers/files.py:541
+#: kallithea/controllers/files.py:543
 msgid "Unknown archive type"
 msgstr "Неизвестный тип архива"
 
-#: kallithea/controllers/files.py:771
+#: kallithea/controllers/files.py:773
 #: kallithea/templates/changeset/changeset_range.html:9
 #: kallithea/templates/email_templates/pull_request.html:15
 #: kallithea/templates/pullrequests/pullrequest.html:97
 msgid "Changesets"
 msgstr "Набор изменений"
 
-#: kallithea/controllers/files.py:772 kallithea/controllers/pullrequests.py:176
-#: kallithea/model/scm.py:820 kallithea/templates/switch_to_list.html:3
+#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:175
+#: kallithea/model/scm.py:716 kallithea/templates/switch_to_list.html:3
 #: kallithea/templates/branches/branches.html:10
 msgid "Branches"
 msgstr "Ветки"
 
-#: kallithea/controllers/files.py:773 kallithea/controllers/pullrequests.py:177
-#: kallithea/model/scm.py:831 kallithea/templates/switch_to_list.html:25
+#: kallithea/controllers/files.py:775 kallithea/controllers/pullrequests.py:176
+#: kallithea/model/scm.py:727 kallithea/templates/switch_to_list.html:25
 #: kallithea/templates/tags/tags.html:10
 msgid "Tags"
 msgstr "Метки"
@@ -265,7 +256,7 @@
 msgid "Groups"
 msgstr "Группы"
 
-#: kallithea/controllers/home.py:89
+#: kallithea/controllers/home.py:94
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:106
 #: kallithea/templates/admin/repos/repo_add.html:12
 #: kallithea/templates/admin/repos/repo_add.html:16
@@ -273,23 +264,27 @@
 #: kallithea/templates/admin/users/user_edit_advanced.html:6
 #: kallithea/templates/base/base.html:60 kallithea/templates/base/base.html:77
 #: kallithea/templates/base/base.html:124
-#: kallithea/templates/base/base.html:390
-#: kallithea/templates/base/base.html:562
+#: kallithea/templates/base/base.html:479
+#: kallithea/templates/base/base.html:653
 msgid "Repositories"
 msgstr "Репозитории"
 
-#: kallithea/controllers/home.py:130
+#: kallithea/controllers/home.py:139
 #: kallithea/templates/files/files_add.html:32
 #: kallithea/templates/files/files_delete.html:23
 #: kallithea/templates/files/files_edit.html:32
 msgid "Branch"
 msgstr "Ветка"
 
-#: kallithea/controllers/home.py:136
+#: kallithea/controllers/home.py:145 kallithea/templates/switch_to_list.html:16
+msgid "Closed Branches"
+msgstr "Закрытые ветки"
+
+#: kallithea/controllers/home.py:151
 msgid "Tag"
 msgstr "Тэги"
 
-#: kallithea/controllers/home.py:142
+#: kallithea/controllers/home.py:157
 msgid "Bookmark"
 msgstr "Закладки"
 
@@ -300,163 +295,163 @@
 msgstr "Публичный журнал"
 
 #: kallithea/controllers/journal.py:115 kallithea/controllers/journal.py:157
-#: kallithea/templates/base/base.html:222
+#: kallithea/templates/base/base.html:306
 #: kallithea/templates/journal/journal.html:4
 #: kallithea/templates/journal/journal.html:12
 msgid "Journal"
 msgstr "Журнал"
 
-#: kallithea/controllers/login.py:151 kallithea/controllers/login.py:197
-#, fuzzy
+#: kallithea/controllers/login.py:144 kallithea/controllers/login.py:190
 msgid "Bad captcha"
-msgstr "неверная капча"
-
-#: kallithea/controllers/login.py:157
-msgid "You have successfully registered into Kallithea"
-msgstr "Регистрация в Kallithea прошла успешно"
-
-#: kallithea/controllers/login.py:202
-#, fuzzy
-#| msgid "Your password reset link was sent"
+msgstr "Неверная капча"
+
+#: kallithea/controllers/login.py:150
+msgid "You have successfully registered with %s"
+msgstr "Регистрация в %s прошла успешно"
+
+#: kallithea/controllers/login.py:195
 msgid "A password reset confirmation code has been sent"
-msgstr "Ссылка для сброса пароля отправлена"
-
-#: kallithea/controllers/login.py:251
-#, fuzzy
-#| msgid "Password reset link"
+msgstr "Код для сброса пароля отправлен"
+
+#: kallithea/controllers/login.py:244
 msgid "Invalid password reset token"
-msgstr "Ссылка сброса пароля"
-
-#: kallithea/controllers/login.py:256
+msgstr "Неверный код для сброса пароля"
+
+#: kallithea/controllers/login.py:249
 #: kallithea/controllers/admin/my_account.py:167
 msgid "Successfully updated password"
 msgstr "Пароль обновлён"
 
-#: kallithea/controllers/pullrequests.py:124
+#: kallithea/controllers/pullrequests.py:123
 #, python-format
 msgid "%s (closed)"
 msgstr "%s (закрыта)"
 
-#: kallithea/controllers/pullrequests.py:152
+#: kallithea/controllers/pullrequests.py:151
 #: kallithea/templates/changeset/changeset.html:12
 #: kallithea/templates/email_templates/changeset_comment.html:17
 msgid "Changeset"
 msgstr "Изменения"
 
-#: kallithea/controllers/pullrequests.py:173
+#: kallithea/controllers/pullrequests.py:172
 msgid "Special"
 msgstr "Специальный"
 
-#: kallithea/controllers/pullrequests.py:174
+#: kallithea/controllers/pullrequests.py:173
 msgid "Peer branches"
 msgstr "Ветки участника"
 
-#: kallithea/controllers/pullrequests.py:175 kallithea/model/scm.py:826
+#: kallithea/controllers/pullrequests.py:174 kallithea/model/scm.py:722
 #: kallithea/templates/switch_to_list.html:38
 #: kallithea/templates/bookmarks/bookmarks.html:10
 msgid "Bookmarks"
 msgstr "Закладки"
 
-#: kallithea/controllers/pullrequests.py:310
+#: kallithea/controllers/pullrequests.py:312
 #, python-format
 msgid "Error creating pull request: %s"
 msgstr "Ошибка при создании pull-запроса: %s"
 
-#: kallithea/controllers/pullrequests.py:356
-#: kallithea/controllers/pullrequests.py:503
+#: kallithea/controllers/pullrequests.py:358
+#: kallithea/controllers/pullrequests.py:505
 msgid "No description"
 msgstr "Нет описания"
 
-#: kallithea/controllers/pullrequests.py:363
+#: kallithea/controllers/pullrequests.py:365
 msgid "Successfully opened new pull request"
 msgstr "Pull-запрос создан успешно"
 
-#: kallithea/controllers/pullrequests.py:366
-#: kallithea/controllers/pullrequests.py:453
-#: kallithea/controllers/pullrequests.py:509
+#: kallithea/controllers/pullrequests.py:368
+#: kallithea/controllers/pullrequests.py:455
+#: kallithea/controllers/pullrequests.py:512
 #, python-format
 msgid "Invalid reviewer \"%s\" specified"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:369
-#: kallithea/controllers/pullrequests.py:456
+#: kallithea/controllers/pullrequests.py:371
+#: kallithea/controllers/pullrequests.py:458
 msgid "Error occurred while creating pull request"
 msgstr "Произошла ошибка при создании pull-запроса"
 
-#: kallithea/controllers/pullrequests.py:401
+#: kallithea/controllers/pullrequests.py:403
 msgid "Missing changesets since the previous pull request:"
 msgstr "Отсутствующие ревизии относительно предыдущего pull-запроса:"
 
-#: kallithea/controllers/pullrequests.py:408
+#: kallithea/controllers/pullrequests.py:410
 #, python-format
 msgid "New changesets on %s %s since the previous pull request:"
 msgstr "Новые ревизии на %s %s относительно предыдущего pull-запроса"
 
-#: kallithea/controllers/pullrequests.py:415
+#: kallithea/controllers/pullrequests.py:417
 msgid "Ancestor didn't change - show diff since previous version:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:422
+#: kallithea/controllers/pullrequests.py:424
 #, python-format
 msgid ""
 "This pull request is based on another %s revision and there is no simple "
 "diff."
 msgstr "Этот pull-запрос основан на другой ревизии %s, простой diff невозможен"
 
-#: kallithea/controllers/pullrequests.py:424
+#: kallithea/controllers/pullrequests.py:426
 #, python-format
 msgid "No changes found on %s %s since previous version."
 msgstr "Нет изменений на %s %s относительно предыдущей версии."
 
-#: kallithea/controllers/pullrequests.py:462
+#: kallithea/controllers/pullrequests.py:464
 #, python-format
 msgid "Closed, replaced by %s ."
 msgstr "Закрыт, замещён %s ."
 
-#: kallithea/controllers/pullrequests.py:470
+#: kallithea/controllers/pullrequests.py:472
 msgid "Pull request update created"
 msgstr "Обновление для pull-запроса создано"
 
-#: kallithea/controllers/pullrequests.py:513
+#: kallithea/controllers/pullrequests.py:516
 msgid "Pull request updated"
 msgstr "Pull-запрос обновлён"
 
-#: kallithea/controllers/pullrequests.py:528
+#: kallithea/controllers/pullrequests.py:531
 msgid "Successfully deleted pull request"
 msgstr "Pull-запрос успешно удалён"
 
-#: kallithea/controllers/pullrequests.py:594
+#: kallithea/controllers/pullrequests.py:597
 #, python-format
 msgid "This pull request has already been merged to %s."
 msgstr "Этот pull-запрос уже принят на ветку %s."
 
-#: kallithea/controllers/pullrequests.py:596
+#: kallithea/controllers/pullrequests.py:599
 msgid "This pull request has been closed and can not be updated."
 msgstr "Этот pull-запрос был закрыт и не может быть обновлён."
 
-#: kallithea/controllers/pullrequests.py:614
-#, python-format
-msgid "This pull request can be updated with changes on %s:"
-msgstr "Этот pull-запрос может быть обновлён из %s:"
-
 #: kallithea/controllers/pullrequests.py:617
+#, python-format
+msgid "The following changes are available on %s:"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:621
 msgid "No changesets found for updating this pull request."
 msgstr "Нет изменений для обновления этого pull-запроса."
 
-#: kallithea/controllers/pullrequests.py:625
+#: kallithea/controllers/pullrequests.py:629
 #, python-format
 msgid "Note: Branch %s has another head: %s."
 msgstr "Внимание: Ветка %s имеет ещё одну верхушку: %s."
 
-#: kallithea/controllers/pullrequests.py:631
+#: kallithea/controllers/pullrequests.py:635
 msgid "Git pull requests don't support updates yet."
 msgstr "Обновление pull-запросы git не поддерживается."
 
-#: kallithea/controllers/pullrequests.py:722
+#: kallithea/controllers/pullrequests.py:727
 msgid "No permission to change pull request status"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:727
+#: kallithea/controllers/pullrequests.py:738
+#, fuzzy, python-format
+msgid "Successfully deleted pull request %s"
+msgstr "Pull-запрос успешно удалён"
+
+#: kallithea/controllers/pullrequests.py:748
 msgid "Closing."
 msgstr "Закрыт."
 
@@ -472,12 +467,12 @@
 msgid "An error occurred during search operation."
 msgstr "Произошла ошибка при выполнении этого поиска."
 
-#: kallithea/controllers/summary.py:180
+#: kallithea/controllers/summary.py:181
 #: kallithea/templates/summary/summary.html:384
 msgid "No data ready yet"
 msgstr "Нет данных"
 
-#: kallithea/controllers/summary.py:183
+#: kallithea/controllers/summary.py:184
 #: kallithea/templates/summary/summary.html:98
 msgid "Statistics are disabled for this repository"
 msgstr "Статистические данные отключены для этого репозитария"
@@ -498,66 +493,66 @@
 msgid "Error occurred during update of defaults"
 msgstr "Произошла ошибка при обновлении стандартных настроек"
 
-#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/gists.py:58
 #: kallithea/controllers/admin/my_account.py:243
-#: kallithea/controllers/admin/users.py:285
+#: kallithea/controllers/admin/users.py:284
 #, fuzzy
 msgid "Forever"
 msgstr "навсегда"
 
-#: kallithea/controllers/admin/gists.py:60
+#: kallithea/controllers/admin/gists.py:59
 #: kallithea/controllers/admin/my_account.py:244
-#: kallithea/controllers/admin/users.py:286
+#: kallithea/controllers/admin/users.py:285
 msgid "5 minutes"
 msgstr "5 минут"
 
+#: kallithea/controllers/admin/gists.py:60
+#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/users.py:286
+msgid "1 hour"
+msgstr "1 час"
+
 #: kallithea/controllers/admin/gists.py:61
-#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/my_account.py:246
 #: kallithea/controllers/admin/users.py:287
-msgid "1 hour"
-msgstr "1 час"
-
-#: kallithea/controllers/admin/gists.py:62
-#: kallithea/controllers/admin/my_account.py:246
-#: kallithea/controllers/admin/users.py:288
 msgid "1 day"
 msgstr "1 день"
 
-#: kallithea/controllers/admin/gists.py:63
+#: kallithea/controllers/admin/gists.py:62
 #: kallithea/controllers/admin/my_account.py:247
-#: kallithea/controllers/admin/users.py:289
+#: kallithea/controllers/admin/users.py:288
 msgid "1 month"
 msgstr "1 месяц"
 
-#: kallithea/controllers/admin/gists.py:67
+#: kallithea/controllers/admin/gists.py:66
 #: kallithea/controllers/admin/my_account.py:249
-#: kallithea/controllers/admin/users.py:291
+#: kallithea/controllers/admin/users.py:290
 msgid "Lifetime"
 msgstr "Срок"
 
-#: kallithea/controllers/admin/gists.py:146
+#: kallithea/controllers/admin/gists.py:145
 msgid "Error occurred during gist creation"
 msgstr "Произошла ошибка во время создания gist-записи"
 
-#: kallithea/controllers/admin/gists.py:184
+#: kallithea/controllers/admin/gists.py:183
 #, python-format
 msgid "Deleted gist %s"
 msgstr "Gist-запись %s удалена"
 
-#: kallithea/controllers/admin/gists.py:233
+#: kallithea/controllers/admin/gists.py:232
 #, fuzzy
 msgid "Unmodified"
 msgstr "Последнее изменение"
 
-#: kallithea/controllers/admin/gists.py:262
+#: kallithea/controllers/admin/gists.py:261
 msgid "Successfully updated gist content"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:267
+#: kallithea/controllers/admin/gists.py:266
 msgid "Successfully updated gist data"
 msgstr "Данные gist-записи обновлены"
 
-#: kallithea/controllers/admin/gists.py:270
+#: kallithea/controllers/admin/gists.py:269
 #, python-format
 msgid "Error occurred during update of gist %s"
 msgstr "Произошла ошибка при обновлении gist-записи %s"
@@ -574,7 +569,7 @@
 msgstr "Ваша учетная запись успешно обновлена"
 
 #: kallithea/controllers/admin/my_account.py:144
-#: kallithea/controllers/admin/users.py:202
+#: kallithea/controllers/admin/users.py:201
 #, python-format
 msgid "Error occurred during update of user %s"
 msgstr "Произошла ошибка при обновлении пользователя %s"
@@ -584,33 +579,33 @@
 msgstr "Ошибка при обновлении пароля"
 
 #: kallithea/controllers/admin/my_account.py:220
-#: kallithea/controllers/admin/users.py:415
+#: kallithea/controllers/admin/users.py:414
 #, python-format
 msgid "Added email %s to user"
 msgstr "Пользователю добавлен e-mail %s"
 
 #: kallithea/controllers/admin/my_account.py:226
-#: kallithea/controllers/admin/users.py:421
+#: kallithea/controllers/admin/users.py:420
 msgid "An error occurred during email saving"
 msgstr "Произошла ошибка при сохранении e-mail"
 
 #: kallithea/controllers/admin/my_account.py:235
-#: kallithea/controllers/admin/users.py:433
+#: kallithea/controllers/admin/users.py:432
 msgid "Removed email from user"
 msgstr "E-mail пользователя удалён"
 
 #: kallithea/controllers/admin/my_account.py:259
-#: kallithea/controllers/admin/users.py:308
+#: kallithea/controllers/admin/users.py:307
 msgid "API key successfully created"
 msgstr "API-ключ успешно создан"
 
 #: kallithea/controllers/admin/my_account.py:271
-#: kallithea/controllers/admin/users.py:321
+#: kallithea/controllers/admin/users.py:320
 msgid "API key successfully reset"
 msgstr "API-ключ успешно сброшен"
 
 #: kallithea/controllers/admin/my_account.py:275
-#: kallithea/controllers/admin/users.py:325
+#: kallithea/controllers/admin/users.py:324
 msgid "API key successfully deleted"
 msgstr "API-ключ успешно удалён"
 
@@ -660,10 +655,10 @@
 #: kallithea/templates/admin/users/user_edit_profile.html:105
 #: kallithea/templates/admin/users/users.html:10
 #: kallithea/templates/admin/users/users.html:55
-#: kallithea/templates/base/base.html:252
-#: kallithea/templates/base/base.html:253
-#: kallithea/templates/base/base.html:259
-#: kallithea/templates/base/base.html:260
+#: kallithea/templates/base/base.html:336
+#: kallithea/templates/base/base.html:337
+#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:344
 #: kallithea/templates/base/perms_summary.html:17
 msgid "Admin"
 msgstr "Администратор"
@@ -694,7 +689,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1564
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1603
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1655
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1701
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1705
 msgid "Manual activation of external account"
 msgstr "Ручная активация внешней учетной записи"
 
@@ -706,7 +701,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1565
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1604
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1656
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1702
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1706
 msgid "Automatic activation of external account"
 msgstr "Автоматическая активация внешней учетной записи"
 
@@ -727,196 +722,196 @@
 msgid "Error occurred during update of permissions"
 msgstr "Произошла ошибка во время обновления привилегий"
 
-#: kallithea/controllers/admin/repo_groups.py:188
+#: kallithea/controllers/admin/repo_groups.py:187
 #, python-format
 msgid "Error occurred during creation of repository group %s"
 msgstr "Произошла ошибка при создании группы репозиториев %s"
 
-#: kallithea/controllers/admin/repo_groups.py:193
+#: kallithea/controllers/admin/repo_groups.py:192
 #, python-format
 msgid "Created repository group %s"
 msgstr "Создана новая группа репозиториев %s"
 
-#: kallithea/controllers/admin/repo_groups.py:250
+#: kallithea/controllers/admin/repo_groups.py:249
 #, python-format
 msgid "Updated repository group %s"
 msgstr "Группа репозиториев %s обновлена"
 
-#: kallithea/controllers/admin/repo_groups.py:266
+#: kallithea/controllers/admin/repo_groups.py:265
 #, python-format
 msgid "Error occurred during update of repository group %s"
 msgstr "Произошла ошибка при обновлении группы репозиториев %s"
 
-#: kallithea/controllers/admin/repo_groups.py:284
+#: kallithea/controllers/admin/repo_groups.py:283
 #, python-format
 msgid "This group contains %s repositories and cannot be deleted"
 msgstr "Данная группа содержит %s репозитариев и не может быть удалена"
 
-#: kallithea/controllers/admin/repo_groups.py:291
+#: kallithea/controllers/admin/repo_groups.py:290
 #, python-format
 msgid "This group contains %s subgroups and cannot be deleted"
 msgstr "Группа содержит в себе %s подгрупп и не может быть удалён"
 
-#: kallithea/controllers/admin/repo_groups.py:297
+#: kallithea/controllers/admin/repo_groups.py:296
 #, python-format
 msgid "Removed repository group %s"
 msgstr "Группа репозиториев %s удалена"
 
-#: kallithea/controllers/admin/repo_groups.py:302
+#: kallithea/controllers/admin/repo_groups.py:301
 #, python-format
 msgid "Error occurred during deletion of repository group %s"
 msgstr "Произошла ошибка при удалении группы репозиториев %s"
 
-#: kallithea/controllers/admin/repo_groups.py:405
-#: kallithea/controllers/admin/repo_groups.py:440
+#: kallithea/controllers/admin/repo_groups.py:404
+#: kallithea/controllers/admin/repo_groups.py:439
 #: kallithea/controllers/admin/user_groups.py:340
 msgid "Cannot revoke permission for yourself as admin"
 msgstr "Администратор не может отозвать свои привелегии"
 
-#: kallithea/controllers/admin/repo_groups.py:420
+#: kallithea/controllers/admin/repo_groups.py:419
 msgid "Repository group permissions updated"
 msgstr "Привилегии группы репозиториев обновлены"
 
-#: kallithea/controllers/admin/repo_groups.py:457
-#: kallithea/controllers/admin/repos.py:398
+#: kallithea/controllers/admin/repo_groups.py:456
+#: kallithea/controllers/admin/repos.py:397
 #: kallithea/controllers/admin/user_groups.py:352
 msgid "An error occurred during revoking of permission"
 msgstr "Произошла ошибка при отзыве привелегии"
 
-#: kallithea/controllers/admin/repos.py:152
+#: kallithea/controllers/admin/repos.py:151
 #, python-format
 msgid "Error creating repository %s"
 msgstr "Произошла ошибка при создании репозитория %s"
 
-#: kallithea/controllers/admin/repos.py:213
+#: kallithea/controllers/admin/repos.py:212
 #, python-format
 msgid "Created repository %s from %s"
 msgstr "Репозиторий %s создан из %s"
 
-#: kallithea/controllers/admin/repos.py:222
+#: kallithea/controllers/admin/repos.py:221
 #, python-format
 msgid "Forked repository %s as %s"
 msgstr "Сделан форк(копия) репозитория %s на %s"
 
-#: kallithea/controllers/admin/repos.py:225
+#: kallithea/controllers/admin/repos.py:224
 #, python-format
 msgid "Created repository %s"
 msgstr "Репозиторий %s создан"
 
-#: kallithea/controllers/admin/repos.py:262
+#: kallithea/controllers/admin/repos.py:261
 #, python-format
 msgid "Repository %s updated successfully"
 msgstr "Репозитарий %s успешно обновлён"
 
-#: kallithea/controllers/admin/repos.py:283
+#: kallithea/controllers/admin/repos.py:282
 #, python-format
 msgid "Error occurred during update of repository %s"
 msgstr "Произошла ошибка во время обновления репозитория %s"
 
-#: kallithea/controllers/admin/repos.py:310
+#: kallithea/controllers/admin/repos.py:309
 #, python-format
 msgid "Detached %s forks"
 msgstr "Форки %s отсоединены"
 
-#: kallithea/controllers/admin/repos.py:313
+#: kallithea/controllers/admin/repos.py:312
 #, python-format
 msgid "Deleted %s forks"
 msgstr "Удалены форки репозитория %s"
 
-#: kallithea/controllers/admin/repos.py:318
+#: kallithea/controllers/admin/repos.py:317
 #, python-format
 msgid "Deleted repository %s"
 msgstr "Репозиторий %s удалён"
 
-#: kallithea/controllers/admin/repos.py:321
+#: kallithea/controllers/admin/repos.py:320
 #, fuzzy, python-format
 msgid "Cannot delete repository %s which still has forks"
 msgstr "Невозможно удалить %s, он всё-ещё содержит форки"
 
-#: kallithea/controllers/admin/repos.py:326
+#: kallithea/controllers/admin/repos.py:325
 #, python-format
 msgid "An error occurred during deletion of %s"
 msgstr "Произошла ошибка во время удаления %s"
 
-#: kallithea/controllers/admin/repos.py:374
+#: kallithea/controllers/admin/repos.py:373
 msgid "Repository permissions updated"
 msgstr "Привилегии репозитория обновлены"
 
-#: kallithea/controllers/admin/repos.py:430
+#: kallithea/controllers/admin/repos.py:429
 msgid "An error occurred during creation of field"
 msgstr "Произошла ошибка при создании поля"
 
-#: kallithea/controllers/admin/repos.py:444
+#: kallithea/controllers/admin/repos.py:443
 msgid "An error occurred during removal of field"
 msgstr "Произошла ошибка при удалении поля"
 
-#: kallithea/controllers/admin/repos.py:460
+#: kallithea/controllers/admin/repos.py:459
 msgid "-- Not a fork --"
 msgstr "-- Не форк --"
 
-#: kallithea/controllers/admin/repos.py:491
+#: kallithea/controllers/admin/repos.py:490
 msgid "Updated repository visibility in public journal"
 msgstr "Видимость репозитория в публичном журнале обновлена"
 
-#: kallithea/controllers/admin/repos.py:495
+#: kallithea/controllers/admin/repos.py:494
 msgid "An error occurred during setting this repository in public journal"
 msgstr "Произошла ошибка при установке репозитария в общедоступный журнал"
 
-#: kallithea/controllers/admin/repos.py:512
+#: kallithea/controllers/admin/repos.py:511
 msgid "Nothing"
 msgstr "Ничего"
 
-#: kallithea/controllers/admin/repos.py:514
+#: kallithea/controllers/admin/repos.py:513
 #, python-format
 msgid "Marked repository %s as fork of %s"
 msgstr "Репозиторий %s отмечен как форк %s"
 
-#: kallithea/controllers/admin/repos.py:521
+#: kallithea/controllers/admin/repos.py:520
 msgid "An error occurred during this operation"
 msgstr "Произошла ошибка при выполнении операции"
 
-#: kallithea/controllers/admin/repos.py:537
-#: kallithea/controllers/admin/repos.py:564
+#: kallithea/controllers/admin/repos.py:536
+#: kallithea/controllers/admin/repos.py:563
 #, fuzzy
 msgid "Repository has been locked"
 msgstr "Репозиторий не заблокирован"
 
-#: kallithea/controllers/admin/repos.py:540
-#: kallithea/controllers/admin/repos.py:561
+#: kallithea/controllers/admin/repos.py:539
+#: kallithea/controllers/admin/repos.py:560
 #, fuzzy
 msgid "Repository has been unlocked"
 msgstr "Репозиторий не заблокирован"
 
-#: kallithea/controllers/admin/repos.py:543
-#: kallithea/controllers/admin/repos.py:568
+#: kallithea/controllers/admin/repos.py:542
+#: kallithea/controllers/admin/repos.py:567
 msgid "An error occurred during unlocking"
 msgstr "Произошла ошибка во время разблокирования"
 
-#: kallithea/controllers/admin/repos.py:582
+#: kallithea/controllers/admin/repos.py:581
 msgid "Cache invalidation successful"
 msgstr "Кэш сброшен"
 
-#: kallithea/controllers/admin/repos.py:586
+#: kallithea/controllers/admin/repos.py:585
 msgid "An error occurred during cache invalidation"
 msgstr "Произошла ошибка при очистке кэша"
 
-#: kallithea/controllers/admin/repos.py:601
+#: kallithea/controllers/admin/repos.py:600
 msgid "Pulled from remote location"
 msgstr "Внесены изменения из удалённого репозитория"
 
-#: kallithea/controllers/admin/repos.py:604
+#: kallithea/controllers/admin/repos.py:603
 msgid "An error occurred during pull from remote location"
 msgstr "Произошла ошибка при внесении изменений из удалённого репозитория"
 
-#: kallithea/controllers/admin/repos.py:637
+#: kallithea/controllers/admin/repos.py:636
 msgid "An error occurred during deletion of repository stats"
 msgstr "Произошла ошибка при удалении статистики репозитория"
 
-#: kallithea/controllers/admin/settings.py:170
+#: kallithea/controllers/admin/settings.py:141
 msgid "Updated VCS settings"
 msgstr "Обновлены настройки VCS"
 
-#: kallithea/controllers/admin/settings.py:174
+#: kallithea/controllers/admin/settings.py:145
 msgid ""
 "Unable to activate hgsubversion support. The \"hgsubversion\" library is "
 "missing"
@@ -924,49 +919,49 @@
 "Невозможно включить поддержку hgsubversion. Библиотека «hgsubversion» "
 "отсутствует"
 
-#: kallithea/controllers/admin/settings.py:180
-#: kallithea/controllers/admin/settings.py:277
+#: kallithea/controllers/admin/settings.py:151
+#: kallithea/controllers/admin/settings.py:248
 msgid "Error occurred while updating application settings"
 msgstr "Произошла ошибка при обновлении настроек приложения"
 
-#: kallithea/controllers/admin/settings.py:216
+#: kallithea/controllers/admin/settings.py:187
 #, python-format
 msgid "Repositories successfully rescanned. Added: %s. Removed: %s."
 msgstr "Репозитории успешно пересканированы, добавлено: %s, удалено: %s."
 
-#: kallithea/controllers/admin/settings.py:273
+#: kallithea/controllers/admin/settings.py:244
 msgid "Updated application settings"
 msgstr "Обновленные параметры настройки приложения"
 
-#: kallithea/controllers/admin/settings.py:330
+#: kallithea/controllers/admin/settings.py:301
 msgid "Updated visualisation settings"
 msgstr "Настройки визуализации обновлены"
 
-#: kallithea/controllers/admin/settings.py:335
+#: kallithea/controllers/admin/settings.py:306
 msgid "Error occurred during updating visualisation settings"
 msgstr "Произошла ошибка при обновлении настроек визуализации"
 
-#: kallithea/controllers/admin/settings.py:361
+#: kallithea/controllers/admin/settings.py:332
 msgid "Please enter email address"
 msgstr "Пожалуйста, введите адрес электронной почты"
 
-#: kallithea/controllers/admin/settings.py:376
+#: kallithea/controllers/admin/settings.py:347
 msgid "Send email task created"
 msgstr "Задача отправки Email создана"
 
-#: kallithea/controllers/admin/settings.py:407
+#: kallithea/controllers/admin/settings.py:378
 msgid "Added new hook"
 msgstr "Добавлена новая ловушка"
 
-#: kallithea/controllers/admin/settings.py:421
+#: kallithea/controllers/admin/settings.py:392
 msgid "Updated hooks"
 msgstr "Обновлённые ловушки"
 
-#: kallithea/controllers/admin/settings.py:425
+#: kallithea/controllers/admin/settings.py:396
 msgid "Error occurred during hook creation"
 msgstr "произошла ошибка при создании хука"
 
-#: kallithea/controllers/admin/settings.py:451
+#: kallithea/controllers/admin/settings.py:422
 msgid "Whoosh reindex task scheduled"
 msgstr "Запланирована переиндексация базы Whoosh"
 
@@ -1007,78 +1002,82 @@
 msgstr "Привилегии группы пользователей обновлены"
 
 #: kallithea/controllers/admin/user_groups.py:440
-#: kallithea/controllers/admin/users.py:384
+#: kallithea/controllers/admin/users.py:383
 msgid "Updated permissions"
 msgstr "Обновлены привилегии"
 
 #: kallithea/controllers/admin/user_groups.py:444
-#: kallithea/controllers/admin/users.py:388
+#: kallithea/controllers/admin/users.py:387
 msgid "An error occurred during permissions saving"
 msgstr "Произошла ошибка при сохранении привилегий"
 
-#: kallithea/controllers/admin/users.py:134
+#: kallithea/controllers/admin/users.py:133
 #, python-format
 msgid "Created user %s"
 msgstr "Пользователь %s создан"
 
-#: kallithea/controllers/admin/users.py:149
+#: kallithea/controllers/admin/users.py:148
 #, python-format
 msgid "Error occurred during creation of user %s"
 msgstr "Произошла ошибка при создании пользователя %s"
 
-#: kallithea/controllers/admin/users.py:182
+#: kallithea/controllers/admin/users.py:181
 msgid "User updated successfully"
 msgstr "Пользователь успешно обновлён"
 
-#: kallithea/controllers/admin/users.py:218
+#: kallithea/controllers/admin/users.py:217
 msgid "Successfully deleted user"
 msgstr "Пользователь успешно удалён"
 
-#: kallithea/controllers/admin/users.py:223
+#: kallithea/controllers/admin/users.py:222
 msgid "An error occurred during deletion of user"
 msgstr "Произошла ошибка при удалении пользователя"
 
-#: kallithea/controllers/admin/users.py:236
+#: kallithea/controllers/admin/users.py:235
 msgid "The default user cannot be edited"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:463
+#: kallithea/controllers/admin/users.py:462
 #, python-format
 msgid "Added IP address %s to user whitelist"
 msgstr "Добавлен IP %s в белый список пользователя"
 
-#: kallithea/controllers/admin/users.py:469
+#: kallithea/controllers/admin/users.py:468
 msgid "An error occurred while adding IP address"
 msgstr "Произошла ошибка при сохранении IP"
 
-#: kallithea/controllers/admin/users.py:483
+#: kallithea/controllers/admin/users.py:482
 msgid "Removed IP address from user whitelist"
 msgstr "Удален IP %s из белого списка пользователя"
 
-#: kallithea/lib/auth.py:743
+#: kallithea/lib/auth.py:737
 #, python-format
 msgid "IP %s not allowed"
 msgstr "IP %s заблокирован"
 
-#: kallithea/lib/auth.py:756
+#: kallithea/lib/auth.py:750
 msgid "Invalid API key"
 msgstr ""
 
-#: kallithea/lib/auth.py:812
+#: kallithea/lib/auth.py:768
+msgid "CSRF token leak has been detected - all form tokens have been expired"
+msgstr ""
+
+#: kallithea/lib/auth.py:813
 msgid "You need to be a registered user to perform this action"
 msgstr ""
 "Вы должны быть зарегистрированным пользователем, чтобы выполнить это "
 "действие"
 
-#: kallithea/lib/auth.py:844
+#: kallithea/lib/auth.py:843
 msgid "You need to be signed in to view this page"
 msgstr "Страница доступна только авторизованным пользователям"
 
-#: kallithea/lib/base.py:490
+#: kallithea/lib/base.py:493
 msgid "Repository not found in the filesystem"
 msgstr "Репозиторий не найден на файловой системе"
 
-#: kallithea/lib/base.py:516 kallithea/lib/helpers.py:622
+#: kallithea/lib/base.py:519 kallithea/lib/helpers.py:623
 msgid "Changeset not found"
 msgstr "Набор изменений не найден"
 
@@ -1096,126 +1095,126 @@
 msgid "No changes detected"
 msgstr "Изменений не обнаружено"
 
-#: kallithea/lib/helpers.py:609
+#: kallithea/lib/helpers.py:610
 #, python-format
 msgid "Deleted branch: %s"
 msgstr "Удалена ветка: %s"
 
-#: kallithea/lib/helpers.py:611
+#: kallithea/lib/helpers.py:612
 #, python-format
 msgid "Created tag: %s"
 msgstr "Создан тег: %s"
 
-#: kallithea/lib/helpers.py:671
+#: kallithea/lib/helpers.py:672
 #, python-format
 msgid "Show all combined changesets %s->%s"
 msgstr "Показать отличия вместе %s->%s"
 
-#: kallithea/lib/helpers.py:677
+#: kallithea/lib/helpers.py:678
 #, fuzzy
 msgid "Compare view"
 msgstr "сравнение"
 
-#: kallithea/lib/helpers.py:696
+#: kallithea/lib/helpers.py:697
 msgid "and"
 msgstr "и"
 
-#: kallithea/lib/helpers.py:697
+#: kallithea/lib/helpers.py:698
 #, python-format
 msgid "%s more"
 msgstr "на %s больше"
 
-#: kallithea/lib/helpers.py:698 kallithea/templates/changelog/changelog.html:44
+#: kallithea/lib/helpers.py:699 kallithea/templates/changelog/changelog.html:44
 msgid "revisions"
 msgstr "версии"
 
-#: kallithea/lib/helpers.py:722
+#: kallithea/lib/helpers.py:723
 #, fuzzy, python-format
 msgid "Fork name %s"
 msgstr "имя форка %s"
 
-#: kallithea/lib/helpers.py:742
+#: kallithea/lib/helpers.py:743
 #, fuzzy, python-format
 msgid "Pull request %s"
 msgstr "Pull-запрос #%s"
 
-#: kallithea/lib/helpers.py:752
+#: kallithea/lib/helpers.py:753
 msgid "[deleted] repository"
 msgstr "[удален] репозиторий"
 
-#: kallithea/lib/helpers.py:754 kallithea/lib/helpers.py:766
+#: kallithea/lib/helpers.py:755 kallithea/lib/helpers.py:767
 msgid "[created] repository"
 msgstr "[создан] репозиторий"
 
-#: kallithea/lib/helpers.py:756
+#: kallithea/lib/helpers.py:757
 msgid "[created] repository as fork"
 msgstr "[создан] репозиторий как форк"
 
-#: kallithea/lib/helpers.py:758 kallithea/lib/helpers.py:768
+#: kallithea/lib/helpers.py:759 kallithea/lib/helpers.py:769
 msgid "[forked] repository"
 msgstr "[форкнут] репозиторий"
 
-#: kallithea/lib/helpers.py:760 kallithea/lib/helpers.py:770
+#: kallithea/lib/helpers.py:761 kallithea/lib/helpers.py:771
 msgid "[updated] repository"
 msgstr "[обновлён] репозиторий"
 
-#: kallithea/lib/helpers.py:762
+#: kallithea/lib/helpers.py:763
 msgid "[downloaded] archive from repository"
 msgstr "[загружен] архив из репозитория"
 
-#: kallithea/lib/helpers.py:764
+#: kallithea/lib/helpers.py:765
 msgid "[delete] repository"
 msgstr "[удален] репозиторий"
 
-#: kallithea/lib/helpers.py:772
+#: kallithea/lib/helpers.py:773
 msgid "[created] user"
 msgstr "[создан] пользователь"
 
-#: kallithea/lib/helpers.py:774
+#: kallithea/lib/helpers.py:775
 msgid "[updated] user"
 msgstr "[обновлён] пользователь"
 
-#: kallithea/lib/helpers.py:776
+#: kallithea/lib/helpers.py:777
 msgid "[created] user group"
 msgstr "[создана] группа пользователей"
 
-#: kallithea/lib/helpers.py:778
+#: kallithea/lib/helpers.py:779
 msgid "[updated] user group"
 msgstr "[обновлена] группа пользователей"
 
-#: kallithea/lib/helpers.py:780
+#: kallithea/lib/helpers.py:781
 msgid "[commented] on revision in repository"
 msgstr "[комментарий] к ревизии в репозитории"
 
-#: kallithea/lib/helpers.py:782
+#: kallithea/lib/helpers.py:783
 msgid "[commented] on pull request for"
 msgstr "[прокомментировано] в запросе на внесение изменений для"
 
-#: kallithea/lib/helpers.py:784
+#: kallithea/lib/helpers.py:785
 msgid "[closed] pull request for"
 msgstr "[закрыт] Pull-запрос для"
 
-#: kallithea/lib/helpers.py:786
+#: kallithea/lib/helpers.py:787
 msgid "[pushed] into"
 msgstr "[отправлено] в"
 
-#: kallithea/lib/helpers.py:788
+#: kallithea/lib/helpers.py:789
 msgid "[committed via Kallithea] into repository"
 msgstr "[внесены изменения с помощью Kallithea] в репозитории"
 
-#: kallithea/lib/helpers.py:790
+#: kallithea/lib/helpers.py:791
 msgid "[pulled from remote] into repository"
 msgstr "[внесены изменения из удалённого репозитория] в репозиторий"
 
-#: kallithea/lib/helpers.py:792
+#: kallithea/lib/helpers.py:793
 msgid "[pulled] from"
 msgstr "[внесены изменения] из"
 
-#: kallithea/lib/helpers.py:794
+#: kallithea/lib/helpers.py:795
 msgid "[started following] repository"
 msgstr "[добавлен в наблюдения] репозиторий"
 
-#: kallithea/lib/helpers.py:796
+#: kallithea/lib/helpers.py:797
 msgid "[stopped following] repository"
 msgstr "[удалён из наблюдения] репозиторий"
 
@@ -1225,8 +1224,8 @@
 msgstr " и на %s больше"
 
 #: kallithea/lib/helpers.py:1128
-#: kallithea/templates/compare/compare_diff.html:65
-#: kallithea/templates/pullrequests/pullrequest_show.html:326
+#: kallithea/templates/compare/compare_diff.html:71
+#: kallithea/templates/pullrequests/pullrequest_show.html:337
 msgid "No files"
 msgstr "Нет файлов"
 
@@ -1250,7 +1249,7 @@
 msgid "chmod"
 msgstr "chmod"
 
-#: kallithea/lib/helpers.py:1444
+#: kallithea/lib/helpers.py:1469
 #, python-format
 msgid ""
 "%s repository is not mapped to db perhaps it was created or renamed from "
@@ -1261,7 +1260,7 @@
 "переименован из файловой системы. Пожалуйста, перезапустите приложение "
 "для сканирования репозиториев"
 
-#: kallithea/lib/utils2.py:415
+#: kallithea/lib/utils2.py:434
 #, python-format
 msgid "%d year"
 msgid_plural "%d years"
@@ -1269,7 +1268,7 @@
 msgstr[1] "%d лет"
 msgstr[2] "%d года"
 
-#: kallithea/lib/utils2.py:416
+#: kallithea/lib/utils2.py:435
 #, python-format
 msgid "%d month"
 msgid_plural "%d months"
@@ -1277,7 +1276,7 @@
 msgstr[1] "%d месяца"
 msgstr[2] "%d месяцев"
 
-#: kallithea/lib/utils2.py:417
+#: kallithea/lib/utils2.py:436
 #, python-format
 msgid "%d day"
 msgid_plural "%d days"
@@ -1285,7 +1284,7 @@
 msgstr[1] "%d дня"
 msgstr[2] "%d дней"
 
-#: kallithea/lib/utils2.py:418
+#: kallithea/lib/utils2.py:437
 #, python-format
 msgid "%d hour"
 msgid_plural "%d hours"
@@ -1293,7 +1292,7 @@
 msgstr[1] "%d часов"
 msgstr[2] "%d часа"
 
-#: kallithea/lib/utils2.py:419
+#: kallithea/lib/utils2.py:438
 #, python-format
 msgid "%d minute"
 msgid_plural "%d minutes"
@@ -1301,7 +1300,7 @@
 msgstr[1] "%d минут"
 msgstr[2] "%d минуты"
 
-#: kallithea/lib/utils2.py:420
+#: kallithea/lib/utils2.py:439
 #, python-format
 msgid "%d second"
 msgid_plural "%d seconds"
@@ -1309,27 +1308,27 @@
 msgstr[1] "%d секунды"
 msgstr[2] "%d секунды"
 
-#: kallithea/lib/utils2.py:436
+#: kallithea/lib/utils2.py:455
 #, python-format
 msgid "in %s"
 msgstr "в %s"
 
-#: kallithea/lib/utils2.py:438
+#: kallithea/lib/utils2.py:457
 #, python-format
 msgid "%s ago"
 msgstr "%s назад"
 
-#: kallithea/lib/utils2.py:440
+#: kallithea/lib/utils2.py:459
 #, python-format
 msgid "in %s and %s"
 msgstr "в %s и %s"
 
-#: kallithea/lib/utils2.py:443
+#: kallithea/lib/utils2.py:462
 #, python-format
 msgid "%s and %s ago"
 msgstr "%s и %s назад"
 
-#: kallithea/lib/utils2.py:446
+#: kallithea/lib/utils2.py:465
 msgid "just now"
 msgstr "прямо сейчас"
 
@@ -1428,7 +1427,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1531
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1570
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1620
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1665
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1669
 msgid "Kallithea Administrator"
 msgstr "Администратор Kallithea"
 
@@ -1539,7 +1538,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2063
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2102
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2155
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2229
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2237
 msgid "Approved"
 msgstr "Одобрено"
 
@@ -1554,7 +1553,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2064
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2103
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2156
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2230
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2238
 msgid "Rejected"
 msgstr "Отклонено"
 
@@ -1581,7 +1580,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1379
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1418
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1471
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1518
 msgid "top level"
 msgstr "верхний уровень"
 
@@ -1728,7 +1727,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1560
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1599
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1651
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1697
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1701
 msgid "Registration disabled"
 msgstr "Регистрация отключена"
 
@@ -1755,12 +1754,12 @@
 msgstr "Регистрация пользователя с автоматической активацией"
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1645
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1691
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1695
 msgid "Repository creation enabled with write permission to a repository group"
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1646
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1692
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1696
 msgid "Repository creation disabled with write permission to a repository group"
 msgstr ""
 
@@ -1769,114 +1768,114 @@
 msgid "on line %s"
 msgstr "на строке %s"
 
-#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:169
+#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:170
 msgid "[Mention]"
 msgstr "[Упоминание]"
 
-#: kallithea/model/db.py:1667
+#: kallithea/model/db.py:1671
 msgid "Default user has no access to new repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1668
+#: kallithea/model/db.py:1672
 #, fuzzy
 msgid "Default user has read access to new repositories"
 msgstr "Несанкционированный доступ к ресурсу"
 
-#: kallithea/model/db.py:1669
+#: kallithea/model/db.py:1673
 #, fuzzy
 msgid "Default user has write access to new repositories"
 msgstr "Несанкционированный доступ к ресурсу"
 
-#: kallithea/model/db.py:1670
+#: kallithea/model/db.py:1674
 msgid "Default user has admin access to new repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1672
+#: kallithea/model/db.py:1676
 msgid "Default user has no access to new repository groups"
 msgstr ""
 
-#: kallithea/model/db.py:1673
-msgid "Default user has read access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1674
-msgid "Default user has write access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1675
-msgid "Default user has admin access to new repository groups"
-msgstr ""
-
 #: kallithea/model/db.py:1677
-msgid "Default user has no access to new user groups"
+msgid "Default user has read access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1678
-msgid "Default user has read access to new user groups"
+msgid "Default user has write access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1679
-msgid "Default user has write access to new user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1680
-msgid "Default user has admin access to new user groups"
+msgid "Default user has admin access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1681
+msgid "Default user has no access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1682
+msgid "Default user has read access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1683
+msgid "Default user has write access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1684
+msgid "Default user has admin access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1686
 #, fuzzy
 msgid "Only admins can create repository groups"
 msgstr "Создана новая группа репозиториев %s"
 
-#: kallithea/model/db.py:1683
+#: kallithea/model/db.py:1687
 #, fuzzy
 msgid "Non-admins can create repository groups"
 msgstr "Создана новая группа репозиториев %s"
 
-#: kallithea/model/db.py:1685
+#: kallithea/model/db.py:1689
 #, fuzzy
 msgid "Only admins can create user groups"
 msgstr "Создавать группы пользователей"
 
-#: kallithea/model/db.py:1686
+#: kallithea/model/db.py:1690
 #, fuzzy
 msgid "Non-admins can create user groups"
 msgstr "Создавать группы пользователей"
 
-#: kallithea/model/db.py:1688
+#: kallithea/model/db.py:1692
 msgid "Only admins can create top level repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1689
+#: kallithea/model/db.py:1693
 msgid "Non-admins can create top level repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1694
+#: kallithea/model/db.py:1698
 #, fuzzy
 msgid "Only admins can fork repositories"
 msgstr "Местонахождение репозиториев"
 
-#: kallithea/model/db.py:1695
+#: kallithea/model/db.py:1699
 #, fuzzy
-msgid "Non-admins can can fork repositories"
+msgid "Non-admins can fork repositories"
 msgstr "Сбросить кэш для всех репозиториев"
 
-#: kallithea/model/db.py:1698
+#: kallithea/model/db.py:1702
 #, fuzzy
 msgid "User registration with manual account activation"
 msgstr "Регистрация пользователя с ручной активацией учётной записи"
 
-#: kallithea/model/db.py:1699
+#: kallithea/model/db.py:1703
 #, fuzzy
 msgid "User registration with automatic account activation"
 msgstr "Регистрация пользователя с автоматической активацией"
 
-#: kallithea/model/db.py:2228
+#: kallithea/model/db.py:2236
 #, fuzzy
 msgid "Not reviewed"
 msgstr "Не просмотрено"
 
-#: kallithea/model/db.py:2231
+#: kallithea/model/db.py:2239
 #, fuzzy
 msgid "Under review"
 msgstr "На рассмотрении"
@@ -1899,7 +1898,7 @@
 msgid "Enter %(min)i characters or more"
 msgstr "Введите не менее %(min)i символов"
 
-#: kallithea/model/forms.py:160
+#: kallithea/model/forms.py:165
 msgid "Name must not contain only digits"
 msgstr ""
 
@@ -1975,14 +1974,11 @@
 
 #: kallithea/model/notification.py:307
 #, fuzzy, python-format
-#| msgid "%(user)s wants you to review pull request %(pr_nice_id)s:
-#| %(pr_title)s"
 msgid "[Added] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
 msgstr "%(user)s просит вас рассмотреть pull request #%(pr_id)s: %(pr_title)s"
 
 #: kallithea/model/notification.py:308
 #, fuzzy, python-format
-#| msgid "[commented] on pull request for"
 msgid "[Comment] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
 msgstr "[прокомментировано] в запросе на внесение изменений для"
 
@@ -1995,7 +1991,7 @@
 msgid "%(user)s wants you to review pull request %(pr_nice_id)s: %(pr_title)s"
 msgstr "%(user)s просит вас рассмотреть pull request #%(pr_id)s: %(pr_title)s"
 
-#: kallithea/model/scm.py:812
+#: kallithea/model/scm.py:708
 msgid "latest tip"
 msgstr "последняя версия"
 
@@ -2039,17 +2035,16 @@
 "поэтому не может быть удалён. Смените владельца или удалите данные "
 "группы: %s"
 
-#: kallithea/model/user.py:360
+#: kallithea/model/user.py:368
 msgid "Password reset link"
 msgstr "Ссылка сброса пароля"
 
-#: kallithea/model/user.py:408
+#: kallithea/model/user.py:418
 #, fuzzy
-#| msgid "Password reset link"
 msgid "Password reset notification"
 msgstr "Ссылка сброса пароля"
 
-#: kallithea/model/user.py:409
+#: kallithea/model/user.py:419
 #, python-format
 msgid ""
 "The password to your account %s has been changed using password reset "
@@ -2060,17 +2055,17 @@
 msgid "Value cannot be an empty list"
 msgstr "Значение не может быть пустым списком"
 
-#: kallithea/model/validators.py:95
+#: kallithea/model/validators.py:96
 #, python-format
 msgid "Username \"%(username)s\" already exists"
 msgstr "Пользователь с именем \"%(username)s\" уже существует"
 
-#: kallithea/model/validators.py:97
+#: kallithea/model/validators.py:98
 #, fuzzy, python-format
 msgid "Username \"%(username)s\" cannot be used"
 msgstr "Имя \"%(username)s\" недопустимо"
 
-#: kallithea/model/validators.py:99
+#: kallithea/model/validators.py:100
 #, fuzzy
 msgid ""
 "Username may only contain alphanumeric characters underscores, periods or"
@@ -2080,25 +2075,25 @@
 "подчеркивания, точки и тире; а так же должно начинаться с буквы, цифры "
 "либо с символа подчеркивания"
 
-#: kallithea/model/validators.py:126
+#: kallithea/model/validators.py:127
 msgid "The input is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:133
+#: kallithea/model/validators.py:134
 #, python-format
 msgid "Username %(username)s is not valid"
 msgstr "Имя \"%(username)s\" недопустимо"
 
-#: kallithea/model/validators.py:152
+#: kallithea/model/validators.py:154
 msgid "Invalid user group name"
 msgstr "Неверное имя группы пользователей"
 
-#: kallithea/model/validators.py:153
+#: kallithea/model/validators.py:155
 #, python-format
 msgid "User group \"%(usergroup)s\" already exists"
 msgstr "Группа пользователей \"%(usergroup)s\" уже существует"
 
-#: kallithea/model/validators.py:155
+#: kallithea/model/validators.py:157
 msgid ""
 "user group name may only contain alphanumeric characters underscores, "
 "periods or dashes and must begin with alphanumeric character"
@@ -2106,107 +2101,107 @@
 "имя группы пользователей может содержать только буквы, цифры, символы "
 "подчеркивания, точки и тире; а так же должно начинаться с буквы или цифры"
 
-#: kallithea/model/validators.py:193
+#: kallithea/model/validators.py:197
 msgid "Cannot assign this group as parent"
 msgstr "Невозможно использовать эту группу как родителя"
 
-#: kallithea/model/validators.py:194
+#: kallithea/model/validators.py:198
 #, python-format
 msgid "Group \"%(group_name)s\" already exists"
 msgstr "Группа \"%(group_name)s\" уже существует"
 
-#: kallithea/model/validators.py:196
+#: kallithea/model/validators.py:200
 #, python-format
 msgid "Repository with name \"%(group_name)s\" already exists"
 msgstr "Репозитарий с  именем \"%(group_name)s\" уже существует"
 
-#: kallithea/model/validators.py:254
+#: kallithea/model/validators.py:258
 msgid "Invalid characters (non-ascii) in password"
 msgstr "Недопустимые символы (не ascii) в пароле"
 
-#: kallithea/model/validators.py:269
+#: kallithea/model/validators.py:273
 msgid "Invalid old password"
 msgstr "Неверно задан старый пароль"
 
-#: kallithea/model/validators.py:285
+#: kallithea/model/validators.py:289
 msgid "Passwords do not match"
 msgstr "Пароли не совпадают"
 
-#: kallithea/model/validators.py:300
+#: kallithea/model/validators.py:304
 #, fuzzy
 msgid "Invalid username or password"
 msgstr "неверный пароль"
 
-#: kallithea/model/validators.py:331
+#: kallithea/model/validators.py:335
 msgid "Token mismatch"
 msgstr "Несовпадение токенов"
 
-#: kallithea/model/validators.py:345
+#: kallithea/model/validators.py:351
 #, fuzzy, python-format
 msgid "Repository name %(repo)s is not allowed"
 msgstr "Имя репозитория %(repo)s запрещено"
 
-#: kallithea/model/validators.py:347
+#: kallithea/model/validators.py:353
 #, python-format
 msgid "Repository named %(repo)s already exists"
 msgstr "Репозитарий %(repo)s уже существует"
 
-#: kallithea/model/validators.py:348
+#: kallithea/model/validators.py:354
 #, python-format
 msgid "Repository \"%(repo)s\" already exists in group \"%(group)s\""
 msgstr "Репозитарий \"%(repo)s\" уже существует в группе \"%(group)s\""
 
-#: kallithea/model/validators.py:350
+#: kallithea/model/validators.py:356
 #, python-format
 msgid "Repository group with name \"%(repo)s\" already exists"
 msgstr "Группа репозиториев \"%(repo)s\" уже существует"
 
-#: kallithea/model/validators.py:465
+#: kallithea/model/validators.py:470
 #, fuzzy
 msgid "Invalid repository URL"
 msgstr "приватный репозиторий"
 
-#: kallithea/model/validators.py:466
+#: kallithea/model/validators.py:471
 msgid ""
 "Invalid repository URL. It must be a valid http, https, ssh, svn+http or "
 "svn+https URL"
 msgstr ""
 
-#: kallithea/model/validators.py:489
+#: kallithea/model/validators.py:496
 msgid "Fork has to be the same type as parent"
 msgstr "Тип форка будет совпадать с родительским"
 
-#: kallithea/model/validators.py:504
+#: kallithea/model/validators.py:511
 msgid "You don't have permissions to create repository in this group"
 msgstr "У вас недостаточно прав для создания репозиториев в этой группе"
 
-#: kallithea/model/validators.py:506
+#: kallithea/model/validators.py:513
 msgid "no permission to create repository in root location"
 msgstr "недостаточно прав для создания репозитория в корневом каталоге"
 
-#: kallithea/model/validators.py:556
+#: kallithea/model/validators.py:563
 msgid "You don't have permissions to create a group in this location"
 msgstr "У Вас недостаточно привилегий для создания группы в этом месте"
 
-#: kallithea/model/validators.py:597
+#: kallithea/model/validators.py:604
 msgid "This username or user group name is not valid"
 msgstr "Данное имя пользователя или группы пользователей недопустимо"
 
-#: kallithea/model/validators.py:690
+#: kallithea/model/validators.py:697
 msgid "This is not a valid path"
 msgstr "Этот путь ошибочен"
 
-#: kallithea/model/validators.py:705
+#: kallithea/model/validators.py:714
 #, fuzzy
 msgid "This email address is already in use"
 msgstr "Этот E-mail уже занят"
 
-#: kallithea/model/validators.py:725
+#: kallithea/model/validators.py:734
 #, fuzzy, python-format
 msgid "Email address \"%(email)s\" not found"
 msgstr "\"%(email)s\" не существует."
 
-#: kallithea/model/validators.py:762
+#: kallithea/model/validators.py:771
 msgid ""
 "The LDAP Login attribute of the CN must be specified - this is the name "
 "of the attribute that is equivalent to \"username\""
@@ -2214,28 +2209,28 @@
 "Для входа по LDAP должно быть указано значение аттрибута CN - это "
 "эквивалент имени пользователя"
 
-#: kallithea/model/validators.py:774
+#: kallithea/model/validators.py:783
 msgid "Please enter a valid IPv4 or IPv6 address"
 msgstr "Пожалуйста, введите существующий IPv4 или IPv6 адре"
 
-#: kallithea/model/validators.py:775
+#: kallithea/model/validators.py:784
 #, python-format
 msgid "The network size (bits) must be within the range of 0-32 (not %(bits)r)"
 msgstr ""
 "Значение маски подсети должно быть в пределах от 0 до 32 (%(bits)r - "
 "неверно)"
 
-#: kallithea/model/validators.py:808
+#: kallithea/model/validators.py:817
 msgid "Key name can only consist of letters, underscore, dash or numbers"
 msgstr ""
 "Ключевое имя может только состоять из букв, символа подчеркивания, тире "
 "или чисел"
 
-#: kallithea/model/validators.py:822
+#: kallithea/model/validators.py:831
 msgid "Filename cannot be inside a directory"
 msgstr "Файла нет в каталоге"
 
-#: kallithea/model/validators.py:838
+#: kallithea/model/validators.py:847
 #, python-format
 msgid "Plugins %(loaded)s and %(next_to_load)s both export the same name"
 msgstr ""
@@ -2362,7 +2357,7 @@
 #: kallithea/templates/admin/user_groups/user_groups.html:50
 #: kallithea/templates/pullrequests/pullrequest_data.html:16
 #: kallithea/templates/pullrequests/pullrequest_show.html:156
-#: kallithea/templates/pullrequests/pullrequest_show.html:233
+#: kallithea/templates/pullrequests/pullrequest_show.html:244
 #: kallithea/templates/summary/summary.html:134
 msgid "Owner"
 msgstr "Владелец"
@@ -2410,7 +2405,7 @@
 #: kallithea/templates/index_base.html:144
 #: kallithea/templates/admin/my_account/my_account_repos.html:61
 #: kallithea/templates/admin/my_account/my_account_watched.html:61
-#: kallithea/templates/base/base.html:140 kallithea/templates/base/root.html:47
+#: kallithea/templates/base/root.html:47
 #: kallithea/templates/bookmarks/bookmarks.html:83
 #: kallithea/templates/branches/branches.html:83
 #: kallithea/templates/journal/journal.html:202
@@ -2420,7 +2415,7 @@
 msgstr "Загрузка..."
 
 #: kallithea/templates/login.html:5 kallithea/templates/login.html:15
-#: kallithea/templates/base/base.html:326
+#: kallithea/templates/base/base.html:414
 msgid "Log In"
 msgstr "Войти"
 
@@ -2435,7 +2430,7 @@
 #: kallithea/templates/admin/users/user_add.html:32
 #: kallithea/templates/admin/users/user_edit_profile.html:24
 #: kallithea/templates/admin/users/users.html:50
-#: kallithea/templates/base/base.html:302
+#: kallithea/templates/base/base.html:390
 #: kallithea/templates/pullrequests/pullrequest_show.html:166
 msgid "Username"
 msgstr "Имя пользователя"
@@ -2443,7 +2438,7 @@
 #: kallithea/templates/login.html:33 kallithea/templates/register.html:33
 #: kallithea/templates/admin/my_account/my_account.html:37
 #: kallithea/templates/admin/users/user_add.html:41
-#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:399
 msgid "Password"
 msgstr "Пароль"
 
@@ -2455,7 +2450,7 @@
 msgid "Forgot your password ?"
 msgstr "Забыли пароль?"
 
-#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:322
+#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:410
 msgid "Don't have an account ?"
 msgstr "Нет аккаунта?"
 
@@ -2494,8 +2489,6 @@
 
 #: kallithea/templates/password_reset.html:47
 #, fuzzy
-#| msgid "" "Password reset link will be sent to the email address matching
-#| your " "username."
 msgid ""
 "A password reset link will be sent to the specified email address if it "
 "is registered in the system."
@@ -2518,13 +2511,11 @@
 
 #: kallithea/templates/password_reset_confirmation.html:39
 #, fuzzy
-#| msgid "New password"
 msgid "New Password"
 msgstr "Новый пароль"
 
 #: kallithea/templates/password_reset_confirmation.html:48
 #, fuzzy
-#| msgid "Confirm new password"
 msgid "Confirm New Password"
 msgstr "Подтвердите новый пароль"
 
@@ -2583,10 +2574,6 @@
 msgid "There are no branches yet"
 msgstr "Ветки ещё не созданы"
 
-#: kallithea/templates/switch_to_list.html:16
-msgid "Closed Branches"
-msgstr "Закрытые ветки"
-
 #: kallithea/templates/switch_to_list.html:32
 #: kallithea/templates/tags/tags_data.html:44
 msgid "There are no tags yet"
@@ -2818,12 +2805,12 @@
 msgid "Never"
 msgstr "никогда"
 
-#: kallithea/templates/admin/gists/edit.html:145
+#: kallithea/templates/admin/gists/edit.html:146
 msgid "Update Gist"
 msgstr "Обновить"
 
-#: kallithea/templates/admin/gists/edit.html:146
-#: kallithea/templates/changeset/changeset_file_comment.html:81
+#: kallithea/templates/admin/gists/edit.html:147
+#: kallithea/templates/changeset/changeset_file_comment.html:105
 msgid "Cancel"
 msgstr "Отмена"
 
@@ -2846,7 +2833,7 @@
 
 #: kallithea/templates/admin/gists/index.html:37
 #: kallithea/templates/admin/gists/show.html:25
-#: kallithea/templates/base/base.html:237
+#: kallithea/templates/base/base.html:321
 msgid "Create New Gist"
 msgstr "Создать новую gist-запись"
 
@@ -2934,7 +2921,8 @@
 #: kallithea/templates/admin/settings/settings_hooks.html:36
 #: kallithea/templates/admin/users/user_edit_emails.html:19
 #: kallithea/templates/admin/users/user_edit_ips.html:22
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+#: kallithea/templates/changeset/changeset_file_comment.html:95
 #: kallithea/templates/data_table/_dt_elements.html:129
 #: kallithea/templates/data_table/_dt_elements.html:157
 #: kallithea/templates/data_table/_dt_elements.html:173
@@ -2954,8 +2942,6 @@
 #: kallithea/templates/base/perms_summary.html:43
 #: kallithea/templates/base/perms_summary.html:79
 #: kallithea/templates/base/perms_summary.html:81
-#: kallithea/templates/changeset/changeset_file_comment.html:83
-#: kallithea/templates/changeset/changeset_file_comment.html:192
 #: kallithea/templates/data_table/_dt_elements.html:122
 #: kallithea/templates/data_table/_dt_elements.html:123
 #: kallithea/templates/data_table/_dt_elements.html:150
@@ -2982,13 +2968,12 @@
 msgstr "создана"
 
 #: kallithea/templates/admin/gists/show.html:86
-#: kallithea/templates/files/files_source.html:73
 msgid "Show as raw"
 msgstr "Показать только текст"
 
 #: kallithea/templates/admin/my_account/my_account.html:5
 #: kallithea/templates/admin/my_account/my_account.html:9
-#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:431
 msgid "My Account"
 msgstr "Мой Аккаунт"
 
@@ -3178,7 +3163,7 @@
 msgstr "Комментарии"
 
 #: kallithea/templates/admin/notifications/notifications.html:26
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 msgid "Pull Requests"
 msgstr "Pull-запросы"
 
@@ -3196,7 +3181,7 @@
 msgstr "Показать уведомление"
 
 #: kallithea/templates/admin/notifications/show_notification.html:9
-#: kallithea/templates/base/base.html:342
+#: kallithea/templates/base/base.html:430
 msgid "Notifications"
 msgstr "Уведомления"
 
@@ -3407,7 +3392,7 @@
 #: kallithea/templates/admin/repos/repo_edit.html:40
 #: kallithea/templates/admin/settings/settings.html:11
 #: kallithea/templates/admin/user_groups/user_group_edit.html:29
-#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:151
+#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:148
 #: kallithea/templates/data_table/_dt_elements.html:45
 #: kallithea/templates/data_table/_dt_elements.html:49
 msgid "Settings"
@@ -3679,6 +3664,11 @@
 msgid "Unlock Repository"
 msgstr "Разблокировать репозиторий"
 
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:56
+#, python-format
+msgid "Locked by %s on %s"
+msgstr ""
+
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:60
 msgid "Confirm to lock repository."
 msgstr "Подтвердите блокировку репозитория."
@@ -3736,10 +3726,6 @@
 msgid "Invalidate Repository Cache"
 msgstr "Сбросить кэш репозитория"
 
-#: kallithea/templates/admin/repos/repo_edit_caches.html:4
-msgid "Confirm to invalidate repository cache."
-msgstr "Подтвердите сброс кэша."
-
 #: kallithea/templates/admin/repos/repo_edit_caches.html:7
 msgid ""
 "Manually invalidate cache for this repository. On first access, the "
@@ -4484,21 +4470,17 @@
 msgid "Files"
 msgstr "Файлы"
 
-#: kallithea/templates/base/base.html:138
-msgid "Switch To"
-msgstr "Переключиться на"
-
-#: kallithea/templates/base/base.html:145
-#: kallithea/templates/base/base.html:147
+#: kallithea/templates/base/base.html:142
+#: kallithea/templates/base/base.html:144
 msgid "Options"
 msgstr "Опции"
 
-#: kallithea/templates/base/base.html:155
+#: kallithea/templates/base/base.html:152
 #: kallithea/templates/forks/forks_data.html:21
 msgid "Compare Fork"
 msgstr "Сравнить форк"
 
-#: kallithea/templates/base/base.html:157
+#: kallithea/templates/base/base.html:154
 #: kallithea/templates/bookmarks/bookmarks.html:56
 #: kallithea/templates/bookmarks/bookmarks_data.html:13
 #: kallithea/templates/branches/branches.html:56
@@ -4508,111 +4490,116 @@
 msgid "Compare"
 msgstr "Сравнить"
 
-#: kallithea/templates/base/base.html:159
-#: kallithea/templates/base/base.html:247
+#: kallithea/templates/base/base.html:156
+#: kallithea/templates/base/base.html:331
 #: kallithea/templates/search/search.html:14
 #: kallithea/templates/search/search.html:54
 msgid "Search"
 msgstr "Поиск"
 
-#: kallithea/templates/base/base.html:163
+#: kallithea/templates/base/base.html:160
 msgid "Unlock"
 msgstr "Разблокировать"
 
-#: kallithea/templates/base/base.html:165
+#: kallithea/templates/base/base.html:162
 msgid "Lock"
 msgstr "Заблокировать"
 
-#: kallithea/templates/base/base.html:173
+#: kallithea/templates/base/base.html:170
 msgid "Follow"
 msgstr "Наблюдать"
 
+#: kallithea/templates/base/base.html:171
+msgid "Unfollow"
+msgstr "Не наблюдать"
+
 #: kallithea/templates/base/base.html:174
-msgid "Unfollow"
-msgstr "Не наблюдать"
-
-#: kallithea/templates/base/base.html:177
 #: kallithea/templates/data_table/_dt_elements.html:37
 #: kallithea/templates/data_table/_dt_elements.html:41
 #: kallithea/templates/forks/fork.html:9
 msgid "Fork"
 msgstr "Форк"
 
-#: kallithea/templates/base/base.html:178
+#: kallithea/templates/base/base.html:175
 #: kallithea/templates/pullrequests/pullrequest.html:88
 msgid "Create Pull Request"
 msgstr "Создать Pull запрос"
 
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 #, python-format
 msgid "Show Pull Requests for %s"
 msgstr "Показать pull-запросы для %s"
 
-#: kallithea/templates/base/base.html:221
+#: kallithea/templates/base/base.html:193
+msgid "Switch To"
+msgstr "Переключиться на"
+
+#: kallithea/templates/base/base.html:203
+#: kallithea/templates/base/base.html:485
+msgid "No matches found"
+msgstr ""
+
+#: kallithea/templates/base/base.html:305
 msgid "Show recent activity"
 msgstr "Показать последнюю активность"
 
-#: kallithea/templates/base/base.html:227
-#: kallithea/templates/base/base.html:228
+#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:312
 msgid "Public journal"
 msgstr "Общедоступный журнал"
 
-#: kallithea/templates/base/base.html:233
+#: kallithea/templates/base/base.html:317
 msgid "Show public gists"
 msgstr "Показать публичные записи"
 
-#: kallithea/templates/base/base.html:234
+#: kallithea/templates/base/base.html:318
 msgid "Gists"
 msgstr "Gist"
 
-#: kallithea/templates/base/base.html:238
+#: kallithea/templates/base/base.html:322
 msgid "All Public Gists"
 msgstr "Все публичные Gist-записи"
 
-#: kallithea/templates/base/base.html:240
+#: kallithea/templates/base/base.html:324
 msgid "My Public Gists"
 msgstr "Мои публичные Gist-записи"
 
-#: kallithea/templates/base/base.html:241
+#: kallithea/templates/base/base.html:325
 msgid "My Private Gists"
 msgstr "Мои приватные Gist-записи"
 
-#: kallithea/templates/base/base.html:246
+#: kallithea/templates/base/base.html:330
 msgid "Search in repositories"
 msgstr "Поиск по репозиториям"
 
-#: kallithea/templates/base/base.html:269
-#: kallithea/templates/base/base.html:270
+#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:354
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:6
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:10
 msgid "My Pull Requests"
 msgstr "Мои Pull-запросы"
 
-#: kallithea/templates/base/base.html:289
+#: kallithea/templates/base/base.html:377
 msgid "Not Logged In"
 msgstr "Не авторизован"
 
-#: kallithea/templates/base/base.html:296
+#: kallithea/templates/base/base.html:384
 msgid "Login to Your Account"
 msgstr "Авторизоваться"
 
-#: kallithea/templates/base/base.html:319
+#: kallithea/templates/base/base.html:407
 msgid "Forgot password ?"
 msgstr "Забыли пароль?"
 
-#: kallithea/templates/base/base.html:346
+#: kallithea/templates/base/base.html:434
 msgid "Log Out"
 msgstr "Выход"
 
-#: kallithea/templates/base/base.html:395
-msgid "No matches found"
-msgstr ""
-
-#: kallithea/templates/base/base.html:524
+#: kallithea/templates/base/base.html:615
 msgid "Keyboard shortcuts"
 msgstr ""
 
-#: kallithea/templates/base/base.html:533
+#: kallithea/templates/base/base.html:624
 msgid "Site-wide shortcuts"
 msgstr ""
 
@@ -4716,7 +4703,6 @@
 
 #: kallithea/templates/base/root.html:31
 #, fuzzy
-#| msgid "on pull request"
 msgid "Open New Pull Request from {0}"
 msgstr "Комментарий в pull-запросе"
 
@@ -4726,7 +4712,6 @@
 
 #: kallithea/templates/base/root.html:33
 #, fuzzy
-#| msgid "Show Selected Changesets __S &rarr; __E"
 msgid "Show Selected Changesets {0} &rarr; {1}"
 msgstr "Показать выбранные наборы изменений: __S &rarr; __E"
 
@@ -4736,6 +4721,7 @@
 
 #: kallithea/templates/base/root.html:35
 #: kallithea/templates/changeset/diff_block.html:8
+#: kallithea/templates/changeset/diff_block.html:21
 msgid "Collapse Diff"
 msgstr "Свернуть сравнение"
 
@@ -4845,53 +4831,55 @@
 #: kallithea/templates/changelog/changelog_summary_data.html:20
 #, fuzzy, python-format
 msgid ""
-"Changeset status: %s\n"
+"Changeset status: %s by %s\n"
 "Click to open associated pull request %s"
 msgstr ""
 "Статус набора изенений: %s⏎\n"
 "Кликрните, чтобы перейти к соответствующему pull-request'у #%s"
 
 #: kallithea/templates/changelog/changelog.html:96
-#: kallithea/templates/compare/compare_cs.html:24
-#, python-format
-msgid "Changeset status: %s"
+#: kallithea/templates/changelog/changelog_summary_data.html:24
+#, fuzzy, python-format
+msgid "Changeset status: %s by %s"
 msgstr "Статус набора изменений: %s"
 
-#: kallithea/templates/changelog/changelog.html:115
+#: kallithea/templates/changelog/changelog.html:116
 #: kallithea/templates/compare/compare_cs.html:63
 msgid "Expand commit message"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:124
+#: kallithea/templates/changelog/changelog.html:125
 #: kallithea/templates/compare/compare_cs.html:30
 msgid "Changeset has comments"
 msgstr "Комментарии отсутствуют"
 
-#: kallithea/templates/changelog/changelog.html:134
-#: kallithea/templates/changelog/changelog_summary_data.html:54
+#: kallithea/templates/changelog/changelog.html:135
+#: kallithea/templates/changelog/changelog_summary_data.html:57
 #: kallithea/templates/changeset/changeset.html:94
 #: kallithea/templates/changeset/changeset_range.html:92
 #, python-format
 msgid "Bookmark %s"
 msgstr "Закладка %s"
 
-#: kallithea/templates/changelog/changelog.html:140
-#: kallithea/templates/changelog/changelog_summary_data.html:60
+#: kallithea/templates/changelog/changelog.html:141
+#: kallithea/templates/changelog/changelog_summary_data.html:63
 #: kallithea/templates/changeset/changeset.html:101
 #: kallithea/templates/changeset/changeset_range.html:98
+#: kallithea/templates/compare/compare_cs.html:69
+#: kallithea/templates/pullrequests/pullrequest_show.html:203
 #, python-format
 msgid "Tag %s"
 msgstr "Метка %s"
 
-#: kallithea/templates/changelog/changelog.html:145
-#: kallithea/templates/changelog/changelog_summary_data.html:65
+#: kallithea/templates/changelog/changelog.html:146
+#: kallithea/templates/changelog/changelog_summary_data.html:68
 #: kallithea/templates/changeset/changeset.html:106
 #: kallithea/templates/changeset/changeset_range.html:102
 #, python-format
 msgid "Branch %s"
 msgstr "Ветка %s"
 
-#: kallithea/templates/changelog/changelog.html:310
+#: kallithea/templates/changelog/changelog.html:311
 msgid "There are no changes yet"
 msgstr "Изменений ещё нет"
 
@@ -4907,7 +4895,7 @@
 
 #: kallithea/templates/changelog/changelog_details.html:6
 #: kallithea/templates/changeset/changeset.html:79
-#: kallithea/templates/changeset/diff_block.html:79
+#: kallithea/templates/changeset/diff_block.html:47
 msgid "Added"
 msgstr "Добавлено"
 
@@ -4937,22 +4925,22 @@
 msgid "Refs"
 msgstr "Ссылки"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:81
+#: kallithea/templates/changelog/changelog_summary_data.html:84
 msgid "Add or upload files directly via Kallithea"
 msgstr "Добавить или загрузить файлы через Kallithea"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:84
+#: kallithea/templates/changelog/changelog_summary_data.html:87
 #: kallithea/templates/files/files_add.html:21
 #: kallithea/templates/files/files_ypjax.html:9
 msgid "Add New File"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:90
+#: kallithea/templates/changelog/changelog_summary_data.html:93
 #, fuzzy
 msgid "Push new repository"
 msgstr "Отправить новый репозиторий"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:98
+#: kallithea/templates/changelog/changelog_summary_data.html:101
 msgid "Existing repository?"
 msgstr "Существующий репозиторий?"
 
@@ -4970,13 +4958,13 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:50
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #: kallithea/templates/changeset/changeset_range.html:48
 msgid "Changeset status"
 msgstr "Статут изменений"
 
 #: kallithea/templates/changeset/changeset.html:54
-#: kallithea/templates/changeset/diff_block.html:27
+#: kallithea/templates/changeset/diff_block.html:72
 #: kallithea/templates/files/diff_2way.html:49
 msgid "Raw diff"
 msgstr "Отобразить в формате diff"
@@ -4986,7 +4974,7 @@
 msgstr "Применить разностное исправление (Patch diff)"
 
 #: kallithea/templates/changeset/changeset.html:60
-#: kallithea/templates/changeset/diff_block.html:30
+#: kallithea/templates/changeset/diff_block.html:75
 #: kallithea/templates/files/diff_2way.html:52
 msgid "Download diff"
 msgstr "Скачать diff"
@@ -5016,8 +5004,8 @@
 msgstr "Создано"
 
 #: kallithea/templates/changeset/changeset.html:166
-#: kallithea/templates/compare/compare_diff.html:54
-#: kallithea/templates/pullrequests/pullrequest_show.html:318
+#: kallithea/templates/compare/compare_diff.html:60
+#: kallithea/templates/pullrequests/pullrequest_show.html:329
 #, python-format
 msgid "%s file changed"
 msgid_plural "%s files changed"
@@ -5026,8 +5014,8 @@
 msgstr[2] "%s файла изменено"
 
 #: kallithea/templates/changeset/changeset.html:168
-#: kallithea/templates/compare/compare_diff.html:56
-#: kallithea/templates/pullrequests/pullrequest_show.html:320
+#: kallithea/templates/compare/compare_diff.html:62
+#: kallithea/templates/pullrequests/pullrequest_show.html:331
 #, python-format
 msgid "%s file changed with %s insertions and %s deletions"
 msgid_plural "%s files changed with %s insertions and %s deletions"
@@ -5037,13 +5025,13 @@
 
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Show full diff anyway"
 msgstr "Показать полный diff"
 
-#: kallithea/templates/changeset/changeset.html:247
-#: kallithea/templates/changeset/changeset.html:284
+#: kallithea/templates/changeset/changeset.html:231
+#: kallithea/templates/changeset/changeset.html:268
 #, fuzzy
 msgid "No revisions"
 msgstr "версии"
@@ -5062,65 +5050,71 @@
 msgid "on this changeset"
 msgstr "Нет изменений"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
 msgid "Delete comment?"
 msgstr "Удалить комментарий?"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #, fuzzy
 msgid "Status change"
 msgstr "Последние изменения"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:59
-msgid "Commenting on line {1}."
+#, fuzzy
+msgid "Commenting on line."
 msgstr "Комментарий к строке {1}."
 
 #: kallithea/templates/changeset/changeset_file_comment.html:60
-#: kallithea/templates/changeset/changeset_file_comment.html:148
-#, python-format
-msgid "Comments parsed using %s syntax with %s support."
-msgstr ""
-"Парсинг комментариев выполнен с использованием синтаксиса %s с поддержкой"
-" %s."
-
-#: kallithea/templates/changeset/changeset_file_comment.html:62
-msgid "Use @username inside this text to notify another user"
+#, fuzzy
+msgid ""
+"Comments are in plain text. Use @username inside this text to notify "
+"another user."
 msgstr ""
 "Используйте @имя_пользователя в тексте, чтобы отправить оповещение "
 "указанному пользователю."
 
-#: kallithea/templates/changeset/changeset_file_comment.html:72
-#: kallithea/templates/changeset/changeset_file_comment.html:184
-msgid "Comment preview"
-msgstr "Предварительный просмотр комментария"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:77
+#: kallithea/templates/changeset/changeset_file_comment.html:67
+msgid "Set changeset status"
+msgstr "Изменить статус ревизии"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:69
+msgid "Vote for pull request status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:75
+msgid "No change"
+msgstr "Без изменений"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:88
+#, fuzzy
+msgid "Finish pull request"
+msgstr "Комментарий в pull-запросе"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:91
+msgid "Close"
+msgstr "Закрыть"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:103
 msgid "Submitting ..."
 msgstr "Применение..."
 
-#: kallithea/templates/changeset/changeset_file_comment.html:80
-#: kallithea/templates/changeset/changeset_file_comment.html:190
+#: kallithea/templates/changeset/changeset_file_comment.html:104
 msgid "Comment"
 msgstr "Комментировать"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:82
-#: kallithea/templates/changeset/changeset_file_comment.html:191
-msgid "Preview"
-msgstr "Предпросмотр"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "You need to be logged in to comment."
 msgstr "Вам необходимо авторизоваться, чтобы оставлять комментарии."
 
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "Login now"
 msgstr "Авторизоваться сейчас"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:94
+#: kallithea/templates/changeset/changeset_file_comment.html:116
 msgid "Hide"
 msgstr "Скрыть"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:106
+#: kallithea/templates/changeset/changeset_file_comment.html:128
 #, python-format
 msgid "%d comment"
 msgid_plural "%d comments"
@@ -5128,7 +5122,7 @@
 msgstr[1] "%d комментария"
 msgstr[2] "%d комментариев"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:107
+#: kallithea/templates/changeset/changeset_file_comment.html:129
 #, python-format
 msgid "%d inline"
 msgid_plural "%d inline"
@@ -5136,7 +5130,7 @@
 msgstr[1] "%d к строкам"
 msgstr[2] "%d к строкам"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:108
+#: kallithea/templates/changeset/changeset_file_comment.html:130
 #, python-format
 msgid "%d general"
 msgid_plural "%d general"
@@ -5144,29 +5138,6 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:150
-#, fuzzy
-msgid "Use @username inside this text to notify another user."
-msgstr ""
-"Используйте @имя_пользователя в тексте, чтобы отправить оповещение "
-"указанному пользователю."
-
-#: kallithea/templates/changeset/changeset_file_comment.html:157
-msgid "Vote for pull request status"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:159
-msgid "Set changeset status"
-msgstr "Изменить статус ревизии"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:163
-msgid "No change"
-msgstr "Без изменений"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:176
-msgid "Close"
-msgstr "Закрыть"
-
 #: kallithea/templates/changeset/changeset_range.html:5
 #, python-format
 msgid "%s Changesets"
@@ -5176,29 +5147,28 @@
 msgid "Files affected"
 msgstr "Затронутые файлы"
 
-#: kallithea/templates/changeset/diff_block.html:21
+#: kallithea/templates/changeset/diff_block.html:54
+msgid "Deleted"
+msgstr "Удалён"
+
+#: kallithea/templates/changeset/diff_block.html:57
+msgid "Renamed"
+msgstr "Переименован"
+
+#: kallithea/templates/changeset/diff_block.html:66
 #: kallithea/templates/files/diff_2way.html:43
 msgid "Show full diff for this file"
 msgstr "Показать полный diff для этого файла"
 
-#: kallithea/templates/changeset/diff_block.html:24
-#: kallithea/templates/changeset/diff_block.html:98
+#: kallithea/templates/changeset/diff_block.html:69
 #: kallithea/templates/files/diff_2way.html:46
 msgid "Show full side-by-side diff for this file"
 msgstr "Показать полный diff для этого файла"
 
-#: kallithea/templates/changeset/diff_block.html:38
+#: kallithea/templates/changeset/diff_block.html:83
 msgid "Show inline comments"
 msgstr "Показать комментарии в строках"
 
-#: kallithea/templates/changeset/diff_block.html:86
-msgid "Deleted"
-msgstr "Удалён"
-
-#: kallithea/templates/changeset/diff_block.html:89
-msgid "Renamed"
-msgstr "Переименован"
-
 #: kallithea/templates/compare/compare_cs.html:4
 msgid "No changesets"
 msgstr "Нет изменений"
@@ -5207,6 +5177,11 @@
 msgid "Ancestor"
 msgstr "Предок"
 
+#: kallithea/templates/compare/compare_cs.html:24
+#, python-format
+msgid "Changeset status: %s"
+msgstr "Статус набора изменений: %s"
+
 #: kallithea/templates/compare/compare_cs.html:44
 msgid "First (oldest) changeset in this list"
 msgstr ""
@@ -5219,29 +5194,29 @@
 msgid "Position in this list of changesets"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:76
+#: kallithea/templates/compare/compare_cs.html:85
 msgid "Show merge diff"
 msgstr "Показать merge diff"
 
-#: kallithea/templates/compare/compare_cs.html:86
-#: kallithea/templates/pullrequests/pullrequest_show.html:310
+#: kallithea/templates/compare/compare_cs.html:95
+#: kallithea/templates/pullrequests/pullrequest_show.html:321
 msgid "Common ancestor"
 msgstr "Общий предок"
 
-#: kallithea/templates/compare/compare_cs.html:90
+#: kallithea/templates/compare/compare_cs.html:99
 msgid "No common ancestor found - repositories are unrelated"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:98
+#: kallithea/templates/compare/compare_cs.html:107
 msgid "is"
 msgstr "отстаёт на"
 
-#: kallithea/templates/compare/compare_cs.html:99
+#: kallithea/templates/compare/compare_cs.html:108
 #, python-format
 msgid "%s changesets"
 msgstr "%s изменений"
 
-#: kallithea/templates/compare/compare_cs.html:100
+#: kallithea/templates/compare/compare_cs.html:109
 msgid "behind"
 msgstr "от"
 
@@ -5252,20 +5227,20 @@
 msgstr "%s Сравнить"
 
 #: kallithea/templates/compare/compare_diff.html:13
-#: kallithea/templates/compare/compare_diff.html:35
+#: kallithea/templates/compare/compare_diff.html:41
 msgid "Compare Revisions"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:33
+#: kallithea/templates/compare/compare_diff.html:39
 msgid "Swap"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:42
+#: kallithea/templates/compare/compare_diff.html:48
 msgid "Compare revisions, branches, bookmarks, or tags."
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:47
-#: kallithea/templates/pullrequests/pullrequest_show.html:305
+#: kallithea/templates/compare/compare_diff.html:53
+#: kallithea/templates/pullrequests/pullrequest_show.html:316
 #, python-format
 msgid "Showing %s commit"
 msgid_plural "Showing %s commits"
@@ -5273,8 +5248,8 @@
 msgstr[1] "Показать %s commit'а"
 msgstr[2] "Показать %s commit'ов"
 
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
 msgid "Show full diff"
 msgstr "Показать полный diff"
 
@@ -5331,21 +5306,26 @@
 
 #: kallithea/templates/email_templates/password_reset.html:6
 #, fuzzy
-#| msgid "We received a request to create a new password for your account."
 msgid "We have received a request to reset the password for your account."
 msgstr "Мы отправили запрос на создание нового пароля для вашего аккаунта."
 
-#: kallithea/templates/email_templates/password_reset.html:7
-msgid "To set a new password, click the following link"
+#: kallithea/templates/email_templates/password_reset.html:8
+msgid ""
+"This account is however managed outside this system and the password "
+"cannot be changed here."
 msgstr ""
 
 #: kallithea/templates/email_templates/password_reset.html:10
+msgid "To set a new password, click the following link"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:13
 msgid ""
 "Should you not be able to use the link above, please type the following "
 "code into the password reset form"
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:12
+#: kallithea/templates/email_templates/password_reset.html:16
 msgid ""
 "If it weren't you who requested the password reset, just disregard this "
 "message."
@@ -5428,8 +5408,9 @@
 msgstr ""
 
 #: kallithea/templates/files/files_add.html:53
-msgid "New file mode"
-msgstr "Режим нового файла"
+#, fuzzy
+msgid "New file type"
+msgstr "новый файл"
 
 #: kallithea/templates/files/files_add.html:64
 #: kallithea/templates/files/files_delete.html:43
@@ -5560,9 +5541,17 @@
 msgid "Binary file (%s)"
 msgstr "Бинарный файл (%s)"
 
-#: kallithea/templates/files/files_source.html:73
-msgid "File is too big to display"
-msgstr "Файл слишком большой для отображения"
+#: kallithea/templates/files/files_source.html:74
+msgid "File is too big to display."
+msgstr "Файл слишком большой для отображения."
+
+#: kallithea/templates/files/files_source.html:76
+msgid "Show full annotation anyway."
+msgstr "Показать полный diff."
+
+#: kallithea/templates/files/files_source.html:78
+msgid "Show as raw."
+msgstr "Показать только текст."
 
 #: kallithea/templates/files/files_ypjax.html:5
 msgid "annotation"
@@ -5761,9 +5750,9 @@
 msgstr "%s Pull-запрос #%s"
 
 #: kallithea/templates/pullrequests/pullrequest_show.html:10
-#, fuzzy, python-format
+#, python-format
 msgid "Pull request %s from %s#%s"
-msgstr "Pull-запросы №%s от %s#%s"
+msgstr "Pull-запросы %s от %s#%s"
 
 #: kallithea/templates/pullrequests/pullrequest_show.html:57
 #, fuzzy
@@ -5831,40 +5820,46 @@
 msgid "Current revision - no change"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:213
+#: kallithea/templates/pullrequests/pullrequest_show.html:215
+msgid ""
+"Pull requests do not change once created. Select a revision and save to "
+"replace this pull request with a new one."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:224
 msgid "Pull Request Reviewers"
 msgstr "Рецензенты pull-запросов"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:238
+#: kallithea/templates/pullrequests/pullrequest_show.html:249
 msgid "Remove reviewer"
 msgstr "Удалить рецензента"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:250
-msgid "Type name of reviewer to add"
-msgstr ""
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:258
-msgid "Potential Reviewers"
-msgstr "Потенциальные рецензенты"
-
 #: kallithea/templates/pullrequests/pullrequest_show.html:261
+msgid "Type name of reviewer to add"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:269
+msgid "Potential Reviewers"
+msgstr "Потенциальные рецензенты"
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:272
 msgid "Click to add the repository owner as reviewer:"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:284
+#: kallithea/templates/pullrequests/pullrequest_show.html:295
 msgid "Save Changes"
 msgstr "Сохранить изменения"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:285
+#: kallithea/templates/pullrequests/pullrequest_show.html:296
 #, fuzzy
-msgid "Save as New Pull Request"
+msgid "Save Updates as New Pull Request"
 msgstr "Создать новый pull запрос"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:286
+#: kallithea/templates/pullrequests/pullrequest_show.html:297
 msgid "Cancel Changes"
 msgstr "Отменить изменения"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#: kallithea/templates/pullrequests/pullrequest_show.html:307
 #, fuzzy
 msgid "Pull Request Content"
 msgstr "Статус pull-request'а был изменен"
@@ -5875,8 +5870,8 @@
 msgstr "%s Запросы на внесение изменений"
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:11
-#, python-format
-msgid "Pull Requests from %s'"
+#, fuzzy, python-format
+msgid "Pull Requests from '%s'"
 msgstr "Pull-запросы от %s"
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:13
@@ -6083,9 +6078,8 @@
 msgstr "Отметьте для скачивания архива с дочерними репозиториями"
 
 #: kallithea/templates/summary/summary.html:125
-#, fuzzy
 msgid "With subrepos"
-msgstr "с дочерними репозиториями"
+msgstr "С дочерними репозиториями"
 
 #: kallithea/templates/summary/summary.html:156
 msgid "Repository Size"
@@ -6360,27 +6354,6 @@
 #~ msgid "reviewer"
 #~ msgstr "рецензент"
 
-#~ msgid ""
-#~ "Your password reset was successful, new"
-#~ " password has been sent to your "
-#~ "email"
-#~ msgstr "Сброс пароля произведён, новый пароль был отправлен на ваш email"
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " changeset %(short_id)s on %(branch)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Added by %(pr_username)s] %(repo_name)s pull"
-#~ " request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " pull request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
 #~ msgid "Your new password"
 #~ msgstr "Ваш новый пароль"
 
@@ -6398,8 +6371,6 @@
 
 #~ msgid "Please ignore this email if you did not request a new password ."
 #~ msgstr ""
-#~ "Пожалуйста, проигнорируйте данное сообщение, "
-#~ "если вы не запрашивали новый пароль."
 
 #~ msgid "Created by"
 #~ msgstr "Создано"
--- a/kallithea/i18n/sk/LC_MESSAGES/kallithea.po	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/i18n/sk/LC_MESSAGES/kallithea.po	Fri Nov 18 01:11:13 2016 +0100
@@ -7,24 +7,23 @@
 msgstr ""
 "Project-Id-Version: Kallithea 0.3\n"
 "Report-Msgid-Bugs-To: translations@kallithea-scm.org\n"
-"POT-Creation-Date: 2015-09-08 10:34+0200\n"
+"POT-Creation-Date: 2016-03-14 16:51+0100\n"
 "PO-Revision-Date: 2015-04-01 12:59+0200\n"
 "Last-Translator: Andrew Shadura <andrew@shadura.me>\n"
 "Language-Team: Slovak "
 "<https://hosted.weblate.org/projects/kallithea/kallithea/sk/>\n"
-"Language: sk\n"
+"Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2\n"
 "MIME-Version: 1.0\n"
-"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Type: text/plain; charset=utf-8\n"
 "Content-Transfer-Encoding: 8bit\n"
-"Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;\n"
-"X-Generator: Weblate 2.3-dev\n"
-
-#: kallithea/controllers/changelog.py:86
-#: kallithea/controllers/pullrequests.py:238 kallithea/lib/base.py:512
+"Generated-By: Babel 1.3\n"
+
+#: kallithea/controllers/changelog.py:85
+#: kallithea/controllers/pullrequests.py:240 kallithea/lib/base.py:515
 msgid "There are no changesets yet"
 msgstr "Zatiaľ nie sú žiadne zmeny"
 
-#: kallithea/controllers/changelog.py:166
+#: kallithea/controllers/changelog.py:164
 #: kallithea/controllers/admin/permissions.py:61
 #: kallithea/controllers/admin/permissions.py:65
 #: kallithea/controllers/admin/permissions.py:69
@@ -36,35 +35,29 @@
 msgid "None"
 msgstr ""
 
-#: kallithea/controllers/changelog.py:169 kallithea/controllers/files.py:196
+#: kallithea/controllers/changelog.py:167 kallithea/controllers/files.py:198
 msgid "(closed)"
 msgstr "(zatvorené)"
 
-#: kallithea/controllers/changeset.py:89
+#: kallithea/controllers/changeset.py:88
 msgid "Show whitespace"
 msgstr "Ukázať medzery"
 
-#: kallithea/controllers/changeset.py:96 kallithea/controllers/changeset.py:103
+#: kallithea/controllers/changeset.py:95 kallithea/controllers/changeset.py:102
 #: kallithea/templates/files/diff_2way.html:55
 msgid "Ignore whitespace"
 msgstr "Ignorovať medzery"
 
-#: kallithea/controllers/changeset.py:169
+#: kallithea/controllers/changeset.py:168
 #, python-format
 msgid "Increase diff context to %(num)s lines"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:212 kallithea/controllers/files.py:96
-#: kallithea/controllers/files.py:116 kallithea/controllers/files.py:742
+#: kallithea/controllers/changeset.py:233 kallithea/controllers/files.py:97
+#: kallithea/controllers/files.py:117 kallithea/controllers/files.py:744
 msgid "Such revision does not exist for this repository"
 msgstr "Taká revízia neexistuje"
 
-#: kallithea/controllers/changeset.py:383
-msgid ""
-"Changing status on a changeset associated with a closed pull request is "
-"not allowed"
-msgstr ""
-
 #: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:41
 msgid "Select changeset"
 msgstr ""
@@ -117,10 +110,10 @@
 #: kallithea/controllers/feed.py:87
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Changeset was too big and was cut off..."
 msgstr ""
 
@@ -129,111 +122,111 @@
 msgid "%s committed on %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:91
+#: kallithea/controllers/files.py:92
 msgid "Click here to add new file"
 msgstr "Kliknite pre pridanie nového súboru"
 
-#: kallithea/controllers/files.py:92
+#: kallithea/controllers/files.py:93
 #, python-format
 msgid "There are no files yet. %s"
 msgstr "Zatiaľ nie sú žiadne súbory. %s"
 
-#: kallithea/controllers/files.py:193
+#: kallithea/controllers/files.py:195
 #, python-format
 msgid "%s at %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:305 kallithea/controllers/files.py:365
-#: kallithea/controllers/files.py:432
+#: kallithea/controllers/files.py:307 kallithea/controllers/files.py:367
+#: kallithea/controllers/files.py:434
 #, python-format
 msgid "This repository has been locked by %s on %s"
 msgstr "Tento repozitár bol uzamknutý používateľom %s dňa %s"
 
-#: kallithea/controllers/files.py:317
-msgid "You can only delete files with revision being a valid branch "
-msgstr ""
-
-#: kallithea/controllers/files.py:328
+#: kallithea/controllers/files.py:319
+msgid "You can only delete files with revision being a valid branch"
+msgstr ""
+
+#: kallithea/controllers/files.py:330
 #, python-format
 msgid "Deleted file %s via Kallithea"
 msgstr "Zmazaný súbor %s cez Kallithea"
 
-#: kallithea/controllers/files.py:350
+#: kallithea/controllers/files.py:352
 #, python-format
 msgid "Successfully deleted file %s"
 msgstr "Úspešne zmazaný súbor %s"
 
-#: kallithea/controllers/files.py:354 kallithea/controllers/files.py:420
-#: kallithea/controllers/files.py:501
+#: kallithea/controllers/files.py:356 kallithea/controllers/files.py:422
+#: kallithea/controllers/files.py:503
 msgid "Error occurred during commit"
 msgstr "Došlo k chybe pri ukladaní"
 
-#: kallithea/controllers/files.py:377
-msgid "You can only edit files with revision being a valid branch "
-msgstr ""
-
-#: kallithea/controllers/files.py:391
+#: kallithea/controllers/files.py:379
+msgid "You can only edit files with revision being a valid branch"
+msgstr ""
+
+#: kallithea/controllers/files.py:393
 #, python-format
 msgid "Edited file %s via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:407
+#: kallithea/controllers/files.py:409
 msgid "No changes"
 msgstr "Žiadne zmeny"
 
-#: kallithea/controllers/files.py:416 kallithea/controllers/files.py:490
+#: kallithea/controllers/files.py:418 kallithea/controllers/files.py:492
 #, python-format
 msgid "Successfully committed to %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:443
+#: kallithea/controllers/files.py:445
 msgid "Added file via Kallithea"
 msgstr "Pridaný súbor cez Kallithea"
 
-#: kallithea/controllers/files.py:464
+#: kallithea/controllers/files.py:466
 msgid "No content"
 msgstr "Žiadny obsah"
 
-#: kallithea/controllers/files.py:468
+#: kallithea/controllers/files.py:470
 msgid "No filename"
 msgstr ""
 
-#: kallithea/controllers/files.py:493
+#: kallithea/controllers/files.py:495
 msgid "Location must be relative path and must not contain .. in path"
 msgstr ""
 
-#: kallithea/controllers/files.py:526
+#: kallithea/controllers/files.py:528
 msgid "Downloads disabled"
 msgstr "Sťahovanie vypnuté"
 
-#: kallithea/controllers/files.py:537
+#: kallithea/controllers/files.py:539
 #, python-format
 msgid "Unknown revision %s"
 msgstr "Neznáma revízia %s"
 
-#: kallithea/controllers/files.py:539
+#: kallithea/controllers/files.py:541
 msgid "Empty repository"
 msgstr "Prázdny repozitár"
 
-#: kallithea/controllers/files.py:541
+#: kallithea/controllers/files.py:543
 msgid "Unknown archive type"
 msgstr ""
 
-#: kallithea/controllers/files.py:771
+#: kallithea/controllers/files.py:773
 #: kallithea/templates/changeset/changeset_range.html:9
 #: kallithea/templates/email_templates/pull_request.html:15
 #: kallithea/templates/pullrequests/pullrequest.html:97
 msgid "Changesets"
 msgstr "Zmeny"
 
-#: kallithea/controllers/files.py:772 kallithea/controllers/pullrequests.py:176
-#: kallithea/model/scm.py:820 kallithea/templates/switch_to_list.html:3
+#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:175
+#: kallithea/model/scm.py:716 kallithea/templates/switch_to_list.html:3
 #: kallithea/templates/branches/branches.html:10
 msgid "Branches"
 msgstr "Vetvy"
 
-#: kallithea/controllers/files.py:773 kallithea/controllers/pullrequests.py:177
-#: kallithea/model/scm.py:831 kallithea/templates/switch_to_list.html:25
+#: kallithea/controllers/files.py:775 kallithea/controllers/pullrequests.py:176
+#: kallithea/model/scm.py:727 kallithea/templates/switch_to_list.html:25
 #: kallithea/templates/tags/tags.html:10
 msgid "Tags"
 msgstr "Tagy"
@@ -247,7 +240,7 @@
 msgid "Groups"
 msgstr "Skupiny"
 
-#: kallithea/controllers/home.py:89
+#: kallithea/controllers/home.py:94
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:106
 #: kallithea/templates/admin/repos/repo_add.html:12
 #: kallithea/templates/admin/repos/repo_add.html:16
@@ -255,23 +248,27 @@
 #: kallithea/templates/admin/users/user_edit_advanced.html:6
 #: kallithea/templates/base/base.html:60 kallithea/templates/base/base.html:77
 #: kallithea/templates/base/base.html:124
-#: kallithea/templates/base/base.html:390
-#: kallithea/templates/base/base.html:562
+#: kallithea/templates/base/base.html:479
+#: kallithea/templates/base/base.html:653
 msgid "Repositories"
 msgstr "Repozitáre"
 
-#: kallithea/controllers/home.py:130
+#: kallithea/controllers/home.py:139
 #: kallithea/templates/files/files_add.html:32
 #: kallithea/templates/files/files_delete.html:23
 #: kallithea/templates/files/files_edit.html:32
 msgid "Branch"
 msgstr "Vetva"
 
-#: kallithea/controllers/home.py:136
+#: kallithea/controllers/home.py:145 kallithea/templates/switch_to_list.html:16
+msgid "Closed Branches"
+msgstr ""
+
+#: kallithea/controllers/home.py:151
 msgid "Tag"
 msgstr ""
 
-#: kallithea/controllers/home.py:142
+#: kallithea/controllers/home.py:157
 msgid "Bookmark"
 msgstr "Záložka"
 
@@ -282,159 +279,164 @@
 msgstr ""
 
 #: kallithea/controllers/journal.py:115 kallithea/controllers/journal.py:157
-#: kallithea/templates/base/base.html:222
+#: kallithea/templates/base/base.html:306
 #: kallithea/templates/journal/journal.html:4
 #: kallithea/templates/journal/journal.html:12
 msgid "Journal"
 msgstr ""
 
-#: kallithea/controllers/login.py:151 kallithea/controllers/login.py:197
+#: kallithea/controllers/login.py:144 kallithea/controllers/login.py:190
 #, fuzzy
 msgid "Bad captcha"
 msgstr "zlá captcha"
 
-#: kallithea/controllers/login.py:157
-msgid "You have successfully registered into Kallithea"
-msgstr ""
-
-#: kallithea/controllers/login.py:202
+#: kallithea/controllers/login.py:150
+msgid "You have successfully registered with %s"
+msgstr ""
+
+#: kallithea/controllers/login.py:195
 msgid "A password reset confirmation code has been sent"
 msgstr ""
 
-#: kallithea/controllers/login.py:251
+#: kallithea/controllers/login.py:244
 msgid "Invalid password reset token"
 msgstr ""
 
-#: kallithea/controllers/login.py:256
+#: kallithea/controllers/login.py:249
 #: kallithea/controllers/admin/my_account.py:167
 msgid "Successfully updated password"
 msgstr "Úspešne aktualizované heslo"
 
-#: kallithea/controllers/pullrequests.py:124
+#: kallithea/controllers/pullrequests.py:123
 #, python-format
 msgid "%s (closed)"
 msgstr "%s (zatvorené)"
 
-#: kallithea/controllers/pullrequests.py:152
+#: kallithea/controllers/pullrequests.py:151
 #: kallithea/templates/changeset/changeset.html:12
 #: kallithea/templates/email_templates/changeset_comment.html:17
 msgid "Changeset"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:173
+#: kallithea/controllers/pullrequests.py:172
 msgid "Special"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:174
+#: kallithea/controllers/pullrequests.py:173
 msgid "Peer branches"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:175 kallithea/model/scm.py:826
+#: kallithea/controllers/pullrequests.py:174 kallithea/model/scm.py:722
 #: kallithea/templates/switch_to_list.html:38
 #: kallithea/templates/bookmarks/bookmarks.html:10
 msgid "Bookmarks"
 msgstr "Záložky"
 
-#: kallithea/controllers/pullrequests.py:310
+#: kallithea/controllers/pullrequests.py:312
 #, python-format
 msgid "Error creating pull request: %s"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:356
-#: kallithea/controllers/pullrequests.py:503
+#: kallithea/controllers/pullrequests.py:358
+#: kallithea/controllers/pullrequests.py:505
 msgid "No description"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:363
+#: kallithea/controllers/pullrequests.py:365
 msgid "Successfully opened new pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:366
-#: kallithea/controllers/pullrequests.py:453
-#: kallithea/controllers/pullrequests.py:509
+#: kallithea/controllers/pullrequests.py:368
+#: kallithea/controllers/pullrequests.py:455
+#: kallithea/controllers/pullrequests.py:512
 #, python-format
 msgid "Invalid reviewer \"%s\" specified"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:369
-#: kallithea/controllers/pullrequests.py:456
+#: kallithea/controllers/pullrequests.py:371
+#: kallithea/controllers/pullrequests.py:458
 msgid "Error occurred while creating pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:401
+#: kallithea/controllers/pullrequests.py:403
 msgid "Missing changesets since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:408
+#: kallithea/controllers/pullrequests.py:410
 #, python-format
 msgid "New changesets on %s %s since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:415
+#: kallithea/controllers/pullrequests.py:417
 msgid "Ancestor didn't change - show diff since previous version:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:422
+#: kallithea/controllers/pullrequests.py:424
 #, python-format
 msgid ""
 "This pull request is based on another %s revision and there is no simple "
 "diff."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:424
+#: kallithea/controllers/pullrequests.py:426
 #, python-format
 msgid "No changes found on %s %s since previous version."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:462
+#: kallithea/controllers/pullrequests.py:464
 #, python-format
 msgid "Closed, replaced by %s ."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:470
+#: kallithea/controllers/pullrequests.py:472
 msgid "Pull request update created"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:513
+#: kallithea/controllers/pullrequests.py:516
 msgid "Pull request updated"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:528
+#: kallithea/controllers/pullrequests.py:531
 msgid "Successfully deleted pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:594
+#: kallithea/controllers/pullrequests.py:597
 #, python-format
 msgid "This pull request has already been merged to %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:596
+#: kallithea/controllers/pullrequests.py:599
 msgid "This pull request has been closed and can not be updated."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:614
-#, python-format
-msgid "This pull request can be updated with changes on %s:"
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:617
+#, python-format
+msgid "The following changes are available on %s:"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:621
 msgid "No changesets found for updating this pull request."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:625
+#: kallithea/controllers/pullrequests.py:629
 #, python-format
 msgid "Note: Branch %s has another head: %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:631
+#: kallithea/controllers/pullrequests.py:635
 msgid "Git pull requests don't support updates yet."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:722
-msgid "No permission to change pull request status"
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:727
+msgid "No permission to change pull request status"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:738
+#, fuzzy, python-format
+msgid "Successfully deleted pull request %s"
+msgstr "Úspešne zmazaný súbor %s"
+
+#: kallithea/controllers/pullrequests.py:748
 msgid "Closing."
 msgstr ""
 
@@ -450,12 +452,12 @@
 msgid "An error occurred during search operation."
 msgstr "Došlo k chybe počas vyhľadávania."
 
-#: kallithea/controllers/summary.py:180
+#: kallithea/controllers/summary.py:181
 #: kallithea/templates/summary/summary.html:384
 msgid "No data ready yet"
 msgstr ""
 
-#: kallithea/controllers/summary.py:183
+#: kallithea/controllers/summary.py:184
 #: kallithea/templates/summary/summary.html:98
 msgid "Statistics are disabled for this repository"
 msgstr ""
@@ -476,64 +478,64 @@
 msgid "Error occurred during update of defaults"
 msgstr ""
 
+#: kallithea/controllers/admin/gists.py:58
+#: kallithea/controllers/admin/my_account.py:243
+#: kallithea/controllers/admin/users.py:284
+msgid "Forever"
+msgstr ""
+
 #: kallithea/controllers/admin/gists.py:59
-#: kallithea/controllers/admin/my_account.py:243
+#: kallithea/controllers/admin/my_account.py:244
 #: kallithea/controllers/admin/users.py:285
-msgid "Forever"
-msgstr ""
+msgid "5 minutes"
+msgstr "5 minút"
 
 #: kallithea/controllers/admin/gists.py:60
-#: kallithea/controllers/admin/my_account.py:244
+#: kallithea/controllers/admin/my_account.py:245
 #: kallithea/controllers/admin/users.py:286
-msgid "5 minutes"
-msgstr "5 minút"
+msgid "1 hour"
+msgstr "1 hodina"
 
 #: kallithea/controllers/admin/gists.py:61
-#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/my_account.py:246
 #: kallithea/controllers/admin/users.py:287
-msgid "1 hour"
-msgstr "1 hodina"
+msgid "1 day"
+msgstr "1 deň"
 
 #: kallithea/controllers/admin/gists.py:62
-#: kallithea/controllers/admin/my_account.py:246
+#: kallithea/controllers/admin/my_account.py:247
 #: kallithea/controllers/admin/users.py:288
-msgid "1 day"
-msgstr "1 deň"
-
-#: kallithea/controllers/admin/gists.py:63
-#: kallithea/controllers/admin/my_account.py:247
-#: kallithea/controllers/admin/users.py:289
 msgid "1 month"
 msgstr "1 mesiac"
 
-#: kallithea/controllers/admin/gists.py:67
+#: kallithea/controllers/admin/gists.py:66
 #: kallithea/controllers/admin/my_account.py:249
-#: kallithea/controllers/admin/users.py:291
+#: kallithea/controllers/admin/users.py:290
 msgid "Lifetime"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:146
+#: kallithea/controllers/admin/gists.py:145
 msgid "Error occurred during gist creation"
 msgstr "Došlo k chybe pri vytváraní gist"
 
-#: kallithea/controllers/admin/gists.py:184
+#: kallithea/controllers/admin/gists.py:183
 #, python-format
 msgid "Deleted gist %s"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:233
+#: kallithea/controllers/admin/gists.py:232
 msgid "Unmodified"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:262
+#: kallithea/controllers/admin/gists.py:261
 msgid "Successfully updated gist content"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:267
+#: kallithea/controllers/admin/gists.py:266
 msgid "Successfully updated gist data"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:270
+#: kallithea/controllers/admin/gists.py:269
 #, python-format
 msgid "Error occurred during update of gist %s"
 msgstr "Došlo k chybe pri aktualizácii gist %s"
@@ -548,7 +550,7 @@
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:144
-#: kallithea/controllers/admin/users.py:202
+#: kallithea/controllers/admin/users.py:201
 #, python-format
 msgid "Error occurred during update of user %s"
 msgstr ""
@@ -558,33 +560,33 @@
 msgstr "Došlo k chybe pri aktualizácii hesla užívateľa"
 
 #: kallithea/controllers/admin/my_account.py:220
-#: kallithea/controllers/admin/users.py:415
+#: kallithea/controllers/admin/users.py:414
 #, python-format
 msgid "Added email %s to user"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:226
-#: kallithea/controllers/admin/users.py:421
+#: kallithea/controllers/admin/users.py:420
 msgid "An error occurred during email saving"
 msgstr "Došlo k chybe pri ukladaní e-mailovej adresy"
 
 #: kallithea/controllers/admin/my_account.py:235
-#: kallithea/controllers/admin/users.py:433
+#: kallithea/controllers/admin/users.py:432
 msgid "Removed email from user"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:259
-#: kallithea/controllers/admin/users.py:308
+#: kallithea/controllers/admin/users.py:307
 msgid "API key successfully created"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:271
-#: kallithea/controllers/admin/users.py:321
+#: kallithea/controllers/admin/users.py:320
 msgid "API key successfully reset"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:275
-#: kallithea/controllers/admin/users.py:325
+#: kallithea/controllers/admin/users.py:324
 msgid "API key successfully deleted"
 msgstr ""
 
@@ -634,10 +636,10 @@
 #: kallithea/templates/admin/users/user_edit_profile.html:105
 #: kallithea/templates/admin/users/users.html:10
 #: kallithea/templates/admin/users/users.html:55
-#: kallithea/templates/base/base.html:252
-#: kallithea/templates/base/base.html:253
-#: kallithea/templates/base/base.html:259
-#: kallithea/templates/base/base.html:260
+#: kallithea/templates/base/base.html:336
+#: kallithea/templates/base/base.html:337
+#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:344
 #: kallithea/templates/base/perms_summary.html:17
 msgid "Admin"
 msgstr ""
@@ -668,7 +670,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1564
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1603
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1655
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1701
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1705
 msgid "Manual activation of external account"
 msgstr ""
 
@@ -680,7 +682,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1565
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1604
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1656
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1702
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1706
 msgid "Automatic activation of external account"
 msgstr ""
 
@@ -701,244 +703,244 @@
 msgid "Error occurred during update of permissions"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:188
+#: kallithea/controllers/admin/repo_groups.py:187
 #, python-format
 msgid "Error occurred during creation of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:193
+#: kallithea/controllers/admin/repo_groups.py:192
 #, python-format
 msgid "Created repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:250
+#: kallithea/controllers/admin/repo_groups.py:249
 #, python-format
 msgid "Updated repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:266
+#: kallithea/controllers/admin/repo_groups.py:265
 #, python-format
 msgid "Error occurred during update of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:284
+#: kallithea/controllers/admin/repo_groups.py:283
 #, python-format
 msgid "This group contains %s repositories and cannot be deleted"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:291
+#: kallithea/controllers/admin/repo_groups.py:290
 #, python-format
 msgid "This group contains %s subgroups and cannot be deleted"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:297
+#: kallithea/controllers/admin/repo_groups.py:296
 #, python-format
 msgid "Removed repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:302
+#: kallithea/controllers/admin/repo_groups.py:301
 #, python-format
 msgid "Error occurred during deletion of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:405
-#: kallithea/controllers/admin/repo_groups.py:440
+#: kallithea/controllers/admin/repo_groups.py:404
+#: kallithea/controllers/admin/repo_groups.py:439
 #: kallithea/controllers/admin/user_groups.py:340
 msgid "Cannot revoke permission for yourself as admin"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:420
+#: kallithea/controllers/admin/repo_groups.py:419
 msgid "Repository group permissions updated"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:457
-#: kallithea/controllers/admin/repos.py:398
+#: kallithea/controllers/admin/repo_groups.py:456
+#: kallithea/controllers/admin/repos.py:397
 #: kallithea/controllers/admin/user_groups.py:352
 msgid "An error occurred during revoking of permission"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:152
+#: kallithea/controllers/admin/repos.py:151
 #, python-format
 msgid "Error creating repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:213
+#: kallithea/controllers/admin/repos.py:212
 #, python-format
 msgid "Created repository %s from %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:222
+#: kallithea/controllers/admin/repos.py:221
 #, python-format
 msgid "Forked repository %s as %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:225
+#: kallithea/controllers/admin/repos.py:224
 #, python-format
 msgid "Created repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:262
+#: kallithea/controllers/admin/repos.py:261
 #, python-format
 msgid "Repository %s updated successfully"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:283
+#: kallithea/controllers/admin/repos.py:282
 #, python-format
 msgid "Error occurred during update of repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:310
+#: kallithea/controllers/admin/repos.py:309
 #, python-format
 msgid "Detached %s forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:313
+#: kallithea/controllers/admin/repos.py:312
 #, python-format
 msgid "Deleted %s forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:318
+#: kallithea/controllers/admin/repos.py:317
 #, python-format
 msgid "Deleted repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:321
+#: kallithea/controllers/admin/repos.py:320
 #, python-format
 msgid "Cannot delete repository %s which still has forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:326
+#: kallithea/controllers/admin/repos.py:325
 #, python-format
 msgid "An error occurred during deletion of %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:374
+#: kallithea/controllers/admin/repos.py:373
 msgid "Repository permissions updated"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:430
+#: kallithea/controllers/admin/repos.py:429
 msgid "An error occurred during creation of field"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:444
+#: kallithea/controllers/admin/repos.py:443
 msgid "An error occurred during removal of field"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:460
+#: kallithea/controllers/admin/repos.py:459
 msgid "-- Not a fork --"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:491
+#: kallithea/controllers/admin/repos.py:490
 msgid "Updated repository visibility in public journal"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:495
+#: kallithea/controllers/admin/repos.py:494
 msgid "An error occurred during setting this repository in public journal"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:512
+#: kallithea/controllers/admin/repos.py:511
 msgid "Nothing"
 msgstr "Nič"
 
-#: kallithea/controllers/admin/repos.py:514
+#: kallithea/controllers/admin/repos.py:513
 #, python-format
 msgid "Marked repository %s as fork of %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:521
+#: kallithea/controllers/admin/repos.py:520
 msgid "An error occurred during this operation"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:537
-#: kallithea/controllers/admin/repos.py:564
+#: kallithea/controllers/admin/repos.py:536
+#: kallithea/controllers/admin/repos.py:563
 #, fuzzy
 msgid "Repository has been locked"
 msgstr "Tento repozitár bol uzamknutý používateľom %s dňa %s"
 
-#: kallithea/controllers/admin/repos.py:540
-#: kallithea/controllers/admin/repos.py:561
+#: kallithea/controllers/admin/repos.py:539
+#: kallithea/controllers/admin/repos.py:560
 #, fuzzy
 msgid "Repository has been unlocked"
 msgstr "Tento repozitár bol uzamknutý používateľom %s dňa %s"
 
-#: kallithea/controllers/admin/repos.py:543
-#: kallithea/controllers/admin/repos.py:568
+#: kallithea/controllers/admin/repos.py:542
+#: kallithea/controllers/admin/repos.py:567
 msgid "An error occurred during unlocking"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:582
+#: kallithea/controllers/admin/repos.py:581
 msgid "Cache invalidation successful"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:586
+#: kallithea/controllers/admin/repos.py:585
 msgid "An error occurred during cache invalidation"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:601
+#: kallithea/controllers/admin/repos.py:600
 msgid "Pulled from remote location"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:604
+#: kallithea/controllers/admin/repos.py:603
 msgid "An error occurred during pull from remote location"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:637
+#: kallithea/controllers/admin/repos.py:636
 msgid "An error occurred during deletion of repository stats"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:170
+#: kallithea/controllers/admin/settings.py:141
 msgid "Updated VCS settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:174
+#: kallithea/controllers/admin/settings.py:145
 msgid ""
 "Unable to activate hgsubversion support. The \"hgsubversion\" library is "
 "missing"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:180
-#: kallithea/controllers/admin/settings.py:277
+#: kallithea/controllers/admin/settings.py:151
+#: kallithea/controllers/admin/settings.py:248
 msgid "Error occurred while updating application settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:216
+#: kallithea/controllers/admin/settings.py:187
 #, python-format
 msgid "Repositories successfully rescanned. Added: %s. Removed: %s."
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:273
+#: kallithea/controllers/admin/settings.py:244
 msgid "Updated application settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:330
+#: kallithea/controllers/admin/settings.py:301
 msgid "Updated visualisation settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:335
+#: kallithea/controllers/admin/settings.py:306
 msgid "Error occurred during updating visualisation settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:361
+#: kallithea/controllers/admin/settings.py:332
 msgid "Please enter email address"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:376
+#: kallithea/controllers/admin/settings.py:347
 msgid "Send email task created"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:407
+#: kallithea/controllers/admin/settings.py:378
 msgid "Added new hook"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:421
+#: kallithea/controllers/admin/settings.py:392
 msgid "Updated hooks"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:425
+#: kallithea/controllers/admin/settings.py:396
 msgid "Error occurred during hook creation"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:451
+#: kallithea/controllers/admin/settings.py:422
 msgid "Whoosh reindex task scheduled"
 msgstr ""
 
@@ -979,76 +981,80 @@
 msgstr ""
 
 #: kallithea/controllers/admin/user_groups.py:440
-#: kallithea/controllers/admin/users.py:384
+#: kallithea/controllers/admin/users.py:383
 msgid "Updated permissions"
 msgstr ""
 
 #: kallithea/controllers/admin/user_groups.py:444
-#: kallithea/controllers/admin/users.py:388
+#: kallithea/controllers/admin/users.py:387
 msgid "An error occurred during permissions saving"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:134
+#: kallithea/controllers/admin/users.py:133
 #, python-format
 msgid "Created user %s"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:149
+#: kallithea/controllers/admin/users.py:148
 #, python-format
 msgid "Error occurred during creation of user %s"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:182
+#: kallithea/controllers/admin/users.py:181
 msgid "User updated successfully"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:218
+#: kallithea/controllers/admin/users.py:217
 msgid "Successfully deleted user"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:223
+#: kallithea/controllers/admin/users.py:222
 msgid "An error occurred during deletion of user"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:236
+#: kallithea/controllers/admin/users.py:235
 msgid "The default user cannot be edited"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:463
+#: kallithea/controllers/admin/users.py:462
 #, python-format
 msgid "Added IP address %s to user whitelist"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:469
+#: kallithea/controllers/admin/users.py:468
 msgid "An error occurred while adding IP address"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:483
+#: kallithea/controllers/admin/users.py:482
 msgid "Removed IP address from user whitelist"
 msgstr ""
 
-#: kallithea/lib/auth.py:743
+#: kallithea/lib/auth.py:737
 #, python-format
 msgid "IP %s not allowed"
 msgstr ""
 
-#: kallithea/lib/auth.py:756
+#: kallithea/lib/auth.py:750
 msgid "Invalid API key"
 msgstr ""
 
-#: kallithea/lib/auth.py:812
+#: kallithea/lib/auth.py:768
+msgid "CSRF token leak has been detected - all form tokens have been expired"
+msgstr ""
+
+#: kallithea/lib/auth.py:813
 msgid "You need to be a registered user to perform this action"
 msgstr ""
 
-#: kallithea/lib/auth.py:844
+#: kallithea/lib/auth.py:843
 msgid "You need to be signed in to view this page"
 msgstr ""
 
-#: kallithea/lib/base.py:490
+#: kallithea/lib/base.py:493
 msgid "Repository not found in the filesystem"
 msgstr ""
 
-#: kallithea/lib/base.py:516 kallithea/lib/helpers.py:622
+#: kallithea/lib/base.py:519 kallithea/lib/helpers.py:623
 msgid "Changeset not found"
 msgstr ""
 
@@ -1064,125 +1070,125 @@
 msgid "No changes detected"
 msgstr ""
 
-#: kallithea/lib/helpers.py:609
+#: kallithea/lib/helpers.py:610
 #, python-format
 msgid "Deleted branch: %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:611
+#: kallithea/lib/helpers.py:612
 #, python-format
 msgid "Created tag: %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:671
+#: kallithea/lib/helpers.py:672
 #, python-format
 msgid "Show all combined changesets %s->%s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:677
+#: kallithea/lib/helpers.py:678
 msgid "Compare view"
 msgstr ""
 
-#: kallithea/lib/helpers.py:696
-msgid "and"
-msgstr ""
-
 #: kallithea/lib/helpers.py:697
+msgid "and"
+msgstr ""
+
+#: kallithea/lib/helpers.py:698
 #, python-format
 msgid "%s more"
 msgstr ""
 
-#: kallithea/lib/helpers.py:698 kallithea/templates/changelog/changelog.html:44
+#: kallithea/lib/helpers.py:699 kallithea/templates/changelog/changelog.html:44
 msgid "revisions"
 msgstr ""
 
-#: kallithea/lib/helpers.py:722
+#: kallithea/lib/helpers.py:723
 #, python-format
 msgid "Fork name %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:742
+#: kallithea/lib/helpers.py:743
 #, python-format
 msgid "Pull request %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:752
+#: kallithea/lib/helpers.py:753
 msgid "[deleted] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:754 kallithea/lib/helpers.py:766
+#: kallithea/lib/helpers.py:755 kallithea/lib/helpers.py:767
 msgid "[created] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:756
+#: kallithea/lib/helpers.py:757
 msgid "[created] repository as fork"
 msgstr ""
 
-#: kallithea/lib/helpers.py:758 kallithea/lib/helpers.py:768
+#: kallithea/lib/helpers.py:759 kallithea/lib/helpers.py:769
 msgid "[forked] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:760 kallithea/lib/helpers.py:770
+#: kallithea/lib/helpers.py:761 kallithea/lib/helpers.py:771
 msgid "[updated] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:762
+#: kallithea/lib/helpers.py:763
 msgid "[downloaded] archive from repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:764
+#: kallithea/lib/helpers.py:765
 msgid "[delete] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:772
+#: kallithea/lib/helpers.py:773
 msgid "[created] user"
 msgstr ""
 
-#: kallithea/lib/helpers.py:774
+#: kallithea/lib/helpers.py:775
 msgid "[updated] user"
 msgstr ""
 
-#: kallithea/lib/helpers.py:776
+#: kallithea/lib/helpers.py:777
 msgid "[created] user group"
 msgstr ""
 
-#: kallithea/lib/helpers.py:778
+#: kallithea/lib/helpers.py:779
 msgid "[updated] user group"
 msgstr ""
 
-#: kallithea/lib/helpers.py:780
+#: kallithea/lib/helpers.py:781
 msgid "[commented] on revision in repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:782
+#: kallithea/lib/helpers.py:783
 msgid "[commented] on pull request for"
 msgstr ""
 
-#: kallithea/lib/helpers.py:784
+#: kallithea/lib/helpers.py:785
 msgid "[closed] pull request for"
 msgstr ""
 
-#: kallithea/lib/helpers.py:786
+#: kallithea/lib/helpers.py:787
 msgid "[pushed] into"
 msgstr ""
 
-#: kallithea/lib/helpers.py:788
+#: kallithea/lib/helpers.py:789
 msgid "[committed via Kallithea] into repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:790
+#: kallithea/lib/helpers.py:791
 msgid "[pulled from remote] into repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:792
+#: kallithea/lib/helpers.py:793
 msgid "[pulled] from"
 msgstr ""
 
-#: kallithea/lib/helpers.py:794
+#: kallithea/lib/helpers.py:795
 msgid "[started following] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:796
+#: kallithea/lib/helpers.py:797
 msgid "[stopped following] repository"
 msgstr ""
 
@@ -1192,8 +1198,8 @@
 msgstr ""
 
 #: kallithea/lib/helpers.py:1128
-#: kallithea/templates/compare/compare_diff.html:65
-#: kallithea/templates/pullrequests/pullrequest_show.html:326
+#: kallithea/templates/compare/compare_diff.html:71
+#: kallithea/templates/pullrequests/pullrequest_show.html:337
 msgid "No files"
 msgstr ""
 
@@ -1217,7 +1223,7 @@
 msgid "chmod"
 msgstr ""
 
-#: kallithea/lib/helpers.py:1444
+#: kallithea/lib/helpers.py:1469
 #, python-format
 msgid ""
 "%s repository is not mapped to db perhaps it was created or renamed from "
@@ -1225,7 +1231,7 @@
 "repositories"
 msgstr ""
 
-#: kallithea/lib/utils2.py:415
+#: kallithea/lib/utils2.py:434
 #, python-format
 msgid "%d year"
 msgid_plural "%d years"
@@ -1233,7 +1239,7 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/lib/utils2.py:416
+#: kallithea/lib/utils2.py:435
 #, python-format
 msgid "%d month"
 msgid_plural "%d months"
@@ -1241,7 +1247,7 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/lib/utils2.py:417
+#: kallithea/lib/utils2.py:436
 #, python-format
 msgid "%d day"
 msgid_plural "%d days"
@@ -1249,7 +1255,7 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/lib/utils2.py:418
+#: kallithea/lib/utils2.py:437
 #, python-format
 msgid "%d hour"
 msgid_plural "%d hours"
@@ -1257,7 +1263,7 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/lib/utils2.py:419
+#: kallithea/lib/utils2.py:438
 #, python-format
 msgid "%d minute"
 msgid_plural "%d minutes"
@@ -1265,7 +1271,7 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/lib/utils2.py:420
+#: kallithea/lib/utils2.py:439
 #, python-format
 msgid "%d second"
 msgid_plural "%d seconds"
@@ -1273,27 +1279,27 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/lib/utils2.py:436
+#: kallithea/lib/utils2.py:455
 #, python-format
 msgid "in %s"
 msgstr ""
 
-#: kallithea/lib/utils2.py:438
+#: kallithea/lib/utils2.py:457
 #, python-format
 msgid "%s ago"
 msgstr ""
 
-#: kallithea/lib/utils2.py:440
+#: kallithea/lib/utils2.py:459
 #, python-format
 msgid "in %s and %s"
 msgstr ""
 
-#: kallithea/lib/utils2.py:443
+#: kallithea/lib/utils2.py:462
 #, python-format
 msgid "%s and %s ago"
 msgstr ""
 
-#: kallithea/lib/utils2.py:446
+#: kallithea/lib/utils2.py:465
 msgid "just now"
 msgstr ""
 
@@ -1392,7 +1398,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1531
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1570
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1620
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1665
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1669
 msgid "Kallithea Administrator"
 msgstr ""
 
@@ -1503,7 +1509,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2063
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2102
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2155
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2229
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2237
 msgid "Approved"
 msgstr ""
 
@@ -1518,7 +1524,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2064
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2103
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2156
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2230
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2238
 msgid "Rejected"
 msgstr ""
 
@@ -1545,7 +1551,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1379
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1418
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1471
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1518
 msgid "top level"
 msgstr ""
 
@@ -1692,7 +1698,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1560
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1599
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1651
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1697
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1701
 msgid "Registration disabled"
 msgstr ""
 
@@ -1719,12 +1725,12 @@
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1645
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1691
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1695
 msgid "Repository creation enabled with write permission to a repository group"
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1646
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1692
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1696
 msgid "Repository creation disabled with write permission to a repository group"
 msgstr ""
 
@@ -1733,106 +1739,106 @@
 msgid "on line %s"
 msgstr ""
 
-#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:169
+#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:170
 msgid "[Mention]"
 msgstr ""
 
-#: kallithea/model/db.py:1667
+#: kallithea/model/db.py:1671
 msgid "Default user has no access to new repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1668
-msgid "Default user has read access to new repositories"
-msgstr ""
-
-#: kallithea/model/db.py:1669
-msgid "Default user has write access to new repositories"
-msgstr ""
-
-#: kallithea/model/db.py:1670
-msgid "Default user has admin access to new repositories"
-msgstr ""
-
 #: kallithea/model/db.py:1672
-msgid "Default user has no access to new repository groups"
+msgid "Default user has read access to new repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1673
-msgid "Default user has read access to new repository groups"
+msgid "Default user has write access to new repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1674
-msgid "Default user has write access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1675
-msgid "Default user has admin access to new repository groups"
+msgid "Default user has admin access to new repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1676
+msgid "Default user has no access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1677
-msgid "Default user has no access to new user groups"
+msgid "Default user has read access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1678
-msgid "Default user has read access to new user groups"
+msgid "Default user has write access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1679
-msgid "Default user has write access to new user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1680
-msgid "Default user has admin access to new user groups"
+msgid "Default user has admin access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1681
+msgid "Default user has no access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1682
-msgid "Only admins can create repository groups"
+msgid "Default user has read access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1683
-msgid "Non-admins can create repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1685
-msgid "Only admins can create user groups"
+msgid "Default user has write access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1684
+msgid "Default user has admin access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1686
-msgid "Non-admins can create user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1688
-msgid "Only admins can create top level repositories"
+msgid "Only admins can create repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1687
+msgid "Non-admins can create repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1689
+msgid "Only admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1690
+msgid "Non-admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1692
+msgid "Only admins can create top level repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1693
 msgid "Non-admins can create top level repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1694
+#: kallithea/model/db.py:1698
 #, fuzzy
 msgid "Only admins can fork repositories"
 msgstr "Repozitáre"
 
-#: kallithea/model/db.py:1695
+#: kallithea/model/db.py:1699
 #, fuzzy
-msgid "Non-admins can can fork repositories"
+msgid "Non-admins can fork repositories"
 msgstr "Repozitáre"
 
-#: kallithea/model/db.py:1698
+#: kallithea/model/db.py:1702
 msgid "User registration with manual account activation"
 msgstr ""
 
-#: kallithea/model/db.py:1699
+#: kallithea/model/db.py:1703
 msgid "User registration with automatic account activation"
 msgstr ""
 
-#: kallithea/model/db.py:2228
+#: kallithea/model/db.py:2236
 #, fuzzy
 msgid "Not reviewed"
 msgstr ""
 
-#: kallithea/model/db.py:2231
+#: kallithea/model/db.py:2239
 #, fuzzy
 msgid "Under review"
 msgstr ""
@@ -1855,7 +1861,7 @@
 msgid "Enter %(min)i characters or more"
 msgstr ""
 
-#: kallithea/model/forms.py:160
+#: kallithea/model/forms.py:165
 msgid "Name must not contain only digits"
 msgstr ""
 
@@ -1948,7 +1954,7 @@
 msgid "%(user)s wants you to review pull request %(pr_nice_id)s: %(pr_title)s"
 msgstr ""
 
-#: kallithea/model/scm.py:812
+#: kallithea/model/scm.py:708
 msgid "latest tip"
 msgstr ""
 
@@ -1981,15 +1987,15 @@
 "owners or remove those user groups: %s"
 msgstr ""
 
-#: kallithea/model/user.py:360
+#: kallithea/model/user.py:368
 msgid "Password reset link"
 msgstr ""
 
-#: kallithea/model/user.py:408
+#: kallithea/model/user.py:418
 msgid "Password reset notification"
 msgstr ""
 
-#: kallithea/model/user.py:409
+#: kallithea/model/user.py:419
 #, python-format
 msgid ""
 "The password to your account %s has been changed using password reset "
@@ -2000,168 +2006,168 @@
 msgid "Value cannot be an empty list"
 msgstr ""
 
-#: kallithea/model/validators.py:95
+#: kallithea/model/validators.py:96
 #, python-format
 msgid "Username \"%(username)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:97
+#: kallithea/model/validators.py:98
 #, python-format
 msgid "Username \"%(username)s\" cannot be used"
 msgstr ""
 
-#: kallithea/model/validators.py:99
+#: kallithea/model/validators.py:100
 msgid ""
 "Username may only contain alphanumeric characters underscores, periods or"
 " dashes and must begin with an alphanumeric character or underscore"
 msgstr ""
 
-#: kallithea/model/validators.py:126
+#: kallithea/model/validators.py:127
 msgid "The input is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:133
+#: kallithea/model/validators.py:134
 #, python-format
 msgid "Username %(username)s is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:152
+#: kallithea/model/validators.py:154
 msgid "Invalid user group name"
 msgstr ""
 
-#: kallithea/model/validators.py:153
-#, python-format
-msgid "User group \"%(usergroup)s\" already exists"
-msgstr ""
-
 #: kallithea/model/validators.py:155
+#, python-format
+msgid "User group \"%(usergroup)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:157
 msgid ""
 "user group name may only contain alphanumeric characters underscores, "
 "periods or dashes and must begin with alphanumeric character"
 msgstr ""
 
-#: kallithea/model/validators.py:193
+#: kallithea/model/validators.py:197
 msgid "Cannot assign this group as parent"
 msgstr ""
 
-#: kallithea/model/validators.py:194
+#: kallithea/model/validators.py:198
 #, python-format
 msgid "Group \"%(group_name)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:196
+#: kallithea/model/validators.py:200
 #, python-format
 msgid "Repository with name \"%(group_name)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:254
+#: kallithea/model/validators.py:258
 msgid "Invalid characters (non-ascii) in password"
 msgstr ""
 
-#: kallithea/model/validators.py:269
+#: kallithea/model/validators.py:273
 msgid "Invalid old password"
 msgstr ""
 
-#: kallithea/model/validators.py:285
+#: kallithea/model/validators.py:289
 msgid "Passwords do not match"
 msgstr ""
 
-#: kallithea/model/validators.py:300
+#: kallithea/model/validators.py:304
 msgid "Invalid username or password"
 msgstr ""
 
-#: kallithea/model/validators.py:331
+#: kallithea/model/validators.py:335
 msgid "Token mismatch"
 msgstr ""
 
-#: kallithea/model/validators.py:345
+#: kallithea/model/validators.py:351
 #, python-format
 msgid "Repository name %(repo)s is not allowed"
 msgstr ""
 
-#: kallithea/model/validators.py:347
+#: kallithea/model/validators.py:353
 #, python-format
 msgid "Repository named %(repo)s already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:348
+#: kallithea/model/validators.py:354
 #, python-format
 msgid "Repository \"%(repo)s\" already exists in group \"%(group)s\""
 msgstr ""
 
-#: kallithea/model/validators.py:350
+#: kallithea/model/validators.py:356
 #, python-format
 msgid "Repository group with name \"%(repo)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:465
+#: kallithea/model/validators.py:470
 #, fuzzy
 msgid "Invalid repository URL"
 msgstr "Odblokovať repozitár"
 
-#: kallithea/model/validators.py:466
+#: kallithea/model/validators.py:471
 msgid ""
 "Invalid repository URL. It must be a valid http, https, ssh, svn+http or "
 "svn+https URL"
 msgstr ""
 
-#: kallithea/model/validators.py:489
+#: kallithea/model/validators.py:496
 msgid "Fork has to be the same type as parent"
 msgstr ""
 
-#: kallithea/model/validators.py:504
+#: kallithea/model/validators.py:511
 msgid "You don't have permissions to create repository in this group"
 msgstr ""
 
-#: kallithea/model/validators.py:506
+#: kallithea/model/validators.py:513
 msgid "no permission to create repository in root location"
 msgstr ""
 
-#: kallithea/model/validators.py:556
+#: kallithea/model/validators.py:563
 msgid "You don't have permissions to create a group in this location"
 msgstr ""
 
-#: kallithea/model/validators.py:597
+#: kallithea/model/validators.py:604
 msgid "This username or user group name is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:690
+#: kallithea/model/validators.py:697
 msgid "This is not a valid path"
 msgstr ""
 
-#: kallithea/model/validators.py:705
+#: kallithea/model/validators.py:714
 msgid "This email address is already in use"
 msgstr ""
 
-#: kallithea/model/validators.py:725
+#: kallithea/model/validators.py:734
 #, python-format
 msgid "Email address \"%(email)s\" not found"
 msgstr ""
 
-#: kallithea/model/validators.py:762
+#: kallithea/model/validators.py:771
 msgid ""
 "The LDAP Login attribute of the CN must be specified - this is the name "
 "of the attribute that is equivalent to \"username\""
 msgstr ""
 
-#: kallithea/model/validators.py:774
+#: kallithea/model/validators.py:783
 msgid "Please enter a valid IPv4 or IPv6 address"
 msgstr ""
 
-#: kallithea/model/validators.py:775
+#: kallithea/model/validators.py:784
 #, python-format
 msgid "The network size (bits) must be within the range of 0-32 (not %(bits)r)"
 msgstr ""
 
-#: kallithea/model/validators.py:808
+#: kallithea/model/validators.py:817
 msgid "Key name can only consist of letters, underscore, dash or numbers"
 msgstr ""
 
-#: kallithea/model/validators.py:822
+#: kallithea/model/validators.py:831
 msgid "Filename cannot be inside a directory"
 msgstr ""
 
-#: kallithea/model/validators.py:838
+#: kallithea/model/validators.py:847
 #, python-format
 msgid "Plugins %(loaded)s and %(next_to_load)s both export the same name"
 msgstr ""
@@ -2288,7 +2294,7 @@
 #: kallithea/templates/admin/user_groups/user_groups.html:50
 #: kallithea/templates/pullrequests/pullrequest_data.html:16
 #: kallithea/templates/pullrequests/pullrequest_show.html:156
-#: kallithea/templates/pullrequests/pullrequest_show.html:233
+#: kallithea/templates/pullrequests/pullrequest_show.html:244
 #: kallithea/templates/summary/summary.html:134
 msgid "Owner"
 msgstr ""
@@ -2336,7 +2342,7 @@
 #: kallithea/templates/index_base.html:144
 #: kallithea/templates/admin/my_account/my_account_repos.html:61
 #: kallithea/templates/admin/my_account/my_account_watched.html:61
-#: kallithea/templates/base/base.html:140 kallithea/templates/base/root.html:47
+#: kallithea/templates/base/root.html:47
 #: kallithea/templates/bookmarks/bookmarks.html:83
 #: kallithea/templates/branches/branches.html:83
 #: kallithea/templates/journal/journal.html:202
@@ -2346,7 +2352,7 @@
 msgstr ""
 
 #: kallithea/templates/login.html:5 kallithea/templates/login.html:15
-#: kallithea/templates/base/base.html:326
+#: kallithea/templates/base/base.html:414
 msgid "Log In"
 msgstr ""
 
@@ -2361,7 +2367,7 @@
 #: kallithea/templates/admin/users/user_add.html:32
 #: kallithea/templates/admin/users/user_edit_profile.html:24
 #: kallithea/templates/admin/users/users.html:50
-#: kallithea/templates/base/base.html:302
+#: kallithea/templates/base/base.html:390
 #: kallithea/templates/pullrequests/pullrequest_show.html:166
 msgid "Username"
 msgstr ""
@@ -2369,7 +2375,7 @@
 #: kallithea/templates/login.html:33 kallithea/templates/register.html:33
 #: kallithea/templates/admin/my_account/my_account.html:37
 #: kallithea/templates/admin/users/user_add.html:41
-#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:399
 msgid "Password"
 msgstr ""
 
@@ -2381,7 +2387,7 @@
 msgid "Forgot your password ?"
 msgstr ""
 
-#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:322
+#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:410
 msgid "Don't have an account ?"
 msgstr ""
 
@@ -2502,10 +2508,6 @@
 msgid "There are no branches yet"
 msgstr ""
 
-#: kallithea/templates/switch_to_list.html:16
-msgid "Closed Branches"
-msgstr ""
-
 #: kallithea/templates/switch_to_list.html:32
 #: kallithea/templates/tags/tags_data.html:44
 msgid "There are no tags yet"
@@ -2734,12 +2736,12 @@
 msgid "Never"
 msgstr ""
 
-#: kallithea/templates/admin/gists/edit.html:145
+#: kallithea/templates/admin/gists/edit.html:146
 msgid "Update Gist"
 msgstr ""
 
-#: kallithea/templates/admin/gists/edit.html:146
-#: kallithea/templates/changeset/changeset_file_comment.html:81
+#: kallithea/templates/admin/gists/edit.html:147
+#: kallithea/templates/changeset/changeset_file_comment.html:105
 msgid "Cancel"
 msgstr ""
 
@@ -2762,7 +2764,7 @@
 
 #: kallithea/templates/admin/gists/index.html:37
 #: kallithea/templates/admin/gists/show.html:25
-#: kallithea/templates/base/base.html:237
+#: kallithea/templates/base/base.html:321
 msgid "Create New Gist"
 msgstr ""
 
@@ -2850,7 +2852,8 @@
 #: kallithea/templates/admin/settings/settings_hooks.html:36
 #: kallithea/templates/admin/users/user_edit_emails.html:19
 #: kallithea/templates/admin/users/user_edit_ips.html:22
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+#: kallithea/templates/changeset/changeset_file_comment.html:95
 #: kallithea/templates/data_table/_dt_elements.html:129
 #: kallithea/templates/data_table/_dt_elements.html:157
 #: kallithea/templates/data_table/_dt_elements.html:173
@@ -2870,8 +2873,6 @@
 #: kallithea/templates/base/perms_summary.html:43
 #: kallithea/templates/base/perms_summary.html:79
 #: kallithea/templates/base/perms_summary.html:81
-#: kallithea/templates/changeset/changeset_file_comment.html:83
-#: kallithea/templates/changeset/changeset_file_comment.html:192
 #: kallithea/templates/data_table/_dt_elements.html:122
 #: kallithea/templates/data_table/_dt_elements.html:123
 #: kallithea/templates/data_table/_dt_elements.html:150
@@ -2898,13 +2899,12 @@
 msgstr ""
 
 #: kallithea/templates/admin/gists/show.html:86
-#: kallithea/templates/files/files_source.html:73
 msgid "Show as raw"
 msgstr ""
 
 #: kallithea/templates/admin/my_account/my_account.html:5
 #: kallithea/templates/admin/my_account/my_account.html:9
-#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:431
 msgid "My Account"
 msgstr ""
 
@@ -3087,7 +3087,7 @@
 msgstr ""
 
 #: kallithea/templates/admin/notifications/notifications.html:26
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 msgid "Pull Requests"
 msgstr ""
 
@@ -3105,7 +3105,7 @@
 msgstr ""
 
 #: kallithea/templates/admin/notifications/show_notification.html:9
-#: kallithea/templates/base/base.html:342
+#: kallithea/templates/base/base.html:430
 msgid "Notifications"
 msgstr ""
 
@@ -3304,7 +3304,7 @@
 #: kallithea/templates/admin/repos/repo_edit.html:40
 #: kallithea/templates/admin/settings/settings.html:11
 #: kallithea/templates/admin/user_groups/user_group_edit.html:29
-#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:151
+#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:148
 #: kallithea/templates/data_table/_dt_elements.html:45
 #: kallithea/templates/data_table/_dt_elements.html:49
 msgid "Settings"
@@ -3569,6 +3569,11 @@
 msgid "Unlock Repository"
 msgstr "Odblokovať repozitár"
 
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:56
+#, python-format
+msgid "Locked by %s on %s"
+msgstr ""
+
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:60
 msgid "Confirm to lock repository."
 msgstr "Potvrdenie blokovania repozitára."
@@ -3626,10 +3631,6 @@
 msgid "Invalidate Repository Cache"
 msgstr ""
 
-#: kallithea/templates/admin/repos/repo_edit_caches.html:4
-msgid "Confirm to invalidate repository cache."
-msgstr ""
-
 #: kallithea/templates/admin/repos/repo_edit_caches.html:7
 msgid ""
 "Manually invalidate cache for this repository. On first access, the "
@@ -4368,21 +4369,17 @@
 msgid "Files"
 msgstr ""
 
-#: kallithea/templates/base/base.html:138
-msgid "Switch To"
-msgstr ""
-
-#: kallithea/templates/base/base.html:145
-#: kallithea/templates/base/base.html:147
+#: kallithea/templates/base/base.html:142
+#: kallithea/templates/base/base.html:144
 msgid "Options"
 msgstr ""
 
-#: kallithea/templates/base/base.html:155
+#: kallithea/templates/base/base.html:152
 #: kallithea/templates/forks/forks_data.html:21
 msgid "Compare Fork"
 msgstr ""
 
-#: kallithea/templates/base/base.html:157
+#: kallithea/templates/base/base.html:154
 #: kallithea/templates/bookmarks/bookmarks.html:56
 #: kallithea/templates/bookmarks/bookmarks_data.html:13
 #: kallithea/templates/branches/branches.html:56
@@ -4392,111 +4389,116 @@
 msgid "Compare"
 msgstr ""
 
-#: kallithea/templates/base/base.html:159
-#: kallithea/templates/base/base.html:247
+#: kallithea/templates/base/base.html:156
+#: kallithea/templates/base/base.html:331
 #: kallithea/templates/search/search.html:14
 #: kallithea/templates/search/search.html:54
 msgid "Search"
 msgstr ""
 
-#: kallithea/templates/base/base.html:163
+#: kallithea/templates/base/base.html:160
 msgid "Unlock"
 msgstr ""
 
-#: kallithea/templates/base/base.html:165
+#: kallithea/templates/base/base.html:162
 msgid "Lock"
 msgstr ""
 
-#: kallithea/templates/base/base.html:173
+#: kallithea/templates/base/base.html:170
 msgid "Follow"
 msgstr ""
 
+#: kallithea/templates/base/base.html:171
+msgid "Unfollow"
+msgstr ""
+
 #: kallithea/templates/base/base.html:174
-msgid "Unfollow"
-msgstr ""
-
-#: kallithea/templates/base/base.html:177
 #: kallithea/templates/data_table/_dt_elements.html:37
 #: kallithea/templates/data_table/_dt_elements.html:41
 #: kallithea/templates/forks/fork.html:9
 msgid "Fork"
 msgstr ""
 
-#: kallithea/templates/base/base.html:178
+#: kallithea/templates/base/base.html:175
 #: kallithea/templates/pullrequests/pullrequest.html:88
 msgid "Create Pull Request"
 msgstr ""
 
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 #, python-format
 msgid "Show Pull Requests for %s"
 msgstr ""
 
-#: kallithea/templates/base/base.html:221
+#: kallithea/templates/base/base.html:193
+msgid "Switch To"
+msgstr ""
+
+#: kallithea/templates/base/base.html:203
+#: kallithea/templates/base/base.html:485
+msgid "No matches found"
+msgstr ""
+
+#: kallithea/templates/base/base.html:305
 msgid "Show recent activity"
 msgstr ""
 
-#: kallithea/templates/base/base.html:227
-#: kallithea/templates/base/base.html:228
+#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:312
 msgid "Public journal"
 msgstr ""
 
-#: kallithea/templates/base/base.html:233
+#: kallithea/templates/base/base.html:317
 msgid "Show public gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:234
+#: kallithea/templates/base/base.html:318
 msgid "Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:238
+#: kallithea/templates/base/base.html:322
 msgid "All Public Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:240
+#: kallithea/templates/base/base.html:324
 msgid "My Public Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:241
+#: kallithea/templates/base/base.html:325
 msgid "My Private Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:246
+#: kallithea/templates/base/base.html:330
 msgid "Search in repositories"
 msgstr ""
 
-#: kallithea/templates/base/base.html:269
-#: kallithea/templates/base/base.html:270
+#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:354
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:6
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:10
 msgid "My Pull Requests"
 msgstr ""
 
-#: kallithea/templates/base/base.html:289
+#: kallithea/templates/base/base.html:377
 msgid "Not Logged In"
 msgstr ""
 
-#: kallithea/templates/base/base.html:296
+#: kallithea/templates/base/base.html:384
 msgid "Login to Your Account"
 msgstr ""
 
-#: kallithea/templates/base/base.html:319
+#: kallithea/templates/base/base.html:407
 msgid "Forgot password ?"
 msgstr ""
 
-#: kallithea/templates/base/base.html:346
+#: kallithea/templates/base/base.html:434
 msgid "Log Out"
 msgstr ""
 
-#: kallithea/templates/base/base.html:395
-msgid "No matches found"
-msgstr ""
-
-#: kallithea/templates/base/base.html:524
+#: kallithea/templates/base/base.html:615
 msgid "Keyboard shortcuts"
 msgstr ""
 
-#: kallithea/templates/base/base.html:533
+#: kallithea/templates/base/base.html:624
 msgid "Site-wide shortcuts"
 msgstr ""
 
@@ -4599,7 +4601,6 @@
 
 #: kallithea/templates/base/root.html:31
 #, fuzzy
-#| msgid "on pull request"
 msgid "Open New Pull Request from {0}"
 msgstr "Zmena stavu"
 
@@ -4617,6 +4618,7 @@
 
 #: kallithea/templates/base/root.html:35
 #: kallithea/templates/changeset/diff_block.html:8
+#: kallithea/templates/changeset/diff_block.html:21
 msgid "Collapse Diff"
 msgstr ""
 
@@ -4727,51 +4729,54 @@
 #: kallithea/templates/changelog/changelog_summary_data.html:20
 #, python-format
 msgid ""
-"Changeset status: %s\n"
+"Changeset status: %s by %s\n"
 "Click to open associated pull request %s"
 msgstr ""
 
 #: kallithea/templates/changelog/changelog.html:96
-#: kallithea/templates/compare/compare_cs.html:24
-#, python-format
-msgid "Changeset status: %s"
-msgstr ""
-
-#: kallithea/templates/changelog/changelog.html:115
+#: kallithea/templates/changelog/changelog_summary_data.html:24
+#, fuzzy, python-format
+#| msgid "Set changeset status"
+msgid "Changeset status: %s by %s"
+msgstr "Zmeny"
+
+#: kallithea/templates/changelog/changelog.html:116
 #: kallithea/templates/compare/compare_cs.html:63
 msgid "Expand commit message"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:124
+#: kallithea/templates/changelog/changelog.html:125
 #: kallithea/templates/compare/compare_cs.html:30
 msgid "Changeset has comments"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:134
-#: kallithea/templates/changelog/changelog_summary_data.html:54
+#: kallithea/templates/changelog/changelog.html:135
+#: kallithea/templates/changelog/changelog_summary_data.html:57
 #: kallithea/templates/changeset/changeset.html:94
 #: kallithea/templates/changeset/changeset_range.html:92
 #, python-format
 msgid "Bookmark %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:140
-#: kallithea/templates/changelog/changelog_summary_data.html:60
+#: kallithea/templates/changelog/changelog.html:141
+#: kallithea/templates/changelog/changelog_summary_data.html:63
 #: kallithea/templates/changeset/changeset.html:101
 #: kallithea/templates/changeset/changeset_range.html:98
+#: kallithea/templates/compare/compare_cs.html:69
+#: kallithea/templates/pullrequests/pullrequest_show.html:203
 #, python-format
 msgid "Tag %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:145
-#: kallithea/templates/changelog/changelog_summary_data.html:65
+#: kallithea/templates/changelog/changelog.html:146
+#: kallithea/templates/changelog/changelog_summary_data.html:68
 #: kallithea/templates/changeset/changeset.html:106
 #: kallithea/templates/changeset/changeset_range.html:102
 #, python-format
 msgid "Branch %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:310
+#: kallithea/templates/changelog/changelog.html:311
 msgid "There are no changes yet"
 msgstr ""
 
@@ -4787,7 +4792,7 @@
 
 #: kallithea/templates/changelog/changelog_details.html:6
 #: kallithea/templates/changeset/changeset.html:79
-#: kallithea/templates/changeset/diff_block.html:79
+#: kallithea/templates/changeset/diff_block.html:47
 msgid "Added"
 msgstr ""
 
@@ -4817,22 +4822,22 @@
 msgid "Refs"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:81
+#: kallithea/templates/changelog/changelog_summary_data.html:84
 msgid "Add or upload files directly via Kallithea"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:84
+#: kallithea/templates/changelog/changelog_summary_data.html:87
 #: kallithea/templates/files/files_add.html:21
 #: kallithea/templates/files/files_ypjax.html:9
 msgid "Add New File"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:90
+#: kallithea/templates/changelog/changelog_summary_data.html:93
 #, fuzzy
 msgid "Push new repository"
 msgstr "Prázdny repozitár"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:98
+#: kallithea/templates/changelog/changelog_summary_data.html:101
 msgid "Existing repository?"
 msgstr ""
 
@@ -4850,13 +4855,13 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:50
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #: kallithea/templates/changeset/changeset_range.html:48
 msgid "Changeset status"
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:54
-#: kallithea/templates/changeset/diff_block.html:27
+#: kallithea/templates/changeset/diff_block.html:72
 #: kallithea/templates/files/diff_2way.html:49
 msgid "Raw diff"
 msgstr ""
@@ -4866,7 +4871,7 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:60
-#: kallithea/templates/changeset/diff_block.html:30
+#: kallithea/templates/changeset/diff_block.html:75
 #: kallithea/templates/files/diff_2way.html:52
 msgid "Download diff"
 msgstr ""
@@ -4893,8 +4898,8 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:166
-#: kallithea/templates/compare/compare_diff.html:54
-#: kallithea/templates/pullrequests/pullrequest_show.html:318
+#: kallithea/templates/compare/compare_diff.html:60
+#: kallithea/templates/pullrequests/pullrequest_show.html:329
 #, python-format
 msgid "%s file changed"
 msgid_plural "%s files changed"
@@ -4903,8 +4908,8 @@
 msgstr[2] ""
 
 #: kallithea/templates/changeset/changeset.html:168
-#: kallithea/templates/compare/compare_diff.html:56
-#: kallithea/templates/pullrequests/pullrequest_show.html:320
+#: kallithea/templates/compare/compare_diff.html:62
+#: kallithea/templates/pullrequests/pullrequest_show.html:331
 #, python-format
 msgid "%s file changed with %s insertions and %s deletions"
 msgid_plural "%s files changed with %s insertions and %s deletions"
@@ -4914,13 +4919,13 @@
 
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Show full diff anyway"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset.html:247
-#: kallithea/templates/changeset/changeset.html:284
+#: kallithea/templates/changeset/changeset.html:231
+#: kallithea/templates/changeset/changeset.html:268
 #, fuzzy
 msgid "No revisions"
 msgstr "Neznáma revízia %s"
@@ -4939,62 +4944,71 @@
 msgid "on this changeset"
 msgstr "%s zmien"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
 #, fuzzy
 msgid "Delete comment?"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #, fuzzy
 msgid "Status change"
 msgstr "Posledné zmeny"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:59
-msgid "Commenting on line {1}."
+msgid "Commenting on line."
 msgstr ""
 
 #: kallithea/templates/changeset/changeset_file_comment.html:60
-#: kallithea/templates/changeset/changeset_file_comment.html:148
-#, python-format
-msgid "Comments parsed using %s syntax with %s support."
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:62
-msgid "Use @username inside this text to notify another user"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:72
-#: kallithea/templates/changeset/changeset_file_comment.html:184
-msgid "Comment preview"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:77
+msgid ""
+"Comments are in plain text. Use @username inside this text to notify "
+"another user."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:67
+#, fuzzy
+msgid "Set changeset status"
+msgstr "Zmeny"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:69
+msgid "Vote for pull request status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:75
+#, fuzzy
+msgid "No change"
+msgstr "Žiadne zmeny"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:88
+#, fuzzy
+msgid "Finish pull request"
+msgstr "Zmena stavu"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:91
+#, fuzzy
+msgid "Close"
+msgstr "(zatvorené)"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:103
 msgid "Submitting ..."
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:80
-#: kallithea/templates/changeset/changeset_file_comment.html:190
+#: kallithea/templates/changeset/changeset_file_comment.html:104
 msgid "Comment"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:82
-#: kallithea/templates/changeset/changeset_file_comment.html:191
-msgid "Preview"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "You need to be logged in to comment."
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "Login now"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:94
+#: kallithea/templates/changeset/changeset_file_comment.html:116
 msgid "Hide"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:106
+#: kallithea/templates/changeset/changeset_file_comment.html:128
 #, python-format
 msgid "%d comment"
 msgid_plural "%d comments"
@@ -5002,7 +5016,7 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:107
+#: kallithea/templates/changeset/changeset_file_comment.html:129
 #, fuzzy, python-format
 msgid "%d inline"
 msgid_plural "%d inline"
@@ -5010,7 +5024,7 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:108
+#: kallithea/templates/changeset/changeset_file_comment.html:130
 #, python-format
 msgid "%d general"
 msgid_plural "%d general"
@@ -5018,29 +5032,6 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:150
-msgid "Use @username inside this text to notify another user."
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:157
-msgid "Vote for pull request status"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:159
-#, fuzzy
-msgid "Set changeset status"
-msgstr "Zmeny"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:163
-#, fuzzy
-msgid "No change"
-msgstr "Žiadne zmeny"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:176
-#, fuzzy
-msgid "Close"
-msgstr "(zatvorené)"
-
 #: kallithea/templates/changeset/changeset_range.html:5
 #, python-format
 msgid "%s Changesets"
@@ -5050,29 +5041,28 @@
 msgid "Files affected"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:21
+#: kallithea/templates/changeset/diff_block.html:54
+msgid "Deleted"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:57
+msgid "Renamed"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:66
 #: kallithea/templates/files/diff_2way.html:43
 msgid "Show full diff for this file"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:24
-#: kallithea/templates/changeset/diff_block.html:98
+#: kallithea/templates/changeset/diff_block.html:69
 #: kallithea/templates/files/diff_2way.html:46
 msgid "Show full side-by-side diff for this file"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:38
+#: kallithea/templates/changeset/diff_block.html:83
 msgid "Show inline comments"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:86
-msgid "Deleted"
-msgstr ""
-
-#: kallithea/templates/changeset/diff_block.html:89
-msgid "Renamed"
-msgstr ""
-
 #: kallithea/templates/compare/compare_cs.html:4
 msgid "No changesets"
 msgstr ""
@@ -5081,6 +5071,11 @@
 msgid "Ancestor"
 msgstr ""
 
+#: kallithea/templates/compare/compare_cs.html:24
+#, python-format
+msgid "Changeset status: %s"
+msgstr ""
+
 #: kallithea/templates/compare/compare_cs.html:44
 msgid "First (oldest) changeset in this list"
 msgstr ""
@@ -5093,29 +5088,29 @@
 msgid "Position in this list of changesets"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:76
+#: kallithea/templates/compare/compare_cs.html:85
 msgid "Show merge diff"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:86
-#: kallithea/templates/pullrequests/pullrequest_show.html:310
+#: kallithea/templates/compare/compare_cs.html:95
+#: kallithea/templates/pullrequests/pullrequest_show.html:321
 msgid "Common ancestor"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:90
-msgid "No common ancestor found - repositories are unrelated"
-msgstr ""
-
-#: kallithea/templates/compare/compare_cs.html:98
-msgid "is"
-msgstr ""
-
 #: kallithea/templates/compare/compare_cs.html:99
+msgid "No common ancestor found - repositories are unrelated"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:107
+msgid "is"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:108
 #, fuzzy, python-format
 msgid "%s changesets"
 msgstr "%s zmien"
 
-#: kallithea/templates/compare/compare_cs.html:100
+#: kallithea/templates/compare/compare_cs.html:109
 msgid "behind"
 msgstr ""
 
@@ -5126,20 +5121,20 @@
 msgstr ""
 
 #: kallithea/templates/compare/compare_diff.html:13
-#: kallithea/templates/compare/compare_diff.html:35
+#: kallithea/templates/compare/compare_diff.html:41
 msgid "Compare Revisions"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:33
+#: kallithea/templates/compare/compare_diff.html:39
 msgid "Swap"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:42
+#: kallithea/templates/compare/compare_diff.html:48
 msgid "Compare revisions, branches, bookmarks, or tags."
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:47
-#: kallithea/templates/pullrequests/pullrequest_show.html:305
+#: kallithea/templates/compare/compare_diff.html:53
+#: kallithea/templates/pullrequests/pullrequest_show.html:316
 #, python-format
 msgid "Showing %s commit"
 msgid_plural "Showing %s commits"
@@ -5147,8 +5142,8 @@
 msgstr[1] ""
 msgstr[2] ""
 
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
 msgid "Show full diff"
 msgstr ""
 
@@ -5207,17 +5202,23 @@
 msgid "We have received a request to reset the password for your account."
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:7
-msgid "To set a new password, click the following link"
+#: kallithea/templates/email_templates/password_reset.html:8
+msgid ""
+"This account is however managed outside this system and the password "
+"cannot be changed here."
 msgstr ""
 
 #: kallithea/templates/email_templates/password_reset.html:10
+msgid "To set a new password, click the following link"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:13
 msgid ""
 "Should you not be able to use the link above, please type the following "
 "code into the password reset form"
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:12
+#: kallithea/templates/email_templates/password_reset.html:16
 msgid ""
 "If it weren't you who requested the password reset, just disregard this "
 "message."
@@ -5300,7 +5301,7 @@
 msgstr ""
 
 #: kallithea/templates/files/files_add.html:53
-msgid "New file mode"
+msgid "New file type"
 msgstr ""
 
 #: kallithea/templates/files/files_add.html:64
@@ -5433,8 +5434,16 @@
 msgid "Binary file (%s)"
 msgstr ""
 
-#: kallithea/templates/files/files_source.html:73
-msgid "File is too big to display"
+#: kallithea/templates/files/files_source.html:74
+msgid "File is too big to display."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:76
+msgid "Show full annotation anyway."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:78
+msgid "Show as raw."
 msgstr ""
 
 #: kallithea/templates/files/files_ypjax.html:5
@@ -5699,41 +5708,47 @@
 msgid "Current revision - no change"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:213
+#: kallithea/templates/pullrequests/pullrequest_show.html:215
+msgid ""
+"Pull requests do not change once created. Select a revision and save to "
+"replace this pull request with a new one."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:224
 msgid "Pull Request Reviewers"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:238
+#: kallithea/templates/pullrequests/pullrequest_show.html:249
 #, fuzzy
 msgid "Remove reviewer"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:250
-msgid "Type name of reviewer to add"
-msgstr ""
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:258
-#, fuzzy
-msgid "Potential Reviewers"
-msgstr ""
-
 #: kallithea/templates/pullrequests/pullrequest_show.html:261
+msgid "Type name of reviewer to add"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:269
+#, fuzzy
+msgid "Potential Reviewers"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:272
 msgid "Click to add the repository owner as reviewer:"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:284
+#: kallithea/templates/pullrequests/pullrequest_show.html:295
 msgid "Save Changes"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:285
-msgid "Save as New Pull Request"
-msgstr ""
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:286
+#: kallithea/templates/pullrequests/pullrequest_show.html:296
+msgid "Save Updates as New Pull Request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:297
 msgid "Cancel Changes"
 msgstr "Zrušiť zmeny"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#: kallithea/templates/pullrequests/pullrequest_show.html:307
 msgid "Pull Request Content"
 msgstr ""
 
@@ -5743,9 +5758,9 @@
 msgstr ""
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:11
-#, python-format
-msgid "Pull Requests from %s'"
-msgstr ""
+#, fuzzy, python-format
+msgid "Pull Requests from '%s'"
+msgstr "Zmena stavu"
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:13
 #, python-format
@@ -6314,39 +6329,12 @@
 #~ msgid "Your password reset link was sent"
 #~ msgstr ""
 
-#~ msgid ""
-#~ "Your password reset was successful, new"
-#~ " password has been sent to your "
-#~ "email"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " changeset %(short_id)s on %(branch)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Added by %(pr_username)s] %(repo_name)s pull"
-#~ " request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " pull request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
 #~ msgid "Your new password"
 #~ msgstr ""
 
 #~ msgid "Your new Kallithea password:%s"
 #~ msgstr ""
 
-#~ msgid ""
-#~ "Password reset link will be sent "
-#~ "to the email address matching your "
-#~ "username."
-#~ msgstr ""
-
 #~ msgid "Open New Pull Request for Selected Changesets"
 #~ msgstr ""
 
@@ -6368,3 +6356,50 @@
 #~ msgid "Created by"
 #~ msgstr ""
 
+#~ msgid "You can only delete files with revision being a valid branch "
+#~ msgstr ""
+
+#~ msgid "You can only edit files with revision being a valid branch "
+#~ msgstr ""
+
+#~ msgid "This pull request can be updated with changes on %s:"
+#~ msgstr ""
+
+#~ msgid "Confirm to invalidate repository cache."
+#~ msgstr ""
+
+#~ msgid "Commenting on line {1}."
+#~ msgstr ""
+
+#~ msgid "Comments parsed using %s syntax with %s support."
+#~ msgstr ""
+
+#~ msgid "Use @username inside this text to notify another user"
+#~ msgstr ""
+
+#~ msgid "Comment preview"
+#~ msgstr ""
+
+#~ msgid "Preview"
+#~ msgstr ""
+
+#~ msgid "Use @username inside this text to notify another user."
+#~ msgstr ""
+
+#~ msgid "New file mode"
+#~ msgstr ""
+
+#~ msgid "File is too big to display"
+#~ msgstr ""
+
+#~ msgid "Save as New Pull Request"
+#~ msgstr ""
+
+#~ msgid "Pull Requests from %s'"
+#~ msgstr ""
+
+#~ msgid ""
+#~ "Changeset status: %s\n"
+#~ "Click to open associated pull request %s"
+#~ msgstr ""
+
--- a/kallithea/i18n/zh_CN/LC_MESSAGES/kallithea.po	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/i18n/zh_CN/LC_MESSAGES/kallithea.po	Fri Nov 18 01:11:13 2016 +0100
@@ -9,23 +9,25 @@
 msgstr ""
 "Project-Id-Version: Kallithea 0.3\n"
 "Report-Msgid-Bugs-To: translations@kallithea-scm.org\n"
-"POT-Creation-Date: 2015-09-08 10:34+0200\n"
-"PO-Revision-Date: 2014-12-12 14:19+0200\n"
-"Last-Translator: Michal Čihař <michal@cihar.com>\n"
-"Language-Team: Simplified Chinese "
+"POT-Creation-Date: 2016-03-14 16:51+0100\n"
+"PO-Revision-Date: 2016-03-24 15:03+0000\n"
+"Last-Translator: YFdyh000 <yfdyh000@gmail.com>\n"
+"Language-Team: Chinese (China) "
 "<https://hosted.weblate.org/projects/kallithea/kallithea/zh_CN/>\n"
 "Language: zh_CN\n"
 "MIME-Version: 1.0\n"
 "Content-Type: text/plain; charset=utf-8\n"
 "Content-Transfer-Encoding: 8bit\n"
 "Plural-Forms: nplurals=1; plural=0;\n"
-
-#: kallithea/controllers/changelog.py:86
-#: kallithea/controllers/pullrequests.py:238 kallithea/lib/base.py:512
+"X-Generator: Weblate 2.6-dev\n"
+"Generated-By: Babel 1.3\n"
+
+#: kallithea/controllers/changelog.py:85
+#: kallithea/controllers/pullrequests.py:240 kallithea/lib/base.py:515
 msgid "There are no changesets yet"
 msgstr "还没有修订集"
 
-#: kallithea/controllers/changelog.py:166
+#: kallithea/controllers/changelog.py:164
 #: kallithea/controllers/admin/permissions.py:61
 #: kallithea/controllers/admin/permissions.py:65
 #: kallithea/controllers/admin/permissions.py:69
@@ -37,51 +39,44 @@
 msgid "None"
 msgstr "无"
 
-#: kallithea/controllers/changelog.py:169 kallithea/controllers/files.py:196
+#: kallithea/controllers/changelog.py:167 kallithea/controllers/files.py:198
 msgid "(closed)"
-msgstr ""
-
-#: kallithea/controllers/changeset.py:89
+msgstr "(已关闭)"
+
+#: kallithea/controllers/changeset.py:88
 msgid "Show whitespace"
-msgstr ""
-
-#: kallithea/controllers/changeset.py:96 kallithea/controllers/changeset.py:103
+msgstr "显示空白"
+
+#: kallithea/controllers/changeset.py:95 kallithea/controllers/changeset.py:102
 #: kallithea/templates/files/diff_2way.html:55
 msgid "Ignore whitespace"
-msgstr ""
-
-#: kallithea/controllers/changeset.py:169
+msgstr "忽略空白"
+
+#: kallithea/controllers/changeset.py:168
 #, python-format
 msgid "Increase diff context to %(num)s lines"
-msgstr ""
-
-#: kallithea/controllers/changeset.py:212 kallithea/controllers/files.py:96
-#: kallithea/controllers/files.py:116 kallithea/controllers/files.py:742
+msgstr "增加差异上下文到 %(num)s 行"
+
+#: kallithea/controllers/changeset.py:233 kallithea/controllers/files.py:97
+#: kallithea/controllers/files.py:117 kallithea/controllers/files.py:744
 msgid "Such revision does not exist for this repository"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:383
-msgid ""
-"Changing status on a changeset associated with a closed pull request is "
-"not allowed"
-msgstr ""
-
 #: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:41
 msgid "Select changeset"
-msgstr ""
+msgstr "选择修订集"
 
 #: kallithea/controllers/compare.py:261
 msgid "Cannot compare repositories without using common ancestor"
 msgstr ""
 
 #: kallithea/controllers/error.py:71
-#, fuzzy
 msgid "No response"
-msgstr "修订"
+msgstr "无响应"
 
 #: kallithea/controllers/error.py:72
 msgid "Unknown error"
-msgstr ""
+msgstr "未知错误"
 
 #: kallithea/controllers/error.py:100
 msgid "The request could not be understood by the server due to malformed syntax."
@@ -118,123 +113,123 @@
 #: kallithea/controllers/feed.py:87
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Changeset was too big and was cut off..."
-msgstr "修订集太大已被截断......"
+msgstr "修订集太大并已被截断..."
 
 #: kallithea/controllers/feed.py:91
 #, python-format
 msgid "%s committed on %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:91
+#: kallithea/controllers/files.py:92
 msgid "Click here to add new file"
-msgstr ""
-
-#: kallithea/controllers/files.py:92
+msgstr "点击这里添加新文件"
+
+#: kallithea/controllers/files.py:93
 #, python-format
 msgid "There are no files yet. %s"
-msgstr ""
-
-#: kallithea/controllers/files.py:193
-#, fuzzy, python-format
+msgstr "这里还没有文件。%s"
+
+#: kallithea/controllers/files.py:195
+#, python-format
 msgid "%s at %s"
-msgstr "%s零%s"
-
-#: kallithea/controllers/files.py:305 kallithea/controllers/files.py:365
-#: kallithea/controllers/files.py:432
+msgstr "%s 在 %s"
+
+#: kallithea/controllers/files.py:307 kallithea/controllers/files.py:367
+#: kallithea/controllers/files.py:434
 #, python-format
 msgid "This repository has been locked by %s on %s"
 msgstr "版本库由%s于%s锁定"
 
-#: kallithea/controllers/files.py:317
-msgid "You can only delete files with revision being a valid branch "
-msgstr ""
-
-#: kallithea/controllers/files.py:328
+#: kallithea/controllers/files.py:319
+msgid "You can only delete files with revision being a valid branch"
+msgstr "您只能删除有效分支的修订中的文件"
+
+#: kallithea/controllers/files.py:330
 #, python-format
 msgid "Deleted file %s via Kallithea"
-msgstr ""
-
-#: kallithea/controllers/files.py:350
+msgstr "删除文件 %s 通过 Kallithea"
+
+#: kallithea/controllers/files.py:352
 #, python-format
 msgid "Successfully deleted file %s"
-msgstr ""
-
-#: kallithea/controllers/files.py:354 kallithea/controllers/files.py:420
-#: kallithea/controllers/files.py:501
+msgstr "成功删除文件 %s"
+
+#: kallithea/controllers/files.py:356 kallithea/controllers/files.py:422
+#: kallithea/controllers/files.py:503
 msgid "Error occurred during commit"
 msgstr "提交时发生错误"
 
-#: kallithea/controllers/files.py:377
-msgid "You can only edit files with revision being a valid branch "
-msgstr ""
-
-#: kallithea/controllers/files.py:391
+#: kallithea/controllers/files.py:379
+msgid "You can only edit files with revision being a valid branch"
+msgstr "您只能编辑有效分支的修订中的文件"
+
+#: kallithea/controllers/files.py:393
 #, python-format
 msgid "Edited file %s via Kallithea"
-msgstr ""
-
-#: kallithea/controllers/files.py:407
+msgstr "已编辑文件 %s 通过 Kallithea"
+
+#: kallithea/controllers/files.py:409
 msgid "No changes"
 msgstr "无变更"
 
-#: kallithea/controllers/files.py:416 kallithea/controllers/files.py:490
+#: kallithea/controllers/files.py:418 kallithea/controllers/files.py:492
 #, python-format
 msgid "Successfully committed to %s"
 msgstr "成功提交到%s"
 
-#: kallithea/controllers/files.py:443
+#: kallithea/controllers/files.py:445
 msgid "Added file via Kallithea"
-msgstr ""
-
-#: kallithea/controllers/files.py:464
+msgstr "已添加文件通过 Kallithea"
+
+#: kallithea/controllers/files.py:466
 msgid "No content"
 msgstr "无内容"
 
-#: kallithea/controllers/files.py:468
+#: kallithea/controllers/files.py:470
 msgid "No filename"
 msgstr "无文件名"
 
-#: kallithea/controllers/files.py:493
+#: kallithea/controllers/files.py:495
 msgid "Location must be relative path and must not contain .. in path"
 msgstr ""
 
-#: kallithea/controllers/files.py:526
+#: kallithea/controllers/files.py:528
 msgid "Downloads disabled"
-msgstr ""
-
-#: kallithea/controllers/files.py:537
+msgstr "下载已禁用"
+
+#: kallithea/controllers/files.py:539
 #, python-format
 msgid "Unknown revision %s"
 msgstr "未知版本%s"
 
-#: kallithea/controllers/files.py:539
+#: kallithea/controllers/files.py:541
 msgid "Empty repository"
 msgstr "空版本库"
 
-#: kallithea/controllers/files.py:541
+#: kallithea/controllers/files.py:543
 msgid "Unknown archive type"
 msgstr "未知包类型"
 
-#: kallithea/controllers/files.py:771
+#: kallithea/controllers/files.py:773
 #: kallithea/templates/changeset/changeset_range.html:9
 #: kallithea/templates/email_templates/pull_request.html:15
 #: kallithea/templates/pullrequests/pullrequest.html:97
 msgid "Changesets"
 msgstr "修订集"
 
-#: kallithea/controllers/files.py:772 kallithea/controllers/pullrequests.py:176
-#: kallithea/model/scm.py:820 kallithea/templates/switch_to_list.html:3
+#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:175
+#: kallithea/model/scm.py:716 kallithea/templates/switch_to_list.html:3
 #: kallithea/templates/branches/branches.html:10
 msgid "Branches"
 msgstr "分支"
 
-#: kallithea/controllers/files.py:773 kallithea/controllers/pullrequests.py:177
-#: kallithea/model/scm.py:831 kallithea/templates/switch_to_list.html:25
+#: kallithea/controllers/files.py:775 kallithea/controllers/pullrequests.py:176
+#: kallithea/model/scm.py:727 kallithea/templates/switch_to_list.html:25
 #: kallithea/templates/tags/tags.html:10
 msgid "Tags"
 msgstr "标签"
@@ -246,9 +241,9 @@
 
 #: kallithea/controllers/home.py:84
 msgid "Groups"
-msgstr ""
-
-#: kallithea/controllers/home.py:89
+msgstr "组"
+
+#: kallithea/controllers/home.py:94
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:106
 #: kallithea/templates/admin/repos/repo_add.html:12
 #: kallithea/templates/admin/repos/repo_add.html:16
@@ -256,25 +251,29 @@
 #: kallithea/templates/admin/users/user_edit_advanced.html:6
 #: kallithea/templates/base/base.html:60 kallithea/templates/base/base.html:77
 #: kallithea/templates/base/base.html:124
-#: kallithea/templates/base/base.html:390
-#: kallithea/templates/base/base.html:562
+#: kallithea/templates/base/base.html:479
+#: kallithea/templates/base/base.html:653
 msgid "Repositories"
 msgstr "版本库"
 
-#: kallithea/controllers/home.py:130
+#: kallithea/controllers/home.py:139
 #: kallithea/templates/files/files_add.html:32
 #: kallithea/templates/files/files_delete.html:23
 #: kallithea/templates/files/files_edit.html:32
 msgid "Branch"
-msgstr ""
-
-#: kallithea/controllers/home.py:136
+msgstr "分支"
+
+#: kallithea/controllers/home.py:145 kallithea/templates/switch_to_list.html:16
+msgid "Closed Branches"
+msgstr "已关闭分支"
+
+#: kallithea/controllers/home.py:151
 msgid "Tag"
-msgstr ""
-
-#: kallithea/controllers/home.py:142
+msgstr "标签"
+
+#: kallithea/controllers/home.py:157
 msgid "Bookmark"
-msgstr ""
+msgstr "书签"
 
 #: kallithea/controllers/journal.py:111 kallithea/controllers/journal.py:153
 #: kallithea/templates/journal/public_journal.html:4
@@ -283,169 +282,165 @@
 msgstr "公共日志"
 
 #: kallithea/controllers/journal.py:115 kallithea/controllers/journal.py:157
-#: kallithea/templates/base/base.html:222
+#: kallithea/templates/base/base.html:306
 #: kallithea/templates/journal/journal.html:4
 #: kallithea/templates/journal/journal.html:12
 msgid "Journal"
 msgstr "日志"
 
-#: kallithea/controllers/login.py:151 kallithea/controllers/login.py:197
+#: kallithea/controllers/login.py:144 kallithea/controllers/login.py:190
 msgid "Bad captcha"
-msgstr ""
-
-#: kallithea/controllers/login.py:157
-msgid "You have successfully registered into Kallithea"
-msgstr ""
-
-#: kallithea/controllers/login.py:202
-#, fuzzy
-#| msgid "Your password reset link was sent"
+msgstr "验证码错误"
+
+#: kallithea/controllers/login.py:150
+msgid "You have successfully registered with %s"
+msgstr "您已成功注册 %s"
+
+#: kallithea/controllers/login.py:195
 msgid "A password reset confirmation code has been sent"
-msgstr "密码重置链接已经发送"
-
-#: kallithea/controllers/login.py:251
-#, fuzzy
-#| msgid "Your password reset link was sent"
+msgstr "密码重置确认码已经发送"
+
+#: kallithea/controllers/login.py:244
 msgid "Invalid password reset token"
-msgstr "密码重置链接已经发送"
-
-#: kallithea/controllers/login.py:256
+msgstr "无效的密码重置令牌"
+
+#: kallithea/controllers/login.py:249
 #: kallithea/controllers/admin/my_account.py:167
 msgid "Successfully updated password"
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:124
+msgstr "成功更新密码"
+
+#: kallithea/controllers/pullrequests.py:123
 #, python-format
 msgid "%s (closed)"
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:152
+msgstr "%s (已关闭)"
+
+#: kallithea/controllers/pullrequests.py:151
 #: kallithea/templates/changeset/changeset.html:12
 #: kallithea/templates/email_templates/changeset_comment.html:17
 msgid "Changeset"
 msgstr "修订集"
 
-#: kallithea/controllers/pullrequests.py:173
+#: kallithea/controllers/pullrequests.py:172
 msgid "Special"
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:174
+msgstr "特殊"
+
+#: kallithea/controllers/pullrequests.py:173
 msgid "Peer branches"
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:175 kallithea/model/scm.py:826
+msgstr "同等分支"
+
+#: kallithea/controllers/pullrequests.py:174 kallithea/model/scm.py:722
 #: kallithea/templates/switch_to_list.html:38
 #: kallithea/templates/bookmarks/bookmarks.html:10
 msgid "Bookmarks"
 msgstr "书签"
 
-#: kallithea/controllers/pullrequests.py:310
+#: kallithea/controllers/pullrequests.py:312
 #, python-format
 msgid "Error creating pull request: %s"
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:356
-#: kallithea/controllers/pullrequests.py:503
-#, fuzzy
+msgstr "创建拉取请求出错:%s"
+
+#: kallithea/controllers/pullrequests.py:358
+#: kallithea/controllers/pullrequests.py:505
 msgid "No description"
-msgstr "描述"
-
-#: kallithea/controllers/pullrequests.py:363
+msgstr "无描述"
+
+#: kallithea/controllers/pullrequests.py:365
 msgid "Successfully opened new pull request"
 msgstr "成功提交拉取请求"
 
-#: kallithea/controllers/pullrequests.py:366
-#: kallithea/controllers/pullrequests.py:453
-#: kallithea/controllers/pullrequests.py:509
+#: kallithea/controllers/pullrequests.py:368
+#: kallithea/controllers/pullrequests.py:455
+#: kallithea/controllers/pullrequests.py:512
 #, python-format
 msgid "Invalid reviewer \"%s\" specified"
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:369
-#: kallithea/controllers/pullrequests.py:456
-#, fuzzy
+msgstr "指定的审核者 \"%s\" 无效"
+
+#: kallithea/controllers/pullrequests.py:371
+#: kallithea/controllers/pullrequests.py:458
 msgid "Error occurred while creating pull request"
-msgstr "提交拉取请求时发生错误"
-
-#: kallithea/controllers/pullrequests.py:401
+msgstr "创建拉取请求时发生错误"
+
+#: kallithea/controllers/pullrequests.py:403
 msgid "Missing changesets since the previous pull request:"
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:408
+msgstr "缺少上次拉取请求之后的修订集:"
+
+#: kallithea/controllers/pullrequests.py:410
 #, python-format
 msgid "New changesets on %s %s since the previous pull request:"
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:415
+msgstr "在上次拉取请求之后,在 %s %s 上的新修订集:"
+
+#: kallithea/controllers/pullrequests.py:417
 msgid "Ancestor didn't change - show diff since previous version:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:422
+#: kallithea/controllers/pullrequests.py:424
 #, python-format
 msgid ""
 "This pull request is based on another %s revision and there is no simple "
 "diff."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:424
+#: kallithea/controllers/pullrequests.py:426
 #, python-format
 msgid "No changes found on %s %s since previous version."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:462
+#: kallithea/controllers/pullrequests.py:464
 #, python-format
 msgid "Closed, replaced by %s ."
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:470
-#, fuzzy
+msgstr "已关闭,被 %s 替换。"
+
+#: kallithea/controllers/pullrequests.py:472
 msgid "Pull request update created"
-msgstr "拉取请求检视人员"
-
-#: kallithea/controllers/pullrequests.py:513
-#, fuzzy
+msgstr "拉取请求更新已创建"
+
+#: kallithea/controllers/pullrequests.py:516
 msgid "Pull request updated"
-msgstr "拉取请求"
-
-#: kallithea/controllers/pullrequests.py:528
+msgstr "拉取请求已更新"
+
+#: kallithea/controllers/pullrequests.py:531
 msgid "Successfully deleted pull request"
 msgstr "成功删除拉取请求"
 
-#: kallithea/controllers/pullrequests.py:594
+#: kallithea/controllers/pullrequests.py:597
 #, python-format
 msgid "This pull request has already been merged to %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:596
+#: kallithea/controllers/pullrequests.py:599
 msgid "This pull request has been closed and can not be updated."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:614
-#, python-format
-msgid "This pull request can be updated with changes on %s:"
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:617
+#, python-format
+msgid "The following changes are available on %s:"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:621
 msgid "No changesets found for updating this pull request."
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:625
+msgstr "没有找到更新此拉取请求的修订集。"
+
+#: kallithea/controllers/pullrequests.py:629
 #, python-format
 msgid "Note: Branch %s has another head: %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:631
+#: kallithea/controllers/pullrequests.py:635
 msgid "Git pull requests don't support updates yet."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:722
-msgid "No permission to change pull request status"
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:727
-#, fuzzy
+msgid "No permission to change pull request status"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:738
+#, fuzzy, python-format
+msgid "Successfully deleted pull request %s"
+msgstr "成功删除拉取请求"
+
+#: kallithea/controllers/pullrequests.py:748
 msgid "Closing."
-msgstr "使用中"
+msgstr "关闭。"
 
 #: kallithea/controllers/search.py:135
 msgid "Invalid search query. Try quoting it."
@@ -456,28 +451,26 @@
 msgstr "没有索引用于搜索。请运行whoosh索引器"
 
 #: kallithea/controllers/search.py:144
-#, fuzzy
 msgid "An error occurred during search operation."
-msgstr "在搜索操作中发生异常"
-
-#: kallithea/controllers/summary.py:180
+msgstr "搜索操作期间发生错误。"
+
+#: kallithea/controllers/summary.py:181
 #: kallithea/templates/summary/summary.html:384
-#, fuzzy
 msgid "No data ready yet"
-msgstr "数据未加载"
-
-#: kallithea/controllers/summary.py:183
+msgstr "数据尚未就绪"
+
+#: kallithea/controllers/summary.py:184
 #: kallithea/templates/summary/summary.html:98
 msgid "Statistics are disabled for this repository"
 msgstr "该版本库统计功能已经禁用"
 
 #: kallithea/controllers/admin/auth_settings.py:135
 msgid "Auth settings updated successfully"
-msgstr ""
+msgstr "验证设置更新成功"
 
 #: kallithea/controllers/admin/auth_settings.py:146
 msgid "error occurred during update of auth settings"
-msgstr ""
+msgstr "验证设置更新时发生错误"
 
 #: kallithea/controllers/admin/defaults.py:97
 msgid "Default settings updated successfully"
@@ -485,71 +478,70 @@
 
 #: kallithea/controllers/admin/defaults.py:112
 msgid "Error occurred during update of defaults"
-msgstr ""
-
-#: kallithea/controllers/admin/gists.py:59
+msgstr "默认值更新时发生错误"
+
+#: kallithea/controllers/admin/gists.py:58
 #: kallithea/controllers/admin/my_account.py:243
-#: kallithea/controllers/admin/users.py:285
+#: kallithea/controllers/admin/users.py:284
 #, fuzzy
 msgid "Forever"
 msgstr "检视者"
 
+#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/my_account.py:244
+#: kallithea/controllers/admin/users.py:285
+msgid "5 minutes"
+msgstr "5 分钟"
+
 #: kallithea/controllers/admin/gists.py:60
-#: kallithea/controllers/admin/my_account.py:244
+#: kallithea/controllers/admin/my_account.py:245
 #: kallithea/controllers/admin/users.py:286
-msgid "5 minutes"
-msgstr ""
+msgid "1 hour"
+msgstr "1 小时"
 
 #: kallithea/controllers/admin/gists.py:61
-#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/my_account.py:246
 #: kallithea/controllers/admin/users.py:287
-msgid "1 hour"
-msgstr ""
+msgid "1 day"
+msgstr "1 天"
 
 #: kallithea/controllers/admin/gists.py:62
-#: kallithea/controllers/admin/my_account.py:246
+#: kallithea/controllers/admin/my_account.py:247
 #: kallithea/controllers/admin/users.py:288
-msgid "1 day"
-msgstr ""
-
-#: kallithea/controllers/admin/gists.py:63
-#: kallithea/controllers/admin/my_account.py:247
-#: kallithea/controllers/admin/users.py:289
 msgid "1 month"
-msgstr ""
-
-#: kallithea/controllers/admin/gists.py:67
+msgstr "1 个月"
+
+#: kallithea/controllers/admin/gists.py:66
 #: kallithea/controllers/admin/my_account.py:249
-#: kallithea/controllers/admin/users.py:291
+#: kallithea/controllers/admin/users.py:290
 msgid "Lifetime"
-msgstr ""
-
-#: kallithea/controllers/admin/gists.py:146
+msgstr "终身"
+
+#: kallithea/controllers/admin/gists.py:145
 msgid "Error occurred during gist creation"
-msgstr ""
-
-#: kallithea/controllers/admin/gists.py:184
+msgstr "gist 创建时发生错误"
+
+#: kallithea/controllers/admin/gists.py:183
 #, python-format
 msgid "Deleted gist %s"
-msgstr ""
-
-#: kallithea/controllers/admin/gists.py:233
-#, fuzzy
+msgstr "已删除 gist %s"
+
+#: kallithea/controllers/admin/gists.py:232
 msgid "Unmodified"
-msgstr "最后修改于"
-
-#: kallithea/controllers/admin/gists.py:262
+msgstr "未修改"
+
+#: kallithea/controllers/admin/gists.py:261
 msgid "Successfully updated gist content"
-msgstr ""
-
-#: kallithea/controllers/admin/gists.py:267
+msgstr "成功更新 gist 内容"
+
+#: kallithea/controllers/admin/gists.py:266
 msgid "Successfully updated gist data"
-msgstr ""
-
-#: kallithea/controllers/admin/gists.py:270
+msgstr "成功更新 gist 数据"
+
+#: kallithea/controllers/admin/gists.py:269
 #, python-format
 msgid "Error occurred during update of gist %s"
-msgstr ""
+msgstr "gist %s 更新时发生错误"
 
 #: kallithea/controllers/admin/my_account.py:70 kallithea/model/user.py:215
 #: kallithea/model/user.py:237
@@ -561,45 +553,45 @@
 msgstr "你的帐号已经更新完成"
 
 #: kallithea/controllers/admin/my_account.py:144
-#: kallithea/controllers/admin/users.py:202
+#: kallithea/controllers/admin/users.py:201
 #, python-format
 msgid "Error occurred during update of user %s"
-msgstr ""
+msgstr "用户 %s 更新时发生错误"
 
 #: kallithea/controllers/admin/my_account.py:178
 msgid "Error occurred during update of user password"
-msgstr ""
+msgstr "用户密码更新时发生错误"
 
 #: kallithea/controllers/admin/my_account.py:220
-#: kallithea/controllers/admin/users.py:415
+#: kallithea/controllers/admin/users.py:414
 #, python-format
 msgid "Added email %s to user"
 msgstr "已为用户添加电子邮件 %s"
 
 #: kallithea/controllers/admin/my_account.py:226
-#: kallithea/controllers/admin/users.py:421
+#: kallithea/controllers/admin/users.py:420
 msgid "An error occurred during email saving"
 msgstr "保存电子邮件时发生错误"
 
 #: kallithea/controllers/admin/my_account.py:235
-#: kallithea/controllers/admin/users.py:433
+#: kallithea/controllers/admin/users.py:432
 msgid "Removed email from user"
 msgstr "成功删除用户电子邮件"
 
 #: kallithea/controllers/admin/my_account.py:259
-#: kallithea/controllers/admin/users.py:308
+#: kallithea/controllers/admin/users.py:307
 msgid "API key successfully created"
-msgstr ""
+msgstr "API 密钥创建成功"
 
 #: kallithea/controllers/admin/my_account.py:271
-#: kallithea/controllers/admin/users.py:321
+#: kallithea/controllers/admin/users.py:320
 msgid "API key successfully reset"
-msgstr ""
+msgstr "API 密钥重置成功"
 
 #: kallithea/controllers/admin/my_account.py:275
-#: kallithea/controllers/admin/users.py:325
+#: kallithea/controllers/admin/users.py:324
 msgid "API key successfully deleted"
-msgstr ""
+msgstr "API 密钥删除成功"
 
 #: kallithea/controllers/admin/permissions.py:62
 #: kallithea/controllers/admin/permissions.py:66
@@ -647,10 +639,10 @@
 #: kallithea/templates/admin/users/user_edit_profile.html:105
 #: kallithea/templates/admin/users/users.html:10
 #: kallithea/templates/admin/users/users.html:55
-#: kallithea/templates/base/base.html:252
-#: kallithea/templates/base/base.html:253
-#: kallithea/templates/base/base.html:259
-#: kallithea/templates/base/base.html:260
+#: kallithea/templates/base/base.html:336
+#: kallithea/templates/base/base.html:337
+#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:344
 #: kallithea/templates/base/perms_summary.html:17
 msgid "Admin"
 msgstr "管理"
@@ -667,11 +659,11 @@
 
 #: kallithea/controllers/admin/permissions.py:77
 msgid "Allowed with manual account activation"
-msgstr ""
+msgstr "已允许手动激活账号"
 
 #: kallithea/controllers/admin/permissions.py:79
 msgid "Allowed with automatic account activation"
-msgstr ""
+msgstr "已允许自动激活账号"
 
 #: kallithea/controllers/admin/permissions.py:82
 #: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1439
@@ -681,9 +673,9 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1564
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1603
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1655
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1701
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1705
 msgid "Manual activation of external account"
-msgstr ""
+msgstr "外部账号手动激活"
 
 #: kallithea/controllers/admin/permissions.py:83
 #: kallithea/lib/dbmigrate/schema/db_1_7_0.py:1440
@@ -693,9 +685,9 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1565
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1604
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1656
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1702
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1706
 msgid "Automatic activation of external account"
-msgstr ""
+msgstr "外部账号自动激活"
 
 #: kallithea/controllers/admin/permissions.py:87
 #: kallithea/controllers/admin/permissions.py:90
@@ -708,250 +700,250 @@
 
 #: kallithea/controllers/admin/permissions.py:124
 msgid "Global permissions updated successfully"
-msgstr ""
+msgstr "全局权限更新成功"
 
 #: kallithea/controllers/admin/permissions.py:139
 msgid "Error occurred during update of permissions"
-msgstr ""
-
-#: kallithea/controllers/admin/repo_groups.py:188
+msgstr "权限更新时发生错误"
+
+#: kallithea/controllers/admin/repo_groups.py:187
 #, python-format
 msgid "Error occurred during creation of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:193
+#: kallithea/controllers/admin/repo_groups.py:192
 #, python-format
 msgid "Created repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:250
+#: kallithea/controllers/admin/repo_groups.py:249
 #, python-format
 msgid "Updated repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:266
+#: kallithea/controllers/admin/repo_groups.py:265
 #, python-format
 msgid "Error occurred during update of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:284
+#: kallithea/controllers/admin/repo_groups.py:283
 #, python-format
 msgid "This group contains %s repositories and cannot be deleted"
 msgstr "这个组内有%s个版本库因而无法删除"
 
-#: kallithea/controllers/admin/repo_groups.py:291
+#: kallithea/controllers/admin/repo_groups.py:290
 #, python-format
 msgid "This group contains %s subgroups and cannot be deleted"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:297
+#: kallithea/controllers/admin/repo_groups.py:296
 #, python-format
 msgid "Removed repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:302
+#: kallithea/controllers/admin/repo_groups.py:301
 #, python-format
 msgid "Error occurred during deletion of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:405
-#: kallithea/controllers/admin/repo_groups.py:440
+#: kallithea/controllers/admin/repo_groups.py:404
+#: kallithea/controllers/admin/repo_groups.py:439
 #: kallithea/controllers/admin/user_groups.py:340
 msgid "Cannot revoke permission for yourself as admin"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:420
+#: kallithea/controllers/admin/repo_groups.py:419
 msgid "Repository group permissions updated"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:457
-#: kallithea/controllers/admin/repos.py:398
+#: kallithea/controllers/admin/repo_groups.py:456
+#: kallithea/controllers/admin/repos.py:397
 #: kallithea/controllers/admin/user_groups.py:352
 msgid "An error occurred during revoking of permission"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:152
+#: kallithea/controllers/admin/repos.py:151
 #, python-format
 msgid "Error creating repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:213
+#: kallithea/controllers/admin/repos.py:212
 #, python-format
 msgid "Created repository %s from %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:222
+#: kallithea/controllers/admin/repos.py:221
 #, python-format
 msgid "Forked repository %s as %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:225
+#: kallithea/controllers/admin/repos.py:224
 #, python-format
 msgid "Created repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:262
+#: kallithea/controllers/admin/repos.py:261
 #, python-format
 msgid "Repository %s updated successfully"
 msgstr "版本库%s成功更新"
 
-#: kallithea/controllers/admin/repos.py:283
+#: kallithea/controllers/admin/repos.py:282
 #, python-format
 msgid "Error occurred during update of repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:310
+#: kallithea/controllers/admin/repos.py:309
 #, python-format
 msgid "Detached %s forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:313
+#: kallithea/controllers/admin/repos.py:312
 #, python-format
 msgid "Deleted %s forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:318
+#: kallithea/controllers/admin/repos.py:317
 #, python-format
 msgid "Deleted repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:321
+#: kallithea/controllers/admin/repos.py:320
 #, fuzzy, python-format
 msgid "Cannot delete repository %s which still has forks"
 msgstr "无法删除%s因为它还有其他分复刻本库"
 
-#: kallithea/controllers/admin/repos.py:326
+#: kallithea/controllers/admin/repos.py:325
 #, python-format
 msgid "An error occurred during deletion of %s"
 msgstr "在删除%s的时候发生错误"
 
-#: kallithea/controllers/admin/repos.py:374
+#: kallithea/controllers/admin/repos.py:373
 msgid "Repository permissions updated"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:430
+#: kallithea/controllers/admin/repos.py:429
 msgid "An error occurred during creation of field"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:444
+#: kallithea/controllers/admin/repos.py:443
 msgid "An error occurred during removal of field"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:460
+#: kallithea/controllers/admin/repos.py:459
 msgid "-- Not a fork --"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:491
+#: kallithea/controllers/admin/repos.py:490
 msgid "Updated repository visibility in public journal"
 msgstr "成功更新在公共日志中的可见性"
 
-#: kallithea/controllers/admin/repos.py:495
+#: kallithea/controllers/admin/repos.py:494
 msgid "An error occurred during setting this repository in public journal"
 msgstr "设置版本库到公共日志时发生错误"
 
-#: kallithea/controllers/admin/repos.py:512
+#: kallithea/controllers/admin/repos.py:511
 msgid "Nothing"
 msgstr "无"
 
-#: kallithea/controllers/admin/repos.py:514
+#: kallithea/controllers/admin/repos.py:513
 #, python-format
 msgid "Marked repository %s as fork of %s"
 msgstr "成功将版本库%s标记为复刻自%s"
 
-#: kallithea/controllers/admin/repos.py:521
+#: kallithea/controllers/admin/repos.py:520
 msgid "An error occurred during this operation"
 msgstr "在搜索操作中发生错误"
 
-#: kallithea/controllers/admin/repos.py:537
-#: kallithea/controllers/admin/repos.py:564
+#: kallithea/controllers/admin/repos.py:536
+#: kallithea/controllers/admin/repos.py:563
 #, fuzzy
 msgid "Repository has been locked"
 msgstr "版本库未锁定"
 
-#: kallithea/controllers/admin/repos.py:540
-#: kallithea/controllers/admin/repos.py:561
+#: kallithea/controllers/admin/repos.py:539
+#: kallithea/controllers/admin/repos.py:560
 #, fuzzy
 msgid "Repository has been unlocked"
 msgstr "版本库未锁定"
 
-#: kallithea/controllers/admin/repos.py:543
-#: kallithea/controllers/admin/repos.py:568
+#: kallithea/controllers/admin/repos.py:542
+#: kallithea/controllers/admin/repos.py:567
 msgid "An error occurred during unlocking"
 msgstr "解锁时发生错误"
 
-#: kallithea/controllers/admin/repos.py:582
+#: kallithea/controllers/admin/repos.py:581
 msgid "Cache invalidation successful"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:586
+#: kallithea/controllers/admin/repos.py:585
 msgid "An error occurred during cache invalidation"
 msgstr "清除缓存时发生错误"
 
-#: kallithea/controllers/admin/repos.py:601
+#: kallithea/controllers/admin/repos.py:600
 msgid "Pulled from remote location"
 msgstr "成功拉取自远程路径"
 
-#: kallithea/controllers/admin/repos.py:604
+#: kallithea/controllers/admin/repos.py:603
 msgid "An error occurred during pull from remote location"
 msgstr "从远程路径拉取时发生错误"
 
-#: kallithea/controllers/admin/repos.py:637
+#: kallithea/controllers/admin/repos.py:636
 msgid "An error occurred during deletion of repository stats"
 msgstr "删除版本库统计时发生错误"
 
-#: kallithea/controllers/admin/settings.py:170
+#: kallithea/controllers/admin/settings.py:141
 msgid "Updated VCS settings"
 msgstr "成功更新版本控制系统设置"
 
-#: kallithea/controllers/admin/settings.py:174
+#: kallithea/controllers/admin/settings.py:145
 msgid ""
 "Unable to activate hgsubversion support. The \"hgsubversion\" library is "
 "missing"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:180
-#: kallithea/controllers/admin/settings.py:277
+#: kallithea/controllers/admin/settings.py:151
+#: kallithea/controllers/admin/settings.py:248
 msgid "Error occurred while updating application settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:216
+#: kallithea/controllers/admin/settings.py:187
 #, python-format
 msgid "Repositories successfully rescanned. Added: %s. Removed: %s."
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:273
+#: kallithea/controllers/admin/settings.py:244
 msgid "Updated application settings"
 msgstr "更新应用设置"
 
-#: kallithea/controllers/admin/settings.py:330
+#: kallithea/controllers/admin/settings.py:301
 msgid "Updated visualisation settings"
 msgstr "成功更新可视化设置"
 
-#: kallithea/controllers/admin/settings.py:335
+#: kallithea/controllers/admin/settings.py:306
 msgid "Error occurred during updating visualisation settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:361
+#: kallithea/controllers/admin/settings.py:332
 msgid "Please enter email address"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:376
+#: kallithea/controllers/admin/settings.py:347
 msgid "Send email task created"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:407
+#: kallithea/controllers/admin/settings.py:378
 msgid "Added new hook"
 msgstr "新建钩子"
 
-#: kallithea/controllers/admin/settings.py:421
+#: kallithea/controllers/admin/settings.py:392
 msgid "Updated hooks"
 msgstr "更新钩子"
 
-#: kallithea/controllers/admin/settings.py:425
+#: kallithea/controllers/admin/settings.py:396
 msgid "Error occurred during hook creation"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:451
+#: kallithea/controllers/admin/settings.py:422
 msgid "Whoosh reindex task scheduled"
 msgstr "Whoosh重新索引任务调度"
 
@@ -992,76 +984,80 @@
 msgstr ""
 
 #: kallithea/controllers/admin/user_groups.py:440
-#: kallithea/controllers/admin/users.py:384
+#: kallithea/controllers/admin/users.py:383
 msgid "Updated permissions"
 msgstr ""
 
 #: kallithea/controllers/admin/user_groups.py:444
-#: kallithea/controllers/admin/users.py:388
+#: kallithea/controllers/admin/users.py:387
 msgid "An error occurred during permissions saving"
 msgstr "保存权限时发生错误"
 
-#: kallithea/controllers/admin/users.py:134
+#: kallithea/controllers/admin/users.py:133
 #, python-format
 msgid "Created user %s"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:149
+#: kallithea/controllers/admin/users.py:148
 #, python-format
 msgid "Error occurred during creation of user %s"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:182
+#: kallithea/controllers/admin/users.py:181
 msgid "User updated successfully"
 msgstr "用户更新成功"
 
-#: kallithea/controllers/admin/users.py:218
+#: kallithea/controllers/admin/users.py:217
 msgid "Successfully deleted user"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:223
+#: kallithea/controllers/admin/users.py:222
 msgid "An error occurred during deletion of user"
 msgstr "删除用户时发生错误"
 
-#: kallithea/controllers/admin/users.py:236
+#: kallithea/controllers/admin/users.py:235
 msgid "The default user cannot be edited"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:463
+#: kallithea/controllers/admin/users.py:462
 #, python-format
 msgid "Added IP address %s to user whitelist"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:469
+#: kallithea/controllers/admin/users.py:468
 msgid "An error occurred while adding IP address"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:483
+#: kallithea/controllers/admin/users.py:482
 msgid "Removed IP address from user whitelist"
 msgstr ""
 
-#: kallithea/lib/auth.py:743
+#: kallithea/lib/auth.py:737
 #, python-format
 msgid "IP %s not allowed"
 msgstr ""
 
-#: kallithea/lib/auth.py:756
+#: kallithea/lib/auth.py:750
 msgid "Invalid API key"
 msgstr ""
 
-#: kallithea/lib/auth.py:812
+#: kallithea/lib/auth.py:768
+msgid "CSRF token leak has been detected - all form tokens have been expired"
+msgstr ""
+
+#: kallithea/lib/auth.py:813
 msgid "You need to be a registered user to perform this action"
 msgstr "必须是注册用户才能进行此操作"
 
-#: kallithea/lib/auth.py:844
+#: kallithea/lib/auth.py:843
 msgid "You need to be signed in to view this page"
 msgstr "必须登录才能访问该页面"
 
-#: kallithea/lib/base.py:490
+#: kallithea/lib/base.py:493
 msgid "Repository not found in the filesystem"
 msgstr ""
 
-#: kallithea/lib/base.py:516 kallithea/lib/helpers.py:622
+#: kallithea/lib/base.py:519 kallithea/lib/helpers.py:623
 msgid "Changeset not found"
 msgstr "未找到修订集"
 
@@ -1071,132 +1067,132 @@
 
 #: kallithea/lib/diffs.py:82
 msgid "Changeset was too big and was cut off, use diff menu to display this diff"
-msgstr "修订集因过大而被截断,可查看原始修订集作为替代"
+msgstr "修订集过大并已被截断,使用差异菜单查看此差异"
 
 #: kallithea/lib/diffs.py:92
 msgid "No changes detected"
 msgstr "未发现差异"
 
-#: kallithea/lib/helpers.py:609
+#: kallithea/lib/helpers.py:610
 #, python-format
 msgid "Deleted branch: %s"
 msgstr "已经删除分支%s"
 
-#: kallithea/lib/helpers.py:611
+#: kallithea/lib/helpers.py:612
 #, python-format
 msgid "Created tag: %s"
 msgstr "创建标签%s"
 
-#: kallithea/lib/helpers.py:671
+#: kallithea/lib/helpers.py:672
 #, python-format
 msgid "Show all combined changesets %s->%s"
-msgstr "显示合并的修订集%s->%s"
-
-#: kallithea/lib/helpers.py:677
+msgstr "显示所有合并的修订集 %s->%s"
+
+#: kallithea/lib/helpers.py:678
 #, fuzzy
 msgid "Compare view"
 msgstr "比较显示"
 
-#: kallithea/lib/helpers.py:696
+#: kallithea/lib/helpers.py:697
 msgid "and"
 msgstr "还有"
 
-#: kallithea/lib/helpers.py:697
+#: kallithea/lib/helpers.py:698
 #, python-format
 msgid "%s more"
 msgstr "%s个"
 
-#: kallithea/lib/helpers.py:698 kallithea/templates/changelog/changelog.html:44
+#: kallithea/lib/helpers.py:699 kallithea/templates/changelog/changelog.html:44
 msgid "revisions"
 msgstr "修订"
 
-#: kallithea/lib/helpers.py:722
+#: kallithea/lib/helpers.py:723
 #, fuzzy, python-format
 msgid "Fork name %s"
 msgstr "复刻名称%s"
 
-#: kallithea/lib/helpers.py:742
+#: kallithea/lib/helpers.py:743
 #, fuzzy, python-format
 msgid "Pull request %s"
 msgstr "拉取请求#%s"
 
-#: kallithea/lib/helpers.py:752
+#: kallithea/lib/helpers.py:753
 msgid "[deleted] repository"
 msgstr "[删除]版本库"
 
-#: kallithea/lib/helpers.py:754 kallithea/lib/helpers.py:766
+#: kallithea/lib/helpers.py:755 kallithea/lib/helpers.py:767
 msgid "[created] repository"
 msgstr "[创建]版本库"
 
-#: kallithea/lib/helpers.py:756
+#: kallithea/lib/helpers.py:757
 msgid "[created] repository as fork"
 msgstr "[创建]复刻版本库"
 
-#: kallithea/lib/helpers.py:758 kallithea/lib/helpers.py:768
+#: kallithea/lib/helpers.py:759 kallithea/lib/helpers.py:769
 msgid "[forked] repository"
 msgstr "[复刻]版本库"
 
-#: kallithea/lib/helpers.py:760 kallithea/lib/helpers.py:770
+#: kallithea/lib/helpers.py:761 kallithea/lib/helpers.py:771
 msgid "[updated] repository"
 msgstr "[更新]版本库"
 
-#: kallithea/lib/helpers.py:762
+#: kallithea/lib/helpers.py:763
 msgid "[downloaded] archive from repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:764
+#: kallithea/lib/helpers.py:765
 msgid "[delete] repository"
 msgstr "[删除]版本库"
 
-#: kallithea/lib/helpers.py:772
+#: kallithea/lib/helpers.py:773
 msgid "[created] user"
 msgstr "[创建]用户"
 
-#: kallithea/lib/helpers.py:774
+#: kallithea/lib/helpers.py:775
 msgid "[updated] user"
 msgstr "[更新]用户"
 
-#: kallithea/lib/helpers.py:776
+#: kallithea/lib/helpers.py:777
 msgid "[created] user group"
 msgstr ""
 
-#: kallithea/lib/helpers.py:778
+#: kallithea/lib/helpers.py:779
 msgid "[updated] user group"
 msgstr ""
 
-#: kallithea/lib/helpers.py:780
+#: kallithea/lib/helpers.py:781
 msgid "[commented] on revision in repository"
 msgstr "[评论]了版本库中的修订"
 
-#: kallithea/lib/helpers.py:782
+#: kallithea/lib/helpers.py:783
 msgid "[commented] on pull request for"
 msgstr "[评论]拉取请求"
 
-#: kallithea/lib/helpers.py:784
+#: kallithea/lib/helpers.py:785
 msgid "[closed] pull request for"
 msgstr "[关闭] 拉取请求"
 
-#: kallithea/lib/helpers.py:786
+#: kallithea/lib/helpers.py:787
 msgid "[pushed] into"
 msgstr "[推送]到"
 
-#: kallithea/lib/helpers.py:788
+#: kallithea/lib/helpers.py:789
 msgid "[committed via Kallithea] into repository"
 msgstr "[通过Kallithea提交]到版本库"
 
-#: kallithea/lib/helpers.py:790
+#: kallithea/lib/helpers.py:791
 msgid "[pulled from remote] into repository"
 msgstr "[远程拉取]到版本库"
 
-#: kallithea/lib/helpers.py:792
+#: kallithea/lib/helpers.py:793
 msgid "[pulled] from"
 msgstr "[拉取]自"
 
-#: kallithea/lib/helpers.py:794
+#: kallithea/lib/helpers.py:795
 msgid "[started following] repository"
 msgstr "[开始关注]版本库"
 
-#: kallithea/lib/helpers.py:796
+#: kallithea/lib/helpers.py:797
 msgid "[stopped following] repository"
 msgstr "[停止关注]版本库"
 
@@ -1206,8 +1202,8 @@
 msgstr " 还有%s个"
 
 #: kallithea/lib/helpers.py:1128
-#: kallithea/templates/compare/compare_diff.html:65
-#: kallithea/templates/pullrequests/pullrequest_show.html:326
+#: kallithea/templates/compare/compare_diff.html:71
+#: kallithea/templates/pullrequests/pullrequest_show.html:337
 msgid "No files"
 msgstr "无文件"
 
@@ -1231,7 +1227,7 @@
 msgid "chmod"
 msgstr ""
 
-#: kallithea/lib/helpers.py:1444
+#: kallithea/lib/helpers.py:1469
 #, python-format
 msgid ""
 "%s repository is not mapped to db perhaps it was created or renamed from "
@@ -1239,63 +1235,63 @@
 "repositories"
 msgstr "版本库%s没有映射到数据库,可能是从文件系统创建或者重命名,请重启Kallithea以重新扫描版本库"
 
-#: kallithea/lib/utils2.py:415
+#: kallithea/lib/utils2.py:434
 #, python-format
 msgid "%d year"
 msgid_plural "%d years"
 msgstr[0] "%d年"
 
-#: kallithea/lib/utils2.py:416
+#: kallithea/lib/utils2.py:435
 #, python-format
 msgid "%d month"
 msgid_plural "%d months"
 msgstr[0] "%d月"
 
-#: kallithea/lib/utils2.py:417
+#: kallithea/lib/utils2.py:436
 #, python-format
 msgid "%d day"
 msgid_plural "%d days"
 msgstr[0] "%d天"
 
-#: kallithea/lib/utils2.py:418
+#: kallithea/lib/utils2.py:437
 #, python-format
 msgid "%d hour"
 msgid_plural "%d hours"
 msgstr[0] "%d时"
 
-#: kallithea/lib/utils2.py:419
+#: kallithea/lib/utils2.py:438
 #, python-format
 msgid "%d minute"
 msgid_plural "%d minutes"
 msgstr[0] "%d分"
 
-#: kallithea/lib/utils2.py:420
+#: kallithea/lib/utils2.py:439
 #, python-format
 msgid "%d second"
 msgid_plural "%d seconds"
 msgstr[0] "%d秒"
 
-#: kallithea/lib/utils2.py:436
+#: kallithea/lib/utils2.py:455
 #, python-format
 msgid "in %s"
 msgstr "%s"
 
-#: kallithea/lib/utils2.py:438
+#: kallithea/lib/utils2.py:457
 #, python-format
 msgid "%s ago"
 msgstr "%s前"
 
-#: kallithea/lib/utils2.py:440
+#: kallithea/lib/utils2.py:459
 #, python-format
 msgid "in %s and %s"
 msgstr "%s零%s"
 
-#: kallithea/lib/utils2.py:443
+#: kallithea/lib/utils2.py:462
 #, python-format
 msgid "%s and %s ago"
 msgstr "%s零%s前"
 
-#: kallithea/lib/utils2.py:446
+#: kallithea/lib/utils2.py:465
 msgid "just now"
 msgstr "刚才"
 
@@ -1394,7 +1390,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1531
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1570
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1620
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1665
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1669
 msgid "Kallithea Administrator"
 msgstr "Kallithea 管理员"
 
@@ -1505,7 +1501,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2063
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2102
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2155
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2229
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2237
 msgid "Approved"
 msgstr "已批准"
 
@@ -1520,7 +1516,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2064
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2103
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2156
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2230
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2238
 msgid "Rejected"
 msgstr "驳回"
 
@@ -1547,7 +1543,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1379
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1418
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1471
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1518
 msgid "top level"
 msgstr ""
 
@@ -1694,7 +1690,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1560
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1599
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1651
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1697
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1701
 msgid "Registration disabled"
 msgstr ""
 
@@ -1721,12 +1717,12 @@
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1645
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1691
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1695
 msgid "Repository creation enabled with write permission to a repository group"
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1646
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1692
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1696
 msgid "Repository creation disabled with write permission to a repository group"
 msgstr ""
 
@@ -1735,110 +1731,110 @@
 msgid "on line %s"
 msgstr "在%s行"
 
-#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:169
+#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:170
 msgid "[Mention]"
 msgstr "[提及]"
 
-#: kallithea/model/db.py:1667
+#: kallithea/model/db.py:1671
 msgid "Default user has no access to new repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1668
+#: kallithea/model/db.py:1672
 #, fuzzy
 msgid "Default user has read access to new repositories"
 msgstr "未授权的资源访问"
 
-#: kallithea/model/db.py:1669
+#: kallithea/model/db.py:1673
 #, fuzzy
 msgid "Default user has write access to new repositories"
 msgstr "未授权的资源访问"
 
-#: kallithea/model/db.py:1670
+#: kallithea/model/db.py:1674
 msgid "Default user has admin access to new repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1672
+#: kallithea/model/db.py:1676
 msgid "Default user has no access to new repository groups"
 msgstr ""
 
-#: kallithea/model/db.py:1673
-msgid "Default user has read access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1674
-msgid "Default user has write access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1675
-msgid "Default user has admin access to new repository groups"
-msgstr ""
-
 #: kallithea/model/db.py:1677
-msgid "Default user has no access to new user groups"
+msgid "Default user has read access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1678
-msgid "Default user has read access to new user groups"
+msgid "Default user has write access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1679
-msgid "Default user has write access to new user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1680
-msgid "Default user has admin access to new user groups"
+msgid "Default user has admin access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1681
+msgid "Default user has no access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1682
-#, fuzzy
-msgid "Only admins can create repository groups"
-msgstr "没有在该版本库组中创建版本库的权限"
+msgid "Default user has read access to new user groups"
+msgstr ""
 
 #: kallithea/model/db.py:1683
-#, fuzzy
-msgid "Non-admins can create repository groups"
-msgstr "没有在该版本库组中创建版本库的权限"
-
-#: kallithea/model/db.py:1685
-msgid "Only admins can create user groups"
+msgid "Default user has write access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1684
+msgid "Default user has admin access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1686
-msgid "Non-admins can create user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1688
-msgid "Only admins can create top level repositories"
-msgstr ""
+#, fuzzy
+msgid "Only admins can create repository groups"
+msgstr "没有在该版本库组中创建版本库的权限"
+
+#: kallithea/model/db.py:1687
+#, fuzzy
+msgid "Non-admins can create repository groups"
+msgstr "没有在该版本库组中创建版本库的权限"
 
 #: kallithea/model/db.py:1689
+msgid "Only admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1690
+msgid "Non-admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1692
+msgid "Only admins can create top level repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1693
 msgid "Non-admins can create top level repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1694
+#: kallithea/model/db.py:1698
 #, fuzzy
 msgid "Only admins can fork repositories"
 msgstr "创建版本库"
 
-#: kallithea/model/db.py:1695
+#: kallithea/model/db.py:1699
 #, fuzzy
-msgid "Non-admins can can fork repositories"
+msgid "Non-admins can fork repositories"
 msgstr "创建版本库"
 
-#: kallithea/model/db.py:1698
+#: kallithea/model/db.py:1702
 msgid "User registration with manual account activation"
 msgstr ""
 
-#: kallithea/model/db.py:1699
+#: kallithea/model/db.py:1703
 msgid "User registration with automatic account activation"
 msgstr ""
 
-#: kallithea/model/db.py:2228
+#: kallithea/model/db.py:2236
 #, fuzzy
 msgid "Not reviewed"
 msgstr "未检视"
 
-#: kallithea/model/db.py:2231
+#: kallithea/model/db.py:2239
 #, fuzzy
 msgid "Under review"
 msgstr "检视中"
@@ -1861,14 +1857,14 @@
 msgid "Enter %(min)i characters or more"
 msgstr "输入少于%(min)i个字符"
 
-#: kallithea/model/forms.py:160
+#: kallithea/model/forms.py:165
 msgid "Name must not contain only digits"
 msgstr ""
 
 #: kallithea/model/notification.py:254
 #, python-format
 msgid "%(user)s commented on changeset %(age)s"
-msgstr ""
+msgstr "%(user)s 已评论修订集在 %(age)s"
 
 #: kallithea/model/notification.py:255
 #, python-format
@@ -1898,7 +1894,7 @@
 #: kallithea/model/notification.py:266
 #, python-format
 msgid "%(user)s commented on changeset at %(when)s"
-msgstr ""
+msgstr "%(user)s 已评论修订集于 %(when)s"
 
 #: kallithea/model/notification.py:267
 #, python-format
@@ -1928,7 +1924,7 @@
 #: kallithea/model/notification.py:302
 #, python-format
 msgid "[Comment] %(repo_name)s changeset %(short_id)s on %(branch)s"
-msgstr ""
+msgstr "[评论] %(repo_name)s 修订集 %(short_id)s 在 %(branch)s"
 
 #: kallithea/model/notification.py:305
 #, fuzzy, python-format
@@ -1942,7 +1938,6 @@
 
 #: kallithea/model/notification.py:308
 #, fuzzy, python-format
-#| msgid "[commented] on pull request for"
 msgid "[Comment] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s"
 msgstr "[评论]拉取请求"
 
@@ -1956,7 +1951,7 @@
 msgid "%(user)s wants you to review pull request %(pr_nice_id)s: %(pr_title)s"
 msgstr ""
 
-#: kallithea/model/scm.py:812
+#: kallithea/model/scm.py:708
 msgid "latest tip"
 msgstr "最新tip版本"
 
@@ -1990,17 +1985,16 @@
 "owners or remove those user groups: %s"
 msgstr "由于用户 \"%s\" 拥有版本库%s因而无法删除,请修改版本库所有者或删除版本库。%s"
 
-#: kallithea/model/user.py:360
+#: kallithea/model/user.py:368
 msgid "Password reset link"
 msgstr ""
 
-#: kallithea/model/user.py:408
+#: kallithea/model/user.py:418
 #, fuzzy
-#| msgid "Password confirmation"
 msgid "Password reset notification"
 msgstr "确认密码"
 
-#: kallithea/model/user.py:409
+#: kallithea/model/user.py:419
 #, python-format
 msgid ""
 "The password to your account %s has been changed using password reset "
@@ -2011,170 +2005,170 @@
 msgid "Value cannot be an empty list"
 msgstr "值不能为空"
 
-#: kallithea/model/validators.py:95
+#: kallithea/model/validators.py:96
 #, python-format
 msgid "Username \"%(username)s\" already exists"
 msgstr "用户名称%(username)s已经存在"
 
-#: kallithea/model/validators.py:97
+#: kallithea/model/validators.py:98
 #, fuzzy, python-format
 msgid "Username \"%(username)s\" cannot be used"
 msgstr "用户名称 %(username)s 无效"
 
-#: kallithea/model/validators.py:99
+#: kallithea/model/validators.py:100
 msgid ""
 "Username may only contain alphanumeric characters underscores, periods or"
 " dashes and must begin with an alphanumeric character or underscore"
 msgstr ""
 
-#: kallithea/model/validators.py:126
+#: kallithea/model/validators.py:127
 msgid "The input is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:133
+#: kallithea/model/validators.py:134
 #, python-format
 msgid "Username %(username)s is not valid"
 msgstr "用户名称 %(username)s 无效"
 
-#: kallithea/model/validators.py:152
+#: kallithea/model/validators.py:154
 msgid "Invalid user group name"
 msgstr ""
 
-#: kallithea/model/validators.py:153
-#, python-format
-msgid "User group \"%(usergroup)s\" already exists"
-msgstr ""
-
 #: kallithea/model/validators.py:155
+#, python-format
+msgid "User group \"%(usergroup)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:157
 msgid ""
 "user group name may only contain alphanumeric characters underscores, "
 "periods or dashes and must begin with alphanumeric character"
 msgstr ""
 
-#: kallithea/model/validators.py:193
+#: kallithea/model/validators.py:197
 msgid "Cannot assign this group as parent"
 msgstr "不能将这个组作为parent"
 
-#: kallithea/model/validators.py:194
+#: kallithea/model/validators.py:198
 #, python-format
 msgid "Group \"%(group_name)s\" already exists"
 msgstr "组 \"%(group_name)s\" 已经存在"
 
-#: kallithea/model/validators.py:196
+#: kallithea/model/validators.py:200
 #, python-format
 msgid "Repository with name \"%(group_name)s\" already exists"
 msgstr "已经存在名为 \"%(group_name)s\" 的版本库"
 
-#: kallithea/model/validators.py:254
+#: kallithea/model/validators.py:258
 msgid "Invalid characters (non-ascii) in password"
 msgstr "密码含有无效(非ASCII)字符"
 
-#: kallithea/model/validators.py:269
+#: kallithea/model/validators.py:273
 msgid "Invalid old password"
 msgstr ""
 
-#: kallithea/model/validators.py:285
+#: kallithea/model/validators.py:289
 msgid "Passwords do not match"
 msgstr "密码不符"
 
-#: kallithea/model/validators.py:300
+#: kallithea/model/validators.py:304
 #, fuzzy
 msgid "Invalid username or password"
 msgstr "无效密码"
 
-#: kallithea/model/validators.py:331
+#: kallithea/model/validators.py:335
 msgid "Token mismatch"
 msgstr "令牌不匹配"
 
-#: kallithea/model/validators.py:345
+#: kallithea/model/validators.py:351
 #, fuzzy, python-format
 msgid "Repository name %(repo)s is not allowed"
 msgstr "版本库名称不能为%(repo)s"
 
-#: kallithea/model/validators.py:347
+#: kallithea/model/validators.py:353
 #, python-format
 msgid "Repository named %(repo)s already exists"
 msgstr "已经存在版本库%(repo)s"
 
-#: kallithea/model/validators.py:348
+#: kallithea/model/validators.py:354
 #, python-format
 msgid "Repository \"%(repo)s\" already exists in group \"%(group)s\""
 msgstr "版本库组 \"%(group)s\" 中已经存在版本库 \"%(repo)s\""
 
-#: kallithea/model/validators.py:350
+#: kallithea/model/validators.py:356
 #, python-format
 msgid "Repository group with name \"%(repo)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:465
+#: kallithea/model/validators.py:470
 #, fuzzy
 msgid "Invalid repository URL"
 msgstr "私有版本库"
 
-#: kallithea/model/validators.py:466
+#: kallithea/model/validators.py:471
 msgid ""
 "Invalid repository URL. It must be a valid http, https, ssh, svn+http or "
 "svn+https URL"
 msgstr ""
 
-#: kallithea/model/validators.py:489
+#: kallithea/model/validators.py:496
 msgid "Fork has to be the same type as parent"
 msgstr "复刻版本库必须和父版本库类型相同"
 
-#: kallithea/model/validators.py:504
+#: kallithea/model/validators.py:511
 msgid "You don't have permissions to create repository in this group"
 msgstr "没有在该版本库组中创建版本库的权限"
 
-#: kallithea/model/validators.py:506
+#: kallithea/model/validators.py:513
 msgid "no permission to create repository in root location"
 msgstr ""
 
-#: kallithea/model/validators.py:556
+#: kallithea/model/validators.py:563
 msgid "You don't have permissions to create a group in this location"
 msgstr ""
 
-#: kallithea/model/validators.py:597
+#: kallithea/model/validators.py:604
 msgid "This username or user group name is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:690
+#: kallithea/model/validators.py:697
 msgid "This is not a valid path"
 msgstr "不是一个合法的路径"
 
-#: kallithea/model/validators.py:705
+#: kallithea/model/validators.py:714
 #, fuzzy
 msgid "This email address is already in use"
 msgstr "该邮件地址已被使用"
 
-#: kallithea/model/validators.py:725
+#: kallithea/model/validators.py:734
 #, fuzzy, python-format
 msgid "Email address \"%(email)s\" not found"
 msgstr "邮件地址\"%(email)s\"不存在"
 
-#: kallithea/model/validators.py:762
+#: kallithea/model/validators.py:771
 msgid ""
 "The LDAP Login attribute of the CN must be specified - this is the name "
 "of the attribute that is equivalent to \"username\""
 msgstr "LDAP 登陆属性的 CN 必须指定 - 这个名字作为用户名"
 
-#: kallithea/model/validators.py:774
+#: kallithea/model/validators.py:783
 msgid "Please enter a valid IPv4 or IPv6 address"
 msgstr ""
 
-#: kallithea/model/validators.py:775
+#: kallithea/model/validators.py:784
 #, python-format
 msgid "The network size (bits) must be within the range of 0-32 (not %(bits)r)"
 msgstr ""
 
-#: kallithea/model/validators.py:808
+#: kallithea/model/validators.py:817
 msgid "Key name can only consist of letters, underscore, dash or numbers"
 msgstr ""
 
-#: kallithea/model/validators.py:822
+#: kallithea/model/validators.py:831
 msgid "Filename cannot be inside a directory"
 msgstr ""
 
-#: kallithea/model/validators.py:838
+#: kallithea/model/validators.py:847
 #, python-format
 msgid "Plugins %(loaded)s and %(next_to_load)s both export the same name"
 msgstr ""
@@ -2301,7 +2295,7 @@
 #: kallithea/templates/admin/user_groups/user_groups.html:50
 #: kallithea/templates/pullrequests/pullrequest_data.html:16
 #: kallithea/templates/pullrequests/pullrequest_show.html:156
-#: kallithea/templates/pullrequests/pullrequest_show.html:233
+#: kallithea/templates/pullrequests/pullrequest_show.html:244
 #: kallithea/templates/summary/summary.html:134
 msgid "Owner"
 msgstr "所有者"
@@ -2344,12 +2338,12 @@
 #: kallithea/templates/journal/journal.html:292
 #: kallithea/templates/tags/tags.html:82
 msgid "Data error."
-msgstr "数据错误"
+msgstr "数据错误。"
 
 #: kallithea/templates/index_base.html:144
 #: kallithea/templates/admin/my_account/my_account_repos.html:61
 #: kallithea/templates/admin/my_account/my_account_watched.html:61
-#: kallithea/templates/base/base.html:140 kallithea/templates/base/root.html:47
+#: kallithea/templates/base/root.html:47
 #: kallithea/templates/bookmarks/bookmarks.html:83
 #: kallithea/templates/branches/branches.html:83
 #: kallithea/templates/journal/journal.html:202
@@ -2359,7 +2353,7 @@
 msgstr "载入中..."
 
 #: kallithea/templates/login.html:5 kallithea/templates/login.html:15
-#: kallithea/templates/base/base.html:326
+#: kallithea/templates/base/base.html:414
 msgid "Log In"
 msgstr "登录"
 
@@ -2374,7 +2368,7 @@
 #: kallithea/templates/admin/users/user_add.html:32
 #: kallithea/templates/admin/users/user_edit_profile.html:24
 #: kallithea/templates/admin/users/users.html:50
-#: kallithea/templates/base/base.html:302
+#: kallithea/templates/base/base.html:390
 #: kallithea/templates/pullrequests/pullrequest_show.html:166
 msgid "Username"
 msgstr "帐号"
@@ -2382,7 +2376,7 @@
 #: kallithea/templates/login.html:33 kallithea/templates/register.html:33
 #: kallithea/templates/admin/my_account/my_account.html:37
 #: kallithea/templates/admin/users/user_add.html:41
-#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:399
 msgid "Password"
 msgstr "密码"
 
@@ -2394,7 +2388,7 @@
 msgid "Forgot your password ?"
 msgstr "忘记了密码?"
 
-#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:322
+#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:410
 msgid "Don't have an account ?"
 msgstr "还没有帐号?"
 
@@ -2435,8 +2429,6 @@
 
 #: kallithea/templates/password_reset.html:47
 #, fuzzy
-#| msgid "" "Password reset link will be sent to the email address matching
-#| your " "username."
 msgid ""
 "A password reset link will be sent to the specified email address if it "
 "is registered in the system."
@@ -2459,13 +2451,11 @@
 
 #: kallithea/templates/password_reset_confirmation.html:39
 #, fuzzy
-#| msgid "New password"
 msgid "New Password"
 msgstr "新密码"
 
 #: kallithea/templates/password_reset_confirmation.html:48
 #, fuzzy
-#| msgid "New password"
 msgid "Confirm New Password"
 msgstr "新密码"
 
@@ -2524,10 +2514,6 @@
 msgid "There are no branches yet"
 msgstr "没有任何分支"
 
-#: kallithea/templates/switch_to_list.html:16
-msgid "Closed Branches"
-msgstr ""
-
 #: kallithea/templates/switch_to_list.html:32
 #: kallithea/templates/tags/tags_data.html:44
 msgid "There are no tags yet"
@@ -2686,7 +2672,7 @@
 #: kallithea/templates/admin/defaults/defaults.html:57
 #: kallithea/templates/admin/repos/repo_edit_settings.html:88
 msgid "Enable statistics window on summary page."
-msgstr "启用概况页的统计窗口"
+msgstr "启用概况页面上的统计窗口。"
 
 #: kallithea/templates/admin/defaults/defaults.html:63
 #: kallithea/templates/admin/repos/repo_edit_settings.html:93
@@ -2696,7 +2682,7 @@
 #: kallithea/templates/admin/defaults/defaults.html:67
 #: kallithea/templates/admin/repos/repo_edit_settings.html:97
 msgid "Enable download menu on summary page."
-msgstr "启用概况页的下载菜单"
+msgstr "启用概况页面上的下载菜单。"
 
 #: kallithea/templates/admin/defaults/defaults.html:73
 #: kallithea/templates/admin/repo_groups/repo_group_edit_settings.html:34
@@ -2707,7 +2693,7 @@
 #: kallithea/templates/admin/defaults/defaults.html:77
 #: kallithea/templates/admin/repos/repo_edit_settings.html:106
 msgid "Enable lock-by-pulling on repository."
-msgstr "启用版本库的拉取锁定"
+msgstr "启用版本库的拉取锁定。"
 
 #: kallithea/templates/admin/gists/edit.html:5
 #: kallithea/templates/admin/gists/edit.html:18
@@ -2757,12 +2743,12 @@
 msgid "Never"
 msgstr "检视者"
 
-#: kallithea/templates/admin/gists/edit.html:145
+#: kallithea/templates/admin/gists/edit.html:146
 msgid "Update Gist"
 msgstr ""
 
-#: kallithea/templates/admin/gists/edit.html:146
-#: kallithea/templates/changeset/changeset_file_comment.html:81
+#: kallithea/templates/admin/gists/edit.html:147
+#: kallithea/templates/changeset/changeset_file_comment.html:105
 msgid "Cancel"
 msgstr ""
 
@@ -2785,7 +2771,7 @@
 
 #: kallithea/templates/admin/gists/index.html:37
 #: kallithea/templates/admin/gists/show.html:25
-#: kallithea/templates/base/base.html:237
+#: kallithea/templates/base/base.html:321
 msgid "Create New Gist"
 msgstr ""
 
@@ -2873,7 +2859,8 @@
 #: kallithea/templates/admin/settings/settings_hooks.html:36
 #: kallithea/templates/admin/users/user_edit_emails.html:19
 #: kallithea/templates/admin/users/user_edit_ips.html:22
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+#: kallithea/templates/changeset/changeset_file_comment.html:95
 #: kallithea/templates/data_table/_dt_elements.html:129
 #: kallithea/templates/data_table/_dt_elements.html:157
 #: kallithea/templates/data_table/_dt_elements.html:173
@@ -2893,8 +2880,6 @@
 #: kallithea/templates/base/perms_summary.html:43
 #: kallithea/templates/base/perms_summary.html:79
 #: kallithea/templates/base/perms_summary.html:81
-#: kallithea/templates/changeset/changeset_file_comment.html:83
-#: kallithea/templates/changeset/changeset_file_comment.html:192
 #: kallithea/templates/data_table/_dt_elements.html:122
 #: kallithea/templates/data_table/_dt_elements.html:123
 #: kallithea/templates/data_table/_dt_elements.html:150
@@ -2921,13 +2906,12 @@
 msgstr ""
 
 #: kallithea/templates/admin/gists/show.html:86
-#: kallithea/templates/files/files_source.html:73
 msgid "Show as raw"
 msgstr ""
 
 #: kallithea/templates/admin/my_account/my_account.html:5
 #: kallithea/templates/admin/my_account/my_account.html:9
-#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:431
 msgid "My Account"
 msgstr "我的账户"
 
@@ -3065,7 +3049,7 @@
 #: kallithea/templates/admin/my_account/my_account_profile.html:12
 #: kallithea/templates/admin/users/user_edit_profile.html:9
 msgid "Using"
-msgstr "使用中"
+msgstr "使用"
 
 #: kallithea/templates/admin/my_account/my_account_profile.html:14
 #: kallithea/templates/admin/users/user_edit_profile.html:11
@@ -3095,7 +3079,7 @@
 #: kallithea/templates/journal/journal.html:291
 #: kallithea/templates/tags/tags.html:81
 msgid "No records found."
-msgstr "没有找到记录"
+msgstr "没有找到记录。"
 
 #: kallithea/templates/admin/my_account/my_account_watched.html:1
 #, fuzzy
@@ -3116,7 +3100,7 @@
 msgstr "评论"
 
 #: kallithea/templates/admin/notifications/notifications.html:26
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 msgid "Pull Requests"
 msgstr ""
 
@@ -3136,7 +3120,7 @@
 msgstr "显示通知"
 
 #: kallithea/templates/admin/notifications/show_notification.html:9
-#: kallithea/templates/base/base.html:342
+#: kallithea/templates/base/base.html:430
 msgid "Notifications"
 msgstr "通知"
 
@@ -3338,7 +3322,7 @@
 #: kallithea/templates/admin/repos/repo_edit.html:40
 #: kallithea/templates/admin/settings/settings.html:11
 #: kallithea/templates/admin/user_groups/user_group_edit.html:29
-#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:151
+#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:148
 #: kallithea/templates/data_table/_dt_elements.html:45
 #: kallithea/templates/data_table/_dt_elements.html:49
 msgid "Settings"
@@ -3498,11 +3482,11 @@
 #: kallithea/templates/admin/repos/repo_edit_settings.html:39
 #: kallithea/templates/forks/fork.html:52
 msgid "Optionally select a group to put this repository into."
-msgstr "可选的,选择一个组将版本库放到其中"
+msgstr "可选的选择一个组将版本库放到其中。"
 
 #: kallithea/templates/admin/repos/repo_add_base.html:59
 msgid "Type of repository to create."
-msgstr "要创建的版本库类型"
+msgstr "要创建的版本库类型。"
 
 #: kallithea/templates/admin/repos/repo_add_base.html:64
 #: kallithea/templates/admin/repos/repo_edit_settings.html:44
@@ -3614,6 +3598,11 @@
 msgid "Unlock Repository"
 msgstr "公共版本库"
 
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:56
+#, python-format
+msgid "Locked by %s on %s"
+msgstr ""
+
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:60
 #, fuzzy
 msgid "Confirm to lock repository."
@@ -3673,11 +3662,6 @@
 msgid "Invalidate Repository Cache"
 msgstr "清除版本库缓存"
 
-#: kallithea/templates/admin/repos/repo_edit_caches.html:4
-#, fuzzy
-msgid "Confirm to invalidate repository cache."
-msgstr "确认清除版本库缓存"
-
 #: kallithea/templates/admin/repos/repo_edit_caches.html:7
 #, fuzzy
 msgid ""
@@ -3812,7 +3796,7 @@
 
 #: kallithea/templates/admin/repos/repo_edit_settings.html:58
 msgid "Change owner of this repository."
-msgstr "修改这个版本库的所有者"
+msgstr "修改这个版本库的所有者。"
 
 #: kallithea/templates/admin/repos/repo_edit_statistics.html:6
 msgid "Processed commits"
@@ -4433,22 +4417,18 @@
 msgid "Files"
 msgstr "浏览"
 
-#: kallithea/templates/base/base.html:138
-msgid "Switch To"
-msgstr ""
-
-#: kallithea/templates/base/base.html:145
-#: kallithea/templates/base/base.html:147
+#: kallithea/templates/base/base.html:142
+#: kallithea/templates/base/base.html:144
 msgid "Options"
 msgstr "选项"
 
-#: kallithea/templates/base/base.html:155
+#: kallithea/templates/base/base.html:152
 #: kallithea/templates/forks/forks_data.html:21
 #, fuzzy
 msgid "Compare Fork"
 msgstr "比较复刻"
 
-#: kallithea/templates/base/base.html:157
+#: kallithea/templates/base/base.html:154
 #: kallithea/templates/bookmarks/bookmarks.html:56
 #: kallithea/templates/bookmarks/bookmarks_data.html:13
 #: kallithea/templates/branches/branches.html:56
@@ -4458,113 +4438,118 @@
 msgid "Compare"
 msgstr "比较显示"
 
-#: kallithea/templates/base/base.html:159
-#: kallithea/templates/base/base.html:247
+#: kallithea/templates/base/base.html:156
+#: kallithea/templates/base/base.html:331
 #: kallithea/templates/search/search.html:14
 #: kallithea/templates/search/search.html:54
 msgid "Search"
 msgstr "搜索"
 
-#: kallithea/templates/base/base.html:163
+#: kallithea/templates/base/base.html:160
 msgid "Unlock"
 msgstr ""
 
-#: kallithea/templates/base/base.html:165
+#: kallithea/templates/base/base.html:162
 msgid "Lock"
 msgstr ""
 
-#: kallithea/templates/base/base.html:173
+#: kallithea/templates/base/base.html:170
 msgid "Follow"
 msgstr ""
 
+#: kallithea/templates/base/base.html:171
+msgid "Unfollow"
+msgstr ""
+
 #: kallithea/templates/base/base.html:174
-msgid "Unfollow"
-msgstr ""
-
-#: kallithea/templates/base/base.html:177
 #: kallithea/templates/data_table/_dt_elements.html:37
 #: kallithea/templates/data_table/_dt_elements.html:41
 #: kallithea/templates/forks/fork.html:9
 msgid "Fork"
 msgstr "复刻"
 
-#: kallithea/templates/base/base.html:178
+#: kallithea/templates/base/base.html:175
 #: kallithea/templates/pullrequests/pullrequest.html:88
 msgid "Create Pull Request"
 msgstr ""
 
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 #, python-format
 msgid "Show Pull Requests for %s"
 msgstr ""
 
-#: kallithea/templates/base/base.html:221
+#: kallithea/templates/base/base.html:193
+msgid "Switch To"
+msgstr ""
+
+#: kallithea/templates/base/base.html:203
+#: kallithea/templates/base/base.html:485
+msgid "No matches found"
+msgstr ""
+
+#: kallithea/templates/base/base.html:305
 msgid "Show recent activity"
 msgstr ""
 
-#: kallithea/templates/base/base.html:227
-#: kallithea/templates/base/base.html:228
+#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:312
 msgid "Public journal"
 msgstr "公共日志"
 
-#: kallithea/templates/base/base.html:233
+#: kallithea/templates/base/base.html:317
 msgid "Show public gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:234
+#: kallithea/templates/base/base.html:318
 msgid "Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:238
+#: kallithea/templates/base/base.html:322
 msgid "All Public Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:240
+#: kallithea/templates/base/base.html:324
 msgid "My Public Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:241
+#: kallithea/templates/base/base.html:325
 msgid "My Private Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:246
+#: kallithea/templates/base/base.html:330
 msgid "Search in repositories"
 msgstr ""
 
-#: kallithea/templates/base/base.html:269
-#: kallithea/templates/base/base.html:270
+#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:354
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:6
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:10
 #, fuzzy
 msgid "My Pull Requests"
 msgstr "拉取请求"
 
-#: kallithea/templates/base/base.html:289
+#: kallithea/templates/base/base.html:377
 msgid "Not Logged In"
 msgstr ""
 
-#: kallithea/templates/base/base.html:296
+#: kallithea/templates/base/base.html:384
 #, fuzzy
 msgid "Login to Your Account"
 msgstr "登录"
 
-#: kallithea/templates/base/base.html:319
+#: kallithea/templates/base/base.html:407
 msgid "Forgot password ?"
 msgstr "忘记密码?"
 
-#: kallithea/templates/base/base.html:346
+#: kallithea/templates/base/base.html:434
 msgid "Log Out"
 msgstr "退出"
 
-#: kallithea/templates/base/base.html:395
-msgid "No matches found"
-msgstr ""
-
-#: kallithea/templates/base/base.html:524
+#: kallithea/templates/base/base.html:615
 msgid "Keyboard shortcuts"
 msgstr ""
 
-#: kallithea/templates/base/base.html:533
+#: kallithea/templates/base/base.html:624
 msgid "Site-wide shortcuts"
 msgstr ""
 
@@ -4667,7 +4652,6 @@
 
 #: kallithea/templates/base/root.html:31
 #, fuzzy
-#| msgid "on pull request"
 msgid "Open New Pull Request from {0}"
 msgstr "[评论]拉取请求"
 
@@ -4676,10 +4660,8 @@
 msgstr ""
 
 #: kallithea/templates/base/root.html:33
-#, fuzzy
-#| msgid "Show Selected Changeset __S"
 msgid "Show Selected Changesets {0} &rarr; {1}"
-msgstr "显示合并的修订集%s->%s"
+msgstr "显示选中的修订集 {0} &rarr; {1}"
 
 #: kallithea/templates/base/root.html:34
 #, fuzzy
@@ -4688,6 +4670,7 @@
 
 #: kallithea/templates/base/root.html:35
 #: kallithea/templates/changeset/diff_block.html:8
+#: kallithea/templates/changeset/diff_block.html:21
 #, fuzzy
 msgid "Collapse Diff"
 msgstr "文件差异"
@@ -4714,9 +4697,8 @@
 msgstr ""
 
 #: kallithea/templates/base/root.html:42
-#, fuzzy
 msgid "Specify changeset"
-msgstr "%s修订集"
+msgstr "指定修订集"
 
 #: kallithea/templates/bookmarks/bookmarks.html:5
 #, python-format
@@ -4800,51 +4782,56 @@
 #: kallithea/templates/changelog/changelog_summary_data.html:20
 #, python-format
 msgid ""
-"Changeset status: %s\n"
+"Changeset status: %s by %s\n"
 "Click to open associated pull request %s"
 msgstr ""
+"修订集状态:%s 由 %s\n"
+"点击打开相关联的拉取请求 %s"
 
 #: kallithea/templates/changelog/changelog.html:96
-#: kallithea/templates/compare/compare_cs.html:24
-#, python-format
-msgid "Changeset status: %s"
-msgstr ""
-
-#: kallithea/templates/changelog/changelog.html:115
+#: kallithea/templates/changelog/changelog_summary_data.html:24
+#, python-format
+#| msgid "Changeset status"
+msgid "Changeset status: %s by %s"
+msgstr "修订集状态:%s 由 %s"
+
+#: kallithea/templates/changelog/changelog.html:116
 #: kallithea/templates/compare/compare_cs.html:63
 msgid "Expand commit message"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:124
+#: kallithea/templates/changelog/changelog.html:125
 #: kallithea/templates/compare/compare_cs.html:30
 msgid "Changeset has comments"
-msgstr ""
-
-#: kallithea/templates/changelog/changelog.html:134
-#: kallithea/templates/changelog/changelog_summary_data.html:54
+msgstr "修订集有评论"
+
+#: kallithea/templates/changelog/changelog.html:135
+#: kallithea/templates/changelog/changelog_summary_data.html:57
 #: kallithea/templates/changeset/changeset.html:94
 #: kallithea/templates/changeset/changeset_range.html:92
 #, python-format
 msgid "Bookmark %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:140
-#: kallithea/templates/changelog/changelog_summary_data.html:60
+#: kallithea/templates/changelog/changelog.html:141
+#: kallithea/templates/changelog/changelog_summary_data.html:63
 #: kallithea/templates/changeset/changeset.html:101
 #: kallithea/templates/changeset/changeset_range.html:98
+#: kallithea/templates/compare/compare_cs.html:69
+#: kallithea/templates/pullrequests/pullrequest_show.html:203
 #, python-format
 msgid "Tag %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:145
-#: kallithea/templates/changelog/changelog_summary_data.html:65
+#: kallithea/templates/changelog/changelog.html:146
+#: kallithea/templates/changelog/changelog_summary_data.html:68
 #: kallithea/templates/changeset/changeset.html:106
 #: kallithea/templates/changeset/changeset_range.html:102
 #, python-format
 msgid "Branch %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:310
+#: kallithea/templates/changelog/changelog.html:311
 msgid "There are no changes yet"
 msgstr "没有任何变更"
 
@@ -4860,7 +4847,7 @@
 
 #: kallithea/templates/changelog/changelog_details.html:6
 #: kallithea/templates/changeset/changeset.html:79
-#: kallithea/templates/changeset/diff_block.html:79
+#: kallithea/templates/changeset/diff_block.html:47
 msgid "Added"
 msgstr ""
 
@@ -4890,29 +4877,29 @@
 msgid "Refs"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:81
+#: kallithea/templates/changelog/changelog_summary_data.html:84
 msgid "Add or upload files directly via Kallithea"
 msgstr "通过Kallithea直接添加或者上传文件"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:84
+#: kallithea/templates/changelog/changelog_summary_data.html:87
 #: kallithea/templates/files/files_add.html:21
 #: kallithea/templates/files/files_ypjax.html:9
 msgid "Add New File"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:90
+#: kallithea/templates/changelog/changelog_summary_data.html:93
 #, fuzzy
 msgid "Push new repository"
 msgstr "推送新版本库"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:98
+#: kallithea/templates/changelog/changelog_summary_data.html:101
 msgid "Existing repository?"
 msgstr "已有版本库?"
 
 #: kallithea/templates/changeset/changeset.html:8
 #, python-format
 msgid "%s Changeset"
-msgstr "%s修订集"
+msgstr "%s 修订集"
 
 #: kallithea/templates/changeset/changeset.html:36
 msgid "Parent rev."
@@ -4923,13 +4910,13 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:50
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #: kallithea/templates/changeset/changeset_range.html:48
 msgid "Changeset status"
 msgstr "修订集状态"
 
 #: kallithea/templates/changeset/changeset.html:54
-#: kallithea/templates/changeset/diff_block.html:27
+#: kallithea/templates/changeset/diff_block.html:72
 #: kallithea/templates/files/diff_2way.html:49
 msgid "Raw diff"
 msgstr ""
@@ -4939,7 +4926,7 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:60
-#: kallithea/templates/changeset/diff_block.html:30
+#: kallithea/templates/changeset/diff_block.html:75
 #: kallithea/templates/files/diff_2way.html:52
 msgid "Download diff"
 msgstr ""
@@ -4970,16 +4957,16 @@
 msgstr "创建于"
 
 #: kallithea/templates/changeset/changeset.html:166
-#: kallithea/templates/compare/compare_diff.html:54
-#: kallithea/templates/pullrequests/pullrequest_show.html:318
+#: kallithea/templates/compare/compare_diff.html:60
+#: kallithea/templates/pullrequests/pullrequest_show.html:329
 #, python-format
 msgid "%s file changed"
 msgid_plural "%s files changed"
 msgstr[0] "修改%s个文件"
 
 #: kallithea/templates/changeset/changeset.html:168
-#: kallithea/templates/compare/compare_diff.html:56
-#: kallithea/templates/pullrequests/pullrequest_show.html:320
+#: kallithea/templates/compare/compare_diff.html:62
+#: kallithea/templates/pullrequests/pullrequest_show.html:331
 #, python-format
 msgid "%s file changed with %s insertions and %s deletions"
 msgid_plural "%s files changed with %s insertions and %s deletions"
@@ -4987,13 +4974,13 @@
 
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Show full diff anyway"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset.html:247
-#: kallithea/templates/changeset/changeset.html:284
+#: kallithea/templates/changeset/changeset.html:231
+#: kallithea/templates/changeset/changeset.html:268
 #, fuzzy
 msgid "No revisions"
 msgstr "修订"
@@ -5009,186 +4996,174 @@
 msgstr "无文件"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:24
-#, fuzzy
 msgid "on this changeset"
-msgstr "无修订"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+msgstr "在此修订集"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:31
 #, fuzzy
 msgid "Delete comment?"
 msgstr "%d条评论"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #, fuzzy
 msgid "Status change"
 msgstr "文件已更改"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:59
-msgid "Commenting on line {1}."
+#, fuzzy
+msgid "Commenting on line."
 msgstr "在{1}行上评论"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:60
-#: kallithea/templates/changeset/changeset_file_comment.html:148
-#, python-format
-msgid "Comments parsed using %s syntax with %s support."
-msgstr "评论使用%s语法并支持%s"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:62
 #, fuzzy
-msgid "Use @username inside this text to notify another user"
+msgid ""
+"Comments are in plain text. Use @username inside this text to notify "
+"another user."
 msgstr "在文本中使用 @用户名 以发送通知到该Kallithea用户"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:72
-#: kallithea/templates/changeset/changeset_file_comment.html:184
-msgid "Comment preview"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:77
+#: kallithea/templates/changeset/changeset_file_comment.html:67
+msgid "Set changeset status"
+msgstr "设置修订集状态"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:69
+msgid "Vote for pull request status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:75
+#, fuzzy
+msgid "No change"
+msgstr "无变更"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:88
+#, fuzzy
+msgid "Finish pull request"
+msgstr "[评论]拉取请求"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:91
+#, fuzzy
+msgid "Close"
+msgstr "已关闭"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:103
 #, fuzzy
 msgid "Submitting ..."
 msgstr "提交中……"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:80
-#: kallithea/templates/changeset/changeset_file_comment.html:190
+#: kallithea/templates/changeset/changeset_file_comment.html:104
 msgid "Comment"
 msgstr "评论"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:82
-#: kallithea/templates/changeset/changeset_file_comment.html:191
-msgid "Preview"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "You need to be logged in to comment."
-msgstr "必须登录才能评论"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+msgstr "您必须登录才能评论。"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "Login now"
 msgstr "现在登陆"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:94
+#: kallithea/templates/changeset/changeset_file_comment.html:116
 msgid "Hide"
 msgstr "隐藏"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:106
+#: kallithea/templates/changeset/changeset_file_comment.html:128
 #, python-format
 msgid "%d comment"
 msgid_plural "%d comments"
 msgstr[0] "%d条评论"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:107
+#: kallithea/templates/changeset/changeset_file_comment.html:129
 #, fuzzy, python-format
 msgid "%d inline"
 msgid_plural "%d inline"
 msgstr[0] "(%d内嵌)"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:108
+#: kallithea/templates/changeset/changeset_file_comment.html:130
 #, fuzzy, python-format
 msgid "%d general"
 msgid_plural "%d general"
 msgstr[0] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:150
-#, fuzzy
-msgid "Use @username inside this text to notify another user."
-msgstr "在文本中使用 @用户名 以发送通知到该Kallithea用户"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:157
-msgid "Vote for pull request status"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:159
-#, fuzzy
-msgid "Set changeset status"
-msgstr "修订集状态"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:163
-#, fuzzy
-msgid "No change"
-msgstr "无变更"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:176
-#, fuzzy
-msgid "Close"
-msgstr "已关闭"
-
 #: kallithea/templates/changeset/changeset_range.html:5
 #, python-format
 msgid "%s Changesets"
-msgstr "%s修订集"
+msgstr "%s 修订集"
 
 #: kallithea/templates/changeset/changeset_range.html:56
 msgid "Files affected"
 msgstr "影响文件"
 
-#: kallithea/templates/changeset/diff_block.html:21
-#: kallithea/templates/files/diff_2way.html:43
-msgid "Show full diff for this file"
-msgstr ""
-
-#: kallithea/templates/changeset/diff_block.html:24
-#: kallithea/templates/changeset/diff_block.html:98
-#: kallithea/templates/files/diff_2way.html:46
-msgid "Show full side-by-side diff for this file"
-msgstr ""
-
-#: kallithea/templates/changeset/diff_block.html:38
-msgid "Show inline comments"
-msgstr ""
-
-#: kallithea/templates/changeset/diff_block.html:86
+#: kallithea/templates/changeset/diff_block.html:54
 #, fuzzy
 msgid "Deleted"
 msgstr "删除"
 
-#: kallithea/templates/changeset/diff_block.html:89
+#: kallithea/templates/changeset/diff_block.html:57
 #, fuzzy
 msgid "Renamed"
 msgstr "读"
 
+#: kallithea/templates/changeset/diff_block.html:66
+#: kallithea/templates/files/diff_2way.html:43
+msgid "Show full diff for this file"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:69
+#: kallithea/templates/files/diff_2way.html:46
+msgid "Show full side-by-side diff for this file"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:83
+msgid "Show inline comments"
+msgstr ""
+
 #: kallithea/templates/compare/compare_cs.html:4
 msgid "No changesets"
-msgstr "无修订"
+msgstr "无修订集"
 
 #: kallithea/templates/compare/compare_cs.html:8
 msgid "Ancestor"
 msgstr ""
 
+#: kallithea/templates/compare/compare_cs.html:24
+#, python-format
+msgid "Changeset status: %s"
+msgstr "修订集状态:%s"
+
 #: kallithea/templates/compare/compare_cs.html:44
 msgid "First (oldest) changeset in this list"
-msgstr ""
+msgstr "此列表中首个(最旧)修订集"
 
 #: kallithea/templates/compare/compare_cs.html:46
 msgid "Last (most recent) changeset in this list"
-msgstr ""
+msgstr "此列表中末个(最近)修订集"
 
 #: kallithea/templates/compare/compare_cs.html:48
 msgid "Position in this list of changesets"
-msgstr ""
-
-#: kallithea/templates/compare/compare_cs.html:76
+msgstr "修订集在此列表中的位置"
+
+#: kallithea/templates/compare/compare_cs.html:85
 msgid "Show merge diff"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:86
-#: kallithea/templates/pullrequests/pullrequest_show.html:310
+#: kallithea/templates/compare/compare_cs.html:95
+#: kallithea/templates/pullrequests/pullrequest_show.html:321
 msgid "Common ancestor"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:90
-msgid "No common ancestor found - repositories are unrelated"
-msgstr ""
-
-#: kallithea/templates/compare/compare_cs.html:98
-msgid "is"
-msgstr ""
-
 #: kallithea/templates/compare/compare_cs.html:99
-#, fuzzy, python-format
+msgid "No common ancestor found - repositories are unrelated"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:107
+msgid "is"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:108
+#, python-format
 msgid "%s changesets"
-msgstr "%s修订集"
-
-#: kallithea/templates/compare/compare_cs.html:100
+msgstr "%s 修订集"
+
+#: kallithea/templates/compare/compare_cs.html:109
 #, fuzzy
 msgid "behind"
 msgstr "重新索引"
@@ -5200,27 +5175,27 @@
 msgstr ""
 
 #: kallithea/templates/compare/compare_diff.html:13
-#: kallithea/templates/compare/compare_diff.html:35
+#: kallithea/templates/compare/compare_diff.html:41
 msgid "Compare Revisions"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:33
+#: kallithea/templates/compare/compare_diff.html:39
 msgid "Swap"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:42
+#: kallithea/templates/compare/compare_diff.html:48
 msgid "Compare revisions, branches, bookmarks, or tags."
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:47
-#: kallithea/templates/pullrequests/pullrequest_show.html:305
+#: kallithea/templates/compare/compare_diff.html:53
+#: kallithea/templates/pullrequests/pullrequest_show.html:316
 #, python-format
 msgid "Showing %s commit"
 msgid_plural "Showing %s commits"
 msgstr[0] "显示%s个提交"
 
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
 msgid "Show full diff"
 msgstr ""
 
@@ -5234,7 +5209,7 @@
 
 #: kallithea/templates/data_table/_dt_elements.html:98
 msgid "No changesets yet"
-msgstr "无修订"
+msgstr "尚无任何修订集"
 
 #: kallithea/templates/data_table/_dt_elements.html:105
 #: kallithea/templates/data_table/_dt_elements.html:107
@@ -5277,21 +5252,26 @@
 
 #: kallithea/templates/email_templates/password_reset.html:6
 #, fuzzy
-#| msgid "We received a request to create a new password for your account."
 msgid "We have received a request to reset the password for your account."
 msgstr "我们收到重置你用户密码的请求。"
 
-#: kallithea/templates/email_templates/password_reset.html:7
-msgid "To set a new password, click the following link"
+#: kallithea/templates/email_templates/password_reset.html:8
+msgid ""
+"This account is however managed outside this system and the password "
+"cannot be changed here."
 msgstr ""
 
 #: kallithea/templates/email_templates/password_reset.html:10
+msgid "To set a new password, click the following link"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:13
 msgid ""
 "Should you not be able to use the link above, please type the following "
 "code into the password reset form"
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:12
+#: kallithea/templates/email_templates/password_reset.html:16
 msgid ""
 "If it weren't you who requested the password reset, just disregard this "
 "message."
@@ -5375,8 +5355,9 @@
 msgstr ""
 
 #: kallithea/templates/files/files_add.html:53
-msgid "New file mode"
-msgstr ""
+#, fuzzy
+msgid "New file type"
+msgstr "未知包类型"
 
 #: kallithea/templates/files/files_add.html:64
 #: kallithea/templates/files/files_delete.html:43
@@ -5508,10 +5489,19 @@
 msgid "Binary file (%s)"
 msgstr "二进制文件(%s)"
 
-#: kallithea/templates/files/files_source.html:73
-msgid "File is too big to display"
+#: kallithea/templates/files/files_source.html:74
+#, fuzzy
+msgid "File is too big to display."
 msgstr "文件过大,不能显示"
 
+#: kallithea/templates/files/files_source.html:76
+msgid "Show full annotation anyway."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:78
+msgid "Show as raw."
+msgstr ""
+
 #: kallithea/templates/files/files_ypjax.html:5
 msgid "annotation"
 msgstr "显示注释"
@@ -5537,7 +5527,7 @@
 
 #: kallithea/templates/followers/followers_data.html:12
 msgid "Started following -"
-msgstr "开始关注 - "
+msgstr "开始关注 -"
 
 #: kallithea/templates/forks/fork.html:5
 #, python-format
@@ -5780,44 +5770,50 @@
 msgid "Current revision - no change"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:213
+#: kallithea/templates/pullrequests/pullrequest_show.html:215
+msgid ""
+"Pull requests do not change once created. Select a revision and save to "
+"replace this pull request with a new one."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:224
 #, fuzzy
 msgid "Pull Request Reviewers"
 msgstr "拉取请求检视人员"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:238
+#: kallithea/templates/pullrequests/pullrequest_show.html:249
 #, fuzzy
 msgid "Remove reviewer"
 msgstr "检视者"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:250
+#: kallithea/templates/pullrequests/pullrequest_show.html:261
 msgid "Type name of reviewer to add"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:258
+#: kallithea/templates/pullrequests/pullrequest_show.html:269
 #, fuzzy
 msgid "Potential Reviewers"
 msgstr "%d个检视者"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:261
+#: kallithea/templates/pullrequests/pullrequest_show.html:272
 msgid "Click to add the repository owner as reviewer:"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:284
+#: kallithea/templates/pullrequests/pullrequest_show.html:295
 msgid "Save Changes"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:285
+#: kallithea/templates/pullrequests/pullrequest_show.html:296
 #, fuzzy
-msgid "Save as New Pull Request"
+msgid "Save Updates as New Pull Request"
 msgstr "新建拉取请求"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:286
+#: kallithea/templates/pullrequests/pullrequest_show.html:297
 #, fuzzy
 msgid "Cancel Changes"
 msgstr "无变更"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#: kallithea/templates/pullrequests/pullrequest_show.html:307
 #, fuzzy
 msgid "Pull Request Content"
 msgstr "拉取请求"
@@ -5829,7 +5825,7 @@
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:11
 #, fuzzy, python-format
-msgid "Pull Requests from %s'"
+msgid "Pull Requests from '%s'"
 msgstr "拉取请求#%s"
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:13
@@ -5934,7 +5930,7 @@
 
 #: kallithea/templates/summary/statistics.html:39
 msgid "Stats gathered: "
-msgstr "已收集的统计:"
+msgstr "已收集的统计: "
 
 #: kallithea/templates/summary/statistics.html:89
 #: kallithea/templates/summary/summary.html:349
@@ -6124,7 +6120,9 @@
 #~ msgstr "没有文件"
 
 #~ msgid ""
-#~ msgstr "在文本中使用 @用户名 以发送通知到该Kallithea用户"
+#~ "_: \n"
+#~ ""
+#~ msgstr ""
 
 #~ msgid "%(user)s wants you to review pull request #%(pr_id)s: %(pr_title)s"
 #~ msgstr ""
@@ -6348,27 +6346,6 @@
 #~ msgid "owner"
 #~ msgstr "所有者"
 
-#~ msgid ""
-#~ "Your password reset was successful, new"
-#~ " password has been sent to your "
-#~ "email"
-#~ msgstr "密码已经成功重置,新密码已经发送到你的邮箱"
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " changeset %(short_id)s on %(branch)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Added by %(pr_username)s] %(repo_name)s pull"
-#~ " request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " pull request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
 #~ msgid "Your new password"
 #~ msgstr ""
 
@@ -6390,3 +6367,34 @@
 #~ msgid "Created by"
 #~ msgstr "创建于"
 
+#~ msgid "You can only delete files with revision being a valid branch "
+#~ msgstr ""
+
+#~ msgid "You can only edit files with revision being a valid branch "
+#~ msgstr ""
+
+#~ msgid "This pull request can be updated with changes on %s:"
+#~ msgstr ""
+
+#~ msgid "Confirm to invalidate repository cache."
+#~ msgstr "确认清除版本库缓存"
+
+#~ msgid "Comments parsed using %s syntax with %s support."
+#~ msgstr "评论使用%s语法并支持%s"
+
+#~ msgid "Use @username inside this text to notify another user"
+#~ msgstr "在文本中使用 @用户名 以发送通知到该Kallithea用户"
+
+#~ msgid "Comment preview"
+#~ msgstr ""
+
+#~ msgid "Preview"
+#~ msgstr ""
+
+#~ msgid "New file mode"
+#~ msgstr ""
+
+#~ msgid ""
+#~ "Changeset status: %s\n"
+#~ "Click to open associated pull request %s"
+#~ msgstr ""
--- a/kallithea/i18n/zh_TW/LC_MESSAGES/kallithea.po	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/i18n/zh_TW/LC_MESSAGES/kallithea.po	Fri Nov 18 01:11:13 2016 +0100
@@ -7,24 +7,23 @@
 msgstr ""
 "Project-Id-Version: Kallithea 0.3\n"
 "Report-Msgid-Bugs-To: translations@kallithea-scm.org\n"
-"POT-Creation-Date: 2015-09-08 10:34+0200\n"
+"POT-Creation-Date: 2016-03-14 16:51+0100\n"
 "PO-Revision-Date: 2015-08-21 15:52+0200\n"
 "Last-Translator: EriCSN Chang <ericsning@gmail.com>\n"
 "Language-Team: Chinese (Taiwan) "
 "<https://hosted.weblate.org/projects/kallithea/kallithea/zh_TW/>\n"
-"Language: zh_TW\n"
+"Plural-Forms: nplurals=1; plural=0\n"
 "MIME-Version: 1.0\n"
-"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Type: text/plain; charset=utf-8\n"
 "Content-Transfer-Encoding: 8bit\n"
-"Plural-Forms: nplurals=1; plural=0;\n"
-"X-Generator: Weblate 2.4-dev\n"
-
-#: kallithea/controllers/changelog.py:86
-#: kallithea/controllers/pullrequests.py:238 kallithea/lib/base.py:512
+"Generated-By: Babel 1.3\n"
+
+#: kallithea/controllers/changelog.py:85
+#: kallithea/controllers/pullrequests.py:240 kallithea/lib/base.py:515
 msgid "There are no changesets yet"
 msgstr ""
 
-#: kallithea/controllers/changelog.py:166
+#: kallithea/controllers/changelog.py:164
 #: kallithea/controllers/admin/permissions.py:61
 #: kallithea/controllers/admin/permissions.py:65
 #: kallithea/controllers/admin/permissions.py:69
@@ -36,35 +35,29 @@
 msgid "None"
 msgstr "無"
 
-#: kallithea/controllers/changelog.py:169 kallithea/controllers/files.py:196
+#: kallithea/controllers/changelog.py:167 kallithea/controllers/files.py:198
 msgid "(closed)"
 msgstr "(已關閉)"
 
-#: kallithea/controllers/changeset.py:89
+#: kallithea/controllers/changeset.py:88
 msgid "Show whitespace"
 msgstr "顯示空格"
 
-#: kallithea/controllers/changeset.py:96 kallithea/controllers/changeset.py:103
+#: kallithea/controllers/changeset.py:95 kallithea/controllers/changeset.py:102
 #: kallithea/templates/files/diff_2way.html:55
 msgid "Ignore whitespace"
 msgstr "忽略空格"
 
-#: kallithea/controllers/changeset.py:169
+#: kallithea/controllers/changeset.py:168
 #, fuzzy, python-format
 msgid "Increase diff context to %(num)s lines"
 msgstr "增加 diff 上下文至 %(num) 行"
 
-#: kallithea/controllers/changeset.py:212 kallithea/controllers/files.py:96
-#: kallithea/controllers/files.py:116 kallithea/controllers/files.py:742
+#: kallithea/controllers/changeset.py:233 kallithea/controllers/files.py:97
+#: kallithea/controllers/files.py:117 kallithea/controllers/files.py:744
 msgid "Such revision does not exist for this repository"
 msgstr ""
 
-#: kallithea/controllers/changeset.py:383
-msgid ""
-"Changing status on a changeset associated with a closed pull request is "
-"not allowed"
-msgstr ""
-
 #: kallithea/controllers/compare.py:161 kallithea/templates/base/root.html:41
 msgid "Select changeset"
 msgstr ""
@@ -117,10 +110,10 @@
 #: kallithea/controllers/feed.py:87
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Changeset was too big and was cut off..."
 msgstr ""
 
@@ -129,111 +122,111 @@
 msgid "%s committed on %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:91
+#: kallithea/controllers/files.py:92
 msgid "Click here to add new file"
 msgstr ""
 
-#: kallithea/controllers/files.py:92
+#: kallithea/controllers/files.py:93
 #, python-format
 msgid "There are no files yet. %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:193
+#: kallithea/controllers/files.py:195
 #, python-format
 msgid "%s at %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:305 kallithea/controllers/files.py:365
-#: kallithea/controllers/files.py:432
+#: kallithea/controllers/files.py:307 kallithea/controllers/files.py:367
+#: kallithea/controllers/files.py:434
 #, python-format
 msgid "This repository has been locked by %s on %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:317
-msgid "You can only delete files with revision being a valid branch "
-msgstr ""
-
-#: kallithea/controllers/files.py:328
+#: kallithea/controllers/files.py:319
+msgid "You can only delete files with revision being a valid branch"
+msgstr ""
+
+#: kallithea/controllers/files.py:330
 #, python-format
 msgid "Deleted file %s via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:350
+#: kallithea/controllers/files.py:352
 #, python-format
 msgid "Successfully deleted file %s"
 msgstr ""
 
-#: kallithea/controllers/files.py:354 kallithea/controllers/files.py:420
-#: kallithea/controllers/files.py:501
+#: kallithea/controllers/files.py:356 kallithea/controllers/files.py:422
+#: kallithea/controllers/files.py:503
 msgid "Error occurred during commit"
 msgstr ""
 
-#: kallithea/controllers/files.py:377
-msgid "You can only edit files with revision being a valid branch "
-msgstr ""
-
-#: kallithea/controllers/files.py:391
+#: kallithea/controllers/files.py:379
+msgid "You can only edit files with revision being a valid branch"
+msgstr ""
+
+#: kallithea/controllers/files.py:393
 #, python-format
 msgid "Edited file %s via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:407
+#: kallithea/controllers/files.py:409
 msgid "No changes"
 msgstr "沒有修改"
 
-#: kallithea/controllers/files.py:416 kallithea/controllers/files.py:490
+#: kallithea/controllers/files.py:418 kallithea/controllers/files.py:492
 #, python-format
 msgid "Successfully committed to %s"
 msgstr "成功遞交至 %s"
 
-#: kallithea/controllers/files.py:443
+#: kallithea/controllers/files.py:445
 msgid "Added file via Kallithea"
 msgstr ""
 
-#: kallithea/controllers/files.py:464
+#: kallithea/controllers/files.py:466
 msgid "No content"
 msgstr ""
 
-#: kallithea/controllers/files.py:468
+#: kallithea/controllers/files.py:470
 msgid "No filename"
 msgstr ""
 
-#: kallithea/controllers/files.py:493
+#: kallithea/controllers/files.py:495
 msgid "Location must be relative path and must not contain .. in path"
 msgstr ""
 
-#: kallithea/controllers/files.py:526
+#: kallithea/controllers/files.py:528
 msgid "Downloads disabled"
 msgstr ""
 
-#: kallithea/controllers/files.py:537
+#: kallithea/controllers/files.py:539
 #, python-format
 msgid "Unknown revision %s"
 msgstr "未知修訂 %s"
 
-#: kallithea/controllers/files.py:539
+#: kallithea/controllers/files.py:541
 msgid "Empty repository"
 msgstr "空的版本庫"
 
-#: kallithea/controllers/files.py:541
+#: kallithea/controllers/files.py:543
 msgid "Unknown archive type"
 msgstr "未知的存檔類型"
 
-#: kallithea/controllers/files.py:771
+#: kallithea/controllers/files.py:773
 #: kallithea/templates/changeset/changeset_range.html:9
 #: kallithea/templates/email_templates/pull_request.html:15
 #: kallithea/templates/pullrequests/pullrequest.html:97
 msgid "Changesets"
 msgstr "變更"
 
-#: kallithea/controllers/files.py:772 kallithea/controllers/pullrequests.py:176
-#: kallithea/model/scm.py:820 kallithea/templates/switch_to_list.html:3
+#: kallithea/controllers/files.py:774 kallithea/controllers/pullrequests.py:175
+#: kallithea/model/scm.py:716 kallithea/templates/switch_to_list.html:3
 #: kallithea/templates/branches/branches.html:10
 msgid "Branches"
 msgstr "分支"
 
-#: kallithea/controllers/files.py:773 kallithea/controllers/pullrequests.py:177
-#: kallithea/model/scm.py:831 kallithea/templates/switch_to_list.html:25
+#: kallithea/controllers/files.py:775 kallithea/controllers/pullrequests.py:176
+#: kallithea/model/scm.py:727 kallithea/templates/switch_to_list.html:25
 #: kallithea/templates/tags/tags.html:10
 msgid "Tags"
 msgstr "標籤"
@@ -247,7 +240,7 @@
 msgid "Groups"
 msgstr ""
 
-#: kallithea/controllers/home.py:89
+#: kallithea/controllers/home.py:94
 #: kallithea/templates/admin/repo_groups/repo_group_edit_perms.html:106
 #: kallithea/templates/admin/repos/repo_add.html:12
 #: kallithea/templates/admin/repos/repo_add.html:16
@@ -255,23 +248,27 @@
 #: kallithea/templates/admin/users/user_edit_advanced.html:6
 #: kallithea/templates/base/base.html:60 kallithea/templates/base/base.html:77
 #: kallithea/templates/base/base.html:124
-#: kallithea/templates/base/base.html:390
-#: kallithea/templates/base/base.html:562
+#: kallithea/templates/base/base.html:479
+#: kallithea/templates/base/base.html:653
 msgid "Repositories"
 msgstr "版本庫"
 
-#: kallithea/controllers/home.py:130
+#: kallithea/controllers/home.py:139
 #: kallithea/templates/files/files_add.html:32
 #: kallithea/templates/files/files_delete.html:23
 #: kallithea/templates/files/files_edit.html:32
 msgid "Branch"
 msgstr ""
 
-#: kallithea/controllers/home.py:136
+#: kallithea/controllers/home.py:145 kallithea/templates/switch_to_list.html:16
+msgid "Closed Branches"
+msgstr ""
+
+#: kallithea/controllers/home.py:151
 msgid "Tag"
 msgstr ""
 
-#: kallithea/controllers/home.py:142
+#: kallithea/controllers/home.py:157
 msgid "Bookmark"
 msgstr ""
 
@@ -282,163 +279,166 @@
 msgstr "開放日誌"
 
 #: kallithea/controllers/journal.py:115 kallithea/controllers/journal.py:157
-#: kallithea/templates/base/base.html:222
+#: kallithea/templates/base/base.html:306
 #: kallithea/templates/journal/journal.html:4
 #: kallithea/templates/journal/journal.html:12
 msgid "Journal"
 msgstr "日誌"
 
-#: kallithea/controllers/login.py:151 kallithea/controllers/login.py:197
+#: kallithea/controllers/login.py:144 kallithea/controllers/login.py:190
 msgid "Bad captcha"
 msgstr ""
 
-#: kallithea/controllers/login.py:157
-msgid "You have successfully registered into Kallithea"
-msgstr ""
-
-#: kallithea/controllers/login.py:202
+#: kallithea/controllers/login.py:150
+msgid "You have successfully registered with %s"
+msgstr ""
+
+#: kallithea/controllers/login.py:195
 #, fuzzy
-#| msgid "Your password reset link was sent"
 msgid "A password reset confirmation code has been sent"
 msgstr "您的密碼重設連結已寄出"
 
-#: kallithea/controllers/login.py:251
+#: kallithea/controllers/login.py:244
 #, fuzzy
-#| msgid "Your password reset link was sent"
 msgid "Invalid password reset token"
 msgstr "您的密碼重設連結已寄出"
 
-#: kallithea/controllers/login.py:256
+#: kallithea/controllers/login.py:249
 #: kallithea/controllers/admin/my_account.py:167
 msgid "Successfully updated password"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:124
+#: kallithea/controllers/pullrequests.py:123
 #, python-format
 msgid "%s (closed)"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:152
+#: kallithea/controllers/pullrequests.py:151
 #: kallithea/templates/changeset/changeset.html:12
 #: kallithea/templates/email_templates/changeset_comment.html:17
 msgid "Changeset"
 msgstr ""
 
+#: kallithea/controllers/pullrequests.py:172
+msgid "Special"
+msgstr ""
+
 #: kallithea/controllers/pullrequests.py:173
-msgid "Special"
-msgstr ""
-
-#: kallithea/controllers/pullrequests.py:174
 msgid "Peer branches"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:175 kallithea/model/scm.py:826
+#: kallithea/controllers/pullrequests.py:174 kallithea/model/scm.py:722
 #: kallithea/templates/switch_to_list.html:38
 #: kallithea/templates/bookmarks/bookmarks.html:10
 msgid "Bookmarks"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:310
+#: kallithea/controllers/pullrequests.py:312
 #, python-format
 msgid "Error creating pull request: %s"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:356
-#: kallithea/controllers/pullrequests.py:503
+#: kallithea/controllers/pullrequests.py:358
+#: kallithea/controllers/pullrequests.py:505
 #, fuzzy
 msgid "No description"
 msgstr "描述"
 
-#: kallithea/controllers/pullrequests.py:363
+#: kallithea/controllers/pullrequests.py:365
 msgid "Successfully opened new pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:366
-#: kallithea/controllers/pullrequests.py:453
-#: kallithea/controllers/pullrequests.py:509
+#: kallithea/controllers/pullrequests.py:368
+#: kallithea/controllers/pullrequests.py:455
+#: kallithea/controllers/pullrequests.py:512
 #, python-format
 msgid "Invalid reviewer \"%s\" specified"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:369
-#: kallithea/controllers/pullrequests.py:456
+#: kallithea/controllers/pullrequests.py:371
+#: kallithea/controllers/pullrequests.py:458
 msgid "Error occurred while creating pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:401
+#: kallithea/controllers/pullrequests.py:403
 msgid "Missing changesets since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:408
+#: kallithea/controllers/pullrequests.py:410
 #, python-format
 msgid "New changesets on %s %s since the previous pull request:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:415
+#: kallithea/controllers/pullrequests.py:417
 msgid "Ancestor didn't change - show diff since previous version:"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:422
+#: kallithea/controllers/pullrequests.py:424
 #, python-format
 msgid ""
 "This pull request is based on another %s revision and there is no simple "
 "diff."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:424
+#: kallithea/controllers/pullrequests.py:426
 #, python-format
 msgid "No changes found on %s %s since previous version."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:462
+#: kallithea/controllers/pullrequests.py:464
 #, python-format
 msgid "Closed, replaced by %s ."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:470
+#: kallithea/controllers/pullrequests.py:472
 msgid "Pull request update created"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:513
+#: kallithea/controllers/pullrequests.py:516
 msgid "Pull request updated"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:528
+#: kallithea/controllers/pullrequests.py:531
 msgid "Successfully deleted pull request"
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:594
+#: kallithea/controllers/pullrequests.py:597
 #, python-format
 msgid "This pull request has already been merged to %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:596
+#: kallithea/controllers/pullrequests.py:599
 msgid "This pull request has been closed and can not be updated."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:614
-#, python-format
-msgid "This pull request can be updated with changes on %s:"
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:617
+#, python-format
+msgid "The following changes are available on %s:"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:621
 msgid "No changesets found for updating this pull request."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:625
+#: kallithea/controllers/pullrequests.py:629
 #, python-format
 msgid "Note: Branch %s has another head: %s."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:631
+#: kallithea/controllers/pullrequests.py:635
 msgid "Git pull requests don't support updates yet."
 msgstr ""
 
-#: kallithea/controllers/pullrequests.py:722
-msgid "No permission to change pull request status"
-msgstr ""
-
 #: kallithea/controllers/pullrequests.py:727
+msgid "No permission to change pull request status"
+msgstr ""
+
+#: kallithea/controllers/pullrequests.py:738
+#, fuzzy, python-format
+msgid "Successfully deleted pull request %s"
+msgstr "成功遞交至 %s"
+
+#: kallithea/controllers/pullrequests.py:748
 #, fuzzy
 msgid "Closing."
 msgstr "使用中"
@@ -455,12 +455,12 @@
 msgid "An error occurred during search operation."
 msgstr ""
 
-#: kallithea/controllers/summary.py:180
+#: kallithea/controllers/summary.py:181
 #: kallithea/templates/summary/summary.html:384
 msgid "No data ready yet"
 msgstr ""
 
-#: kallithea/controllers/summary.py:183
+#: kallithea/controllers/summary.py:184
 #: kallithea/templates/summary/summary.html:98
 msgid "Statistics are disabled for this repository"
 msgstr "這個版本庫的統計功能已停用"
@@ -481,65 +481,65 @@
 msgid "Error occurred during update of defaults"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/gists.py:58
 #: kallithea/controllers/admin/my_account.py:243
+#: kallithea/controllers/admin/users.py:284
+msgid "Forever"
+msgstr ""
+
+#: kallithea/controllers/admin/gists.py:59
+#: kallithea/controllers/admin/my_account.py:244
 #: kallithea/controllers/admin/users.py:285
-msgid "Forever"
+msgid "5 minutes"
 msgstr ""
 
 #: kallithea/controllers/admin/gists.py:60
-#: kallithea/controllers/admin/my_account.py:244
+#: kallithea/controllers/admin/my_account.py:245
 #: kallithea/controllers/admin/users.py:286
-msgid "5 minutes"
+msgid "1 hour"
 msgstr ""
 
 #: kallithea/controllers/admin/gists.py:61
-#: kallithea/controllers/admin/my_account.py:245
+#: kallithea/controllers/admin/my_account.py:246
 #: kallithea/controllers/admin/users.py:287
-msgid "1 hour"
+msgid "1 day"
 msgstr ""
 
 #: kallithea/controllers/admin/gists.py:62
-#: kallithea/controllers/admin/my_account.py:246
+#: kallithea/controllers/admin/my_account.py:247
 #: kallithea/controllers/admin/users.py:288
-msgid "1 day"
-msgstr ""
-
-#: kallithea/controllers/admin/gists.py:63
-#: kallithea/controllers/admin/my_account.py:247
-#: kallithea/controllers/admin/users.py:289
 msgid "1 month"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:67
+#: kallithea/controllers/admin/gists.py:66
 #: kallithea/controllers/admin/my_account.py:249
-#: kallithea/controllers/admin/users.py:291
+#: kallithea/controllers/admin/users.py:290
 msgid "Lifetime"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:146
+#: kallithea/controllers/admin/gists.py:145
 msgid "Error occurred during gist creation"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:184
+#: kallithea/controllers/admin/gists.py:183
 #, python-format
 msgid "Deleted gist %s"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:233
+#: kallithea/controllers/admin/gists.py:232
 #, fuzzy
 msgid "Unmodified"
 msgstr "最後修改"
 
-#: kallithea/controllers/admin/gists.py:262
+#: kallithea/controllers/admin/gists.py:261
 msgid "Successfully updated gist content"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:267
+#: kallithea/controllers/admin/gists.py:266
 msgid "Successfully updated gist data"
 msgstr ""
 
-#: kallithea/controllers/admin/gists.py:270
+#: kallithea/controllers/admin/gists.py:269
 #, python-format
 msgid "Error occurred during update of gist %s"
 msgstr ""
@@ -554,7 +554,7 @@
 msgstr "您的帳號已更新完成"
 
 #: kallithea/controllers/admin/my_account.py:144
-#: kallithea/controllers/admin/users.py:202
+#: kallithea/controllers/admin/users.py:201
 #, python-format
 msgid "Error occurred during update of user %s"
 msgstr ""
@@ -564,33 +564,33 @@
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:220
-#: kallithea/controllers/admin/users.py:415
+#: kallithea/controllers/admin/users.py:414
 #, python-format
 msgid "Added email %s to user"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:226
-#: kallithea/controllers/admin/users.py:421
+#: kallithea/controllers/admin/users.py:420
 msgid "An error occurred during email saving"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:235
-#: kallithea/controllers/admin/users.py:433
+#: kallithea/controllers/admin/users.py:432
 msgid "Removed email from user"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:259
-#: kallithea/controllers/admin/users.py:308
+#: kallithea/controllers/admin/users.py:307
 msgid "API key successfully created"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:271
-#: kallithea/controllers/admin/users.py:321
+#: kallithea/controllers/admin/users.py:320
 msgid "API key successfully reset"
 msgstr ""
 
 #: kallithea/controllers/admin/my_account.py:275
-#: kallithea/controllers/admin/users.py:325
+#: kallithea/controllers/admin/users.py:324
 msgid "API key successfully deleted"
 msgstr ""
 
@@ -640,10 +640,10 @@
 #: kallithea/templates/admin/users/user_edit_profile.html:105
 #: kallithea/templates/admin/users/users.html:10
 #: kallithea/templates/admin/users/users.html:55
-#: kallithea/templates/base/base.html:252
-#: kallithea/templates/base/base.html:253
-#: kallithea/templates/base/base.html:259
-#: kallithea/templates/base/base.html:260
+#: kallithea/templates/base/base.html:336
+#: kallithea/templates/base/base.html:337
+#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:344
 #: kallithea/templates/base/perms_summary.html:17
 msgid "Admin"
 msgstr "管理"
@@ -674,7 +674,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1564
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1603
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1655
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1701
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1682 kallithea/model/db.py:1705
 msgid "Manual activation of external account"
 msgstr ""
 
@@ -686,7 +686,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1565
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1604
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1656
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1702
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1683 kallithea/model/db.py:1706
 msgid "Automatic activation of external account"
 msgstr ""
 
@@ -707,244 +707,244 @@
 msgid "Error occurred during update of permissions"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:188
+#: kallithea/controllers/admin/repo_groups.py:187
 #, python-format
 msgid "Error occurred during creation of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:193
+#: kallithea/controllers/admin/repo_groups.py:192
 #, python-format
 msgid "Created repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:250
+#: kallithea/controllers/admin/repo_groups.py:249
 #, python-format
 msgid "Updated repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:266
+#: kallithea/controllers/admin/repo_groups.py:265
 #, python-format
 msgid "Error occurred during update of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:284
+#: kallithea/controllers/admin/repo_groups.py:283
 #, python-format
 msgid "This group contains %s repositories and cannot be deleted"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:291
+#: kallithea/controllers/admin/repo_groups.py:290
 #, python-format
 msgid "This group contains %s subgroups and cannot be deleted"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:297
+#: kallithea/controllers/admin/repo_groups.py:296
 #, python-format
 msgid "Removed repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:302
+#: kallithea/controllers/admin/repo_groups.py:301
 #, python-format
 msgid "Error occurred during deletion of repository group %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:405
-#: kallithea/controllers/admin/repo_groups.py:440
+#: kallithea/controllers/admin/repo_groups.py:404
+#: kallithea/controllers/admin/repo_groups.py:439
 #: kallithea/controllers/admin/user_groups.py:340
 msgid "Cannot revoke permission for yourself as admin"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:420
+#: kallithea/controllers/admin/repo_groups.py:419
 msgid "Repository group permissions updated"
 msgstr ""
 
-#: kallithea/controllers/admin/repo_groups.py:457
-#: kallithea/controllers/admin/repos.py:398
+#: kallithea/controllers/admin/repo_groups.py:456
+#: kallithea/controllers/admin/repos.py:397
 #: kallithea/controllers/admin/user_groups.py:352
 msgid "An error occurred during revoking of permission"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:152
+#: kallithea/controllers/admin/repos.py:151
 #, python-format
 msgid "Error creating repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:213
+#: kallithea/controllers/admin/repos.py:212
 #, python-format
 msgid "Created repository %s from %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:222
+#: kallithea/controllers/admin/repos.py:221
 #, python-format
 msgid "Forked repository %s as %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:225
+#: kallithea/controllers/admin/repos.py:224
 #, python-format
 msgid "Created repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:262
+#: kallithea/controllers/admin/repos.py:261
 #, python-format
 msgid "Repository %s updated successfully"
 msgstr "版本庫 %s 更新完成"
 
-#: kallithea/controllers/admin/repos.py:283
+#: kallithea/controllers/admin/repos.py:282
 #, python-format
 msgid "Error occurred during update of repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:310
+#: kallithea/controllers/admin/repos.py:309
 #, python-format
 msgid "Detached %s forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:313
+#: kallithea/controllers/admin/repos.py:312
 #, python-format
 msgid "Deleted %s forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:318
+#: kallithea/controllers/admin/repos.py:317
 #, python-format
 msgid "Deleted repository %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:321
+#: kallithea/controllers/admin/repos.py:320
 #, python-format
 msgid "Cannot delete repository %s which still has forks"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:326
+#: kallithea/controllers/admin/repos.py:325
 #, python-format
 msgid "An error occurred during deletion of %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:374
+#: kallithea/controllers/admin/repos.py:373
 msgid "Repository permissions updated"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:430
+#: kallithea/controllers/admin/repos.py:429
 msgid "An error occurred during creation of field"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:444
+#: kallithea/controllers/admin/repos.py:443
 msgid "An error occurred during removal of field"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:460
+#: kallithea/controllers/admin/repos.py:459
 msgid "-- Not a fork --"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:491
+#: kallithea/controllers/admin/repos.py:490
 msgid "Updated repository visibility in public journal"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:495
+#: kallithea/controllers/admin/repos.py:494
 msgid "An error occurred during setting this repository in public journal"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:512
+#: kallithea/controllers/admin/repos.py:511
 msgid "Nothing"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:514
+#: kallithea/controllers/admin/repos.py:513
 #, python-format
 msgid "Marked repository %s as fork of %s"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:521
+#: kallithea/controllers/admin/repos.py:520
 msgid "An error occurred during this operation"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:537
-#: kallithea/controllers/admin/repos.py:564
+#: kallithea/controllers/admin/repos.py:536
+#: kallithea/controllers/admin/repos.py:563
 #, fuzzy
 msgid "Repository has been locked"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:540
-#: kallithea/controllers/admin/repos.py:561
+#: kallithea/controllers/admin/repos.py:539
+#: kallithea/controllers/admin/repos.py:560
 #, fuzzy
 msgid "Repository has been unlocked"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:543
-#: kallithea/controllers/admin/repos.py:568
+#: kallithea/controllers/admin/repos.py:542
+#: kallithea/controllers/admin/repos.py:567
 msgid "An error occurred during unlocking"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:582
+#: kallithea/controllers/admin/repos.py:581
 msgid "Cache invalidation successful"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:586
+#: kallithea/controllers/admin/repos.py:585
 msgid "An error occurred during cache invalidation"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:601
+#: kallithea/controllers/admin/repos.py:600
 msgid "Pulled from remote location"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:604
+#: kallithea/controllers/admin/repos.py:603
 msgid "An error occurred during pull from remote location"
 msgstr ""
 
-#: kallithea/controllers/admin/repos.py:637
+#: kallithea/controllers/admin/repos.py:636
 msgid "An error occurred during deletion of repository stats"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:170
+#: kallithea/controllers/admin/settings.py:141
 msgid "Updated VCS settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:174
+#: kallithea/controllers/admin/settings.py:145
 msgid ""
 "Unable to activate hgsubversion support. The \"hgsubversion\" library is "
 "missing"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:180
-#: kallithea/controllers/admin/settings.py:277
+#: kallithea/controllers/admin/settings.py:151
+#: kallithea/controllers/admin/settings.py:248
 msgid "Error occurred while updating application settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:216
+#: kallithea/controllers/admin/settings.py:187
 #, python-format
 msgid "Repositories successfully rescanned. Added: %s. Removed: %s."
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:273
+#: kallithea/controllers/admin/settings.py:244
 msgid "Updated application settings"
 msgstr "更新應用設定"
 
-#: kallithea/controllers/admin/settings.py:330
+#: kallithea/controllers/admin/settings.py:301
 msgid "Updated visualisation settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:335
+#: kallithea/controllers/admin/settings.py:306
 msgid "Error occurred during updating visualisation settings"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:361
+#: kallithea/controllers/admin/settings.py:332
 msgid "Please enter email address"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:376
+#: kallithea/controllers/admin/settings.py:347
 msgid "Send email task created"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:407
+#: kallithea/controllers/admin/settings.py:378
 msgid "Added new hook"
 msgstr "新增hook"
 
-#: kallithea/controllers/admin/settings.py:421
+#: kallithea/controllers/admin/settings.py:392
 msgid "Updated hooks"
 msgstr "更新hook"
 
-#: kallithea/controllers/admin/settings.py:425
+#: kallithea/controllers/admin/settings.py:396
 msgid "Error occurred during hook creation"
 msgstr ""
 
-#: kallithea/controllers/admin/settings.py:451
+#: kallithea/controllers/admin/settings.py:422
 msgid "Whoosh reindex task scheduled"
 msgstr "Whoosh 重新索引工作排程"
 
@@ -985,76 +985,80 @@
 msgstr ""
 
 #: kallithea/controllers/admin/user_groups.py:440
-#: kallithea/controllers/admin/users.py:384
+#: kallithea/controllers/admin/users.py:383
 msgid "Updated permissions"
 msgstr ""
 
 #: kallithea/controllers/admin/user_groups.py:444
-#: kallithea/controllers/admin/users.py:388
+#: kallithea/controllers/admin/users.py:387
 msgid "An error occurred during permissions saving"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:134
+#: kallithea/controllers/admin/users.py:133
 #, python-format
 msgid "Created user %s"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:149
+#: kallithea/controllers/admin/users.py:148
 #, python-format
 msgid "Error occurred during creation of user %s"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:182
+#: kallithea/controllers/admin/users.py:181
 msgid "User updated successfully"
 msgstr "使用者更新完成"
 
-#: kallithea/controllers/admin/users.py:218
+#: kallithea/controllers/admin/users.py:217
 msgid "Successfully deleted user"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:223
+#: kallithea/controllers/admin/users.py:222
 msgid "An error occurred during deletion of user"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:236
+#: kallithea/controllers/admin/users.py:235
 msgid "The default user cannot be edited"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:463
+#: kallithea/controllers/admin/users.py:462
 #, python-format
 msgid "Added IP address %s to user whitelist"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:469
+#: kallithea/controllers/admin/users.py:468
 msgid "An error occurred while adding IP address"
 msgstr ""
 
-#: kallithea/controllers/admin/users.py:483
+#: kallithea/controllers/admin/users.py:482
 msgid "Removed IP address from user whitelist"
 msgstr ""
 
-#: kallithea/lib/auth.py:743
+#: kallithea/lib/auth.py:737
 #, python-format
 msgid "IP %s not allowed"
 msgstr ""
 
-#: kallithea/lib/auth.py:756
+#: kallithea/lib/auth.py:750
 msgid "Invalid API key"
 msgstr ""
 
-#: kallithea/lib/auth.py:812
+#: kallithea/lib/auth.py:768
+msgid "CSRF token leak has been detected - all form tokens have been expired"
+msgstr ""
+
+#: kallithea/lib/auth.py:813
 msgid "You need to be a registered user to perform this action"
 msgstr "您必須是註冊使用者才能執行這個動作"
 
-#: kallithea/lib/auth.py:844
+#: kallithea/lib/auth.py:843
 msgid "You need to be signed in to view this page"
 msgstr "您必須登入後才能瀏覽這個頁面"
 
-#: kallithea/lib/base.py:490
+#: kallithea/lib/base.py:493
 msgid "Repository not found in the filesystem"
 msgstr ""
 
-#: kallithea/lib/base.py:516 kallithea/lib/helpers.py:622
+#: kallithea/lib/base.py:519 kallithea/lib/helpers.py:623
 msgid "Changeset not found"
 msgstr ""
 
@@ -1070,125 +1074,125 @@
 msgid "No changes detected"
 msgstr "尚未有任何變更"
 
-#: kallithea/lib/helpers.py:609
+#: kallithea/lib/helpers.py:610
 #, python-format
 msgid "Deleted branch: %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:611
+#: kallithea/lib/helpers.py:612
 #, python-format
 msgid "Created tag: %s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:671
+#: kallithea/lib/helpers.py:672
 #, python-format
 msgid "Show all combined changesets %s->%s"
 msgstr ""
 
-#: kallithea/lib/helpers.py:677
+#: kallithea/lib/helpers.py:678
 msgid "Compare view"
 msgstr ""
 
-#: kallithea/lib/helpers.py:696
-msgid "and"
-msgstr "和"
-
 #: kallithea/lib/helpers.py:697
+msgid "and"
+msgstr "和"
+
+#: kallithea/lib/helpers.py:698
 #, python-format
 msgid "%s more"
 msgstr ""
 
-#: kallithea/lib/helpers.py:698 kallithea/templates/changelog/changelog.html:44
+#: kallithea/lib/helpers.py:699 kallithea/templates/changelog/changelog.html:44
 msgid "revisions"
 msgstr "修訂"
 
-#: kallithea/lib/helpers.py:722
+#: kallithea/lib/helpers.py:723
 #, fuzzy, python-format
 msgid "Fork name %s"
 msgstr "分支名稱"
 
-#: kallithea/lib/helpers.py:742
+#: kallithea/lib/helpers.py:743
 #, fuzzy, python-format
 msgid "Pull request %s"
 msgstr "文件內容"
 
-#: kallithea/lib/helpers.py:752
+#: kallithea/lib/helpers.py:753
 msgid "[deleted] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:754 kallithea/lib/helpers.py:766
+#: kallithea/lib/helpers.py:755 kallithea/lib/helpers.py:767
 msgid "[created] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:756
+#: kallithea/lib/helpers.py:757
 msgid "[created] repository as fork"
 msgstr ""
 
-#: kallithea/lib/helpers.py:758 kallithea/lib/helpers.py:768
+#: kallithea/lib/helpers.py:759 kallithea/lib/helpers.py:769
 msgid "[forked] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:760 kallithea/lib/helpers.py:770
+#: kallithea/lib/helpers.py:761 kallithea/lib/helpers.py:771
 msgid "[updated] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:762
+#: kallithea/lib/helpers.py:763
 msgid "[downloaded] archive from repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:764
+#: kallithea/lib/helpers.py:765
 msgid "[delete] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:772
+#: kallithea/lib/helpers.py:773
 msgid "[created] user"
 msgstr ""
 
-#: kallithea/lib/helpers.py:774
+#: kallithea/lib/helpers.py:775
 msgid "[updated] user"
 msgstr ""
 
-#: kallithea/lib/helpers.py:776
+#: kallithea/lib/helpers.py:777
 msgid "[created] user group"
 msgstr ""
 
-#: kallithea/lib/helpers.py:778
+#: kallithea/lib/helpers.py:779
 msgid "[updated] user group"
 msgstr ""
 
-#: kallithea/lib/helpers.py:780
+#: kallithea/lib/helpers.py:781
 msgid "[commented] on revision in repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:782
+#: kallithea/lib/helpers.py:783
 msgid "[commented] on pull request for"
 msgstr ""
 
-#: kallithea/lib/helpers.py:784
+#: kallithea/lib/helpers.py:785
 msgid "[closed] pull request for"
 msgstr ""
 
-#: kallithea/lib/helpers.py:786
+#: kallithea/lib/helpers.py:787
 msgid "[pushed] into"
 msgstr ""
 
-#: kallithea/lib/helpers.py:788
+#: kallithea/lib/helpers.py:789
 msgid "[committed via Kallithea] into repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:790
+#: kallithea/lib/helpers.py:791
 msgid "[pulled from remote] into repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:792
+#: kallithea/lib/helpers.py:793
 msgid "[pulled] from"
 msgstr ""
 
-#: kallithea/lib/helpers.py:794
+#: kallithea/lib/helpers.py:795
 msgid "[started following] repository"
 msgstr ""
 
-#: kallithea/lib/helpers.py:796
+#: kallithea/lib/helpers.py:797
 msgid "[stopped following] repository"
 msgstr ""
 
@@ -1198,8 +1202,8 @@
 msgstr ""
 
 #: kallithea/lib/helpers.py:1128
-#: kallithea/templates/compare/compare_diff.html:65
-#: kallithea/templates/pullrequests/pullrequest_show.html:326
+#: kallithea/templates/compare/compare_diff.html:71
+#: kallithea/templates/pullrequests/pullrequest_show.html:337
 msgid "No files"
 msgstr ""
 
@@ -1223,7 +1227,7 @@
 msgid "chmod"
 msgstr ""
 
-#: kallithea/lib/helpers.py:1444
+#: kallithea/lib/helpers.py:1469
 #, python-format
 msgid ""
 "%s repository is not mapped to db perhaps it was created or renamed from "
@@ -1231,63 +1235,63 @@
 "repositories"
 msgstr ""
 
-#: kallithea/lib/utils2.py:415
+#: kallithea/lib/utils2.py:434
 #, python-format
 msgid "%d year"
 msgid_plural "%d years"
 msgstr[0] ""
 
-#: kallithea/lib/utils2.py:416
+#: kallithea/lib/utils2.py:435
 #, python-format
 msgid "%d month"
 msgid_plural "%d months"
 msgstr[0] ""
 
-#: kallithea/lib/utils2.py:417
+#: kallithea/lib/utils2.py:436
 #, python-format
 msgid "%d day"
 msgid_plural "%d days"
 msgstr[0] ""
 
-#: kallithea/lib/utils2.py:418
+#: kallithea/lib/utils2.py:437
 #, python-format
 msgid "%d hour"
 msgid_plural "%d hours"
 msgstr[0] ""
 
-#: kallithea/lib/utils2.py:419
+#: kallithea/lib/utils2.py:438
 #, python-format
 msgid "%d minute"
 msgid_plural "%d minutes"
 msgstr[0] ""
 
-#: kallithea/lib/utils2.py:420
+#: kallithea/lib/utils2.py:439
 #, python-format
 msgid "%d second"
 msgid_plural "%d seconds"
 msgstr[0] ""
 
-#: kallithea/lib/utils2.py:436
+#: kallithea/lib/utils2.py:455
 #, python-format
 msgid "in %s"
 msgstr ""
 
-#: kallithea/lib/utils2.py:438
+#: kallithea/lib/utils2.py:457
 #, python-format
 msgid "%s ago"
 msgstr ""
 
-#: kallithea/lib/utils2.py:440
+#: kallithea/lib/utils2.py:459
 #, python-format
 msgid "in %s and %s"
 msgstr ""
 
-#: kallithea/lib/utils2.py:443
+#: kallithea/lib/utils2.py:462
 #, python-format
 msgid "%s and %s ago"
 msgstr ""
 
-#: kallithea/lib/utils2.py:446
+#: kallithea/lib/utils2.py:465
 msgid "just now"
 msgstr "現在"
 
@@ -1386,7 +1390,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1531
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1570
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1620
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1665
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1647 kallithea/model/db.py:1669
 msgid "Kallithea Administrator"
 msgstr ""
 
@@ -1497,7 +1501,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2063
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2102
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2155
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2229
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2201 kallithea/model/db.py:2237
 msgid "Approved"
 msgstr ""
 
@@ -1512,7 +1516,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:2064
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:2103
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:2156
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2230
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:2202 kallithea/model/db.py:2238
 msgid "Rejected"
 msgstr ""
 
@@ -1539,7 +1543,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1379
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1418
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1471
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1514
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1498 kallithea/model/db.py:1518
 msgid "top level"
 msgstr ""
 
@@ -1686,7 +1690,7 @@
 #: kallithea/lib/dbmigrate/schema/db_2_0_2.py:1560
 #: kallithea/lib/dbmigrate/schema/db_2_1_0.py:1599
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1651
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1697
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1678 kallithea/model/db.py:1701
 msgid "Registration disabled"
 msgstr ""
 
@@ -1713,12 +1717,12 @@
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1645
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1691
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1672 kallithea/model/db.py:1695
 msgid "Repository creation enabled with write permission to a repository group"
 msgstr ""
 
 #: kallithea/lib/dbmigrate/schema/db_2_2_0.py:1646
-#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1692
+#: kallithea/lib/dbmigrate/schema/db_2_2_3.py:1673 kallithea/model/db.py:1696
 msgid "Repository creation disabled with write permission to a repository group"
 msgstr ""
 
@@ -1727,106 +1731,106 @@
 msgid "on line %s"
 msgstr ""
 
-#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:169
+#: kallithea/model/comment.py:217 kallithea/model/pull_request.py:170
 msgid "[Mention]"
 msgstr ""
 
-#: kallithea/model/db.py:1667
+#: kallithea/model/db.py:1671
 msgid "Default user has no access to new repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1668
-msgid "Default user has read access to new repositories"
-msgstr ""
-
-#: kallithea/model/db.py:1669
-msgid "Default user has write access to new repositories"
-msgstr ""
-
-#: kallithea/model/db.py:1670
-msgid "Default user has admin access to new repositories"
-msgstr ""
-
 #: kallithea/model/db.py:1672
-msgid "Default user has no access to new repository groups"
+msgid "Default user has read access to new repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1673
-msgid "Default user has read access to new repository groups"
+msgid "Default user has write access to new repositories"
 msgstr ""
 
 #: kallithea/model/db.py:1674
-msgid "Default user has write access to new repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1675
-msgid "Default user has admin access to new repository groups"
+msgid "Default user has admin access to new repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1676
+msgid "Default user has no access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1677
-msgid "Default user has no access to new user groups"
+msgid "Default user has read access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1678
-msgid "Default user has read access to new user groups"
+msgid "Default user has write access to new repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1679
-msgid "Default user has write access to new user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1680
-msgid "Default user has admin access to new user groups"
+msgid "Default user has admin access to new repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1681
+msgid "Default user has no access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1682
-msgid "Only admins can create repository groups"
+msgid "Default user has read access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1683
-msgid "Non-admins can create repository groups"
-msgstr ""
-
-#: kallithea/model/db.py:1685
-msgid "Only admins can create user groups"
+msgid "Default user has write access to new user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1684
+msgid "Default user has admin access to new user groups"
 msgstr ""
 
 #: kallithea/model/db.py:1686
-msgid "Non-admins can create user groups"
-msgstr ""
-
-#: kallithea/model/db.py:1688
-msgid "Only admins can create top level repositories"
+msgid "Only admins can create repository groups"
+msgstr ""
+
+#: kallithea/model/db.py:1687
+msgid "Non-admins can create repository groups"
 msgstr ""
 
 #: kallithea/model/db.py:1689
+msgid "Only admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1690
+msgid "Non-admins can create user groups"
+msgstr ""
+
+#: kallithea/model/db.py:1692
+msgid "Only admins can create top level repositories"
+msgstr ""
+
+#: kallithea/model/db.py:1693
 msgid "Non-admins can create top level repositories"
 msgstr ""
 
-#: kallithea/model/db.py:1694
+#: kallithea/model/db.py:1698
 #, fuzzy
 msgid "Only admins can fork repositories"
 msgstr "建立版本庫"
 
-#: kallithea/model/db.py:1695
+#: kallithea/model/db.py:1699
 #, fuzzy
-msgid "Non-admins can can fork repositories"
+msgid "Non-admins can fork repositories"
 msgstr "建立版本庫"
 
-#: kallithea/model/db.py:1698
+#: kallithea/model/db.py:1702
 msgid "User registration with manual account activation"
 msgstr ""
 
-#: kallithea/model/db.py:1699
+#: kallithea/model/db.py:1703
 msgid "User registration with automatic account activation"
 msgstr ""
 
-#: kallithea/model/db.py:2228
+#: kallithea/model/db.py:2236
 #, fuzzy
 msgid "Not reviewed"
 msgstr ""
 
-#: kallithea/model/db.py:2231
+#: kallithea/model/db.py:2239
 #, fuzzy
 msgid "Under review"
 msgstr ""
@@ -1849,7 +1853,7 @@
 msgid "Enter %(min)i characters or more"
 msgstr ""
 
-#: kallithea/model/forms.py:160
+#: kallithea/model/forms.py:165
 msgid "Name must not contain only digits"
 msgstr ""
 
@@ -1943,7 +1947,7 @@
 msgid "%(user)s wants you to review pull request %(pr_nice_id)s: %(pr_title)s"
 msgstr ""
 
-#: kallithea/model/scm.py:812
+#: kallithea/model/scm.py:708
 msgid "latest tip"
 msgstr ""
 
@@ -1977,15 +1981,15 @@
 "owners or remove those user groups: %s"
 msgstr ""
 
-#: kallithea/model/user.py:360
+#: kallithea/model/user.py:368
 msgid "Password reset link"
 msgstr ""
 
-#: kallithea/model/user.py:408
+#: kallithea/model/user.py:418
 msgid "Password reset notification"
 msgstr ""
 
-#: kallithea/model/user.py:409
+#: kallithea/model/user.py:419
 #, python-format
 msgid ""
 "The password to your account %s has been changed using password reset "
@@ -1996,170 +2000,170 @@
 msgid "Value cannot be an empty list"
 msgstr ""
 
-#: kallithea/model/validators.py:95
+#: kallithea/model/validators.py:96
 #, python-format
 msgid "Username \"%(username)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:97
+#: kallithea/model/validators.py:98
 #, python-format
 msgid "Username \"%(username)s\" cannot be used"
 msgstr ""
 
-#: kallithea/model/validators.py:99
+#: kallithea/model/validators.py:100
 msgid ""
 "Username may only contain alphanumeric characters underscores, periods or"
 " dashes and must begin with an alphanumeric character or underscore"
 msgstr ""
 
-#: kallithea/model/validators.py:126
+#: kallithea/model/validators.py:127
 msgid "The input is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:133
+#: kallithea/model/validators.py:134
 #, python-format
 msgid "Username %(username)s is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:152
+#: kallithea/model/validators.py:154
 msgid "Invalid user group name"
 msgstr ""
 
-#: kallithea/model/validators.py:153
-#, python-format
-msgid "User group \"%(usergroup)s\" already exists"
-msgstr ""
-
 #: kallithea/model/validators.py:155
+#, python-format
+msgid "User group \"%(usergroup)s\" already exists"
+msgstr ""
+
+#: kallithea/model/validators.py:157
 msgid ""
 "user group name may only contain alphanumeric characters underscores, "
 "periods or dashes and must begin with alphanumeric character"
 msgstr ""
 
-#: kallithea/model/validators.py:193
+#: kallithea/model/validators.py:197
 msgid "Cannot assign this group as parent"
 msgstr ""
 
-#: kallithea/model/validators.py:194
+#: kallithea/model/validators.py:198
 #, python-format
 msgid "Group \"%(group_name)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:196
+#: kallithea/model/validators.py:200
 #, python-format
 msgid "Repository with name \"%(group_name)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:254
+#: kallithea/model/validators.py:258
 msgid "Invalid characters (non-ascii) in password"
 msgstr ""
 
-#: kallithea/model/validators.py:269
+#: kallithea/model/validators.py:273
 msgid "Invalid old password"
 msgstr ""
 
-#: kallithea/model/validators.py:285
+#: kallithea/model/validators.py:289
 msgid "Passwords do not match"
 msgstr "密碼不相符"
 
-#: kallithea/model/validators.py:300
+#: kallithea/model/validators.py:304
 #, fuzzy
 msgid "Invalid username or password"
 msgstr "無效的密碼"
 
-#: kallithea/model/validators.py:331
+#: kallithea/model/validators.py:335
 msgid "Token mismatch"
 msgstr ""
 
-#: kallithea/model/validators.py:345
+#: kallithea/model/validators.py:351
 #, python-format
 msgid "Repository name %(repo)s is not allowed"
 msgstr ""
 
-#: kallithea/model/validators.py:347
+#: kallithea/model/validators.py:353
 #, python-format
 msgid "Repository named %(repo)s already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:348
+#: kallithea/model/validators.py:354
 #, python-format
 msgid "Repository \"%(repo)s\" already exists in group \"%(group)s\""
 msgstr ""
 
-#: kallithea/model/validators.py:350
+#: kallithea/model/validators.py:356
 #, python-format
 msgid "Repository group with name \"%(repo)s\" already exists"
 msgstr ""
 
-#: kallithea/model/validators.py:465
+#: kallithea/model/validators.py:470
 #, fuzzy
 msgid "Invalid repository URL"
 msgstr "私有版本庫"
 
-#: kallithea/model/validators.py:466
+#: kallithea/model/validators.py:471
 msgid ""
 "Invalid repository URL. It must be a valid http, https, ssh, svn+http or "
 "svn+https URL"
 msgstr ""
 
-#: kallithea/model/validators.py:489
+#: kallithea/model/validators.py:496
 msgid "Fork has to be the same type as parent"
 msgstr ""
 
-#: kallithea/model/validators.py:504
+#: kallithea/model/validators.py:511
 msgid "You don't have permissions to create repository in this group"
 msgstr ""
 
-#: kallithea/model/validators.py:506
+#: kallithea/model/validators.py:513
 msgid "no permission to create repository in root location"
 msgstr ""
 
-#: kallithea/model/validators.py:556
+#: kallithea/model/validators.py:563
 msgid "You don't have permissions to create a group in this location"
 msgstr ""
 
-#: kallithea/model/validators.py:597
+#: kallithea/model/validators.py:604
 msgid "This username or user group name is not valid"
 msgstr ""
 
-#: kallithea/model/validators.py:690
+#: kallithea/model/validators.py:697
 msgid "This is not a valid path"
 msgstr "不是一個有效的路徑"
 
-#: kallithea/model/validators.py:705
+#: kallithea/model/validators.py:714
 #, fuzzy
 msgid "This email address is already in use"
 msgstr "這個郵件位址已經使用了"
 
-#: kallithea/model/validators.py:725
+#: kallithea/model/validators.py:734
 #, python-format
 msgid "Email address \"%(email)s\" not found"
 msgstr ""
 
-#: kallithea/model/validators.py:762
+#: kallithea/model/validators.py:771
 msgid ""
 "The LDAP Login attribute of the CN must be specified - this is the name "
 "of the attribute that is equivalent to \"username\""
 msgstr ""
 
-#: kallithea/model/validators.py:774
+#: kallithea/model/validators.py:783
 msgid "Please enter a valid IPv4 or IPv6 address"
 msgstr ""
 
-#: kallithea/model/validators.py:775
+#: kallithea/model/validators.py:784
 #, python-format
 msgid "The network size (bits) must be within the range of 0-32 (not %(bits)r)"
 msgstr ""
 
-#: kallithea/model/validators.py:808
+#: kallithea/model/validators.py:817
 msgid "Key name can only consist of letters, underscore, dash or numbers"
 msgstr ""
 
-#: kallithea/model/validators.py:822
+#: kallithea/model/validators.py:831
 msgid "Filename cannot be inside a directory"
 msgstr ""
 
-#: kallithea/model/validators.py:838
+#: kallithea/model/validators.py:847
 #, python-format
 msgid "Plugins %(loaded)s and %(next_to_load)s both export the same name"
 msgstr ""
@@ -2286,7 +2290,7 @@
 #: kallithea/templates/admin/user_groups/user_groups.html:50
 #: kallithea/templates/pullrequests/pullrequest_data.html:16
 #: kallithea/templates/pullrequests/pullrequest_show.html:156
-#: kallithea/templates/pullrequests/pullrequest_show.html:233
+#: kallithea/templates/pullrequests/pullrequest_show.html:244
 #: kallithea/templates/summary/summary.html:134
 msgid "Owner"
 msgstr "擁有者"
@@ -2334,7 +2338,7 @@
 #: kallithea/templates/index_base.html:144
 #: kallithea/templates/admin/my_account/my_account_repos.html:61
 #: kallithea/templates/admin/my_account/my_account_watched.html:61
-#: kallithea/templates/base/base.html:140 kallithea/templates/base/root.html:47
+#: kallithea/templates/base/root.html:47
 #: kallithea/templates/bookmarks/bookmarks.html:83
 #: kallithea/templates/branches/branches.html:83
 #: kallithea/templates/journal/journal.html:202
@@ -2344,7 +2348,7 @@
 msgstr ""
 
 #: kallithea/templates/login.html:5 kallithea/templates/login.html:15
-#: kallithea/templates/base/base.html:326
+#: kallithea/templates/base/base.html:414
 msgid "Log In"
 msgstr ""
 
@@ -2359,7 +2363,7 @@
 #: kallithea/templates/admin/users/user_add.html:32
 #: kallithea/templates/admin/users/user_edit_profile.html:24
 #: kallithea/templates/admin/users/users.html:50
-#: kallithea/templates/base/base.html:302
+#: kallithea/templates/base/base.html:390
 #: kallithea/templates/pullrequests/pullrequest_show.html:166
 msgid "Username"
 msgstr "帳號"
@@ -2367,7 +2371,7 @@
 #: kallithea/templates/login.html:33 kallithea/templates/register.html:33
 #: kallithea/templates/admin/my_account/my_account.html:37
 #: kallithea/templates/admin/users/user_add.html:41
-#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:399
 msgid "Password"
 msgstr "密碼"
 
@@ -2379,7 +2383,7 @@
 msgid "Forgot your password ?"
 msgstr "忘記您的密碼?"
 
-#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:322
+#: kallithea/templates/login.html:56 kallithea/templates/base/base.html:410
 msgid "Don't have an account ?"
 msgstr "沒有帳號?"
 
@@ -2419,8 +2423,6 @@
 
 #: kallithea/templates/password_reset.html:47
 #, fuzzy
-#| msgid "" "Password reset link will be sent to the email address matching
-#| your " "username."
 msgid ""
 "A password reset link will be sent to the specified email address if it "
 "is registered in the system."
@@ -2443,13 +2445,11 @@
 
 #: kallithea/templates/password_reset_confirmation.html:39
 #, fuzzy
-#| msgid "New password"
 msgid "New Password"
 msgstr "新密碼"
 
 #: kallithea/templates/password_reset_confirmation.html:48
 #, fuzzy
-#| msgid "New password"
 msgid "Confirm New Password"
 msgstr "新密碼"
 
@@ -2508,10 +2508,6 @@
 msgid "There are no branches yet"
 msgstr "沒有任何分支"
 
-#: kallithea/templates/switch_to_list.html:16
-msgid "Closed Branches"
-msgstr ""
-
 #: kallithea/templates/switch_to_list.html:32
 #: kallithea/templates/tags/tags_data.html:44
 msgid "There are no tags yet"
@@ -2741,12 +2737,12 @@
 msgid "Never"
 msgstr "擁有者"
 
-#: kallithea/templates/admin/gists/edit.html:145
+#: kallithea/templates/admin/gists/edit.html:146
 msgid "Update Gist"
 msgstr ""
 
-#: kallithea/templates/admin/gists/edit.html:146
-#: kallithea/templates/changeset/changeset_file_comment.html:81
+#: kallithea/templates/admin/gists/edit.html:147
+#: kallithea/templates/changeset/changeset_file_comment.html:105
 msgid "Cancel"
 msgstr ""
 
@@ -2769,7 +2765,7 @@
 
 #: kallithea/templates/admin/gists/index.html:37
 #: kallithea/templates/admin/gists/show.html:25
-#: kallithea/templates/base/base.html:237
+#: kallithea/templates/base/base.html:321
 msgid "Create New Gist"
 msgstr ""
 
@@ -2857,7 +2853,8 @@
 #: kallithea/templates/admin/settings/settings_hooks.html:36
 #: kallithea/templates/admin/users/user_edit_emails.html:19
 #: kallithea/templates/admin/users/user_edit_ips.html:22
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
+#: kallithea/templates/changeset/changeset_file_comment.html:95
 #: kallithea/templates/data_table/_dt_elements.html:129
 #: kallithea/templates/data_table/_dt_elements.html:157
 #: kallithea/templates/data_table/_dt_elements.html:173
@@ -2877,8 +2874,6 @@
 #: kallithea/templates/base/perms_summary.html:43
 #: kallithea/templates/base/perms_summary.html:79
 #: kallithea/templates/base/perms_summary.html:81
-#: kallithea/templates/changeset/changeset_file_comment.html:83
-#: kallithea/templates/changeset/changeset_file_comment.html:192
 #: kallithea/templates/data_table/_dt_elements.html:122
 #: kallithea/templates/data_table/_dt_elements.html:123
 #: kallithea/templates/data_table/_dt_elements.html:150
@@ -2905,13 +2900,12 @@
 msgstr ""
 
 #: kallithea/templates/admin/gists/show.html:86
-#: kallithea/templates/files/files_source.html:73
 msgid "Show as raw"
 msgstr ""
 
 #: kallithea/templates/admin/my_account/my_account.html:5
 #: kallithea/templates/admin/my_account/my_account.html:9
-#: kallithea/templates/base/base.html:343
+#: kallithea/templates/base/base.html:431
 msgid "My Account"
 msgstr "我的帳號"
 
@@ -3099,7 +3093,7 @@
 msgstr ""
 
 #: kallithea/templates/admin/notifications/notifications.html:26
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 msgid "Pull Requests"
 msgstr ""
 
@@ -3117,7 +3111,7 @@
 msgstr ""
 
 #: kallithea/templates/admin/notifications/show_notification.html:9
-#: kallithea/templates/base/base.html:342
+#: kallithea/templates/base/base.html:430
 msgid "Notifications"
 msgstr ""
 
@@ -3318,7 +3312,7 @@
 #: kallithea/templates/admin/repos/repo_edit.html:40
 #: kallithea/templates/admin/settings/settings.html:11
 #: kallithea/templates/admin/user_groups/user_group_edit.html:29
-#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:151
+#: kallithea/templates/base/base.html:67 kallithea/templates/base/base.html:148
 #: kallithea/templates/data_table/_dt_elements.html:45
 #: kallithea/templates/data_table/_dt_elements.html:49
 msgid "Settings"
@@ -3590,6 +3584,11 @@
 msgid "Unlock Repository"
 msgstr "公開的版本庫"
 
+#: kallithea/templates/admin/repos/repo_edit_advanced.html:56
+#, python-format
+msgid "Locked by %s on %s"
+msgstr ""
+
 #: kallithea/templates/admin/repos/repo_edit_advanced.html:60
 #, fuzzy
 msgid "Confirm to lock repository."
@@ -3649,11 +3648,6 @@
 msgid "Invalidate Repository Cache"
 msgstr "確認廢止版本庫快取"
 
-#: kallithea/templates/admin/repos/repo_edit_caches.html:4
-#, fuzzy
-msgid "Confirm to invalidate repository cache."
-msgstr "確認廢止版本庫快取"
-
 #: kallithea/templates/admin/repos/repo_edit_caches.html:7
 msgid ""
 "Manually invalidate cache for this repository. On first access, the "
@@ -4403,21 +4397,17 @@
 msgid "Files"
 msgstr "檔案"
 
-#: kallithea/templates/base/base.html:138
-msgid "Switch To"
-msgstr ""
-
-#: kallithea/templates/base/base.html:145
-#: kallithea/templates/base/base.html:147
+#: kallithea/templates/base/base.html:142
+#: kallithea/templates/base/base.html:144
 msgid "Options"
 msgstr "選項"
 
-#: kallithea/templates/base/base.html:155
+#: kallithea/templates/base/base.html:152
 #: kallithea/templates/forks/forks_data.html:21
 msgid "Compare Fork"
 msgstr ""
 
-#: kallithea/templates/base/base.html:157
+#: kallithea/templates/base/base.html:154
 #: kallithea/templates/bookmarks/bookmarks.html:56
 #: kallithea/templates/bookmarks/bookmarks_data.html:13
 #: kallithea/templates/branches/branches.html:56
@@ -4427,111 +4417,116 @@
 msgid "Compare"
 msgstr ""
 
-#: kallithea/templates/base/base.html:159
-#: kallithea/templates/base/base.html:247
+#: kallithea/templates/base/base.html:156
+#: kallithea/templates/base/base.html:331
 #: kallithea/templates/search/search.html:14
 #: kallithea/templates/search/search.html:54
 msgid "Search"
 msgstr "搜尋"
 
-#: kallithea/templates/base/base.html:163
+#: kallithea/templates/base/base.html:160
 msgid "Unlock"
 msgstr ""
 
-#: kallithea/templates/base/base.html:165
+#: kallithea/templates/base/base.html:162
 msgid "Lock"
 msgstr ""
 
-#: kallithea/templates/base/base.html:173
+#: kallithea/templates/base/base.html:170
 msgid "Follow"
 msgstr ""
 
+#: kallithea/templates/base/base.html:171
+msgid "Unfollow"
+msgstr ""
+
 #: kallithea/templates/base/base.html:174
-msgid "Unfollow"
-msgstr ""
-
-#: kallithea/templates/base/base.html:177
 #: kallithea/templates/data_table/_dt_elements.html:37
 #: kallithea/templates/data_table/_dt_elements.html:41
 #: kallithea/templates/forks/fork.html:9
 msgid "Fork"
 msgstr "分支"
 
-#: kallithea/templates/base/base.html:178
+#: kallithea/templates/base/base.html:175
 #: kallithea/templates/pullrequests/pullrequest.html:88
 msgid "Create Pull Request"
 msgstr ""
 
-#: kallithea/templates/base/base.html:183
+#: kallithea/templates/base/base.html:180
 #, python-format
 msgid "Show Pull Requests for %s"
 msgstr ""
 
-#: kallithea/templates/base/base.html:221
+#: kallithea/templates/base/base.html:193
+msgid "Switch To"
+msgstr ""
+
+#: kallithea/templates/base/base.html:203
+#: kallithea/templates/base/base.html:485
+msgid "No matches found"
+msgstr ""
+
+#: kallithea/templates/base/base.html:305
 msgid "Show recent activity"
 msgstr ""
 
-#: kallithea/templates/base/base.html:227
-#: kallithea/templates/base/base.html:228
+#: kallithea/templates/base/base.html:311
+#: kallithea/templates/base/base.html:312
 msgid "Public journal"
 msgstr "公開日誌"
 
-#: kallithea/templates/base/base.html:233
+#: kallithea/templates/base/base.html:317
 msgid "Show public gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:234
+#: kallithea/templates/base/base.html:318
 msgid "Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:238
+#: kallithea/templates/base/base.html:322
 msgid "All Public Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:240
+#: kallithea/templates/base/base.html:324
 msgid "My Public Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:241
+#: kallithea/templates/base/base.html:325
 msgid "My Private Gists"
 msgstr ""
 
-#: kallithea/templates/base/base.html:246
+#: kallithea/templates/base/base.html:330
 msgid "Search in repositories"
 msgstr ""
 
-#: kallithea/templates/base/base.html:269
-#: kallithea/templates/base/base.html:270
+#: kallithea/templates/base/base.html:353
+#: kallithea/templates/base/base.html:354
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:6
 #: kallithea/templates/pullrequests/pullrequest_show_my.html:10
 msgid "My Pull Requests"
 msgstr ""
 
-#: kallithea/templates/base/base.html:289
+#: kallithea/templates/base/base.html:377
 msgid "Not Logged In"
 msgstr ""
 
-#: kallithea/templates/base/base.html:296
+#: kallithea/templates/base/base.html:384
 msgid "Login to Your Account"
 msgstr ""
 
-#: kallithea/templates/base/base.html:319
+#: kallithea/templates/base/base.html:407
 msgid "Forgot password ?"
 msgstr "忘記密碼?"
 
-#: kallithea/templates/base/base.html:346
+#: kallithea/templates/base/base.html:434
 msgid "Log Out"
 msgstr "登出"
 
-#: kallithea/templates/base/base.html:395
-msgid "No matches found"
-msgstr ""
-
-#: kallithea/templates/base/base.html:524
+#: kallithea/templates/base/base.html:615
 msgid "Keyboard shortcuts"
 msgstr ""
 
-#: kallithea/templates/base/base.html:533
+#: kallithea/templates/base/base.html:624
 msgid "Site-wide shortcuts"
 msgstr ""
 
@@ -4650,6 +4645,7 @@
 
 #: kallithea/templates/base/root.html:35
 #: kallithea/templates/changeset/diff_block.html:8
+#: kallithea/templates/changeset/diff_block.html:21
 #, fuzzy
 msgid "Collapse Diff"
 msgstr "檔案差異"
@@ -4760,51 +4756,54 @@
 #: kallithea/templates/changelog/changelog_summary_data.html:20
 #, python-format
 msgid ""
-"Changeset status: %s\n"
+"Changeset status: %s by %s\n"
 "Click to open associated pull request %s"
 msgstr ""
 
 #: kallithea/templates/changelog/changelog.html:96
-#: kallithea/templates/compare/compare_cs.html:24
-#, python-format
-msgid "Changeset status: %s"
-msgstr ""
-
-#: kallithea/templates/changelog/changelog.html:115
+#: kallithea/templates/changelog/changelog_summary_data.html:24
+#, fuzzy, python-format
+#| msgid "Set changeset status"
+msgid "Changeset status: %s by %s"
+msgstr "尚未有任何變更"
+
+#: kallithea/templates/changelog/changelog.html:116
 #: kallithea/templates/compare/compare_cs.html:63
 msgid "Expand commit message"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:124
+#: kallithea/templates/changelog/changelog.html:125
 #: kallithea/templates/compare/compare_cs.html:30
 msgid "Changeset has comments"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:134
-#: kallithea/templates/changelog/changelog_summary_data.html:54
+#: kallithea/templates/changelog/changelog.html:135
+#: kallithea/templates/changelog/changelog_summary_data.html:57
 #: kallithea/templates/changeset/changeset.html:94
 #: kallithea/templates/changeset/changeset_range.html:92
 #, python-format
 msgid "Bookmark %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:140
-#: kallithea/templates/changelog/changelog_summary_data.html:60
+#: kallithea/templates/changelog/changelog.html:141
+#: kallithea/templates/changelog/changelog_summary_data.html:63
 #: kallithea/templates/changeset/changeset.html:101
 #: kallithea/templates/changeset/changeset_range.html:98
+#: kallithea/templates/compare/compare_cs.html:69
+#: kallithea/templates/pullrequests/pullrequest_show.html:203
 #, python-format
 msgid "Tag %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:145
-#: kallithea/templates/changelog/changelog_summary_data.html:65
+#: kallithea/templates/changelog/changelog.html:146
+#: kallithea/templates/changelog/changelog_summary_data.html:68
 #: kallithea/templates/changeset/changeset.html:106
 #: kallithea/templates/changeset/changeset_range.html:102
 #, python-format
 msgid "Branch %s"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog.html:310
+#: kallithea/templates/changelog/changelog.html:311
 msgid "There are no changes yet"
 msgstr "尚未有任何變更"
 
@@ -4820,7 +4819,7 @@
 
 #: kallithea/templates/changelog/changelog_details.html:6
 #: kallithea/templates/changeset/changeset.html:79
-#: kallithea/templates/changeset/diff_block.html:79
+#: kallithea/templates/changeset/diff_block.html:47
 msgid "Added"
 msgstr ""
 
@@ -4850,22 +4849,22 @@
 msgid "Refs"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:81
+#: kallithea/templates/changelog/changelog_summary_data.html:84
 msgid "Add or upload files directly via Kallithea"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:84
+#: kallithea/templates/changelog/changelog_summary_data.html:87
 #: kallithea/templates/files/files_add.html:21
 #: kallithea/templates/files/files_ypjax.html:9
 msgid "Add New File"
 msgstr ""
 
-#: kallithea/templates/changelog/changelog_summary_data.html:90
+#: kallithea/templates/changelog/changelog_summary_data.html:93
 #, fuzzy
 msgid "Push new repository"
 msgstr "私有版本庫"
 
-#: kallithea/templates/changelog/changelog_summary_data.html:98
+#: kallithea/templates/changelog/changelog_summary_data.html:101
 msgid "Existing repository?"
 msgstr ""
 
@@ -4883,13 +4882,13 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:50
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #: kallithea/templates/changeset/changeset_range.html:48
 msgid "Changeset status"
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:54
-#: kallithea/templates/changeset/diff_block.html:27
+#: kallithea/templates/changeset/diff_block.html:72
 #: kallithea/templates/files/diff_2way.html:49
 msgid "Raw diff"
 msgstr ""
@@ -4899,7 +4898,7 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:60
-#: kallithea/templates/changeset/diff_block.html:30
+#: kallithea/templates/changeset/diff_block.html:75
 #: kallithea/templates/files/diff_2way.html:52
 msgid "Download diff"
 msgstr ""
@@ -4927,16 +4926,16 @@
 msgstr ""
 
 #: kallithea/templates/changeset/changeset.html:166
-#: kallithea/templates/compare/compare_diff.html:54
-#: kallithea/templates/pullrequests/pullrequest_show.html:318
+#: kallithea/templates/compare/compare_diff.html:60
+#: kallithea/templates/pullrequests/pullrequest_show.html:329
 #, python-format
 msgid "%s file changed"
 msgid_plural "%s files changed"
 msgstr[0] ""
 
 #: kallithea/templates/changeset/changeset.html:168
-#: kallithea/templates/compare/compare_diff.html:56
-#: kallithea/templates/pullrequests/pullrequest_show.html:320
+#: kallithea/templates/compare/compare_diff.html:62
+#: kallithea/templates/pullrequests/pullrequest_show.html:331
 #, python-format
 msgid "%s file changed with %s insertions and %s deletions"
 msgid_plural "%s files changed with %s insertions and %s deletions"
@@ -4944,13 +4943,13 @@
 
 #: kallithea/templates/changeset/changeset.html:182
 #: kallithea/templates/changeset/changeset.html:195
-#: kallithea/templates/pullrequests/pullrequest_show.html:339
-#: kallithea/templates/pullrequests/pullrequest_show.html:363
+#: kallithea/templates/pullrequests/pullrequest_show.html:350
+#: kallithea/templates/pullrequests/pullrequest_show.html:372
 msgid "Show full diff anyway"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset.html:247
-#: kallithea/templates/changeset/changeset.html:284
+#: kallithea/templates/changeset/changeset.html:231
+#: kallithea/templates/changeset/changeset.html:268
 #, fuzzy
 msgid "No revisions"
 msgstr "修訂"
@@ -4969,101 +4968,87 @@
 msgid "on this changeset"
 msgstr "沒有修改"
 
-#: kallithea/templates/changeset/changeset_file_comment.html:30
+#: kallithea/templates/changeset/changeset_file_comment.html:31
 #, fuzzy
 msgid "Delete comment?"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:37
+#: kallithea/templates/changeset/changeset_file_comment.html:39
 #, fuzzy
 msgid "Status change"
 msgstr "多個檔案修改"
 
 #: kallithea/templates/changeset/changeset_file_comment.html:59
-msgid "Commenting on line {1}."
+msgid "Commenting on line."
 msgstr ""
 
 #: kallithea/templates/changeset/changeset_file_comment.html:60
-#: kallithea/templates/changeset/changeset_file_comment.html:148
-#, python-format
-msgid "Comments parsed using %s syntax with %s support."
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:62
-msgid "Use @username inside this text to notify another user"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:72
-#: kallithea/templates/changeset/changeset_file_comment.html:184
-msgid "Comment preview"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:77
+msgid ""
+"Comments are in plain text. Use @username inside this text to notify "
+"another user."
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:67
+#, fuzzy
+msgid "Set changeset status"
+msgstr "尚未有任何變更"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:69
+msgid "Vote for pull request status"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:75
+#, fuzzy
+msgid "No change"
+msgstr "沒有修改"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:88
+#, fuzzy
+msgid "Finish pull request"
+msgstr "文件內容"
+
+#: kallithea/templates/changeset/changeset_file_comment.html:91
+msgid "Close"
+msgstr ""
+
+#: kallithea/templates/changeset/changeset_file_comment.html:103
 msgid "Submitting ..."
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:80
-#: kallithea/templates/changeset/changeset_file_comment.html:190
+#: kallithea/templates/changeset/changeset_file_comment.html:104
 msgid "Comment"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:82
-#: kallithea/templates/changeset/changeset_file_comment.html:191
-msgid "Preview"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "You need to be logged in to comment."
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:90
+#: kallithea/templates/changeset/changeset_file_comment.html:112
 msgid "Login now"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:94
+#: kallithea/templates/changeset/changeset_file_comment.html:116
 msgid "Hide"
 msgstr ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:106
+#: kallithea/templates/changeset/changeset_file_comment.html:128
 #, python-format
 msgid "%d comment"
 msgid_plural "%d comments"
 msgstr[0] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:107
+#: kallithea/templates/changeset/changeset_file_comment.html:129
 #, fuzzy, python-format
 msgid "%d inline"
 msgid_plural "%d inline"
 msgstr[0] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:108
+#: kallithea/templates/changeset/changeset_file_comment.html:130
 #, python-format
 msgid "%d general"
 msgid_plural "%d general"
 msgstr[0] ""
 
-#: kallithea/templates/changeset/changeset_file_comment.html:150
-msgid "Use @username inside this text to notify another user."
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:157
-msgid "Vote for pull request status"
-msgstr ""
-
-#: kallithea/templates/changeset/changeset_file_comment.html:159
-#, fuzzy
-msgid "Set changeset status"
-msgstr "尚未有任何變更"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:163
-#, fuzzy
-msgid "No change"
-msgstr "沒有修改"
-
-#: kallithea/templates/changeset/changeset_file_comment.html:176
-msgid "Close"
-msgstr ""
-
 #: kallithea/templates/changeset/changeset_range.html:5
 #, python-format
 msgid "%s Changesets"
@@ -5073,31 +5058,30 @@
 msgid "Files affected"
 msgstr ""
 
-#: kallithea/templates/changeset/diff_block.html:21
-#: kallithea/templates/files/diff_2way.html:43
-msgid "Show full diff for this file"
-msgstr ""
-
-#: kallithea/templates/changeset/diff_block.html:24
-#: kallithea/templates/changeset/diff_block.html:98
-#: kallithea/templates/files/diff_2way.html:46
-msgid "Show full side-by-side diff for this file"
-msgstr ""
-
-#: kallithea/templates/changeset/diff_block.html:38
-msgid "Show inline comments"
-msgstr ""
-
-#: kallithea/templates/changeset/diff_block.html:86
+#: kallithea/templates/changeset/diff_block.html:54
 #, fuzzy
 msgid "Deleted"
 msgstr "刪除"
 
-#: kallithea/templates/changeset/diff_block.html:89
+#: kallithea/templates/changeset/diff_block.html:57
 #, fuzzy
 msgid "Renamed"
 msgstr "讀"
 
+#: kallithea/templates/changeset/diff_block.html:66
+#: kallithea/templates/files/diff_2way.html:43
+msgid "Show full diff for this file"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:69
+#: kallithea/templates/files/diff_2way.html:46
+msgid "Show full side-by-side diff for this file"
+msgstr ""
+
+#: kallithea/templates/changeset/diff_block.html:83
+msgid "Show inline comments"
+msgstr ""
+
 #: kallithea/templates/compare/compare_cs.html:4
 msgid "No changesets"
 msgstr ""
@@ -5106,6 +5090,11 @@
 msgid "Ancestor"
 msgstr ""
 
+#: kallithea/templates/compare/compare_cs.html:24
+#, python-format
+msgid "Changeset status: %s"
+msgstr ""
+
 #: kallithea/templates/compare/compare_cs.html:44
 msgid "First (oldest) changeset in this list"
 msgstr ""
@@ -5118,29 +5107,29 @@
 msgid "Position in this list of changesets"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:76
+#: kallithea/templates/compare/compare_cs.html:85
 msgid "Show merge diff"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:86
-#: kallithea/templates/pullrequests/pullrequest_show.html:310
+#: kallithea/templates/compare/compare_cs.html:95
+#: kallithea/templates/pullrequests/pullrequest_show.html:321
 msgid "Common ancestor"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:90
-msgid "No common ancestor found - repositories are unrelated"
-msgstr ""
-
-#: kallithea/templates/compare/compare_cs.html:98
-msgid "is"
-msgstr ""
-
 #: kallithea/templates/compare/compare_cs.html:99
+msgid "No common ancestor found - repositories are unrelated"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:107
+msgid "is"
+msgstr ""
+
+#: kallithea/templates/compare/compare_cs.html:108
 #, fuzzy, python-format
 msgid "%s changesets"
 msgstr ""
 
-#: kallithea/templates/compare/compare_cs.html:100
+#: kallithea/templates/compare/compare_cs.html:109
 #, fuzzy
 msgid "behind"
 msgstr "重新索引"
@@ -5152,27 +5141,27 @@
 msgstr ""
 
 #: kallithea/templates/compare/compare_diff.html:13
-#: kallithea/templates/compare/compare_diff.html:35
+#: kallithea/templates/compare/compare_diff.html:41
 msgid "Compare Revisions"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:33
+#: kallithea/templates/compare/compare_diff.html:39
 msgid "Swap"
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:42
+#: kallithea/templates/compare/compare_diff.html:48
 msgid "Compare revisions, branches, bookmarks, or tags."
 msgstr ""
 
-#: kallithea/templates/compare/compare_diff.html:47
-#: kallithea/templates/pullrequests/pullrequest_show.html:305
+#: kallithea/templates/compare/compare_diff.html:53
+#: kallithea/templates/pullrequests/pullrequest_show.html:316
 #, python-format
 msgid "Showing %s commit"
 msgid_plural "Showing %s commits"
 msgstr[0] ""
 
-#: kallithea/templates/compare/compare_diff.html:78
-#: kallithea/templates/compare/compare_diff.html:89
+#: kallithea/templates/compare/compare_diff.html:84
+#: kallithea/templates/compare/compare_diff.html:93
 msgid "Show full diff"
 msgstr ""
 
@@ -5231,17 +5220,23 @@
 msgid "We have received a request to reset the password for your account."
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:7
-msgid "To set a new password, click the following link"
+#: kallithea/templates/email_templates/password_reset.html:8
+msgid ""
+"This account is however managed outside this system and the password "
+"cannot be changed here."
 msgstr ""
 
 #: kallithea/templates/email_templates/password_reset.html:10
+msgid "To set a new password, click the following link"
+msgstr ""
+
+#: kallithea/templates/email_templates/password_reset.html:13
 msgid ""
 "Should you not be able to use the link above, please type the following "
 "code into the password reset form"
 msgstr ""
 
-#: kallithea/templates/email_templates/password_reset.html:12
+#: kallithea/templates/email_templates/password_reset.html:16
 msgid ""
 "If it weren't you who requested the password reset, just disregard this "
 "message."
@@ -5324,8 +5319,9 @@
 msgstr ""
 
 #: kallithea/templates/files/files_add.html:53
-msgid "New file mode"
-msgstr ""
+#, fuzzy
+msgid "New file type"
+msgstr "未知的存檔類型"
 
 #: kallithea/templates/files/files_add.html:64
 #: kallithea/templates/files/files_delete.html:43
@@ -5457,10 +5453,19 @@
 msgid "Binary file (%s)"
 msgstr "二進位檔 (%s)"
 
-#: kallithea/templates/files/files_source.html:73
-msgid "File is too big to display"
+#: kallithea/templates/files/files_source.html:74
+#, fuzzy
+msgid "File is too big to display."
 msgstr "顯示的檔案太大"
 
+#: kallithea/templates/files/files_source.html:76
+msgid "Show full annotation anyway."
+msgstr ""
+
+#: kallithea/templates/files/files_source.html:78
+msgid "Show as raw."
+msgstr ""
+
 #: kallithea/templates/files/files_ypjax.html:5
 msgid "annotation"
 msgstr ""
@@ -5725,42 +5730,48 @@
 msgid "Current revision - no change"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:213
+#: kallithea/templates/pullrequests/pullrequest_show.html:215
+msgid ""
+"Pull requests do not change once created. Select a revision and save to "
+"replace this pull request with a new one."
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:224
 msgid "Pull Request Reviewers"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:238
+#: kallithea/templates/pullrequests/pullrequest_show.html:249
 #, fuzzy
 msgid "Remove reviewer"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:250
-msgid "Type name of reviewer to add"
-msgstr ""
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:258
-#, fuzzy
-msgid "Potential Reviewers"
-msgstr ""
-
 #: kallithea/templates/pullrequests/pullrequest_show.html:261
+msgid "Type name of reviewer to add"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:269
+#, fuzzy
+msgid "Potential Reviewers"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:272
 msgid "Click to add the repository owner as reviewer:"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:284
+#: kallithea/templates/pullrequests/pullrequest_show.html:295
 msgid "Save Changes"
 msgstr ""
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:285
-msgid "Save as New Pull Request"
-msgstr ""
-
-#: kallithea/templates/pullrequests/pullrequest_show.html:286
+#: kallithea/templates/pullrequests/pullrequest_show.html:296
+msgid "Save Updates as New Pull Request"
+msgstr ""
+
+#: kallithea/templates/pullrequests/pullrequest_show.html:297
 #, fuzzy
 msgid "Cancel Changes"
 msgstr "沒有修改"
 
-#: kallithea/templates/pullrequests/pullrequest_show.html:296
+#: kallithea/templates/pullrequests/pullrequest_show.html:307
 #, fuzzy
 msgid "Pull Request Content"
 msgstr "文件內容"
@@ -5771,9 +5782,9 @@
 msgstr ""
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:11
-#, python-format
-msgid "Pull Requests from %s'"
-msgstr ""
+#, fuzzy, python-format
+msgid "Pull Requests from '%s'"
+msgstr "文件內容"
 
 #: kallithea/templates/pullrequests/pullrequest_show_all.html:13
 #, python-format
@@ -6325,27 +6336,6 @@
 #~ msgid "with subrepos"
 #~ msgstr ""
 
-#~ msgid ""
-#~ "Your password reset was successful, new"
-#~ " password has been sent to your "
-#~ "email"
-#~ msgstr "您的密碼重設動作已完成,新的密碼已寄至您的信箱"
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " changeset %(short_id)s on %(branch)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Added by %(pr_username)s] %(repo_name)s pull"
-#~ " request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
-#~ msgid ""
-#~ "[Comment from %(comment_username)s] %(repo_name)s"
-#~ " pull request %(pr_nice_id)s from %(ref)s"
-#~ msgstr ""
-
 #~ msgid "Your new password"
 #~ msgstr ""
 
@@ -6373,3 +6363,47 @@
 #~ msgid "Created by"
 #~ msgstr ""
 
+#~ msgid "You can only delete files with revision being a valid branch "
+#~ msgstr ""
+
+#~ msgid "You can only edit files with revision being a valid branch "
+#~ msgstr ""
+
+#~ msgid "This pull request can be updated with changes on %s:"
+#~ msgstr ""
+
+#~ msgid "Confirm to invalidate repository cache."
+#~ msgstr "確認廢止版本庫快取"
+
+#~ msgid "Commenting on line {1}."
+#~ msgstr ""
+
+#~ msgid "Comments parsed using %s syntax with %s support."
+#~ msgstr ""
+
+#~ msgid "Use @username inside this text to notify another user"
+#~ msgstr ""
+
+#~ msgid "Comment preview"
+#~ msgstr ""
+
+#~ msgid "Preview"
+#~ msgstr ""
+
+#~ msgid "Use @username inside this text to notify another user."
+#~ msgstr ""
+
+#~ msgid "New file mode"
+#~ msgstr ""
+
+#~ msgid "Save as New Pull Request"
+#~ msgstr ""
+
+#~ msgid "Pull Requests from %s'"
+#~ msgstr ""
+
+#~ msgid ""
+#~ "Changeset status: %s\n"
+#~ "Click to open associated pull request %s"
+#~ msgstr ""
+
--- a/kallithea/lib/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/__init__.py	Fri Nov 18 01:11:13 2016 +0100
@@ -24,30 +24,3 @@
 :copyright: (c) 2013 RhodeCode GmbH, and others.
 :license: GPLv3, see LICENSE.md for more details.
 """
-
-import os
-
-def get_current_revision(quiet=False):
-    """
-    Returns tuple of (number, id) from repository containing this package
-    or None if repository could not be found.
-
-    :param quiet: prints error for fetching revision if True
-    """
-
-    try:
-        from kallithea.lib.vcs import get_repo
-        from kallithea.lib.vcs.utils.helpers import get_scm
-        repopath = os.path.abspath(os.path.join(os.path.dirname(__file__),
-                                                '..', '..'))
-        scm = get_scm(repopath)[0]
-        repo = get_repo(path=repopath, alias=scm)
-        wk_dir = repo.workdir
-        cur_rev = wk_dir.get_changeset()
-        return (cur_rev.revision, cur_rev.short_id)
-    except Exception as err:
-        if not quiet:
-            print ("WARNING: Cannot retrieve kallithea's revision. "
-                   "disregard this if you don't know what that means. "
-                   "Original error was: %s" % err)
-        return None
--- a/kallithea/lib/annotate.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/annotate.py	Fri Nov 18 01:11:13 2016 +0100
@@ -48,7 +48,7 @@
     :param headers: dictionary with headers (keys are whats in ``order``
       parameter)
     """
-    from kallithea.lib.utils import get_custom_lexer
+    from kallithea.lib.pygmentsutils import get_custom_lexer
     options['linenos'] = True
     formatter = AnnotateHtmlFormatter(filenode=filenode, order=order,
         headers=headers,
@@ -68,7 +68,7 @@
         following function as ``annotate_from_changeset_func``::
 
             def changeset_to_anchor(changeset):
-                return '<a href="/changesets/%s/">%s</a>\n' %\
+                return '<a href="/changesets/%s/">%s</a>\n' % \
                        (changeset.id, changeset.id)
 
         :param annotate_from_changeset_func: see above
--- a/kallithea/lib/auth.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/auth.py	Fri Nov 18 01:11:13 2016 +0100
@@ -34,15 +34,16 @@
 
 from decorator import decorator
 
-from pylons import url, request, session
-from pylons.controllers.util import abort, redirect
+from pylons import request, session
 from pylons.i18n.translation import _
 from webhelpers.pylonslib import secure_form
 from sqlalchemy import or_
 from sqlalchemy.orm.exc import ObjectDeletedError
 from sqlalchemy.orm import joinedload
+from webob.exc import HTTPFound, HTTPBadRequest, HTTPForbidden, HTTPMethodNotAllowed
 
 from kallithea import __platform__, is_windows, is_unix
+from kallithea.config.routing import url
 from kallithea.lib.vcs.utils.lazy import LazyProperty
 from kallithea.model import meta
 from kallithea.model.meta import Session
@@ -52,7 +53,7 @@
     RepoGroup, UserGroupRepoGroupToPerm, UserIpMap, UserGroupUserGroupToPerm, \
     UserGroup, UserApiKeys
 
-from kallithea.lib.utils2 import safe_unicode, aslist
+from kallithea.lib.utils2 import safe_str, safe_unicode, aslist
 from kallithea.lib.utils import get_repo_slug, get_repo_group_slug, \
     get_user_group_slug, conditional_cache
 from kallithea.lib.caching_query import FromCache
@@ -93,52 +94,40 @@
         return ''.join(l)
 
 
-class KallitheaCrypto(object):
-
-    @classmethod
-    def hash_string(cls, str_):
-        """
-        Cryptographic function used for password hashing based on pybcrypt
-        or Python's own OpenSSL wrapper on windows
-
-        :param password: password to hash
-        """
-        if is_windows:
-            return hashlib.sha256(str_).hexdigest()
-        elif is_unix:
-            import bcrypt
-            return bcrypt.hashpw(str_, bcrypt.gensalt(10))
-        else:
-            raise Exception('Unknown or unsupported platform %s' \
-                            % __platform__)
+def get_crypt_password(password):
+    """
+    Cryptographic function used for password hashing based on pybcrypt
+    or Python's own OpenSSL wrapper on windows
 
-    @classmethod
-    def hash_check(cls, password, hashed):
-        """
-        Checks matching password with it's hashed value, runs different
-        implementation based on platform it runs on
-
-        :param password: password
-        :param hashed: password in hashed form
-        """
-
-        if is_windows:
-            return hashlib.sha256(password).hexdigest() == hashed
-        elif is_unix:
-            import bcrypt
-            return bcrypt.hashpw(password, hashed) == hashed
-        else:
-            raise Exception('Unknown or unsupported platform %s' \
-                            % __platform__)
-
-
-def get_crypt_password(password):
-    return KallitheaCrypto.hash_string(password)
+    :param password: password to hash
+    """
+    if is_windows:
+        return hashlib.sha256(password).hexdigest()
+    elif is_unix:
+        import bcrypt
+        return bcrypt.hashpw(safe_str(password), bcrypt.gensalt(10))
+    else:
+        raise Exception('Unknown or unsupported platform %s' \
+                        % __platform__)
 
 
 def check_password(password, hashed):
-    return KallitheaCrypto.hash_check(password, hashed)
+    """
+    Checks matching password with it's hashed value, runs different
+    implementation based on platform it runs on
+
+    :param password: password
+    :param hashed: password in hashed form
+    """
 
+    if is_windows:
+        return hashlib.sha256(password).hexdigest() == hashed
+    elif is_unix:
+        import bcrypt
+        return bcrypt.checkpw(safe_str(password), safe_str(hashed))
+    else:
+        raise Exception('Unknown or unsupported platform %s' \
+                        % __platform__)
 
 
 def _cached_perms_data(user_id, user_is_admin, user_inherit_default_permissions,
@@ -204,8 +193,8 @@
     #==================================================================
 
     # default global permissions taken from the default user
-    default_global_perms = UserToPerm.query()\
-        .filter(UserToPerm.user_id == default_user_id)\
+    default_global_perms = UserToPerm.query() \
+        .filter(UserToPerm.user_id == default_user_id) \
         .options(joinedload(UserToPerm.permission))
 
     for perm in default_global_perms:
@@ -214,10 +203,10 @@
     # defaults for repositories, taken from default user
     for perm in default_repo_perms:
         r_k = perm.UserRepoToPerm.repository.repo_name
-        if perm.Repository.private and not (perm.Repository.user_id == user_id):
+        if perm.Repository.private and not (perm.Repository.owner_id == user_id):
             # disable defaults for private repos,
             p = 'repository.none'
-        elif perm.Repository.user_id == user_id:
+        elif perm.Repository.owner_id == user_id:
             # set admin if owner
             p = 'repository.admin'
         else:
@@ -251,15 +240,15 @@
 
     # USER GROUPS comes first
     # user group global permissions
-    user_perms_from_users_groups = Session().query(UserGroupToPerm)\
-        .options(joinedload(UserGroupToPerm.permission))\
+    user_perms_from_users_groups = Session().query(UserGroupToPerm) \
+        .options(joinedload(UserGroupToPerm.permission)) \
         .join((UserGroupMember, UserGroupToPerm.users_group_id ==
-               UserGroupMember.users_group_id))\
-        .filter(UserGroupMember.user_id == user_id)\
+               UserGroupMember.users_group_id)) \
+        .filter(UserGroupMember.user_id == user_id) \
         .join((UserGroup, UserGroupMember.users_group_id ==
-               UserGroup.users_group_id))\
-        .filter(UserGroup.users_group_active == True)\
-        .order_by(UserGroupToPerm.users_group_id)\
+               UserGroup.users_group_id)) \
+        .filter(UserGroup.users_group_active == True) \
+        .order_by(UserGroupToPerm.users_group_id) \
         .all()
     # need to group here by groups since user can be in more than
     # one group
@@ -273,20 +262,20 @@
         if not gr.inherit_default_permissions:
             # NEED TO IGNORE all configurable permissions and
             # replace them with explicitly set
-            permissions[GLOBAL] = permissions[GLOBAL]\
+            permissions[GLOBAL] = permissions[GLOBAL] \
                                             .difference(_configurable)
         for perm in perms:
             permissions[GLOBAL].add(perm.permission.permission_name)
 
     # user specific global permissions
-    user_perms = Session().query(UserToPerm)\
-            .options(joinedload(UserToPerm.permission))\
+    user_perms = Session().query(UserToPerm) \
+            .options(joinedload(UserToPerm.permission)) \
             .filter(UserToPerm.user_id == user_id).all()
 
     if not user_inherit_default_permissions:
         # NEED TO IGNORE all configurable permissions and
         # replace them with explicitly set
-        permissions[GLOBAL] = permissions[GLOBAL]\
+        permissions[GLOBAL] = permissions[GLOBAL] \
                                         .difference(_configurable)
 
         for perm in user_perms:
@@ -304,17 +293,17 @@
 
     # user group for repositories permissions
     user_repo_perms_from_users_groups = \
-     Session().query(UserGroupRepoToPerm, Permission, Repository,)\
+     Session().query(UserGroupRepoToPerm, Permission, Repository,) \
         .join((Repository, UserGroupRepoToPerm.repository_id ==
-               Repository.repo_id))\
+               Repository.repo_id)) \
         .join((Permission, UserGroupRepoToPerm.permission_id ==
-               Permission.permission_id))\
+               Permission.permission_id)) \
         .join((UserGroup, UserGroupRepoToPerm.users_group_id ==
-               UserGroup.users_group_id))\
-        .filter(UserGroup.users_group_active == True)\
+               UserGroup.users_group_id)) \
+        .filter(UserGroup.users_group_active == True) \
         .join((UserGroupMember, UserGroupRepoToPerm.users_group_id ==
-               UserGroupMember.users_group_id))\
-        .filter(UserGroupMember.user_id == user_id)\
+               UserGroupMember.users_group_id)) \
+        .filter(UserGroupMember.user_id == user_id) \
         .all()
 
     multiple_counter = collections.defaultdict(int)
@@ -324,7 +313,7 @@
         p = perm.Permission.permission_name
         cur_perm = permissions[RK][r_k]
 
-        if perm.Repository.user_id == user_id:
+        if perm.Repository.owner_id == user_id:
             # set admin if owner
             p = 'repository.admin'
         else:
@@ -339,7 +328,7 @@
         r_k = perm.UserRepoToPerm.repository.repo_name
         cur_perm = permissions[RK][r_k]
         # set admin if owner
-        if perm.Repository.user_id == user_id:
+        if perm.Repository.owner_id == user_id:
             p = 'repository.admin'
         else:
             p = perm.Permission.permission_name
@@ -357,16 +346,16 @@
     #======================================================================
     # user group for repo groups permissions
     user_repo_group_perms_from_users_groups = \
-     Session().query(UserGroupRepoGroupToPerm, Permission, RepoGroup)\
-     .join((RepoGroup, UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id))\
+     Session().query(UserGroupRepoGroupToPerm, Permission, RepoGroup) \
+     .join((RepoGroup, UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)) \
      .join((Permission, UserGroupRepoGroupToPerm.permission_id
-            == Permission.permission_id))\
+            == Permission.permission_id)) \
      .join((UserGroup, UserGroupRepoGroupToPerm.users_group_id ==
-            UserGroup.users_group_id))\
-     .filter(UserGroup.users_group_active == True)\
+            UserGroup.users_group_id)) \
+     .filter(UserGroup.users_group_active == True) \
      .join((UserGroupMember, UserGroupRepoGroupToPerm.users_group_id
-            == UserGroupMember.users_group_id))\
-     .filter(UserGroupMember.user_id == user_id)\
+            == UserGroupMember.users_group_id)) \
+     .filter(UserGroupMember.user_id == user_id) \
      .all()
 
     multiple_counter = collections.defaultdict(int)
@@ -394,17 +383,17 @@
     #======================================================================
     # user group for user group permissions
     user_group_user_groups_perms = \
-     Session().query(UserGroupUserGroupToPerm, Permission, UserGroup)\
+     Session().query(UserGroupUserGroupToPerm, Permission, UserGroup) \
      .join((UserGroup, UserGroupUserGroupToPerm.target_user_group_id
-            == UserGroup.users_group_id))\
+            == UserGroup.users_group_id)) \
      .join((Permission, UserGroupUserGroupToPerm.permission_id
-            == Permission.permission_id))\
+            == Permission.permission_id)) \
      .join((UserGroupMember, UserGroupUserGroupToPerm.user_group_id
-            == UserGroupMember.users_group_id))\
-     .filter(UserGroupMember.user_id == user_id)\
+            == UserGroupMember.users_group_id)) \
+     .filter(UserGroupMember.user_id == user_id) \
      .join((UserGroup, UserGroupMember.users_group_id ==
-            UserGroup.users_group_id), aliased=True, from_joinpoint=True)\
-     .filter(UserGroup.users_group_active == True)\
+            UserGroup.users_group_id), aliased=True, from_joinpoint=True) \
+     .filter(UserGroup.users_group_active == True) \
      .all()
 
     multiple_counter = collections.defaultdict(int)
@@ -465,8 +454,7 @@
     access to Kallithea is enabled, the default user is loaded instead.
 
     `AuthUser` does not by itself authenticate users and the constructor
-    sets the `is_authenticated` field to False, except when falling back
-    to the default anonymous user (if enabled). It's up to other parts
+    sets the `is_authenticated` field to False. It's up to other parts
     of the code to check e.g. if a supplied password is correct, and if
     so, set `is_authenticated` to True.
 
@@ -482,7 +470,7 @@
         user_model = UserModel()
         self.anonymous_user = User.get_default_user(cache=True)
 
-        # These attributes will be overriden by fill_data, below, unless the
+        # These attributes will be overridden by fill_data, below, unless the
         # requested user cannot be found and the default anonymous user is
         # not enabled.
         self.user_id = None
@@ -508,9 +496,7 @@
         if not is_user_loaded:
             is_user_loaded =  self._fill_data(self.anonymous_user)
 
-        # The anonymous user is always "logged in".
-        if self.user_id == self.anonymous_user.user_id:
-            self.is_authenticated = True
+        self.is_default_user = (self.user_id == self.anonymous_user.user_id)
 
         if not self.username:
             self.username = 'None'
@@ -569,8 +555,8 @@
 
     def _get_api_keys(self):
         api_keys = [self.api_key]
-        for api_key in UserApiKeys.query()\
-                .filter(UserApiKeys.user_id == self.user_id)\
+        for api_key in UserApiKeys.query() \
+                .filter(UserApiKeys.user_id == self.user_id) \
                 .filter(or_(UserApiKeys.expires == -1,
                             UserApiKeys.expires >= time.time())).all():
             api_keys.append(api_key.api_key)
@@ -622,18 +608,13 @@
             return False
 
     def __repr__(self):
-        return "<AuthUser('id:%s[%s] auth:%s')>"\
-            % (self.user_id, self.username, self.is_authenticated)
-
-    def set_authenticated(self, authenticated=True):
-        if self.user_id != self.anonymous_user.user_id:
-            self.is_authenticated = authenticated
+        return "<AuthUser('id:%s[%s] auth:%s')>" \
+            % (self.user_id, self.username, (self.is_authenticated or self.is_default_user))
 
     def to_cookie(self):
         """ Serializes this login session to a cookie `dict`. """
         return {
             'user_id': self.user_id,
-            'is_authenticated': self.is_authenticated,
             'is_external_auth': self.is_external_auth,
         }
 
@@ -647,9 +628,7 @@
             user_id=cookie.get('user_id'),
             is_external_auth=cookie.get('is_external_auth', False),
         )
-        if not au.is_authenticated and au.user_id is not None:
-            # user is not authenticated and not empty
-            au.set_authenticated(cookie.get('is_authenticated'))
+        au.is_authenticated = True
         return au
 
     @classmethod
@@ -689,12 +668,12 @@
 
 def set_available_permissions(config):
     """
-    This function will propagate pylons globals with all available defined
+    This function will propagate globals with all available defined
     permission given in db. We don't want to check each time from db for new
     permissions since adding a new permission also requires application restart
     ie. to decorate new views with the newly created permission
 
-    :param config: current pylons config instance
+    :param config: current config instance
 
     """
     log.info('getting information about all available permissions')
@@ -710,13 +689,16 @@
 # CHECK DECORATORS
 #==============================================================================
 
-def redirect_to_login(message=None):
+def _redirect_to_login(message=None):
+    """Return an exception that must be raised. It will redirect to the login
+    page which will redirect back to the current URL after authentication.
+    The optional message will be shown in a flash message."""
     from kallithea.lib import helpers as h
-    p = request.path_qs
     if message:
         h.flash(h.literal(message), category='warning')
+    p = request.path_qs
     log.debug('Redirecting to login page, origin: %s', p)
-    return redirect(url('login_home', came_from=p))
+    return HTTPFound(location=url('login_home', came_from=p))
 
 
 class LoginRequired(object):
@@ -741,7 +723,7 @@
         log.debug('Checking access for user %s @ %s', user, loc)
 
         if not AuthUser.check_ip_allowed(user, controller.ip_addr):
-            return redirect_to_login(_('IP %s not allowed') % controller.ip_addr)
+            raise _redirect_to_login(_('IP %s not allowed') % controller.ip_addr)
 
         # check if we used an API key and it's a valid one
         api_key = request.GET.get('api_key')
@@ -754,25 +736,20 @@
                     return func(*fargs, **fkwargs)
                 else:
                     log.warning('API key ****%s is NOT valid', api_key[-4:])
-                    return redirect_to_login(_('Invalid API key'))
+                    raise _redirect_to_login(_('Invalid API key'))
             else:
                 # controller does not allow API access
                 log.warning('API access to %s is not allowed', loc)
-                return abort(403)
+                raise HTTPForbidden()
 
-        # Only allow the following HTTP request methods. (We sometimes use POST
-        # requests with a '_method' set to 'PUT' or 'DELETE'; but that is only
-        # used for the route lookup, and does not affect request.method.)
-        if request.method not in ['GET', 'HEAD', 'POST', 'PUT']:
-            return abort(405)
+        # Only allow the following HTTP request methods.
+        if request.method not in ['GET', 'HEAD', 'POST']:
+            raise HTTPMethodNotAllowed()
 
-        # Also verify the _method override. This is only permitted in POST
-        # requests, and can specify PUT or DELETE.
+        # Also verify the _method override - no longer allowed
         _method = request.params.get('_method')
         if _method is None:
             pass # no override, no problem
-        elif request.method == 'POST' and _method.upper() in ['PUT', 'DELETE']:
-            pass # permitted override
         else:
             raise HTTPMethodNotAllowed()
 
@@ -795,22 +772,22 @@
             token = request.POST.get(secure_form.token_key)
             if not token or token != secure_form.authentication_token():
                 log.error('CSRF check failed')
-                return abort(403)
+                raise HTTPForbidden()
 
         # WebOb already ignores request payload parameters for anything other
         # than POST/PUT, but double-check since other Kallithea code relies on
         # this assumption.
         if request.method not in ['POST', 'PUT'] and request.POST:
             log.error('%r request with payload parameters; WebOb should have stopped this', request.method)
-            return abort(400)
+            raise HTTPBadRequest()
 
         # regular user authentication
-        if user.is_authenticated:
+        if user.is_authenticated or user.is_default_user:
             log.info('user %s authenticated with regular auth @ %s', user, loc)
             return func(*fargs, **fkwargs)
         else:
             log.warning('user %s NOT authenticated with regular auth @ %s', user, loc)
-            return redirect_to_login()
+            raise _redirect_to_login()
 
 class NotAnonymous(object):
     """
@@ -826,11 +803,9 @@
 
         log.debug('Checking if user is not anonymous @%s', cls)
 
-        anonymous = self.user.username == User.DEFAULT_USER
-
-        if anonymous:
-            return redirect_to_login(_('You need to be a registered user to '
-                    'perform this action'))
+        if self.user.is_default_user:
+            raise _redirect_to_login(_('You need to be a registered user to '
+                                       'perform this action'))
         else:
             return func(*fargs, **fkwargs)
 
@@ -858,31 +833,16 @@
 
         else:
             log.debug('Permission denied for %s %s', cls, self.user)
-            anonymous = self.user.username == User.DEFAULT_USER
-
-            if anonymous:
-                return redirect_to_login(_('You need to be signed in to view this page'))
+            if self.user.is_default_user:
+                raise _redirect_to_login(_('You need to be signed in to view this page'))
             else:
-                # redirect with forbidden ret code
-                return abort(403)
+                raise HTTPForbidden()
 
     def check_permissions(self):
         """Dummy function for overriding"""
         raise Exception('You have to write this function in child class')
 
 
-class HasPermissionAllDecorator(PermsDecorator):
-    """
-    Checks for access permission for all given predicates. All of them
-    have to be meet in order to fulfill the request
-    """
-
-    def check_permissions(self):
-        if self.required_perms.issubset(self.user_perms.get('global')):
-            return True
-        return False
-
-
 class HasPermissionAnyDecorator(PermsDecorator):
     """
     Checks for access permission for any of given predicates. In order to
@@ -895,23 +855,6 @@
         return False
 
 
-class HasRepoPermissionAllDecorator(PermsDecorator):
-    """
-    Checks for access permission for all given predicates for specific
-    repository. All of them have to be meet in order to fulfill the request
-    """
-
-    def check_permissions(self):
-        repo_name = get_repo_slug(request)
-        try:
-            user_perms = set([self.user_perms['repositories'][repo_name]])
-        except KeyError:
-            return False
-        if self.required_perms.issubset(user_perms):
-            return True
-        return False
-
-
 class HasRepoPermissionAnyDecorator(PermsDecorator):
     """
     Checks for access permission for any of given predicates for specific
@@ -930,24 +873,6 @@
         return False
 
 
-class HasRepoGroupPermissionAllDecorator(PermsDecorator):
-    """
-    Checks for access permission for all given predicates for specific
-    repository group. All of them have to be meet in order to fulfill the request
-    """
-
-    def check_permissions(self):
-        group_name = get_repo_group_slug(request)
-        try:
-            user_perms = set([self.user_perms['repositories_groups'][group_name]])
-        except KeyError:
-            return False
-
-        if self.required_perms.issubset(user_perms):
-            return True
-        return False
-
-
 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
     """
     Checks for access permission for any of given predicates for specific
@@ -966,24 +891,6 @@
         return False
 
 
-class HasUserGroupPermissionAllDecorator(PermsDecorator):
-    """
-    Checks for access permission for all given predicates for specific
-    user group. All of them have to be meet in order to fulfill the request
-    """
-
-    def check_permissions(self):
-        group_name = get_user_group_slug(request)
-        try:
-            user_perms = set([self.user_perms['user_groups'][group_name]])
-        except KeyError:
-            return False
-
-        if self.required_perms.issubset(user_perms):
-            return True
-        return False
-
-
 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
     """
     Checks for access permission for any of given predicates for specific
@@ -1014,53 +921,37 @@
         self.repo_name = None
         self.group_name = None
 
-    def __call__(self, check_location='', user=None):
-        if not user:
-            #TODO: remove this someday,put as user as attribute here
-            user = request.user
+    def __nonzero__(self):
+        """ Defend against accidentally forgetting to call the object
+            and instead evaluating it directly in a boolean context,
+            which could have security implications.
+        """
+        raise AssertionError(self.__class__.__name__ + ' is not a bool and must be called!')
 
-        # init auth user if not already given
-        if not isinstance(user, AuthUser):
-            user = AuthUser(user.user_id)
+    def __call__(self, check_location='unspecified location'):
+        user = request.user
+        assert user
+        assert isinstance(user, AuthUser), user
 
         cls_name = self.__class__.__name__
-        check_scope = {
-            'HasPermissionAll': '',
-            'HasPermissionAny': '',
-            'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
-            'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
-            'HasRepoGroupPermissionAll': 'group:%s' % self.group_name,
-            'HasRepoGroupPermissionAny': 'group:%s' % self.group_name,
-        }.get(cls_name, '?')
+        check_scope = self._scope()
         log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
                   self.required_perms, user, check_scope,
-                  check_location or 'unspecified location')
-        if not user:
-            log.debug('Empty request user')
-            return False
+                  check_location)
         self.user_perms = user.permissions
-        if self.check_permissions():
-            log.debug('Permission to %s granted for user: %s @ %s',
-                      check_scope, user,
-                         check_location or 'unspecified location')
-            return True
 
-        else:
-            log.debug('Permission to %s denied for user: %s @ %s',
-                      check_scope, user,
-                         check_location or 'unspecified location')
-            return False
+        result = self.check_permissions()
+        result_text = 'granted' if result else 'denied'
+        log.debug('Permission to %s %s for user: %s @ %s',
+            check_scope, result_text, user, check_location)
+        return result
 
     def check_permissions(self):
         """Dummy function for overriding"""
         raise Exception('You have to write this function in child class')
 
-
-class HasPermissionAll(PermsFunction):
-    def check_permissions(self):
-        if self.required_perms.issubset(self.user_perms.get('global')):
-            return True
-        return False
+    def _scope(self):
+        return '(unknown scope)'
 
 
 class HasPermissionAny(PermsFunction):
@@ -1069,31 +960,14 @@
             return True
         return False
 
-
-class HasRepoPermissionAll(PermsFunction):
-    def __call__(self, repo_name=None, check_location='', user=None):
-        self.repo_name = repo_name
-        return super(HasRepoPermissionAll, self).__call__(check_location, user)
-
-    def check_permissions(self):
-        if not self.repo_name:
-            self.repo_name = get_repo_slug(request)
-
-        try:
-            self._user_perms = set(
-                [self.user_perms['repositories'][self.repo_name]]
-            )
-        except KeyError:
-            return False
-        if self.required_perms.issubset(self._user_perms):
-            return True
-        return False
+    def _scope(self):
+        return 'global'
 
 
 class HasRepoPermissionAny(PermsFunction):
-    def __call__(self, repo_name=None, check_location='', user=None):
+    def __call__(self, repo_name=None, check_location=''):
         self.repo_name = repo_name
-        return super(HasRepoPermissionAny, self).__call__(check_location, user)
+        return super(HasRepoPermissionAny, self).__call__(check_location)
 
     def check_permissions(self):
         if not self.repo_name:
@@ -1109,11 +983,14 @@
             return True
         return False
 
+    def _scope(self):
+        return 'repo:%s' % self.repo_name
+
 
 class HasRepoGroupPermissionAny(PermsFunction):
-    def __call__(self, group_name=None, check_location='', user=None):
+    def __call__(self, group_name=None, check_location=''):
         self.group_name = group_name
-        return super(HasRepoGroupPermissionAny, self).__call__(check_location, user)
+        return super(HasRepoGroupPermissionAny, self).__call__(check_location)
 
     def check_permissions(self):
         try:
@@ -1126,28 +1003,14 @@
             return True
         return False
 
-
-class HasRepoGroupPermissionAll(PermsFunction):
-    def __call__(self, group_name=None, check_location='', user=None):
-        self.group_name = group_name
-        return super(HasRepoGroupPermissionAll, self).__call__(check_location, user)
-
-    def check_permissions(self):
-        try:
-            self._user_perms = set(
-                [self.user_perms['repositories_groups'][self.group_name]]
-            )
-        except KeyError:
-            return False
-        if self.required_perms.issubset(self._user_perms):
-            return True
-        return False
+    def _scope(self):
+        return 'repogroup:%s' % self.group_name
 
 
 class HasUserGroupPermissionAny(PermsFunction):
-    def __call__(self, user_group_name=None, check_location='', user=None):
+    def __call__(self, user_group_name=None, check_location=''):
         self.user_group_name = user_group_name
-        return super(HasUserGroupPermissionAny, self).__call__(check_location, user)
+        return super(HasUserGroupPermissionAny, self).__call__(check_location)
 
     def check_permissions(self):
         try:
@@ -1160,22 +1023,8 @@
             return True
         return False
 
-
-class HasUserGroupPermissionAll(PermsFunction):
-    def __call__(self, user_group_name=None, check_location='', user=None):
-        self.user_group_name = user_group_name
-        return super(HasUserGroupPermissionAll, self).__call__(check_location, user)
-
-    def check_permissions(self):
-        try:
-            self._user_perms = set(
-                [self.user_perms['user_groups'][self.user_group_name]]
-            )
-        except KeyError:
-            return False
-        if self.required_perms.issubset(self._user_perms):
-            return True
-        return False
+    def _scope(self):
+        return 'usergroup:%s' % self.user_group_name
 
 
 #==============================================================================
@@ -1208,115 +1057,6 @@
         return False
 
 
-#==============================================================================
-# SPECIAL VERSION TO HANDLE API AUTH
-#==============================================================================
-class _BaseApiPerm(object):
-    def __init__(self, *perms):
-        self.required_perms = set(perms)
-
-    def __call__(self, check_location=None, user=None, repo_name=None,
-                 group_name=None):
-        cls_name = self.__class__.__name__
-        check_scope = 'user:%s' % (user)
-        if repo_name:
-            check_scope += ', repo:%s' % (repo_name)
-
-        if group_name:
-            check_scope += ', repo group:%s' % (group_name)
-
-        log.debug('checking cls:%s %s %s @ %s',
-                  cls_name, self.required_perms, check_scope, check_location)
-        if not user:
-            log.debug('Empty User passed into arguments')
-            return False
-
-        ## process user
-        if not isinstance(user, AuthUser):
-            user = AuthUser(user.user_id)
-        if not check_location:
-            check_location = 'unspecified'
-        if self.check_permissions(user.permissions, repo_name, group_name):
-            log.debug('Permission to %s granted for user: %s @ %s',
-                      check_scope, user, check_location)
-            return True
-
-        else:
-            log.debug('Permission to %s denied for user: %s @ %s',
-                      check_scope, user, check_location)
-            return False
-
-    def check_permissions(self, perm_defs, repo_name=None, group_name=None):
-        """
-        implement in child class should return True if permissions are ok,
-        False otherwise
-
-        :param perm_defs: dict with permission definitions
-        :param repo_name: repo name
-        """
-        raise NotImplementedError()
-
-
-class HasPermissionAllApi(_BaseApiPerm):
-    def check_permissions(self, perm_defs, repo_name=None, group_name=None):
-        if self.required_perms.issubset(perm_defs.get('global')):
-            return True
-        return False
-
-
-class HasPermissionAnyApi(_BaseApiPerm):
-    def check_permissions(self, perm_defs, repo_name=None, group_name=None):
-        if self.required_perms.intersection(perm_defs.get('global')):
-            return True
-        return False
-
-
-class HasRepoPermissionAllApi(_BaseApiPerm):
-    def check_permissions(self, perm_defs, repo_name=None, group_name=None):
-        try:
-            _user_perms = set([perm_defs['repositories'][repo_name]])
-        except KeyError:
-            log.warning(traceback.format_exc())
-            return False
-        if self.required_perms.issubset(_user_perms):
-            return True
-        return False
-
-
-class HasRepoPermissionAnyApi(_BaseApiPerm):
-    def check_permissions(self, perm_defs, repo_name=None, group_name=None):
-        try:
-            _user_perms = set([perm_defs['repositories'][repo_name]])
-        except KeyError:
-            log.warning(traceback.format_exc())
-            return False
-        if self.required_perms.intersection(_user_perms):
-            return True
-        return False
-
-
-class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
-    def check_permissions(self, perm_defs, repo_name=None, group_name=None):
-        try:
-            _user_perms = set([perm_defs['repositories_groups'][group_name]])
-        except KeyError:
-            log.warning(traceback.format_exc())
-            return False
-        if self.required_perms.intersection(_user_perms):
-            return True
-        return False
-
-class HasRepoGroupPermissionAllApi(_BaseApiPerm):
-    def check_permissions(self, perm_defs, repo_name=None, group_name=None):
-        try:
-            _user_perms = set([perm_defs['repositories_groups'][group_name]])
-        except KeyError:
-            log.warning(traceback.format_exc())
-            return False
-        if self.required_perms.issubset(_user_perms):
-            return True
-        return False
-
 def check_ip_access(source_ip, allowed_ips=None):
     """
     Checks if source_ip is a subnet of any of allowed_ips.
--- a/kallithea/lib/auth_modules/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/auth_modules/__init__.py	Fri Nov 18 01:11:13 2016 +0100
@@ -17,9 +17,8 @@
 
 import logging
 import traceback
+import importlib
 
-from kallithea import EXTERN_TYPE_INTERNAL
-from kallithea.lib.compat import importlib
 from kallithea.lib.utils2 import str2bool
 from kallithea.lib.compat import formatted_json, hybrid_property
 from kallithea.lib.auth import PasswordGenerator
@@ -139,8 +138,8 @@
         log.debug('Trying to fetch user `%s` from Kallithea database',
                   username)
         if username:
-            user = User.get_by_username(username)
-            if not user:
+            user = User.get_by_username_or_email(username)
+            if user is None:
                 log.debug('Fallback to fetch user in case insensitive mode')
                 user = User.get_by_username(username, case_insensitive=True)
         else:
@@ -289,7 +288,6 @@
                 extern_name=user_data["extern_name"],
                 extern_type=self.name
             )
-            Session().flush()
             # enforce user is just in given groups, all of them has to be ones
             # created from plugins. We store this info in _group_data JSON field
             groups = user_data['groups'] or []
@@ -314,8 +312,6 @@
         parts = plugin.split(u'.lib.auth_modules.auth_', 1)
         if len(parts) == 2:
             _module, pn = parts
-            if pn == EXTERN_TYPE_INTERNAL:
-                pn = "internal"
             plugin = u'kallithea.lib.auth_modules.auth_' + pn
     PLUGIN_CLASS_NAME = "KallitheaAuthPlugin"
     try:
@@ -395,8 +391,15 @@
         else:
             log.debug('Plugin %s accepted user `%s` for authentication',
                       module, user)
+            # The user might have tried to authenticate using their email address,
+            # then the username variable wouldn't contain a valid username.
+            # But as the plugin has accepted the user, .username field should
+            # have a valid username, so use it for authentication purposes.
+            if user is not None:
+                username = user.username
 
         log.info('Authenticating user using %s plugin', plugin.__module__)
+
         # _authenticate is a wrapper for .auth() method of plugin.
         # it checks if .auth() sends proper data. For KallitheaExternalAuthPlugin
         # it also maps users to Database and maps the attributes returned
--- a/kallithea/lib/auth_modules/auth_container.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/auth_modules/auth_container.py	Fri Nov 18 01:11:13 2016 +0100
@@ -27,9 +27,9 @@
 
 import logging
 from kallithea.lib import auth_modules
-from kallithea.lib.utils2 import str2bool, safe_unicode
+from kallithea.lib.utils2 import str2bool, safe_unicode, safe_str
 from kallithea.lib.compat import hybrid_property
-from kallithea.model.db import User
+from kallithea.model.db import User, Setting
 
 log = logging.getLogger(__name__)
 
@@ -53,15 +53,39 @@
                 "name": "header",
                 "validator": self.validators.UnicodeString(strip=True, not_empty=True),
                 "type": "string",
-                "description": "Header to extract the user from",
+                "description": "Request header to extract the username from",
                 "default": "REMOTE_USER",
-                "formname": "Header"
+                "formname": "Username header"
+            },
+            {
+                "name": "email_header",
+                "validator": self.validators.UnicodeString(strip=True),
+                "type": "string",
+                "description": "Optional request header to extract the email from",
+                "default": "",
+                "formname": "Email header"
+            },
+            {
+                "name": "firstname_header",
+                "validator": self.validators.UnicodeString(strip=True),
+                "type": "string",
+                "description": "Optional request header to extract the first name from",
+                "default": "",
+                "formname": "Firstname header"
+            },
+            {
+                "name": "lastname_header",
+                "validator": self.validators.UnicodeString(strip=True),
+                "type": "string",
+                "description": "Optional request header to extract the last name from",
+                "default": "",
+                "formname": "Lastname header"
             },
             {
                 "name": "fallback_header",
                 "validator": self.validators.UnicodeString(strip=True),
                 "type": "string",
-                "description": "Header to extract the user from when main one fails",
+                "description": "Request header to extract the user from when main one fails",
                 "default": "HTTP_X_FORWARDED_USER",
                 "formname": "Fallback header"
             },
@@ -158,7 +182,7 @@
         # only way to log in is using environ
         username = None
         if userobj:
-            username = getattr(userobj, 'username')
+            username = safe_str(getattr(userobj, 'username'))
 
         if not username:
             # we don't have any objects in DB, user doesn't exist, extract
@@ -172,9 +196,9 @@
         # old attrs fetched from Kallithea database
         admin = getattr(userobj, 'admin', False)
         active = getattr(userobj, 'active', True)
-        email = getattr(userobj, 'email', '')
-        firstname = getattr(userobj, 'firstname', '')
-        lastname = getattr(userobj, 'lastname', '')
+        email = environ.get(settings.get('email_header'), getattr(userobj, 'email', ''))
+        firstname = environ.get(settings.get('firstname_header'), getattr(userobj, 'firstname', ''))
+        lastname = environ.get(settings.get('lastname_header'), getattr(userobj, 'lastname', ''))
 
         user_data = {
             'username': username,
@@ -192,4 +216,11 @@
         return user_data
 
     def get_managed_fields(self):
-        return ['username', 'password']
+        fields = ['username', 'password']
+        if(Setting.get_by_name('auth_container_email_header').app_settings_value):
+            fields.append('email')
+        if(Setting.get_by_name('auth_container_firstname_header').app_settings_value):
+            fields.append('firstname')
+        if(Setting.get_by_name('auth_container_lastname_header').app_settings_value):
+            fields.append('lastname')
+        return fields
--- a/kallithea/lib/auth_modules/auth_internal.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/auth_modules/auth_internal.py	Fri Nov 18 01:11:13 2016 +0100
@@ -28,7 +28,6 @@
 
 import logging
 
-from kallithea import EXTERN_TYPE_INTERNAL
 from kallithea.lib import auth_modules
 from kallithea.lib.compat import formatted_json, hybrid_property
 from kallithea.model.db import User
@@ -42,7 +41,8 @@
 
     @hybrid_property
     def name(self):
-        return EXTERN_TYPE_INTERNAL
+        # Also found as kallithea.lib.model.db.User.DEFAULT_AUTH_TYPE
+        return 'internal'
 
     def settings(self):
         return []
@@ -86,7 +86,7 @@
         log.debug(formatted_json(user_data))
         if userobj.active:
             from kallithea.lib import auth
-            password_match = auth.KallitheaCrypto.hash_check(password, userobj.password)
+            password_match = auth.check_password(password, userobj.password)
             if userobj.username == User.DEFAULT_USER and userobj.active:
                 log.info('user %s authenticated correctly as anonymous user',
                          username)
--- a/kallithea/lib/auth_modules/auth_ldap.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/auth_modules/auth_ldap.py	Fri Nov 18 01:11:13 2016 +0100
@@ -41,6 +41,7 @@
 
 try:
     import ldap
+    import ldap.filter
 except ImportError:
     # means that python-ldap is not installed
     ldap = None
@@ -48,38 +49,33 @@
 
 class AuthLdap(object):
 
-    def __init__(self, server, base_dn, port=389, bind_dn='', bind_pass='',
-                 tls_kind='PLAIN', tls_reqcert='DEMAND', ldap_version=3,
+    def __init__(self, server, base_dn, port=None, bind_dn='', bind_pass='',
+                 tls_kind='PLAIN', tls_reqcert='DEMAND', cacertdir=None, ldap_version=3,
                  ldap_filter='(&(objectClass=user)(!(objectClass=computer)))',
                  search_scope='SUBTREE', attr_login='uid'):
         if ldap is None:
             raise LdapImportError
 
         self.ldap_version = ldap_version
-        ldap_server_type = 'ldap'
 
         self.TLS_KIND = tls_kind
-
-        if self.TLS_KIND == 'LDAPS':
-            port = port or 689
-            ldap_server_type = ldap_server_type + 's'
-
         OPT_X_TLS_DEMAND = 2
         self.TLS_REQCERT = getattr(ldap, 'OPT_X_TLS_%s' % tls_reqcert,
                                    OPT_X_TLS_DEMAND)
-        # split server into list
-        self.LDAP_SERVER_ADDRESS = server.split(',')
-        self.LDAP_SERVER_PORT = port
+        self.cacertdir = cacertdir
 
-        # USE FOR READ ONLY BIND TO LDAP SERVER
+        protocol = 'ldaps' if self.TLS_KIND == 'LDAPS' else 'ldap'
+        if not port:
+            port = 636 if self.TLS_KIND == 'LDAPS' else 389
+        self.LDAP_SERVER = str(', '.join(
+            "%s://%s:%s" % (protocol,
+                            host.strip(),
+                            port)
+            for host in server.split(',')))
+
         self.LDAP_BIND_DN = safe_str(bind_dn)
         self.LDAP_BIND_PASS = safe_str(bind_pass)
-        _LDAP_SERVERS = []
-        for host in self.LDAP_SERVER_ADDRESS:
-            _LDAP_SERVERS.append("%s://%s:%s" % (ldap_server_type,
-                                                     host.replace(' ', ''),
-                                                     self.LDAP_SERVER_PORT))
-        self.LDAP_SERVER = str(', '.join(s for s in _LDAP_SERVERS))
+
         self.BASE_DN = safe_str(base_dn)
         self.LDAP_FILTER = safe_str(ldap_filter)
         self.SEARCH_SCOPE = getattr(ldap, 'SCOPE_%s' % search_scope)
@@ -96,10 +92,6 @@
         :param password: password
         """
 
-        from kallithea.lib.helpers import chop_at
-
-        uid = chop_at(username, "@%s" % self.LDAP_SERVER_ADDRESS)
-
         if not password:
             log.debug("Attempt to authenticate LDAP user "
                       "with blank password rejected.")
@@ -107,9 +99,11 @@
         if "," in username:
             raise LdapUsernameError("invalid character in username: ,")
         try:
-            if hasattr(ldap, 'OPT_X_TLS_CACERTDIR'):
-                ldap.set_option(ldap.OPT_X_TLS_CACERTDIR,
-                                '/etc/openldap/cacerts')
+            if self.cacertdir:
+                if hasattr(ldap, 'OPT_X_TLS_CACERTDIR'):
+                    ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, self.cacertdir)
+                else:
+                    log.debug("OPT_X_TLS_CACERTDIR is not available - can't set %s", self.cacertdir)
             ldap.set_option(ldap.OPT_REFERRALS, ldap.OPT_OFF)
             ldap.set_option(ldap.OPT_RESTART, ldap.OPT_ON)
             ldap.set_option(ldap.OPT_TIMEOUT, 20)
@@ -131,8 +125,9 @@
                           self.LDAP_BIND_DN)
                 server.simple_bind_s(self.LDAP_BIND_DN, self.LDAP_BIND_PASS)
 
-            filter_ = '(&%s(%s=%s))' % (self.LDAP_FILTER, self.attr_login,
-                                        username)
+            filter_ = '(&%s(%s=%s))' % (self.LDAP_FILTER,
+                                        ldap.filter.escape_filter_chars(self.attr_login),
+                                        ldap.filter.escape_filter_chars(username))
             log.debug("Authenticating %r filter %s at %s", self.BASE_DN,
                       filter_, self.LDAP_SERVER)
             lobjects = server.search_ext_s(self.BASE_DN, self.SEARCH_SCOPE,
@@ -148,26 +143,28 @@
                 try:
                     log.debug('Trying simple bind with %s', dn)
                     server.simple_bind_s(dn, safe_str(password))
-                    attrs = server.search_ext_s(dn, ldap.SCOPE_BASE,
-                                                '(objectClass=*)')[0][1]
-                    break
+                    results = server.search_ext_s(dn, ldap.SCOPE_BASE,
+                                                  '(objectClass=*)')
+                    if len(results) == 1:
+                        dn_, attrs = results[0]
+                        assert dn_ == dn
+                        return dn, attrs
 
                 except ldap.INVALID_CREDENTIALS:
-                    log.debug("LDAP rejected password for user '%s' (%s): %s",
-                              uid, username, dn)
+                    log.debug("LDAP rejected password for user '%s': %s",
+                              username, dn)
+                    continue # accept authentication as another ldap user with same username
 
-            else:
-                log.debug("No matching LDAP objects for authentication "
-                          "of '%s' (%s)", uid, username)
-                raise LdapPasswordError()
+            log.debug("No matching LDAP objects for authentication "
+                      "of '%s'", username)
+            raise LdapPasswordError()
 
         except ldap.NO_SUCH_OBJECT:
-            log.debug("LDAP says no such user '%s' (%s)", uid, username)
+            log.debug("LDAP says no such user '%s'", username)
             raise LdapUsernameError()
         except ldap.SERVER_DOWN:
-            raise LdapConnectionError("LDAP can't access authentication server")
-
-        return dn, attrs
+            # [0] might be {'info': "TLS error -8179:Peer's Certificate issuer is not recognized.", 'desc': "Can't contact LDAP server"}
+            raise LdapConnectionError("LDAP can't connect to authentication server")
 
 
 class KallitheaAuthPlugin(auth_modules.KallitheaExternalAuthPlugin):
@@ -192,11 +189,11 @@
             },
             {
                 "name": "port",
-                "validator": self.validators.Number(strip=True, not_empty=True),
+                "validator": self.validators.Number(strip=True),
                 "type": "string",
-                "description": "Port that the LDAP server is listening on",
-                "default": 389,
-                "formname": "Port"
+                "description": "Port that the LDAP server is listening on. Defaults to 389 for PLAIN/START_TLS and 636 for LDAPS.",
+                "default": "",
+                "formname": "Custom LDAP Port"
             },
             {
                 "name": "dn_user",
@@ -230,6 +227,13 @@
                 "formname": "Certificate Checks"
             },
             {
+                "name": "cacertdir",
+                "validator": self.validators.UnicodeString(strip=True),
+                "type": "string",
+                "description": "Optional: Custom CA certificate directory for validating LDAPS",
+                "formname": "Custom CA Certificates"
+            },
+            {
                 "name": "base_dn",
                 "validator": self.validators.UnicodeString(strip=True),
                 "type": "string",
@@ -313,6 +317,7 @@
             'bind_pass': settings.get('dn_pass'),
             'tls_kind': settings.get('tls_kind'),
             'tls_reqcert': settings.get('tls_reqcert'),
+            'cacertdir': settings.get('cacertdir'),
             'ldap_filter': settings.get('filter'),
             'search_scope': settings.get('search_scope'),
             'attr_login': settings.get('attr_login'),
@@ -353,12 +358,13 @@
             log.info('user %s authenticated correctly', user_data['username'])
             return user_data
 
-        except (LdapUsernameError, LdapPasswordError, LdapImportError):
-            log.error(traceback.format_exc())
-            return None
-        except (Exception,):
-            log.error(traceback.format_exc())
-            return None
+        except LdapUsernameError:
+            log.info('Error authenticating %s with LDAP: User not found', username)
+        except LdapPasswordError:
+            log.info('Error authenticating %s with LDAP: Password error', username)
+        except LdapImportError:
+            log.error('Error authenticating %s with LDAP: LDAP not available', username)
+        return None
 
     def get_managed_fields(self):
         return ['username', 'firstname', 'lastname', 'email', 'password']
--- a/kallithea/lib/base.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/base.py	Fri Nov 18 01:11:13 2016 +0100
@@ -38,15 +38,15 @@
 import paste.auth.basic
 import paste.httpheaders
 
-from pylons import config, tmpl_context as c, request, session, url
+from pylons import config, tmpl_context as c, request, session
 from pylons.controllers import WSGIController
-from pylons.controllers.util import redirect
 from pylons.templating import render_mako as render  # don't remove this import
 from pylons.i18n.translation import _
 
 from kallithea import __version__, BACKENDS
 
-from kallithea.lib.utils2 import str2bool, safe_unicode, AttributeDict,\
+from kallithea.config.routing import url
+from kallithea.lib.utils2 import str2bool, safe_unicode, AttributeDict, \
     safe_str, safe_int
 from kallithea.lib import auth_modules
 from kallithea.lib.auth import AuthUser, HasPermissionAnyMiddleware
@@ -55,10 +55,9 @@
 from kallithea.lib.vcs.exceptions import RepositoryError, EmptyRepositoryError, ChangesetDoesNotExistError
 from kallithea.model import meta
 
-from kallithea.model.db import Repository, Ui, User, Setting
+from kallithea.model.db import PullRequest, Repository, Ui, User, Setting
 from kallithea.model.notification import NotificationModel
 from kallithea.model.scm import ScmModel
-from kallithea.model.pull_request import PullRequestModel
 
 log = logging.getLogger(__name__)
 
@@ -117,7 +116,9 @@
 
     auth_user = AuthUser(dbuser=user,
                          is_external_auth=is_external_auth)
-    auth_user.set_authenticated()
+    # It should not be possible to explicitly log in as the default user.
+    assert not auth_user.is_default_user
+    auth_user.is_authenticated = True
 
     # Start new session to prevent session fixation attacks.
     session.invalidate()
@@ -248,20 +249,6 @@
     def _get_ip_addr(self, environ):
         return _get_ip_addr(environ)
 
-    def _check_ssl(self, environ):
-        """
-        Checks the SSL check flag and returns False if SSL is not present
-        and required True otherwise
-        """
-        #check if we have SSL required  ! if not it's a bad request !
-        if str2bool(Ui.get_by_key('push_ssl').ui_value):
-            org_proto = environ.get('wsgi._org_proto', environ['wsgi.url_scheme'])
-            if org_proto != 'https':
-                log.debug('proto is %s and SSL is required BAD REQUEST !',
-                          org_proto)
-                return False
-        return True
-
     def _check_locking_state(self, environ, action, repo, user_id):
         """
         Checks locking on this repository, if locking is enabled and lock is
@@ -332,7 +319,7 @@
         c.visual.show_public_icon = str2bool(rc_config.get('show_public_icon'))
         c.visual.show_private_icon = str2bool(rc_config.get('show_private_icon'))
         c.visual.stylify_metatags = str2bool(rc_config.get('stylify_metatags'))
-        c.visual.dashboard_items = safe_int(rc_config.get('dashboard_items', 100))
+        c.visual.page_size = safe_int(rc_config.get('dashboard_items', 100))
         c.visual.admin_grid_items = safe_int(rc_config.get('admin_grid_items', 100))
         c.visual.repository_fields = str2bool(rc_config.get('repository_fields'))
         c.visual.show_version = str2bool(rc_config.get('show_version'))
@@ -366,12 +353,12 @@
 
         c.repo_name = get_repo_slug(request)  # can be empty
         c.backends = BACKENDS.keys()
-        c.unread_notifications = NotificationModel()\
+        c.unread_notifications = NotificationModel() \
                         .get_unread_cnt_for_user(c.authuser.user_id)
 
         self.cut_off_limit = safe_int(config.get('cut_off_limit'))
 
-        c.my_pr_count = PullRequestModel().get_pullrequest_cnt_for_user(c.authuser.user_id)
+        c.my_pr_count = PullRequest.query(reviewer_id=c.authuser.user_id, include_closed=False).count()
 
         self.sa = meta.Session
         self.scm_model = ScmModel(self.sa)
@@ -392,7 +379,9 @@
         # Authenticate by session cookie
         # In ancient login sessions, 'authuser' may not be a dict.
         # In that case, the user will have to log in again.
-        if isinstance(session_authuser, dict):
+        # v0.3 and earlier included an 'is_authenticated' key; if present,
+        # this must be True.
+        if isinstance(session_authuser, dict) and session_authuser.get('is_authenticated', True):
             try:
                 return AuthUser.from_cookie(session_authuser)
             except UserCreationError as e:
@@ -479,7 +468,7 @@
                 if route in ['repo_creating_home']:
                     return
                 check_url = url('repo_creating_home', repo_name=c.repo_name)
-                return redirect(check_url)
+                raise webob.exc.HTTPFound(location=check_url)
 
             dbr = c.db_repo = _dbr
             c.db_repo_scm_instance = c.db_repo.scm_instance
@@ -513,7 +502,8 @@
                     category='error')
             raise webob.exc.HTTPNotFound()
         except ChangesetDoesNotExistError as e:
-            h.flash(h.literal(_('Changeset not found')),
+            h.flash(h.literal(_('Changeset for %s %s not found in %s') %
+                              (ref_type, ref_name, repo.repo_name)),
                     category='error')
             raise webob.exc.HTTPNotFound()
         except RepositoryError as e:
--- a/kallithea/lib/caching_query.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/caching_query.py	Fri Nov 18 01:11:13 2016 +0100
@@ -9,8 +9,6 @@
    retrieves results in/from Beaker.
  * FromCache - a query option that establishes caching
    parameters on a Query
- * RelationshipCache - a variant of FromCache which is specific
-   to a query invoked during a lazy load.
  * _params_from_query - extracts value parameters from
    a Query.
 
@@ -54,7 +52,7 @@
     by this query, which are usually literals defined in the
     WHERE clause.
 
-    The FromCache and RelationshipCache mapper options below represent
+    The FromCache mapper option below represent
     the "public" method of configuring this state upon the CachingQuery.
 
     """
@@ -212,65 +210,6 @@
                               self.cache_key)
 
 
-class RelationshipCache(MapperOption):
-    """Specifies that a Query as called within a "lazy load"
-       should load results from a cache."""
-
-    propagate_to_loaders = True
-
-    def __init__(self, region, namespace, attribute):
-        """Construct a new RelationshipCache.
-
-        :param region: the cache region.  Should be a
-        region configured in the Beaker CacheManager.
-
-        :param namespace: the cache namespace.  Should
-        be a name uniquely describing the target Query's
-        lexical structure.
-
-        :param attribute: A Class.attribute which
-        indicates a particular class relationship() whose
-        lazy loader should be pulled from the cache.
-
-        """
-        self.region = region
-        self.namespace = namespace
-        self._relationship_options = {
-            (attribute.property.parent.class_, attribute.property.key): self
-        }
-
-    def process_query_conditionally(self, query):
-        """Process a Query that is used within a lazy loader.
-
-        (the process_query_conditionally() method is a SQLAlchemy
-        hook invoked only within lazyload.)
-
-        """
-        if query._current_path:
-            mapper, key = query._current_path[-2:]
-
-            for cls in mapper.class_.__mro__:
-                if (cls, key) in self._relationship_options:
-                    relationship_option = \
-                        self._relationship_options[(cls, key)]
-                    _set_cache_parameters(
-                            query,
-                            relationship_option.region,
-                            relationship_option.namespace,
-                            None)
-
-    def and_(self, option):
-        """Chain another RelationshipCache option to this one.
-
-        While many RelationshipCache objects can be specified on a single
-        Query separately, chaining them together allows for a more efficient
-        lookup during load.
-
-        """
-        self._relationship_options.update(option._relationship_options)
-        return self
-
-
 def _params_from_query(query):
     """Pull the bind parameter values from a query.
 
--- a/kallithea/lib/celerylib/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/celerylib/__init__.py	Fri Nov 18 01:11:13 2016 +0100
@@ -26,20 +26,18 @@
 """
 
 
-import socket
-import traceback
+import os
 import logging
-from os.path import join as jn
+
 from pylons import config
 
 from hashlib import md5
 from decorator import decorator
 
-from kallithea.lib.vcs.utils.lazy import LazyProperty
 from kallithea import CELERY_ON, CELERY_EAGER
-from kallithea.lib.utils2 import str2bool, safe_str
+from kallithea.lib.utils2 import safe_str
 from kallithea.lib.pidlock import DaemonLock, LockHeld
-from kallithea.model import init_model
+from kallithea.model.base import init_model
 from kallithea.model import meta
 
 from sqlalchemy import engine_from_config
@@ -48,36 +46,49 @@
 log = logging.getLogger(__name__)
 
 
-class ResultWrapper(object):
-    def __init__(self, task):
-        self.task = task
+class FakeTask(object):
+    """Fake a sync result to make it look like a finished task"""
+
+    def __init__(self, result):
+        self.result = result
 
-    @LazyProperty
-    def result(self):
-        return self.task
+    def failed(self):
+        return False
+
+    traceback = None # if failed
+
+    task_id = None
 
 
-def run_task(task, *args, **kwargs):
-    global CELERY_ON
-    if CELERY_ON:
-        try:
-            t = task.apply_async(args=args, kwargs=kwargs)
-            log.info('running task %s:%s', t.task_id, task)
-            return t
+def task(f_org):
+    """Wrapper of celery.task.task, running async if CELERY_ON
+    """
 
-        except socket.error as e:
-            if isinstance(e, IOError) and e.errno == 111:
-                log.debug('Unable to connect to celeryd. Sync execution')
-                CELERY_ON = False
-            else:
-                log.error(traceback.format_exc())
-        except KeyError as e:
-                log.debug('Unable to connect to celeryd. Sync execution')
-        except Exception as e:
-            log.error(traceback.format_exc())
+    if CELERY_ON:
+        def f_async(*args, **kwargs):
+            log.info('executing %s task', f_org.__name__)
+            try:
+                f_org(*args, **kwargs)
+            finally:
+                log.info('executed %s task', f_org.__name__)
+        f_async.__name__ = f_org.__name__
+        from kallithea.lib import celerypylons
+        runner = celerypylons.task(ignore_result=True)(f_async)
+        def f_wrapped(*args, **kwargs):
+            t = runner.apply_async(args=args, kwargs=kwargs)
+            log.info('executing task %s in async mode - id %s', f_org, t.task_id)
+            return t
+    else:
+        def f_wrapped(*args, **kwargs):
+            log.info('executing task %s in sync', f_org.__name__)
+            try:
+                result = f_org(*args, **kwargs)
+            except Exception as e:
+                log.error('exception executing sync task %s in sync', f_org.__name__, e)
+                raise # TODO: return this in FakeTask as with async tasks?
+            return FakeTask(result)
 
-    log.debug('executing task %s in sync mode', task)
-    return ResultWrapper(task(*args, **kwargs))
+    return f_wrapped
 
 
 def __get_lockkey(func, *fargs, **fkwargs):
@@ -98,7 +109,7 @@
 
         log.info('running task with lockkey %s', lockkey)
         try:
-            l = DaemonLock(file_=jn(lockkey_path, lockkey))
+            l = DaemonLock(file_=os.path.join(lockkey_path, lockkey))
             ret = func(*fargs, **fkwargs)
             l.release()
             return ret
@@ -111,7 +122,7 @@
 
 def get_session():
     if CELERY_ON:
-        engine = engine_from_config(config, 'sqlalchemy.db1.')
+        engine = engine_from_config(config, 'sqlalchemy.')
         init_model(engine)
     sa = meta.Session()
     return sa
--- a/kallithea/lib/celerylib/tasks.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/celerylib/tasks.py	Fri Nov 18 01:11:13 2016 +0100
@@ -26,13 +26,10 @@
 :license: GPLv3, see LICENSE.md for more details.
 """
 
-from celery.decorators import task
-
 import os
 import traceback
 import logging
 import rfc822
-from os.path import join as jn
 
 from time import mktime
 from operator import itemgetter
@@ -41,11 +38,11 @@
 from pylons import config
 
 from kallithea import CELERY_ON
-from kallithea.lib.celerylib import run_task, locked_task, dbsession, \
-    str2bool, __get_lockkey, LockHeld, DaemonLock, get_session
+from kallithea.lib import celerylib
 from kallithea.lib.helpers import person
 from kallithea.lib.rcmail.smtp_mailer import SmtpMailer
-from kallithea.lib.utils import add_cache, action_logger
+from kallithea.lib.utils import setup_cache_regions, action_logger
+from kallithea.lib.utils2 import str2bool
 from kallithea.lib.vcs.utils import author_email
 from kallithea.lib.compat import json, OrderedDict
 from kallithea.lib.hooks import log_create_repository
@@ -53,46 +50,39 @@
 from kallithea.model.db import Statistics, Repository, User
 
 
-add_cache(config)  # pragma: no cover
+setup_cache_regions(config)  # pragma: no cover
 
 __all__ = ['whoosh_index', 'get_commits_stats', 'send_email']
 
 
-def get_logger(cls):
-    if CELERY_ON:
-        try:
-            return cls.get_logger()
-        except AttributeError:
-            pass
-    return logging.getLogger(__name__)
+log = logging.getLogger(__name__)
 
 
-@task(ignore_result=True)
-@locked_task
-@dbsession
+@celerylib.task
+@celerylib.locked_task
+@celerylib.dbsession
 def whoosh_index(repo_location, full_index):
     from kallithea.lib.indexers.daemon import WhooshIndexingDaemon
-    DBS = get_session()
+    DBS = celerylib.get_session()
 
     index_location = config['index_dir']
     WhooshIndexingDaemon(index_location=index_location,
-                         repo_location=repo_location, sa=DBS)\
+                         repo_location=repo_location, sa=DBS) \
                          .run(full_index=full_index)
 
 
-@task(ignore_result=True)
-@dbsession
+@celerylib.task
+@celerylib.dbsession
 def get_commits_stats(repo_name, ts_min_y, ts_max_y, recurse_limit=100):
-    log = get_logger(get_commits_stats)
-    DBS = get_session()
-    lockkey = __get_lockkey('get_commits_stats', repo_name, ts_min_y,
+    DBS = celerylib.get_session()
+    lockkey = celerylib.__get_lockkey('get_commits_stats', repo_name, ts_min_y,
                             ts_max_y)
     lockkey_path = config['app_conf']['cache_dir']
 
     log.info('running task with lockkey %s', lockkey)
 
     try:
-        lock = l = DaemonLock(file_=jn(lockkey_path, lockkey))
+        lock = l = celerylib.DaemonLock(file_=os.path.join(lockkey_path, lockkey))
 
         # for js data compatibility cleans the key for person from '
         akc = lambda k: person(k).replace('"', "")
@@ -116,9 +106,9 @@
         last_cs = None
         timegetter = itemgetter('time')
 
-        dbrepo = DBS.query(Repository)\
+        dbrepo = DBS.query(Repository) \
             .filter(Repository.repo_name == repo_name).scalar()
-        cur_stats = DBS.query(Statistics)\
+        cur_stats = DBS.query(Statistics) \
             .filter(Statistics.repository == dbrepo).scalar()
 
         if cur_stats is not None:
@@ -176,7 +166,7 @@
                                     "changed": len(cs.changed),
                                     "removed": len(cs.removed),
                                    }
-                        co_day_auth_aggr[akc(cs.author)]['data']\
+                        co_day_auth_aggr[akc(cs.author)]['data'] \
                             .append(datadict)
 
             else:
@@ -236,19 +226,18 @@
 
         # execute another task if celery is enabled
         if len(repo.revisions) > 1 and CELERY_ON and recurse_limit > 0:
-            recurse_limit -= 1
-            run_task(get_commits_stats, repo_name, ts_min_y, ts_max_y,
-                     recurse_limit)
-        if recurse_limit <= 0:
-            log.debug('Breaking recursive mode due to reach of recurse limit')
-        return True
-    except LockHeld:
-        log.info('LockHeld')
+            get_commits_stats(repo_name, ts_min_y, ts_max_y, recurse_limit - 1)
+        elif recurse_limit <= 0:
+            log.debug('Not recursing - limit has been reached')
+        else:
+            log.debug('Not recursing')
+    except celerylib.LockHeld:
+        log.info('Task with key %s already running', lockkey)
         return 'Task with key %s already running' % lockkey
 
 
-@task(ignore_result=True)
-@dbsession
+@celerylib.task
+@celerylib.dbsession
 def send_email(recipients, subject, body='', html_body='', headers=None, author=None):
     """
     Sends an email with defined parameters from the .ini files.
@@ -261,7 +250,6 @@
     :param headers: dictionary of prepopulated e-mail headers
     :param author: User object of the author of this mail, if known and relevant
     """
-    log = get_logger(send_email)
     assert isinstance(recipients, list), recipients
     if headers is None:
         headers = {}
@@ -335,15 +323,14 @@
         return False
     return True
 
-@task(ignore_result=False)
-@dbsession
+@celerylib.task
+@celerylib.dbsession
 def create_repo(form_data, cur_user):
     from kallithea.model.repo import RepoModel
     from kallithea.model.user import UserModel
     from kallithea.model.db import Setting
 
-    log = get_logger(create_repo)
-    DBS = get_session()
+    DBS = celerylib.get_session()
 
     cur_user = UserModel(DBS)._get_user(cur_user)
 
@@ -417,15 +404,11 @@
             RepoModel(DBS)._delete_filesystem_repo(repo)
         raise
 
-    # it's an odd fix to make celery fail task when exception occurs
-    def on_failure(self, *args, **kwargs):
-        pass
-
     return True
 
 
-@task(ignore_result=False)
-@dbsession
+@celerylib.task
+@celerylib.dbsession
 def create_repo_fork(form_data, cur_user):
     """
     Creates a fork of repository using interval VCS methods
@@ -436,8 +419,7 @@
     from kallithea.model.repo import RepoModel
     from kallithea.model.user import UserModel
 
-    log = get_logger(create_repo_fork)
-    DBS = get_session()
+    DBS = celerylib.get_session()
 
     base_path = Repository.base_path()
     cur_user = UserModel(DBS)._get_user(cur_user)
@@ -502,10 +484,6 @@
             RepoModel(DBS)._delete_filesystem_repo(repo)
         raise
 
-    # it's an odd fix to make celery fail task when exception occurs
-    def on_failure(self, *args, **kwargs):
-        pass
-
     return True
 
 
--- a/kallithea/lib/celerypylons/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/celerypylons/__init__.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,19 +1,36 @@
 # -*- coding: utf-8 -*-
 
 """
-Automatically sets the environment variable `CELERY_LOADER` to
-`celerypylons.loader:PylonsLoader`.  This ensures the loader is
-specified when accessing the rest of this package, and allows celery
-to be installed in a webapp just by importing celerypylons::
+Kallithea wrapper of Celery
+
+The Celery configuration is in the normal Pylons ini file. We thus have to set
+the `CELERY_LOADER` environment variable to point at a custom "loader" that can
+read it. That environment variable must be set *before* importing celery. To
+ensure that, we wrap celery in this module.
 
-    import celerypylons
+Also, the loader depends on Pylons being configured to it can read the Celery
+configuration out of it. To make sure that really is the case and give an early
+warning, we check one of the mandatory settings.
 
+This module must thus not be imported in global scope but must be imported on
+demand in function scope.
 """
 
 import os
 import warnings
 
+# Verify Pylons configuration has been loaded
+from pylons import config
+assert config['celery.imports'] == 'kallithea.lib.celerylib.tasks', 'Kallithea Celery configuration has not been loaded'
+
+# Prepare environment to point at Kallithea Pylons loader
 CELERYPYLONS_LOADER = 'kallithea.lib.celerypylons.loader.PylonsLoader'
 if os.environ.get('CELERY_LOADER', CELERYPYLONS_LOADER) != CELERYPYLONS_LOADER:
     warnings.warn("'CELERY_LOADER' environment variable will be overridden by celery-pylons.")
 os.environ['CELERY_LOADER'] = CELERYPYLONS_LOADER
+
+# Import (and expose) celery, thus immediately triggering use of the custom Pylons loader
+import celery.app as app
+import celery.result as result
+from celery.task import task
+from celery.bin import worker
--- a/kallithea/lib/celerypylons/commands.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,100 +0,0 @@
-# -*- coding: utf-8 -*-
-
-import kallithea
-from kallithea.lib.utils import BasePasterCommand, Command, load_rcextensions
-from celery.app import app_or_default
-from celery.bin import camqadm, celerybeat, celeryd, celeryev
-
-from kallithea.lib.utils2 import str2bool
-
-__all__ = ['CeleryDaemonCommand', 'CeleryBeatCommand',
-           'CAMQPAdminCommand', 'CeleryEventCommand']
-
-
-class CeleryCommand(BasePasterCommand):
-    """Abstract class implements run methods needed for celery
-
-    Starts the celery worker that uses a paste.deploy configuration
-    file.
-    """
-
-    def update_parser(self):
-        """
-        Abstract method.  Allows for the class's parser to be updated
-        before the superclass's `run` method is called.  Necessary to
-        allow options/arguments to be passed through to the underlying
-        celery command.
-        """
-
-        cmd = self.celery_command(app_or_default())
-        for x in cmd.get_options():
-            self.parser.add_option(x)
-
-    def command(self):
-        from pylons import config
-        try:
-            CELERY_ON = str2bool(config['app_conf'].get('use_celery'))
-        except KeyError:
-            CELERY_ON = False
-
-        if not CELERY_ON:
-            raise Exception('Please set use_celery = true in .ini config '
-                            'file before running celeryd')
-        kallithea.CELERY_ON = CELERY_ON
-        load_rcextensions(config['here'])
-        cmd = self.celery_command(app_or_default())
-        return cmd.run(**vars(self.options))
-
-
-class CeleryDaemonCommand(CeleryCommand):
-    """Start the celery worker
-
-    Starts the celery worker that uses a paste.deploy configuration
-    file.
-    """
-    usage = 'CONFIG_FILE [celeryd options...]'
-    summary = __doc__.splitlines()[0]
-    description = "".join(__doc__.splitlines()[2:])
-
-    parser = Command.standard_parser(quiet=True)
-    celery_command = celeryd.WorkerCommand
-
-
-class CeleryBeatCommand(CeleryCommand):
-    """Start the celery beat server
-
-    Starts the celery beat server using a paste.deploy configuration
-    file.
-    """
-    usage = 'CONFIG_FILE [celerybeat options...]'
-    summary = __doc__.splitlines()[0]
-    description = "".join(__doc__.splitlines()[2:])
-
-    parser = Command.standard_parser(quiet=True)
-    celery_command = celerybeat.BeatCommand
-
-
-class CAMQPAdminCommand(CeleryCommand):
-    """CAMQP Admin
-
-    CAMQP celery admin tool.
-    """
-    usage = 'CONFIG_FILE [camqadm options...]'
-    summary = __doc__.splitlines()[0]
-    description = "".join(__doc__.splitlines()[2:])
-
-    parser = Command.standard_parser(quiet=True)
-    celery_command = camqadm.AMQPAdminCommand
-
-
-class CeleryEventCommand(CeleryCommand):
-    """Celery event command.
-
-    Capture celery events.
-    """
-    usage = 'CONFIG_FILE [celeryev options...]'
-    summary = __doc__.splitlines()[0]
-    description = "".join(__doc__.splitlines()[2:])
-
-    parser = Command.standard_parser(quiet=True)
-    celery_command = celeryev.EvCommand
--- a/kallithea/lib/celerypylons/loader.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/celerypylons/loader.py	Fri Nov 18 01:11:13 2016 +0100
@@ -3,38 +3,45 @@
 from celery.loaders.base import BaseLoader
 from pylons import config
 
+# TODO: drop this mangling and just use a separate celery config section
 to_pylons = lambda x: x.replace('_', '.').lower()
 to_celery = lambda x: x.replace('.', '_').upper()
 
-LIST_PARAMS = """CELERY_IMPORTS ADMINS ROUTES""".split()
+LIST_PARAMS = """CELERY_IMPORTS ADMINS ROUTES CELERY_ACCEPT_CONTENT""".split()
 
 
 class PylonsSettingsProxy(object):
     """Pylons Settings Proxy
 
-    Proxies settings from pylons.config
+    Make settings from pylons.config appear the way Celery expects them.
+    """
+
+    def __getattr__(self, key):
+        try:
+            return self[key]
+        except KeyError:
+            raise AttributeError(key)
 
-    """
-    def __getattr__(self, key):
+    def get(self, key, default=None):
+        try:
+            return self[key]
+        except KeyError:
+            return default
+
+    def __getitem__(self, key):
+        pylons_key = to_pylons(key)
+        value = config[pylons_key]
+        if key in LIST_PARAMS:
+            return value.split()
+        return self.type_converter(value)
+
+    def __contains__(self, key):
         pylons_key = to_pylons(key)
         try:
-            value = config[pylons_key]
-            if key in LIST_PARAMS:return value.split()
-            return self.type_converter(value)
+            config[pylons_key]
         except KeyError:
-            raise AttributeError(pylons_key)
-
-    def get(self, key):
-        try:
-            return self.__getattr__(key)
-        except AttributeError:
-            return None
-
-    def __getitem__(self, key):
-        try:
-            return self.__getattr__(key)
-        except AttributeError:
-            raise KeyError()
+            return False
+        return True
 
     def __setattr__(self, key, value):
         pylons_key = to_pylons(key)
--- a/kallithea/lib/colored_formatter.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/colored_formatter.py	Fri Nov 18 01:11:13 2016 +0100
@@ -42,19 +42,19 @@
 def format_sql(sql):
     sql = sql.replace('\n', '')
     sql = one_space_trim(sql)
-    sql = sql\
-        .replace(',', ',\n\t')\
-        .replace('SELECT', '\n\tSELECT \n\t')\
-        .replace('UPDATE', '\n\tUPDATE \n\t')\
-        .replace('DELETE', '\n\tDELETE \n\t')\
-        .replace('FROM', '\n\tFROM')\
-        .replace('ORDER BY', '\n\tORDER BY')\
-        .replace('LIMIT', '\n\tLIMIT')\
-        .replace('WHERE', '\n\tWHERE')\
-        .replace('AND', '\n\tAND')\
-        .replace('LEFT', '\n\tLEFT')\
-        .replace('INNER', '\n\tINNER')\
-        .replace('INSERT', '\n\tINSERT')\
+    sql = sql \
+        .replace(',', ',\n\t') \
+        .replace('SELECT', '\n\tSELECT \n\t') \
+        .replace('UPDATE', '\n\tUPDATE \n\t') \
+        .replace('DELETE', '\n\tDELETE \n\t') \
+        .replace('FROM', '\n\tFROM') \
+        .replace('ORDER BY', '\n\tORDER BY') \
+        .replace('LIMIT', '\n\tLIMIT') \
+        .replace('WHERE', '\n\tWHERE') \
+        .replace('AND', '\n\tAND') \
+        .replace('LEFT', '\n\tLEFT') \
+        .replace('INNER', '\n\tINNER') \
+        .replace('INSERT', '\n\tINSERT') \
         .replace('DELETE', '\n\tDELETE')
     return sql
 
--- a/kallithea/lib/compat.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/compat.py	Fri Nov 18 01:11:13 2016 +0100
@@ -27,10 +27,9 @@
 """
 
 
+import sys
 import os
 import functools
-import importlib
-from kallithea import __py_version__, is_windows
 
 #==============================================================================
 # json
@@ -40,37 +39,18 @@
 # alias for formatted json
 formatted_json = functools.partial(json.dumps, indent=4, sort_keys=True)
 
-if __py_version__ >= (2, 7):
+
+#==============================================================================
+# unittest
+#==============================================================================
+if sys.version_info >= (2, 7):
     import unittest
 else:
     import unittest2 as unittest
 
-#==============================================================================
-# izip_longest
-#==============================================================================
-try:
-    from itertools import izip_longest
-except ImportError:
-    import itertools
-
-    def izip_longest(*args, **kwds):
-        fillvalue = kwds.get("fillvalue")
-
-        def sentinel(counter=([fillvalue] * (len(args) - 1)).pop):
-            yield counter()  # yields the fillvalue, or raises IndexError
-
-        fillers = itertools.repeat(fillvalue)
-        iters = [itertools.chain(it, sentinel(), fillers)
-                    for it in args]
-        try:
-            for tup in itertools.izip(*iters):
-                yield tup
-        except IndexError:
-            pass
-
 
 #==============================================================================
-# OrderedDict
+# OrderedDict - Python 2.7 could perhaps use collections.OrderedDict
 #==============================================================================
 
 # Python Software Foundation License
@@ -377,13 +357,13 @@
 #==============================================================================
 # Hybrid property/method
 #==============================================================================
-from sqlalchemy.ext.hybrid import hybrid_method, hybrid_property
+from sqlalchemy.ext.hybrid import hybrid_property
 
 
 #==============================================================================
-# kill FUNCTIONS
+# kill
 #==============================================================================
-if is_windows:
+if os.name == 'nt': # Windows
     import ctypes
 
     def kill(pid, sig):
@@ -394,175 +374,3 @@
 
 else:
     kill = os.kill
-
-
-#==============================================================================
-# itertools.product
-#==============================================================================
-
-try:
-    from itertools import product
-except ImportError:
-    def product(*args, **kwds):
-        # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
-        # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
-        pools = map(tuple, args) * kwds.get('repeat', 1)
-        result = [[]]
-        for pool in pools:
-            result = [x + [y] for x in result for y in pool]
-        for prod in result:
-            yield tuple(prod)
-
-
-#==============================================================================
-# BytesIO
-#==============================================================================
-
-try:
-    from io import BytesIO
-except ImportError:
-    from cStringIO import StringIO as BytesIO
-
-
-#==============================================================================
-# bytes
-#==============================================================================
-if __py_version__ >= (2, 6):
-    _bytes = bytes
-else:
-    # in py2.6 bytes is a synonym for str
-    _bytes = str
-
-if __py_version__ >= (2, 6):
-    _bytearray = bytearray
-else:
-    import array
-    # no idea if this is correct but all integration tests are passing
-    # i think we never use bytearray anyway
-    _bytearray = array
-
-
-#==============================================================================
-# deque
-#==============================================================================
-
-if __py_version__ >= (2, 6):
-    from collections import deque
-else:
-    #need to implement our own deque with maxlen
-    class deque(object):
-
-        def __init__(self, iterable=(), maxlen= -1):
-            if not hasattr(self, 'data'):
-                self.left = self.right = 0
-                self.data = {}
-            self.maxlen = maxlen or -1
-            self.extend(iterable)
-
-        def append(self, x):
-            self.data[self.right] = x
-            self.right += 1
-            if self.maxlen != -1 and len(self) > self.maxlen:
-                self.popleft()
-
-        def appendleft(self, x):
-            self.left -= 1
-            self.data[self.left] = x
-            if self.maxlen != -1 and len(self) > self.maxlen:
-                self.pop()
-
-        def pop(self):
-            if self.left == self.right:
-                raise IndexError('cannot pop from empty deque')
-            self.right -= 1
-            elem = self.data[self.right]
-            del self.data[self.right]
-            return elem
-
-        def popleft(self):
-            if self.left == self.right:
-                raise IndexError('cannot pop from empty deque')
-            elem = self.data[self.left]
-            del self.data[self.left]
-            self.left += 1
-            return elem
-
-        def clear(self):
-            self.data.clear()
-            self.left = self.right = 0
-
-        def extend(self, iterable):
-            for elem in iterable:
-                self.append(elem)
-
-        def extendleft(self, iterable):
-            for elem in iterable:
-                self.appendleft(elem)
-
-        def rotate(self, n=1):
-            if self:
-                n %= len(self)
-                for i in xrange(n):
-                    self.appendleft(self.pop())
-
-        def __getitem__(self, i):
-            if i < 0:
-                i += len(self)
-            try:
-                return self.data[i + self.left]
-            except KeyError:
-                raise IndexError
-
-        def __setitem__(self, i, value):
-            if i < 0:
-                i += len(self)
-            try:
-                self.data[i + self.left] = value
-            except KeyError:
-                raise IndexError
-
-        def __delitem__(self, i):
-            size = len(self)
-            if not (-size <= i < size):
-                raise IndexError
-            data = self.data
-            if i < 0:
-                i += size
-            for j in xrange(self.left + i, self.right - 1):
-                data[j] = data[j + 1]
-            self.pop()
-
-        def __len__(self):
-            return self.right - self.left
-
-        def __cmp__(self, other):
-            if type(self) != type(other):
-                return cmp(type(self), type(other))
-            return cmp(list(self), list(other))
-
-        def __repr__(self, _track=[]):
-            if id(self) in _track:
-                return '...'
-            _track.append(id(self))
-            r = 'deque(%r, maxlen=%s)' % (list(self), self.maxlen)
-            _track.remove(id(self))
-            return r
-
-        def __getstate__(self):
-            return (tuple(self),)
-
-        def __setstate__(self, s):
-            self.__init__(s[0])
-
-        def __hash__(self):
-            raise TypeError
-
-        def __copy__(self):
-            return self.__class__(self)
-
-        def __deepcopy__(self, memo={}):
-            from copy import deepcopy
-            result = self.__class__()
-            memo[id(self)] = result
-            result.__init__(deepcopy(tuple(self), memo))
-            return result
--- a/kallithea/lib/db_manage.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/db_manage.py	Fri Nov 18 01:11:13 2016 +0100
@@ -31,14 +31,16 @@
 import time
 import uuid
 import logging
-from os.path import dirname as dn, join as jn
+from os.path import dirname
 
-from kallithea import __dbversion__, __py_version__, EXTERN_TYPE_INTERNAL, DB_MIGRATIONS
+import alembic.config
+import alembic.command
+
+from kallithea.lib.paster_commands.common import ask_ok
 from kallithea.model.user import UserModel
-from kallithea.lib.utils import ask_ok
-from kallithea.model import init_model
+from kallithea.model.base import init_model
 from kallithea.model.db import User, Permission, Ui, \
-    Setting, UserToPerm, DbMigrateVersion, RepoGroup, \
+    Setting, UserToPerm, RepoGroup, \
     UserRepoGroupToPerm, CacheInvalidation, Repository
 
 from sqlalchemy.engine import create_engine
@@ -61,20 +63,22 @@
 
 
 class DbManage(object):
-    def __init__(self, log_sql, dbconf, root, tests=False, SESSION=None, cli_args={}):
+    def __init__(self, log_sql, dbconf, root, tests=False, SESSION=None, cli_args=None):
         self.dbname = dbconf.split('/')[-1]
         self.tests = tests
         self.root = root
         self.dburi = dbconf
         self.log_sql = log_sql
         self.db_exists = False
-        self.cli_args = cli_args
+        self.cli_args = cli_args or {}
         self.init_db(SESSION=SESSION)
 
+    def _ask_ok(self, msg):
+        """Invoke ask_ok unless the force_ask option provides the answer"""
         force_ask = self.cli_args.get('force_ask')
         if force_ask is not None:
-            global ask_ok
-            ask_ok = lambda *args, **kwargs: force_ask
+            return force_ask
+        return ask_ok(msg)
 
     def init_db(self, SESSION=None):
         if SESSION:
@@ -94,7 +98,7 @@
         if self.tests:
             destroy = True
         else:
-            destroy = ask_ok('Are you sure to destroy old database ? [y/n]')
+            destroy = self._ask_ok('Are you sure to destroy old database ? [y/n]')
         if not destroy:
             print 'Nothing done.'
             sys.exit(0)
@@ -103,89 +107,27 @@
 
         checkfirst = not override
         Base.metadata.create_all(checkfirst=checkfirst)
-        log.info('Created tables for %s', self.dbname)
-
-    def set_db_version(self):
-        ver = DbMigrateVersion()
-        ver.version = __dbversion__
-        ver.repository_id = DB_MIGRATIONS
-        ver.repository_path = 'versions'
-        self.sa.add(ver)
-        log.info('db version set to: %s', __dbversion__)
-
-    def upgrade(self):
-        """
-        Upgrades given database schema to given revision following
-        all needed steps, to perform the upgrade
-
-        """
-
-        from kallithea.lib.dbmigrate.migrate.versioning import api
-        from kallithea.lib.dbmigrate.migrate.exceptions import \
-            DatabaseNotControlledError
-
-        if 'sqlite' in self.dburi:
-            print (
-               '********************** WARNING **********************\n'
-               'Make sure your version of sqlite is at least 3.7.X.  \n'
-               'Earlier versions are known to fail on some migrations\n'
-               '*****************************************************\n')
-
-        upgrade = ask_ok('You are about to perform database upgrade, make '
-                         'sure You backed up your database before. '
-                         'Continue ? [y/n]')
-        if not upgrade:
-            print 'No upgrade performed'
-            sys.exit(0)
 
-        repository_path = jn(dn(dn(dn(os.path.realpath(__file__)))),
-                             'kallithea/lib/dbmigrate')
-        db_uri = self.dburi
-
-        try:
-            curr_version = api.db_version(db_uri, repository_path)
-            msg = ('Found current database under version '
-                   'control with version %s' % curr_version)
-
-        except (RuntimeError, DatabaseNotControlledError):
-            curr_version = 1
-            msg = ('Current database is not under version control. Setting '
-                   'as version %s' % curr_version)
-            api.version_control(db_uri, repository_path, curr_version)
-
-        notify(msg)
-        if curr_version == __dbversion__:
-            print 'This database is already at the newest version'
-            sys.exit(0)
+        # Create an Alembic configuration and generate the version table,
+        # "stamping" it with the most recent Alembic migration revision, to
+        # tell Alembic that all the schema upgrades are already in effect.
+        alembic_cfg = alembic.config.Config()
+        alembic_cfg.set_main_option('script_location', 'kallithea:alembic')
+        alembic_cfg.set_main_option('sqlalchemy.url', self.dburi)
+        # This command will give an error in an Alembic multi-head scenario,
+        # but in practice, such a scenario should not come up during database
+        # creation, even during development.
+        alembic.command.stamp(alembic_cfg, 'head')
 
-        # clear cache keys
-        log.info("Clearing cache keys now...")
-        CacheInvalidation.clear_cache()
-
-        upgrade_steps = range(curr_version + 1, __dbversion__ + 1)
-        notify('attempting to do database upgrade from '
-               'version %s to version %s' % (curr_version, __dbversion__))
-
-        # CALL THE PROPER ORDER OF STEPS TO PERFORM FULL UPGRADE
-        _step = None
-        for step in upgrade_steps:
-            notify('performing upgrade step %s' % step)
-            time.sleep(0.5)
-
-            api.upgrade(db_uri, repository_path, step)
-            notify('schema upgrade for step %s completed' % (step,))
-
-            _step = step
-
-        notify('upgrade to version %s successful' % _step)
+        log.info('Created tables for %s', self.dbname)
 
     def fix_repo_paths(self):
         """
         Fixes a old kallithea version path into new one without a '*'
         """
 
-        paths = self.sa.query(Ui)\
-                .filter(Ui.ui_key == '/')\
+        paths = self.sa.query(Ui) \
+                .filter(Ui.ui_key == '/') \
                 .scalar()
 
         paths.ui_value = paths.ui_value.replace('*', '')
@@ -198,8 +140,8 @@
         Fixes a old default user with some 'nicer' default values,
         used mostly for anonymous access
         """
-        def_user = self.sa.query(User)\
-                .filter(User.username == User.DEFAULT_USER)\
+        def_user = self.sa.query(User) \
+                .filter(User.username == User.DEFAULT_USER) \
                 .one()
 
         def_user.name = 'Anonymous'
@@ -223,11 +165,9 @@
         if not self.tests:
             import getpass
 
-            # defaults
-            defaults = self.cli_args
-            username = defaults.get('username')
-            password = defaults.get('password')
-            email = defaults.get('email')
+            username = self.cli_args.get('username')
+            password = self.cli_args.get('password')
+            email = self.cli_args.get('email')
 
             def get_password():
                 password = getpass.getpass('Specify admin password '
@@ -256,7 +196,7 @@
             self.create_user(username, password, email, True)
         else:
             log.info('creating admin and regular test users')
-            from kallithea.tests import TEST_USER_ADMIN_LOGIN, \
+            from kallithea.tests.base import TEST_USER_ADMIN_LOGIN, \
             TEST_USER_ADMIN_PASS, TEST_USER_ADMIN_EMAIL, \
             TEST_USER_REGULAR_LOGIN, TEST_USER_REGULAR_PASS, \
             TEST_USER_REGULAR_EMAIL, TEST_USER_REGULAR2_LOGIN, \
@@ -278,7 +218,7 @@
 
         #HOOKS
         hooks1_key = Ui.HOOK_UPDATE
-        hooks1_ = self.sa.query(Ui)\
+        hooks1_ = self.sa.query(Ui) \
             .filter(Ui.ui_key == hooks1_key).scalar()
 
         hooks1 = Ui() if hooks1_ is None else hooks1_
@@ -289,7 +229,7 @@
         self.sa.add(hooks1)
 
         hooks2_key = Ui.HOOK_REPO_SIZE
-        hooks2_ = self.sa.query(Ui)\
+        hooks2_ = self.sa.query(Ui) \
             .filter(Ui.ui_key == hooks2_key).scalar()
         hooks2 = Ui() if hooks2_ is None else hooks2_
         hooks2.ui_section = 'hooks'
@@ -390,9 +330,9 @@
             g.group_name = g.get_new_name(g.name)
             self.sa.add(g)
             # get default perm
-            default = UserRepoGroupToPerm.query()\
-                .filter(UserRepoGroupToPerm.group == g)\
-                .filter(UserRepoGroupToPerm.user == def_usr)\
+            default = UserRepoGroupToPerm.query() \
+                .filter(UserRepoGroupToPerm.group == g) \
+                .filter(UserRepoGroupToPerm.user == def_usr) \
                 .scalar()
 
             if default is None:
@@ -411,7 +351,7 @@
         if not default_user:
             return
 
-        u2p = UserToPerm.query()\
+        u2p = UserToPerm.query() \
             .filter(UserToPerm.user == default_user).all()
         fixed = False
         if len(u2p) != len(Permission.DEFAULT_USER_PERMISSIONS):
@@ -422,11 +362,11 @@
         return fixed
 
     def update_repo_info(self):
-        RepoModel.update_repoinfo()
+        for repo in Repository.query():
+            repo.update_changeset_cache()
 
     def config_prompt(self, test_repo_path='', retries=3):
-        defaults = self.cli_args
-        _path = defaults.get('repos_location')
+        _path = self.cli_args.get('repos_location')
         if retries == 3:
             log.info('Setting up repositories config')
 
@@ -458,7 +398,7 @@
         # check write access, warn user about non writeable paths
         elif not os.access(path, os.W_OK) and path_ok:
             log.warning('No write permission to given path %s', path)
-            if not ask_ok('Given path %s is not writeable, do you want to '
+            if not self._ask_ok('Given path %s is not writeable, do you want to '
                           'continue with read only mode ? [y/n]' % (path,)):
                 log.error('Canceled by user')
                 sys.exit(-1)
@@ -466,8 +406,10 @@
         if retries == 0:
             sys.exit('max retries reached')
         if not path_ok:
+            if _path is not None:
+                sys.exit('Invalid repo path: %s' % _path)
             retries -= 1
-            return self.config_prompt(test_repo_path, retries)
+            return self.config_prompt(test_repo_path, retries) # recursing!!!
 
         real_path = os.path.normpath(os.path.realpath(path))
 
@@ -481,9 +423,7 @@
         self.create_ui_settings(path)
 
         ui_config = [
-            ('web', 'push_ssl', 'false'),
             ('web', 'allow_archive', 'gz zip bz2'),
-            ('web', 'allow_push', '*'),
             ('web', 'baseurl', '/'),
             ('paths', '/', path),
             #('phases', 'publish', 'false')
@@ -502,7 +442,7 @@
             ('show_public_icon', True, 'bool'),
             ('show_private_icon', True, 'bool'),
             ('stylify_metatags', False, 'bool'),
-            ('dashboard_items', 100, 'int'),
+            ('dashboard_items', 100, 'int'), # TODO: call it page_size
             ('admin_grid_items', 25, 'int'),
             ('show_version', True, 'bool'),
             ('use_gravatar', True, 'bool'),
@@ -522,9 +462,9 @@
     def create_user(self, username, password, email='', admin=False):
         log.info('creating user %s', username)
         UserModel().create_or_update(username, password, email,
-                                     firstname='Kallithea', lastname='Admin',
+                                     firstname=u'Kallithea', lastname=u'Admin',
                                      active=True, admin=admin,
-                                     extern_type=EXTERN_TYPE_INTERNAL)
+                                     extern_type=User.DEFAULT_AUTH_TYPE)
 
     def create_default_user(self):
         log.info('creating default user')
@@ -532,14 +472,13 @@
         user = UserModel().create_or_update(username=User.DEFAULT_USER,
                                             password=str(uuid.uuid1())[:20],
                                             email='anonymous@kallithea-scm.org',
-                                            firstname='Anonymous',
-                                            lastname='User')
+                                            firstname=u'Anonymous',
+                                            lastname=u'User')
         # based on configuration options activate/deactivate this user which
         # controls anonymous access
         if self.cli_args.get('public_access') is False:
             log.info('Public access disabled')
             user.active = False
-            Session().add(user)
             Session().commit()
 
     def create_permissions(self):
@@ -558,13 +497,3 @@
         """
         log.info('creating default user permissions')
         PermissionModel(self.sa).create_default_permissions(user=User.DEFAULT_USER)
-
-    @staticmethod
-    def check_waitress():
-        """
-        Function executed at the end of setup
-        """
-        if not __py_version__ >= (2, 6):
-            notify('Python2.5 detected, please switch '
-                   'egg:waitress#main -> egg:Paste#http '
-                   'in your .ini file')
--- a/kallithea/lib/dbmigrate/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/dbmigrate/__init__.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,75 +1,11 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate
-~~~~~~~~~~~~~~~~~~~~~~~
+from paste.script.command import Command
 
-Database migration modules
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Dec 11, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-import logging
-
-from kallithea.lib.utils import BasePasterCommand, Command, add_cache
-from kallithea.lib.db_manage import DbManage
-
-log = logging.getLogger(__name__)
-
+class UpgradeDb(Command):
+    hidden = True
+    summary = '(removed)'
 
-class UpgradeDb(BasePasterCommand):
-    """Command used for paster to upgrade our database to newer version
-    """
-
-    max_args = 1
-    min_args = 1
-
-    usage = "CONFIG_FILE"
-    summary = "Upgrades current db to newer version"
-    group_name = "Kallithea"
-
-    parser = Command.standard_parser(verbose=True)
-
-    def command(self):
-        from pylons import config
-        add_cache(config)
-
-        db_uri = config['sqlalchemy.db1.url']
-        dbmanage = DbManage(log_sql=True, dbconf=db_uri,
-                            root=config['here'], tests=False,
-                            cli_args=self.options.__dict__)
-        dbmanage.upgrade()
-
-    def update_parser(self):
-        self.parser.add_option('--sql',
-                      action='store_true',
-                      dest='just_sql',
-                      help="Prints upgrade sql for further investigation",
-                      default=False)
-
-        self.parser.add_option('--force-yes',
-                           action='store_true',
-                           dest='force_ask',
-                           default=None,
-                           help='Force yes to every question')
-        self.parser.add_option('--force-no',
-                           action='store_false',
-                           dest='force_ask',
-                           default=None,
-                           help='Force no to every question')
+    def run(self, args):
+        raise SystemExit(
+            'The "paster upgrade-db" command has been removed; please see the docs:\n'
+            '    https://kallithea.readthedocs.io/en/default/upgrade.html'
+        )
--- a/kallithea/lib/dbmigrate/migrate.cfg	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,20 +0,0 @@
-[db_settings]
-# Used to identify which repository this database is versioned under.
-# You can use the name of your project.
-repository_id=kallithea_db_migrations
-
-# The name of the database table used to track the schema version.
-# This name shouldn't already be used by your project.
-# If this is changed once a database is under version control, you'll need to
-# change the table name in each database too.
-version_table=db_migrate_version
-
-# When committing a change script, Migrate will attempt to generate the
-# sql for all supported databases; normally, if one of them fails - probably
-# because you don't have that database installed - it is ignored and the
-# commit continues, perhaps ending successfully.
-# Databases in this list MUST compile successfully during a commit, or the
-# entire commit will fail. List the databases your application will actually
-# be using to ensure your updates to that database work properly.
-# This must be a list; example: ['postgres','sqlite']
-required_dbs=['sqlite']
--- a/kallithea/lib/dbmigrate/migrate/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,11 +0,0 @@
-"""
-   SQLAlchemy migrate provides two APIs :mod:`migrate.versioning` for
-   database schema version and repository management and
-   :mod:`migrate.changeset` that allows to define database schema changes
-   using Python.
-"""
-
-from kallithea.lib.dbmigrate.migrate.versioning import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-__version__ = '0.7.3.dev'
--- a/kallithea/lib/dbmigrate/migrate/changeset/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,30 +0,0 @@
-"""
-   This module extends SQLAlchemy and provides additional DDL [#]_
-   support.
-
-   .. [#] SQL Data Definition Language
-"""
-import re
-import warnings
-
-import sqlalchemy
-from sqlalchemy import __version__ as _sa_version
-
-warnings.simplefilter('always', DeprecationWarning)
-
-_sa_version = tuple(int(re.match("\d+", x).group(0))
-                    for x in _sa_version.split("."))
-SQLA_06 = _sa_version >= (0, 6)
-SQLA_07 = _sa_version >= (0, 7)
-
-del re
-del _sa_version
-
-from kallithea.lib.dbmigrate.migrate.changeset.schema import *
-from kallithea.lib.dbmigrate.migrate.changeset.constraint import *
-
-sqlalchemy.schema.Table.__bases__ += (ChangesetTable,)
-sqlalchemy.schema.Column.__bases__ += (ChangesetColumn,)
-sqlalchemy.schema.Index.__bases__ += (ChangesetIndex,)
-
-sqlalchemy.schema.DefaultClause.__bases__ += (ChangesetDefaultClause,)
--- a/kallithea/lib/dbmigrate/migrate/changeset/ansisql.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,293 +0,0 @@
-"""
-   Extensions to SQLAlchemy for altering existing tables.
-
-   At the moment, this isn't so much based off of ANSI as much as
-   things that just happen to work with multiple databases.
-"""
-import StringIO
-
-import sqlalchemy as sa
-from sqlalchemy.schema import SchemaVisitor
-from sqlalchemy.engine.default import DefaultDialect
-from sqlalchemy.sql import ClauseElement
-from sqlalchemy.schema import (ForeignKeyConstraint,
-                               PrimaryKeyConstraint,
-                               CheckConstraint,
-                               UniqueConstraint,
-                               Index)
-
-from kallithea.lib.dbmigrate.migrate import exceptions
-from kallithea.lib.dbmigrate.migrate.changeset import constraint
-
-from sqlalchemy.schema import AddConstraint, DropConstraint
-from sqlalchemy.sql.compiler import DDLCompiler
-SchemaGenerator = SchemaDropper = DDLCompiler
-
-
-class AlterTableVisitor(SchemaVisitor):
-    """Common operations for ``ALTER TABLE`` statements."""
-
-    # engine.Compiler looks for .statement
-    # when it spawns off a new compiler
-    statement = ClauseElement()
-
-    def append(self, s):
-        """Append content to the SchemaIterator's query buffer."""
-
-        self.buffer.write(s)
-
-    def execute(self):
-        """Execute the contents of the SchemaIterator's buffer."""
-        try:
-            return self.connection.execute(self.buffer.getvalue())
-        finally:
-            self.buffer.truncate(0)
-
-    def __init__(self, dialect, connection, **kw):
-        self.connection = connection
-        self.buffer = StringIO.StringIO()
-        self.preparer = dialect.identifier_preparer
-        self.dialect = dialect
-
-    def traverse_single(self, elem):
-        ret = super(AlterTableVisitor, self).traverse_single(elem)
-        if ret:
-            # adapt to 0.6 which uses a string-returning
-            # object
-            self.append(" %s" % ret)
-
-    def _to_table(self, param):
-        """Returns the table object for the given param object."""
-        if isinstance(param, (sa.Column, sa.Index, sa.schema.Constraint)):
-            ret = param.table
-        else:
-            ret = param
-        return ret
-
-    def start_alter_table(self, param):
-        """Returns the start of an ``ALTER TABLE`` SQL-Statement.
-
-        Use the param object to determine the table name and use it
-        for building the SQL statement.
-
-        :param param: object to determine the table from
-        :type param: :class:`sqlalchemy.Column`, :class:`sqlalchemy.Index`,
-          :class:`sqlalchemy.schema.Constraint`, :class:`sqlalchemy.Table`,
-          or string (table name)
-        """
-        table = self._to_table(param)
-        self.append('\nALTER TABLE %s ' % self.preparer.format_table(table))
-        return table
-
-
-class ANSIColumnGenerator(AlterTableVisitor, SchemaGenerator):
-    """Extends ansisql generator for column creation (alter table add col)"""
-
-    def visit_column(self, column):
-        """Create a column (table already exists).
-
-        :param column: column object
-        :type column: :class:`sqlalchemy.Column` instance
-        """
-        if column.default is not None:
-            self.traverse_single(column.default)
-
-        table = self.start_alter_table(column)
-        self.append("ADD ")
-
-        self.append(self.get_column_specification(column))
-
-        for cons in column.constraints:
-            self.traverse_single(cons)
-        self.execute()
-
-        # ALTER TABLE STATEMENTS
-
-        # add indexes and unique constraints
-        if column.index_name:
-            Index(column.index_name,column).create()
-        elif column.unique_name:
-            constraint.UniqueConstraint(column,
-                                        name=column.unique_name).create()
-
-        # SA bounds FK constraints to table, add manually
-        for fk in column.foreign_keys:
-            self.add_foreignkey(fk.constraint)
-
-        # add primary key constraint if needed
-        if column.primary_key_name:
-            cons = constraint.PrimaryKeyConstraint(column,
-                                                   name=column.primary_key_name)
-            cons.create()
-
-    def add_foreignkey(self, fk):
-        self.connection.execute(AddConstraint(fk))
-
-class ANSIColumnDropper(AlterTableVisitor, SchemaDropper):
-    """Extends ANSI SQL dropper for column dropping (``ALTER TABLE
-    DROP COLUMN``).
-    """
-
-    def visit_column(self, column):
-        """Drop a column from its table.
-
-        :param column: the column object
-        :type column: :class:`sqlalchemy.Column`
-        """
-        table = self.start_alter_table(column)
-        self.append('DROP COLUMN %s' % self.preparer.format_column(column))
-        self.execute()
-
-
-class ANSISchemaChanger(AlterTableVisitor, SchemaGenerator):
-    """Manages changes to existing schema elements.
-
-    Note that columns are schema elements; ``ALTER TABLE ADD COLUMN``
-    is in SchemaGenerator.
-
-    All items may be renamed. Columns can also have many of their properties -
-    type, for example - changed.
-
-    Each function is passed a tuple, containing (object, name); where
-    object is a type of object you'd expect for that function
-    (ie. table for visit_table) and name is the object's new
-    name. NONE means the name is unchanged.
-    """
-
-    def visit_table(self, table):
-        """Rename a table. Other ops aren't supported."""
-        self.start_alter_table(table)
-        self.append("RENAME TO %s" % self.preparer.quote(table.new_name,
-                                                         table.quote))
-        self.execute()
-
-    def visit_index(self, index):
-        """Rename an index"""
-        if hasattr(self, '_validate_identifier'):
-            # SA <= 0.6.3
-            self.append("ALTER INDEX %s RENAME TO %s" % (
-                    self.preparer.quote(
-                        self._validate_identifier(
-                            index.name, True), index.quote),
-                    self.preparer.quote(
-                        self._validate_identifier(
-                            index.new_name, True), index.quote)))
-        else:
-            # SA >= 0.6.5
-            self.append("ALTER INDEX %s RENAME TO %s" % (
-                    self.preparer.quote(
-                        self._index_identifier(
-                            index.name), index.quote),
-                    self.preparer.quote(
-                        self._index_identifier(
-                            index.new_name), index.quote)))
-        self.execute()
-
-    def visit_column(self, delta):
-        """Rename/change a column."""
-        # ALTER COLUMN is implemented as several ALTER statements
-        keys = delta.keys()
-        if 'type' in keys:
-            self._run_subvisit(delta, self._visit_column_type)
-        if 'nullable' in keys:
-            self._run_subvisit(delta, self._visit_column_nullable)
-        if 'server_default' in keys:
-            # Skip 'default': only handle server-side defaults, others
-            # are managed by the app, not the db.
-            self._run_subvisit(delta, self._visit_column_default)
-        if 'name' in keys:
-            self._run_subvisit(delta, self._visit_column_name, start_alter=False)
-
-    def _run_subvisit(self, delta, func, start_alter=True):
-        """Runs visit method based on what needs to be changed on column"""
-        table = self._to_table(delta.table)
-        col_name = delta.current_name
-        if start_alter:
-            self.start_alter_column(table, col_name)
-        ret = func(table, delta.result_column, delta)
-        self.execute()
-
-    def start_alter_column(self, table, col_name):
-        """Starts ALTER COLUMN"""
-        self.start_alter_table(table)
-        self.append("ALTER COLUMN %s " % self.preparer.quote(col_name, table.quote))
-
-    def _visit_column_nullable(self, table, column, delta):
-        nullable = delta['nullable']
-        if nullable:
-            self.append("DROP NOT NULL")
-        else:
-            self.append("SET NOT NULL")
-
-    def _visit_column_default(self, table, column, delta):
-        default_text = self.get_column_default_string(column)
-        if default_text is not None:
-            self.append("SET DEFAULT %s" % default_text)
-        else:
-            self.append("DROP DEFAULT")
-
-    def _visit_column_type(self, table, column, delta):
-        type_ = delta['type']
-        type_text = str(type_.compile(dialect=self.dialect))
-        self.append("TYPE %s" % type_text)
-
-    def _visit_column_name(self, table, column, delta):
-        self.start_alter_table(table)
-        col_name = self.preparer.quote(delta.current_name, table.quote)
-        new_name = self.preparer.format_column(delta.result_column)
-        self.append('RENAME COLUMN %s TO %s' % (col_name, new_name))
-
-
-class ANSIConstraintCommon(AlterTableVisitor):
-    """
-    Migrate's constraints require a separate creation function from
-    SA's: Migrate's constraints are created independently of a table;
-    SA's are created at the same time as the table.
-    """
-
-    def get_constraint_name(self, cons):
-        """Gets a name for the given constraint.
-
-        If the name is already set it will be used otherwise the
-        constraint's :meth:`autoname <migrate.changeset.constraint.ConstraintChangeset.autoname>`
-        method is used.
-
-        :param cons: constraint object
-        """
-        if cons.name is not None:
-            ret = cons.name
-        else:
-            ret = cons.name = cons.autoname()
-        return self.preparer.quote(ret, cons.quote)
-
-    def visit_migrate_primary_key_constraint(self, *p, **k):
-        self._visit_constraint(*p, **k)
-
-    def visit_migrate_foreign_key_constraint(self, *p, **k):
-        self._visit_constraint(*p, **k)
-
-    def visit_migrate_check_constraint(self, *p, **k):
-        self._visit_constraint(*p, **k)
-
-    def visit_migrate_unique_constraint(self, *p, **k):
-        self._visit_constraint(*p, **k)
-
-class ANSIConstraintGenerator(ANSIConstraintCommon, SchemaGenerator):
-    def _visit_constraint(self, constraint):
-        constraint.name = self.get_constraint_name(constraint)
-        self.append(self.process(AddConstraint(constraint)))
-        self.execute()
-
-class ANSIConstraintDropper(ANSIConstraintCommon, SchemaDropper):
-    def _visit_constraint(self, constraint):
-        constraint.name = self.get_constraint_name(constraint)
-        self.append(self.process(DropConstraint(constraint, cascade=constraint.cascade)))
-        self.execute()
-
-
-class ANSIDialect(DefaultDialect):
-    columngenerator = ANSIColumnGenerator
-    columndropper = ANSIColumnDropper
-    schemachanger = ANSISchemaChanger
-    constraintgenerator = ANSIConstraintGenerator
-    constraintdropper = ANSIConstraintDropper
--- a/kallithea/lib/dbmigrate/migrate/changeset/constraint.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,200 +0,0 @@
-"""
-   This module defines standalone schema constraint classes.
-"""
-from sqlalchemy import schema
-
-from kallithea.lib.dbmigrate.migrate.exceptions import *
-
-
-class ConstraintChangeset(object):
-    """Base class for Constraint classes."""
-
-    def _normalize_columns(self, cols, table_name=False):
-        """Given: column objects or names; return col names and
-        (maybe) a table"""
-        colnames = []
-        table = None
-        for col in cols:
-            if isinstance(col, schema.Column):
-                if col.table is not None and table is None:
-                    table = col.table
-                if table_name:
-                    col = '.'.join((col.table.name, col.name))
-                else:
-                    col = col.name
-            colnames.append(col)
-        return colnames, table
-
-    def __do_imports(self, visitor_name, *a, **kw):
-        engine = kw.pop('engine', self.table.bind)
-        from kallithea.lib.dbmigrate.migrate.changeset.databases.visitor import (get_engine_visitor,
-                                                                                 run_single_visitor)
-        visitorcallable = get_engine_visitor(engine, visitor_name)
-        run_single_visitor(engine, visitorcallable, self, *a, **kw)
-
-    def create(self, *a, **kw):
-        """Create the constraint in the database.
-
-        :param engine: the database engine to use. If this is \
-        :keyword:`None` the instance's engine will be used
-        :type engine: :class:`sqlalchemy.engine.base.Engine`
-        :param connection: reuse connection instead of creating new one.
-        :type connection: :class:`sqlalchemy.engine.base.Connection` instance
-        """
-        # TODO: set the parent here instead of in __init__
-        self.__do_imports('constraintgenerator', *a, **kw)
-
-    def drop(self, *a, **kw):
-        """Drop the constraint from the database.
-
-        :param engine: the database engine to use. If this is
-          :keyword:`None` the instance's engine will be used
-        :param cascade: Issue CASCADE drop if database supports it
-        :type engine: :class:`sqlalchemy.engine.base.Engine`
-        :type cascade: bool
-        :param connection: reuse connection instead of creating new one.
-        :type connection: :class:`sqlalchemy.engine.base.Connection` instance
-        :returns: Instance with cleared columns
-        """
-        self.cascade = kw.pop('cascade', False)
-        self.__do_imports('constraintdropper', *a, **kw)
-        # the spirit of Constraint objects is that they
-        # are immutable (just like in a DB.  they're only ADDed
-        # or DROPped).
-        #self.columns.clear()
-        return self
-
-
-class PrimaryKeyConstraint(ConstraintChangeset, schema.PrimaryKeyConstraint):
-    """Construct PrimaryKeyConstraint
-
-    Migrate's additional parameters:
-
-    :param cols: Columns in constraint.
-    :param table: If columns are passed as strings, this kw is required
-    :type table: Table instance
-    :type cols: strings or Column instances
-    """
-
-    __migrate_visit_name__ = 'migrate_primary_key_constraint'
-
-    def __init__(self, *cols, **kwargs):
-        colnames, table = self._normalize_columns(cols)
-        table = kwargs.pop('table', table)
-        super(PrimaryKeyConstraint, self).__init__(*colnames, **kwargs)
-        if table is not None:
-            self._set_parent(table)
-
-    def autoname(self):
-        """Mimic the database's automatic constraint names"""
-        return "%s_pkey" % self.table.name
-
-
-class ForeignKeyConstraint(ConstraintChangeset, schema.ForeignKeyConstraint):
-    """Construct ForeignKeyConstraint
-
-    Migrate's additional parameters:
-
-    :param columns: Columns in constraint
-    :param refcolumns: Columns that this FK reffers to in another table.
-    :param table: If columns are passed as strings, this kw is required
-    :type table: Table instance
-    :type columns: list of strings or Column instances
-    :type refcolumns: list of strings or Column instances
-    """
-
-    __migrate_visit_name__ = 'migrate_foreign_key_constraint'
-
-    def __init__(self, columns, refcolumns, *args, **kwargs):
-        colnames, table = self._normalize_columns(columns)
-        table = kwargs.pop('table', table)
-        refcolnames, reftable = self._normalize_columns(refcolumns,
-                                                        table_name=True)
-        super(ForeignKeyConstraint, self).__init__(
-            colnames, refcolnames, *args,**kwargs
-        )
-        if table is not None:
-            self._set_parent(table)
-
-    @property
-    def referenced(self):
-        return [e.column for e in self.elements]
-
-    @property
-    def reftable(self):
-        return self.referenced[0].table
-
-    def autoname(self):
-        """Mimic the database's automatic constraint names"""
-        if hasattr(self.columns, 'keys'):
-            # SA <= 0.5
-            firstcol = self.columns[self.columns.keys()[0]]
-            ret = "%(table)s_%(firstcolumn)s_fkey" % dict(
-                table=firstcol.table.name,
-                firstcolumn=firstcol.name,)
-        else:
-            # SA >= 0.6
-            ret = "%(table)s_%(firstcolumn)s_fkey" % dict(
-                table=self.table.name,
-                firstcolumn=self.columns[0],)
-        return ret
-
-
-class CheckConstraint(ConstraintChangeset, schema.CheckConstraint):
-    """Construct CheckConstraint
-
-    Migrate's additional parameters:
-
-    :param sqltext: Plain SQL text to check condition
-    :param columns: If not name is applied, you must supply this kw\
-    to autoname constraint
-    :param table: If columns are passed as strings, this kw is required
-    :type table: Table instance
-    :type columns: list of Columns instances
-    :type sqltext: string
-    """
-
-    __migrate_visit_name__ = 'migrate_check_constraint'
-
-    def __init__(self, sqltext, *args, **kwargs):
-        cols = kwargs.pop('columns', [])
-        if not cols and not kwargs.get('name', False):
-            raise InvalidConstraintError('You must either set "name"'
-                'parameter or "columns" to autogenarate it.')
-        colnames, table = self._normalize_columns(cols)
-        table = kwargs.pop('table', table)
-        schema.CheckConstraint.__init__(self, sqltext, *args, **kwargs)
-        if table is not None:
-            self._set_parent(table)
-        self.colnames = colnames
-
-    def autoname(self):
-        return "%(table)s_%(cols)s_check" % \
-            dict(table=self.table.name, cols="_".join(self.colnames))
-
-
-class UniqueConstraint(ConstraintChangeset, schema.UniqueConstraint):
-    """Construct UniqueConstraint
-
-    Migrate's additional parameters:
-
-    :param cols: Columns in constraint.
-    :param table: If columns are passed as strings, this kw is required
-    :type table: Table instance
-    :type cols: strings or Column instances
-
-    .. versionadded:: 0.6.0
-    """
-
-    __migrate_visit_name__ = 'migrate_unique_constraint'
-
-    def __init__(self, *cols, **kwargs):
-        self.colnames, table = self._normalize_columns(cols)
-        table = kwargs.pop('table', table)
-        super(UniqueConstraint, self).__init__(*self.colnames, **kwargs)
-        if table is not None:
-            self._set_parent(table)
-
-    def autoname(self):
-        """Mimic the database's automatic constraint names"""
-        return "%s_%s_key" % (self.table.name, '_'.join(self.colnames))
--- a/kallithea/lib/dbmigrate/migrate/changeset/databases/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,10 +0,0 @@
-"""
-   This module contains database dialect specific changeset
-   implementations.
-"""
-__all__ = [
-    'postgres',
-    'sqlite',
-    'mysql',
-    'oracle',
-]
--- a/kallithea/lib/dbmigrate/migrate/changeset/databases/firebird.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,93 +0,0 @@
-"""
-   Firebird database specific implementations of changeset classes.
-"""
-from sqlalchemy.databases import firebird as sa_base
-from sqlalchemy.schema import PrimaryKeyConstraint
-from kallithea.lib.dbmigrate.migrate import exceptions
-from kallithea.lib.dbmigrate.migrate.changeset import ansisql
-
-
-FBSchemaGenerator = sa_base.FBDDLCompiler
-
-class FBColumnGenerator(FBSchemaGenerator, ansisql.ANSIColumnGenerator):
-    """Firebird column generator implementation."""
-
-
-class FBColumnDropper(ansisql.ANSIColumnDropper):
-    """Firebird column dropper implementation."""
-
-    def visit_column(self, column):
-        """Firebird supports 'DROP col' instead of 'DROP COLUMN col' syntax
-
-        Drop primary key and unique constraints if dropped column is referencing it."""
-        if column.primary_key:
-            if column.table.primary_key.columns.contains_column(column):
-                column.table.primary_key.drop()
-                # TODO: recreate primary key if it references more than this column
-
-        for index in column.table.indexes:
-            # "column in index.columns" causes problems as all
-            # column objects compare equal and return a SQL expression
-            if column.name in [col.name for col in index.columns]:
-                index.drop()
-                # TODO: recreate index if it references more than this column
-
-        for cons in column.table.constraints:
-            if isinstance(cons,PrimaryKeyConstraint):
-                # will be deleted only when the column its on
-                # is deleted!
-                continue
-
-            should_drop = column.name in cons.columns
-            if should_drop:
-                self.start_alter_table(column)
-                self.append("DROP CONSTRAINT ")
-                self.append(self.preparer.format_constraint(cons))
-                self.execute()
-            # TODO: recreate unique constraint if it refenrences more than this column
-
-        self.start_alter_table(column)
-        self.append('DROP %s' % self.preparer.format_column(column))
-        self.execute()
-
-
-class FBSchemaChanger(ansisql.ANSISchemaChanger):
-    """Firebird schema changer implementation."""
-
-    def visit_table(self, table):
-        """Rename table not supported"""
-        raise exceptions.NotSupportedError(
-            "Firebird does not support renaming tables.")
-
-    def _visit_column_name(self, table, column, delta):
-        self.start_alter_table(table)
-        col_name = self.preparer.quote(delta.current_name, table.quote)
-        new_name = self.preparer.format_column(delta.result_column)
-        self.append('ALTER COLUMN %s TO %s' % (col_name, new_name))
-
-    def _visit_column_nullable(self, table, column, delta):
-        """Changing NULL is not supported"""
-        # TODO: http://www.firebirdfaq.org/faq103/
-        raise exceptions.NotSupportedError(
-            "Firebird does not support altering NULL behavior.")
-
-
-class FBConstraintGenerator(ansisql.ANSIConstraintGenerator):
-    """Firebird constraint generator implementation."""
-
-
-class FBConstraintDropper(ansisql.ANSIConstraintDropper):
-    """Firebird constraint dropper implementation."""
-
-    def cascade_constraint(self, constraint):
-        """Cascading constraints is not supported"""
-        raise exceptions.NotSupportedError(
-            "Firebird does not support cascading constraints")
-
-
-class FBDialect(ansisql.ANSIDialect):
-    columngenerator = FBColumnGenerator
-    columndropper = FBColumnDropper
-    schemachanger = FBSchemaChanger
-    constraintgenerator = FBConstraintGenerator
-    constraintdropper = FBConstraintDropper
--- a/kallithea/lib/dbmigrate/migrate/changeset/databases/mysql.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-"""
-   MySQL database specific implementations of changeset classes.
-"""
-
-from sqlalchemy.databases import mysql as sa_base
-from sqlalchemy import types as sqltypes
-
-from kallithea.lib.dbmigrate.migrate import exceptions
-from kallithea.lib.dbmigrate.migrate.changeset import ansisql
-
-
-MySQLSchemaGenerator = sa_base.MySQLDDLCompiler
-
-class MySQLColumnGenerator(MySQLSchemaGenerator, ansisql.ANSIColumnGenerator):
-    pass
-
-
-class MySQLColumnDropper(ansisql.ANSIColumnDropper):
-    pass
-
-
-class MySQLSchemaChanger(MySQLSchemaGenerator, ansisql.ANSISchemaChanger):
-
-    def visit_column(self, delta):
-        table = delta.table
-        colspec = self.get_column_specification(delta.result_column)
-        if delta.result_column.autoincrement:
-            primary_keys = [c for c in table.primary_key.columns
-                       if (c.autoincrement and
-                            isinstance(c.type, sqltypes.Integer) and
-                            not c.foreign_keys)]
-
-            if primary_keys:
-                first = primary_keys.pop(0)
-                if first.name == delta.current_name:
-                    colspec += " AUTO_INCREMENT"
-        old_col_name = self.preparer.quote(delta.current_name, table.quote)
-
-        self.start_alter_table(table)
-
-        self.append("CHANGE COLUMN %s " % old_col_name)
-        self.append(colspec)
-        self.execute()
-
-    def visit_index(self, param):
-        # If MySQL can do this, I can't find how
-        raise exceptions.NotSupportedError("MySQL cannot rename indexes")
-
-
-class MySQLConstraintGenerator(ansisql.ANSIConstraintGenerator):
-    pass
-
-
-class MySQLConstraintDropper(MySQLSchemaGenerator, ansisql.ANSIConstraintDropper):
-    def visit_migrate_check_constraint(self, *p, **k):
-        raise exceptions.NotSupportedError("MySQL does not support CHECK"
-            " constraints, use triggers instead.")
-
-
-class MySQLDialect(ansisql.ANSIDialect):
-    columngenerator = MySQLColumnGenerator
-    columndropper = MySQLColumnDropper
-    schemachanger = MySQLSchemaChanger
-    constraintgenerator = MySQLConstraintGenerator
-    constraintdropper = MySQLConstraintDropper
--- a/kallithea/lib/dbmigrate/migrate/changeset/databases/oracle.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,111 +0,0 @@
-"""
-   Oracle database specific implementations of changeset classes.
-"""
-import sqlalchemy as sa
-from sqlalchemy.databases import oracle as sa_base
-
-from kallithea.lib.dbmigrate.migrate import exceptions
-from kallithea.lib.dbmigrate.migrate.changeset import ansisql, SQLA_06
-
-
-if not SQLA_06:
-    OracleSchemaGenerator = sa_base.OracleSchemaGenerator
-else:
-    OracleSchemaGenerator = sa_base.OracleDDLCompiler
-
-
-class OracleColumnGenerator(OracleSchemaGenerator, ansisql.ANSIColumnGenerator):
-    pass
-
-
-class OracleColumnDropper(ansisql.ANSIColumnDropper):
-    pass
-
-
-class OracleSchemaChanger(OracleSchemaGenerator, ansisql.ANSISchemaChanger):
-
-    def get_column_specification(self, column, **kwargs):
-        # Ignore the NOT NULL generated
-        override_nullable = kwargs.pop('override_nullable', None)
-        if override_nullable:
-            orig = column.nullable
-            column.nullable = True
-        ret = super(OracleSchemaChanger, self).get_column_specification(
-            column, **kwargs)
-        if override_nullable:
-            column.nullable = orig
-        return ret
-
-    def visit_column(self, delta):
-        keys = delta.keys()
-
-        if 'name' in keys:
-            self._run_subvisit(delta,
-                               self._visit_column_name,
-                               start_alter=False)
-
-        if len(set(('type', 'nullable', 'server_default')).intersection(keys)):
-            self._run_subvisit(delta,
-                               self._visit_column_change,
-                               start_alter=False)
-
-    def _visit_column_change(self, table, column, delta):
-        # Oracle cannot drop a default once created, but it can set it
-        # to null.  We'll do that if default=None
-        # http://forums.oracle.com/forums/message.jspa?messageID=1273234#1273234
-        dropdefault_hack = (column.server_default is None \
-                                and 'server_default' in delta.keys())
-        # Oracle apparently doesn't like it when we say "not null" if
-        # the column's already not null. Fudge it, so we don't need a
-        # new function
-        notnull_hack = ((not column.nullable) \
-                            and ('nullable' not in delta.keys()))
-        # We need to specify NULL if we're removing a NOT NULL
-        # constraint
-        null_hack = (column.nullable and ('nullable' in delta.keys()))
-
-        if dropdefault_hack:
-            column.server_default = sa.PassiveDefault(sa.sql.null())
-        if notnull_hack:
-            column.nullable = True
-        colspec = self.get_column_specification(column,
-            override_nullable=null_hack)
-        if null_hack:
-            colspec += ' NULL'
-        if notnull_hack:
-            column.nullable = False
-        if dropdefault_hack:
-            column.server_default = None
-
-        self.start_alter_table(table)
-        self.append("MODIFY (")
-        self.append(colspec)
-        self.append(")")
-
-
-class OracleConstraintCommon(object):
-
-    def get_constraint_name(self, cons):
-        # Oracle constraints can't guess their name like other DBs
-        if not cons.name:
-            raise exceptions.NotSupportedError(
-                "Oracle constraint names must be explicitly stated")
-        return cons.name
-
-
-class OracleConstraintGenerator(OracleConstraintCommon,
-                                ansisql.ANSIConstraintGenerator):
-    pass
-
-
-class OracleConstraintDropper(OracleConstraintCommon,
-                              ansisql.ANSIConstraintDropper):
-    pass
-
-
-class OracleDialect(ansisql.ANSIDialect):
-    columngenerator = OracleColumnGenerator
-    columndropper = OracleColumnDropper
-    schemachanger = OracleSchemaChanger
-    constraintgenerator = OracleConstraintGenerator
-    constraintdropper = OracleConstraintDropper
--- a/kallithea/lib/dbmigrate/migrate/changeset/databases/postgres.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,43 +0,0 @@
-"""
-   `PostgreSQL`_ database specific implementations of changeset classes.
-
-   .. _`PostgreSQL`: http://www.postgresql.org/
-"""
-from kallithea.lib.dbmigrate.migrate.changeset import ansisql
-
-
-from sqlalchemy.databases import postgresql as sa_base
-PGSchemaGenerator = sa_base.PGDDLCompiler
-
-
-class PGColumnGenerator(PGSchemaGenerator, ansisql.ANSIColumnGenerator):
-    """PostgreSQL column generator implementation."""
-    pass
-
-
-class PGColumnDropper(ansisql.ANSIColumnDropper):
-    """PostgreSQL column dropper implementation."""
-    pass
-
-
-class PGSchemaChanger(ansisql.ANSISchemaChanger):
-    """PostgreSQL schema changer implementation."""
-    pass
-
-
-class PGConstraintGenerator(ansisql.ANSIConstraintGenerator):
-    """PostgreSQL constraint generator implementation."""
-    pass
-
-
-class PGConstraintDropper(ansisql.ANSIConstraintDropper):
-    """PostgreSQL constraint dropper implementation."""
-    pass
-
-
-class PGDialect(ansisql.ANSIDialect):
-    columngenerator = PGColumnGenerator
-    columndropper = PGColumnDropper
-    schemachanger = PGSchemaChanger
-    constraintgenerator = PGConstraintGenerator
-    constraintdropper = PGConstraintDropper
--- a/kallithea/lib/dbmigrate/migrate/changeset/databases/sqlite.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,153 +0,0 @@
-"""
-   `SQLite`_ database specific implementations of changeset classes.
-
-   .. _`SQLite`: http://www.sqlite.org/
-"""
-from UserDict import DictMixin
-from copy import copy
-
-from sqlalchemy.databases import sqlite as sa_base
-
-from kallithea.lib.dbmigrate.migrate import exceptions
-from kallithea.lib.dbmigrate.migrate.changeset import ansisql, SQLA_06
-
-SQLiteSchemaGenerator = sa_base.SQLiteDDLCompiler
-
-
-class SQLiteCommon(object):
-
-    def _not_supported(self, op):
-        raise exceptions.NotSupportedError("SQLite does not support "
-            "%s; see http://www.sqlite.org/lang_altertable.html" % op)
-
-
-class SQLiteHelper(SQLiteCommon):
-
-    def recreate_table(self,table,column=None,delta=None):
-        table_name = self.preparer.format_table(table)
-
-        # we remove all indexes so as not to have
-        # problems during copy and re-create
-        for index in table.indexes:
-            index.drop()
-
-        self.append('ALTER TABLE %s RENAME TO migration_tmp' % table_name)
-        self.execute()
-
-        insertion_string = self._modify_table(table, column, delta)
-
-        table.create(bind=self.connection)
-        self.append(insertion_string % {'table_name': table_name})
-        self.execute()
-        self.append('DROP TABLE migration_tmp')
-        self.execute()
-
-    def visit_column(self, delta):
-        if isinstance(delta, DictMixin):
-            column = delta.result_column
-            table = self._to_table(delta.table)
-        else:
-            column = delta
-            table = self._to_table(column.table)
-
-        self.recreate_table(table,column,delta)
-
-class SQLiteColumnGenerator(SQLiteSchemaGenerator,
-                            ansisql.ANSIColumnGenerator,
-                            # at the end so we get the normal
-                            # visit_column by default
-                            SQLiteHelper,
-                            SQLiteCommon
-                            ):
-    """SQLite ColumnGenerator"""
-
-    def _modify_table(self, table, column, delta):
-        columns = ' ,'.join(map(
-                self.preparer.format_column,
-                [c for c in table.columns if c.name!=column.name]))
-        return ('INSERT INTO %%(table_name)s (%(cols)s) '
-                'SELECT %(cols)s from migration_tmp')%{'cols':columns}
-
-    def visit_column(self,column):
-        if column.foreign_keys:
-            SQLiteHelper.visit_column(self,column)
-        else:
-            super(SQLiteColumnGenerator,self).visit_column(column)
-
-class SQLiteColumnDropper(SQLiteHelper, ansisql.ANSIColumnDropper):
-    """SQLite ColumnDropper"""
-
-    def _modify_table(self, table, column, delta):
-
-        columns = ' ,'.join(map(self.preparer.format_column, table.columns))
-        return 'INSERT INTO %(table_name)s SELECT ' + columns + \
-            ' from migration_tmp'
-
-    def visit_column(self,column):
-        # For SQLite, we *have* to remove the column here so the table
-        # is re-created properly.
-        column.remove_from_table(column.table,unset_table=False)
-        super(SQLiteColumnDropper,self).visit_column(column)
-
-
-class SQLiteSchemaChanger(SQLiteHelper, ansisql.ANSISchemaChanger):
-    """SQLite SchemaChanger"""
-
-    def _modify_table(self, table, column, delta):
-        return 'INSERT INTO %(table_name)s SELECT * from migration_tmp'
-
-    def visit_index(self, index):
-        """Does not support ALTER INDEX"""
-        self._not_supported('ALTER INDEX')
-
-
-class SQLiteConstraintGenerator(ansisql.ANSIConstraintGenerator, SQLiteHelper, SQLiteCommon):
-
-    def visit_migrate_primary_key_constraint(self, constraint):
-        tmpl = "CREATE UNIQUE INDEX %s ON %s ( %s )"
-        cols = ', '.join(map(self.preparer.format_column, constraint.columns))
-        tname = self.preparer.format_table(constraint.table)
-        name = self.get_constraint_name(constraint)
-        msg = tmpl % (name, tname, cols)
-        self.append(msg)
-        self.execute()
-
-    def _modify_table(self, table, column, delta):
-        return 'INSERT INTO %(table_name)s SELECT * from migration_tmp'
-
-    def visit_migrate_foreign_key_constraint(self, *p, **k):
-        self.recreate_table(p[0].table)
-
-    def visit_migrate_unique_constraint(self, *p, **k):
-        self.recreate_table(p[0].table)
-
-
-class SQLiteConstraintDropper(ansisql.ANSIColumnDropper,
-                              SQLiteCommon,
-                              ansisql.ANSIConstraintCommon):
-
-    def visit_migrate_primary_key_constraint(self, constraint):
-        tmpl = "DROP INDEX %s "
-        name = self.get_constraint_name(constraint)
-        msg = tmpl % (name)
-        self.append(msg)
-        self.execute()
-
-    def visit_migrate_foreign_key_constraint(self, *p, **k):
-        self._not_supported('ALTER TABLE DROP CONSTRAINT')
-
-    def visit_migrate_check_constraint(self, *p, **k):
-        self._not_supported('ALTER TABLE DROP CONSTRAINT')
-
-    def visit_migrate_unique_constraint(self, *p, **k):
-        self._not_supported('ALTER TABLE DROP CONSTRAINT')
-
-
-# TODO: technically primary key is a NOT NULL + UNIQUE constraint, should add NOT NULL to index
-
-class SQLiteDialect(ansisql.ANSIDialect):
-    columngenerator = SQLiteColumnGenerator
-    columndropper = SQLiteColumnDropper
-    schemachanger = SQLiteSchemaChanger
-    constraintgenerator = SQLiteConstraintGenerator
-    constraintdropper = SQLiteConstraintDropper
--- a/kallithea/lib/dbmigrate/migrate/changeset/databases/visitor.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,78 +0,0 @@
-"""
-   Module for visitor class mapping.
-"""
-import sqlalchemy as sa
-
-from kallithea.lib.dbmigrate.migrate.changeset import ansisql
-from kallithea.lib.dbmigrate.migrate.changeset.databases import (sqlite,
-                                         postgres,
-                                         mysql,
-                                         oracle,
-                                         firebird)
-
-
-# Map SA dialects to the corresponding Migrate extensions
-DIALECTS = {
-    "default": ansisql.ANSIDialect,
-    "sqlite": sqlite.SQLiteDialect,
-    "postgres": postgres.PGDialect,
-    "postgresql": postgres.PGDialect,
-    "mysql": mysql.MySQLDialect,
-    "oracle": oracle.OracleDialect,
-    "firebird": firebird.FBDialect,
-}
-
-
-def get_engine_visitor(engine, name):
-    """
-    Get the visitor implementation for the given database engine.
-
-    :param engine: SQLAlchemy Engine
-    :param name: Name of the visitor
-    :type name: string
-    :type engine: Engine
-    :returns: visitor
-    """
-    # TODO: link to supported visitors
-    return get_dialect_visitor(engine.dialect, name)
-
-
-def get_dialect_visitor(sa_dialect, name):
-    """
-    Get the visitor implementation for the given dialect.
-
-    Finds the visitor implementation based on the dialect class and
-    returns and instance initialized with the given name.
-
-    Binds dialect specific preparer to visitor.
-    """
-
-    # map sa dialect to migrate dialect and return visitor
-    sa_dialect_name = getattr(sa_dialect, 'name', 'default')
-    migrate_dialect_cls = DIALECTS[sa_dialect_name]
-    visitor = getattr(migrate_dialect_cls, name)
-
-    # bind preparer
-    visitor.preparer = sa_dialect.preparer(sa_dialect)
-
-    return visitor
-
-def run_single_visitor(engine, visitorcallable, element,
-    connection=None, **kwargs):
-    """Taken from :meth:`sqlalchemy.engine.base.Engine._run_single_visitor`
-    with support for migrate visitors.
-    """
-    if connection is None:
-        conn = engine.contextual_connect(close_with_result=False)
-    else:
-        conn = connection
-    visitor = visitorcallable(engine.dialect, conn)
-    try:
-        if hasattr(element, '__migrate_visit_name__'):
-            fn = getattr(visitor, 'visit_' + element.__migrate_visit_name__)
-        else:
-            fn = getattr(visitor, 'visit_' + element.__visit_name__)
-        fn(element, **kwargs)
-    finally:
-        if connection is None:
-            conn.close()
--- a/kallithea/lib/dbmigrate/migrate/changeset/schema.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,655 +0,0 @@
-"""
-   Schema module providing common schema operations.
-"""
-import warnings
-
-from UserDict import DictMixin
-
-import sqlalchemy
-
-from sqlalchemy.schema import ForeignKeyConstraint
-from sqlalchemy.schema import UniqueConstraint
-
-from kallithea.lib.dbmigrate.migrate.exceptions import *
-from kallithea.lib.dbmigrate.migrate.changeset import SQLA_06, SQLA_07
-from kallithea.lib.dbmigrate.migrate.changeset.databases.visitor import (get_engine_visitor,
-                                                                         run_single_visitor)
-
-
-__all__ = [
-    'create_column',
-    'drop_column',
-    'alter_column',
-    'rename_table',
-    'rename_index',
-    'ChangesetTable',
-    'ChangesetColumn',
-    'ChangesetIndex',
-    'ChangesetDefaultClause',
-    'ColumnDelta',
-]
-
-def create_column(column, table=None, *p, **kw):
-    """Create a column, given the table.
-
-    API to :meth:`ChangesetColumn.create`.
-    """
-    if table is not None:
-        return table.create_column(column, *p, **kw)
-    return column.create(*p, **kw)
-
-
-def drop_column(column, table=None, *p, **kw):
-    """Drop a column, given the table.
-
-    API to :meth:`ChangesetColumn.drop`.
-    """
-    if table is not None:
-        return table.drop_column(column, *p, **kw)
-    return column.drop(*p, **kw)
-
-
-def rename_table(table, name, engine=None, **kw):
-    """Rename a table.
-
-    If Table instance is given, engine is not used.
-
-    API to :meth:`ChangesetTable.rename`.
-
-    :param table: Table to be renamed.
-    :param name: New name for Table.
-    :param engine: Engine instance.
-    :type table: string or Table instance
-    :type name: string
-    :type engine: obj
-    """
-    table = _to_table(table, engine)
-    table.rename(name, **kw)
-
-
-def rename_index(index, name, table=None, engine=None, **kw):
-    """Rename an index.
-
-    If Index instance is given,
-    table and engine are not used.
-
-    API to :meth:`ChangesetIndex.rename`.
-
-    :param index: Index to be renamed.
-    :param name: New name for index.
-    :param table: Table to which Index is reffered.
-    :param engine: Engine instance.
-    :type index: string or Index instance
-    :type name: string
-    :type table: string or Table instance
-    :type engine: obj
-    """
-    index = _to_index(index, table, engine)
-    index.rename(name, **kw)
-
-
-def alter_column(*p, **k):
-    """Alter a column.
-
-    This is a helper function that creates a :class:`ColumnDelta` and
-    runs it.
-
-    :argument column:
-      The name of the column to be altered or a
-      :class:`ChangesetColumn` column representing it.
-
-    :param table:
-      A :class:`~sqlalchemy.schema.Table` or table name to
-      for the table where the column will be changed.
-
-    :param engine:
-      The :class:`~sqlalchemy.engine.base.Engine` to use for table
-      reflection and schema alterations.
-
-    :returns: A :class:`ColumnDelta` instance representing the change.
-
-
-    """
-
-    if 'table' not in k and isinstance(p[0], sqlalchemy.Column):
-        k['table'] = p[0].table
-    if 'engine' not in k:
-        k['engine'] = k['table'].bind
-
-    # deprecation
-    if len(p) >= 2 and isinstance(p[1], sqlalchemy.Column):
-        warnings.warn(
-            "Passing a Column object to alter_column is deprecated."
-            " Just pass in keyword parameters instead.",
-            MigrateDeprecationWarning
-            )
-    engine = k['engine']
-
-    # enough tests seem to break when metadata is always altered
-    # that this crutch has to be left in until they can be sorted
-    # out
-    k['alter_metadata']=True
-
-    delta = ColumnDelta(*p, **k)
-
-    visitorcallable = get_engine_visitor(engine, 'schemachanger')
-    engine._run_visitor(visitorcallable, delta)
-
-    return delta
-
-
-def _to_table(table, engine=None):
-    """Return if instance of Table, else construct new with metadata"""
-    if isinstance(table, sqlalchemy.Table):
-        return table
-
-    # Given: table name, maybe an engine
-    meta = sqlalchemy.MetaData()
-    if engine is not None:
-        meta.bind = engine
-    return sqlalchemy.Table(table, meta)
-
-
-def _to_index(index, table=None, engine=None):
-    """Return if instance of Index, else construct new with metadata"""
-    if isinstance(index, sqlalchemy.Index):
-        return index
-
-    # Given: index name; table name required
-    table = _to_table(table, engine)
-    ret = sqlalchemy.Index(index)
-    ret.table = table
-    return ret
-
-
-class ColumnDelta(DictMixin, sqlalchemy.schema.SchemaItem):
-    """Extracts the differences between two columns/column-parameters
-
-        May receive parameters arranged in several different ways:
-
-        * **current_column, new_column, \*p, \*\*kw**
-            Additional parameters can be specified to override column
-            differences.
-
-        * **current_column, \*p, \*\*kw**
-            Additional parameters alter current_column. Table name is extracted
-            from current_column object.
-            Name is changed to current_column.name from current_name,
-            if current_name is specified.
-
-        * **current_col_name, \*p, \*\*kw**
-            Table kw must specified.
-
-        :param table: Table at which current Column should be bound to.\
-        If table name is given, reflection will be used.
-        :type table: string or Table instance
-
-        :param metadata: A :class:`MetaData` instance to store
-                         reflected table names
-
-        :param engine: When reflecting tables, either engine or metadata must \
-        be specified to acquire engine object.
-        :type engine: :class:`Engine` instance
-        :returns: :class:`ColumnDelta` instance provides interface for altered attributes to \
-        `result_column` through :func:`dict` alike object.
-
-        * :class:`ColumnDelta`.result_column is altered column with new attributes
-
-        * :class:`ColumnDelta`.current_name is current name of column in db
-
-
-    """
-
-    # Column attributes that can be altered
-    diff_keys = ('name', 'type', 'primary_key', 'nullable',
-        'server_onupdate', 'server_default', 'autoincrement')
-    diffs = dict()
-    __visit_name__ = 'column'
-
-    def __init__(self, *p, **kw):
-        # 'alter_metadata' is not a public api. It exists purely
-        # as a crutch until the tests that fail when 'alter_metadata'
-        # behaviour always happens can be sorted out
-        self.alter_metadata = kw.pop("alter_metadata", False)
-
-        self.meta = kw.pop("metadata", None)
-        self.engine = kw.pop("engine", None)
-
-        # Things are initialized differently depending on how many column
-        # parameters are given. Figure out how many and call the appropriate
-        # method.
-        if len(p) >= 1 and isinstance(p[0], sqlalchemy.Column):
-            # At least one column specified
-            if len(p) >= 2 and isinstance(p[1], sqlalchemy.Column):
-                # Two columns specified
-                diffs = self.compare_2_columns(*p, **kw)
-            else:
-                # Exactly one column specified
-                diffs = self.compare_1_column(*p, **kw)
-        else:
-            # Zero columns specified
-            if not len(p) or not isinstance(p[0], basestring):
-                raise ValueError("First argument must be column name")
-            diffs = self.compare_parameters(*p, **kw)
-
-        self.apply_diffs(diffs)
-
-    def __repr__(self):
-        return '<ColumnDelta altermetadata=%r, %s>' % (
-            self.alter_metadata,
-            super(ColumnDelta, self).__repr__()
-            )
-
-    def __getitem__(self, key):
-        if key not in self.keys():
-            raise KeyError("No such diff key, available: %s" % self.diffs )
-        return getattr(self.result_column, key)
-
-    def __setitem__(self, key, value):
-        if key not in self.keys():
-            raise KeyError("No such diff key, available: %s" % self.diffs )
-        setattr(self.result_column, key, value)
-
-    def __delitem__(self, key):
-        raise NotImplementedError
-
-    def keys(self):
-        return self.diffs.keys()
-
-    def compare_parameters(self, current_name, *p, **k):
-        """Compares Column objects with reflection"""
-        self.table = k.pop('table')
-        self.result_column = self._table.c.get(current_name)
-        if len(p):
-            k = self._extract_parameters(p, k, self.result_column)
-        return k
-
-    def compare_1_column(self, col, *p, **k):
-        """Compares one Column object"""
-        self.table = k.pop('table', None)
-        if self.table is None:
-            self.table = col.table
-        self.result_column = col
-        if len(p):
-            k = self._extract_parameters(p, k, self.result_column)
-        return k
-
-    def compare_2_columns(self, old_col, new_col, *p, **k):
-        """Compares two Column objects"""
-        self.process_column(new_col)
-        self.table = k.pop('table', None)
-        # we cannot use bool() on table in SA06
-        if self.table is None:
-            self.table = old_col.table
-        if self.table is None:
-            new_col.table
-        self.result_column = old_col
-
-        # set differences
-        # leave out some stuff for later comp
-        for key in (set(self.diff_keys) - set(('type',))):
-            val = getattr(new_col, key, None)
-            if getattr(self.result_column, key, None) != val:
-                k.setdefault(key, val)
-
-        # inspect types
-        if not self.are_column_types_eq(self.result_column.type, new_col.type):
-            k.setdefault('type', new_col.type)
-
-        if len(p):
-            k = self._extract_parameters(p, k, self.result_column)
-        return k
-
-    def apply_diffs(self, diffs):
-        """Populate dict and column object with new values"""
-        self.diffs = diffs
-        for key in self.diff_keys:
-            if key in diffs:
-                setattr(self.result_column, key, diffs[key])
-
-        self.process_column(self.result_column)
-
-        # create an instance of class type if not yet
-        if 'type' in diffs and callable(self.result_column.type):
-            self.result_column.type = self.result_column.type()
-
-        # add column to the table
-        if self.table is not None and self.alter_metadata:
-            self.result_column.add_to_table(self.table)
-
-    def are_column_types_eq(self, old_type, new_type):
-        """Compares two types to be equal"""
-        ret = old_type.__class__ == new_type.__class__
-
-        # String length is a special case
-        if ret and isinstance(new_type, sqlalchemy.types.String):
-            ret = (getattr(old_type, 'length', None) == \
-                       getattr(new_type, 'length', None))
-        return ret
-
-    def _extract_parameters(self, p, k, column):
-        """Extracts data from p and modifies diffs"""
-        p = list(p)
-        while len(p):
-            if isinstance(p[0], basestring):
-                k.setdefault('name', p.pop(0))
-            elif isinstance(p[0], sqlalchemy.types.AbstractType):
-                k.setdefault('type', p.pop(0))
-            elif callable(p[0]):
-                p[0] = p[0]()
-            else:
-                break
-
-        if len(p):
-            new_col = column.copy_fixed()
-            new_col._init_items(*p)
-            k = self.compare_2_columns(column, new_col, **k)
-        return k
-
-    def process_column(self, column):
-        """Processes default values for column"""
-        # XXX: this is a snippet from SA processing of positional parameters
-        toinit = list()
-
-        if column.server_default is not None:
-            if isinstance(column.server_default, sqlalchemy.FetchedValue):
-                toinit.append(column.server_default)
-            else:
-                toinit.append(sqlalchemy.DefaultClause(column.server_default))
-        if column.server_onupdate is not None:
-            if isinstance(column.server_onupdate, FetchedValue):
-                toinit.append(column.server_default)
-            else:
-                toinit.append(sqlalchemy.DefaultClause(column.server_onupdate,
-                                            for_update=True))
-        if toinit:
-            column._init_items(*toinit)
-
-    def _get_table(self):
-        return getattr(self, '_table', None)
-
-    def _set_table(self, table):
-        if isinstance(table, basestring):
-            if self.alter_metadata:
-                if not self.meta:
-                    raise ValueError("metadata must be specified for table"
-                        " reflection when using alter_metadata")
-                meta = self.meta
-                if self.engine:
-                    meta.bind = self.engine
-            else:
-                if not self.engine and not self.meta:
-                    raise ValueError("engine or metadata must be specified"
-                        " to reflect tables")
-                if not self.engine:
-                    self.engine = self.meta.bind
-                meta = sqlalchemy.MetaData(bind=self.engine)
-            self._table = sqlalchemy.Table(table, meta, autoload=True)
-        elif isinstance(table, sqlalchemy.Table):
-            self._table = table
-            if not self.alter_metadata:
-                self._table.meta = sqlalchemy.MetaData(bind=self._table.bind)
-    def _get_result_column(self):
-        return getattr(self, '_result_column', None)
-
-    def _set_result_column(self, column):
-        """Set Column to Table based on alter_metadata evaluation."""
-        self.process_column(column)
-        if not hasattr(self, 'current_name'):
-            self.current_name = column.name
-        if self.alter_metadata:
-            self._result_column = column
-        else:
-            self._result_column = column.copy_fixed()
-
-    table = property(_get_table, _set_table)
-    result_column = property(_get_result_column, _set_result_column)
-
-
-class ChangesetTable(object):
-    """Changeset extensions to SQLAlchemy tables."""
-
-    def create_column(self, column, *p, **kw):
-        """Creates a column.
-
-        The column parameter may be a column definition or the name of
-        a column in this table.
-
-        API to :meth:`ChangesetColumn.create`
-
-        :param column: Column to be created
-        :type column: Column instance or string
-        """
-        if not isinstance(column, sqlalchemy.Column):
-            # It's a column name
-            column = getattr(self.c, str(column))
-        column.create(table=self, *p, **kw)
-
-    def drop_column(self, column, *p, **kw):
-        """Drop a column, given its name or definition.
-
-        API to :meth:`ChangesetColumn.drop`
-
-        :param column: Column to be dropped
-        :type column: Column instance or string
-        """
-        if not isinstance(column, sqlalchemy.Column):
-            # It's a column name
-            try:
-                column = getattr(self.c, str(column))
-            except AttributeError:
-                # That column isn't part of the table. We don't need
-                # its entire definition to drop the column, just its
-                # name, so create a dummy column with the same name.
-                column = sqlalchemy.Column(str(column), sqlalchemy.Integer())
-        column.drop(table=self, *p, **kw)
-
-    def rename(self, name, connection=None, **kwargs):
-        """Rename this table.
-
-        :param name: New name of the table.
-        :type name: string
-        :param connection: reuse connection instead of creating new one.
-        :type connection: :class:`sqlalchemy.engine.base.Connection` instance
-        """
-        engine = self.bind
-        self.new_name = name
-        visitorcallable = get_engine_visitor(engine, 'schemachanger')
-        run_single_visitor(engine, visitorcallable, self, connection, **kwargs)
-
-        # Fix metadata registration
-        self.name = name
-        self.deregister()
-        self._set_parent(self.metadata)
-
-    def _meta_key(self):
-        """Get the meta key for this table."""
-        return sqlalchemy.schema._get_table_key(self.name, self.schema)
-
-    def deregister(self):
-        """Remove this table from its metadata"""
-        if SQLA_07:
-            self.metadata._remove_table(self.name, self.schema)
-        else:
-            key = self._meta_key()
-            meta = self.metadata
-            if key in meta.tables:
-                del meta.tables[key]
-
-
-class ChangesetColumn(object):
-    """Changeset extensions to SQLAlchemy columns."""
-
-    def alter(self, *p, **k):
-        """Makes a call to :func:`alter_column` for the column this
-        method is called on.
-        """
-        if 'table' not in k:
-            k['table'] = self.table
-        if 'engine' not in k:
-            k['engine'] = k['table'].bind
-        return alter_column(self, *p, **k)
-
-    def create(self, table=None, index_name=None, unique_name=None,
-               primary_key_name=None, populate_default=True, connection=None, **kwargs):
-        """Create this column in the database.
-
-        Assumes the given table exists. ``ALTER TABLE ADD COLUMN``,
-        for most databases.
-
-        :param table: Table instance to create on.
-        :param index_name: Creates :class:`ChangesetIndex` on this column.
-        :param unique_name: Creates :class:\
-`~migrate.changeset.constraint.UniqueConstraint` on this column.
-        :param primary_key_name: Creates :class:\
-`~migrate.changeset.constraint.PrimaryKeyConstraint` on this column.
-        :param populate_default: If True, created column will be \
-populated with defaults
-        :param connection: reuse connection instead of creating new one.
-        :type table: Table instance
-        :type index_name: string
-        :type unique_name: string
-        :type primary_key_name: string
-        :type populate_default: bool
-        :type connection: :class:`sqlalchemy.engine.base.Connection` instance
-
-        :returns: self
-        """
-        self.populate_default = populate_default
-        self.index_name = index_name
-        self.unique_name = unique_name
-        self.primary_key_name = primary_key_name
-        for cons in ('index_name', 'unique_name', 'primary_key_name'):
-            self._check_sanity_constraints(cons)
-
-        self.add_to_table(table)
-        engine = self.table.bind
-        visitorcallable = get_engine_visitor(engine, 'columngenerator')
-        engine._run_visitor(visitorcallable, self, connection, **kwargs)
-
-        # TODO: reuse existing connection
-        if self.populate_default and self.default is not None:
-            stmt = table.update().values({self: engine._execute_default(self.default)})
-            engine.execute(stmt)
-
-        return self
-
-    def drop(self, table=None, connection=None, **kwargs):
-        """Drop this column from the database, leaving its table intact.
-
-        ``ALTER TABLE DROP COLUMN``, for most databases.
-
-        :param connection: reuse connection instead of creating new one.
-        :type connection: :class:`sqlalchemy.engine.base.Connection` instance
-        """
-        if table is not None:
-            self.table = table
-        engine = self.table.bind
-        visitorcallable = get_engine_visitor(engine, 'columndropper')
-        engine._run_visitor(visitorcallable, self, connection, **kwargs)
-        self.remove_from_table(self.table, unset_table=False)
-        self.table = None
-        return self
-
-    def add_to_table(self, table):
-        if table is not None  and self.table is None:
-            if SQLA_07:
-                table.append_column(self)
-            else:
-                self._set_parent(table)
-
-    def _col_name_in_constraint(self,cons,name):
-        return False
-
-    def remove_from_table(self, table, unset_table=True):
-        # TODO: remove primary keys, constraints, etc
-        if unset_table:
-            self.table = None
-
-        to_drop = set()
-        for index in table.indexes:
-            columns = []
-            for col in index.columns:
-                if col.name!=self.name:
-                    columns.append(col)
-            if columns:
-                index.columns=columns
-            else:
-                to_drop.add(index)
-        table.indexes = table.indexes - to_drop
-
-        to_drop = set()
-        for cons in table.constraints:
-            # TODO: deal with other types of constraint
-            if isinstance(cons,(ForeignKeyConstraint,
-                                UniqueConstraint)):
-                for col_name in cons.columns:
-                    if not isinstance(col_name,basestring):
-                        col_name = col_name.name
-                    if self.name==col_name:
-                        to_drop.add(cons)
-        table.constraints = table.constraints - to_drop
-
-        if table.c.contains_column(self):
-            if SQLA_07:
-                table._columns.remove(self)
-            else:
-                table.c.remove(self)
-
-    # TODO: this is fixed in 0.6
-    def copy_fixed(self, **kw):
-        """Create a copy of this ``Column``, with all attributes."""
-        return sqlalchemy.Column(self.name, self.type, self.default,
-            key=self.key,
-            primary_key=self.primary_key,
-            nullable=self.nullable,
-            quote=self.quote,
-            index=self.index,
-            unique=self.unique,
-            onupdate=self.onupdate,
-            autoincrement=self.autoincrement,
-            server_default=self.server_default,
-            server_onupdate=self.server_onupdate,
-            *[c.copy(**kw) for c in self.constraints])
-
-    def _check_sanity_constraints(self, name):
-        """Check if constraints names are correct"""
-        obj = getattr(self, name)
-        if (getattr(self, name[:-5]) and not obj):
-            raise InvalidConstraintError("Column.create() accepts index_name,"
-            " primary_key_name and unique_name to generate constraints")
-        if not isinstance(obj, basestring) and obj is not None:
-            raise InvalidConstraintError(
-            "%s argument for column must be constraint name" % name)
-
-
-class ChangesetIndex(object):
-    """Changeset extensions to SQLAlchemy Indexes."""
-
-    __visit_name__ = 'index'
-
-    def rename(self, name, connection=None, **kwargs):
-        """Change the name of an index.
-
-        :param name: New name of the Index.
-        :type name: string
-        :param connection: reuse connection instead of creating new one.
-        :type connection: :class:`sqlalchemy.engine.base.Connection` instance
-        """
-        engine = self.table.bind
-        self.new_name = name
-        visitorcallable = get_engine_visitor(engine, 'schemachanger')
-        engine._run_visitor(visitorcallable, self, connection, **kwargs)
-        self.name = name
-
-
-class ChangesetDefaultClause(object):
-    """Implements comparison between :class:`DefaultClause` instances"""
-
-    def __eq__(self, other):
-        if isinstance(other, self.__class__):
-            if self.arg == other.arg:
-                return True
-
-    def __ne__(self, other):
-        return not self.__eq__(other)
--- a/kallithea/lib/dbmigrate/migrate/exceptions.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,84 +0,0 @@
-"""
-   Provide exception classes for :mod:`migrate`
-"""
-
-
-class Error(Exception):
-    """Error base class."""
-
-
-class ApiError(Error):
-    """Base class for API errors."""
-
-
-class KnownError(ApiError):
-    """A known error condition."""
-
-
-class UsageError(ApiError):
-    """A known error condition where help should be displayed."""
-
-
-class ControlledSchemaError(Error):
-    """Base class for controlled schema errors."""
-
-
-class InvalidVersionError(ControlledSchemaError):
-    """Invalid version number."""
-
-
-class DatabaseNotControlledError(ControlledSchemaError):
-    """Database should be under version control, but it's not."""
-
-
-class DatabaseAlreadyControlledError(ControlledSchemaError):
-    """Database shouldn't be under version control, but it is"""
-
-
-class WrongRepositoryError(ControlledSchemaError):
-    """This database is under version control by another repository."""
-
-
-class NoSuchTableError(ControlledSchemaError):
-    """The table does not exist."""
-
-
-class PathError(Error):
-    """Base class for path errors."""
-
-
-class PathNotFoundError(PathError):
-    """A path with no file was required; found a file."""
-
-
-class PathFoundError(PathError):
-    """A path with a file was required; found no file."""
-
-
-class RepositoryError(Error):
-    """Base class for repository errors."""
-
-
-class InvalidRepositoryError(RepositoryError):
-    """Invalid repository error."""
-
-
-class ScriptError(Error):
-    """Base class for script errors."""
-
-
-class InvalidScriptError(ScriptError):
-    """Invalid script error."""
-
-
-# migrate.changeset
-
-class NotSupportedError(Error):
-    """Not supported error"""
-
-
-class InvalidConstraintError(Error):
-    """Invalid constraint error"""
-
-class MigrateDeprecationWarning(DeprecationWarning):
-    """Warning for deprecated features in Migrate"""
--- a/kallithea/lib/dbmigrate/migrate/versioning/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,5 +0,0 @@
-"""
-   This package provides functionality to create and manage
-   repositories of database schema changesets and to apply these
-   changesets to databases.
-"""
--- a/kallithea/lib/dbmigrate/migrate/versioning/api.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,384 +0,0 @@
-"""
-   This module provides an external API to the versioning system.
-
-   .. versionchanged:: 0.6.0
-    :func:`migrate.versioning.api.test` and schema diff functions
-    changed order of positional arguments so all accept `url` and `repository`
-    as first arguments.
-
-   .. versionchanged:: 0.5.4
-    ``--preview_sql`` displays source file when using SQL scripts.
-    If Python script is used, it runs the action with mocked engine and
-    returns captured SQL statements.
-
-   .. versionchanged:: 0.5.4
-    Deprecated ``--echo`` parameter in favour of new
-    :func:`migrate.versioning.util.construct_engine` behavior.
-"""
-
-# Dear migrate developers,
-#
-# please do not comment this module using sphinx syntax because its
-# docstrings are presented as user help and most users cannot
-# interpret sphinx annotated ReStructuredText.
-#
-# Thanks,
-# Jan Dittberner
-
-import sys
-import inspect
-import logging
-
-from kallithea.lib.dbmigrate.migrate import exceptions
-from kallithea.lib.dbmigrate.migrate.versioning import repository, schema, version, \
-    script as script_ # command name conflict
-from kallithea.lib.dbmigrate.migrate.versioning.util import catch_known_errors, with_engine
-
-
-log = logging.getLogger(__name__)
-command_desc = {
-    'help': 'displays help on a given command',
-    'create': 'create an empty repository at the specified path',
-    'script': 'create an empty change Python script',
-    'script_sql': 'create empty change SQL scripts for given database',
-    'version': 'display the latest version available in a repository',
-    'db_version': 'show the current version of the repository under version control',
-    'source': 'display the Python code for a particular version in this repository',
-    'version_control': 'mark a database as under this repository\'s version control',
-    'upgrade': 'upgrade a database to a later version',
-    'downgrade': 'downgrade a database to an earlier version',
-    'drop_version_control': 'removes version control from a database',
-    'manage': 'creates a Python script that runs Migrate with a set of default values',
-    'test': 'performs the upgrade and downgrade command on the given database',
-    'compare_model_to_db': 'compare MetaData against the current database state',
-    'create_model': 'dump the current database as a Python model to stdout',
-    'make_update_script_for_model': 'create a script changing the old MetaData to the new (current) MetaData',
-    'update_db_from_model': 'modify the database to match the structure of the current MetaData',
-}
-__all__ = command_desc.keys()
-
-Repository = repository.Repository
-ControlledSchema = schema.ControlledSchema
-VerNum = version.VerNum
-PythonScript = script_.PythonScript
-SqlScript = script_.SqlScript
-
-
-# deprecated
-def help(cmd=None, **opts):
-    """%prog help COMMAND
-
-    Displays help on a given command.
-    """
-    if cmd is None:
-        raise exceptions.UsageError(None)
-    try:
-        func = globals()[cmd]
-    except:
-        raise exceptions.UsageError(
-            "'%s' isn't a valid command. Try 'help COMMAND'" % cmd)
-    ret = func.__doc__
-    if sys.argv[0]:
-        ret = ret.replace('%prog', sys.argv[0])
-    return ret
-
-@catch_known_errors
-def create(repository, name, **opts):
-    """%prog create REPOSITORY_PATH NAME [--table=TABLE]
-
-    Create an empty repository at the specified path.
-
-    You can specify the version_table to be used; by default, it is
-    'migrate_version'.  This table is created in all version-controlled
-    databases.
-    """
-    repo_path = Repository.create(repository, name, **opts)
-
-
-@catch_known_errors
-def script(description, repository, **opts):
-    """%prog script DESCRIPTION REPOSITORY_PATH
-
-    Create an empty change script using the next unused version number
-    appended with the given description.
-
-    For instance, manage.py script "Add initial tables" creates:
-    repository/versions/001_Add_initial_tables.py
-    """
-    repo = Repository(repository)
-    repo.create_script(description, **opts)
-
-
-@catch_known_errors
-def script_sql(database, description, repository, **opts):
-    """%prog script_sql DATABASE DESCRIPTION REPOSITORY_PATH
-
-    Create empty change SQL scripts for given DATABASE, where DATABASE
-    is either specific ('postgresql', 'mysql', 'oracle', 'sqlite', etc.)
-    or generic ('default').
-
-    For instance, manage.py script_sql postgresql description creates:
-    repository/versions/001_description_postgresql_upgrade.sql and
-    repository/versions/001_description_postgresql_downgrade.sql
-    """
-    repo = Repository(repository)
-    repo.create_script_sql(database, description, **opts)
-
-
-def version(repository, **opts):
-    """%prog version REPOSITORY_PATH
-
-    Display the latest version available in a repository.
-    """
-    repo = Repository(repository)
-    return repo.latest
-
-
-@with_engine
-def db_version(url, repository, **opts):
-    """%prog db_version URL REPOSITORY_PATH
-
-    Show the current version of the repository with the given
-    connection string, under version control of the specified
-    repository.
-
-    The url should be any valid SQLAlchemy connection string.
-    """
-    engine = opts.pop('engine')
-    schema = ControlledSchema(engine, repository)
-    return schema.version
-
-
-def source(version, dest=None, repository=None, **opts):
-    """%prog source VERSION [DESTINATION] --repository=REPOSITORY_PATH
-
-    Display the Python code for a particular version in this
-    repository.  Save it to the file at DESTINATION or, if omitted,
-    send to stdout.
-    """
-    if repository is None:
-        raise exceptions.UsageError("A repository must be specified")
-    repo = Repository(repository)
-    ret = repo.version(version).script().source()
-    if dest is not None:
-        dest = open(dest, 'w')
-        dest.write(ret)
-        dest.close()
-        ret = None
-    return ret
-
-
-def upgrade(url, repository, version=None, **opts):
-    """%prog upgrade URL REPOSITORY_PATH [VERSION] [--preview_py|--preview_sql]
-
-    Upgrade a database to a later version.
-
-    This runs the upgrade() function defined in your change scripts.
-
-    By default, the database is updated to the latest available
-    version. You may specify a version instead, if you wish.
-
-    You may preview the Python or SQL code to be executed, rather than
-    actually executing it, using the appropriate 'preview' option.
-    """
-    err = "Cannot upgrade a database of version %s to version %s. "\
-        "Try 'downgrade' instead."
-    return _migrate(url, repository, version, upgrade=True, err=err, **opts)
-
-
-def downgrade(url, repository, version, **opts):
-    """%prog downgrade URL REPOSITORY_PATH VERSION [--preview_py|--preview_sql]
-
-    Downgrade a database to an earlier version.
-
-    This is the reverse of upgrade; this runs the downgrade() function
-    defined in your change scripts.
-
-    You may preview the Python or SQL code to be executed, rather than
-    actually executing it, using the appropriate 'preview' option.
-    """
-    err = "Cannot downgrade a database of version %s to version %s. "\
-        "Try 'upgrade' instead."
-    return _migrate(url, repository, version, upgrade=False, err=err, **opts)
-
-@with_engine
-def test(url, repository, **opts):
-    """%prog test URL REPOSITORY_PATH [VERSION]
-
-    Performs the upgrade and downgrade option on the given
-    database. This is not a real test and may leave the database in a
-    bad state. You should therefore better run the test on a copy of
-    your database.
-    """
-    engine = opts.pop('engine')
-    repos = Repository(repository)
-
-    # Upgrade
-    log.info("Upgrading...")
-    script = repos.version(None).script(engine.name, 'upgrade')
-    script.run(engine, 1)
-    log.info("done")
-
-    log.info("Downgrading...")
-    script = repos.version(None).script(engine.name, 'downgrade')
-    script.run(engine, -1)
-    log.info("done")
-    log.info("Success")
-
-
-@with_engine
-def version_control(url, repository, version=None, **opts):
-    """%prog version_control URL REPOSITORY_PATH [VERSION]
-
-    Mark a database as under this repository's version control.
-
-    Once a database is under version control, schema changes should
-    only be done via change scripts in this repository.
-
-    This creates the table version_table in the database.
-
-    The url should be any valid SQLAlchemy connection string.
-
-    By default, the database begins at version 0 and is assumed to be
-    empty.  If the database is not empty, you may specify a version at
-    which to begin instead. No attempt is made to verify this
-    version's correctness - the database schema is expected to be
-    identical to what it would be if the database were created from
-    scratch.
-    """
-    engine = opts.pop('engine')
-    ControlledSchema.create(engine, repository, version)
-
-
-@with_engine
-def drop_version_control(url, repository, **opts):
-    """%prog drop_version_control URL REPOSITORY_PATH
-
-    Removes version control from a database.
-    """
-    engine = opts.pop('engine')
-    schema = ControlledSchema(engine, repository)
-    schema.drop()
-
-
-def manage(file, **opts):
-    """%prog manage FILENAME [VARIABLES...]
-
-    Creates a script that runs Migrate with a set of default values.
-
-    For example::
-
-        %prog manage manage.py --repository=/path/to/repository \
---url=sqlite:///project.db
-
-    would create the script manage.py. The following two commands
-    would then have exactly the same results::
-
-        python manage.py version
-        %prog version --repository=/path/to/repository
-    """
-    Repository.create_manage_file(file, **opts)
-
-
-@with_engine
-def compare_model_to_db(url, repository, model, **opts):
-    """%prog compare_model_to_db URL REPOSITORY_PATH MODEL
-
-    Compare the current model (assumed to be a module level variable
-    of type sqlalchemy.MetaData) against the current database.
-
-    NOTE: This is EXPERIMENTAL.
-    """  # TODO: get rid of EXPERIMENTAL label
-    engine = opts.pop('engine')
-    return ControlledSchema.compare_model_to_db(engine, model, repository)
-
-
-@with_engine
-def create_model(url, repository, **opts):
-    """%prog create_model URL REPOSITORY_PATH [DECLERATIVE=True]
-
-    Dump the current database as a Python model to stdout.
-
-    NOTE: This is EXPERIMENTAL.
-    """  # TODO: get rid of EXPERIMENTAL label
-    engine = opts.pop('engine')
-    declarative = opts.get('declarative', False)
-    return ControlledSchema.create_model(engine, repository, declarative)
-
-
-@catch_known_errors
-@with_engine
-def make_update_script_for_model(url, repository, oldmodel, model, **opts):
-    """%prog make_update_script_for_model URL OLDMODEL MODEL REPOSITORY_PATH
-
-    Create a script changing the old Python model to the new (current)
-    Python model, sending to stdout.
-
-    NOTE: This is EXPERIMENTAL.
-    """  # TODO: get rid of EXPERIMENTAL label
-    engine = opts.pop('engine')
-    return PythonScript.make_update_script_for_model(
-        engine, oldmodel, model, repository, **opts)
-
-
-@with_engine
-def update_db_from_model(url, repository, model, **opts):
-    """%prog update_db_from_model URL REPOSITORY_PATH MODEL
-
-    Modify the database to match the structure of the current Python
-    model. This also sets the db_version number to the latest in the
-    repository.
-
-    NOTE: This is EXPERIMENTAL.
-    """  # TODO: get rid of EXPERIMENTAL label
-    engine = opts.pop('engine')
-    schema = ControlledSchema(engine, repository)
-    schema.update_db_from_model(model)
-
-@with_engine
-def _migrate(url, repository, version, upgrade, err, **opts):
-    engine = opts.pop('engine')
-    url = str(engine.url)
-    schema = ControlledSchema(engine, repository)
-    version = _migrate_version(schema, version, upgrade, err)
-
-    changeset = schema.changeset(version)
-    for ver, change in changeset:
-        nextver = ver + changeset.step
-        log.info('%s -> %s... ', ver, nextver)
-
-        if opts.get('preview_sql'):
-            if isinstance(change, PythonScript):
-                log.info(change.preview_sql(url, changeset.step, **opts))
-            elif isinstance(change, SqlScript):
-                log.info(change.source())
-
-        elif opts.get('preview_py'):
-            if not isinstance(change, PythonScript):
-                raise exceptions.UsageError("Python source can be only displayed"
-                    " for python migration files")
-            source_ver = max(ver, nextver)
-            module = schema.repository.version(source_ver).script().module
-            funcname = upgrade and "upgrade" or "downgrade"
-            func = getattr(module, funcname)
-            log.info(inspect.getsource(func))
-        else:
-            schema.runchange(ver, change, changeset.step)
-            log.info('done')
-
-
-def _migrate_version(schema, version, upgrade, err):
-    if version is None:
-        return version
-    # Version is specified: ensure we're upgrading in the right direction
-    # (current version < target version for upgrading; reverse for down)
-    version = VerNum(version)
-    cur = schema.version
-    if upgrade is not None:
-        if upgrade:
-            direction = cur <= version
-        else:
-            direction = cur >= version
-        if not direction:
-            raise exceptions.KnownError(err % (cur, version))
-    return version
--- a/kallithea/lib/dbmigrate/migrate/versioning/cfgparse.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-"""
-   Configuration parser module.
-"""
-
-from ConfigParser import ConfigParser
-
-from kallithea.lib.dbmigrate.migrate.versioning.config import *
-from kallithea.lib.dbmigrate.migrate.versioning import pathed
-
-
-class Parser(ConfigParser):
-    """A project configuration file."""
-
-    def to_dict(self, sections=None):
-        """It's easier to access config values like dictionaries"""
-        return self._sections
-
-
-class Config(pathed.Pathed, Parser):
-    """Configuration class."""
-
-    def __init__(self, path, *p, **k):
-        """Confirm the config file exists; read it."""
-        self.require_found(path)
-        pathed.Pathed.__init__(self, path)
-        Parser.__init__(self, *p, **k)
-        self.read(path)
--- a/kallithea/lib/dbmigrate/migrate/versioning/config.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,14 +0,0 @@
-#!/usr/bin/env python2
-# -*- coding: utf-8 -*-
-
-from sqlalchemy.util import OrderedDict
-
-
-__all__ = ['databases', 'operations']
-
-databases = ('sqlite', 'postgres', 'mysql', 'oracle', 'mssql', 'firebird')
-
-# Map operation names to function names
-operations = OrderedDict()
-operations['upgrade'] = 'upgrade'
-operations['downgrade'] = 'downgrade'
--- a/kallithea/lib/dbmigrate/migrate/versioning/genmodel.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,284 +0,0 @@
-"""
-Code to generate a Python model from a database or differences
-between a model and database.
-
-Some of this is borrowed heavily from the AutoCode project at:
-http://code.google.com/p/sqlautocode/
-"""
-
-import sys
-import logging
-
-import sqlalchemy
-
-from kallithea.lib.dbmigrate import migrate
-from kallithea.lib.dbmigrate.migrate import changeset
-
-
-log = logging.getLogger(__name__)
-HEADER = """
-## File autogenerated by genmodel.py
-
-from sqlalchemy import *
-meta = MetaData()
-"""
-
-DECLARATIVE_HEADER = """
-## File autogenerated by genmodel.py
-
-from sqlalchemy import *
-from sqlalchemy.ext import declarative
-
-Base = declarative.declarative_base()
-"""
-
-
-class ModelGenerator(object):
-    """Various transformations from an A, B diff.
-
-    In the implementation, A tends to be called the model and B
-    the database (although this is not true of all diffs).
-    The diff is directionless, but transformations apply the diff
-    in a particular direction, described in the method name.
-    """
-
-    def __init__(self, diff, engine, declarative=False):
-        self.diff = diff
-        self.engine = engine
-        self.declarative = declarative
-
-    def column_repr(self, col):
-        kwarg = []
-        if col.key != col.name:
-            kwarg.append('key')
-        if col.primary_key:
-            col.primary_key = True  # otherwise it dumps it as 1
-            kwarg.append('primary_key')
-        if not col.nullable:
-            kwarg.append('nullable')
-        if col.onupdate:
-            kwarg.append('onupdate')
-        if col.default:
-            if col.primary_key:
-                # I found that PostgreSQL automatically creates a
-                # default value for the sequence, but let's not show
-                # that.
-                pass
-            else:
-                kwarg.append('default')
-        args = ['%s=%r' % (k, getattr(col, k)) for k in kwarg]
-
-        # crs: not sure if this is good idea, but it gets rid of extra
-        # u''
-        name = col.name.encode('utf8')
-
-        type_ = col.type
-        for cls in col.type.__class__.__mro__:
-            if cls.__module__ == 'sqlalchemy.types' and \
-                not cls.__name__.isupper():
-                if cls is not type_.__class__:
-                    type_ = cls()
-                break
-
-        type_repr = repr(type_)
-        if type_repr.endswith('()'):
-            type_repr = type_repr[:-2]
-
-        constraints = [repr(cn) for cn in col.constraints]
-
-        data = {
-            'name': name,
-            'commonStuff': ', '.join([type_repr] + constraints + args),
-        }
-
-        if self.declarative:
-            return """%(name)s = Column(%(commonStuff)s)""" % data
-        else:
-            return """Column(%(name)r, %(commonStuff)s)""" % data
-
-    def _getTableDefn(self, table, metaName='meta'):
-        out = []
-        tableName = table.name
-        if self.declarative:
-            out.append("class %(table)s(Base):" % {'table': tableName})
-            out.append("    __tablename__ = '%(table)s'\n" %
-                            {'table': tableName})
-            for col in table.columns:
-                out.append("    %s" % self.column_repr(col))
-            out.append('\n')
-        else:
-            out.append("%(table)s = Table('%(table)s', %(meta)s," %
-                       {'table': tableName, 'meta': metaName})
-            for col in table.columns:
-                out.append("    %s," % self.column_repr(col))
-            out.append(")\n")
-        return out
-
-    def _get_tables(self,missingA=False,missingB=False,modified=False):
-        to_process = []
-        for bool_,names,metadata in (
-            (missingA,self.diff.tables_missing_from_A,self.diff.metadataB),
-            (missingB,self.diff.tables_missing_from_B,self.diff.metadataA),
-            (modified,self.diff.tables_different,self.diff.metadataA),
-                ):
-            if bool_:
-                for name in names:
-                    yield metadata.tables.get(name)
-
-    def genBDefinition(self):
-        """Generates the source code for a definition of B.
-
-        Assumes a diff where A is empty.
-
-        Was: toPython. Assume database (B) is current and model (A) is empty.
-        """
-
-        out = []
-        if self.declarative:
-            out.append(DECLARATIVE_HEADER)
-        else:
-            out.append(HEADER)
-        out.append("")
-        for table in self._get_tables(missingA=True):
-            out.extend(self._getTableDefn(table))
-        return '\n'.join(out)
-
-    def genB2AMigration(self, indent='    '):
-        """Generate a migration from B to A.
-
-        Was: toUpgradeDowngradePython
-        Assume model (A) is most current and database (B) is out-of-date.
-        """
-
-        decls = ['from migrate.changeset import schema',
-                 'pre_meta = MetaData()',
-                 'post_meta = MetaData()',
-                ]
-        upgradeCommands = ['pre_meta.bind = migrate_engine',
-                           'post_meta.bind = migrate_engine']
-        downgradeCommands = list(upgradeCommands)
-
-        for tn in self.diff.tables_missing_from_A:
-            pre_table = self.diff.metadataB.tables[tn]
-            decls.extend(self._getTableDefn(pre_table, metaName='pre_meta'))
-            upgradeCommands.append(
-                "pre_meta.tables[%(table)r].drop()" % {'table': tn})
-            downgradeCommands.append(
-                "pre_meta.tables[%(table)r].create()" % {'table': tn})
-
-        for tn in self.diff.tables_missing_from_B:
-            post_table = self.diff.metadataA.tables[tn]
-            decls.extend(self._getTableDefn(post_table, metaName='post_meta'))
-            upgradeCommands.append(
-                "post_meta.tables[%(table)r].create()" % {'table': tn})
-            downgradeCommands.append(
-                "post_meta.tables[%(table)r].drop()" % {'table': tn})
-
-        for (tn, td) in self.diff.tables_different.iteritems():
-            if td.columns_missing_from_A or td.columns_different:
-                pre_table = self.diff.metadataB.tables[tn]
-                decls.extend(self._getTableDefn(
-                    pre_table, metaName='pre_meta'))
-            if td.columns_missing_from_B or td.columns_different:
-                post_table = self.diff.metadataA.tables[tn]
-                decls.extend(self._getTableDefn(
-                    post_table, metaName='post_meta'))
-
-            for col in td.columns_missing_from_A:
-                upgradeCommands.append(
-                    'pre_meta.tables[%r].columns[%r].drop()' % (tn, col))
-                downgradeCommands.append(
-                    'pre_meta.tables[%r].columns[%r].create()' % (tn, col))
-            for col in td.columns_missing_from_B:
-                upgradeCommands.append(
-                    'post_meta.tables[%r].columns[%r].create()' % (tn, col))
-                downgradeCommands.append(
-                    'post_meta.tables[%r].columns[%r].drop()' % (tn, col))
-            for modelCol, databaseCol, modelDecl, databaseDecl in td.columns_different:
-                upgradeCommands.append(
-                    'assert False, "Can\'t alter columns: %s:%s=>%s"' % (
-                    tn, modelCol.name, databaseCol.name))
-                downgradeCommands.append(
-                    'assert False, "Can\'t alter columns: %s:%s=>%s"' % (
-                    tn, modelCol.name, databaseCol.name))
-
-        return (
-            '\n'.join(decls),
-            '\n'.join('%s%s' % (indent, line) for line in upgradeCommands),
-            '\n'.join('%s%s' % (indent, line) for line in downgradeCommands))
-
-    def _db_can_handle_this_change(self,td):
-        """Check if the database can handle going from B to A."""
-
-        if (td.columns_missing_from_B
-            and not td.columns_missing_from_A
-            and not td.columns_different):
-            # Even sqlite can handle column additions.
-            return True
-        else:
-            return not self.engine.url.drivername.startswith('sqlite')
-
-    def runB2A(self):
-        """Goes from B to A.
-
-        Was: applyModel. Apply model (A) to current database (B).
-        """
-
-        meta = sqlalchemy.MetaData(self.engine)
-
-        for table in self._get_tables(missingA=True):
-            table = table.tometadata(meta)
-            table.drop()
-        for table in self._get_tables(missingB=True):
-            table = table.tometadata(meta)
-            table.create()
-        for modelTable in self._get_tables(modified=True):
-            tableName = modelTable.name
-            modelTable = modelTable.tometadata(meta)
-            dbTable = self.diff.metadataB.tables[tableName]
-
-            td = self.diff.tables_different[tableName]
-
-            if self._db_can_handle_this_change(td):
-
-                for col in td.columns_missing_from_B:
-                    modelTable.columns[col].create()
-                for col in td.columns_missing_from_A:
-                    dbTable.columns[col].drop()
-                # XXX handle column changes here.
-            else:
-                # Sqlite doesn't support drop column, so you have to
-                # do more: create temp table, copy data to it, drop
-                # old table, create new table, copy data back.
-                #
-                # I wonder if this is guaranteed to be unique?
-                tempName = '_temp_%s' % modelTable.name
-
-                def getCopyStatement():
-                    preparer = self.engine.dialect.preparer
-                    commonCols = []
-                    for modelCol in modelTable.columns:
-                        if modelCol.name in dbTable.columns:
-                            commonCols.append(modelCol.name)
-                    commonColsStr = ', '.join(commonCols)
-                    return 'INSERT INTO %s (%s) SELECT %s FROM %s' % \
-                        (tableName, commonColsStr, commonColsStr, tempName)
-
-                # Move the data in one transaction, so that we don't
-                # leave the database in a nasty state.
-                connection = self.engine.connect()
-                trans = connection.begin()
-                try:
-                    connection.execute(
-                        'CREATE TEMPORARY TABLE %s as SELECT * from %s' % \
-                            (tempName, modelTable.name))
-                    # make sure the drop takes place inside our
-                    # transaction with the bind parameter
-                    modelTable.drop(bind=connection)
-                    modelTable.create(bind=connection)
-                    connection.execute(getCopyStatement())
-                    connection.execute('DROP TABLE %s' % tempName)
-                    trans.commit()
-                except:
-                    trans.rollback()
-                    raise
--- a/kallithea/lib/dbmigrate/migrate/versioning/migrate_repository.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,100 +0,0 @@
-"""
-   Script to migrate repository from sqlalchemy <= 0.4.4 to the new
-   repository schema. This shouldn't use any other migrate modules, so
-   that it can work in any version.
-"""
-
-import os
-import sys
-import logging
-
-log = logging.getLogger(__name__)
-
-
-def usage():
-    """Gives usage information."""
-    print """Usage: %(prog)s repository-to-migrate
-
-    Upgrade your repository to the new flat format.
-
-    NOTE: You should probably make a backup before running this.
-    """ % {'prog': sys.argv[0]}
-
-    sys.exit(1)
-
-
-def delete_file(filepath):
-    """Deletes a file and prints a message."""
-    log.info('Deleting file: %s', filepath)
-    os.remove(filepath)
-
-
-def move_file(src, tgt):
-    """Moves a file and prints a message."""
-    log.info('Moving file %s to %s', src, tgt)
-    if os.path.exists(tgt):
-        raise Exception(
-            'Cannot move file %s because target %s already exists' % \
-                (src, tgt))
-    os.rename(src, tgt)
-
-
-def delete_directory(dirpath):
-    """Delete a directory and print a message."""
-    log.info('Deleting directory: %s', dirpath)
-    os.rmdir(dirpath)
-
-
-def migrate_repository(repos):
-    """Does the actual migration to the new repository format."""
-    log.info('Migrating repository at: %s to new format', repos)
-    versions = '%s/versions' % repos
-    dirs = os.listdir(versions)
-    # Only use int's in list.
-    numdirs = [int(dirname) for dirname in dirs if dirname.isdigit()]
-    numdirs.sort()  # Sort list.
-    for dirname in numdirs:
-        origdir = '%s/%s' % (versions, dirname)
-        log.info('Working on directory: %s', origdir)
-        files = os.listdir(origdir)
-        files.sort()
-        for filename in files:
-            # Delete compiled Python files.
-            if filename.endswith('.pyc') or filename.endswith('.pyo'):
-                delete_file('%s/%s' % (origdir, filename))
-
-            # Delete empty __init__.py files.
-            origfile = '%s/__init__.py' % origdir
-            if os.path.exists(origfile) and len(open(origfile).read()) == 0:
-                delete_file(origfile)
-
-            # Move sql upgrade scripts.
-            if filename.endswith('.sql'):
-                version, dbms, operation = filename.split('.', 3)[0:3]
-                origfile = '%s/%s' % (origdir, filename)
-                # For instance:  2.postgres.upgrade.sql ->
-                #  002_postgres_upgrade.sql
-                tgtfile = '%s/%03d_%s_%s.sql' % (
-                    versions, int(version), dbms, operation)
-                move_file(origfile, tgtfile)
-
-        # Move Python upgrade script.
-        pyfile = '%s.py' % dirname
-        pyfilepath = '%s/%s' % (origdir, pyfile)
-        if os.path.exists(pyfilepath):
-            tgtfile = '%s/%03d.py' % (versions, int(dirname))
-            move_file(pyfilepath, tgtfile)
-
-        # Try to remove directory. Will fail if it's not empty.
-        delete_directory(origdir)
-
-
-def main():
-    """Main function to be called when using this script."""
-    if len(sys.argv) != 2:
-        usage()
-    migrate_repository(sys.argv[1])
-
-
-if __name__ == '__main__':
-    main()
--- a/kallithea/lib/dbmigrate/migrate/versioning/pathed.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,75 +0,0 @@
-"""
-   A path/directory class.
-"""
-
-import os
-import shutil
-import logging
-
-from kallithea.lib.dbmigrate.migrate import exceptions
-from kallithea.lib.dbmigrate.migrate.versioning.config import *
-from kallithea.lib.dbmigrate.migrate.versioning.util import KeyedInstance
-
-
-log = logging.getLogger(__name__)
-
-class Pathed(KeyedInstance):
-    """
-    A class associated with a path/directory tree.
-
-    Only one instance of this class may exist for a particular file;
-    __new__ will return an existing instance if possible
-    """
-    parent = None
-
-    @classmethod
-    def _key(cls, path):
-        return str(path)
-
-    def __init__(self, path):
-        self.path = path
-        if self.__class__.parent is not None:
-            self._init_parent(path)
-
-    def _init_parent(self, path):
-        """Try to initialize this object's parent, if it has one"""
-        parent_path = self.__class__._parent_path(path)
-        self.parent = self.__class__.parent(parent_path)
-        log.debug("Getting parent %r:%r", self.__class__.parent, parent_path)
-        self.parent._init_child(path, self)
-
-    def _init_child(self, child, path):
-        """Run when a child of this object is initialized.
-
-        Parameters: the child object; the path to this object (its
-        parent)
-        """
-
-    @classmethod
-    def _parent_path(cls, path):
-        """
-        Fetch the path of this object's parent from this object's path.
-        """
-        # os.path.dirname(), but strip directories like files (like
-        # unix basename)
-        #
-        # Treat directories like files...
-        if path[-1] == '/':
-            path = path[:-1]
-        ret = os.path.dirname(path)
-        return ret
-
-    @classmethod
-    def require_notfound(cls, path):
-        """Ensures a given path does not already exist"""
-        if os.path.exists(path):
-            raise exceptions.PathFoundError(path)
-
-    @classmethod
-    def require_found(cls, path):
-        """Ensures a given path already exists"""
-        if not os.path.exists(path):
-            raise exceptions.PathNotFoundError(path)
-
-    def __str__(self):
-        return self.path
--- a/kallithea/lib/dbmigrate/migrate/versioning/repository.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,247 +0,0 @@
-"""
-   SQLAlchemy migrate repository management.
-"""
-import os
-import shutil
-import string
-import logging
-
-from pkg_resources import resource_filename
-from tempita import Template as TempitaTemplate
-
-import kallithea
-from kallithea.lib.dbmigrate.migrate import exceptions
-from kallithea.lib.dbmigrate.migrate.versioning import version, pathed, cfgparse
-from kallithea.lib.dbmigrate.migrate.versioning.template import Template
-from kallithea.lib.dbmigrate.migrate.versioning.config import *
-
-
-log = logging.getLogger(__name__)
-
-class Changeset(dict):
-    """A collection of changes to be applied to a database.
-
-    Changesets are bound to a repository and manage a set of
-    scripts from that repository.
-
-    Behaves like a dict, for the most part. Keys are ordered based on step value.
-    """
-
-    def __init__(self, start, *changes, **k):
-        """
-        Give a start version; step must be explicitly stated.
-        """
-        self.step = k.pop('step', 1)
-        self.start = version.VerNum(start)
-        self.end = self.start
-        for change in changes:
-            self.add(change)
-
-    def __iter__(self):
-        return iter(self.items())
-
-    def keys(self):
-        """
-        In a series of upgrades x -> y, keys are version x. Sorted.
-        """
-        ret = super(Changeset, self).keys()
-        # Reverse order if downgrading
-        ret.sort(reverse=(self.step < 1))
-        return ret
-
-    def values(self):
-        return [self[k] for k in self.keys()]
-
-    def items(self):
-        return zip(self.keys(), self.values())
-
-    def add(self, change):
-        """Add new change to changeset"""
-        key = self.end
-        self.end += self.step
-        self[key] = change
-
-    def run(self, *p, **k):
-        """Run the changeset scripts"""
-        for _version, script in self:
-            script.run(*p, **k)
-
-
-class Repository(pathed.Pathed):
-    """A project's change script repository"""
-
-    _config = 'migrate.cfg'
-    _versions = 'versions'
-
-    def __init__(self, path):
-        log.debug('Loading repository %s...', path)
-        self.verify(path)
-        super(Repository, self).__init__(path)
-        self.config = cfgparse.Config(os.path.join(self.path, self._config))
-        self.versions = version.Collection(os.path.join(self.path,
-                                                      self._versions))
-        log.debug('Repository %s loaded successfully', path)
-        log.debug('Config: %r', self.config.to_dict())
-
-    @classmethod
-    def verify(cls, path):
-        """
-        Ensure the target path is a valid repository.
-
-        :raises: :exc:`InvalidRepositoryError <migrate.exceptions.InvalidRepositoryError>`
-        """
-        # Ensure the existence of required files
-        try:
-            cls.require_found(path)
-            cls.require_found(os.path.join(path, cls._config))
-            cls.require_found(os.path.join(path, cls._versions))
-        except exceptions.PathNotFoundError as e:
-            raise exceptions.InvalidRepositoryError(path)
-
-    @classmethod
-    def prepare_config(cls, tmpl_dir, name, options=None):
-        """
-        Prepare a project configuration file for a new project.
-
-        :param tmpl_dir: Path to Repository template
-        :param config_file: Name of the config file in Repository template
-        :param name: Repository name
-        :type tmpl_dir: string
-        :type config_file: string
-        :type name: string
-        :returns: Populated config file
-        """
-        if options is None:
-            options = {}
-        options.setdefault('version_table', 'migrate_version')
-        options.setdefault('repository_id', name)
-        options.setdefault('required_dbs', [])
-        options.setdefault('use_timestamp_numbering', False)
-
-        tmpl = open(os.path.join(tmpl_dir, cls._config)).read()
-        ret = TempitaTemplate(tmpl).substitute(options)
-
-        # cleanup
-        del options['__template_name__']
-
-        return ret
-
-    @classmethod
-    def create(cls, path, name, **opts):
-        """Create a repository at a specified path"""
-        cls.require_notfound(path)
-        theme = opts.pop('templates_theme', None)
-        t_path = opts.pop('templates_path', None)
-
-        # Create repository
-        tmpl_dir = Template(t_path).get_repository(theme=theme)
-        shutil.copytree(tmpl_dir, path)
-
-        # Edit config defaults
-        config_text = cls.prepare_config(tmpl_dir, name, options=opts)
-        fd = open(os.path.join(path, cls._config), 'w')
-        fd.write(config_text)
-        fd.close()
-
-        opts['repository_name'] = name
-
-        # Create a management script
-        manager = os.path.join(path, 'manage.py')
-        Repository.create_manage_file(manager, templates_theme=theme,
-            templates_path=t_path, **opts)
-
-        return cls(path)
-
-    def create_script(self, description, **k):
-        """API to :meth:`migrate.versioning.version.Collection.create_new_python_version`"""
-
-        k['use_timestamp_numbering'] = self.use_timestamp_numbering
-        self.versions.create_new_python_version(description, **k)
-
-    def create_script_sql(self, database, description, **k):
-        """API to :meth:`migrate.versioning.version.Collection.create_new_sql_version`"""
-        k['use_timestamp_numbering'] = self.use_timestamp_numbering
-        self.versions.create_new_sql_version(database, description, **k)
-
-    @property
-    def latest(self):
-        """API to :attr:`migrate.versioning.version.Collection.latest`"""
-        return self.versions.latest
-
-    @property
-    def version_table(self):
-        """Returns version_table name specified in config"""
-        return self.config.get('db_settings', 'version_table')
-
-    @property
-    def id(self):
-        """Returns repository id specified in config"""
-        # Adjust the value read from kallithea/lib/dbmigrate/migrate.cfg, normally "kallithea_db_migrations"
-        s = self.config.get('db_settings', 'repository_id')
-        if s == "kallithea_db_migrations":
-            s = kallithea.DB_MIGRATIONS
-        return s
-
-    @property
-    def use_timestamp_numbering(self):
-        """Returns use_timestamp_numbering specified in config"""
-        if self.config.has_option('db_settings', 'use_timestamp_numbering'):
-            return self.config.getboolean('db_settings', 'use_timestamp_numbering')
-        return False
-
-    def version(self, *p, **k):
-        """API to :attr:`migrate.versioning.version.Collection.version`"""
-        return self.versions.version(*p, **k)
-
-    @classmethod
-    def clear(cls):
-        # TODO: deletes repo
-        super(Repository, cls).clear()
-        version.Collection.clear()
-
-    def changeset(self, database, start, end=None):
-        """Create a changeset to migrate this database from ver. start to end/latest.
-
-        :param database: name of database to generate changeset
-        :param start: version to start at
-        :param end: version to end at (latest if None given)
-        :type database: string
-        :type start: int
-        :type end: int
-        :returns: :class:`Changeset instance <migration.versioning.repository.Changeset>`
-        """
-        start = version.VerNum(start)
-
-        if end is None:
-            end = self.latest
-        else:
-            end = version.VerNum(end)
-
-        if start <= end:
-            step = 1
-            range_mod = 1
-            op = 'upgrade'
-        else:
-            step = -1
-            range_mod = 0
-            op = 'downgrade'
-
-        versions = range(start + range_mod, end + range_mod, step)
-        changes = [self.version(v).script(database, op) for v in versions]
-        ret = Changeset(start, step=step, *changes)
-        return ret
-
-    @classmethod
-    def create_manage_file(cls, file_, **opts):
-        """Create a project management script (manage.py)
-
-        :param file_: Destination file to be written
-        :param opts: Options that are passed to :func:`migrate.versioning.shell.main`
-        """
-        mng_file = Template(opts.pop('templates_path', None))\
-            .get_manage(theme=opts.pop('templates_theme', None))
-
-        tmpl = open(mng_file).read()
-        fd = open(file_, 'w')
-        fd.write(TempitaTemplate(tmpl).substitute(opts))
-        fd.close()
--- a/kallithea/lib/dbmigrate/migrate/versioning/schema.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,221 +0,0 @@
-"""
-   Database schema version management.
-"""
-import sys
-import logging
-
-from sqlalchemy import (Table, Column, MetaData, String, Text, Integer,
-    create_engine)
-from sqlalchemy.sql import and_
-from sqlalchemy import exc as sa_exceptions
-from sqlalchemy.sql import bindparam
-
-from kallithea.lib.dbmigrate.migrate import exceptions
-from kallithea.lib.dbmigrate.migrate.changeset import SQLA_07
-from kallithea.lib.dbmigrate.migrate.versioning import genmodel, schemadiff
-from kallithea.lib.dbmigrate.migrate.versioning.repository import Repository
-from kallithea.lib.dbmigrate.migrate.versioning.util import load_model
-from kallithea.lib.dbmigrate.migrate.versioning.version import VerNum
-
-
-log = logging.getLogger(__name__)
-
-
-class ControlledSchema(object):
-    """A database under version control"""
-
-    def __init__(self, engine, repository):
-        if isinstance(repository, basestring):
-            repository = Repository(repository)
-        self.engine = engine
-        self.repository = repository
-        self.meta = MetaData(engine)
-        self.load()
-
-    def __eq__(self, other):
-        """Compare two schemas by repositories and versions"""
-        return (self.repository is other.repository \
-            and self.version == other.version)
-
-    def load(self):
-        """Load controlled schema version info from DB"""
-        tname = self.repository.version_table
-        try:
-            if not hasattr(self, 'table') or self.table is None:
-                    self.table = Table(tname, self.meta, autoload=True)
-
-            result = self.engine.execute(self.table.select(
-                self.table.c.repository_id == str(self.repository.id)))
-
-            data = list(result)[0]
-        except:
-            cls, exc, tb = sys.exc_info()
-            raise exceptions.DatabaseNotControlledError, exc.__str__(), tb
-
-        self.version = data['version']
-        return data
-
-    def drop(self):
-        """
-        Remove version control from a database.
-        """
-        if SQLA_07:
-            try:
-                self.table.drop()
-            except sa_exceptions.DatabaseError:
-                raise exceptions.DatabaseNotControlledError(str(self.table))
-        else:
-            try:
-                self.table.drop()
-            except (sa_exceptions.SQLError):
-                raise exceptions.DatabaseNotControlledError(str(self.table))
-
-    def changeset(self, version=None):
-        """API to Changeset creation.
-
-        Uses self.version for start version and engine.name
-        to get database name.
-        """
-        database = self.engine.name
-        start_ver = self.version
-        changeset = self.repository.changeset(database, start_ver, version)
-        return changeset
-
-    def runchange(self, ver, change, step):
-        startver = ver
-        endver = ver + step
-        # Current database version must be correct! Don't run if corrupt!
-        if self.version != startver:
-            raise exceptions.InvalidVersionError("%s is not %s" % \
-                                                     (self.version, startver))
-        # Run the change
-        change.run(self.engine, step)
-
-        # Update/refresh database version
-        self.update_repository_table(startver, endver)
-        self.load()
-
-    def update_repository_table(self, startver, endver):
-        """Update version_table with new information"""
-        update = self.table.update(and_(self.table.c.version == int(startver),
-             self.table.c.repository_id == str(self.repository.id)))
-        self.engine.execute(update, version=int(endver))
-
-    def upgrade(self, version=None):
-        """
-        Upgrade (or downgrade) to a specified version, or latest version.
-        """
-        changeset = self.changeset(version)
-        for ver, change in changeset:
-            self.runchange(ver, change, changeset.step)
-
-    def update_db_from_model(self, model):
-        """
-        Modify the database to match the structure of the current Python model.
-        """
-        model = load_model(model)
-
-        diff = schemadiff.getDiffOfModelAgainstDatabase(
-            model, self.engine, excludeTables=[self.repository.version_table]
-            )
-        genmodel.ModelGenerator(diff,self.engine).runB2A()
-
-        self.update_repository_table(self.version, int(self.repository.latest))
-
-        self.load()
-
-    @classmethod
-    def create(cls, engine, repository, version=None):
-        """
-        Declare a database to be under a repository's version control.
-
-        :raises: :exc:`DatabaseAlreadyControlledError`
-        :returns: :class:`ControlledSchema`
-        """
-        # Confirm that the version # is valid: positive, integer,
-        # exists in repos
-        if isinstance(repository, basestring):
-            repository = Repository(repository)
-        version = cls._validate_version(repository, version)
-        table = cls._create_table_version(engine, repository, version)
-        # TODO: history table
-        # Load repository information and return
-        return cls(engine, repository)
-
-    @classmethod
-    def _validate_version(cls, repository, version):
-        """
-        Ensures this is a valid version number for this repository.
-
-        :raises: :exc:`InvalidVersionError` if invalid
-        :return: valid version number
-        """
-        if version is None:
-            version = 0
-        try:
-            version = VerNum(version) # raises valueerror
-            if version < 0 or version > repository.latest:
-                raise ValueError()
-        except ValueError:
-            raise exceptions.InvalidVersionError(version)
-        return version
-
-    @classmethod
-    def _create_table_version(cls, engine, repository, version):
-        """
-        Creates the versioning table in a database.
-
-        :raises: :exc:`DatabaseAlreadyControlledError`
-        """
-        # Create tables
-        tname = repository.version_table
-        meta = MetaData(engine)
-
-        table = Table(
-            tname, meta,
-            Column('repository_id', String(250), primary_key=True),
-            Column('repository_path', Text),
-            Column('version', Integer), )
-
-        # there can be multiple repositories/schemas in the same db
-        if not table.exists():
-            table.create()
-
-        # test for existing repository_id
-        s = table.select(table.c.repository_id == bindparam("repository_id"))
-        result = engine.execute(s, repository_id=repository.id)
-        if result.fetchone():
-            raise exceptions.DatabaseAlreadyControlledError
-
-        # Insert data
-        engine.execute(table.insert().values(
-                           repository_id=repository.id,
-                           repository_path=repository.path,
-                           version=int(version)))
-        return table
-
-    @classmethod
-    def compare_model_to_db(cls, engine, model, repository):
-        """
-        Compare the current model against the current database.
-        """
-        if isinstance(repository, basestring):
-            repository = Repository(repository)
-        model = load_model(model)
-
-        diff = schemadiff.getDiffOfModelAgainstDatabase(
-            model, engine, excludeTables=[repository.version_table])
-        return diff
-
-    @classmethod
-    def create_model(cls, engine, repository, declarative=False):
-        """
-        Dump the current database as a Python model.
-        """
-        if isinstance(repository, basestring):
-            repository = Repository(repository)
-
-        diff = schemadiff.getDiffOfModelAgainstDatabase(
-            MetaData(), engine, excludeTables=[repository.version_table]
-            )
-        return genmodel.ModelGenerator(diff, engine, declarative).genBDefinition()
--- a/kallithea/lib/dbmigrate/migrate/versioning/schemadiff.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,295 +0,0 @@
-"""
-   Schema differencing support.
-"""
-
-import logging
-import sqlalchemy
-
-from kallithea.lib.dbmigrate.migrate.changeset import SQLA_06
-from sqlalchemy.types import Float
-
-log = logging.getLogger(__name__)
-
-
-def getDiffOfModelAgainstDatabase(metadata, engine, excludeTables=None):
-    """
-    Return differences of model against database.
-
-    :return: object which will evaluate to :keyword:`True` if there \
-      are differences else :keyword:`False`.
-    """
-    db_metadata = sqlalchemy.MetaData(engine)
-    db_metadata.reflect()
-
-    # sqlite will include a dynamically generated 'sqlite_sequence' table if
-    # there are autoincrement sequences in the database; this should not be
-    # compared.
-    if engine.dialect.name == 'sqlite':
-        if 'sqlite_sequence' in db_metadata.tables:
-            db_metadata.remove(db_metadata.tables['sqlite_sequence'])
-
-    return SchemaDiff(metadata, db_metadata,
-                      labelA='model',
-                      labelB='database',
-                      excludeTables=excludeTables)
-
-
-def getDiffOfModelAgainstModel(metadataA, metadataB, excludeTables=None):
-    """
-    Return differences of model against another model.
-
-    :return: object which will evaluate to :keyword:`True` if there \
-      are differences else :keyword:`False`.
-    """
-    return SchemaDiff(metadataA, metadataB, excludeTables=excludeTables)
-
-
-class ColDiff(object):
-    """
-    Container for differences in one :class:`~sqlalchemy.schema.Column`
-    between two :class:`~sqlalchemy.schema.Table` instances, ``A``
-    and ``B``.
-
-    .. attribute:: col_A
-
-      The :class:`~sqlalchemy.schema.Column` object for A.
-
-    .. attribute:: col_B
-
-      The :class:`~sqlalchemy.schema.Column` object for B.
-
-    .. attribute:: type_A
-
-      The most generic type of the :class:`~sqlalchemy.schema.Column`
-      object in A.
-
-    .. attribute:: type_B
-
-      The most generic type of the :class:`~sqlalchemy.schema.Column`
-      object in A.
-
-    """
-
-    diff = False
-
-    def __init__(self,col_A,col_B):
-        self.col_A = col_A
-        self.col_B = col_B
-
-        self.type_A = col_A.type
-        self.type_B = col_B.type
-
-        self.affinity_A = self.type_A._type_affinity
-        self.affinity_B = self.type_B._type_affinity
-
-        if self.affinity_A is not self.affinity_B:
-            self.diff = True
-            return
-
-        if isinstance(self.type_A,Float) or isinstance(self.type_B,Float):
-            if not (isinstance(self.type_A,Float) and isinstance(self.type_B,Float)):
-                self.diff=True
-                return
-
-        for attr in ('precision','scale','length'):
-            A = getattr(self.type_A,attr,None)
-            B = getattr(self.type_B,attr,None)
-            if not (A is None or B is None) and A!=B:
-                self.diff=True
-                return
-
-    def __nonzero__(self):
-        return self.diff
-
-class TableDiff(object):
-    """
-    Container for differences in one :class:`~sqlalchemy.schema.Table`
-    between two :class:`~sqlalchemy.schema.MetaData` instances, ``A``
-    and ``B``.
-
-    .. attribute:: columns_missing_from_A
-
-      A sequence of column names that were found in B but weren't in
-      A.
-
-    .. attribute:: columns_missing_from_B
-
-      A sequence of column names that were found in A but weren't in
-      B.
-
-    .. attribute:: columns_different
-
-      A dictionary containing information about columns that were
-      found to be different.
-      It maps column names to a :class:`ColDiff` objects describing the
-      differences found.
-    """
-    __slots__ = (
-        'columns_missing_from_A',
-        'columns_missing_from_B',
-        'columns_different',
-        )
-
-    def __nonzero__(self):
-        return bool(
-            self.columns_missing_from_A or
-            self.columns_missing_from_B or
-            self.columns_different
-            )
-
-class SchemaDiff(object):
-    """
-    Compute the difference between two :class:`~sqlalchemy.schema.MetaData`
-    objects.
-
-    The string representation of a :class:`SchemaDiff` will summarise
-    the changes found between the two
-    :class:`~sqlalchemy.schema.MetaData` objects.
-
-    The length of a :class:`SchemaDiff` will give the number of
-    changes found, enabling it to be used much like a boolean in
-    expressions.
-
-    :param metadataA:
-      First :class:`~sqlalchemy.schema.MetaData` to compare.
-
-    :param metadataB:
-      Second :class:`~sqlalchemy.schema.MetaData` to compare.
-
-    :param labelA:
-      The label to use in messages about the first
-      :class:`~sqlalchemy.schema.MetaData`.
-
-    :param labelB:
-      The label to use in messages about the second
-      :class:`~sqlalchemy.schema.MetaData`.
-
-    :param excludeTables:
-      A sequence of table names to exclude.
-
-    .. attribute:: tables_missing_from_A
-
-      A sequence of table names that were found in B but weren't in
-      A.
-
-    .. attribute:: tables_missing_from_B
-
-      A sequence of table names that were found in A but weren't in
-      B.
-
-    .. attribute:: tables_different
-
-      A dictionary containing information about tables that were found
-      to be different.
-      It maps table names to a :class:`TableDiff` objects describing the
-      differences found.
-    """
-
-    def __init__(self,
-                 metadataA, metadataB,
-                 labelA='metadataA',
-                 labelB='metadataB',
-                 excludeTables=None):
-
-        self.metadataA, self.metadataB = metadataA, metadataB
-        self.labelA, self.labelB = labelA, labelB
-        self.label_width = max(len(labelA),len(labelB))
-        excludeTables = set(excludeTables or [])
-
-        A_table_names = set(metadataA.tables.keys())
-        B_table_names = set(metadataB.tables.keys())
-
-        self.tables_missing_from_A = sorted(
-            B_table_names - A_table_names - excludeTables
-            )
-        self.tables_missing_from_B = sorted(
-            A_table_names - B_table_names - excludeTables
-            )
-
-        self.tables_different = {}
-        for table_name in A_table_names.intersection(B_table_names):
-
-            td = TableDiff()
-
-            A_table = metadataA.tables[table_name]
-            B_table = metadataB.tables[table_name]
-
-            A_column_names = set(A_table.columns.keys())
-            B_column_names = set(B_table.columns.keys())
-
-            td.columns_missing_from_A = sorted(
-                B_column_names - A_column_names
-                )
-
-            td.columns_missing_from_B = sorted(
-                A_column_names - B_column_names
-                )
-
-            td.columns_different = {}
-
-            for col_name in A_column_names.intersection(B_column_names):
-
-                cd = ColDiff(
-                    A_table.columns.get(col_name),
-                    B_table.columns.get(col_name)
-                    )
-
-                if cd:
-                    td.columns_different[col_name]=cd
-
-            # XXX - index and constraint differences should
-            #       be checked for here
-
-            if td:
-                self.tables_different[table_name]=td
-
-    def __str__(self):
-        """ Summarize differences. """
-        out = []
-        column_template ='      %%%is: %%r' % self.label_width
-
-        for names,label in (
-            (self.tables_missing_from_A,self.labelA),
-            (self.tables_missing_from_B,self.labelB),
-            ):
-            if names:
-                out.append(
-                    '  tables missing from %s: %s' % (
-                        label,', '.join(sorted(names))
-                        )
-                    )
-
-        for name,td in sorted(self.tables_different.items()):
-            out.append(
-               '  table with differences: %s' % name
-               )
-            for names,label in (
-                (td.columns_missing_from_A,self.labelA),
-                (td.columns_missing_from_B,self.labelB),
-                ):
-                if names:
-                    out.append(
-                        '    %s missing these columns: %s' % (
-                            label,', '.join(sorted(names))
-                            )
-                        )
-            for name,cd in td.columns_different.items():
-                out.append('    column with differences: %s' % name)
-                out.append(column_template % (self.labelA,cd.col_A))
-                out.append(column_template % (self.labelB,cd.col_B))
-
-        if out:
-            out.insert(0, 'Schema diffs:')
-            return '\n'.join(out)
-        else:
-            return 'No schema diffs'
-
-    def __len__(self):
-        """
-        Used in bool evaluation, return of 0 means no diffs.
-        """
-        return (
-            len(self.tables_missing_from_A) +
-            len(self.tables_missing_from_B) +
-            len(self.tables_different)
-            )
--- a/kallithea/lib/dbmigrate/migrate/versioning/script/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,6 +0,0 @@
-#!/usr/bin/env python2
-# -*- coding: utf-8 -*-
-
-from kallithea.lib.dbmigrate.migrate.versioning.script.base import BaseScript
-from kallithea.lib.dbmigrate.migrate.versioning.script.py import PythonScript
-from kallithea.lib.dbmigrate.migrate.versioning.script.sql import SqlScript
--- a/kallithea/lib/dbmigrate/migrate/versioning/script/base.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,57 +0,0 @@
-#!/usr/bin/env python2
-# -*- coding: utf-8 -*-
-import logging
-
-from kallithea.lib.dbmigrate.migrate import exceptions
-from kallithea.lib.dbmigrate.migrate.versioning.config import operations
-from kallithea.lib.dbmigrate.migrate.versioning import pathed
-
-
-log = logging.getLogger(__name__)
-
-class BaseScript(pathed.Pathed):
-    """Base class for other types of scripts.
-    All scripts have the following properties:
-
-    source (script.source())
-      The source code of the script
-    version (script.version())
-      The version number of the script
-    operations (script.operations())
-      The operations defined by the script: upgrade(), downgrade() or both.
-      Returns a tuple of operations.
-      Can also check for an operation with ex. script.operation(Script.ops.up)
-    """ # TODO: sphinxfy this and implement it correctly
-
-    def __init__(self, path):
-        log.debug('Loading script %s...', path)
-        self.verify(path)
-        super(BaseScript, self).__init__(path)
-        log.debug('Script %s loaded successfully', path)
-
-    @classmethod
-    def verify(cls, path):
-        """Ensure this is a valid script
-        This version simply ensures the script file's existence
-
-        :raises: :exc:`InvalidScriptError <migrate.exceptions.InvalidScriptError>`
-        """
-        try:
-            cls.require_found(path)
-        except:
-            raise exceptions.InvalidScriptError(path)
-
-    def source(self):
-        """:returns: source code of the script.
-        :rtype: string
-        """
-        fd = open(self.path)
-        ret = fd.read()
-        fd.close()
-        return ret
-
-    def run(self, engine):
-        """Core of each BaseScript subclass.
-        This method executes the script.
-        """
-        raise NotImplementedError()
--- a/kallithea/lib/dbmigrate/migrate/versioning/script/py.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,160 +0,0 @@
-#!/usr/bin/env python2
-# -*- coding: utf-8 -*-
-
-import shutil
-import warnings
-import logging
-import inspect
-from StringIO import StringIO
-
-from kallithea.lib.dbmigrate import migrate
-from kallithea.lib.dbmigrate.migrate.versioning import genmodel, schemadiff
-from kallithea.lib.dbmigrate.migrate.versioning.config import operations
-from kallithea.lib.dbmigrate.migrate.versioning.template import Template
-from kallithea.lib.dbmigrate.migrate.versioning.script import base
-from kallithea.lib.dbmigrate.migrate.versioning.util import import_path, load_model, with_engine
-from kallithea.lib.dbmigrate.migrate.exceptions import MigrateDeprecationWarning, InvalidScriptError, ScriptError
-
-log = logging.getLogger(__name__)
-__all__ = ['PythonScript']
-
-
-class PythonScript(base.BaseScript):
-    """Base for Python scripts"""
-
-    @classmethod
-    def create(cls, path, **opts):
-        """Create an empty migration script at specified path
-
-        :returns: :class:`PythonScript instance <migrate.versioning.script.py.PythonScript>`"""
-        cls.require_notfound(path)
-
-        src = Template(opts.pop('templates_path', None)).get_script(theme=opts.pop('templates_theme', None))
-        shutil.copy(src, path)
-
-        return cls(path)
-
-    @classmethod
-    def make_update_script_for_model(cls, engine, oldmodel,
-                                     model, repository, **opts):
-        """Create a migration script based on difference between two SA models.
-
-        :param repository: path to migrate repository
-        :param oldmodel: dotted.module.name:SAClass or SAClass object
-        :param model: dotted.module.name:SAClass or SAClass object
-        :param engine: SQLAlchemy engine
-        :type repository: string or :class:`Repository instance <migrate.versioning.repository.Repository>`
-        :type oldmodel: string or Class
-        :type model: string or Class
-        :type engine: Engine instance
-        :returns: Upgrade / Downgrade script
-        :rtype: string
-        """
-
-        if isinstance(repository, basestring):
-            # oh dear, an import cycle!
-            from kallithea.lib.dbmigrate.migrate.versioning.repository import Repository
-            repository = Repository(repository)
-
-        oldmodel = load_model(oldmodel)
-        model = load_model(model)
-
-        # Compute differences.
-        diff = schemadiff.getDiffOfModelAgainstModel(
-            model,
-            oldmodel,
-            excludeTables=[repository.version_table])
-        # TODO: diff can be False (there is no difference?)
-        decls, upgradeCommands, downgradeCommands = \
-            genmodel.ModelGenerator(diff,engine).genB2AMigration()
-
-        # Store differences into file.
-        src = Template(opts.pop('templates_path', None)).get_script(opts.pop('templates_theme', None))
-        f = open(src)
-        contents = f.read()
-        f.close()
-
-        # generate source
-        search = 'def upgrade(migrate_engine):'
-        contents = contents.replace(search, '\n\n'.join((decls, search)), 1)
-        if upgradeCommands:
-            contents = contents.replace('    pass', upgradeCommands, 1)
-        if downgradeCommands:
-            contents = contents.replace('    pass', downgradeCommands, 1)
-        return contents
-
-    @classmethod
-    def verify_module(cls, path):
-        """Ensure path is a valid script
-
-        :param path: Script location
-        :type path: string
-        :raises: :exc:`InvalidScriptError <migrate.exceptions.InvalidScriptError>`
-        :returns: Python module
-        """
-        # Try to import and get the upgrade() func
-        module = import_path(path)
-        try:
-            assert callable(module.upgrade)
-        except Exception as e:
-            raise InvalidScriptError(path + ': %s' % str(e))
-        return module
-
-    def preview_sql(self, url, step, **args):
-        """Mocks SQLAlchemy Engine to store all executed calls in a string
-        and runs :meth:`PythonScript.run <migrate.versioning.script.py.PythonScript.run>`
-
-        :returns: SQL file
-        """
-        buf = StringIO()
-        args['engine_arg_strategy'] = 'mock'
-        args['engine_arg_executor'] = lambda s, p = '': buf.write(str(s) + p)
-
-        @with_engine
-        def go(url, step, **kw):
-            engine = kw.pop('engine')
-            self.run(engine, step)
-            return buf.getvalue()
-
-        return go(url, step, **args)
-
-    def run(self, engine, step):
-        """Core method of Script file.
-        Executes :func:`update` or :func:`downgrade` functions
-
-        :param engine: SQLAlchemy Engine
-        :param step: Operation to run
-        :type engine: string
-        :type step: int
-        """
-        if step > 0:
-            op = 'upgrade'
-        elif step < 0:
-            op = 'downgrade'
-        else:
-            raise ScriptError("%d is not a valid step" % step)
-
-        funcname = base.operations[op]
-        script_func = self._func(funcname)
-
-        # check for old way of using engine
-        if not inspect.getargspec(script_func)[0]:
-            raise TypeError("upgrade/downgrade functions must accept engine"
-                " parameter (since version 0.5.4)")
-
-        script_func(engine)
-
-    @property
-    def module(self):
-        """Calls :meth:`migrate.versioning.script.py.verify_module`
-        and returns it.
-        """
-        if not hasattr(self, '_module'):
-            self._module = self.verify_module(self.path)
-        return self._module
-
-    def _func(self, funcname):
-        if not hasattr(self.module, funcname):
-            msg = "Function '%s' is not defined in this script"
-            raise ScriptError(msg % funcname)
-        return getattr(self.module, funcname)
--- a/kallithea/lib/dbmigrate/migrate/versioning/script/sql.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,49 +0,0 @@
-#!/usr/bin/env python2
-# -*- coding: utf-8 -*-
-import logging
-import shutil
-
-from kallithea.lib.dbmigrate.migrate.versioning.script import base
-from kallithea.lib.dbmigrate.migrate.versioning.template import Template
-
-
-log = logging.getLogger(__name__)
-
-class SqlScript(base.BaseScript):
-    """A file containing plain SQL statements."""
-
-    @classmethod
-    def create(cls, path, **opts):
-        """Create an empty migration script at specified path
-
-        :returns: :class:`SqlScript instance <migrate.versioning.script.sql.SqlScript>`"""
-        cls.require_notfound(path)
-
-        src = Template(opts.pop('templates_path', None)).get_sql_script(theme=opts.pop('templates_theme', None))
-        shutil.copy(src, path)
-        return cls(path)
-
-    # TODO: why is step parameter even here?
-    def run(self, engine, step=None, executemany=True):
-        """Runs SQL script through raw dbapi execute call"""
-        text = self.source()
-        # Don't rely on SA's autocommit here
-        # (SA uses .startswith to check if a commit is needed. What if script
-        # starts with a comment?)
-        conn = engine.connect()
-        try:
-            trans = conn.begin()
-            try:
-                # HACK: SQLite doesn't allow multiple statements through
-                # its execute() method, but it provides executescript() instead
-                dbapi = conn.engine.raw_connection()
-                if executemany and getattr(dbapi, 'executescript', None):
-                    dbapi.executescript(text)
-                else:
-                    conn.execute(text)
-                trans.commit()
-            except:
-                trans.rollback()
-                raise
-        finally:
-            conn.close()
--- a/kallithea/lib/dbmigrate/migrate/versioning/shell.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,214 +0,0 @@
-#!/usr/bin/env python2
-# -*- coding: utf-8 -*-
-
-"""The migrate command-line tool."""
-
-import sys
-import inspect
-import logging
-from optparse import OptionParser, BadOptionError
-
-from kallithea.lib.dbmigrate.migrate import exceptions
-from kallithea.lib.dbmigrate.migrate.versioning import api
-from kallithea.lib.dbmigrate.migrate.versioning.config import *
-from kallithea.lib.dbmigrate.migrate.versioning.util import asbool
-
-
-alias = dict(
-    s=api.script,
-    vc=api.version_control,
-    dbv=api.db_version,
-    v=api.version,
-)
-
-def alias_setup():
-    global alias
-    for key, val in alias.iteritems():
-        setattr(api, key, val)
-alias_setup()
-
-
-class PassiveOptionParser(OptionParser):
-
-    def _process_args(self, largs, rargs, values):
-        """little hack to support all --some_option=value parameters"""
-
-        while rargs:
-            arg = rargs[0]
-            if arg == "--":
-                del rargs[0]
-                return
-            elif arg[0:2] == "--":
-                # if parser does not know about the option
-                # pass it along (make it anonymous)
-                try:
-                    opt = arg.split('=', 1)[0]
-                    self._match_long_opt(opt)
-                except BadOptionError:
-                    largs.append(arg)
-                    del rargs[0]
-                else:
-                    self._process_long_opt(rargs, values)
-            elif arg[:1] == "-" and len(arg) > 1:
-                self._process_short_opts(rargs, values)
-            elif self.allow_interspersed_args:
-                largs.append(arg)
-                del rargs[0]
-
-def main(argv=None, **kwargs):
-    """Shell interface to :mod:`migrate.versioning.api`.
-
-    kwargs are default options that can be overridden with passing
-    --some_option as command line option
-
-    :param disable_logging: Let migrate configure logging
-    :type disable_logging: bool
-    """
-    if argv is not None:
-        argv = argv
-    else:
-        argv = list(sys.argv[1:])
-    commands = list(api.__all__)
-    commands.sort()
-
-    usage = """%%prog COMMAND ...
-
-    Available commands:
-        %s
-
-    Enter "%%prog help COMMAND" for information on a particular command.
-    """ % '\n\t'.join(["%s - %s" % (command.ljust(28), api.command_desc.get(command)) for command in commands])
-
-    parser = PassiveOptionParser(usage=usage)
-    parser.add_option("-d", "--debug",
-                     action="store_true",
-                     dest="debug",
-                     default=False,
-                     help="Shortcut to turn on DEBUG mode for logging")
-    parser.add_option("-q", "--disable_logging",
-                      action="store_true",
-                      dest="disable_logging",
-                      default=False,
-                      help="Use this option to disable logging configuration")
-    help_commands = ['help', '-h', '--help']
-    HELP = False
-
-    try:
-        command = argv.pop(0)
-        if command in help_commands:
-            HELP = True
-            command = argv.pop(0)
-    except IndexError:
-        parser.print_help()
-        return
-
-    command_func = getattr(api, command, None)
-    if command_func is None or command.startswith('_'):
-        parser.error("Invalid command %s" % command)
-
-    parser.set_usage(inspect.getdoc(command_func))
-    f_args, f_varargs, f_kwargs, f_defaults = inspect.getargspec(command_func)
-    for arg in f_args:
-        parser.add_option(
-            "--%s" % arg,
-            dest=arg,
-            action='store',
-            type="string")
-
-    # display help of the current command
-    if HELP:
-        parser.print_help()
-        return
-
-    options, args = parser.parse_args(argv)
-
-    # override kwargs with anonymous parameters
-    override_kwargs = dict()
-    for arg in list(args):
-        if arg.startswith('--'):
-            args.remove(arg)
-            if '=' in arg:
-                opt, value = arg[2:].split('=', 1)
-            else:
-                opt = arg[2:]
-                value = True
-            override_kwargs[opt] = value
-
-    # override kwargs with options if user is overwriting
-    for key, value in options.__dict__.iteritems():
-        if value is not None:
-            override_kwargs[key] = value
-
-    # arguments that function accepts without passed kwargs
-    f_required = list(f_args)
-    candidates = dict(kwargs)
-    candidates.update(override_kwargs)
-    for key, value in candidates.iteritems():
-        if key in f_args:
-            f_required.remove(key)
-
-    # map function arguments to parsed arguments
-    for arg in args:
-        try:
-            kw = f_required.pop(0)
-        except IndexError:
-            parser.error("Too many arguments for command %s: %s" % (command,
-                                                                    arg))
-        kwargs[kw] = arg
-
-    # apply overrides
-    kwargs.update(override_kwargs)
-
-    # configure options
-    for key, value in options.__dict__.iteritems():
-        kwargs.setdefault(key, value)
-
-    # configure logging
-    if not asbool(kwargs.pop('disable_logging', False)):
-        # filter to log =< INFO into stdout and rest to stderr
-        class SingleLevelFilter(logging.Filter):
-            def __init__(self, min=None, max=None):
-                self.min = min or 0
-                self.max = max or 100
-
-            def filter(self, record):
-                return self.min <= record.levelno <= self.max
-
-        logger = logging.getLogger()
-        h1 = logging.StreamHandler(sys.stdout)
-        f1 = SingleLevelFilter(max=logging.INFO)
-        h1.addFilter(f1)
-        h2 = logging.StreamHandler(sys.stderr)
-        f2 = SingleLevelFilter(min=logging.WARN)
-        h2.addFilter(f2)
-        logger.addHandler(h1)
-        logger.addHandler(h2)
-
-        if options.debug:
-            logger.setLevel(logging.DEBUG)
-        else:
-            logger.setLevel(logging.INFO)
-
-    log = logging.getLogger(__name__)
-
-    # check if all args are given
-    try:
-        num_defaults = len(f_defaults)
-    except TypeError:
-        num_defaults = 0
-    f_args_default = f_args[len(f_args) - num_defaults:]
-    required = list(set(f_required) - set(f_args_default))
-    if required:
-        parser.error("Not enough arguments for command %s: %s not specified" \
-            % (command, ', '.join(required)))
-
-    # handle command
-    try:
-        ret = command_func(**kwargs)
-        if ret is not None:
-            log.info(ret)
-    except (exceptions.UsageError, exceptions.KnownError) as e:
-        parser.error(e.args[0])
-
-if __name__ == "__main__":
-    main()
--- a/kallithea/lib/dbmigrate/migrate/versioning/template.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,94 +0,0 @@
-#!/usr/bin/env python2
-# -*- coding: utf-8 -*-
-
-import os
-import shutil
-import sys
-
-from pkg_resources import resource_filename
-
-from kallithea.lib.dbmigrate.migrate.versioning.config import *
-from kallithea.lib.dbmigrate.migrate.versioning import pathed
-
-
-class Collection(pathed.Pathed):
-    """A collection of templates of a specific type"""
-    _mask = None
-
-    def get_path(self, file):
-        return os.path.join(self.path, str(file))
-
-
-class RepositoryCollection(Collection):
-    _mask = '%s'
-
-class ScriptCollection(Collection):
-    _mask = '%s.py_tmpl'
-
-class ManageCollection(Collection):
-    _mask = '%s.py_tmpl'
-
-class SQLScriptCollection(Collection):
-    _mask = '%s.py_tmpl'
-
-class Template(pathed.Pathed):
-    """Finds the paths/packages of various Migrate templates.
-
-    :param path: Templates are loaded from kallithea.lib.dbmigrate.migrate package
-    if `path` is not provided.
-    """
-    pkg = 'kallithea.lib.dbmigrate.migrate.versioning.templates'
-    _manage = 'manage.py_tmpl'
-
-    def __new__(cls, path=None):
-        if path is None:
-            path = cls._find_path(cls.pkg)
-        return super(Template, cls).__new__(cls, path)
-
-    def __init__(self, path=None):
-        if path is None:
-            path = Template._find_path(self.pkg)
-        super(Template, self).__init__(path)
-        self.repository = RepositoryCollection(os.path.join(path, 'repository'))
-        self.script = ScriptCollection(os.path.join(path, 'script'))
-        self.manage = ManageCollection(os.path.join(path, 'manage'))
-        self.sql_script = SQLScriptCollection(os.path.join(path, 'sql_script'))
-
-    @classmethod
-    def _find_path(cls, pkg):
-        """Returns absolute path to dotted python package."""
-        tmp_pkg = pkg.rsplit('.', 1)
-
-        if len(tmp_pkg) != 1:
-            return resource_filename(tmp_pkg[0], tmp_pkg[1])
-        else:
-            return resource_filename(tmp_pkg[0], '')
-
-    def _get_item(self, collection, theme=None):
-        """Locates and returns collection.
-
-        :param collection: name of collection to locate
-        :param type_: type of subfolder in collection (defaults to "_default")
-        :returns: (package, source)
-        :rtype: str, str
-        """
-        item = getattr(self, collection)
-        theme_mask = getattr(item, '_mask')
-        theme = theme_mask % (theme or 'default')
-        return item.get_path(theme)
-
-    def get_repository(self, *a, **kw):
-        """Calls self._get_item('repository', *a, **kw)"""
-        return self._get_item('repository', *a, **kw)
-
-    def get_script(self, *a, **kw):
-        """Calls self._get_item('script', *a, **kw)"""
-        return self._get_item('script', *a, **kw)
-
-    def get_sql_script(self, *a, **kw):
-        """Calls self._get_item('sql_script', *a, **kw)"""
-        return self._get_item('sql_script', *a, **kw)
-
-    def get_manage(self, *a, **kw):
-        """Calls self._get_item('manage', *a, **kw)"""
-        return self._get_item('manage', *a, **kw)
--- a/kallithea/lib/dbmigrate/migrate/versioning/templates/manage.py_tmpl	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,5 +0,0 @@
-#!/usr/bin/env python2
-from migrate.versioning.shell import main
-
-if __name__ == '__main__':
-    main(%(defaults)s)
--- a/kallithea/lib/dbmigrate/migrate/versioning/templates/manage/default.py_tmpl	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,12 +0,0 @@
-#!/usr/bin/env python2
-from migrate.versioning.shell import main
-
-{{py:
-_vars = locals().copy()
-del _vars['__template_name__']
-_vars.pop('repository_name', None)
-defaults = ", ".join(["%s='%s'" % var for var in _vars.iteritems()])
-}}
-
-if __name__ == '__main__':
-    main({{ defaults }})
--- a/kallithea/lib/dbmigrate/migrate/versioning/templates/manage/pylons.py_tmpl	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,30 +0,0 @@
-#!/usr/bin/env python2
-# -*- coding: utf-8 -*-
-import sys
-
-from sqlalchemy import engine_from_config
-from paste.deploy.loadwsgi import ConfigLoader
-
-from migrate.versioning.shell import main
-from {{ locals().pop('repository_name') }}.model import migrations
-
-
-if '-c' in sys.argv:
-    pos = sys.argv.index('-c')
-    conf_path = sys.argv[pos + 1]
-    del sys.argv[pos:pos + 2]
-else:
-    conf_path = 'development.ini'
-
-{{py:
-_vars = locals().copy()
-del _vars['__template_name__']
-defaults = ", ".join(["%s='%s'" % var for var in _vars.iteritems()])
-}}
-
-conf_dict = ConfigLoader(conf_path).parser._sections['app:main']
-
-# migrate supports passing url as an existing Engine instance (since 0.6.0)
-# usage: migrate -c path/to/config.ini COMMANDS
-if __name__ == '__main__':
-    main(url=engine_from_config(conf_dict), repository=migrations.__path__[0],{{ defaults }})
--- a/kallithea/lib/dbmigrate/migrate/versioning/templates/repository/default/README	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,4 +0,0 @@
-This is a database migration repository.
-
-More information at
-http://code.google.com/p/sqlalchemy-migrate/
--- a/kallithea/lib/dbmigrate/migrate/versioning/templates/repository/default/migrate.cfg	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,25 +0,0 @@
-[db_settings]
-# Used to identify which repository this database is versioned under.
-# You can use the name of your project.
-repository_id={{ locals().pop('repository_id') }}
-
-# The name of the database table used to track the schema version.
-# This name shouldn't already be used by your project.
-# If this is changed once a database is under version control, you'll need to
-# change the table name in each database too.
-version_table={{ locals().pop('version_table') }}
-
-# When committing a change script, Migrate will attempt to generate the
-# sql for all supported databases; normally, if one of them fails - probably
-# because you don't have that database installed - it is ignored and the
-# commit continues, perhaps ending successfully.
-# Databases in this list MUST compile successfully during a commit, or the
-# entire commit will fail. List the databases your application will actually
-# be using to ensure your updates to that database work properly.
-# This must be a list; example: ['postgres','sqlite']
-required_dbs={{ locals().pop('required_dbs') }}
-
-# When creating new change scripts, Migrate will stamp the new script with
-# a version number. By default this is latest_version + 1. You can set this
-# to 'true' to tell Migrate to use the UTC timestamp instead.
-use_timestamp_numbering='false'
--- a/kallithea/lib/dbmigrate/migrate/versioning/templates/repository/pylons/README	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,4 +0,0 @@
-This is a database migration repository.
-
-More information at
-http://code.google.com/p/sqlalchemy-migrate/
--- a/kallithea/lib/dbmigrate/migrate/versioning/templates/repository/pylons/migrate.cfg	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,20 +0,0 @@
-[db_settings]
-# Used to identify which repository this database is versioned under.
-# You can use the name of your project.
-repository_id={{ locals().pop('repository_id') }}
-
-# The name of the database table used to track the schema version.
-# This name shouldn't already be used by your project.
-# If this is changed once a database is under version control, you'll need to
-# change the table name in each database too.
-version_table={{ locals().pop('version_table') }}
-
-# When committing a change script, Migrate will attempt to generate the
-# sql for all supported databases; normally, if one of them fails - probably
-# because you don't have that database installed - it is ignored and the
-# commit continues, perhaps ending successfully.
-# Databases in this list MUST compile successfully during a commit, or the
-# entire commit will fail. List the databases your application will actually
-# be using to ensure your updates to that database work properly.
-# This must be a list; example: ['postgres','sqlite']
-required_dbs={{ locals().pop('required_dbs') }}
--- a/kallithea/lib/dbmigrate/migrate/versioning/templates/script/default.py_tmpl	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,11 +0,0 @@
-from sqlalchemy import *
-from migrate import *
-
-def upgrade(migrate_engine):
-    # Upgrade operations go here. Don't create your own engine; bind migrate_engine
-    # to your metadata
-    pass
-
-def downgrade(migrate_engine):
-    # Operations to reverse the above upgrade go here.
-    pass
--- a/kallithea/lib/dbmigrate/migrate/versioning/templates/script/pylons.py_tmpl	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,11 +0,0 @@
-from sqlalchemy import *
-from migrate import *
-
-def upgrade(migrate_engine):
-    # Upgrade operations go here. Don't create your own engine; bind migrate_engine
-    # to your metadata
-    pass
-
-def downgrade(migrate_engine):
-    # Operations to reverse the above upgrade go here.
-    pass
--- a/kallithea/lib/dbmigrate/migrate/versioning/util/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,179 +0,0 @@
-#!/usr/bin/env python2
-# -*- coding: utf-8 -*-
-""".. currentmodule:: migrate.versioning.util"""
-
-import warnings
-import logging
-from decorator import decorator
-from pkg_resources import EntryPoint
-
-from sqlalchemy import create_engine
-from sqlalchemy.engine import Engine
-from sqlalchemy.pool import StaticPool
-
-from kallithea.lib.dbmigrate.migrate import exceptions
-from kallithea.lib.dbmigrate.migrate.versioning.util.keyedinstance import KeyedInstance
-from kallithea.lib.dbmigrate.migrate.versioning.util.importpath import import_path
-
-
-log = logging.getLogger(__name__)
-
-def load_model(dotted_name):
-    """Import module and use module-level variable".
-
-    :param dotted_name: path to model in form of string: ``some.python.module:Class``
-
-    .. versionchanged:: 0.5.4
-
-    """
-    if isinstance(dotted_name, basestring):
-        if ':' not in dotted_name:
-            # backwards compatibility
-            warnings.warn('model should be in form of module.model:User '
-                'and not module.model.User', exceptions.MigrateDeprecationWarning)
-            dotted_name = ':'.join(dotted_name.rsplit('.', 1))
-        return EntryPoint.parse('x=%s' % dotted_name).load(False)
-    else:
-        # Assume it's already loaded.
-        return dotted_name
-
-def asbool(obj):
-    """Do everything to use object as bool"""
-    if isinstance(obj, basestring):
-        obj = obj.strip().lower()
-        if obj in ['true', 'yes', 'on', 'y', 't', '1']:
-            return True
-        elif obj in ['false', 'no', 'off', 'n', 'f', '0']:
-            return False
-        else:
-            raise ValueError("String is not true/false: %r" % obj)
-    if obj in (True, False):
-        return bool(obj)
-    else:
-        raise ValueError("String is not true/false: %r" % obj)
-
-def guess_obj_type(obj):
-    """Do everything to guess object type from string
-
-    Tries to convert to `int`, `bool` and finally returns if not succeded.
-
-    .. versionadded: 0.5.4
-    """
-
-    result = None
-
-    try:
-        result = int(obj)
-    except:
-        pass
-
-    if result is None:
-        try:
-            result = asbool(obj)
-        except:
-            pass
-
-    if result is not None:
-        return result
-    else:
-        return obj
-
-@decorator
-def catch_known_errors(f, *a, **kw):
-    """Decorator that catches known api errors
-
-    .. versionadded: 0.5.4
-    """
-
-    try:
-        return f(*a, **kw)
-    except exceptions.PathFoundError as e:
-        raise exceptions.KnownError("The path %s already exists" % e.args[0])
-
-def construct_engine(engine, **opts):
-    """.. versionadded:: 0.5.4
-
-    Constructs and returns SQLAlchemy engine.
-
-    Currently, there are 2 ways to pass create_engine options to :mod:`migrate.versioning.api` functions:
-
-    :param engine: connection string or a existing engine
-    :param engine_dict: python dictionary of options to pass to `create_engine`
-    :param engine_arg_*: keyword parameters to pass to `create_engine` (evaluated with :func:`migrate.versioning.util.guess_obj_type`)
-    :type engine_dict: dict
-    :type engine: string or Engine instance
-    :type engine_arg_*: string
-    :returns: SQLAlchemy Engine
-
-    .. note::
-
-        keyword parameters override ``engine_dict`` values.
-
-    """
-    if isinstance(engine, Engine):
-        return engine
-    elif not isinstance(engine, basestring):
-        raise ValueError("you need to pass either an existing engine or a database uri")
-
-    # get options for create_engine
-    if opts.get('engine_dict') and isinstance(opts['engine_dict'], dict):
-        kwargs = opts['engine_dict']
-    else:
-        kwargs = dict()
-
-    # DEPRECATED: handle echo the old way
-    echo = asbool(opts.get('echo', False))
-    if echo:
-        warnings.warn('echo=True parameter is deprecated, pass '
-            'engine_arg_echo=True or engine_dict={"echo": True}',
-            exceptions.MigrateDeprecationWarning)
-        kwargs['echo'] = echo
-
-    # parse keyword arguments
-    for key, value in opts.iteritems():
-        if key.startswith('engine_arg_'):
-            kwargs[key[11:]] = guess_obj_type(value)
-
-    log.debug('Constructing engine')
-    # TODO: return create_engine(engine, poolclass=StaticPool, **kwargs)
-    # seems like 0.5.x branch does not work with engine.dispose and staticpool
-    return create_engine(engine, **kwargs)
-
-@decorator
-def with_engine(f, *a, **kw):
-    """Decorator for :mod:`migrate.versioning.api` functions
-    to safely close resources after function usage.
-
-    Passes engine parameters to :func:`construct_engine` and
-    resulting parameter is available as kw['engine'].
-
-    Engine is disposed after wrapped function is executed.
-
-    .. versionadded: 0.6.0
-    """
-    url = a[0]
-    engine = construct_engine(url, **kw)
-
-    try:
-        kw['engine'] = engine
-        return f(*a, **kw)
-    finally:
-        if isinstance(engine, Engine) and engine is not url:
-            log.debug('Disposing SQLAlchemy engine %s', engine)
-            engine.dispose()
-
-
-class Memoize:
-    """Memoize(fn) - an instance which acts like fn but memoizes its arguments
-       Will only work on functions with non-mutable arguments
-
-       ActiveState Code 52201
-    """
-    def __init__(self, fn):
-        self.fn = fn
-        self.memo = {}
-
-    def __call__(self, *args):
-        if not self.memo.has_key(args):
-            self.memo[args] = self.fn(*args)
-        return self.memo[args]
--- a/kallithea/lib/dbmigrate/migrate/versioning/util/importpath.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,15 +0,0 @@
-import os
-import sys
-
-def import_path(fullpath):
-    """ Import a file with full path specification. Allows one to
-        import from anywhere, something __import__ does not do.
-    """
-    # http://zephyrfalcon.org/weblog/arch_d7_2002_08_31.html
-    path, filename = os.path.split(fullpath)
-    filename, ext = os.path.splitext(filename)
-    sys.path.append(path)
-    module = __import__(filename)
-    reload(module) # Might be out of date during tests
-    del sys.path[-1]
-    return module
--- a/kallithea/lib/dbmigrate/migrate/versioning/util/keyedinstance.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,36 +0,0 @@
-#!/usr/bin/env python2
-# -*- coding: utf-8 -*-
-
-class KeyedInstance(object):
-    """A class whose instances have a unique identifier of some sort
-    No two instances with the same unique ID should exist - if we try to create
-    a second instance, the first should be returned.
-    """
-
-    _instances = dict()
-
-    def __new__(cls, *p, **k):
-        instances = cls._instances
-        clskey = str(cls)
-        if clskey not in instances:
-            instances[clskey] = dict()
-        instances = instances[clskey]
-
-        key = cls._key(*p, **k)
-        if key not in instances:
-            instances[key] = super(KeyedInstance, cls).__new__(cls)
-        return instances[key]
-
-    @classmethod
-    def _key(cls, *p, **k):
-        """Given a unique identifier, return a dictionary key
-        This should be overridden by child classes, to specify which parameters
-        should determine an object's uniqueness
-        """
-        raise NotImplementedError()
-
-    @classmethod
-    def clear(cls):
-        # Allow cls.clear() as well as uniqueInstance.clear(cls)
-        if str(cls) in cls._instances:
-            del cls._instances[str(cls)]
--- a/kallithea/lib/dbmigrate/migrate/versioning/version.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,238 +0,0 @@
-#!/usr/bin/env python2
-# -*- coding: utf-8 -*-
-
-import os
-import re
-import shutil
-import logging
-
-from kallithea.lib.dbmigrate.migrate import exceptions
-from kallithea.lib.dbmigrate.migrate.versioning import pathed, script
-from datetime import datetime
-
-
-log = logging.getLogger(__name__)
-
-class VerNum(object):
-    """A version number that behaves like a string and int at the same time"""
-
-    _instances = dict()
-
-    def __new__(cls, value):
-        val = str(value)
-        if val not in cls._instances:
-            cls._instances[val] = super(VerNum, cls).__new__(cls)
-        ret = cls._instances[val]
-        return ret
-
-    def __init__(self,value):
-        self.value = str(int(value))
-        if self < 0:
-            raise ValueError("Version number cannot be negative")
-
-    def __add__(self, value):
-        ret = int(self) + int(value)
-        return VerNum(ret)
-
-    def __sub__(self, value):
-        return self + (int(value) * -1)
-
-    def __cmp__(self, value):
-        return int(self) - int(value)
-
-    def __repr__(self):
-        return "<VerNum(%s)>" % self.value
-
-    def __str__(self):
-        return str(self.value)
-
-    def __int__(self):
-        return int(self.value)
-
-
-class Collection(pathed.Pathed):
-    """A collection of versioning scripts in a repository"""
-
-    FILENAME_WITH_VERSION = re.compile(r'^(\d{3,}).*')
-
-    def __init__(self, path):
-        """Collect current version scripts in repository
-        and store them in self.versions
-        """
-        super(Collection, self).__init__(path)
-
-        # Create temporary list of files, allowing skipped version numbers.
-        files = os.listdir(path)
-        if '1' in files:
-            # deprecation
-            raise Exception('It looks like you have a repository in the old '
-                'format (with directories for each version). '
-                'Please convert repository before proceeding.')
-
-        tempVersions = dict()
-        for filename in files:
-            match = self.FILENAME_WITH_VERSION.match(filename)
-            if match:
-                num = int(match.group(1))
-                tempVersions.setdefault(num, []).append(filename)
-            else:
-                pass  # Must be a helper file or something, let's ignore it.
-
-        # Create the versions member where the keys
-        # are VerNum's and the values are Version's.
-        self.versions = dict()
-        for num, files in tempVersions.items():
-            self.versions[VerNum(num)] = Version(num, path, files)
-
-    @property
-    def latest(self):
-        """:returns: Latest version in Collection"""
-        return max([VerNum(0)] + self.versions.keys())
-
-    def _next_ver_num(self, use_timestamp_numbering):
-        if use_timestamp_numbering:
-            return VerNum(int(datetime.utcnow().strftime('%Y%m%d%H%M%S')))
-        else:
-            return self.latest + 1
-
-    def create_new_python_version(self, description, **k):
-        """Create Python files for new version"""
-        ver = self._next_ver_num(k.pop('use_timestamp_numbering', False))
-        extra = str_to_filename(description)
-
-        if extra:
-            if extra == '_':
-                extra = ''
-            elif not extra.startswith('_'):
-                extra = '_%s' % extra
-
-        filename = '%03d%s.py' % (ver, extra)
-        filepath = self._version_path(filename)
-
-        script.PythonScript.create(filepath, **k)
-        self.versions[ver] = Version(ver, self.path, [filename])
-
-    def create_new_sql_version(self, database, description, **k):
-        """Create SQL files for new version"""
-        ver = self._next_ver_num(k.pop('use_timestamp_numbering', False))
-        self.versions[ver] = Version(ver, self.path, [])
-
-        extra = str_to_filename(description)
-
-        if extra:
-            if extra == '_':
-                extra = ''
-            elif not extra.startswith('_'):
-                extra = '_%s' % extra
-
-        # Create new files.
-        for op in ('upgrade', 'downgrade'):
-            filename = '%03d%s_%s_%s.sql' % (ver, extra, database, op)
-            filepath = self._version_path(filename)
-            script.SqlScript.create(filepath, **k)
-            self.versions[ver].add_script(filepath)
-
-    def version(self, vernum=None):
-        """Returns latest Version if vernum is not given.
-        Otherwise, returns wanted version"""
-        if vernum is None:
-            vernum = self.latest
-        return self.versions[VerNum(vernum)]
-
-    @classmethod
-    def clear(cls):
-        super(Collection, cls).clear()
-
-    def _version_path(self, ver):
-        """Returns path of file in versions repository"""
-        return os.path.join(self.path, str(ver))
-
-
-class Version(object):
-    """A single version in a collection
-    :param vernum: Version Number
-    :param path: Path to script files
-    :param filelist: List of scripts
-    :type vernum: int, VerNum
-    :type path: string
-    :type filelist: list
-    """
-
-    def __init__(self, vernum, path, filelist):
-        self.version = VerNum(vernum)
-
-        # Collect scripts in this folder
-        self.sql = dict()
-        self.python = None
-
-        for script in filelist:
-            self.add_script(os.path.join(path, script))
-
-    def script(self, database=None, operation=None):
-        """Returns SQL or Python Script"""
-        for db in (database, 'default'):
-            # Try to return a .sql script first
-            try:
-                return self.sql[db][operation]
-            except KeyError:
-                continue  # No .sql script exists
-
-        # TODO: maybe add force Python parameter?
-        ret = self.python
-
-        assert ret is not None, \
-            "There is no script for %d version" % self.version
-        return ret
-
-    def add_script(self, path):
-        """Add script to Collection/Version"""
-        if path.endswith(Extensions.py):
-            self._add_script_py(path)
-        elif path.endswith(Extensions.sql):
-            self._add_script_sql(path)
-
-    SQL_FILENAME = re.compile(r'^.*\.sql')
-
-    def _add_script_sql(self, path):
-        basename = os.path.basename(path)
-        match = self.SQL_FILENAME.match(basename)
-
-        if match:
-            basename = basename.replace('.sql', '')
-            parts = basename.split('_')
-            if len(parts) < 3:
-                raise exceptions.ScriptError(
-                    "Invalid SQL script name %s " % basename + \
-                    "(needs to be ###_description_database_operation.sql)")
-            version = parts[0]
-            op = parts[-1]
-            dbms = parts[-2]
-        else:
-            raise exceptions.ScriptError(
-                "Invalid SQL script name %s " % basename + \
-                "(needs to be ###_description_database_operation.sql)")
-
-        # File the script into a dictionary
-        self.sql.setdefault(dbms, {})[op] = script.SqlScript(path)
-
-    def _add_script_py(self, path):
-        if self.python is not None:
-            raise exceptions.ScriptError('You can only have one Python script '
-                'per version, but you have: %s and %s' % (self.python, path))
-        self.python = script.PythonScript(path)
-
-
-class Extensions:
-    """A namespace for file extensions"""
-    py = 'py'
-    sql = 'sql'
-
-def str_to_filename(s):
-    """Replaces spaces, (double and single) quotes
-    and double underscores to underscores
-    """
-
-    s = s.replace(' ', '_').replace('"', '_').replace("'", '_').replace(".", "_")
-    while '__' in s:
-        s = s.replace('__', '_')
-    return s
--- a/kallithea/lib/dbmigrate/schema/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,26 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate.schema
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Schemas for migrations
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Nov 1, 2011
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
--- a/kallithea/lib/dbmigrate/schema/db_1_1_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,93 +0,0 @@
-from sqlalchemy import *
-from sqlalchemy.orm import relation, class_mapper
-from sqlalchemy.orm.session import Session
-from kallithea.model.meta import Base
-
-class BaseModel(object):
-    """Base Model for all classess
-
-    """
-
-    @classmethod
-    def _get_keys(cls):
-        """return column names for this model """
-        return class_mapper(cls).c.keys()
-
-    def get_dict(self):
-        """return dict with keys and values corresponding
-        to this model data """
-
-        d = {}
-        for k in self._get_keys():
-            d[k] = getattr(self, k)
-        return d
-
-    def get_appstruct(self):
-        """return list with keys and values tuples corresponding
-        to this model data """
-
-        l = []
-        for k in self._get_keys():
-            l.append((k, getattr(self, k),))
-        return l
-
-    def populate_obj(self, populate_dict):
-        """populate model with data from given populate_dict"""
-
-        for k in self._get_keys():
-            if k in populate_dict:
-                setattr(self, k, populate_dict[k])
-
-    @classmethod
-    def query(cls):
-        return Session.query(cls)
-
-    @classmethod
-    def get(cls, id_):
-        if id_:
-            return cls.query().get(id_)
-
-    @classmethod
-    def getAll(cls):
-        return cls.query().all()
-
-    @classmethod
-    def delete(cls, id_):
-        obj = cls.query().get(id_)
-        Session.delete(obj)
-        Session.commit()
-
-
-class UserFollowing(Base, BaseModel):
-    __tablename__ = 'user_followings'
-    __table_args__ = (UniqueConstraint('user_id', 'follows_repository_id'),
-                      UniqueConstraint('user_id', 'follows_user_id')
-                      , {'useexisting':True})
-
-    user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey(u'users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey(u'repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column("follows_user_id", Integer(), ForeignKey(u'users.user_id'), nullable=True, unique=None, default=None)
-
-    user = relation('User', primaryjoin='User.user_id==UserFollowing.user_id')
-
-    follows_user = relation('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relation('Repository')
-
-
-class CacheInvalidation(Base, BaseModel):
-    __tablename__ = 'cache_invalidation'
-    __table_args__ = (UniqueConstraint('cache_key'), {'useexisting':True})
-    cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    cache_key = Column("cache_key", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    cache_args = Column("cache_args", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
-
-
-    def __init__(self, cache_key, cache_args=''):
-        self.cache_key = cache_key
-        self.cache_args = cache_args
-        self.cache_active = False
-
-    def __repr__(self):
-        return "<CacheInvalidation('%s:%s')>" % (self.cache_id, self.cache_key)
--- a/kallithea/lib/dbmigrate/schema/db_1_2_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1097 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate.schema.db_1_2_0
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Database Models for Kallithea <=1.2.X
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Apr 08, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-import os
-import logging
-import datetime
-import traceback
-from datetime import date
-
-from sqlalchemy import *
-from sqlalchemy.ext.hybrid import hybrid_property
-from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
-from beaker.cache import cache_region, region_invalidate
-
-from kallithea.lib.vcs import get_backend
-from kallithea.lib.vcs.utils.helpers import get_scm
-from kallithea.lib.vcs.exceptions import VCSError
-from kallithea.lib.vcs.utils.lazy import LazyProperty
-
-from kallithea.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
-    generate_api_key, safe_unicode
-from kallithea.lib.exceptions import UserGroupsAssignedException
-from kallithea.lib.compat import json
-
-from kallithea.model.meta import Base, Session
-from kallithea.lib.caching_query import FromCache
-
-from kallithea import DB_PREFIX
-
-log = logging.getLogger(__name__)
-
-#==============================================================================
-# BASE CLASSES
-#==============================================================================
-
-class ModelSerializer(json.JSONEncoder):
-    """
-    Simple Serializer for JSON,
-
-    usage::
-
-        to make object customized for serialization implement a __json__
-        method that will return a dict for serialization into json
-
-    example::
-
-        class Task(object):
-
-            def __init__(self, name, value):
-                self.name = name
-                self.value = value
-
-            def __json__(self):
-                return dict(name=self.name,
-                            value=self.value)
-
-    """
-
-    def default(self, obj):
-
-        if hasattr(obj, '__json__'):
-            return obj.__json__()
-        else:
-            return json.JSONEncoder.default(self, obj)
-
-class BaseModel(object):
-    """Base Model for all classes
-
-    """
-
-    @classmethod
-    def _get_keys(cls):
-        """return column names for this model """
-        return class_mapper(cls).c.keys()
-
-    def get_dict(self):
-        """return dict with keys and values corresponding
-        to this model data """
-
-        d = {}
-        for k in self._get_keys():
-            d[k] = getattr(self, k)
-        return d
-
-    def get_appstruct(self):
-        """return list with keys and values tuples corresponding
-        to this model data """
-
-        l = []
-        for k in self._get_keys():
-            l.append((k, getattr(self, k),))
-        return l
-
-    def populate_obj(self, populate_dict):
-        """populate model with data from given populate_dict"""
-
-        for k in self._get_keys():
-            if k in populate_dict:
-                setattr(self, k, populate_dict[k])
-
-    @classmethod
-    def query(cls):
-        return Session.query(cls)
-
-    @classmethod
-    def get(cls, id_):
-        if id_:
-            return cls.query().get(id_)
-
-    @classmethod
-    def getAll(cls):
-        return cls.query().all()
-
-    @classmethod
-    def delete(cls, id_):
-        obj = cls.query().get(id_)
-        Session.delete(obj)
-        Session.commit()
-
-
-class Setting(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'settings'
-    __table_args__ = (UniqueConstraint('app_settings_name'), {'extend_existing':True})
-    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    app_settings_name = Column("app_settings_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_value = Column("app_settings_value", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __init__(self, k='', v=''):
-        self.app_settings_name = k
-        self.app_settings_value = v
-
-
-    @validates('_app_settings_value')
-    def validate_settings_value(self, key, val):
-        assert type(val) == unicode
-        return val
-
-    @hybrid_property
-    def app_settings_value(self):
-        v = self._app_settings_value
-        if v == 'ldap_active':
-            v = str2bool(v)
-        return v
-
-    @app_settings_value.setter
-    def app_settings_value(self, val):
-        """
-        Setter that will always make sure we use unicode in app_settings_value
-
-        :param val:
-        """
-        self._app_settings_value = safe_unicode(val)
-
-    def __repr__(self):
-        return "<%s('%s:%s')>" % (self.__class__.__name__,
-                                  self.app_settings_name, self.app_settings_value)
-
-
-    @classmethod
-    def get_by_name(cls, ldap_key):
-        return cls.query()\
-            .filter(cls.app_settings_name == ldap_key).scalar()
-
-    @classmethod
-    def get_app_settings(cls, cache=False):
-
-        ret = cls.query()
-
-        if cache:
-            ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
-
-        if not ret:
-            raise Exception('Could not get application settings !')
-        settings = {}
-        for each in ret:
-            settings[each.app_settings_name] = \
-                each.app_settings_value
-
-        return settings
-
-    @classmethod
-    def get_ldap_settings(cls, cache=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('ldap_')).all()
-        fd = {}
-        for row in ret:
-            fd.update({row.app_settings_name:row.app_settings_value})
-
-        return fd
-
-
-class Ui(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'ui'
-    __table_args__ = (UniqueConstraint('ui_key'), {'extend_existing':True})
-
-    HOOK_UPDATE = 'changegroup.update'
-    HOOK_REPO_SIZE = 'changegroup.repo_size'
-    HOOK_PUSH = 'pretxnchangegroup.push_logger'
-    HOOK_PULL = 'preoutgoing.pull_logger'
-
-    ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    ui_section = Column("ui_section", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_key = Column("ui_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_value = Column("ui_value", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
-
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.ui_key == key)
-
-
-    @classmethod
-    def get_builtin_hooks(cls):
-        q = cls.query()
-        q = q.filter(cls.ui_key.in_([cls.HOOK_UPDATE,
-                                    cls.HOOK_REPO_SIZE,
-                                    cls.HOOK_PUSH, cls.HOOK_PULL]))
-        return q.all()
-
-    @classmethod
-    def get_custom_hooks(cls):
-        q = cls.query()
-        q = q.filter(~cls.ui_key.in_([cls.HOOK_UPDATE,
-                                    cls.HOOK_REPO_SIZE,
-                                    cls.HOOK_PUSH, cls.HOOK_PULL]))
-        q = q.filter(cls.ui_section == 'hooks')
-        return q.all()
-
-    @classmethod
-    def create_or_update_hook(cls, key, val):
-        new_ui = cls.get_by_key(key).scalar() or cls()
-        new_ui.ui_section = 'hooks'
-        new_ui.ui_active = True
-        new_ui.ui_key = key
-        new_ui.ui_value = val
-
-        Session.add(new_ui)
-        Session.commit()
-
-
-class User(Base, BaseModel):
-    __tablename__ = 'users'
-    __table_args__ = (UniqueConstraint('username'), UniqueConstraint('email'), {'extend_existing':True})
-    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    username = Column("username", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    password = Column("password", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=None)
-    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
-    name = Column("name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    lastname = Column("lastname", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    email = Column("email", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
-    ldap_dn = Column("ldap_dn", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    api_key = Column("api_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    user_log = relationship('UserLog', cascade='all')
-    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
-
-    repositories = relationship('Repository')
-    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
-    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
-
-    group_member = relationship('UserGroupMember', cascade='all')
-
-    @property
-    def full_contact(self):
-        return '%s %s <%s>' % (self.name, self.lastname, self.email)
-
-    @property
-    def short_contact(self):
-        return '%s %s' % (self.name, self.lastname)
-
-    @property
-    def is_admin(self):
-        return self.admin
-
-    def __repr__(self):
-        try:
-            return "<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                             self.user_id, self.username)
-        except:
-            return self.__class__.__name__
-
-    @classmethod
-    def get_by_username(cls, username, case_insensitive=False):
-        if case_insensitive:
-            return Session.query(cls).filter(cls.username.ilike(username)).scalar()
-        else:
-            return Session.query(cls).filter(cls.username == username).scalar()
-
-    @classmethod
-    def get_by_api_key(cls, api_key):
-        return cls.query().filter(cls.api_key == api_key).one()
-
-    def update_lastlogin(self):
-        """Update user lastlogin"""
-
-        self.last_login = datetime.datetime.now()
-        Session.add(self)
-        Session.commit()
-        log.debug('updated user %s lastlogin', self.username)
-
-    @classmethod
-    def create(cls, form_data):
-        from kallithea.lib.auth import get_crypt_password
-
-        try:
-            new_user = cls()
-            for k, v in form_data.items():
-                if k == 'password':
-                    v = get_crypt_password(v)
-                setattr(new_user, k, v)
-
-            new_user.api_key = generate_api_key()
-            Session.add(new_user)
-            Session.commit()
-            return new_user
-        except:
-            log.error(traceback.format_exc())
-            Session.rollback()
-            raise
-
-class UserLog(Base, BaseModel):
-    __tablename__ = 'user_logs'
-    __table_args__ = {'extend_existing':True}
-    user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-    repository_name = Column("repository_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    user_ip = Column("user_ip", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action = Column("action", UnicodeText(length=1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
-
-    @property
-    def action_as_day(self):
-        return date(*self.action_date.timetuple()[:3])
-
-    user = relationship('User')
-    repository = relationship('Repository')
-
-
-class UserGroup(Base, BaseModel):
-    __tablename__ = 'users_groups'
-    __table_args__ = {'extend_existing':True}
-
-    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_name = Column("users_group_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
-
-    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
-
-    def __repr__(self):
-        return '<userGroup(%s)>' % (self.users_group_name)
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
-        if case_insensitive:
-            gr = cls.query()\
-                .filter(cls.users_group_name.ilike(group_name))
-        else:
-            gr = cls.query()\
-                .filter(cls.users_group_name == group_name)
-        if cache:
-            gr = gr.options(FromCache("sql_cache_short",
-                                          "get_user_%s" % group_name))
-        return gr.scalar()
-
-
-    @classmethod
-    def get(cls, users_group_id, cache=False):
-        users_group = cls.query()
-        if cache:
-            users_group = users_group.options(FromCache("sql_cache_short",
-                                    "get_users_group_%s" % users_group_id))
-        return users_group.get(users_group_id)
-
-    @classmethod
-    def create(cls, form_data):
-        try:
-            new_users_group = cls()
-            for k, v in form_data.items():
-                setattr(new_users_group, k, v)
-
-            Session.add(new_users_group)
-            Session.commit()
-            return new_users_group
-        except:
-            log.error(traceback.format_exc())
-            Session.rollback()
-            raise
-
-    @classmethod
-    def update(cls, users_group_id, form_data):
-
-        try:
-            users_group = cls.get(users_group_id, cache=False)
-
-            for k, v in form_data.items():
-                if k == 'users_group_members':
-                    users_group.members = []
-                    Session.flush()
-                    members_list = []
-                    if v:
-                        v = [v] if isinstance(v, basestring) else v
-                        for u_id in set(v):
-                            member = UserGroupMember(users_group_id, u_id)
-                            members_list.append(member)
-                    setattr(users_group, 'members', members_list)
-                setattr(users_group, k, v)
-
-            Session.add(users_group)
-            Session.commit()
-        except:
-            log.error(traceback.format_exc())
-            Session.rollback()
-            raise
-
-    @classmethod
-    def delete(cls, users_group_id):
-        try:
-
-            # check if this group is not assigned to repo
-            assigned_groups = UserGroupRepoToPerm.query()\
-                .filter(UserGroupRepoToPerm.users_group_id ==
-                        users_group_id).all()
-
-            if assigned_groups:
-                raise UserGroupsAssignedException('RepoGroup assigned to %s' %
-                                                   assigned_groups)
-
-            users_group = cls.get(users_group_id, cache=False)
-            Session.delete(users_group)
-            Session.commit()
-        except:
-            log.error(traceback.format_exc())
-            Session.rollback()
-            raise
-
-class UserGroupMember(Base, BaseModel):
-    __tablename__ = 'users_groups_members'
-    __table_args__ = {'extend_existing':True}
-
-    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User', lazy='joined')
-    users_group = relationship('UserGroup')
-
-    def __init__(self, gr_id='', u_id=''):
-        self.users_group_id = gr_id
-        self.user_id = u_id
-
-    @staticmethod
-    def add_user_to_group(group, user):
-        ugm = UserGroupMember()
-        ugm.users_group = group
-        ugm.user = user
-        Session.add(ugm)
-        Session.commit()
-        return ugm
-
-class Repository(Base, BaseModel):
-    __tablename__ = 'repositories'
-    __table_args__ = (UniqueConstraint('repo_name'), {'extend_existing':True},)
-
-    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repo_name = Column("repo_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    clone_uri = Column("clone_uri", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    repo_type = Column("repo_type", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default='hg')
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
-    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
-    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
-    description = Column("description", String(length=10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-
-    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
-
-
-    user = relationship('User')
-    fork = relationship('Repository', remote_side=repo_id)
-    group = relationship('RepoGroup')
-    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    stats = relationship('Statistics', cascade='all', uselist=False)
-
-    followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', cascade='all')
-
-    logs = relationship('UserLog', cascade='all')
-
-    def __repr__(self):
-        return "<%s('%s:%s')>" % (self.__class__.__name__,
-                                  self.repo_id, self.repo_name)
-
-    @classmethod
-    def url_sep(cls):
-        return '/'
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        q = Session.query(cls).filter(cls.repo_name == repo_name)
-        q = q.options(joinedload(Repository.fork))\
-                .options(joinedload(Repository.user))\
-                .options(joinedload(Repository.group))
-        return q.one()
-
-    @classmethod
-    def get_repo_forks(cls, repo_id):
-        return cls.query().filter(Repository.fork_id == repo_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all repos are stored
-
-        :param cls:
-        """
-        q = Session.query(Ui).filter(Ui.ui_key ==
-                                              cls.url_sep())
-        q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def just_name(self):
-        return self.repo_name.split(Repository.url_sep())[-1]
-
-    @property
-    def groups_with_parents(self):
-        groups = []
-        if self.group is None:
-            return groups
-
-        cur_gr = self.group
-        groups.insert(0, cur_gr)
-        while 1:
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            groups.insert(0, gr)
-
-        return groups
-
-    @property
-    def groups_and_repo(self):
-        return self.groups_with_parents, self.just_name
-
-    @LazyProperty
-    def repo_path(self):
-        """
-        Returns base full path for that repository means where it actually
-        exists on a filesystem
-        """
-        q = Session.query(Ui).filter(Ui.ui_key ==
-                                              Repository.url_sep())
-        q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def repo_full_path(self):
-        p = [self.repo_path]
-        # we need to split the name by / since this is how we store the
-        # names in the database, but that eventually needs to be converted
-        # into a valid system path
-        p += self.repo_name.split(Repository.url_sep())
-        return os.path.join(*p)
-
-    def get_new_name(self, repo_name):
-        """
-        returns new full repository name based on assigned group and new new
-
-        :param group_name:
-        """
-        path_prefix = self.group.full_path_splitted if self.group else []
-        return Repository.url_sep().join(path_prefix + [repo_name])
-
-    @property
-    def _ui(self):
-        """
-        Creates an db based ui object for this repository
-        """
-        from mercurial import ui
-        from mercurial import config
-        baseui = ui.ui()
-
-        #clean the baseui object
-        baseui._ocfg = config.config()
-        baseui._ucfg = config.config()
-        baseui._tcfg = config.config()
-
-
-        ret = Ui.query()\
-            .options(FromCache("sql_cache_short", "repository_repo_ui")).all()
-
-        hg_ui = ret
-        for ui_ in hg_ui:
-            if ui_.ui_active:
-                log.debug('settings ui from db: [%s] %s=%s', ui_.ui_section,
-                          ui_.ui_key, ui_.ui_value)
-                baseui.setconfig(ui_.ui_section, ui_.ui_key, ui_.ui_value)
-
-        return baseui
-
-    @classmethod
-    def is_valid(cls, repo_name):
-        """
-        returns True if given repo name is a valid filesystem repository
-
-        :param cls:
-        :param repo_name:
-        """
-        from kallithea.lib.utils import is_valid_repo
-
-        return is_valid_repo(repo_name, cls.base_path())
-
-
-    #==========================================================================
-    # SCM PROPERTIES
-    #==========================================================================
-
-    def get_changeset(self, rev):
-        return get_changeset_safe(self.scm_instance, rev)
-
-    @property
-    def tip(self):
-        return self.get_changeset('tip')
-
-    @property
-    def author(self):
-        return self.tip.author
-
-    @property
-    def last_change(self):
-        return self.scm_instance.last_change
-
-    #==========================================================================
-    # SCM CACHE INSTANCE
-    #==========================================================================
-
-    @property
-    def invalidate(self):
-        return CacheInvalidation.invalidate(self.repo_name)
-
-    def set_invalidate(self):
-        """
-        set a cache for invalidation for this instance
-        """
-        CacheInvalidation.set_invalidate(self.repo_name)
-
-    @LazyProperty
-    def scm_instance(self):
-        return self.__get_instance()
-
-    @property
-    def scm_instance_cached(self):
-        @cache_region('long_term')
-        def _c(repo_name):
-            return self.__get_instance()
-        rn = self.repo_name
-
-        inv = self.invalidate
-        if inv is not None:
-            region_invalidate(_c, None, rn)
-            # update our cache
-            CacheInvalidation.set_valid(inv.cache_key)
-        return _c(rn)
-
-    def __get_instance(self):
-
-        repo_full_path = self.repo_full_path
-
-        try:
-            alias = get_scm(repo_full_path)[0]
-            log.debug('Creating instance of %s repository', alias)
-            backend = get_backend(alias)
-        except VCSError:
-            log.error(traceback.format_exc())
-            log.error('Perhaps this repository is in db and not in '
-                      'filesystem run rescan repositories with '
-                      '"destroy old data " option from admin panel')
-            return
-
-        if alias == 'hg':
-
-            repo = backend(safe_str(repo_full_path), create=False,
-                           baseui=self._ui)
-        else:
-            repo = backend(repo_full_path, create=False)
-
-        return repo
-
-
-class Group(Base, BaseModel):
-    __tablename__ = 'groups'
-    __table_args__ = (UniqueConstraint('group_name', 'group_parent_id'),
-                      CheckConstraint('group_id != group_parent_id'), {'extend_existing':True},)
-    __mapper_args__ = {'order_by':'group_name'}
-
-    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    group_name = Column("group_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
-    group_description = Column("group_description", String(length=10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    parent_group = relationship('Group', remote_side=group_id)
-
-    def __init__(self, group_name='', parent_group=None):
-        self.group_name = group_name
-        self.parent_group = parent_group
-
-    def __repr__(self):
-        return "<%s('%s:%s')>" % (self.__class__.__name__, self.group_id,
-                                  self.group_name)
-
-    @classmethod
-    def groups_choices(cls):
-        from webhelpers.html import literal as _literal
-        repo_groups = [('', '')]
-        sep = ' &raquo; '
-        _name = lambda k: _literal(sep.join(k))
-
-        repo_groups.extend([(x.group_id, _name(x.full_path_splitted))
-                              for x in cls.query().all()])
-
-        repo_groups = sorted(repo_groups, key=lambda t: t[1].split(sep)[0])
-        return repo_groups
-
-    @classmethod
-    def url_sep(cls):
-        return '/'
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
-        if case_insensitive:
-            gr = cls.query()\
-                .filter(cls.group_name.ilike(group_name))
-        else:
-            gr = cls.query()\
-                .filter(cls.group_name == group_name)
-        if cache:
-            gr = gr.options(FromCache("sql_cache_short",
-                                          "get_group_%s" % group_name))
-        return gr.scalar()
-
-    @property
-    def parents(self):
-        parents_recursion_limit = 5
-        groups = []
-        if self.parent_group is None:
-            return groups
-        cur_gr = self.parent_group
-        groups.insert(0, cur_gr)
-        cnt = 0
-        while 1:
-            cnt += 1
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            if cnt == parents_recursion_limit:
-                # this will prevent accidental infinite loops
-                log.error('group nested more than %s',
-                          parents_recursion_limit)
-                break
-
-            groups.insert(0, gr)
-        return groups
-
-    @property
-    def children(self):
-        return Group.query().filter(Group.parent_group == self)
-
-    @property
-    def name(self):
-        return self.group_name.split(Group.url_sep())[-1]
-
-    @property
-    def full_path(self):
-        return self.group_name
-
-    @property
-    def full_path_splitted(self):
-        return self.group_name.split(Group.url_sep())
-
-    @property
-    def repositories(self):
-        return Repository.query().filter(Repository.group == self)
-
-    @property
-    def repositories_recursive_count(self):
-        cnt = self.repositories.count()
-
-        def children_count(group):
-            cnt = 0
-            for child in group.children:
-                cnt += child.repositories.count()
-                cnt += children_count(child)
-            return cnt
-
-        return cnt + children_count(self)
-
-
-    def get_new_name(self, group_name):
-        """
-        returns new full group name based on parent and new name
-
-        :param group_name:
-        """
-        path_prefix = (self.parent_group.full_path_splitted if
-                       self.parent_group else [])
-        return Group.url_sep().join(path_prefix + [group_name])
-
-
-class Permission(Base, BaseModel):
-    __tablename__ = 'permissions'
-    __table_args__ = {'extend_existing':True}
-    permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    permission_name = Column("permission_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    permission_longname = Column("permission_longname", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __repr__(self):
-        return "<%s('%s:%s')>" % (self.__class__.__name__,
-                                  self.permission_id, self.permission_name)
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.permission_name == key).scalar()
-
-class UserRepoToPerm(Base, BaseModel):
-    __tablename__ = 'repo_to_perm'
-    __table_args__ = (UniqueConstraint('user_id', 'repository_id'), {'extend_existing':True})
-    repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    permission = relationship('Permission')
-    repository = relationship('Repository')
-
-class UserToPerm(Base, BaseModel):
-    __tablename__ = 'user_to_perm'
-    __table_args__ = (UniqueConstraint('user_id', 'permission_id'), {'extend_existing':True})
-    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    permission = relationship('Permission')
-
-    @classmethod
-    def has_perm(cls, user_id, perm):
-        if not isinstance(perm, Permission):
-            raise Exception('perm needs to be an instance of Permission class')
-
-        return cls.query().filter(cls.user_id == user_id)\
-            .filter(cls.permission == perm).scalar() is not None
-
-    @classmethod
-    def grant_perm(cls, user_id, perm):
-        if not isinstance(perm, Permission):
-            raise Exception('perm needs to be an instance of Permission class')
-
-        new = cls()
-        new.user_id = user_id
-        new.permission = perm
-        try:
-            Session.add(new)
-            Session.commit()
-        except:
-            Session.rollback()
-
-
-    @classmethod
-    def revoke_perm(cls, user_id, perm):
-        if not isinstance(perm, Permission):
-            raise Exception('perm needs to be an instance of Permission class')
-
-        try:
-            cls.query().filter(cls.user_id == user_id) \
-                .filter(cls.permission == perm).delete()
-            Session.commit()
-        except:
-            Session.rollback()
-
-class UserGroupRepoToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_to_perm'
-    __table_args__ = (UniqueConstraint('repository_id', 'users_group_id', 'permission_id'), {'extend_existing':True})
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    repository = relationship('Repository')
-
-    def __repr__(self):
-        return '<userGroup:%s => %s >' % (self.users_group, self.repository)
-
-class UserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_to_perm'
-    __table_args__ = {'extend_existing':True}
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-
-    @classmethod
-    def has_perm(cls, users_group_id, perm):
-        if not isinstance(perm, Permission):
-            raise Exception('perm needs to be an instance of Permission class')
-
-        return cls.query().filter(cls.users_group_id ==
-                                         users_group_id)\
-                                         .filter(cls.permission == perm)\
-                                         .scalar() is not None
-
-    @classmethod
-    def grant_perm(cls, users_group_id, perm):
-        if not isinstance(perm, Permission):
-            raise Exception('perm needs to be an instance of Permission class')
-
-        new = cls()
-        new.users_group_id = users_group_id
-        new.permission = perm
-        try:
-            Session.add(new)
-            Session.commit()
-        except:
-            Session.rollback()
-
-
-    @classmethod
-    def revoke_perm(cls, users_group_id, perm):
-        if not isinstance(perm, Permission):
-            raise Exception('perm needs to be an instance of Permission class')
-
-        try:
-            cls.query().filter(cls.users_group_id == users_group_id) \
-                .filter(cls.permission == perm).delete()
-            Session.commit()
-        except:
-            Session.rollback()
-
-
-class UserRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'group_to_perm'
-    __table_args__ = (UniqueConstraint('group_id', 'permission_id'), {'extend_existing':True})
-
-    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    permission = relationship('Permission')
-    group = relationship('RepoGroup')
-
-class Statistics(Base, BaseModel):
-    __tablename__ = 'statistics'
-    __table_args__ = (UniqueConstraint('repository_id'), {'extend_existing':True})
-    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
-    stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
-    commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
-    commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
-    languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
-
-    repository = relationship('Repository', single_parent=True)
-
-class UserFollowing(Base, BaseModel):
-    __tablename__ = 'user_followings'
-    __table_args__ = (UniqueConstraint('user_id', 'follows_repository_id'),
-                      UniqueConstraint('user_id', 'follows_user_id')
-                      , {'extend_existing':True})
-
-    user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-
-    user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
-
-    follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relationship('Repository', order_by='Repository.repo_name')
-
-
-    @classmethod
-    def get_repo_followers(cls, repo_id):
-        return cls.query().filter(cls.follows_repo_id == repo_id)
-
-class CacheInvalidation(Base, BaseModel):
-    __tablename__ = 'cache_invalidation'
-    __table_args__ = (UniqueConstraint('cache_key'), {'extend_existing':True})
-    cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    cache_key = Column("cache_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    cache_args = Column("cache_args", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
-
-
-    def __init__(self, cache_key, cache_args=''):
-        self.cache_key = cache_key
-        self.cache_args = cache_args
-        self.cache_active = False
-
-    def __repr__(self):
-        return "<%s('%s:%s')>" % (self.__class__.__name__,
-                                  self.cache_id, self.cache_key)
-
-    @classmethod
-    def invalidate(cls, key):
-        """
-        Returns Invalidation object if this given key should be invalidated
-        None otherwise. `cache_active = False` means that this cache
-        state is not valid and needs to be invalidated
-
-        :param key:
-        """
-        return cls.query()\
-                .filter(CacheInvalidation.cache_key == key)\
-                .filter(CacheInvalidation.cache_active == False)\
-                .scalar()
-
-    @classmethod
-    def set_invalidate(cls, key):
-        """
-        Mark this Cache key for invalidation
-
-        :param key:
-        """
-
-        log.debug('marking %s for invalidation', key)
-        inv_obj = Session.query(cls)\
-            .filter(cls.cache_key == key).scalar()
-        if inv_obj:
-            inv_obj.cache_active = False
-        else:
-            log.debug('cache key not found in invalidation db -> creating one')
-            inv_obj = CacheInvalidation(key)
-
-        try:
-            Session.add(inv_obj)
-            Session.commit()
-        except Exception:
-            log.error(traceback.format_exc())
-            Session.rollback()
-
-    @classmethod
-    def set_valid(cls, key):
-        """
-        Mark this cache key as active and currently cached
-
-        :param key:
-        """
-        inv_obj = Session.query(CacheInvalidation)\
-            .filter(CacheInvalidation.cache_key == key).scalar()
-        inv_obj.cache_active = True
-        Session.add(inv_obj)
-        Session.commit()
-
-class DbMigrateVersion(Base, BaseModel):
-    __tablename__ = 'db_migrate_version'
-    __table_args__ = {'extend_existing':True}
-    repository_id = Column('repository_id', String(250), primary_key=True)
-    repository_path = Column('repository_path', Text)
-    version = Column('version', Integer)
--- a/kallithea/lib/dbmigrate/schema/db_1_3_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1322 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate.schema.db_1_3_0
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Database Models for Kallithea <=1.3.X
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Apr 08, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-
-"""
-
-
-import os
-import logging
-import datetime
-import traceback
-from collections import defaultdict
-
-from sqlalchemy import *
-from sqlalchemy.ext.hybrid import hybrid_property
-from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
-from beaker.cache import cache_region, region_invalidate
-
-from kallithea.lib.vcs import get_backend
-from kallithea.lib.vcs.utils.helpers import get_scm
-from kallithea.lib.vcs.exceptions import VCSError
-from kallithea.lib.vcs.utils.lazy import LazyProperty
-
-from kallithea.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
-    safe_unicode
-from kallithea.lib.compat import json
-from kallithea.lib.caching_query import FromCache
-
-from kallithea.model.meta import Base, Session
-import hashlib
-
-from kallithea import DB_PREFIX
-
-log = logging.getLogger(__name__)
-
-#==============================================================================
-# BASE CLASSES
-#==============================================================================
-
-_hash_key = lambda k: hashlib.md5(safe_str(k)).hexdigest()
-
-
-class ModelSerializer(json.JSONEncoder):
-    """
-    Simple Serializer for JSON,
-
-    usage::
-
-        to make object customized for serialization implement a __json__
-        method that will return a dict for serialization into json
-
-    example::
-
-        class Task(object):
-
-            def __init__(self, name, value):
-                self.name = name
-                self.value = value
-
-            def __json__(self):
-                return dict(name=self.name,
-                            value=self.value)
-
-    """
-
-    def default(self, obj):
-
-        if hasattr(obj, '__json__'):
-            return obj.__json__()
-        else:
-            return json.JSONEncoder.default(self, obj)
-
-
-class BaseModel(object):
-    """
-    Base Model for all classess
-    """
-
-    @classmethod
-    def _get_keys(cls):
-        """return column names for this model """
-        return class_mapper(cls).c.keys()
-
-    def get_dict(self):
-        """
-        return dict with keys and values corresponding
-        to this model data """
-
-        d = {}
-        for k in self._get_keys():
-            d[k] = getattr(self, k)
-
-        # also use __json__() if present to get additional fields
-        for k, val in getattr(self, '__json__', lambda: {})().iteritems():
-            d[k] = val
-        return d
-
-    def get_appstruct(self):
-        """return list with keys and values tuples corresponding
-        to this model data """
-
-        l = []
-        for k in self._get_keys():
-            l.append((k, getattr(self, k),))
-        return l
-
-    def populate_obj(self, populate_dict):
-        """populate model with data from given populate_dict"""
-
-        for k in self._get_keys():
-            if k in populate_dict:
-                setattr(self, k, populate_dict[k])
-
-    @classmethod
-    def query(cls):
-        return Session.query(cls)
-
-    @classmethod
-    def get(cls, id_):
-        if id_:
-            return cls.query().get(id_)
-
-    @classmethod
-    def getAll(cls):
-        return cls.query().all()
-
-    @classmethod
-    def delete(cls, id_):
-        obj = cls.query().get(id_)
-        Session.delete(obj)
-
-    def __repr__(self):
-        if hasattr(self, '__unicode__'):
-            # python repr needs to return str
-            return safe_str(self.__unicode__())
-        return '<DB:%s>' % (self.__class__.__name__)
-
-class Setting(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'settings'
-    __table_args__ = (
-        UniqueConstraint('app_settings_name'),
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    app_settings_name = Column("app_settings_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_value = Column("app_settings_value", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __init__(self, k='', v=''):
-        self.app_settings_name = k
-        self.app_settings_value = v
-
-    @validates('_app_settings_value')
-    def validate_settings_value(self, key, val):
-        assert type(val) == unicode
-        return val
-
-    @hybrid_property
-    def app_settings_value(self):
-        v = self._app_settings_value
-        if self.app_settings_name == 'ldap_active':
-            v = str2bool(v)
-        return v
-
-    @app_settings_value.setter
-    def app_settings_value(self, val):
-        """
-        Setter that will always make sure we use unicode in app_settings_value
-
-        :param val:
-        """
-        self._app_settings_value = safe_unicode(val)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.app_settings_name, self.app_settings_value
-        )
-
-    @classmethod
-    def get_by_name(cls, ldap_key):
-        return cls.query()\
-            .filter(cls.app_settings_name == ldap_key).scalar()
-
-    @classmethod
-    def get_app_settings(cls, cache=False):
-
-        ret = cls.query()
-
-        if cache:
-            ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
-
-        if not ret:
-            raise Exception('Could not get application settings !')
-        settings = {}
-        for each in ret:
-            settings[each.app_settings_name] = \
-                each.app_settings_value
-
-        return settings
-
-    @classmethod
-    def get_ldap_settings(cls, cache=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('ldap_')).all()
-        fd = {}
-        for row in ret:
-            fd.update({row.app_settings_name:row.app_settings_value})
-
-        return fd
-
-
-class Ui(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'ui'
-    __table_args__ = (
-        UniqueConstraint('ui_key'),
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    HOOK_UPDATE = 'changegroup.update'
-    HOOK_REPO_SIZE = 'changegroup.repo_size'
-    HOOK_PUSH = 'pretxnchangegroup.push_logger'
-    HOOK_PULL = 'preoutgoing.pull_logger'
-
-    ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    ui_section = Column("ui_section", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_key = Column("ui_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_value = Column("ui_value", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.ui_key == key)
-
-    @classmethod
-    def get_builtin_hooks(cls):
-        q = cls.query()
-        q = q.filter(cls.ui_key.in_([cls.HOOK_UPDATE,
-                                    cls.HOOK_REPO_SIZE,
-                                    cls.HOOK_PUSH, cls.HOOK_PULL]))
-        return q.all()
-
-    @classmethod
-    def get_custom_hooks(cls):
-        q = cls.query()
-        q = q.filter(~cls.ui_key.in_([cls.HOOK_UPDATE,
-                                    cls.HOOK_REPO_SIZE,
-                                    cls.HOOK_PUSH, cls.HOOK_PULL]))
-        q = q.filter(cls.ui_section == 'hooks')
-        return q.all()
-
-    @classmethod
-    def create_or_update_hook(cls, key, val):
-        new_ui = cls.get_by_key(key).scalar() or cls()
-        new_ui.ui_section = 'hooks'
-        new_ui.ui_active = True
-        new_ui.ui_key = key
-        new_ui.ui_value = val
-
-        Session.add(new_ui)
-
-
-class User(Base, BaseModel):
-    __tablename__ = 'users'
-    __table_args__ = (
-        UniqueConstraint('username'), UniqueConstraint('email'),
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    username = Column("username", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    password = Column("password", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=None)
-    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
-    name = Column("name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    lastname = Column("lastname", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _email = Column("email", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
-    ldap_dn = Column("ldap_dn", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    api_key = Column("api_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    user_log = relationship('UserLog', cascade='all')
-    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
-
-    repositories = relationship('Repository')
-    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
-    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
-
-    group_member = relationship('UserGroupMember', cascade='all')
-
-    notifications = relationship('UserNotification', cascade='all')
-    # notifications assigned to this user
-    user_created_notifications = relationship('Notification', cascade='all')
-    # comments created by this user
-    user_comments = relationship('ChangesetComment', cascade='all')
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-    @property
-    def full_name(self):
-        return '%s %s' % (self.name, self.lastname)
-
-    @property
-    def full_name_or_username(self):
-        return ('%s %s' % (self.name, self.lastname)
-                if (self.name and self.lastname) else self.username)
-
-    @property
-    def full_contact(self):
-        return '%s %s <%s>' % (self.name, self.lastname, self.email)
-
-    @property
-    def short_contact(self):
-        return '%s %s' % (self.name, self.lastname)
-
-    @property
-    def is_admin(self):
-        return self.admin
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                     self.user_id, self.username)
-
-    @classmethod
-    def get_by_username(cls, username, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.username.ilike(username))
-        else:
-            q = cls.query().filter(cls.username == username)
-
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(username)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get_by_api_key(cls, api_key, cache=False):
-        q = cls.query().filter(cls.api_key == api_key)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_api_key_%s" % api_key))
-        return q.scalar()
-
-    @classmethod
-    def get_by_email(cls, email, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.email.ilike(email))
-        else:
-            q = cls.query().filter(cls.email == email)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_api_key_%s" % email))
-        return q.scalar()
-
-    def update_lastlogin(self):
-        """Update user lastlogin"""
-        self.last_login = datetime.datetime.now()
-        Session.add(self)
-        log.debug('updated user %s lastlogin', self.username)
-
-    def __json__(self):
-        return dict(
-            user_id=self.user_id,
-            first_name=self.name,
-            last_name=self.lastname,
-            email=self.email,
-            full_name=self.full_name,
-            full_name_or_username=self.full_name_or_username,
-            short_contact=self.short_contact,
-            full_contact=self.full_contact
-        )
-
-
-class UserLog(Base, BaseModel):
-    __tablename__ = 'user_logs'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
-    repository_name = Column("repository_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    user_ip = Column("user_ip", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action = Column("action", UnicodeText(length=1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
-
-    @property
-    def action_as_day(self):
-        return datetime.date(*self.action_date.timetuple()[:3])
-
-    user = relationship('User')
-    repository = relationship('Repository', cascade='')
-
-
-class UserGroup(Base, BaseModel):
-    __tablename__ = 'users_groups'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_name = Column("users_group_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
-
-    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
-    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
-    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-
-    def __unicode__(self):
-        return u'<userGroup(%s)>' % (self.users_group_name)
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False,
-                          case_insensitive=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.users_group_name.ilike(group_name))
-        else:
-            q = cls.query().filter(cls.users_group_name == group_name)
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(group_name)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get(cls, users_group_id, cache=False):
-        users_group = cls.query()
-        if cache:
-            users_group = users_group.options(FromCache("sql_cache_short",
-                                    "get_users_group_%s" % users_group_id))
-        return users_group.get(users_group_id)
-
-
-class UserGroupMember(Base, BaseModel):
-    __tablename__ = 'users_groups_members'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User', lazy='joined')
-    users_group = relationship('UserGroup')
-
-    def __init__(self, gr_id='', u_id=''):
-        self.users_group_id = gr_id
-        self.user_id = u_id
-
-
-class Repository(Base, BaseModel):
-    __tablename__ = 'repositories'
-    __table_args__ = (
-        UniqueConstraint('repo_name'),
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repo_name = Column("repo_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    clone_uri = Column("clone_uri", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    repo_type = Column("repo_type", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default='hg')
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
-    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
-    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
-    description = Column("description", String(length=10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-
-    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
-
-    user = relationship('User')
-    fork = relationship('Repository', remote_side=repo_id)
-    group = relationship('RepoGroup')
-    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    stats = relationship('Statistics', cascade='all', uselist=False)
-
-    followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', cascade='all')
-
-    logs = relationship('UserLog')
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__,self.repo_id,
-                                   self.repo_name)
-
-    @classmethod
-    def url_sep(cls):
-        return '/'
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        q = Session.query(cls).filter(cls.repo_name == repo_name)
-        q = q.options(joinedload(Repository.fork))\
-                .options(joinedload(Repository.user))\
-                .options(joinedload(Repository.group))
-        return q.scalar()
-
-    @classmethod
-    def get_repo_forks(cls, repo_id):
-        return cls.query().filter(Repository.fork_id == repo_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all repos are stored
-
-        :param cls:
-        """
-        q = Session.query(Ui)\
-            .filter(Ui.ui_key == cls.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def just_name(self):
-        return self.repo_name.split(Repository.url_sep())[-1]
-
-    @property
-    def groups_with_parents(self):
-        groups = []
-        if self.group is None:
-            return groups
-
-        cur_gr = self.group
-        groups.insert(0, cur_gr)
-        while 1:
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            groups.insert(0, gr)
-
-        return groups
-
-    @property
-    def groups_and_repo(self):
-        return self.groups_with_parents, self.just_name
-
-    @LazyProperty
-    def repo_path(self):
-        """
-        Returns base full path for that repository means where it actually
-        exists on a filesystem
-        """
-        q = Session.query(Ui).filter(Ui.ui_key ==
-                                              Repository.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def repo_full_path(self):
-        p = [self.repo_path]
-        # we need to split the name by / since this is how we store the
-        # names in the database, but that eventually needs to be converted
-        # into a valid system path
-        p += self.repo_name.split(Repository.url_sep())
-        return os.path.join(*p)
-
-    def get_new_name(self, repo_name):
-        """
-        returns new full repository name based on assigned group and new new
-
-        :param group_name:
-        """
-        path_prefix = self.group.full_path_splitted if self.group else []
-        return Repository.url_sep().join(path_prefix + [repo_name])
-
-    @property
-    def _ui(self):
-        """
-        Creates an db based ui object for this repository
-        """
-        from mercurial import ui
-        from mercurial import config
-        baseui = ui.ui()
-
-        #clean the baseui object
-        baseui._ocfg = config.config()
-        baseui._ucfg = config.config()
-        baseui._tcfg = config.config()
-
-        ret = Ui.query()\
-            .options(FromCache("sql_cache_short", "repository_repo_ui")).all()
-
-        hg_ui = ret
-        for ui_ in hg_ui:
-            if ui_.ui_active:
-                log.debug('settings ui from db: [%s] %s=%s', ui_.ui_section,
-                          ui_.ui_key, ui_.ui_value)
-                baseui.setconfig(ui_.ui_section, ui_.ui_key, ui_.ui_value)
-
-        return baseui
-
-    @classmethod
-    def is_valid(cls, repo_name):
-        """
-        returns True if given repo name is a valid filesystem repository
-
-        :param cls:
-        :param repo_name:
-        """
-        from kallithea.lib.utils import is_valid_repo
-
-        return is_valid_repo(repo_name, cls.base_path())
-
-    #==========================================================================
-    # SCM PROPERTIES
-    #==========================================================================
-
-    def get_changeset(self, rev):
-        return get_changeset_safe(self.scm_instance, rev)
-
-    @property
-    def tip(self):
-        return self.get_changeset('tip')
-
-    @property
-    def author(self):
-        return self.tip.author
-
-    @property
-    def last_change(self):
-        return self.scm_instance.last_change
-
-    def comments(self, revisions=None):
-        """
-        Returns comments for this repository grouped by revisions
-
-        :param revisions: filter query by revisions only
-        """
-        cmts = ChangesetComment.query()\
-            .filter(ChangesetComment.repo == self)
-        if revisions:
-            cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
-        grouped = defaultdict(list)
-        for cmt in cmts.all():
-            grouped[cmt.revision].append(cmt)
-        return grouped
-
-    #==========================================================================
-    # SCM CACHE INSTANCE
-    #==========================================================================
-
-    @property
-    def invalidate(self):
-        return CacheInvalidation.invalidate(self.repo_name)
-
-    def set_invalidate(self):
-        """
-        set a cache for invalidation for this instance
-        """
-        CacheInvalidation.set_invalidate(self.repo_name)
-
-    @LazyProperty
-    def scm_instance(self):
-        return self.__get_instance()
-
-    @property
-    def scm_instance_cached(self):
-        @cache_region('long_term')
-        def _c(repo_name):
-            return self.__get_instance()
-        rn = self.repo_name
-        log.debug('Getting cached instance of repo')
-        inv = self.invalidate
-        if inv is not None:
-            region_invalidate(_c, None, rn)
-            # update our cache
-            CacheInvalidation.set_valid(inv.cache_key)
-        return _c(rn)
-
-    def __get_instance(self):
-        repo_full_path = self.repo_full_path
-        try:
-            alias = get_scm(repo_full_path)[0]
-            log.debug('Creating instance of %s repository', alias)
-            backend = get_backend(alias)
-        except VCSError:
-            log.error(traceback.format_exc())
-            log.error('Perhaps this repository is in db and not in '
-                      'filesystem run rescan repositories with '
-                      '"destroy old data " option from admin panel')
-            return
-
-        if alias == 'hg':
-
-            repo = backend(safe_str(repo_full_path), create=False,
-                           baseui=self._ui)
-        else:
-            repo = backend(repo_full_path, create=False)
-
-        return repo
-
-
-class RepoGroup(Base, BaseModel):
-    __tablename__ = 'groups'
-    __table_args__ = (
-        UniqueConstraint('group_name', 'group_parent_id'),
-        CheckConstraint('group_id != group_parent_id'),
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    __mapper_args__ = {'order_by': 'group_name'}
-
-    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    group_name = Column("group_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
-    group_description = Column("group_description", String(length=10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-
-    parent_group = relationship('RepoGroup', remote_side=group_id)
-
-    def __init__(self, group_name='', parent_group=None):
-        self.group_name = group_name
-        self.parent_group = parent_group
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.group_id,
-                                  self.group_name)
-
-    @classmethod
-    def groups_choices(cls):
-        from webhelpers.html import literal as _literal
-        repo_groups = [('', '')]
-        sep = ' &raquo; '
-        _name = lambda k: _literal(sep.join(k))
-
-        repo_groups.extend([(x.group_id, _name(x.full_path_splitted))
-                              for x in cls.query().all()])
-
-        repo_groups = sorted(repo_groups, key=lambda t: t[1].split(sep)[0])
-        return repo_groups
-
-    @classmethod
-    def url_sep(cls):
-        return '/'
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
-        if case_insensitive:
-            gr = cls.query()\
-                .filter(cls.group_name.ilike(group_name))
-        else:
-            gr = cls.query()\
-                .filter(cls.group_name == group_name)
-        if cache:
-            gr = gr.options(FromCache(
-                            "sql_cache_short",
-                            "get_group_%s" % _hash_key(group_name)
-                            )
-            )
-        return gr.scalar()
-
-    @property
-    def parents(self):
-        parents_recursion_limit = 5
-        groups = []
-        if self.parent_group is None:
-            return groups
-        cur_gr = self.parent_group
-        groups.insert(0, cur_gr)
-        cnt = 0
-        while 1:
-            cnt += 1
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            if cnt == parents_recursion_limit:
-                # this will prevent accidental infinite loops
-                log.error('group nested more than %s',
-                          parents_recursion_limit)
-                break
-
-            groups.insert(0, gr)
-        return groups
-
-    @property
-    def children(self):
-        return RepoGroup.query().filter(RepoGroup.parent_group == self)
-
-    @property
-    def name(self):
-        return self.group_name.split(RepoGroup.url_sep())[-1]
-
-    @property
-    def full_path(self):
-        return self.group_name
-
-    @property
-    def full_path_splitted(self):
-        return self.group_name.split(RepoGroup.url_sep())
-
-    @property
-    def repositories(self):
-        return Repository.query()\
-                .filter(Repository.group == self)\
-                .order_by(Repository.repo_name)
-
-    @property
-    def repositories_recursive_count(self):
-        cnt = self.repositories.count()
-
-        def children_count(group):
-            cnt = 0
-            for child in group.children:
-                cnt += child.repositories.count()
-                cnt += children_count(child)
-            return cnt
-
-        return cnt + children_count(self)
-
-    def get_new_name(self, group_name):
-        """
-        returns new full group name based on parent and new name
-
-        :param group_name:
-        """
-        path_prefix = (self.parent_group.full_path_splitted if
-                       self.parent_group else [])
-        return RepoGroup.url_sep().join(path_prefix + [group_name])
-
-
-class Permission(Base, BaseModel):
-    __tablename__ = 'permissions'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    permission_name = Column("permission_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    permission_longname = Column("permission_longname", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__, self.permission_id, self.permission_name
-        )
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.permission_name == key).scalar()
-
-    @classmethod
-    def get_default_perms(cls, default_user_id):
-        q = Session.query(UserRepoToPerm, Repository, cls)\
-         .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
-         .join((cls, UserRepoToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_group_perms(cls, default_user_id):
-        q = Session.query(UserRepoGroupToPerm, RepoGroup, cls)\
-         .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
-         .join((cls, UserRepoGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-
-class UserRepoToPerm(Base, BaseModel):
-    __tablename__ = 'repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'repository_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    repository = relationship('Repository')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, repository, permission):
-        n = cls()
-        n.user = user
-        n.repository = repository
-        n.permission = permission
-        Session.add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<user:%s => %s >' % (self.user, self.repository)
-
-
-class UserToPerm(Base, BaseModel):
-    __tablename__ = 'user_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    permission = relationship('Permission', lazy='joined')
-
-
-class UserGroupRepoToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    repository = relationship('Repository')
-
-    @classmethod
-    def create(cls, users_group, repository, permission):
-        n = cls()
-        n.users_group = users_group
-        n.repository = repository
-        n.permission = permission
-        Session.add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<userGroup:%s => %s >' % (self.users_group, self.repository)
-
-
-class UserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'permission_id',),
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-
-class UserRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    group = relationship('RepoGroup')
-    permission = relationship('Permission')
-
-
-class UserGroupRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'group_id'),
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    group = relationship('RepoGroup')
-
-
-class Statistics(Base, BaseModel):
-    __tablename__ = 'statistics'
-    __table_args__ = (
-         UniqueConstraint('repository_id'),
-         {'extend_existing': True, 'mysql_engine':'InnoDB',
-          'mysql_charset': 'utf8'}
-    )
-    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
-    stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
-    commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
-    commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
-    languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
-
-    repository = relationship('Repository', single_parent=True)
-
-
-class UserFollowing(Base, BaseModel):
-    __tablename__ = 'user_followings'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'follows_repository_id'),
-        UniqueConstraint('user_id', 'follows_user_id'),
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-
-    user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
-
-    follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relationship('Repository', order_by='Repository.repo_name')
-
-    @classmethod
-    def get_repo_followers(cls, repo_id):
-        return cls.query().filter(cls.follows_repo_id == repo_id)
-
-
-class CacheInvalidation(Base, BaseModel):
-    __tablename__ = 'cache_invalidation'
-    __table_args__ = (
-        UniqueConstraint('cache_key'),
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    cache_key = Column("cache_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    cache_args = Column("cache_args", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
-
-    def __init__(self, cache_key, cache_args=''):
-        self.cache_key = cache_key
-        self.cache_args = cache_args
-        self.cache_active = False
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__,
-                                  self.cache_id, self.cache_key)
-    @classmethod
-    def clear_cache(cls):
-        cls.query().delete()
-
-    @classmethod
-    def _get_key(cls, key):
-        """
-        Wrapper for generating a key, together with a prefix
-
-        :param key:
-        """
-        import kallithea
-        prefix = ''
-        iid = kallithea.CONFIG.get('instance_id')
-        if iid:
-            prefix = iid
-        return "%s%s" % (prefix, key), prefix, key.rstrip('_README')
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.cache_key == key).scalar()
-
-    @classmethod
-    def _get_or_create_key(cls, key, prefix, org_key):
-        inv_obj = Session.query(cls).filter(cls.cache_key == key).scalar()
-        if not inv_obj:
-            try:
-                inv_obj = CacheInvalidation(key, org_key)
-                Session.add(inv_obj)
-                Session.commit()
-            except Exception:
-                log.error(traceback.format_exc())
-                Session.rollback()
-        return inv_obj
-
-    @classmethod
-    def invalidate(cls, key):
-        """
-        Returns Invalidation object if this given key should be invalidated
-        None otherwise. `cache_active = False` means that this cache
-        state is not valid and needs to be invalidated
-
-        :param key:
-        """
-
-        key, _prefix, _org_key = cls._get_key(key)
-        inv = cls._get_or_create_key(key, _prefix, _org_key)
-
-        if inv and inv.cache_active is False:
-            return inv
-
-    @classmethod
-    def set_invalidate(cls, key):
-        """
-        Mark this Cache key for invalidation
-
-        :param key:
-        """
-
-        key, _prefix, _org_key = cls._get_key(key)
-        inv_objs = Session.query(cls).filter(cls.cache_args == _org_key).all()
-        log.debug('marking %s key[s] %s for invalidation', len(inv_objs),
-                                                             _org_key)
-        try:
-            for inv_obj in inv_objs:
-                if inv_obj:
-                    inv_obj.cache_active = False
-
-                Session.add(inv_obj)
-            Session.commit()
-        except Exception:
-            log.error(traceback.format_exc())
-            Session.rollback()
-
-    @classmethod
-    def set_valid(cls, key):
-        """
-        Mark this cache key as active and currently cached
-
-        :param key:
-        """
-        inv_obj = cls.get_by_key(key)
-        inv_obj.cache_active = True
-        Session.add(inv_obj)
-        Session.commit()
-
-
-class ChangesetComment(Base, BaseModel):
-    __tablename__ = 'changeset_comments'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    revision = Column('revision', String(40), nullable=False)
-    line_no = Column('line_no', Unicode(10), nullable=True)
-    f_path = Column('f_path', Unicode(1000), nullable=True)
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
-    text = Column('text', Unicode(25000), nullable=False)
-    modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-
-    @classmethod
-    def get_users(cls, revision):
-        """
-        Returns user associated with this changesetComment. ie those
-        who actually commented
-
-        :param cls:
-        :param revision:
-        """
-        return Session.query(User)\
-                .filter(cls.revision == revision)\
-                .join(ChangesetComment.author).all()
-
-
-class Notification(Base, BaseModel):
-    __tablename__ = 'notifications'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    TYPE_CHANGESET_COMMENT = u'cs_comment'
-    TYPE_MESSAGE = u'message'
-    TYPE_MENTION = u'mention'
-    TYPE_REGISTRATION = u'registration'
-
-    notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
-    subject = Column('subject', Unicode(512), nullable=True)
-    body = Column('body', Unicode(50000), nullable=True)
-    created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    type_ = Column('type', Unicode(256))
-
-    created_by_user = relationship('User')
-    notifications_to_users = relationship('UserNotification', lazy='joined',
-                                          cascade="all, delete, delete-orphan")
-
-    @property
-    def recipients(self):
-        return [x.user for x in UserNotification.query()\
-                .filter(UserNotification.notification == self).all()]
-
-    @classmethod
-    def create(cls, created_by, subject, body, recipients, type_=None):
-        if type_ is None:
-            type_ = Notification.TYPE_MESSAGE
-
-        notification = cls()
-        notification.created_by_user = created_by
-        notification.subject = subject
-        notification.body = body
-        notification.type_ = type_
-        notification.created_on = datetime.datetime.now()
-
-        for u in recipients:
-            assoc = UserNotification()
-            assoc.notification = notification
-            u.notifications.append(assoc)
-        Session.add(notification)
-        return notification
-
-    @property
-    def description(self):
-        from kallithea.model.notification import NotificationModel
-        return NotificationModel().make_description(self)
-
-
-class UserNotification(Base, BaseModel):
-    __tablename__ = 'user_to_notification'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'notification_id'),
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
-    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
-    read = Column('read', Boolean, default=False)
-    sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
-
-    user = relationship('User', lazy="joined")
-    notification = relationship('Notification', lazy="joined",
-                                order_by=lambda: Notification.created_on.desc(),)
-
-    def mark_as_read(self):
-        self.read = True
-        Session.add(self)
-
-
-class DbMigrateVersion(Base, BaseModel):
-    __tablename__ = 'db_migrate_version'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine':'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    repository_id = Column('repository_id', String(250), primary_key=True)
-    repository_path = Column('repository_path', Text)
-    version = Column('version', Integer)
-
-## this is migration from 1_4_0, but now it's here to overcome a problem of
-## attaching a FK to this from 1_3_0 !
-
-
-class PullRequest(Base, BaseModel):
-    __tablename__ = 'pull_requests'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    STATUS_NEW = u'new'
-    STATUS_OPEN = u'open'
-    STATUS_CLOSED = u'closed'
-
-    pull_request_id = Column('pull_request_id', Integer(), nullable=False, primary_key=True)
-    title = Column('title', Unicode(256), nullable=True)
-    description = Column('description', UnicodeText(10240), nullable=True)
-    status = Column('status', Unicode(256), nullable=False, default=STATUS_NEW)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    _revisions = Column('revisions', UnicodeText(20500))  # 500 revisions max
-    org_repo_id = Column('org_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    org_ref = Column('org_ref', Unicode(256), nullable=False)
-    other_repo_id = Column('other_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    other_ref = Column('other_ref', Unicode(256), nullable=False)
--- a/kallithea/lib/dbmigrate/schema/db_1_4_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1814 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate.schema.db_1_4_0
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Database Models for Kallithea <=1.4.X
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Apr 08, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-
-import os
-import logging
-import datetime
-import traceback
-import hashlib
-import time
-from collections import defaultdict
-
-from sqlalchemy import *
-from sqlalchemy.ext.hybrid import hybrid_property
-from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
-from beaker.cache import cache_region, region_invalidate
-from webob.exc import HTTPNotFound
-
-from pylons.i18n.translation import lazy_ugettext as _
-
-from kallithea.lib.vcs import get_backend
-from kallithea.lib.vcs.utils.helpers import get_scm
-from kallithea.lib.vcs.exceptions import VCSError
-from kallithea.lib.vcs.utils.lazy import LazyProperty
-
-from kallithea.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
-    safe_unicode, remove_suffix
-from kallithea.lib.caching_query import FromCache
-
-from kallithea.model.meta import Base, Session
-
-from kallithea import DB_PREFIX
-
-URL_SEP = '/'
-log = logging.getLogger(__name__)
-
-#==============================================================================
-# BASE CLASSES
-#==============================================================================
-
-_hash_key = lambda k: hashlib.md5(safe_str(k)).hexdigest()
-
-
-class BaseModel(object):
-    """
-    Base Model for all classess
-    """
-
-    @classmethod
-    def _get_keys(cls):
-        """return column names for this model """
-        return class_mapper(cls).c.keys()
-
-    def get_dict(self):
-        """
-        return dict with keys and values corresponding
-        to this model data """
-
-        d = {}
-        for k in self._get_keys():
-            d[k] = getattr(self, k)
-
-        # also use __json__() if present to get additional fields
-        _json_attr = getattr(self, '__json__', None)
-        if _json_attr:
-            # update with attributes from __json__
-            if callable(_json_attr):
-                _json_attr = _json_attr()
-            for k, val in _json_attr.iteritems():
-                d[k] = val
-        return d
-
-    def get_appstruct(self):
-        """return list with keys and values tuples corresponding
-        to this model data """
-
-        l = []
-        for k in self._get_keys():
-            l.append((k, getattr(self, k),))
-        return l
-
-    def populate_obj(self, populate_dict):
-        """populate model with data from given populate_dict"""
-
-        for k in self._get_keys():
-            if k in populate_dict:
-                setattr(self, k, populate_dict[k])
-
-    @classmethod
-    def query(cls):
-        return Session().query(cls)
-
-    @classmethod
-    def get(cls, id_):
-        if id_:
-            return cls.query().get(id_)
-
-    @classmethod
-    def get_or_404(cls, id_):
-        try:
-            id_ = int(id_)
-        except (TypeError, ValueError):
-            raise HTTPNotFound
-
-        res = cls.query().get(id_)
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def getAll(cls):
-        return cls.query().all()
-
-    @classmethod
-    def delete(cls, id_):
-        obj = cls.query().get(id_)
-        Session().delete(obj)
-
-    def __repr__(self):
-        if hasattr(self, '__unicode__'):
-            # python repr needs to return str
-            return safe_str(self.__unicode__())
-        return '<DB:%s>' % (self.__class__.__name__)
-
-
-class Setting(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'settings'
-    __table_args__ = (
-        UniqueConstraint('app_settings_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    app_settings_name = Column("app_settings_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_value = Column("app_settings_value", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __init__(self, k='', v=''):
-        self.app_settings_name = k
-        self.app_settings_value = v
-
-    @validates('_app_settings_value')
-    def validate_settings_value(self, key, val):
-        assert type(val) == unicode
-        return val
-
-    @hybrid_property
-    def app_settings_value(self):
-        v = self._app_settings_value
-        if self.app_settings_name == 'ldap_active':
-            v = str2bool(v)
-        return v
-
-    @app_settings_value.setter
-    def app_settings_value(self, val):
-        """
-        Setter that will always make sure we use unicode in app_settings_value
-
-        :param val:
-        """
-        self._app_settings_value = safe_unicode(val)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.app_settings_name, self.app_settings_value
-        )
-
-    @classmethod
-    def get_by_name(cls, key):
-        return cls.query()\
-            .filter(cls.app_settings_name == key).scalar()
-
-    @classmethod
-    def get_by_name_or_create(cls, key):
-        res = cls.get_by_name(key)
-        if not res:
-            res = cls(key)
-        return res
-
-    @classmethod
-    def get_app_settings(cls, cache=False):
-
-        ret = cls.query()
-
-        if cache:
-            ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
-
-        if not ret:
-            raise Exception('Could not get application settings !')
-        settings = {}
-        for each in ret:
-            settings[each.app_settings_name] = \
-                each.app_settings_value
-
-        return settings
-
-    @classmethod
-    def get_ldap_settings(cls, cache=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('ldap_')).all()
-        fd = {}
-        for row in ret:
-            fd.update({row.app_settings_name: row.app_settings_value})
-
-        return fd
-
-
-class Ui(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'ui'
-    __table_args__ = (
-        UniqueConstraint('ui_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    HOOK_UPDATE = 'changegroup.update'
-    HOOK_REPO_SIZE = 'changegroup.repo_size'
-    HOOK_PUSH = 'changegroup.push_logger'
-    HOOK_PRE_PUSH = 'prechangegroup.pre_push'
-    HOOK_PULL = 'outgoing.pull_logger'
-    HOOK_PRE_PULL = 'preoutgoing.pre_pull'
-
-    ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    ui_section = Column("ui_section", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_key = Column("ui_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_value = Column("ui_value", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.ui_key == key).scalar()
-
-    @classmethod
-    def get_builtin_hooks(cls):
-        q = cls.query()
-        q = q.filter(cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                     cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                     cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        return q.all()
-
-    @classmethod
-    def get_custom_hooks(cls):
-        q = cls.query()
-        q = q.filter(~cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                      cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                      cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        q = q.filter(cls.ui_section == 'hooks')
-        return q.all()
-
-    @classmethod
-    def get_repos_location(cls):
-        return cls.get_by_key('/').ui_value
-
-    @classmethod
-    def create_or_update_hook(cls, key, val):
-        new_ui = cls.get_by_key(key) or cls()
-        new_ui.ui_section = 'hooks'
-        new_ui.ui_active = True
-        new_ui.ui_key = key
-        new_ui.ui_value = val
-
-        Session().add(new_ui)
-
-    def __repr__(self):
-        return '<DB:%s[%s:%s]>' % (self.__class__.__name__, self.ui_key,
-                                   self.ui_value)
-
-
-class User(Base, BaseModel):
-    __tablename__ = 'users'
-    __table_args__ = (
-        UniqueConstraint('username'), UniqueConstraint('email'),
-        Index('u_username_idx', 'username'),
-        Index('u_email_idx', 'email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    DEFAULT_USER = 'default'
-    DEFAULT_PERMISSIONS = [
-        'hg.register.manual_activate', 'hg.create.repository',
-        'hg.fork.repository', 'repository.read', 'group.read'
-    ]
-    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    password = Column("password", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
-    name = Column("firstname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    lastname = Column("lastname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
-    ldap_dn = Column("ldap_dn", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    api_key = Column("api_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-
-    user_log = relationship('UserLog', cascade='all')
-    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
-
-    repositories = relationship('Repository')
-    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
-    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
-
-    group_member = relationship('UserGroupMember', cascade='all')
-
-    notifications = relationship('UserNotification', cascade='all')
-    # notifications assigned to this user
-    user_created_notifications = relationship('Notification', cascade='all')
-    # comments created by this user
-    user_comments = relationship('ChangesetComment', cascade='all')
-    #extra emails for this user
-    user_emails = relationship('UserEmailMap', cascade='all')
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-    @property
-    def firstname(self):
-        # alias for future
-        return self.name
-
-    @property
-    def emails(self):
-        other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
-        return [self.email] + [x.email for x in other]
-
-    @property
-    def username_and_name(self):
-        return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
-
-    @property
-    def full_name(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def full_name_or_username(self):
-        return ('%s %s' % (self.firstname, self.lastname)
-                if (self.firstname and self.lastname) else self.username)
-
-    @property
-    def full_contact(self):
-        return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
-
-    @property
-    def short_contact(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def is_admin(self):
-        return self.admin
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                     self.user_id, self.username)
-
-    @classmethod
-    def get_by_username(cls, username, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.username.ilike(username))
-        else:
-            q = cls.query().filter(cls.username == username)
-
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(username)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get_by_api_key(cls, api_key, cache=False):
-        q = cls.query().filter(cls.api_key == api_key)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_api_key_%s" % api_key))
-        return q.scalar()
-
-    @classmethod
-    def get_by_email(cls, email, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.email.ilike(email))
-        else:
-            q = cls.query().filter(cls.email == email)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_email_key_%s" % email))
-
-        ret = q.scalar()
-        if ret is None:
-            q = UserEmailMap.query()
-            # try fetching in alternate email map
-            if case_insensitive:
-                q = q.filter(UserEmailMap.email.ilike(email))
-            else:
-                q = q.filter(UserEmailMap.email == email)
-            q = q.options(joinedload(UserEmailMap.user))
-            if cache:
-                q = q.options(FromCache("sql_cache_short",
-                                        "get_email_map_key_%s" % email))
-            ret = getattr(q.scalar(), 'user', None)
-
-        return ret
-
-    def update_lastlogin(self):
-        """Update user lastlogin"""
-        self.last_login = datetime.datetime.now()
-        Session().add(self)
-        log.debug('updated user %s lastlogin', self.username)
-
-    def get_api_data(self):
-        """
-        Common function for generating user related data for API
-        """
-        user = self
-        data = dict(
-            user_id=user.user_id,
-            username=user.username,
-            firstname=user.name,
-            lastname=user.lastname,
-            email=user.email,
-            emails=user.emails,
-            api_key=user.api_key,
-            active=user.active,
-            admin=user.admin,
-            ldap_dn=user.ldap_dn,
-            last_login=user.last_login,
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-            full_name=self.full_name,
-            full_name_or_username=self.full_name_or_username,
-            short_contact=self.short_contact,
-            full_contact=self.full_contact
-        )
-        data.update(self.get_api_data())
-        return data
-
-
-class UserEmailMap(Base, BaseModel):
-    __tablename__ = 'user_email_map'
-    __table_args__ = (
-        Index('uem_email_idx', 'email'),
-        UniqueConstraint('email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    __mapper_args__ = {}
-
-    email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    user = relationship('User', lazy='joined')
-
-    @validates('_email')
-    def validate_email(self, key, email):
-        # check if this email is not main one
-        main_email = Session().query(User).filter(User.email == email).scalar()
-        if main_email is not None:
-            raise AttributeError('email %s is present is user table' % email)
-        return email
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-
-class UserLog(Base, BaseModel):
-    __tablename__ = 'user_logs'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
-    repository_name = Column("repository_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    user_ip = Column("user_ip", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action = Column("action", UnicodeText(1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
-
-    @property
-    def action_as_day(self):
-        return datetime.date(*self.action_date.timetuple()[:3])
-
-    user = relationship('User')
-    repository = relationship('Repository', cascade='')
-
-
-class UserGroup(Base, BaseModel):
-    __tablename__ = 'users_groups'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_name = Column("users_group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-
-    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
-    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
-    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-
-    def __unicode__(self):
-        return u'<userGroup(%s)>' % (self.users_group_name)
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False,
-                          case_insensitive=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.users_group_name.ilike(group_name))
-        else:
-            q = cls.query().filter(cls.users_group_name == group_name)
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(group_name)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get(cls, users_group_id, cache=False):
-        users_group = cls.query()
-        if cache:
-            users_group = users_group.options(FromCache("sql_cache_short",
-                                    "get_users_group_%s" % users_group_id))
-        return users_group.get(users_group_id)
-
-    def get_api_data(self):
-        users_group = self
-
-        data = dict(
-            users_group_id=users_group.users_group_id,
-            group_name=users_group.users_group_name,
-            active=users_group.users_group_active,
-        )
-
-        return data
-
-
-class UserGroupMember(Base, BaseModel):
-    __tablename__ = 'users_groups_members'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User', lazy='joined')
-    users_group = relationship('UserGroup')
-
-    def __init__(self, gr_id='', u_id=''):
-        self.users_group_id = gr_id
-        self.user_id = u_id
-
-
-class Repository(Base, BaseModel):
-    __tablename__ = 'repositories'
-    __table_args__ = (
-        UniqueConstraint('repo_name'),
-        Index('r_repo_name_idx', 'repo_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repo_name = Column("repo_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    clone_uri = Column("clone_uri", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    repo_type = Column("repo_type", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
-    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
-    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
-    description = Column("description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    landing_rev = Column("landing_revision", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    _locked = Column("locked", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-
-    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
-
-    user = relationship('User')
-    fork = relationship('Repository', remote_side=repo_id)
-    group = relationship('RepoGroup')
-    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    stats = relationship('Statistics', cascade='all', uselist=False)
-
-    followers = relationship('UserFollowing',
-                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
-                             cascade='all')
-
-    logs = relationship('UserLog')
-    comments = relationship('ChangesetComment', cascade="all, delete, delete-orphan")
-
-    pull_requests_org = relationship('PullRequest',
-                    primaryjoin='PullRequest.org_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    pull_requests_other = relationship('PullRequest',
-                    primaryjoin='PullRequest.other_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
-                                   self.repo_name)
-
-    @hybrid_property
-    def locked(self):
-        # always should return [user_id, timelocked]
-        if self._locked:
-            _lock_info = self._locked.split(':')
-            return int(_lock_info[0]), _lock_info[1]
-        return [None, None]
-
-    @locked.setter
-    def locked(self, val):
-        if val and isinstance(val, (list, tuple)):
-            self._locked = ':'.join(map(str, val))
-        else:
-            self._locked = None
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        q = Session().query(cls).filter(cls.repo_name == repo_name)
-        q = q.options(joinedload(Repository.fork))\
-                .options(joinedload(Repository.user))\
-                .options(joinedload(Repository.group))
-        return q.scalar()
-
-    @classmethod
-    def get_by_full_path(cls, repo_full_path):
-        repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
-        return cls.get_by_repo_name(repo_name.strip(URL_SEP))
-
-    @classmethod
-    def get_repo_forks(cls, repo_id):
-        return cls.query().filter(Repository.fork_id == repo_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all repos are stored
-
-        :param cls:
-        """
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == cls.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def forks(self):
-        """
-        Return forks of this repo
-        """
-        return Repository.get_repo_forks(self.repo_id)
-
-    @property
-    def parent(self):
-        """
-        Returns fork parent
-        """
-        return self.fork
-
-    @property
-    def just_name(self):
-        return self.repo_name.split(Repository.url_sep())[-1]
-
-    @property
-    def groups_with_parents(self):
-        groups = []
-        if self.group is None:
-            return groups
-
-        cur_gr = self.group
-        groups.insert(0, cur_gr)
-        while 1:
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            groups.insert(0, gr)
-
-        return groups
-
-    @property
-    def groups_and_repo(self):
-        return self.groups_with_parents, self.just_name
-
-    @LazyProperty
-    def repo_path(self):
-        """
-        Returns base full path for that repository means where it actually
-        exists on a filesystem
-        """
-        q = Session().query(Ui).filter(Ui.ui_key ==
-                                              Repository.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def repo_full_path(self):
-        p = [self.repo_path]
-        # we need to split the name by / since this is how we store the
-        # names in the database, but that eventually needs to be converted
-        # into a valid system path
-        p += self.repo_name.split(Repository.url_sep())
-        return os.path.join(*p)
-
-    @property
-    def cache_keys(self):
-        """
-        Returns associated cache keys for that repo
-        """
-        return CacheInvalidation.query()\
-            .filter(CacheInvalidation.cache_args == self.repo_name)\
-            .order_by(CacheInvalidation.cache_key)\
-            .all()
-
-    def get_new_name(self, repo_name):
-        """
-        returns new full repository name based on assigned group and new new
-
-        :param group_name:
-        """
-        path_prefix = self.group.full_path_splitted if self.group else []
-        return Repository.url_sep().join(path_prefix + [repo_name])
-
-    @property
-    def _ui(self):
-        """
-        Creates an db based ui object for this repository
-        """
-        from kallithea.lib.utils import make_ui
-        return make_ui('db', clear_session=False)
-
-    @classmethod
-    def inject_ui(cls, repo, extras={}):
-        from kallithea.lib.vcs.backends.hg import MercurialRepository
-        from kallithea.lib.vcs.backends.git import GitRepository
-        required = (MercurialRepository, GitRepository)
-        if not isinstance(repo, required):
-            raise Exception('repo must be instance of %s' % (','.join(required)))
-
-        # inject ui extra param to log this action via push logger
-        for k, v in extras.items():
-            repo._repo.ui.setconfig('extras', k, v)
-
-    @classmethod
-    def is_valid(cls, repo_name):
-        """
-        returns True if given repo name is a valid filesystem repository
-
-        :param cls:
-        :param repo_name:
-        """
-        from kallithea.lib.utils import is_valid_repo
-
-        return is_valid_repo(repo_name, cls.base_path())
-
-    def get_api_data(self):
-        """
-        Common function for generating repo api data
-
-        """
-        repo = self
-        data = dict(
-            repo_id=repo.repo_id,
-            repo_name=repo.repo_name,
-            repo_type=repo.repo_type,
-            clone_uri=repo.clone_uri,
-            private=repo.private,
-            created_on=repo.created_on,
-            description=repo.description,
-            landing_rev=repo.landing_rev,
-            owner=repo.user.username,
-            fork_of=repo.fork.repo_name if repo.fork else None
-        )
-
-        return data
-
-    @classmethod
-    def lock(cls, repo, user_id):
-        repo.locked = [user_id, time.time()]
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def unlock(cls, repo):
-        repo.locked = None
-        Session().add(repo)
-        Session().commit()
-
-    @property
-    def last_db_change(self):
-        return self.updated_on
-
-    #==========================================================================
-    # SCM PROPERTIES
-    #==========================================================================
-
-    def get_changeset(self, rev=None):
-        return get_changeset_safe(self.scm_instance, rev)
-
-    def get_landing_changeset(self):
-        """
-        Returns landing changeset, or if that doesn't exist returns the tip
-        """
-        cs = self.get_changeset(self.landing_rev) or self.get_changeset()
-        return cs
-
-    def update_last_change(self, last_change=None):
-        if last_change is None:
-            last_change = datetime.datetime.now()
-        if self.updated_on is None or self.updated_on != last_change:
-            log.debug('updated repo %s with new date %s', self, last_change)
-            self.updated_on = last_change
-            Session().add(self)
-            Session().commit()
-
-    @property
-    def tip(self):
-        return self.get_changeset('tip')
-
-    @property
-    def author(self):
-        return self.tip.author
-
-    @property
-    def last_change(self):
-        return self.scm_instance.last_change
-
-    def get_comments(self, revisions=None):
-        """
-        Returns comments for this repository grouped by revisions
-
-        :param revisions: filter query by revisions only
-        """
-        cmts = ChangesetComment.query()\
-            .filter(ChangesetComment.repo == self)
-        if revisions:
-            cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
-        grouped = defaultdict(list)
-        for cmt in cmts.all():
-            grouped[cmt.revision].append(cmt)
-        return grouped
-
-    def statuses(self, revisions=None):
-        """
-        Returns statuses for this repository
-
-        :param revisions: list of revisions to get statuses for
-        :type revisions: list
-        """
-
-        statuses = ChangesetStatus.query()\
-            .filter(ChangesetStatus.repo == self)\
-            .filter(ChangesetStatus.version == 0)
-        if revisions:
-            statuses = statuses.filter(ChangesetStatus.revision.in_(revisions))
-        grouped = {}
-
-        #maybe we have open new pullrequest without a status ?
-        stat = ChangesetStatus.STATUS_UNDER_REVIEW
-        status_lbl = ChangesetStatus.get_status_lbl(stat)
-        for pr in PullRequest.query().filter(PullRequest.org_repo == self).all():
-            for rev in pr.revisions:
-                pr_id = pr.pull_request_id
-                pr_repo = pr.other_repo.repo_name
-                grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
-
-        for stat in statuses.all():
-            pr_id = pr_repo = None
-            if stat.pull_request:
-                pr_id = stat.pull_request.pull_request_id
-                pr_repo = stat.pull_request.other_repo.repo_name
-            grouped[stat.revision] = [str(stat.status), stat.status_lbl,
-                                      pr_id, pr_repo]
-        return grouped
-
-    #==========================================================================
-    # SCM CACHE INSTANCE
-    #==========================================================================
-
-    @property
-    def invalidate(self):
-        return CacheInvalidation.invalidate(self.repo_name)
-
-    def set_invalidate(self):
-        """
-        set a cache for invalidation for this instance
-        """
-        CacheInvalidation.set_invalidate(repo_name=self.repo_name)
-
-    @LazyProperty
-    def scm_instance(self):
-        import kallithea
-        full_cache = str2bool(kallithea.CONFIG.get('vcs_full_cache'))
-        if full_cache:
-            return self.scm_instance_cached()
-        return self.__get_instance()
-
-    def scm_instance_cached(self, cache_map=None):
-        @cache_region('long_term')
-        def _c(repo_name):
-            return self.__get_instance()
-        rn = self.repo_name
-        log.debug('Getting cached instance of repo')
-
-        if cache_map:
-            # get using prefilled cache_map
-            invalidate_repo = cache_map[self.repo_name]
-            if invalidate_repo:
-                invalidate_repo = (None if invalidate_repo.cache_active
-                                   else invalidate_repo)
-        else:
-            # get from invalidate
-            invalidate_repo = self.invalidate
-
-        if invalidate_repo is not None:
-            region_invalidate(_c, None, rn)
-            # update our cache
-            CacheInvalidation.set_valid(invalidate_repo.cache_key)
-        return _c(rn)
-
-    def __get_instance(self):
-        repo_full_path = self.repo_full_path
-        try:
-            alias = get_scm(repo_full_path)[0]
-            log.debug('Creating instance of %s repository', alias)
-            backend = get_backend(alias)
-        except VCSError:
-            log.error(traceback.format_exc())
-            log.error('Perhaps this repository is in db and not in '
-                      'filesystem run rescan repositories with '
-                      '"destroy old data " option from admin panel')
-            return
-
-        if alias == 'hg':
-
-            repo = backend(safe_str(repo_full_path), create=False,
-                           baseui=self._ui)
-        else:
-            repo = backend(repo_full_path, create=False)
-
-        return repo
-
-
-class RepoGroup(Base, BaseModel):
-    __tablename__ = 'groups'
-    __table_args__ = (
-        UniqueConstraint('group_name', 'group_parent_id'),
-        CheckConstraint('group_id != group_parent_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    __mapper_args__ = {'order_by': 'group_name'}
-
-    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    group_name = Column("group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
-    group_description = Column("group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-
-    parent_group = relationship('RepoGroup', remote_side=group_id)
-
-    def __init__(self, group_name='', parent_group=None):
-        self.group_name = group_name
-        self.parent_group = parent_group
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.group_id,
-                                  self.group_name)
-
-    @classmethod
-    def groups_choices(cls, check_perms=False):
-        from webhelpers.html import literal as _literal
-        from kallithea.model.scm import ScmModel
-        groups = cls.query().all()
-        if check_perms:
-            #filter group user have access to, it's done
-            #magically inside ScmModel based on current user
-            groups = ScmModel().get_repos_groups(groups)
-        repo_groups = [('', '')]
-        sep = ' &raquo; '
-        _name = lambda k: _literal(sep.join(k))
-
-        repo_groups.extend([(x.group_id, _name(x.full_path_splitted))
-                              for x in groups])
-
-        repo_groups = sorted(repo_groups, key=lambda t: t[1].split(sep)[0])
-        return repo_groups
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
-        if case_insensitive:
-            gr = cls.query()\
-                .filter(cls.group_name.ilike(group_name))
-        else:
-            gr = cls.query()\
-                .filter(cls.group_name == group_name)
-        if cache:
-            gr = gr.options(FromCache(
-                            "sql_cache_short",
-                            "get_group_%s" % _hash_key(group_name)
-                            )
-            )
-        return gr.scalar()
-
-    @property
-    def parents(self):
-        parents_recursion_limit = 5
-        groups = []
-        if self.parent_group is None:
-            return groups
-        cur_gr = self.parent_group
-        groups.insert(0, cur_gr)
-        cnt = 0
-        while 1:
-            cnt += 1
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            if cnt == parents_recursion_limit:
-                # this will prevent accidental infinite loops
-                log.error('group nested more than %s',
-                          parents_recursion_limit)
-                break
-
-            groups.insert(0, gr)
-        return groups
-
-    @property
-    def children(self):
-        return RepoGroup.query().filter(RepoGroup.parent_group == self)
-
-    @property
-    def name(self):
-        return self.group_name.split(RepoGroup.url_sep())[-1]
-
-    @property
-    def full_path(self):
-        return self.group_name
-
-    @property
-    def full_path_splitted(self):
-        return self.group_name.split(RepoGroup.url_sep())
-
-    @property
-    def repositories(self):
-        return Repository.query()\
-                .filter(Repository.group == self)\
-                .order_by(Repository.repo_name)
-
-    @property
-    def repositories_recursive_count(self):
-        cnt = self.repositories.count()
-
-        def children_count(group):
-            cnt = 0
-            for child in group.children:
-                cnt += child.repositories.count()
-                cnt += children_count(child)
-            return cnt
-
-        return cnt + children_count(self)
-
-    def recursive_groups_and_repos(self):
-        """
-        Recursive return all groups, with repositories in those groups
-        """
-        all_ = []
-
-        def _get_members(root_gr):
-            for r in root_gr.repositories:
-                all_.append(r)
-            childs = root_gr.children.all()
-            if childs:
-                for gr in childs:
-                    all_.append(gr)
-                    _get_members(gr)
-
-        _get_members(self)
-        return [self] + all_
-
-    def get_new_name(self, group_name):
-        """
-        returns new full group name based on parent and new name
-
-        :param group_name:
-        """
-        path_prefix = (self.parent_group.full_path_splitted if
-                       self.parent_group else [])
-        return RepoGroup.url_sep().join(path_prefix + [group_name])
-
-
-class Permission(Base, BaseModel):
-    __tablename__ = 'permissions'
-    __table_args__ = (
-        Index('p_perm_name_idx', 'permission_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    PERMS = [
-        ('repository.none', _('Repository no access')),
-        ('repository.read', _('Repository read access')),
-        ('repository.write', _('Repository write access')),
-        ('repository.admin', _('Repository admin access')),
-
-        ('group.none', _('Repository Group no access')),
-        ('group.read', _('Repository Group read access')),
-        ('group.write', _('Repository Group write access')),
-        ('group.admin', _('Repository Group admin access')),
-
-        ('hg.admin', _('Kallithea Administrator')),
-        ('hg.create.none', _('Repository creation disabled')),
-        ('hg.create.repository', _('Repository creation enabled')),
-        ('hg.fork.none', _('Repository forking disabled')),
-        ('hg.fork.repository', _('Repository forking enabled')),
-        ('hg.register.none', _('Register disabled')),
-        ('hg.register.manual_activate', _('Register new user with Kallithea '
-                                          'with manual activation')),
-
-        ('hg.register.auto_activate', _('Register new user with Kallithea '
-                                        'with auto activation')),
-    ]
-
-    # defines which permissions are more important higher the more important
-    PERM_WEIGHTS = {
-        'repository.none': 0,
-        'repository.read': 1,
-        'repository.write': 3,
-        'repository.admin': 4,
-
-        'group.none': 0,
-        'group.read': 1,
-        'group.write': 3,
-        'group.admin': 4,
-
-        'hg.fork.none': 0,
-        'hg.fork.repository': 1,
-        'hg.create.none': 0,
-        'hg.create.repository':1
-    }
-
-    permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    permission_name = Column("permission_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    permission_longname = Column("permission_longname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__, self.permission_id, self.permission_name
-        )
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.permission_name == key).scalar()
-
-    @classmethod
-    def get_default_perms(cls, default_user_id):
-        q = Session().query(UserRepoToPerm, Repository, cls)\
-         .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
-         .join((cls, UserRepoToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_group_perms(cls, default_user_id):
-        q = Session().query(UserRepoGroupToPerm, RepoGroup, cls)\
-         .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
-         .join((cls, UserRepoGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-
-class UserRepoToPerm(Base, BaseModel):
-    __tablename__ = 'repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'repository_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    repository = relationship('Repository')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, repository, permission):
-        n = cls()
-        n.user = user
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<user:%s => %s >' % (self.user, self.repository)
-
-
-class UserToPerm(Base, BaseModel):
-    __tablename__ = 'user_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    permission = relationship('Permission', lazy='joined')
-
-
-class UserGroupRepoToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    repository = relationship('Repository')
-
-    @classmethod
-    def create(cls, users_group, repository, permission):
-        n = cls()
-        n.users_group = users_group
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<userGroup:%s => %s >' % (self.users_group, self.repository)
-
-
-class UserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'permission_id',),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-
-class UserRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    group = relationship('RepoGroup')
-    permission = relationship('Permission')
-
-
-class UserGroupRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    group = relationship('RepoGroup')
-
-
-class Statistics(Base, BaseModel):
-    __tablename__ = 'statistics'
-    __table_args__ = (
-         UniqueConstraint('repository_id'),
-         {'extend_existing': True, 'mysql_engine': 'InnoDB',
-          'mysql_charset': 'utf8'}
-    )
-    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
-    stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
-    commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
-    commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
-    languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
-
-    repository = relationship('Repository', single_parent=True)
-
-
-class UserFollowing(Base, BaseModel):
-    __tablename__ = 'user_followings'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'follows_repository_id'),
-        UniqueConstraint('user_id', 'follows_user_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-
-    user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
-
-    follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relationship('Repository', order_by='Repository.repo_name')
-
-    @classmethod
-    def get_repo_followers(cls, repo_id):
-        return cls.query().filter(cls.follows_repo_id == repo_id)
-
-
-class CacheInvalidation(Base, BaseModel):
-    __tablename__ = 'cache_invalidation'
-    __table_args__ = (
-        UniqueConstraint('cache_key'),
-        Index('key_idx', 'cache_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    cache_key = Column("cache_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    cache_args = Column("cache_args", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
-
-    def __init__(self, cache_key, cache_args=''):
-        self.cache_key = cache_key
-        self.cache_args = cache_args
-        self.cache_active = False
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__,
-                                  self.cache_id, self.cache_key)
-
-    @property
-    def prefix(self):
-        _split = self.cache_key.split(self.cache_args, 1)
-        if _split and len(_split) == 2:
-            return _split[0]
-        return ''
-
-    @classmethod
-    def clear_cache(cls):
-        cls.query().delete()
-
-    @classmethod
-    def _get_key(cls, key):
-        """
-        Wrapper for generating a key, together with a prefix
-
-        :param key:
-        """
-        import kallithea
-        prefix = ''
-        org_key = key
-        iid = kallithea.CONFIG.get('instance_id')
-        if iid:
-            prefix = iid
-
-        return "%s%s" % (prefix, key), prefix, org_key
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.cache_key == key).scalar()
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        return cls.query().filter(cls.cache_args == repo_name).all()
-
-    @classmethod
-    def _get_or_create_key(cls, key, repo_name, commit=True):
-        inv_obj = Session().query(cls).filter(cls.cache_key == key).scalar()
-        if not inv_obj:
-            try:
-                inv_obj = CacheInvalidation(key, repo_name)
-                Session().add(inv_obj)
-                if commit:
-                    Session().commit()
-            except Exception:
-                log.error(traceback.format_exc())
-                Session().rollback()
-        return inv_obj
-
-    @classmethod
-    def invalidate(cls, key):
-        """
-        Returns Invalidation object if this given key should be invalidated
-        None otherwise. `cache_active = False` means that this cache
-        state is not valid and needs to be invalidated
-
-        :param key:
-        """
-        repo_name = key
-        repo_name = remove_suffix(repo_name, '_README')
-        repo_name = remove_suffix(repo_name, '_RSS')
-        repo_name = remove_suffix(repo_name, '_ATOM')
-
-        # adds instance prefix
-        key, _prefix, _org_key = cls._get_key(key)
-        inv = cls._get_or_create_key(key, repo_name)
-
-        if inv and inv.cache_active is False:
-            return inv
-
-    @classmethod
-    def set_invalidate(cls, key=None, repo_name=None):
-        """
-        Mark this Cache key for invalidation, either by key or whole
-        cache sets based on repo_name
-
-        :param key:
-        """
-        if key:
-            key, _prefix, _org_key = cls._get_key(key)
-            inv_objs = Session().query(cls).filter(cls.cache_key == key).all()
-        elif repo_name:
-            inv_objs = Session().query(cls).filter(cls.cache_args == repo_name).all()
-
-        log.debug('marking %s key[s] for invalidation based on key=%s,repo_name=%s',
-                  len(inv_objs), key, repo_name)
-        try:
-            for inv_obj in inv_objs:
-                inv_obj.cache_active = False
-                Session().add(inv_obj)
-            Session().commit()
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-
-    @classmethod
-    def set_valid(cls, key):
-        """
-        Mark this cache key as active and currently cached
-
-        :param key:
-        """
-        inv_obj = cls.get_by_key(key)
-        inv_obj.cache_active = True
-        Session().add(inv_obj)
-        Session().commit()
-
-    @classmethod
-    def get_cache_map(cls):
-
-        class cachemapdict(dict):
-
-            def __init__(self, *args, **kwargs):
-                fixkey = kwargs.get('fixkey')
-                if fixkey:
-                    del kwargs['fixkey']
-                self.fixkey = fixkey
-                super(cachemapdict, self).__init__(*args, **kwargs)
-
-            def __getattr__(self, name):
-                key = name
-                if self.fixkey:
-                    key, _prefix, _org_key = cls._get_key(key)
-                if key in self.__dict__:
-                    return self.__dict__[key]
-                else:
-                    return self[key]
-
-            def __getitem__(self, key):
-                if self.fixkey:
-                    key, _prefix, _org_key = cls._get_key(key)
-                try:
-                    return super(cachemapdict, self).__getitem__(key)
-                except KeyError:
-                    return
-
-        cache_map = cachemapdict(fixkey=True)
-        for obj in cls.query().all():
-            cache_map[obj.cache_key] = cachemapdict(obj.get_dict())
-        return cache_map
-
-
-class ChangesetComment(Base, BaseModel):
-    __tablename__ = 'changeset_comments'
-    __table_args__ = (
-        Index('cc_revision_idx', 'revision'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    revision = Column('revision', String(40), nullable=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-    line_no = Column('line_no', Unicode(10), nullable=True)
-    hl_lines = Column('hl_lines', Unicode(512), nullable=True)
-    f_path = Column('f_path', Unicode(1000), nullable=True)
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
-    text = Column('text', UnicodeText(25000), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    @classmethod
-    def get_users(cls, revision=None, pull_request_id=None):
-        """
-        Returns user associated with this ChangesetComment. ie those
-        who actually commented
-
-        :param cls:
-        :param revision:
-        """
-        q = Session().query(User)\
-                .join(ChangesetComment.author)
-        if revision:
-            q = q.filter(cls.revision == revision)
-        elif pull_request_id:
-            q = q.filter(cls.pull_request_id == pull_request_id)
-        return q.all()
-
-
-class ChangesetStatus(Base, BaseModel):
-    __tablename__ = 'changeset_statuses'
-    __table_args__ = (
-        Index('cs_revision_idx', 'revision'),
-        Index('cs_version_idx', 'version'),
-        UniqueConstraint('repo_id', 'revision', 'version'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
-    STATUS_APPROVED = 'approved'
-    STATUS_REJECTED = 'rejected'
-    STATUS_UNDER_REVIEW = 'under_review'
-
-    STATUSES = [
-        (STATUS_NOT_REVIEWED, _("Not Reviewed")),  # (no icon) and default
-        (STATUS_APPROVED, _("Approved")),
-        (STATUS_REJECTED, _("Rejected")),
-        (STATUS_UNDER_REVIEW, _("Under Review")),
-    ]
-
-    changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    revision = Column('revision', String(40), nullable=False)
-    status = Column('status', String(128), nullable=False, default=DEFAULT)
-    changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
-    modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
-    version = Column('version', Integer(), nullable=False, default=0)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    comment = relationship('ChangesetComment', lazy='joined')
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.status, self.author
-        )
-
-    @classmethod
-    def get_status_lbl(cls, value):
-        return dict(cls.STATUSES).get(value)
-
-    @property
-    def status_lbl(self):
-        return ChangesetStatus.get_status_lbl(self.status)
-
-
-class PullRequest(Base, BaseModel):
-    __tablename__ = 'pull_requests'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    STATUS_NEW = u'new'
-    STATUS_OPEN = u'open'
-    STATUS_CLOSED = u'closed'
-
-    pull_request_id = Column('pull_request_id', Integer(), nullable=False, primary_key=True)
-    title = Column('title', Unicode(256), nullable=True)
-    description = Column('description', UnicodeText(10240), nullable=True)
-    status = Column('status', Unicode(256), nullable=False, default=STATUS_NEW)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    _revisions = Column('revisions', UnicodeText(20500))  # 500 revisions max
-    org_repo_id = Column('org_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    org_ref = Column('org_ref', Unicode(256), nullable=False)
-    other_repo_id = Column('other_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    other_ref = Column('other_ref', Unicode(256), nullable=False)
-
-    @hybrid_property
-    def revisions(self):
-        return self._revisions.split(':')
-
-    @revisions.setter
-    def revisions(self, val):
-        self._revisions = ':'.join(val)
-
-    author = relationship('User', lazy='joined')
-    reviewers = relationship('PullRequestReviewers',
-                             cascade="all, delete, delete-orphan")
-    org_repo = relationship('Repository', primaryjoin='PullRequest.org_repo_id==Repository.repo_id')
-    other_repo = relationship('Repository', primaryjoin='PullRequest.other_repo_id==Repository.repo_id')
-    statuses = relationship('ChangesetStatus')
-    comments = relationship('ChangesetComment',
-                             cascade="all, delete, delete-orphan")
-
-    def is_closed(self):
-        return self.status == self.STATUS_CLOSED
-
-    def __json__(self):
-        return dict(
-          revisions=self.revisions
-        )
-
-
-class PullRequestReviewers(Base, BaseModel):
-    __tablename__ = 'pull_request_reviewers'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    def __init__(self, user=None, pull_request=None):
-        self.user = user
-        self.pull_request = pull_request
-
-    pull_requests_reviewers_id = Column('pull_requests_reviewers_id', Integer(), nullable=False, primary_key=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
-
-    user = relationship('User')
-    pull_request = relationship('PullRequest')
-
-
-class Notification(Base, BaseModel):
-    __tablename__ = 'notifications'
-    __table_args__ = (
-        Index('notification_type_idx', 'type'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    TYPE_CHANGESET_COMMENT = u'cs_comment'
-    TYPE_MESSAGE = u'message'
-    TYPE_MENTION = u'mention'
-    TYPE_REGISTRATION = u'registration'
-    TYPE_PULL_REQUEST = u'pull_request'
-    TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
-
-    notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
-    subject = Column('subject', Unicode(512), nullable=True)
-    body = Column('body', UnicodeText(50000), nullable=True)
-    created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    type_ = Column('type', Unicode(256))
-
-    created_by_user = relationship('User')
-    notifications_to_users = relationship('UserNotification', lazy='joined',
-                                          cascade="all, delete, delete-orphan")
-
-    @property
-    def recipients(self):
-        return [x.user for x in UserNotification.query()\
-                .filter(UserNotification.notification == self)\
-                .order_by(UserNotification.user_id.asc()).all()]
-
-    @classmethod
-    def create(cls, created_by, subject, body, recipients, type_=None):
-        if type_ is None:
-            type_ = Notification.TYPE_MESSAGE
-
-        notification = cls()
-        notification.created_by_user = created_by
-        notification.subject = subject
-        notification.body = body
-        notification.type_ = type_
-        notification.created_on = datetime.datetime.now()
-
-        for u in recipients:
-            assoc = UserNotification()
-            assoc.notification = notification
-            u.notifications.append(assoc)
-        Session().add(notification)
-        return notification
-
-    @property
-    def description(self):
-        from kallithea.model.notification import NotificationModel
-        return NotificationModel().make_description(self)
-
-
-class UserNotification(Base, BaseModel):
-    __tablename__ = 'user_to_notification'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'notification_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
-    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
-    read = Column('read', Boolean, default=False)
-    sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
-
-    user = relationship('User', lazy="joined")
-    notification = relationship('Notification', lazy="joined",
-                                order_by=lambda: Notification.created_on.desc(),)
-
-    def mark_as_read(self):
-        self.read = True
-        Session().add(self)
-
-
-class DbMigrateVersion(Base, BaseModel):
-    __tablename__ = 'db_migrate_version'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    repository_id = Column('repository_id', String(250), primary_key=True)
-    repository_path = Column('repository_path', Text)
-    version = Column('version', Integer)
--- a/kallithea/lib/dbmigrate/schema/db_1_5_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1841 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate.schema.db_1_5_0
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Database Models for Kallithea <=1.5.2
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Apr 08, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-import os
-import logging
-import datetime
-import traceback
-import hashlib
-import time
-from collections import defaultdict
-
-from sqlalchemy import *
-from sqlalchemy.ext.hybrid import hybrid_property
-from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
-from beaker.cache import cache_region, region_invalidate
-from webob.exc import HTTPNotFound
-
-from pylons.i18n.translation import lazy_ugettext as _
-
-from kallithea.lib.vcs import get_backend
-from kallithea.lib.vcs.utils.helpers import get_scm
-from kallithea.lib.vcs.exceptions import VCSError
-from kallithea.lib.vcs.utils.lazy import LazyProperty
-
-from kallithea.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
-    safe_unicode, remove_suffix, remove_prefix
-from kallithea.lib.caching_query import FromCache
-
-from kallithea.model.meta import Base, Session
-
-from kallithea import DB_PREFIX
-
-URL_SEP = '/'
-log = logging.getLogger(__name__)
-
-#==============================================================================
-# BASE CLASSES
-#==============================================================================
-
-_hash_key = lambda k: hashlib.md5(safe_str(k)).hexdigest()
-
-
-class BaseModel(object):
-    """
-    Base Model for all classess
-    """
-
-    @classmethod
-    def _get_keys(cls):
-        """return column names for this model """
-        return class_mapper(cls).c.keys()
-
-    def get_dict(self):
-        """
-        return dict with keys and values corresponding
-        to this model data """
-
-        d = {}
-        for k in self._get_keys():
-            d[k] = getattr(self, k)
-
-        # also use __json__() if present to get additional fields
-        _json_attr = getattr(self, '__json__', None)
-        if _json_attr:
-            # update with attributes from __json__
-            if callable(_json_attr):
-                _json_attr = _json_attr()
-            for k, val in _json_attr.iteritems():
-                d[k] = val
-        return d
-
-    def get_appstruct(self):
-        """return list with keys and values tuples corresponding
-        to this model data """
-
-        l = []
-        for k in self._get_keys():
-            l.append((k, getattr(self, k),))
-        return l
-
-    def populate_obj(self, populate_dict):
-        """populate model with data from given populate_dict"""
-
-        for k in self._get_keys():
-            if k in populate_dict:
-                setattr(self, k, populate_dict[k])
-
-    @classmethod
-    def query(cls):
-        return Session().query(cls)
-
-    @classmethod
-    def get(cls, id_):
-        if id_:
-            return cls.query().get(id_)
-
-    @classmethod
-    def get_or_404(cls, id_):
-        try:
-            id_ = int(id_)
-        except (TypeError, ValueError):
-            raise HTTPNotFound
-
-        res = cls.query().get(id_)
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def getAll(cls):
-        return cls.query().all()
-
-    @classmethod
-    def delete(cls, id_):
-        obj = cls.query().get(id_)
-        Session().delete(obj)
-
-    def __repr__(self):
-        if hasattr(self, '__unicode__'):
-            # python repr needs to return str
-            return safe_str(self.__unicode__())
-        return '<DB:%s>' % (self.__class__.__name__)
-
-
-class Setting(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'settings'
-    __table_args__ = (
-        UniqueConstraint('app_settings_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    app_settings_name = Column("app_settings_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_value = Column("app_settings_value", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __init__(self, k='', v=''):
-        self.app_settings_name = k
-        self.app_settings_value = v
-
-    @validates('_app_settings_value')
-    def validate_settings_value(self, key, val):
-        assert type(val) == unicode
-        return val
-
-    @hybrid_property
-    def app_settings_value(self):
-        v = self._app_settings_value
-        if self.app_settings_name in ["ldap_active",
-                                      "default_repo_enable_statistics",
-                                      "default_repo_enable_locking",
-                                      "default_repo_private",
-                                      "default_repo_enable_downloads"]:
-            v = str2bool(v)
-        return v
-
-    @app_settings_value.setter
-    def app_settings_value(self, val):
-        """
-        Setter that will always make sure we use unicode in app_settings_value
-
-        :param val:
-        """
-        self._app_settings_value = safe_unicode(val)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.app_settings_name, self.app_settings_value
-        )
-
-    @classmethod
-    def get_by_name(cls, key):
-        return cls.query()\
-            .filter(cls.app_settings_name == key).scalar()
-
-    @classmethod
-    def get_by_name_or_create(cls, key):
-        res = cls.get_by_name(key)
-        if not res:
-            res = cls(key)
-        return res
-
-    @classmethod
-    def get_app_settings(cls, cache=False):
-
-        ret = cls.query()
-
-        if cache:
-            ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
-
-        if not ret:
-            raise Exception('Could not get application settings !')
-        settings = {}
-        for each in ret:
-            settings[each.app_settings_name] = \
-                each.app_settings_value
-
-        return settings
-
-    @classmethod
-    def get_ldap_settings(cls, cache=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('ldap_')).all()
-        fd = {}
-        for row in ret:
-            fd.update({row.app_settings_name: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_default_repo_settings(cls, cache=False, strip_prefix=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('default_')).all()
-        fd = {}
-        for row in ret:
-            key = row.app_settings_name
-            if strip_prefix:
-                key = remove_prefix(key, prefix='default_')
-            fd.update({key: row.app_settings_value})
-
-        return fd
-
-
-class Ui(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'ui'
-    __table_args__ = (
-        UniqueConstraint('ui_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    HOOK_UPDATE = 'changegroup.update'
-    HOOK_REPO_SIZE = 'changegroup.repo_size'
-    HOOK_PUSH = 'changegroup.push_logger'
-    HOOK_PRE_PUSH = 'prechangegroup.pre_push'
-    HOOK_PULL = 'outgoing.pull_logger'
-    HOOK_PRE_PULL = 'preoutgoing.pre_pull'
-
-    ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    ui_section = Column("ui_section", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_key = Column("ui_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_value = Column("ui_value", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.ui_key == key).scalar()
-
-    @classmethod
-    def get_builtin_hooks(cls):
-        q = cls.query()
-        q = q.filter(cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                     cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                     cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        return q.all()
-
-    @classmethod
-    def get_custom_hooks(cls):
-        q = cls.query()
-        q = q.filter(~cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                      cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                      cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        q = q.filter(cls.ui_section == 'hooks')
-        return q.all()
-
-    @classmethod
-    def get_repos_location(cls):
-        return cls.get_by_key('/').ui_value
-
-    @classmethod
-    def create_or_update_hook(cls, key, val):
-        new_ui = cls.get_by_key(key) or cls()
-        new_ui.ui_section = 'hooks'
-        new_ui.ui_active = True
-        new_ui.ui_key = key
-        new_ui.ui_value = val
-
-        Session().add(new_ui)
-
-    def __repr__(self):
-        return '<DB:%s[%s:%s]>' % (self.__class__.__name__, self.ui_key,
-                                   self.ui_value)
-
-
-class User(Base, BaseModel):
-    __tablename__ = 'users'
-    __table_args__ = (
-        UniqueConstraint('username'), UniqueConstraint('email'),
-        Index('u_username_idx', 'username'),
-        Index('u_email_idx', 'email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    DEFAULT_USER = 'default'
-    DEFAULT_PERMISSIONS = [
-        'hg.register.manual_activate', 'hg.create.repository',
-        'hg.fork.repository', 'repository.read', 'group.read'
-    ]
-    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    password = Column("password", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
-    name = Column("firstname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    lastname = Column("lastname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
-    ldap_dn = Column("ldap_dn", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    api_key = Column("api_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-
-    user_log = relationship('UserLog')
-    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
-
-    repositories = relationship('Repository')
-    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
-    followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
-
-    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
-
-    group_member = relationship('UserGroupMember', cascade='all')
-
-    notifications = relationship('UserNotification', cascade='all')
-    # notifications assigned to this user
-    user_created_notifications = relationship('Notification', cascade='all')
-    # comments created by this user
-    user_comments = relationship('ChangesetComment', cascade='all')
-    #extra emails for this user
-    user_emails = relationship('UserEmailMap', cascade='all')
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-    @property
-    def firstname(self):
-        # alias for future
-        return self.name
-
-    @property
-    def emails(self):
-        other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
-        return [self.email] + [x.email for x in other]
-
-    @property
-    def username_and_name(self):
-        return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
-
-    @property
-    def full_name(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def full_name_or_username(self):
-        return ('%s %s' % (self.firstname, self.lastname)
-                if (self.firstname and self.lastname) else self.username)
-
-    @property
-    def full_contact(self):
-        return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
-
-    @property
-    def short_contact(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def is_admin(self):
-        return self.admin
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                     self.user_id, self.username)
-
-    @classmethod
-    def get_by_username(cls, username, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.username.ilike(username))
-        else:
-            q = cls.query().filter(cls.username == username)
-
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(username)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get_by_api_key(cls, api_key, cache=False):
-        q = cls.query().filter(cls.api_key == api_key)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_api_key_%s" % api_key))
-        return q.scalar()
-
-    @classmethod
-    def get_by_email(cls, email, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.email.ilike(email))
-        else:
-            q = cls.query().filter(cls.email == email)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_email_key_%s" % email))
-
-        ret = q.scalar()
-        if ret is None:
-            q = UserEmailMap.query()
-            # try fetching in alternate email map
-            if case_insensitive:
-                q = q.filter(UserEmailMap.email.ilike(email))
-            else:
-                q = q.filter(UserEmailMap.email == email)
-            q = q.options(joinedload(UserEmailMap.user))
-            if cache:
-                q = q.options(FromCache("sql_cache_short",
-                                        "get_email_map_key_%s" % email))
-            ret = getattr(q.scalar(), 'user', None)
-
-        return ret
-
-    def update_lastlogin(self):
-        """Update user lastlogin"""
-        self.last_login = datetime.datetime.now()
-        Session().add(self)
-        log.debug('updated user %s lastlogin', self.username)
-
-    def get_api_data(self):
-        """
-        Common function for generating user related data for API
-        """
-        user = self
-        data = dict(
-            user_id=user.user_id,
-            username=user.username,
-            firstname=user.name,
-            lastname=user.lastname,
-            email=user.email,
-            emails=user.emails,
-            api_key=user.api_key,
-            active=user.active,
-            admin=user.admin,
-            ldap_dn=user.ldap_dn,
-            last_login=user.last_login,
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-            full_name=self.full_name,
-            full_name_or_username=self.full_name_or_username,
-            short_contact=self.short_contact,
-            full_contact=self.full_contact
-        )
-        data.update(self.get_api_data())
-        return data
-
-
-class UserEmailMap(Base, BaseModel):
-    __tablename__ = 'user_email_map'
-    __table_args__ = (
-        Index('uem_email_idx', 'email'),
-        UniqueConstraint('email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    __mapper_args__ = {}
-
-    email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    user = relationship('User', lazy='joined')
-
-    @validates('_email')
-    def validate_email(self, key, email):
-        # check if this email is not main one
-        main_email = Session().query(User).filter(User.email == email).scalar()
-        if main_email is not None:
-            raise AttributeError('email %s is present is user table' % email)
-        return email
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-
-class UserLog(Base, BaseModel):
-    __tablename__ = 'user_logs'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
-    repository_name = Column("repository_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    user_ip = Column("user_ip", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action = Column("action", UnicodeText(1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
-
-    @property
-    def action_as_day(self):
-        return datetime.date(*self.action_date.timetuple()[:3])
-
-    user = relationship('User')
-    repository = relationship('Repository', cascade='')
-
-
-class UserGroup(Base, BaseModel):
-    __tablename__ = 'users_groups'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_name = Column("users_group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-
-    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
-    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
-    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-
-    def __unicode__(self):
-        return u'<userGroup(%s)>' % (self.users_group_name)
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False,
-                          case_insensitive=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.users_group_name.ilike(group_name))
-        else:
-            q = cls.query().filter(cls.users_group_name == group_name)
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(group_name)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get(cls, users_group_id, cache=False):
-        users_group = cls.query()
-        if cache:
-            users_group = users_group.options(FromCache("sql_cache_short",
-                                    "get_users_group_%s" % users_group_id))
-        return users_group.get(users_group_id)
-
-    def get_api_data(self):
-        users_group = self
-
-        data = dict(
-            users_group_id=users_group.users_group_id,
-            group_name=users_group.users_group_name,
-            active=users_group.users_group_active,
-        )
-
-        return data
-
-
-class UserGroupMember(Base, BaseModel):
-    __tablename__ = 'users_groups_members'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User', lazy='joined')
-    users_group = relationship('UserGroup')
-
-    def __init__(self, gr_id='', u_id=''):
-        self.users_group_id = gr_id
-        self.user_id = u_id
-
-
-class Repository(Base, BaseModel):
-    __tablename__ = 'repositories'
-    __table_args__ = (
-        UniqueConstraint('repo_name'),
-        Index('r_repo_name_idx', 'repo_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repo_name = Column("repo_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    clone_uri = Column("clone_uri", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    repo_type = Column("repo_type", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
-    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
-    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
-    description = Column("description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    landing_rev = Column("landing_revision", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    _locked = Column("locked", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-
-    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
-
-    user = relationship('User')
-    fork = relationship('Repository', remote_side=repo_id)
-    group = relationship('RepoGroup')
-    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    stats = relationship('Statistics', cascade='all', uselist=False)
-
-    followers = relationship('UserFollowing',
-                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
-                             cascade='all')
-
-    logs = relationship('UserLog')
-    comments = relationship('ChangesetComment', cascade="all, delete, delete-orphan")
-
-    pull_requests_org = relationship('PullRequest',
-                    primaryjoin='PullRequest.org_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    pull_requests_other = relationship('PullRequest',
-                    primaryjoin='PullRequest.other_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
-                                   self.repo_name)
-
-    @hybrid_property
-    def locked(self):
-        # always should return [user_id, timelocked]
-        if self._locked:
-            _lock_info = self._locked.split(':')
-            return int(_lock_info[0]), _lock_info[1]
-        return [None, None]
-
-    @locked.setter
-    def locked(self, val):
-        if val and isinstance(val, (list, tuple)):
-            self._locked = ':'.join(map(str, val))
-        else:
-            self._locked = None
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        q = Session().query(cls).filter(cls.repo_name == repo_name)
-        q = q.options(joinedload(Repository.fork))\
-                .options(joinedload(Repository.user))\
-                .options(joinedload(Repository.group))
-        return q.scalar()
-
-    @classmethod
-    def get_by_full_path(cls, repo_full_path):
-        repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
-        return cls.get_by_repo_name(repo_name.strip(URL_SEP))
-
-    @classmethod
-    def get_repo_forks(cls, repo_id):
-        return cls.query().filter(Repository.fork_id == repo_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all repos are stored
-
-        :param cls:
-        """
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == cls.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def forks(self):
-        """
-        Return forks of this repo
-        """
-        return Repository.get_repo_forks(self.repo_id)
-
-    @property
-    def parent(self):
-        """
-        Returns fork parent
-        """
-        return self.fork
-
-    @property
-    def just_name(self):
-        return self.repo_name.split(Repository.url_sep())[-1]
-
-    @property
-    def groups_with_parents(self):
-        groups = []
-        if self.group is None:
-            return groups
-
-        cur_gr = self.group
-        groups.insert(0, cur_gr)
-        while 1:
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            groups.insert(0, gr)
-
-        return groups
-
-    @property
-    def groups_and_repo(self):
-        return self.groups_with_parents, self.just_name
-
-    @LazyProperty
-    def repo_path(self):
-        """
-        Returns base full path for that repository means where it actually
-        exists on a filesystem
-        """
-        q = Session().query(Ui).filter(Ui.ui_key ==
-                                              Repository.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def repo_full_path(self):
-        p = [self.repo_path]
-        # we need to split the name by / since this is how we store the
-        # names in the database, but that eventually needs to be converted
-        # into a valid system path
-        p += self.repo_name.split(Repository.url_sep())
-        return os.path.join(*p)
-
-    @property
-    def cache_keys(self):
-        """
-        Returns associated cache keys for that repo
-        """
-        return CacheInvalidation.query()\
-            .filter(CacheInvalidation.cache_args == self.repo_name)\
-            .order_by(CacheInvalidation.cache_key)\
-            .all()
-
-    def get_new_name(self, repo_name):
-        """
-        returns new full repository name based on assigned group and new new
-
-        :param group_name:
-        """
-        path_prefix = self.group.full_path_splitted if self.group else []
-        return Repository.url_sep().join(path_prefix + [repo_name])
-
-    @property
-    def _ui(self):
-        """
-        Creates an db based ui object for this repository
-        """
-        from kallithea.lib.utils import make_ui
-        return make_ui('db', clear_session=False)
-
-    @classmethod
-    def inject_ui(cls, repo, extras={}):
-        from kallithea.lib.vcs.backends.hg import MercurialRepository
-        from kallithea.lib.vcs.backends.git import GitRepository
-        required = (MercurialRepository, GitRepository)
-        if not isinstance(repo, required):
-            raise Exception('repo must be instance of %s' % (','.join(required)))
-
-        # inject ui extra param to log this action via push logger
-        for k, v in extras.items():
-            repo._repo.ui.setconfig('extras', k, v)
-
-    @classmethod
-    def is_valid(cls, repo_name):
-        """
-        returns True if given repo name is a valid filesystem repository
-
-        :param cls:
-        :param repo_name:
-        """
-        from kallithea.lib.utils import is_valid_repo
-
-        return is_valid_repo(repo_name, cls.base_path())
-
-    def get_api_data(self):
-        """
-        Common function for generating repo api data
-
-        """
-        repo = self
-        data = dict(
-            repo_id=repo.repo_id,
-            repo_name=repo.repo_name,
-            repo_type=repo.repo_type,
-            clone_uri=repo.clone_uri,
-            private=repo.private,
-            created_on=repo.created_on,
-            description=repo.description,
-            landing_rev=repo.landing_rev,
-            owner=repo.user.username,
-            fork_of=repo.fork.repo_name if repo.fork else None
-        )
-
-        return data
-
-    @classmethod
-    def lock(cls, repo, user_id):
-        repo.locked = [user_id, time.time()]
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def unlock(cls, repo):
-        repo.locked = None
-        Session().add(repo)
-        Session().commit()
-
-    @property
-    def last_db_change(self):
-        return self.updated_on
-
-    #==========================================================================
-    # SCM PROPERTIES
-    #==========================================================================
-
-    def get_changeset(self, rev=None):
-        return get_changeset_safe(self.scm_instance, rev)
-
-    def get_landing_changeset(self):
-        """
-        Returns landing changeset, or if that doesn't exist returns the tip
-        """
-        cs = self.get_changeset(self.landing_rev) or self.get_changeset()
-        return cs
-
-    def update_last_change(self, last_change=None):
-        if last_change is None:
-            last_change = datetime.datetime.now()
-        if self.updated_on is None or self.updated_on != last_change:
-            log.debug('updated repo %s with new date %s', self, last_change)
-            self.updated_on = last_change
-            Session().add(self)
-            Session().commit()
-
-    @property
-    def tip(self):
-        return self.get_changeset('tip')
-
-    @property
-    def author(self):
-        return self.tip.author
-
-    @property
-    def last_change(self):
-        return self.scm_instance.last_change
-
-    def get_comments(self, revisions=None):
-        """
-        Returns comments for this repository grouped by revisions
-
-        :param revisions: filter query by revisions only
-        """
-        cmts = ChangesetComment.query()\
-            .filter(ChangesetComment.repo == self)
-        if revisions:
-            cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
-        grouped = defaultdict(list)
-        for cmt in cmts.all():
-            grouped[cmt.revision].append(cmt)
-        return grouped
-
-    def statuses(self, revisions=None):
-        """
-        Returns statuses for this repository
-
-        :param revisions: list of revisions to get statuses for
-        :type revisions: list
-        """
-
-        statuses = ChangesetStatus.query()\
-            .filter(ChangesetStatus.repo == self)\
-            .filter(ChangesetStatus.version == 0)
-        if revisions:
-            statuses = statuses.filter(ChangesetStatus.revision.in_(revisions))
-        grouped = {}
-
-        #maybe we have open new pullrequest without a status ?
-        stat = ChangesetStatus.STATUS_UNDER_REVIEW
-        status_lbl = ChangesetStatus.get_status_lbl(stat)
-        for pr in PullRequest.query().filter(PullRequest.org_repo == self).all():
-            for rev in pr.revisions:
-                pr_id = pr.pull_request_id
-                pr_repo = pr.other_repo.repo_name
-                grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
-
-        for stat in statuses.all():
-            pr_id = pr_repo = None
-            if stat.pull_request:
-                pr_id = stat.pull_request.pull_request_id
-                pr_repo = stat.pull_request.other_repo.repo_name
-            grouped[stat.revision] = [str(stat.status), stat.status_lbl,
-                                      pr_id, pr_repo]
-        return grouped
-
-    #==========================================================================
-    # SCM CACHE INSTANCE
-    #==========================================================================
-
-    @property
-    def invalidate(self):
-        return CacheInvalidation.invalidate(self.repo_name)
-
-    def set_invalidate(self):
-        """
-        set a cache for invalidation for this instance
-        """
-        CacheInvalidation.set_invalidate(repo_name=self.repo_name)
-
-    @LazyProperty
-    def scm_instance(self):
-        import kallithea
-        full_cache = str2bool(kallithea.CONFIG.get('vcs_full_cache'))
-        if full_cache:
-            return self.scm_instance_cached()
-        return self.__get_instance()
-
-    def scm_instance_cached(self, cache_map=None):
-        @cache_region('long_term')
-        def _c(repo_name):
-            return self.__get_instance()
-        rn = self.repo_name
-        log.debug('Getting cached instance of repo')
-
-        if cache_map:
-            # get using prefilled cache_map
-            invalidate_repo = cache_map[self.repo_name]
-            if invalidate_repo:
-                invalidate_repo = (None if invalidate_repo.cache_active
-                                   else invalidate_repo)
-        else:
-            # get from invalidate
-            invalidate_repo = self.invalidate
-
-        if invalidate_repo is not None:
-            region_invalidate(_c, None, rn)
-            # update our cache
-            CacheInvalidation.set_valid(invalidate_repo.cache_key)
-        return _c(rn)
-
-    def __get_instance(self):
-        repo_full_path = self.repo_full_path
-        try:
-            alias = get_scm(repo_full_path)[0]
-            log.debug('Creating instance of %s repository', alias)
-            backend = get_backend(alias)
-        except VCSError:
-            log.error(traceback.format_exc())
-            log.error('Perhaps this repository is in db and not in '
-                      'filesystem run rescan repositories with '
-                      '"destroy old data " option from admin panel')
-            return
-
-        if alias == 'hg':
-
-            repo = backend(safe_str(repo_full_path), create=False,
-                           baseui=self._ui)
-        else:
-            repo = backend(repo_full_path, create=False)
-
-        return repo
-
-
-class RepoGroup(Base, BaseModel):
-    __tablename__ = 'groups'
-    __table_args__ = (
-        UniqueConstraint('group_name', 'group_parent_id'),
-        CheckConstraint('group_id != group_parent_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    __mapper_args__ = {'order_by': 'group_name'}
-
-    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    group_name = Column("group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
-    group_description = Column("group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-
-    parent_group = relationship('RepoGroup', remote_side=group_id)
-
-    def __init__(self, group_name='', parent_group=None):
-        self.group_name = group_name
-        self.parent_group = parent_group
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.group_id,
-                                  self.group_name)
-
-    @classmethod
-    def groups_choices(cls, check_perms=False):
-        from webhelpers.html import literal as _literal
-        from kallithea.model.scm import ScmModel
-        groups = cls.query().all()
-        if check_perms:
-            #filter group user have access to, it's done
-            #magically inside ScmModel based on current user
-            groups = ScmModel().get_repos_groups(groups)
-        repo_groups = [('', '')]
-        sep = ' &raquo; '
-        _name = lambda k: _literal(sep.join(k))
-
-        repo_groups.extend([(x.group_id, _name(x.full_path_splitted))
-                              for x in groups])
-
-        repo_groups = sorted(repo_groups, key=lambda t: t[1].split(sep)[0])
-        return repo_groups
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
-        if case_insensitive:
-            gr = cls.query()\
-                .filter(cls.group_name.ilike(group_name))
-        else:
-            gr = cls.query()\
-                .filter(cls.group_name == group_name)
-        if cache:
-            gr = gr.options(FromCache(
-                            "sql_cache_short",
-                            "get_group_%s" % _hash_key(group_name)
-                            )
-            )
-        return gr.scalar()
-
-    @property
-    def parents(self):
-        parents_recursion_limit = 5
-        groups = []
-        if self.parent_group is None:
-            return groups
-        cur_gr = self.parent_group
-        groups.insert(0, cur_gr)
-        cnt = 0
-        while 1:
-            cnt += 1
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            if cnt == parents_recursion_limit:
-                # this will prevent accidental infinite loops
-                log.error('group nested more than %s',
-                          parents_recursion_limit)
-                break
-
-            groups.insert(0, gr)
-        return groups
-
-    @property
-    def children(self):
-        return RepoGroup.query().filter(RepoGroup.parent_group == self)
-
-    @property
-    def name(self):
-        return self.group_name.split(RepoGroup.url_sep())[-1]
-
-    @property
-    def full_path(self):
-        return self.group_name
-
-    @property
-    def full_path_splitted(self):
-        return self.group_name.split(RepoGroup.url_sep())
-
-    @property
-    def repositories(self):
-        return Repository.query()\
-                .filter(Repository.group == self)\
-                .order_by(Repository.repo_name)
-
-    @property
-    def repositories_recursive_count(self):
-        cnt = self.repositories.count()
-
-        def children_count(group):
-            cnt = 0
-            for child in group.children:
-                cnt += child.repositories.count()
-                cnt += children_count(child)
-            return cnt
-
-        return cnt + children_count(self)
-
-    def recursive_groups_and_repos(self):
-        """
-        Recursive return all groups, with repositories in those groups
-        """
-        all_ = []
-
-        def _get_members(root_gr):
-            for r in root_gr.repositories:
-                all_.append(r)
-            childs = root_gr.children.all()
-            if childs:
-                for gr in childs:
-                    all_.append(gr)
-                    _get_members(gr)
-
-        _get_members(self)
-        return [self] + all_
-
-    def get_new_name(self, group_name):
-        """
-        returns new full group name based on parent and new name
-
-        :param group_name:
-        """
-        path_prefix = (self.parent_group.full_path_splitted if
-                       self.parent_group else [])
-        return RepoGroup.url_sep().join(path_prefix + [group_name])
-
-
-class Permission(Base, BaseModel):
-    __tablename__ = 'permissions'
-    __table_args__ = (
-        Index('p_perm_name_idx', 'permission_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    PERMS = [
-        ('repository.none', _('Repository no access')),
-        ('repository.read', _('Repository read access')),
-        ('repository.write', _('Repository write access')),
-        ('repository.admin', _('Repository admin access')),
-
-        ('group.none', _('Repository Group no access')),
-        ('group.read', _('Repository Group read access')),
-        ('group.write', _('Repository Group write access')),
-        ('group.admin', _('Repository Group admin access')),
-
-        ('hg.admin', _('Kallithea Administrator')),
-        ('hg.create.none', _('Repository creation disabled')),
-        ('hg.create.repository', _('Repository creation enabled')),
-        ('hg.fork.none', _('Repository forking disabled')),
-        ('hg.fork.repository', _('Repository forking enabled')),
-        ('hg.register.none', _('Register disabled')),
-        ('hg.register.manual_activate', _('Register new user with Kallithea '
-                                          'with manual activation')),
-
-        ('hg.register.auto_activate', _('Register new user with Kallithea '
-                                        'with auto activation')),
-    ]
-
-    # defines which permissions are more important higher the more important
-    PERM_WEIGHTS = {
-        'repository.none': 0,
-        'repository.read': 1,
-        'repository.write': 3,
-        'repository.admin': 4,
-
-        'group.none': 0,
-        'group.read': 1,
-        'group.write': 3,
-        'group.admin': 4,
-
-        'hg.fork.none': 0,
-        'hg.fork.repository': 1,
-        'hg.create.none': 0,
-        'hg.create.repository':1
-    }
-
-    DEFAULT_USER_PERMISSIONS = [
-        'repository.read',
-        'group.read',
-        'hg.create.repository',
-        'hg.fork.repository',
-        'hg.register.manual_activate',
-    ]
-
-    permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    permission_name = Column("permission_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    permission_longname = Column("permission_longname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__, self.permission_id, self.permission_name
-        )
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.permission_name == key).scalar()
-
-    @classmethod
-    def get_default_perms(cls, default_user_id):
-        q = Session().query(UserRepoToPerm, Repository, cls)\
-         .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
-         .join((cls, UserRepoToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_group_perms(cls, default_user_id):
-        q = Session().query(UserRepoGroupToPerm, RepoGroup, cls)\
-         .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
-         .join((cls, UserRepoGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-
-class UserRepoToPerm(Base, BaseModel):
-    __tablename__ = 'repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'repository_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    repository = relationship('Repository')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, repository, permission):
-        n = cls()
-        n.user = user
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<user:%s => %s >' % (self.user, self.repository)
-
-
-class UserToPerm(Base, BaseModel):
-    __tablename__ = 'user_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    permission = relationship('Permission', lazy='joined')
-
-
-class UserGroupRepoToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    repository = relationship('Repository')
-
-    @classmethod
-    def create(cls, users_group, repository, permission):
-        n = cls()
-        n.users_group = users_group
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<userGroup:%s => %s >' % (self.users_group, self.repository)
-
-
-class UserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'permission_id',),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-
-class UserRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    group = relationship('RepoGroup')
-    permission = relationship('Permission')
-
-
-class UserGroupRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    group = relationship('RepoGroup')
-
-
-class Statistics(Base, BaseModel):
-    __tablename__ = 'statistics'
-    __table_args__ = (
-         UniqueConstraint('repository_id'),
-         {'extend_existing': True, 'mysql_engine': 'InnoDB',
-          'mysql_charset': 'utf8'}
-    )
-    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
-    stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
-    commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
-    commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
-    languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
-
-    repository = relationship('Repository', single_parent=True)
-
-
-class UserFollowing(Base, BaseModel):
-    __tablename__ = 'user_followings'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'follows_repository_id'),
-        UniqueConstraint('user_id', 'follows_user_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-
-    user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
-
-    follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relationship('Repository', order_by='Repository.repo_name')
-
-    @classmethod
-    def get_repo_followers(cls, repo_id):
-        return cls.query().filter(cls.follows_repo_id == repo_id)
-
-
-class CacheInvalidation(Base, BaseModel):
-    __tablename__ = 'cache_invalidation'
-    __table_args__ = (
-        UniqueConstraint('cache_key'),
-        Index('key_idx', 'cache_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    cache_key = Column("cache_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    cache_args = Column("cache_args", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
-
-    def __init__(self, cache_key, cache_args=''):
-        self.cache_key = cache_key
-        self.cache_args = cache_args
-        self.cache_active = False
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__,
-                                  self.cache_id, self.cache_key)
-
-    @property
-    def prefix(self):
-        _split = self.cache_key.split(self.cache_args, 1)
-        if _split and len(_split) == 2:
-            return _split[0]
-        return ''
-
-    @classmethod
-    def clear_cache(cls):
-        cls.query().delete()
-
-    @classmethod
-    def _get_key(cls, key):
-        """
-        Wrapper for generating a key, together with a prefix
-
-        :param key:
-        """
-        import kallithea
-        prefix = ''
-        org_key = key
-        iid = kallithea.CONFIG.get('instance_id')
-        if iid:
-            prefix = iid
-
-        return "%s%s" % (prefix, key), prefix, org_key
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.cache_key == key).scalar()
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        return cls.query().filter(cls.cache_args == repo_name).all()
-
-    @classmethod
-    def _get_or_create_key(cls, key, repo_name, commit=True):
-        inv_obj = Session().query(cls).filter(cls.cache_key == key).scalar()
-        if not inv_obj:
-            try:
-                inv_obj = CacheInvalidation(key, repo_name)
-                Session().add(inv_obj)
-                if commit:
-                    Session().commit()
-            except Exception:
-                log.error(traceback.format_exc())
-                Session().rollback()
-        return inv_obj
-
-    @classmethod
-    def invalidate(cls, key):
-        """
-        Returns Invalidation object if this given key should be invalidated
-        None otherwise. `cache_active = False` means that this cache
-        state is not valid and needs to be invalidated
-
-        :param key:
-        """
-        repo_name = key
-        repo_name = remove_suffix(repo_name, '_README')
-        repo_name = remove_suffix(repo_name, '_RSS')
-        repo_name = remove_suffix(repo_name, '_ATOM')
-
-        # adds instance prefix
-        key, _prefix, _org_key = cls._get_key(key)
-        inv = cls._get_or_create_key(key, repo_name)
-
-        if inv and inv.cache_active is False:
-            return inv
-
-    @classmethod
-    def set_invalidate(cls, key=None, repo_name=None):
-        """
-        Mark this Cache key for invalidation, either by key or whole
-        cache sets based on repo_name
-
-        :param key:
-        """
-        if key:
-            key, _prefix, _org_key = cls._get_key(key)
-            inv_objs = Session().query(cls).filter(cls.cache_key == key).all()
-        elif repo_name:
-            inv_objs = Session().query(cls).filter(cls.cache_args == repo_name).all()
-
-        log.debug('marking %s key[s] for invalidation based on key=%s,repo_name=%s',
-                  len(inv_objs), key, repo_name)
-        try:
-            for inv_obj in inv_objs:
-                inv_obj.cache_active = False
-                Session().add(inv_obj)
-            Session().commit()
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-
-    @classmethod
-    def set_valid(cls, key):
-        """
-        Mark this cache key as active and currently cached
-
-        :param key:
-        """
-        inv_obj = cls.get_by_key(key)
-        inv_obj.cache_active = True
-        Session().add(inv_obj)
-        Session().commit()
-
-    @classmethod
-    def get_cache_map(cls):
-
-        class cachemapdict(dict):
-
-            def __init__(self, *args, **kwargs):
-                fixkey = kwargs.get('fixkey')
-                if fixkey:
-                    del kwargs['fixkey']
-                self.fixkey = fixkey
-                super(cachemapdict, self).__init__(*args, **kwargs)
-
-            def __getattr__(self, name):
-                key = name
-                if self.fixkey:
-                    key, _prefix, _org_key = cls._get_key(key)
-                if key in self.__dict__:
-                    return self.__dict__[key]
-                else:
-                    return self[key]
-
-            def __getitem__(self, key):
-                if self.fixkey:
-                    key, _prefix, _org_key = cls._get_key(key)
-                try:
-                    return super(cachemapdict, self).__getitem__(key)
-                except KeyError:
-                    return
-
-        cache_map = cachemapdict(fixkey=True)
-        for obj in cls.query().all():
-            cache_map[obj.cache_key] = cachemapdict(obj.get_dict())
-        return cache_map
-
-
-class ChangesetComment(Base, BaseModel):
-    __tablename__ = 'changeset_comments'
-    __table_args__ = (
-        Index('cc_revision_idx', 'revision'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    revision = Column('revision', String(40), nullable=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-    line_no = Column('line_no', Unicode(10), nullable=True)
-    hl_lines = Column('hl_lines', Unicode(512), nullable=True)
-    f_path = Column('f_path', Unicode(1000), nullable=True)
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
-    text = Column('text', UnicodeText(25000), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    @classmethod
-    def get_users(cls, revision=None, pull_request_id=None):
-        """
-        Returns user associated with this ChangesetComment. ie those
-        who actually commented
-
-        :param cls:
-        :param revision:
-        """
-        q = Session().query(User)\
-                .join(ChangesetComment.author)
-        if revision:
-            q = q.filter(cls.revision == revision)
-        elif pull_request_id:
-            q = q.filter(cls.pull_request_id == pull_request_id)
-        return q.all()
-
-
-class ChangesetStatus(Base, BaseModel):
-    __tablename__ = 'changeset_statuses'
-    __table_args__ = (
-        Index('cs_revision_idx', 'revision'),
-        Index('cs_version_idx', 'version'),
-        UniqueConstraint('repo_id', 'revision', 'version'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
-    STATUS_APPROVED = 'approved'
-    STATUS_REJECTED = 'rejected'
-    STATUS_UNDER_REVIEW = 'under_review'
-
-    STATUSES = [
-        (STATUS_NOT_REVIEWED, _("Not Reviewed")),  # (no icon) and default
-        (STATUS_APPROVED, _("Approved")),
-        (STATUS_REJECTED, _("Rejected")),
-        (STATUS_UNDER_REVIEW, _("Under Review")),
-    ]
-
-    changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    revision = Column('revision', String(40), nullable=False)
-    status = Column('status', String(128), nullable=False, default=DEFAULT)
-    changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
-    modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
-    version = Column('version', Integer(), nullable=False, default=0)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    comment = relationship('ChangesetComment', lazy='joined')
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.status, self.author
-        )
-
-    @classmethod
-    def get_status_lbl(cls, value):
-        return dict(cls.STATUSES).get(value)
-
-    @property
-    def status_lbl(self):
-        return ChangesetStatus.get_status_lbl(self.status)
-
-
-class PullRequest(Base, BaseModel):
-    __tablename__ = 'pull_requests'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    STATUS_NEW = u'new'
-    STATUS_OPEN = u'open'
-    STATUS_CLOSED = u'closed'
-
-    pull_request_id = Column('pull_request_id', Integer(), nullable=False, primary_key=True)
-    title = Column('title', Unicode(256), nullable=True)
-    description = Column('description', UnicodeText(10240), nullable=True)
-    status = Column('status', Unicode(256), nullable=False, default=STATUS_NEW)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    _revisions = Column('revisions', UnicodeText(20500))  # 500 revisions max
-    org_repo_id = Column('org_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    org_ref = Column('org_ref', Unicode(256), nullable=False)
-    other_repo_id = Column('other_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    other_ref = Column('other_ref', Unicode(256), nullable=False)
-
-    @hybrid_property
-    def revisions(self):
-        return self._revisions.split(':')
-
-    @revisions.setter
-    def revisions(self, val):
-        self._revisions = ':'.join(val)
-
-    author = relationship('User', lazy='joined')
-    reviewers = relationship('PullRequestReviewers',
-                             cascade="all, delete, delete-orphan")
-    org_repo = relationship('Repository', primaryjoin='PullRequest.org_repo_id==Repository.repo_id')
-    other_repo = relationship('Repository', primaryjoin='PullRequest.other_repo_id==Repository.repo_id')
-    statuses = relationship('ChangesetStatus')
-    comments = relationship('ChangesetComment',
-                             cascade="all, delete, delete-orphan")
-
-    def is_closed(self):
-        return self.status == self.STATUS_CLOSED
-
-    def __json__(self):
-        return dict(
-          revisions=self.revisions
-        )
-
-
-class PullRequestReviewers(Base, BaseModel):
-    __tablename__ = 'pull_request_reviewers'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    def __init__(self, user=None, pull_request=None):
-        self.user = user
-        self.pull_request = pull_request
-
-    pull_requests_reviewers_id = Column('pull_requests_reviewers_id', Integer(), nullable=False, primary_key=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
-
-    user = relationship('User')
-    pull_request = relationship('PullRequest')
-
-
-class Notification(Base, BaseModel):
-    __tablename__ = 'notifications'
-    __table_args__ = (
-        Index('notification_type_idx', 'type'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    TYPE_CHANGESET_COMMENT = u'cs_comment'
-    TYPE_MESSAGE = u'message'
-    TYPE_MENTION = u'mention'
-    TYPE_REGISTRATION = u'registration'
-    TYPE_PULL_REQUEST = u'pull_request'
-    TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
-
-    notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
-    subject = Column('subject', Unicode(512), nullable=True)
-    body = Column('body', UnicodeText(50000), nullable=True)
-    created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    type_ = Column('type', Unicode(256))
-
-    created_by_user = relationship('User')
-    notifications_to_users = relationship('UserNotification', lazy='joined',
-                                          cascade="all, delete, delete-orphan")
-
-    @property
-    def recipients(self):
-        return [x.user for x in UserNotification.query()\
-                .filter(UserNotification.notification == self)\
-                .order_by(UserNotification.user_id.asc()).all()]
-
-    @classmethod
-    def create(cls, created_by, subject, body, recipients, type_=None):
-        if type_ is None:
-            type_ = Notification.TYPE_MESSAGE
-
-        notification = cls()
-        notification.created_by_user = created_by
-        notification.subject = subject
-        notification.body = body
-        notification.type_ = type_
-        notification.created_on = datetime.datetime.now()
-
-        for u in recipients:
-            assoc = UserNotification()
-            assoc.notification = notification
-            u.notifications.append(assoc)
-        Session().add(notification)
-        return notification
-
-    @property
-    def description(self):
-        from kallithea.model.notification import NotificationModel
-        return NotificationModel().make_description(self)
-
-
-class UserNotification(Base, BaseModel):
-    __tablename__ = 'user_to_notification'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'notification_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
-    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
-    read = Column('read', Boolean, default=False)
-    sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
-
-    user = relationship('User', lazy="joined")
-    notification = relationship('Notification', lazy="joined",
-                                order_by=lambda: Notification.created_on.desc(),)
-
-    def mark_as_read(self):
-        self.read = True
-        Session().add(self)
-
-
-class DbMigrateVersion(Base, BaseModel):
-    __tablename__ = 'db_migrate_version'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    repository_id = Column('repository_id', String(250), primary_key=True)
-    repository_path = Column('repository_path', Text)
-    version = Column('version', Integer)
--- a/kallithea/lib/dbmigrate/schema/db_1_5_2.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1962 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate.schema.db_1_5_2
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Database Models for Kallithea <=1.5.X
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Apr 08, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-import os
-import logging
-import datetime
-import traceback
-import hashlib
-import time
-from collections import defaultdict
-
-from sqlalchemy import *
-from sqlalchemy.ext.hybrid import hybrid_property
-from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
-from beaker.cache import cache_region, region_invalidate
-from webob.exc import HTTPNotFound
-
-from pylons.i18n.translation import lazy_ugettext as _
-
-from kallithea.lib.vcs import get_backend
-from kallithea.lib.vcs.utils.helpers import get_scm
-from kallithea.lib.vcs.exceptions import VCSError
-from kallithea.lib.vcs.utils.lazy import LazyProperty
-from kallithea.lib.vcs.backends.base import EmptyChangeset
-
-from kallithea.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
-    safe_unicode, remove_suffix, remove_prefix
-from kallithea.lib.compat import json
-from kallithea.lib.caching_query import FromCache
-
-from kallithea.model.meta import Base, Session
-
-URL_SEP = '/'
-log = logging.getLogger(__name__)
-
-from kallithea import DB_PREFIX
-
-#==============================================================================
-# BASE CLASSES
-#==============================================================================
-
-_hash_key = lambda k: hashlib.md5(safe_str(k)).hexdigest()
-
-
-class BaseModel(object):
-    """
-    Base Model for all classess
-    """
-
-    @classmethod
-    def _get_keys(cls):
-        """return column names for this model """
-        return class_mapper(cls).c.keys()
-
-    def get_dict(self):
-        """
-        return dict with keys and values corresponding
-        to this model data """
-
-        d = {}
-        for k in self._get_keys():
-            d[k] = getattr(self, k)
-
-        # also use __json__() if present to get additional fields
-        _json_attr = getattr(self, '__json__', None)
-        if _json_attr:
-            # update with attributes from __json__
-            if callable(_json_attr):
-                _json_attr = _json_attr()
-            for k, val in _json_attr.iteritems():
-                d[k] = val
-        return d
-
-    def get_appstruct(self):
-        """return list with keys and values tuples corresponding
-        to this model data """
-
-        l = []
-        for k in self._get_keys():
-            l.append((k, getattr(self, k),))
-        return l
-
-    def populate_obj(self, populate_dict):
-        """populate model with data from given populate_dict"""
-
-        for k in self._get_keys():
-            if k in populate_dict:
-                setattr(self, k, populate_dict[k])
-
-    @classmethod
-    def query(cls):
-        return Session().query(cls)
-
-    @classmethod
-    def get(cls, id_):
-        if id_:
-            return cls.query().get(id_)
-
-    @classmethod
-    def get_or_404(cls, id_):
-        try:
-            id_ = int(id_)
-        except (TypeError, ValueError):
-            raise HTTPNotFound
-
-        res = cls.query().get(id_)
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def getAll(cls):
-        return cls.query().all()
-
-    @classmethod
-    def delete(cls, id_):
-        obj = cls.query().get(id_)
-        Session().delete(obj)
-
-    def __repr__(self):
-        if hasattr(self, '__unicode__'):
-            # python repr needs to return str
-            return safe_str(self.__unicode__())
-        return '<DB:%s>' % (self.__class__.__name__)
-
-
-class Setting(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'settings'
-    __table_args__ = (
-        UniqueConstraint('app_settings_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    app_settings_name = Column("app_settings_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_value = Column("app_settings_value", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __init__(self, k='', v=''):
-        self.app_settings_name = k
-        self.app_settings_value = v
-
-    @validates('_app_settings_value')
-    def validate_settings_value(self, key, val):
-        assert type(val) == unicode
-        return val
-
-    @hybrid_property
-    def app_settings_value(self):
-        v = self._app_settings_value
-        if self.app_settings_name in ["ldap_active",
-                                      "default_repo_enable_statistics",
-                                      "default_repo_enable_locking",
-                                      "default_repo_private",
-                                      "default_repo_enable_downloads"]:
-            v = str2bool(v)
-        return v
-
-    @app_settings_value.setter
-    def app_settings_value(self, val):
-        """
-        Setter that will always make sure we use unicode in app_settings_value
-
-        :param val:
-        """
-        self._app_settings_value = safe_unicode(val)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.app_settings_name, self.app_settings_value
-        )
-
-    @classmethod
-    def get_by_name(cls, key):
-        return cls.query()\
-            .filter(cls.app_settings_name == key).scalar()
-
-    @classmethod
-    def get_by_name_or_create(cls, key):
-        res = cls.get_by_name(key)
-        if not res:
-            res = cls(key)
-        return res
-
-    @classmethod
-    def get_app_settings(cls, cache=False):
-
-        ret = cls.query()
-
-        if cache:
-            ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
-
-        if not ret:
-            raise Exception('Could not get application settings !')
-        settings = {}
-        for each in ret:
-            settings[each.app_settings_name] = \
-                each.app_settings_value
-
-        return settings
-
-    @classmethod
-    def get_ldap_settings(cls, cache=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('ldap_')).all()
-        fd = {}
-        for row in ret:
-            fd.update({row.app_settings_name: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_default_repo_settings(cls, cache=False, strip_prefix=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('default_')).all()
-        fd = {}
-        for row in ret:
-            key = row.app_settings_name
-            if strip_prefix:
-                key = remove_prefix(key, prefix='default_')
-            fd.update({key: row.app_settings_value})
-
-        return fd
-
-
-class Ui(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'ui'
-    __table_args__ = (
-        UniqueConstraint('ui_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    HOOK_UPDATE = 'changegroup.update'
-    HOOK_REPO_SIZE = 'changegroup.repo_size'
-    HOOK_PUSH = 'changegroup.push_logger'
-    HOOK_PRE_PUSH = 'prechangegroup.pre_push'
-    HOOK_PULL = 'outgoing.pull_logger'
-    HOOK_PRE_PULL = 'preoutgoing.pre_pull'
-
-    ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    ui_section = Column("ui_section", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_key = Column("ui_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_value = Column("ui_value", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.ui_key == key).scalar()
-
-    @classmethod
-    def get_builtin_hooks(cls):
-        q = cls.query()
-        q = q.filter(cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                     cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                     cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        return q.all()
-
-    @classmethod
-    def get_custom_hooks(cls):
-        q = cls.query()
-        q = q.filter(~cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                      cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                      cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        q = q.filter(cls.ui_section == 'hooks')
-        return q.all()
-
-    @classmethod
-    def get_repos_location(cls):
-        return cls.get_by_key('/').ui_value
-
-    @classmethod
-    def create_or_update_hook(cls, key, val):
-        new_ui = cls.get_by_key(key) or cls()
-        new_ui.ui_section = 'hooks'
-        new_ui.ui_active = True
-        new_ui.ui_key = key
-        new_ui.ui_value = val
-
-        Session().add(new_ui)
-
-    def __repr__(self):
-        return '<DB:%s[%s:%s]>' % (self.__class__.__name__, self.ui_key,
-                                   self.ui_value)
-
-
-class User(Base, BaseModel):
-    __tablename__ = 'users'
-    __table_args__ = (
-        UniqueConstraint('username'), UniqueConstraint('email'),
-        Index('u_username_idx', 'username'),
-        Index('u_email_idx', 'email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    DEFAULT_USER = 'default'
-    DEFAULT_PERMISSIONS = [
-        'hg.register.manual_activate', 'hg.create.repository',
-        'hg.fork.repository', 'repository.read', 'group.read'
-    ]
-    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    password = Column("password", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
-    name = Column("firstname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    lastname = Column("lastname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
-    ldap_dn = Column("ldap_dn", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    api_key = Column("api_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-
-    user_log = relationship('UserLog')
-    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
-
-    repositories = relationship('Repository')
-    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
-    followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
-
-    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
-
-    group_member = relationship('UserGroupMember', cascade='all')
-
-    notifications = relationship('UserNotification', cascade='all')
-    # notifications assigned to this user
-    user_created_notifications = relationship('Notification', cascade='all')
-    # comments created by this user
-    user_comments = relationship('ChangesetComment', cascade='all')
-    #extra emails for this user
-    user_emails = relationship('UserEmailMap', cascade='all')
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-    @property
-    def firstname(self):
-        # alias for future
-        return self.name
-
-    @property
-    def emails(self):
-        other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
-        return [self.email] + [x.email for x in other]
-
-    @property
-    def ip_addresses(self):
-        ret = UserIpMap.query().filter(UserIpMap.user == self).all()
-        return [x.ip_addr for x in ret]
-
-    @property
-    def username_and_name(self):
-        return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
-
-    @property
-    def full_name(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def full_name_or_username(self):
-        return ('%s %s' % (self.firstname, self.lastname)
-                if (self.firstname and self.lastname) else self.username)
-
-    @property
-    def full_contact(self):
-        return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
-
-    @property
-    def short_contact(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def is_admin(self):
-        return self.admin
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                     self.user_id, self.username)
-
-    @classmethod
-    def get_by_username(cls, username, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.username.ilike(username))
-        else:
-            q = cls.query().filter(cls.username == username)
-
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(username)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get_by_api_key(cls, api_key, cache=False):
-        q = cls.query().filter(cls.api_key == api_key)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_api_key_%s" % api_key))
-        return q.scalar()
-
-    @classmethod
-    def get_by_email(cls, email, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.email.ilike(email))
-        else:
-            q = cls.query().filter(cls.email == email)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_email_key_%s" % email))
-
-        ret = q.scalar()
-        if ret is None:
-            q = UserEmailMap.query()
-            # try fetching in alternate email map
-            if case_insensitive:
-                q = q.filter(UserEmailMap.email.ilike(email))
-            else:
-                q = q.filter(UserEmailMap.email == email)
-            q = q.options(joinedload(UserEmailMap.user))
-            if cache:
-                q = q.options(FromCache("sql_cache_short",
-                                        "get_email_map_key_%s" % email))
-            ret = getattr(q.scalar(), 'user', None)
-
-        return ret
-
-    def update_lastlogin(self):
-        """Update user lastlogin"""
-        self.last_login = datetime.datetime.now()
-        Session().add(self)
-        log.debug('updated user %s lastlogin', self.username)
-
-    def get_api_data(self):
-        """
-        Common function for generating user related data for API
-        """
-        user = self
-        data = dict(
-            user_id=user.user_id,
-            username=user.username,
-            firstname=user.name,
-            lastname=user.lastname,
-            email=user.email,
-            emails=user.emails,
-            api_key=user.api_key,
-            active=user.active,
-            admin=user.admin,
-            ldap_dn=user.ldap_dn,
-            last_login=user.last_login,
-            ip_addresses=user.ip_addresses
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-            full_name=self.full_name,
-            full_name_or_username=self.full_name_or_username,
-            short_contact=self.short_contact,
-            full_contact=self.full_contact
-        )
-        data.update(self.get_api_data())
-        return data
-
-
-class UserEmailMap(Base, BaseModel):
-    __tablename__ = 'user_email_map'
-    __table_args__ = (
-        Index('uem_email_idx', 'email'),
-        UniqueConstraint('email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    __mapper_args__ = {}
-
-    email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    user = relationship('User', lazy='joined')
-
-    @validates('_email')
-    def validate_email(self, key, email):
-        # check if this email is not main one
-        main_email = Session().query(User).filter(User.email == email).scalar()
-        if main_email is not None:
-            raise AttributeError('email %s is present is user table' % email)
-        return email
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-
-class UserIpMap(Base, BaseModel):
-    __tablename__ = 'user_ip_map'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'ip_addr'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    __mapper_args__ = {}
-
-    ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    ip_addr = Column("ip_addr", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    user = relationship('User', lazy='joined')
-
-    @classmethod
-    def _get_ip_range(cls, ip_addr):
-        from kallithea.lib import ipaddr
-        net = ipaddr.IPv4Network(ip_addr)
-        return [str(net.network), str(net.broadcast)]
-
-    def __json__(self):
-        return dict(
-          ip_addr=self.ip_addr,
-          ip_range=self._get_ip_range(self.ip_addr)
-        )
-
-
-class UserLog(Base, BaseModel):
-    __tablename__ = 'user_logs'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
-    repository_name = Column("repository_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    user_ip = Column("user_ip", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action = Column("action", UnicodeText(1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
-
-    @property
-    def action_as_day(self):
-        return datetime.date(*self.action_date.timetuple()[:3])
-
-    user = relationship('User')
-    repository = relationship('Repository', cascade='')
-
-
-class UserGroup(Base, BaseModel):
-    __tablename__ = 'users_groups'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_name = Column("users_group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-
-    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
-    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
-    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-
-    def __unicode__(self):
-        return u'<userGroup(%s)>' % (self.users_group_name)
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False,
-                          case_insensitive=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.users_group_name.ilike(group_name))
-        else:
-            q = cls.query().filter(cls.users_group_name == group_name)
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(group_name)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get(cls, users_group_id, cache=False):
-        users_group = cls.query()
-        if cache:
-            users_group = users_group.options(FromCache("sql_cache_short",
-                                    "get_users_group_%s" % users_group_id))
-        return users_group.get(users_group_id)
-
-    def get_api_data(self):
-        users_group = self
-
-        data = dict(
-            users_group_id=users_group.users_group_id,
-            group_name=users_group.users_group_name,
-            active=users_group.users_group_active,
-        )
-
-        return data
-
-
-class UserGroupMember(Base, BaseModel):
-    __tablename__ = 'users_groups_members'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User', lazy='joined')
-    users_group = relationship('UserGroup')
-
-    def __init__(self, gr_id='', u_id=''):
-        self.users_group_id = gr_id
-        self.user_id = u_id
-
-
-class Repository(Base, BaseModel):
-    __tablename__ = 'repositories'
-    __table_args__ = (
-        UniqueConstraint('repo_name'),
-        Index('r_repo_name_idx', 'repo_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repo_name = Column("repo_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    clone_uri = Column("clone_uri", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    repo_type = Column("repo_type", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
-    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
-    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
-    description = Column("description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    landing_rev = Column("landing_revision", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    _locked = Column("locked", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) #JSON data
-
-    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
-
-    user = relationship('User')
-    fork = relationship('Repository', remote_side=repo_id)
-    group = relationship('RepoGroup')
-    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    stats = relationship('Statistics', cascade='all', uselist=False)
-
-    followers = relationship('UserFollowing',
-                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
-                             cascade='all')
-
-    logs = relationship('UserLog')
-    comments = relationship('ChangesetComment', cascade="all, delete, delete-orphan")
-
-    pull_requests_org = relationship('PullRequest',
-                    primaryjoin='PullRequest.org_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    pull_requests_other = relationship('PullRequest',
-                    primaryjoin='PullRequest.other_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
-                                   safe_unicode(self.repo_name))
-
-    @hybrid_property
-    def locked(self):
-        # always should return [user_id, timelocked]
-        if self._locked:
-            _lock_info = self._locked.split(':')
-            return int(_lock_info[0]), _lock_info[1]
-        return [None, None]
-
-    @locked.setter
-    def locked(self, val):
-        if val and isinstance(val, (list, tuple)):
-            self._locked = ':'.join(map(str, val))
-        else:
-            self._locked = None
-
-    @hybrid_property
-    def changeset_cache(self):
-        from kallithea.lib.vcs.backends.base import EmptyChangeset
-        dummy = EmptyChangeset().__json__()
-        if not self._changeset_cache:
-            return dummy
-        try:
-            return json.loads(self._changeset_cache)
-        except TypeError:
-            return dummy
-
-    @changeset_cache.setter
-    def changeset_cache(self, val):
-        try:
-            self._changeset_cache = json.dumps(val)
-        except:
-            log.error(traceback.format_exc())
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def normalize_repo_name(cls, repo_name):
-        """
-        Normalizes os specific repo_name to the format internally stored inside
-        dabatabase using URL_SEP
-
-        :param cls:
-        :param repo_name:
-        """
-        return cls.url_sep().join(repo_name.split(os.sep))
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        q = Session().query(cls).filter(cls.repo_name == repo_name)
-        q = q.options(joinedload(Repository.fork))\
-                .options(joinedload(Repository.user))\
-                .options(joinedload(Repository.group))
-        return q.scalar()
-
-    @classmethod
-    def get_by_full_path(cls, repo_full_path):
-        repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
-        repo_name = cls.normalize_repo_name(repo_name)
-        return cls.get_by_repo_name(repo_name.strip(URL_SEP))
-
-    @classmethod
-    def get_repo_forks(cls, repo_id):
-        return cls.query().filter(Repository.fork_id == repo_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all repos are stored
-
-        :param cls:
-        """
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == cls.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def forks(self):
-        """
-        Return forks of this repo
-        """
-        return Repository.get_repo_forks(self.repo_id)
-
-    @property
-    def parent(self):
-        """
-        Returns fork parent
-        """
-        return self.fork
-
-    @property
-    def just_name(self):
-        return self.repo_name.split(Repository.url_sep())[-1]
-
-    @property
-    def groups_with_parents(self):
-        groups = []
-        if self.group is None:
-            return groups
-
-        cur_gr = self.group
-        groups.insert(0, cur_gr)
-        while 1:
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            groups.insert(0, gr)
-
-        return groups
-
-    @property
-    def groups_and_repo(self):
-        return self.groups_with_parents, self.just_name
-
-    @LazyProperty
-    def repo_path(self):
-        """
-        Returns base full path for that repository means where it actually
-        exists on a filesystem
-        """
-        q = Session().query(Ui).filter(Ui.ui_key ==
-                                              Repository.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def repo_full_path(self):
-        p = [self.repo_path]
-        # we need to split the name by / since this is how we store the
-        # names in the database, but that eventually needs to be converted
-        # into a valid system path
-        p += self.repo_name.split(Repository.url_sep())
-        return os.path.join(*p)
-
-    @property
-    def cache_keys(self):
-        """
-        Returns associated cache keys for that repo
-        """
-        return CacheInvalidation.query()\
-            .filter(CacheInvalidation.cache_args == self.repo_name)\
-            .order_by(CacheInvalidation.cache_key)\
-            .all()
-
-    def get_new_name(self, repo_name):
-        """
-        returns new full repository name based on assigned group and new new
-
-        :param group_name:
-        """
-        path_prefix = self.group.full_path_splitted if self.group else []
-        return Repository.url_sep().join(path_prefix + [repo_name])
-
-    @property
-    def _ui(self):
-        """
-        Creates an db based ui object for this repository
-        """
-        from kallithea.lib.utils import make_ui
-        return make_ui('db', clear_session=False)
-
-    @classmethod
-    def inject_ui(cls, repo, extras={}):
-        from kallithea.lib.vcs.backends.hg import MercurialRepository
-        from kallithea.lib.vcs.backends.git import GitRepository
-        required = (MercurialRepository, GitRepository)
-        if not isinstance(repo, required):
-            raise Exception('repo must be instance of %s' % (','.join(required)))
-
-        # inject ui extra param to log this action via push logger
-        for k, v in extras.items():
-            repo._repo.ui.setconfig('extras', k, v)
-
-    @classmethod
-    def is_valid(cls, repo_name):
-        """
-        returns True if given repo name is a valid filesystem repository
-
-        :param cls:
-        :param repo_name:
-        """
-        from kallithea.lib.utils import is_valid_repo
-
-        return is_valid_repo(repo_name, cls.base_path())
-
-    def get_api_data(self):
-        """
-        Common function for generating repo api data
-
-        """
-        repo = self
-        data = dict(
-            repo_id=repo.repo_id,
-            repo_name=repo.repo_name,
-            repo_type=repo.repo_type,
-            clone_uri=repo.clone_uri,
-            private=repo.private,
-            created_on=repo.created_on,
-            description=repo.description,
-            landing_rev=repo.landing_rev,
-            owner=repo.user.username,
-            fork_of=repo.fork.repo_name if repo.fork else None,
-            enable_statistics=repo.enable_statistics,
-            enable_locking=repo.enable_locking,
-            enable_downloads=repo.enable_downloads,
-            last_changeset=repo.changeset_cache
-        )
-
-        return data
-
-    @classmethod
-    def lock(cls, repo, user_id):
-        repo.locked = [user_id, time.time()]
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def unlock(cls, repo):
-        repo.locked = None
-        Session().add(repo)
-        Session().commit()
-
-    @property
-    def last_db_change(self):
-        return self.updated_on
-
-    def clone_url(self, **override):
-        import kallithea.lib.helpers as h
-        from urlparse import urlparse
-        import urllib
-        parsed_url = urlparse(h.canonical_url('home'))
-        default_clone_uri = '%(scheme)s://%(user)s%(pass)s%(netloc)s%(prefix)s%(path)s'
-        decoded_path = safe_unicode(urllib.unquote(parsed_url.path))
-        args = {
-           'user': '',
-           'pass': '',
-           'scheme': parsed_url.scheme,
-           'netloc': parsed_url.netloc,
-           'prefix': decoded_path,
-           'path': self.repo_name
-        }
-
-        args.update(override)
-        return default_clone_uri % args
-
-    #==========================================================================
-    # SCM PROPERTIES
-    #==========================================================================
-
-    def get_changeset(self, rev=None):
-        return get_changeset_safe(self.scm_instance, rev)
-
-    def get_landing_changeset(self):
-        """
-        Returns landing changeset, or if that doesn't exist returns the tip
-        """
-        cs = self.get_changeset(self.landing_rev) or self.get_changeset()
-        return cs
-
-    def update_changeset_cache(self, cs_cache=None):
-        """
-        Update cache of last changeset for repository, keys should be::
-
-            short_id
-            raw_id
-            revision
-            message
-            date
-            author
-
-        :param cs_cache:
-        """
-        from kallithea.lib.vcs.backends.base import BaseChangeset
-        if cs_cache is None:
-            cs_cache = EmptyChangeset()
-            # use no-cache version here
-            scm_repo = self.scm_instance_no_cache()
-            if scm_repo:
-                cs_cache = scm_repo.get_changeset()
-
-        if isinstance(cs_cache, BaseChangeset):
-            cs_cache = cs_cache.__json__()
-
-        if (cs_cache != self.changeset_cache or not self.changeset_cache):
-            _default = datetime.datetime.fromtimestamp(0)
-            last_change = cs_cache.get('date') or _default
-            log.debug('updated repo %s with new cs cache %s',
-                      self.repo_name, cs_cache)
-            self.updated_on = last_change
-            self.changeset_cache = cs_cache
-            Session().add(self)
-            Session().commit()
-        else:
-            log.debug('Skipping repo:%s already with latest changes',
-                      self.repo_name)
-
-    @property
-    def tip(self):
-        return self.get_changeset('tip')
-
-    @property
-    def author(self):
-        return self.tip.author
-
-    @property
-    def last_change(self):
-        return self.scm_instance.last_change
-
-    def get_comments(self, revisions=None):
-        """
-        Returns comments for this repository grouped by revisions
-
-        :param revisions: filter query by revisions only
-        """
-        cmts = ChangesetComment.query()\
-            .filter(ChangesetComment.repo == self)
-        if revisions:
-            cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
-        grouped = defaultdict(list)
-        for cmt in cmts.all():
-            grouped[cmt.revision].append(cmt)
-        return grouped
-
-    def statuses(self, revisions=None):
-        """
-        Returns statuses for this repository
-
-        :param revisions: list of revisions to get statuses for
-        :type revisions: list
-        """
-
-        statuses = ChangesetStatus.query()\
-            .filter(ChangesetStatus.repo == self)\
-            .filter(ChangesetStatus.version == 0)
-        if revisions:
-            statuses = statuses.filter(ChangesetStatus.revision.in_(revisions))
-        grouped = {}
-
-        #maybe we have open new pullrequest without a status ?
-        stat = ChangesetStatus.STATUS_UNDER_REVIEW
-        status_lbl = ChangesetStatus.get_status_lbl(stat)
-        for pr in PullRequest.query().filter(PullRequest.org_repo == self).all():
-            for rev in pr.revisions:
-                pr_id = pr.pull_request_id
-                pr_repo = pr.other_repo.repo_name
-                grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
-
-        for stat in statuses.all():
-            pr_id = pr_repo = None
-            if stat.pull_request:
-                pr_id = stat.pull_request.pull_request_id
-                pr_repo = stat.pull_request.other_repo.repo_name
-            grouped[stat.revision] = [str(stat.status), stat.status_lbl,
-                                      pr_id, pr_repo]
-        return grouped
-
-    #==========================================================================
-    # SCM CACHE INSTANCE
-    #==========================================================================
-
-    @property
-    def invalidate(self):
-        return CacheInvalidation.invalidate(self.repo_name)
-
-    def set_invalidate(self):
-        """
-        set a cache for invalidation for this instance
-        """
-        CacheInvalidation.set_invalidate(repo_name=self.repo_name)
-
-    def scm_instance_no_cache(self):
-        return self.__get_instance()
-
-    @LazyProperty
-    def scm_instance(self):
-        import kallithea
-        full_cache = str2bool(kallithea.CONFIG.get('vcs_full_cache'))
-        if full_cache:
-            return self.scm_instance_cached()
-        return self.__get_instance()
-
-    def scm_instance_cached(self, cache_map=None):
-        @cache_region('long_term')
-        def _c(repo_name):
-            return self.__get_instance()
-        rn = self.repo_name
-        log.debug('Getting cached instance of repo')
-
-        if cache_map:
-            # get using prefilled cache_map
-            invalidate_repo = cache_map[self.repo_name]
-            if invalidate_repo:
-                invalidate_repo = (None if invalidate_repo.cache_active
-                                   else invalidate_repo)
-        else:
-            # get from invalidate
-            invalidate_repo = self.invalidate
-
-        if invalidate_repo is not None:
-            region_invalidate(_c, None, rn)
-            # update our cache
-            CacheInvalidation.set_valid(invalidate_repo.cache_key)
-        return _c(rn)
-
-    def __get_instance(self):
-        repo_full_path = self.repo_full_path
-        try:
-            alias = get_scm(repo_full_path)[0]
-            log.debug('Creating instance of %s repository', alias)
-            backend = get_backend(alias)
-        except VCSError:
-            log.error(traceback.format_exc())
-            log.error('Perhaps this repository is in db and not in '
-                      'filesystem run rescan repositories with '
-                      '"destroy old data " option from admin panel')
-            return
-
-        if alias == 'hg':
-
-            repo = backend(safe_str(repo_full_path), create=False,
-                           baseui=self._ui)
-        else:
-            repo = backend(repo_full_path, create=False)
-
-        return repo
-
-
-class RepoGroup(Base, BaseModel):
-    __tablename__ = 'groups'
-    __table_args__ = (
-        UniqueConstraint('group_name', 'group_parent_id'),
-        CheckConstraint('group_id != group_parent_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    __mapper_args__ = {'order_by': 'group_name'}
-
-    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    group_name = Column("group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
-    group_description = Column("group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-
-    parent_group = relationship('RepoGroup', remote_side=group_id)
-
-    def __init__(self, group_name='', parent_group=None):
-        self.group_name = group_name
-        self.parent_group = parent_group
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.group_id,
-                                  self.group_name)
-
-    @classmethod
-    def groups_choices(cls, check_perms=False):
-        from webhelpers.html import literal as _literal
-        from kallithea.model.scm import ScmModel
-        groups = cls.query().all()
-        if check_perms:
-            #filter group user have access to, it's done
-            #magically inside ScmModel based on current user
-            groups = ScmModel().get_repos_groups(groups)
-        repo_groups = [('', '')]
-        sep = ' &raquo; '
-        _name = lambda k: _literal(sep.join(k))
-
-        repo_groups.extend([(x.group_id, _name(x.full_path_splitted))
-                              for x in groups])
-
-        repo_groups = sorted(repo_groups, key=lambda t: t[1].split(sep)[0])
-        return repo_groups
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
-        if case_insensitive:
-            gr = cls.query()\
-                .filter(cls.group_name.ilike(group_name))
-        else:
-            gr = cls.query()\
-                .filter(cls.group_name == group_name)
-        if cache:
-            gr = gr.options(FromCache(
-                            "sql_cache_short",
-                            "get_group_%s" % _hash_key(group_name)
-                            )
-            )
-        return gr.scalar()
-
-    @property
-    def parents(self):
-        parents_recursion_limit = 5
-        groups = []
-        if self.parent_group is None:
-            return groups
-        cur_gr = self.parent_group
-        groups.insert(0, cur_gr)
-        cnt = 0
-        while 1:
-            cnt += 1
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            if cnt == parents_recursion_limit:
-                # this will prevent accidental infinite loops
-                log.error('group nested more than %s',
-                          parents_recursion_limit)
-                break
-
-            groups.insert(0, gr)
-        return groups
-
-    @property
-    def children(self):
-        return RepoGroup.query().filter(RepoGroup.parent_group == self)
-
-    @property
-    def name(self):
-        return self.group_name.split(RepoGroup.url_sep())[-1]
-
-    @property
-    def full_path(self):
-        return self.group_name
-
-    @property
-    def full_path_splitted(self):
-        return self.group_name.split(RepoGroup.url_sep())
-
-    @property
-    def repositories(self):
-        return Repository.query()\
-                .filter(Repository.group == self)\
-                .order_by(Repository.repo_name)
-
-    @property
-    def repositories_recursive_count(self):
-        cnt = self.repositories.count()
-
-        def children_count(group):
-            cnt = 0
-            for child in group.children:
-                cnt += child.repositories.count()
-                cnt += children_count(child)
-            return cnt
-
-        return cnt + children_count(self)
-
-    def recursive_groups_and_repos(self):
-        """
-        Recursive return all groups, with repositories in those groups
-        """
-        all_ = []
-
-        def _get_members(root_gr):
-            for r in root_gr.repositories:
-                all_.append(r)
-            childs = root_gr.children.all()
-            if childs:
-                for gr in childs:
-                    all_.append(gr)
-                    _get_members(gr)
-
-        _get_members(self)
-        return [self] + all_
-
-    def get_new_name(self, group_name):
-        """
-        returns new full group name based on parent and new name
-
-        :param group_name:
-        """
-        path_prefix = (self.parent_group.full_path_splitted if
-                       self.parent_group else [])
-        return RepoGroup.url_sep().join(path_prefix + [group_name])
-
-
-class Permission(Base, BaseModel):
-    __tablename__ = 'permissions'
-    __table_args__ = (
-        Index('p_perm_name_idx', 'permission_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    PERMS = [
-        ('repository.none', _('Repository no access')),
-        ('repository.read', _('Repository read access')),
-        ('repository.write', _('Repository write access')),
-        ('repository.admin', _('Repository admin access')),
-
-        ('group.none', _('Repository Group no access')),
-        ('group.read', _('Repository Group read access')),
-        ('group.write', _('Repository Group write access')),
-        ('group.admin', _('Repository Group admin access')),
-
-        ('hg.admin', _('Kallithea Administrator')),
-        ('hg.create.none', _('Repository creation disabled')),
-        ('hg.create.repository', _('Repository creation enabled')),
-        ('hg.fork.none', _('Repository forking disabled')),
-        ('hg.fork.repository', _('Repository forking enabled')),
-        ('hg.register.none', _('Register disabled')),
-        ('hg.register.manual_activate', _('Register new user with Kallithea '
-                                          'with manual activation')),
-
-        ('hg.register.auto_activate', _('Register new user with Kallithea '
-                                        'with auto activation')),
-    ]
-
-    # defines which permissions are more important higher the more important
-    PERM_WEIGHTS = {
-        'repository.none': 0,
-        'repository.read': 1,
-        'repository.write': 3,
-        'repository.admin': 4,
-
-        'group.none': 0,
-        'group.read': 1,
-        'group.write': 3,
-        'group.admin': 4,
-
-        'hg.fork.none': 0,
-        'hg.fork.repository': 1,
-        'hg.create.none': 0,
-        'hg.create.repository':1
-    }
-
-    permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    permission_name = Column("permission_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    permission_longname = Column("permission_longname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__, self.permission_id, self.permission_name
-        )
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.permission_name == key).scalar()
-
-    @classmethod
-    def get_default_perms(cls, default_user_id):
-        q = Session().query(UserRepoToPerm, Repository, cls)\
-         .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
-         .join((cls, UserRepoToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_group_perms(cls, default_user_id):
-        q = Session().query(UserRepoGroupToPerm, RepoGroup, cls)\
-         .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
-         .join((cls, UserRepoGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-
-class UserRepoToPerm(Base, BaseModel):
-    __tablename__ = 'repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'repository_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    repository = relationship('Repository')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, repository, permission):
-        n = cls()
-        n.user = user
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<user:%s => %s >' % (self.user, self.repository)
-
-
-class UserToPerm(Base, BaseModel):
-    __tablename__ = 'user_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    permission = relationship('Permission', lazy='joined')
-
-
-class UserGroupRepoToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    repository = relationship('Repository')
-
-    @classmethod
-    def create(cls, users_group, repository, permission):
-        n = cls()
-        n.users_group = users_group
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<userGroup:%s => %s >' % (self.users_group, self.repository)
-
-
-class UserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'permission_id',),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-
-class UserRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    group = relationship('RepoGroup')
-    permission = relationship('Permission')
-
-
-class UserGroupRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    group = relationship('RepoGroup')
-
-
-class Statistics(Base, BaseModel):
-    __tablename__ = 'statistics'
-    __table_args__ = (
-         UniqueConstraint('repository_id'),
-         {'extend_existing': True, 'mysql_engine': 'InnoDB',
-          'mysql_charset': 'utf8'}
-    )
-    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
-    stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
-    commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
-    commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
-    languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
-
-    repository = relationship('Repository', single_parent=True)
-
-
-class UserFollowing(Base, BaseModel):
-    __tablename__ = 'user_followings'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'follows_repository_id'),
-        UniqueConstraint('user_id', 'follows_user_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-
-    user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
-
-    follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relationship('Repository', order_by='Repository.repo_name')
-
-    @classmethod
-    def get_repo_followers(cls, repo_id):
-        return cls.query().filter(cls.follows_repo_id == repo_id)
-
-
-class CacheInvalidation(Base, BaseModel):
-    __tablename__ = 'cache_invalidation'
-    __table_args__ = (
-        UniqueConstraint('cache_key'),
-        Index('key_idx', 'cache_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    cache_key = Column("cache_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    cache_args = Column("cache_args", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
-
-    def __init__(self, cache_key, cache_args=''):
-        self.cache_key = cache_key
-        self.cache_args = cache_args
-        self.cache_active = False
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__,
-                                  self.cache_id, self.cache_key)
-
-    @property
-    def prefix(self):
-        _split = self.cache_key.split(self.cache_args, 1)
-        if _split and len(_split) == 2:
-            return _split[0]
-        return ''
-
-    @classmethod
-    def clear_cache(cls):
-        cls.query().delete()
-
-    @classmethod
-    def _get_key(cls, key):
-        """
-        Wrapper for generating a key, together with a prefix
-
-        :param key:
-        """
-        import kallithea
-        prefix = ''
-        org_key = key
-        iid = kallithea.CONFIG.get('instance_id')
-        if iid:
-            prefix = iid
-
-        return "%s%s" % (prefix, key), prefix, org_key
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.cache_key == key).scalar()
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        return cls.query().filter(cls.cache_args == repo_name).all()
-
-    @classmethod
-    def _get_or_create_key(cls, key, repo_name, commit=True):
-        inv_obj = Session().query(cls).filter(cls.cache_key == key).scalar()
-        if not inv_obj:
-            try:
-                inv_obj = CacheInvalidation(key, repo_name)
-                Session().add(inv_obj)
-                if commit:
-                    Session().commit()
-            except Exception:
-                log.error(traceback.format_exc())
-                Session().rollback()
-        return inv_obj
-
-    @classmethod
-    def invalidate(cls, key):
-        """
-        Returns Invalidation object if this given key should be invalidated
-        None otherwise. `cache_active = False` means that this cache
-        state is not valid and needs to be invalidated
-
-        :param key:
-        """
-        repo_name = key
-        repo_name = remove_suffix(repo_name, '_README')
-        repo_name = remove_suffix(repo_name, '_RSS')
-        repo_name = remove_suffix(repo_name, '_ATOM')
-
-        # adds instance prefix
-        key, _prefix, _org_key = cls._get_key(key)
-        inv = cls._get_or_create_key(key, repo_name)
-
-        if inv and inv.cache_active is False:
-            return inv
-
-    @classmethod
-    def set_invalidate(cls, key=None, repo_name=None):
-        """
-        Mark this Cache key for invalidation, either by key or whole
-        cache sets based on repo_name
-
-        :param key:
-        """
-        if key:
-            key, _prefix, _org_key = cls._get_key(key)
-            inv_objs = Session().query(cls).filter(cls.cache_key == key).all()
-        elif repo_name:
-            inv_objs = Session().query(cls).filter(cls.cache_args == repo_name).all()
-
-        log.debug('marking %s key[s] for invalidation based on key=%s,repo_name=%s',
-                  len(inv_objs), key, repo_name)
-        try:
-            for inv_obj in inv_objs:
-                inv_obj.cache_active = False
-                Session().add(inv_obj)
-            Session().commit()
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-
-    @classmethod
-    def set_valid(cls, key):
-        """
-        Mark this cache key as active and currently cached
-
-        :param key:
-        """
-        inv_obj = cls.get_by_key(key)
-        inv_obj.cache_active = True
-        Session().add(inv_obj)
-        Session().commit()
-
-    @classmethod
-    def get_cache_map(cls):
-
-        class cachemapdict(dict):
-
-            def __init__(self, *args, **kwargs):
-                fixkey = kwargs.get('fixkey')
-                if fixkey:
-                    del kwargs['fixkey']
-                self.fixkey = fixkey
-                super(cachemapdict, self).__init__(*args, **kwargs)
-
-            def __getattr__(self, name):
-                key = name
-                if self.fixkey:
-                    key, _prefix, _org_key = cls._get_key(key)
-                if key in self.__dict__:
-                    return self.__dict__[key]
-                else:
-                    return self[key]
-
-            def __getitem__(self, key):
-                if self.fixkey:
-                    key, _prefix, _org_key = cls._get_key(key)
-                try:
-                    return super(cachemapdict, self).__getitem__(key)
-                except KeyError:
-                    return
-
-        cache_map = cachemapdict(fixkey=True)
-        for obj in cls.query().all():
-            cache_map[obj.cache_key] = cachemapdict(obj.get_dict())
-        return cache_map
-
-
-class ChangesetComment(Base, BaseModel):
-    __tablename__ = 'changeset_comments'
-    __table_args__ = (
-        Index('cc_revision_idx', 'revision'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    revision = Column('revision', String(40), nullable=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-    line_no = Column('line_no', Unicode(10), nullable=True)
-    hl_lines = Column('hl_lines', Unicode(512), nullable=True)
-    f_path = Column('f_path', Unicode(1000), nullable=True)
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
-    text = Column('text', UnicodeText(25000), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    @classmethod
-    def get_users(cls, revision=None, pull_request_id=None):
-        """
-        Returns user associated with this ChangesetComment. ie those
-        who actually commented
-
-        :param cls:
-        :param revision:
-        """
-        q = Session().query(User)\
-                .join(ChangesetComment.author)
-        if revision:
-            q = q.filter(cls.revision == revision)
-        elif pull_request_id:
-            q = q.filter(cls.pull_request_id == pull_request_id)
-        return q.all()
-
-
-class ChangesetStatus(Base, BaseModel):
-    __tablename__ = 'changeset_statuses'
-    __table_args__ = (
-        Index('cs_revision_idx', 'revision'),
-        Index('cs_version_idx', 'version'),
-        UniqueConstraint('repo_id', 'revision', 'version'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
-    STATUS_APPROVED = 'approved'
-    STATUS_REJECTED = 'rejected'
-    STATUS_UNDER_REVIEW = 'under_review'
-
-    STATUSES = [
-        (STATUS_NOT_REVIEWED, _("Not Reviewed")),  # (no icon) and default
-        (STATUS_APPROVED, _("Approved")),
-        (STATUS_REJECTED, _("Rejected")),
-        (STATUS_UNDER_REVIEW, _("Under Review")),
-    ]
-
-    changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    revision = Column('revision', String(40), nullable=False)
-    status = Column('status', String(128), nullable=False, default=DEFAULT)
-    changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
-    modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
-    version = Column('version', Integer(), nullable=False, default=0)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    comment = relationship('ChangesetComment', lazy='joined')
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.status, self.author
-        )
-
-    @classmethod
-    def get_status_lbl(cls, value):
-        return dict(cls.STATUSES).get(value)
-
-    @property
-    def status_lbl(self):
-        return ChangesetStatus.get_status_lbl(self.status)
-
-
-class PullRequest(Base, BaseModel):
-    __tablename__ = 'pull_requests'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    STATUS_NEW = u'new'
-    STATUS_OPEN = u'open'
-    STATUS_CLOSED = u'closed'
-
-    pull_request_id = Column('pull_request_id', Integer(), nullable=False, primary_key=True)
-    title = Column('title', Unicode(256), nullable=True)
-    description = Column('description', UnicodeText(10240), nullable=True)
-    status = Column('status', Unicode(256), nullable=False, default=STATUS_NEW)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    _revisions = Column('revisions', UnicodeText(20500))  # 500 revisions max
-    org_repo_id = Column('org_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    org_ref = Column('org_ref', Unicode(256), nullable=False)
-    other_repo_id = Column('other_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    other_ref = Column('other_ref', Unicode(256), nullable=False)
-
-    @hybrid_property
-    def revisions(self):
-        return self._revisions.split(':')
-
-    @revisions.setter
-    def revisions(self, val):
-        self._revisions = ':'.join(val)
-
-    @property
-    def org_ref_parts(self):
-        return self.org_ref.split(':')
-
-    @property
-    def other_ref_parts(self):
-        return self.other_ref.split(':')
-
-    author = relationship('User', lazy='joined')
-    reviewers = relationship('PullRequestReviewers',
-                             cascade="all, delete, delete-orphan")
-    org_repo = relationship('Repository', primaryjoin='PullRequest.org_repo_id==Repository.repo_id')
-    other_repo = relationship('Repository', primaryjoin='PullRequest.other_repo_id==Repository.repo_id')
-    statuses = relationship('ChangesetStatus')
-    comments = relationship('ChangesetComment',
-                             cascade="all, delete, delete-orphan")
-
-    def is_closed(self):
-        return self.status == self.STATUS_CLOSED
-
-    def __json__(self):
-        return dict(
-          revisions=self.revisions
-        )
-
-
-class PullRequestReviewers(Base, BaseModel):
-    __tablename__ = 'pull_request_reviewers'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    def __init__(self, user=None, pull_request=None):
-        self.user = user
-        self.pull_request = pull_request
-
-    pull_requests_reviewers_id = Column('pull_requests_reviewers_id', Integer(), nullable=False, primary_key=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
-
-    user = relationship('User')
-    pull_request = relationship('PullRequest')
-
-
-class Notification(Base, BaseModel):
-    __tablename__ = 'notifications'
-    __table_args__ = (
-        Index('notification_type_idx', 'type'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    TYPE_CHANGESET_COMMENT = u'cs_comment'
-    TYPE_MESSAGE = u'message'
-    TYPE_MENTION = u'mention'
-    TYPE_REGISTRATION = u'registration'
-    TYPE_PULL_REQUEST = u'pull_request'
-    TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
-
-    notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
-    subject = Column('subject', Unicode(512), nullable=True)
-    body = Column('body', UnicodeText(50000), nullable=True)
-    created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    type_ = Column('type', Unicode(256))
-
-    created_by_user = relationship('User')
-    notifications_to_users = relationship('UserNotification', lazy='joined',
-                                          cascade="all, delete, delete-orphan")
-
-    @property
-    def recipients(self):
-        return [x.user for x in UserNotification.query()\
-                .filter(UserNotification.notification == self)\
-                .order_by(UserNotification.user_id.asc()).all()]
-
-    @classmethod
-    def create(cls, created_by, subject, body, recipients, type_=None):
-        if type_ is None:
-            type_ = Notification.TYPE_MESSAGE
-
-        notification = cls()
-        notification.created_by_user = created_by
-        notification.subject = subject
-        notification.body = body
-        notification.type_ = type_
-        notification.created_on = datetime.datetime.now()
-
-        for u in recipients:
-            assoc = UserNotification()
-            assoc.notification = notification
-            u.notifications.append(assoc)
-        Session().add(notification)
-        return notification
-
-    @property
-    def description(self):
-        from kallithea.model.notification import NotificationModel
-        return NotificationModel().make_description(self)
-
-
-class UserNotification(Base, BaseModel):
-    __tablename__ = 'user_to_notification'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'notification_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
-    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
-    read = Column('read', Boolean, default=False)
-    sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
-
-    user = relationship('User', lazy="joined")
-    notification = relationship('Notification', lazy="joined",
-                                order_by=lambda: Notification.created_on.desc(),)
-
-    def mark_as_read(self):
-        self.read = True
-        Session().add(self)
-
-
-class DbMigrateVersion(Base, BaseModel):
-    __tablename__ = 'db_migrate_version'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    repository_id = Column('repository_id', String(250), primary_key=True)
-    repository_path = Column('repository_path', Text)
-    version = Column('version', Integer)
--- a/kallithea/lib/dbmigrate/schema/db_1_6_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,2041 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate.schema.db_1_6_0
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Database Models for Kallithea <=1.5.X
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Apr 08, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-import os
-import logging
-import datetime
-import traceback
-import hashlib
-import time
-from collections import defaultdict
-
-from sqlalchemy import *
-from sqlalchemy.ext.hybrid import hybrid_property
-from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
-from beaker.cache import cache_region, region_invalidate
-from webob.exc import HTTPNotFound
-
-from pylons.i18n.translation import lazy_ugettext as _
-
-from kallithea.lib.vcs import get_backend
-from kallithea.lib.vcs.utils.helpers import get_scm
-from kallithea.lib.vcs.exceptions import VCSError
-from kallithea.lib.vcs.utils.lazy import LazyProperty
-from kallithea.lib.vcs.backends.base import EmptyChangeset
-
-from kallithea.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
-    safe_unicode, remove_suffix, remove_prefix, time_to_datetime
-from kallithea.lib.compat import json
-from kallithea.lib.caching_query import FromCache
-
-from kallithea.model.meta import Base, Session
-
-URL_SEP = '/'
-log = logging.getLogger(__name__)
-
-from kallithea import DB_PREFIX
-
-#==============================================================================
-# BASE CLASSES
-#==============================================================================
-
-_hash_key = lambda k: hashlib.md5(safe_str(k)).hexdigest()
-
-
-class BaseModel(object):
-    """
-    Base Model for all classess
-    """
-
-    @classmethod
-    def _get_keys(cls):
-        """return column names for this model """
-        return class_mapper(cls).c.keys()
-
-    def get_dict(self):
-        """
-        return dict with keys and values corresponding
-        to this model data """
-
-        d = {}
-        for k in self._get_keys():
-            d[k] = getattr(self, k)
-
-        # also use __json__() if present to get additional fields
-        _json_attr = getattr(self, '__json__', None)
-        if _json_attr:
-            # update with attributes from __json__
-            if callable(_json_attr):
-                _json_attr = _json_attr()
-            for k, val in _json_attr.iteritems():
-                d[k] = val
-        return d
-
-    def get_appstruct(self):
-        """return list with keys and values tuples corresponding
-        to this model data """
-
-        l = []
-        for k in self._get_keys():
-            l.append((k, getattr(self, k),))
-        return l
-
-    def populate_obj(self, populate_dict):
-        """populate model with data from given populate_dict"""
-
-        for k in self._get_keys():
-            if k in populate_dict:
-                setattr(self, k, populate_dict[k])
-
-    @classmethod
-    def query(cls):
-        return Session().query(cls)
-
-    @classmethod
-    def get(cls, id_):
-        if id_:
-            return cls.query().get(id_)
-
-    @classmethod
-    def get_or_404(cls, id_):
-        try:
-            id_ = int(id_)
-        except (TypeError, ValueError):
-            raise HTTPNotFound
-
-        res = cls.query().get(id_)
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def getAll(cls):
-        return cls.query().all()
-
-    @classmethod
-    def delete(cls, id_):
-        obj = cls.query().get(id_)
-        Session().delete(obj)
-
-    def __repr__(self):
-        if hasattr(self, '__unicode__'):
-            # python repr needs to return str
-            return safe_str(self.__unicode__())
-        return '<DB:%s>' % (self.__class__.__name__)
-
-
-class Setting(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'settings'
-    __table_args__ = (
-        UniqueConstraint('app_settings_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    app_settings_name = Column("app_settings_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_value = Column("app_settings_value", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __init__(self, k='', v=''):
-        self.app_settings_name = k
-        self.app_settings_value = v
-
-    @validates('_app_settings_value')
-    def validate_settings_value(self, key, val):
-        assert type(val) == unicode
-        return val
-
-    @hybrid_property
-    def app_settings_value(self):
-        v = self._app_settings_value
-        if self.app_settings_name in ["ldap_active",
-                                      "default_repo_enable_statistics",
-                                      "default_repo_enable_locking",
-                                      "default_repo_private",
-                                      "default_repo_enable_downloads"]:
-            v = str2bool(v)
-        return v
-
-    @app_settings_value.setter
-    def app_settings_value(self, val):
-        """
-        Setter that will always make sure we use unicode in app_settings_value
-
-        :param val:
-        """
-        self._app_settings_value = safe_unicode(val)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.app_settings_name, self.app_settings_value
-        )
-
-    @classmethod
-    def get_by_name(cls, key):
-        return cls.query()\
-            .filter(cls.app_settings_name == key).scalar()
-
-    @classmethod
-    def get_by_name_or_create(cls, key):
-        res = cls.get_by_name(key)
-        if not res:
-            res = cls(key)
-        return res
-
-    @classmethod
-    def get_app_settings(cls, cache=False):
-
-        ret = cls.query()
-
-        if cache:
-            ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
-
-        if not ret:
-            raise Exception('Could not get application settings !')
-        settings = {}
-        for each in ret:
-            settings[each.app_settings_name] = \
-                each.app_settings_value
-
-        return settings
-
-    @classmethod
-    def get_ldap_settings(cls, cache=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('ldap_')).all()
-        fd = {}
-        for row in ret:
-            fd.update({row.app_settings_name: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_default_repo_settings(cls, cache=False, strip_prefix=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('default_')).all()
-        fd = {}
-        for row in ret:
-            key = row.app_settings_name
-            if strip_prefix:
-                key = remove_prefix(key, prefix='default_')
-            fd.update({key: row.app_settings_value})
-
-        return fd
-
-
-class Ui(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'ui'
-    __table_args__ = (
-        UniqueConstraint('ui_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    HOOK_UPDATE = 'changegroup.update'
-    HOOK_REPO_SIZE = 'changegroup.repo_size'
-    HOOK_PUSH = 'changegroup.push_logger'
-    HOOK_PRE_PUSH = 'prechangegroup.pre_push'
-    HOOK_PULL = 'outgoing.pull_logger'
-    HOOK_PRE_PULL = 'preoutgoing.pre_pull'
-
-    ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    ui_section = Column("ui_section", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_key = Column("ui_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_value = Column("ui_value", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.ui_key == key).scalar()
-
-    @classmethod
-    def get_builtin_hooks(cls):
-        q = cls.query()
-        q = q.filter(cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                     cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                     cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        return q.all()
-
-    @classmethod
-    def get_custom_hooks(cls):
-        q = cls.query()
-        q = q.filter(~cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                      cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                      cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        q = q.filter(cls.ui_section == 'hooks')
-        return q.all()
-
-    @classmethod
-    def get_repos_location(cls):
-        return cls.get_by_key('/').ui_value
-
-    @classmethod
-    def create_or_update_hook(cls, key, val):
-        new_ui = cls.get_by_key(key) or cls()
-        new_ui.ui_section = 'hooks'
-        new_ui.ui_active = True
-        new_ui.ui_key = key
-        new_ui.ui_value = val
-
-        Session().add(new_ui)
-
-    def __repr__(self):
-        return '<DB:%s[%s:%s]>' % (self.__class__.__name__, self.ui_key,
-                                   self.ui_value)
-
-
-class User(Base, BaseModel):
-    __tablename__ = 'users'
-    __table_args__ = (
-        UniqueConstraint('username'), UniqueConstraint('email'),
-        Index('u_username_idx', 'username'),
-        Index('u_email_idx', 'email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    DEFAULT_USER = 'default'
-    DEFAULT_PERMISSIONS = [
-        'hg.register.manual_activate', 'hg.create.repository',
-        'hg.fork.repository', 'repository.read', 'group.read'
-    ]
-    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    password = Column("password", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
-    name = Column("firstname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    lastname = Column("lastname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
-    ldap_dn = Column("ldap_dn", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    api_key = Column("api_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-
-    user_log = relationship('UserLog')
-    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
-
-    repositories = relationship('Repository')
-    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
-    followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
-
-    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
-
-    group_member = relationship('UserGroupMember', cascade='all')
-
-    notifications = relationship('UserNotification', cascade='all')
-    # notifications assigned to this user
-    user_created_notifications = relationship('Notification', cascade='all')
-    # comments created by this user
-    user_comments = relationship('ChangesetComment', cascade='all')
-    #extra emails for this user
-    user_emails = relationship('UserEmailMap', cascade='all')
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-    @property
-    def firstname(self):
-        # alias for future
-        return self.name
-
-    @property
-    def emails(self):
-        other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
-        return [self.email] + [x.email for x in other]
-
-    @property
-    def ip_addresses(self):
-        ret = UserIpMap.query().filter(UserIpMap.user == self).all()
-        return [x.ip_addr for x in ret]
-
-    @property
-    def username_and_name(self):
-        return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
-
-    @property
-    def full_name(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def full_name_or_username(self):
-        return ('%s %s' % (self.firstname, self.lastname)
-                if (self.firstname and self.lastname) else self.username)
-
-    @property
-    def full_contact(self):
-        return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
-
-    @property
-    def short_contact(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def is_admin(self):
-        return self.admin
-
-    @property
-    def AuthUser(self):
-        """
-        Returns instance of AuthUser for this user
-        """
-        from kallithea.lib.auth import AuthUser
-        return AuthUser(user_id=self.user_id, api_key=self.api_key,
-                        username=self.username)
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                     self.user_id, self.username)
-
-    @classmethod
-    def get_by_username(cls, username, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.username.ilike(username))
-        else:
-            q = cls.query().filter(cls.username == username)
-
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(username)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get_by_api_key(cls, api_key, cache=False):
-        q = cls.query().filter(cls.api_key == api_key)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_api_key_%s" % api_key))
-        return q.scalar()
-
-    @classmethod
-    def get_by_email(cls, email, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.email.ilike(email))
-        else:
-            q = cls.query().filter(cls.email == email)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_email_key_%s" % email))
-
-        ret = q.scalar()
-        if ret is None:
-            q = UserEmailMap.query()
-            # try fetching in alternate email map
-            if case_insensitive:
-                q = q.filter(UserEmailMap.email.ilike(email))
-            else:
-                q = q.filter(UserEmailMap.email == email)
-            q = q.options(joinedload(UserEmailMap.user))
-            if cache:
-                q = q.options(FromCache("sql_cache_short",
-                                        "get_email_map_key_%s" % email))
-            ret = getattr(q.scalar(), 'user', None)
-
-        return ret
-
-    @classmethod
-    def get_from_cs_author(cls, author):
-        """
-        Tries to get User objects out of commit author string
-
-        :param author:
-        """
-        from kallithea.lib.helpers import email, author_name
-        # Valid email in the attribute passed, see if they're in the system
-        _email = email(author)
-        if _email:
-            user = cls.get_by_email(_email, case_insensitive=True)
-            if user:
-                return user
-        # Maybe we can match by username?
-        _author = author_name(author)
-        user = cls.get_by_username(_author, case_insensitive=True)
-        if user:
-            return user
-
-    def update_lastlogin(self):
-        """Update user lastlogin"""
-        self.last_login = datetime.datetime.now()
-        Session().add(self)
-        log.debug('updated user %s lastlogin', self.username)
-
-    def get_api_data(self):
-        """
-        Common function for generating user related data for API
-        """
-        user = self
-        data = dict(
-            user_id=user.user_id,
-            username=user.username,
-            firstname=user.name,
-            lastname=user.lastname,
-            email=user.email,
-            emails=user.emails,
-            api_key=user.api_key,
-            active=user.active,
-            admin=user.admin,
-            ldap_dn=user.ldap_dn,
-            last_login=user.last_login,
-            ip_addresses=user.ip_addresses
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-            full_name=self.full_name,
-            full_name_or_username=self.full_name_or_username,
-            short_contact=self.short_contact,
-            full_contact=self.full_contact
-        )
-        data.update(self.get_api_data())
-        return data
-
-
-class UserEmailMap(Base, BaseModel):
-    __tablename__ = 'user_email_map'
-    __table_args__ = (
-        Index('uem_email_idx', 'email'),
-        UniqueConstraint('email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    __mapper_args__ = {}
-
-    email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    user = relationship('User', lazy='joined')
-
-    @validates('_email')
-    def validate_email(self, key, email):
-        # check if this email is not main one
-        main_email = Session().query(User).filter(User.email == email).scalar()
-        if main_email is not None:
-            raise AttributeError('email %s is present is user table' % email)
-        return email
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-
-class UserIpMap(Base, BaseModel):
-    __tablename__ = 'user_ip_map'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'ip_addr'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    __mapper_args__ = {}
-
-    ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    ip_addr = Column("ip_addr", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    user = relationship('User', lazy='joined')
-
-    @classmethod
-    def _get_ip_range(cls, ip_addr):
-        from kallithea.lib import ipaddr
-        net = ipaddr.IPNetwork(address=ip_addr)
-        return [str(net.network), str(net.broadcast)]
-
-    def __json__(self):
-        return dict(
-          ip_addr=self.ip_addr,
-          ip_range=self._get_ip_range(self.ip_addr)
-        )
-
-
-class UserLog(Base, BaseModel):
-    __tablename__ = 'user_logs'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
-    repository_name = Column("repository_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    user_ip = Column("user_ip", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action = Column("action", UnicodeText(1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
-
-    @property
-    def action_as_day(self):
-        return datetime.date(*self.action_date.timetuple()[:3])
-
-    user = relationship('User')
-    repository = relationship('Repository', cascade='')
-
-
-class UserGroup(Base, BaseModel):
-    __tablename__ = 'users_groups'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_name = Column("users_group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-
-    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
-    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
-    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-
-    def __unicode__(self):
-        return u'<userGroup(%s)>' % (self.users_group_name)
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False,
-                          case_insensitive=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.users_group_name.ilike(group_name))
-        else:
-            q = cls.query().filter(cls.users_group_name == group_name)
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(group_name)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get(cls, users_group_id, cache=False):
-        users_group = cls.query()
-        if cache:
-            users_group = users_group.options(FromCache("sql_cache_short",
-                                    "get_users_group_%s" % users_group_id))
-        return users_group.get(users_group_id)
-
-    def get_api_data(self):
-        users_group = self
-
-        data = dict(
-            users_group_id=users_group.users_group_id,
-            group_name=users_group.users_group_name,
-            active=users_group.users_group_active,
-        )
-
-        return data
-
-
-class UserGroupMember(Base, BaseModel):
-    __tablename__ = 'users_groups_members'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User', lazy='joined')
-    users_group = relationship('UserGroup')
-
-    def __init__(self, gr_id='', u_id=''):
-        self.users_group_id = gr_id
-        self.user_id = u_id
-
-
-class RepositoryField(Base, BaseModel):
-    __tablename__ = 'repositories_fields'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'field_key'),  # no-multi field
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    PREFIX = 'ex_'  # prefix used in form to not conflict with already existing fields
-
-    repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-    field_key = Column("field_key", String(250, convert_unicode=False, assert_unicode=None))
-    field_label = Column("field_label", String(1024, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_value = Column("field_value", String(10000, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_desc = Column("field_desc", String(1024, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_type = Column("field_type", String(256), nullable=False, unique=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    repository = relationship('Repository')
-
-    @property
-    def field_key_prefixed(self):
-        return 'ex_%s' % self.field_key
-
-    @classmethod
-    def un_prefix_key(cls, key):
-        if key.startswith(cls.PREFIX):
-            return key[len(cls.PREFIX):]
-        return key
-
-    @classmethod
-    def get_by_key_name(cls, key, repo):
-        row = cls.query()\
-                .filter(cls.repository == repo)\
-                .filter(cls.field_key == key).scalar()
-        return row
-
-
-class Repository(Base, BaseModel):
-    __tablename__ = 'repositories'
-    __table_args__ = (
-        UniqueConstraint('repo_name'),
-        Index('r_repo_name_idx', 'repo_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repo_name = Column("repo_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    clone_uri = Column("clone_uri", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    repo_type = Column("repo_type", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
-    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
-    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
-    description = Column("description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    landing_rev = Column("landing_revision", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    _locked = Column("locked", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) #JSON data
-
-    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
-
-    user = relationship('User')
-    fork = relationship('Repository', remote_side=repo_id)
-    group = relationship('RepoGroup')
-    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    stats = relationship('Statistics', cascade='all', uselist=False)
-
-    followers = relationship('UserFollowing',
-                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
-                             cascade='all')
-    extra_fields = relationship('RepositoryField',
-                                cascade="all, delete, delete-orphan")
-
-    logs = relationship('UserLog')
-    comments = relationship('ChangesetComment', cascade="all, delete, delete-orphan")
-
-    pull_requests_org = relationship('PullRequest',
-                    primaryjoin='PullRequest.org_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    pull_requests_other = relationship('PullRequest',
-                    primaryjoin='PullRequest.other_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
-                                   safe_unicode(self.repo_name))
-
-    @hybrid_property
-    def locked(self):
-        # always should return [user_id, timelocked]
-        if self._locked:
-            _lock_info = self._locked.split(':')
-            return int(_lock_info[0]), _lock_info[1]
-        return [None, None]
-
-    @locked.setter
-    def locked(self, val):
-        if val and isinstance(val, (list, tuple)):
-            self._locked = ':'.join(map(str, val))
-        else:
-            self._locked = None
-
-    @hybrid_property
-    def changeset_cache(self):
-        from kallithea.lib.vcs.backends.base import EmptyChangeset
-        dummy = EmptyChangeset().__json__()
-        if not self._changeset_cache:
-            return dummy
-        try:
-            return json.loads(self._changeset_cache)
-        except TypeError:
-            return dummy
-
-    @changeset_cache.setter
-    def changeset_cache(self, val):
-        try:
-            self._changeset_cache = json.dumps(val)
-        except Exception:
-            log.error(traceback.format_exc())
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def normalize_repo_name(cls, repo_name):
-        """
-        Normalizes os specific repo_name to the format internally stored inside
-        dabatabase using URL_SEP
-
-        :param cls:
-        :param repo_name:
-        """
-        return cls.url_sep().join(repo_name.split(os.sep))
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        q = Session().query(cls).filter(cls.repo_name == repo_name)
-        q = q.options(joinedload(Repository.fork))\
-                .options(joinedload(Repository.user))\
-                .options(joinedload(Repository.group))
-        return q.scalar()
-
-    @classmethod
-    def get_by_full_path(cls, repo_full_path):
-        repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
-        repo_name = cls.normalize_repo_name(repo_name)
-        return cls.get_by_repo_name(repo_name.strip(URL_SEP))
-
-    @classmethod
-    def get_repo_forks(cls, repo_id):
-        return cls.query().filter(Repository.fork_id == repo_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all repos are stored
-
-        :param cls:
-        """
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == cls.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def forks(self):
-        """
-        Return forks of this repo
-        """
-        return Repository.get_repo_forks(self.repo_id)
-
-    @property
-    def parent(self):
-        """
-        Returns fork parent
-        """
-        return self.fork
-
-    @property
-    def just_name(self):
-        return self.repo_name.split(Repository.url_sep())[-1]
-
-    @property
-    def groups_with_parents(self):
-        groups = []
-        if self.group is None:
-            return groups
-
-        cur_gr = self.group
-        groups.insert(0, cur_gr)
-        while 1:
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            groups.insert(0, gr)
-
-        return groups
-
-    @property
-    def groups_and_repo(self):
-        return self.groups_with_parents, self.just_name, self.repo_name
-
-    @LazyProperty
-    def repo_path(self):
-        """
-        Returns base full path for that repository means where it actually
-        exists on a filesystem
-        """
-        q = Session().query(Ui).filter(Ui.ui_key ==
-                                              Repository.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def repo_full_path(self):
-        p = [self.repo_path]
-        # we need to split the name by / since this is how we store the
-        # names in the database, but that eventually needs to be converted
-        # into a valid system path
-        p += self.repo_name.split(Repository.url_sep())
-        return os.path.join(*map(safe_unicode, p))
-
-    @property
-    def cache_keys(self):
-        """
-        Returns associated cache keys for that repo
-        """
-        return CacheInvalidation.query()\
-            .filter(CacheInvalidation.cache_args == self.repo_name)\
-            .order_by(CacheInvalidation.cache_key)\
-            .all()
-
-    def get_new_name(self, repo_name):
-        """
-        returns new full repository name based on assigned group and new new
-
-        :param group_name:
-        """
-        path_prefix = self.group.full_path_splitted if self.group else []
-        return Repository.url_sep().join(path_prefix + [repo_name])
-
-    @property
-    def _ui(self):
-        """
-        Creates an db based ui object for this repository
-        """
-        from kallithea.lib.utils import make_ui
-        return make_ui('db', clear_session=False)
-
-    @classmethod
-    def is_valid(cls, repo_name):
-        """
-        returns True if given repo name is a valid filesystem repository
-
-        :param cls:
-        :param repo_name:
-        """
-        from kallithea.lib.utils import is_valid_repo
-
-        return is_valid_repo(repo_name, cls.base_path())
-
-    def get_api_data(self):
-        """
-        Common function for generating repo api data
-
-        """
-        repo = self
-        data = dict(
-            repo_id=repo.repo_id,
-            repo_name=repo.repo_name,
-            repo_type=repo.repo_type,
-            clone_uri=repo.clone_uri,
-            private=repo.private,
-            created_on=repo.created_on,
-            description=repo.description,
-            landing_rev=repo.landing_rev,
-            owner=repo.user.username,
-            fork_of=repo.fork.repo_name if repo.fork else None,
-            enable_statistics=repo.enable_statistics,
-            enable_locking=repo.enable_locking,
-            enable_downloads=repo.enable_downloads,
-            last_changeset=repo.changeset_cache,
-            locked_by=User.get(self.locked[0]).get_api_data() \
-                if self.locked[0] else None,
-            locked_date=time_to_datetime(self.locked[1]) \
-                if self.locked[1] else None
-        )
-        rc_config = Setting.get_app_settings()
-        repository_fields = str2bool(rc_config.get('repository_fields'))
-        if repository_fields:
-            for f in self.extra_fields:
-                data[f.field_key_prefixed] = f.field_value
-
-        return data
-
-    @classmethod
-    def lock(cls, repo, user_id):
-        repo.locked = [user_id, time.time()]
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def unlock(cls, repo):
-        repo.locked = None
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def getlock(cls, repo):
-        return repo.locked
-
-    @property
-    def last_db_change(self):
-        return self.updated_on
-
-    def clone_url(self, **override):
-        import kallithea.lib.helpers as h
-        from urlparse import urlparse
-        import urllib
-        parsed_url = urlparse(h.canonical_url('home'))
-        default_clone_uri = '%(scheme)s://%(user)s%(pass)s%(netloc)s%(prefix)s%(path)s'
-        decoded_path = safe_unicode(urllib.unquote(parsed_url.path))
-        args = {
-           'user': '',
-           'pass': '',
-           'scheme': parsed_url.scheme,
-           'netloc': parsed_url.netloc,
-           'prefix': decoded_path,
-           'path': self.repo_name
-        }
-
-        args.update(override)
-        return default_clone_uri % args
-
-    #==========================================================================
-    # SCM PROPERTIES
-    #==========================================================================
-
-    def get_changeset(self, rev=None):
-        return get_changeset_safe(self.scm_instance, rev)
-
-    def get_landing_changeset(self):
-        """
-        Returns landing changeset, or if that doesn't exist returns the tip
-        """
-        cs = self.get_changeset(self.landing_rev) or self.get_changeset()
-        return cs
-
-    def update_changeset_cache(self, cs_cache=None):
-        """
-        Update cache of last changeset for repository, keys should be::
-
-            short_id
-            raw_id
-            revision
-            message
-            date
-            author
-
-        :param cs_cache:
-        """
-        from kallithea.lib.vcs.backends.base import BaseChangeset
-        if cs_cache is None:
-            cs_cache = EmptyChangeset()
-            # use no-cache version here
-            scm_repo = self.scm_instance_no_cache()
-            if scm_repo:
-                cs_cache = scm_repo.get_changeset()
-
-        if isinstance(cs_cache, BaseChangeset):
-            cs_cache = cs_cache.__json__()
-
-        if (cs_cache != self.changeset_cache or not self.changeset_cache):
-            _default = datetime.datetime.fromtimestamp(0)
-            last_change = cs_cache.get('date') or _default
-            log.debug('updated repo %s with new cs cache %s',
-                      self.repo_name, cs_cache)
-            self.updated_on = last_change
-            self.changeset_cache = cs_cache
-            Session().add(self)
-            Session().commit()
-        else:
-            log.debug('Skipping repo:%s already with latest changes',
-                      self.repo_name)
-
-    @property
-    def tip(self):
-        return self.get_changeset('tip')
-
-    @property
-    def author(self):
-        return self.tip.author
-
-    @property
-    def last_change(self):
-        return self.scm_instance.last_change
-
-    def get_comments(self, revisions=None):
-        """
-        Returns comments for this repository grouped by revisions
-
-        :param revisions: filter query by revisions only
-        """
-        cmts = ChangesetComment.query()\
-            .filter(ChangesetComment.repo == self)
-        if revisions:
-            cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
-        grouped = defaultdict(list)
-        for cmt in cmts.all():
-            grouped[cmt.revision].append(cmt)
-        return grouped
-
-    def statuses(self, revisions=None):
-        """
-        Returns statuses for this repository
-
-        :param revisions: list of revisions to get statuses for
-        :type revisions: list
-        """
-
-        statuses = ChangesetStatus.query()\
-            .filter(ChangesetStatus.repo == self)\
-            .filter(ChangesetStatus.version == 0)
-        if revisions:
-            statuses = statuses.filter(ChangesetStatus.revision.in_(revisions))
-        grouped = {}
-
-        #maybe we have open new pullrequest without a status ?
-        stat = ChangesetStatus.STATUS_UNDER_REVIEW
-        status_lbl = ChangesetStatus.get_status_lbl(stat)
-        for pr in PullRequest.query().filter(PullRequest.org_repo == self).all():
-            for rev in pr.revisions:
-                pr_id = pr.pull_request_id
-                pr_repo = pr.other_repo.repo_name
-                grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
-
-        for stat in statuses.all():
-            pr_id = pr_repo = None
-            if stat.pull_request:
-                pr_id = stat.pull_request.pull_request_id
-                pr_repo = stat.pull_request.other_repo.repo_name
-            grouped[stat.revision] = [str(stat.status), stat.status_lbl,
-                                      pr_id, pr_repo]
-        return grouped
-
-    def _repo_size(self):
-        from kallithea.lib import helpers as h
-        log.debug('calculating repository size...')
-        return h.format_byte_size(self.scm_instance.size)
-
-    #==========================================================================
-    # SCM CACHE INSTANCE
-    #==========================================================================
-
-    @property
-    def invalidate(self):
-        return CacheInvalidation.invalidate(self.repo_name)
-
-    def set_invalidate(self):
-        """
-        set a cache for invalidation for this instance
-        """
-        CacheInvalidation.set_invalidate(repo_name=self.repo_name)
-
-    def scm_instance_no_cache(self):
-        return self.__get_instance()
-
-    @LazyProperty
-    def scm_instance(self):
-        import kallithea
-        full_cache = str2bool(kallithea.CONFIG.get('vcs_full_cache'))
-        if full_cache:
-            return self.scm_instance_cached()
-        return self.__get_instance()
-
-    def scm_instance_cached(self, cache_map=None):
-        @cache_region('long_term')
-        def _c(repo_name):
-            return self.__get_instance()
-        rn = self.repo_name
-        log.debug('Getting cached instance of repo')
-
-        if cache_map:
-            # get using prefilled cache_map
-            invalidate_repo = cache_map[self.repo_name]
-            if invalidate_repo:
-                invalidate_repo = (None if invalidate_repo.cache_active
-                                   else invalidate_repo)
-        else:
-            # get from invalidate
-            invalidate_repo = self.invalidate
-
-        if invalidate_repo is not None:
-            region_invalidate(_c, None, rn)
-            # update our cache
-            CacheInvalidation.set_valid(invalidate_repo.cache_key)
-        return _c(rn)
-
-    def __get_instance(self):
-        repo_full_path = self.repo_full_path
-        try:
-            alias = get_scm(repo_full_path)[0]
-            log.debug('Creating instance of %s repository from %s',
-                      alias, repo_full_path)
-            backend = get_backend(alias)
-        except VCSError:
-            log.error(traceback.format_exc())
-            log.error('Perhaps this repository is in db and not in '
-                      'filesystem run rescan repositories with '
-                      '"destroy old data " option from admin panel')
-            return
-
-        if alias == 'hg':
-
-            repo = backend(safe_str(repo_full_path), create=False,
-                           baseui=self._ui)
-        else:
-            repo = backend(repo_full_path, create=False)
-
-        return repo
-
-
-class RepoGroup(Base, BaseModel):
-    __tablename__ = 'groups'
-    __table_args__ = (
-        UniqueConstraint('group_name', 'group_parent_id'),
-        CheckConstraint('group_id != group_parent_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    __mapper_args__ = {'order_by': 'group_name'}
-
-    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    group_name = Column("group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
-    group_description = Column("group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-
-    parent_group = relationship('RepoGroup', remote_side=group_id)
-
-    def __init__(self, group_name='', parent_group=None):
-        self.group_name = group_name
-        self.parent_group = parent_group
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.group_id,
-                                  self.group_name)
-
-    @classmethod
-    def groups_choices(cls, groups=None, show_empty_group=True):
-        from webhelpers.html import literal as _literal
-        if not groups:
-            groups = cls.query().all()
-
-        repo_groups = []
-        if show_empty_group:
-            repo_groups = [('-1', '-- %s --' % _('top level'))]
-        sep = ' &raquo; '
-        _name = lambda k: _literal(sep.join(k))
-
-        repo_groups.extend([(x.group_id, _name(x.full_path_splitted))
-                              for x in groups])
-
-        repo_groups = sorted(repo_groups, key=lambda t: t[1].split(sep)[0])
-        return repo_groups
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
-        if case_insensitive:
-            gr = cls.query()\
-                .filter(cls.group_name.ilike(group_name))
-        else:
-            gr = cls.query()\
-                .filter(cls.group_name == group_name)
-        if cache:
-            gr = gr.options(FromCache(
-                            "sql_cache_short",
-                            "get_group_%s" % _hash_key(group_name)
-                            )
-            )
-        return gr.scalar()
-
-    @property
-    def parents(self):
-        parents_recursion_limit = 5
-        groups = []
-        if self.parent_group is None:
-            return groups
-        cur_gr = self.parent_group
-        groups.insert(0, cur_gr)
-        cnt = 0
-        while 1:
-            cnt += 1
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            if cnt == parents_recursion_limit:
-                # this will prevent accidental infinite loops
-                log.error('group nested more than %s',
-                          parents_recursion_limit)
-                break
-
-            groups.insert(0, gr)
-        return groups
-
-    @property
-    def children(self):
-        return RepoGroup.query().filter(RepoGroup.parent_group == self)
-
-    @property
-    def name(self):
-        return self.group_name.split(RepoGroup.url_sep())[-1]
-
-    @property
-    def full_path(self):
-        return self.group_name
-
-    @property
-    def full_path_splitted(self):
-        return self.group_name.split(RepoGroup.url_sep())
-
-    @property
-    def repositories(self):
-        return Repository.query()\
-                .filter(Repository.group == self)\
-                .order_by(Repository.repo_name)
-
-    @property
-    def repositories_recursive_count(self):
-        cnt = self.repositories.count()
-
-        def children_count(group):
-            cnt = 0
-            for child in group.children:
-                cnt += child.repositories.count()
-                cnt += children_count(child)
-            return cnt
-
-        return cnt + children_count(self)
-
-    def _recursive_objects(self, include_repos=True):
-        all_ = []
-
-        def _get_members(root_gr):
-            if include_repos:
-                for r in root_gr.repositories:
-                    all_.append(r)
-            childs = root_gr.children.all()
-            if childs:
-                for gr in childs:
-                    all_.append(gr)
-                    _get_members(gr)
-
-        _get_members(self)
-        return [self] + all_
-
-    def recursive_groups_and_repos(self):
-        """
-        Recursive return all groups, with repositories in those groups
-        """
-        return self._recursive_objects()
-
-    def recursive_groups(self):
-        """
-        Returns all children groups for this group including children of children
-        """
-        return self._recursive_objects(include_repos=False)
-
-    def get_new_name(self, group_name):
-        """
-        returns new full group name based on parent and new name
-
-        :param group_name:
-        """
-        path_prefix = (self.parent_group.full_path_splitted if
-                       self.parent_group else [])
-        return RepoGroup.url_sep().join(path_prefix + [group_name])
-
-
-class Permission(Base, BaseModel):
-    __tablename__ = 'permissions'
-    __table_args__ = (
-        Index('p_perm_name_idx', 'permission_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    PERMS = [
-        ('repository.none', _('Repository no access')),
-        ('repository.read', _('Repository read access')),
-        ('repository.write', _('Repository write access')),
-        ('repository.admin', _('Repository admin access')),
-
-        ('group.none', _('Repository group no access')),
-        ('group.read', _('Repository group read access')),
-        ('group.write', _('Repository group write access')),
-        ('group.admin', _('Repository group admin access')),
-
-        ('hg.admin', _('Kallithea Administrator')),
-        ('hg.create.none', _('Repository creation disabled')),
-        ('hg.create.repository', _('Repository creation enabled')),
-        ('hg.fork.none', _('Repository forking disabled')),
-        ('hg.fork.repository', _('Repository forking enabled')),
-        ('hg.register.none', _('Register disabled')),
-        ('hg.register.manual_activate', _('Register new user with Kallithea '
-                                          'with manual activation')),
-
-        ('hg.register.auto_activate', _('Register new user with Kallithea '
-                                        'with auto activation')),
-    ]
-
-    # defines which permissions are more important higher the more important
-    PERM_WEIGHTS = {
-        'repository.none': 0,
-        'repository.read': 1,
-        'repository.write': 3,
-        'repository.admin': 4,
-
-        'group.none': 0,
-        'group.read': 1,
-        'group.write': 3,
-        'group.admin': 4,
-
-        'hg.fork.none': 0,
-        'hg.fork.repository': 1,
-        'hg.create.none': 0,
-        'hg.create.repository':1
-    }
-
-    permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    permission_name = Column("permission_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    permission_longname = Column("permission_longname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__, self.permission_id, self.permission_name
-        )
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.permission_name == key).scalar()
-
-    @classmethod
-    def get_default_perms(cls, default_user_id):
-        q = Session().query(UserRepoToPerm, Repository, cls)\
-         .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
-         .join((cls, UserRepoToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_group_perms(cls, default_user_id):
-        q = Session().query(UserRepoGroupToPerm, RepoGroup, cls)\
-         .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
-         .join((cls, UserRepoGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-
-class UserRepoToPerm(Base, BaseModel):
-    __tablename__ = 'repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'repository_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    repository = relationship('Repository')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, repository, permission):
-        n = cls()
-        n.user = user
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<user:%s => %s >' % (self.user, self.repository)
-
-
-class UserToPerm(Base, BaseModel):
-    __tablename__ = 'user_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    permission = relationship('Permission', lazy='joined')
-
-
-class UserGroupRepoToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    repository = relationship('Repository')
-
-    @classmethod
-    def create(cls, users_group, repository, permission):
-        n = cls()
-        n.users_group = users_group
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<userGroup:%s => %s >' % (self.users_group, self.repository)
-
-
-class UserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'permission_id',),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-
-class UserRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    group = relationship('RepoGroup')
-    permission = relationship('Permission')
-
-
-class UserGroupRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    group = relationship('RepoGroup')
-
-
-class Statistics(Base, BaseModel):
-    __tablename__ = 'statistics'
-    __table_args__ = (
-         UniqueConstraint('repository_id'),
-         {'extend_existing': True, 'mysql_engine': 'InnoDB',
-          'mysql_charset': 'utf8'}
-    )
-    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
-    stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
-    commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
-    commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
-    languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
-
-    repository = relationship('Repository', single_parent=True)
-
-
-class UserFollowing(Base, BaseModel):
-    __tablename__ = 'user_followings'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'follows_repository_id'),
-        UniqueConstraint('user_id', 'follows_user_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-
-    user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
-
-    follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relationship('Repository', order_by='Repository.repo_name')
-
-    @classmethod
-    def get_repo_followers(cls, repo_id):
-        return cls.query().filter(cls.follows_repo_id == repo_id)
-
-
-class CacheInvalidation(Base, BaseModel):
-    __tablename__ = 'cache_invalidation'
-    __table_args__ = (
-        UniqueConstraint('cache_key'),
-        Index('key_idx', 'cache_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    # cache_id, not used
-    cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    # cache_key as created by _get_cache_key
-    cache_key = Column("cache_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    # cache_args is usually a repo_name, possibly with _README/_RSS/_ATOM suffix
-    cache_args = Column("cache_args", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    # instance sets cache_active True when it is caching, other instances set cache_active to False to invalidate
-    cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
-
-    def __init__(self, cache_key, cache_args=''):
-        self.cache_key = cache_key
-        self.cache_args = cache_args
-        self.cache_active = False
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__,
-                                  self.cache_id, self.cache_key)
-
-    def get_prefix(self):
-        """
-        Guess prefix that might have been used in _get_cache_key to generate self.cache_key .
-        Only used for informational purposes in repo_edit.html .
-        """
-        _split = self.cache_key.split(self.cache_args, 1)
-        if len(_split) == 2:
-            return _split[0]
-        return ''
-
-    @classmethod
-    def _get_cache_key(cls, key):
-        """
-        Wrapper for generating a unique cache key for this instance and "key".
-        """
-        import kallithea
-        prefix = kallithea.CONFIG.get('instance_id', '')
-        return "%s%s" % (prefix, key)
-
-    @classmethod
-    def _get_or_create_inv_obj(cls, key, repo_name, commit=True):
-        inv_obj = Session().query(cls).filter(cls.cache_key == key).scalar()
-        if not inv_obj:
-            try:
-                inv_obj = CacheInvalidation(key, repo_name)
-                Session().add(inv_obj)
-                if commit:
-                    Session().commit()
-            except Exception:
-                log.error(traceback.format_exc())
-                Session().rollback()
-        return inv_obj
-
-    @classmethod
-    def invalidate(cls, key):
-        """
-        Returns Invalidation object if this given key should be invalidated
-        None otherwise. `cache_active = False` means that this cache
-        state is not valid and needs to be invalidated
-
-        :param key:
-        """
-        repo_name = key
-        repo_name = remove_suffix(repo_name, '_README')
-        repo_name = remove_suffix(repo_name, '_RSS')
-        repo_name = remove_suffix(repo_name, '_ATOM')
-
-        cache_key = cls._get_cache_key(key)
-        inv = cls._get_or_create_inv_obj(cache_key, repo_name)
-
-        if inv and not inv.cache_active:
-            return inv
-
-    @classmethod
-    def set_invalidate(cls, key=None, repo_name=None):
-        """
-        Mark this Cache key for invalidation, either by key or whole
-        cache sets based on repo_name
-
-        :param key:
-        """
-        invalidated_keys = []
-        if key:
-            assert not repo_name
-            cache_key = cls._get_cache_key(key)
-            inv_objs = Session().query(cls).filter(cls.cache_key == cache_key).all()
-        else:
-            assert repo_name
-            inv_objs = Session().query(cls).filter(cls.cache_args == repo_name).all()
-
-        try:
-            for inv_obj in inv_objs:
-                inv_obj.cache_active = False
-                log.debug('marking %s key for invalidation based on key=%s,repo_name=%s',
-                  inv_obj, key, safe_str(repo_name))
-                invalidated_keys.append(inv_obj.cache_key)
-                Session().add(inv_obj)
-            Session().commit()
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-        return invalidated_keys
-
-    @classmethod
-    def set_valid(cls, key):
-        """
-        Mark this cache key as active and currently cached
-
-        :param key:
-        """
-        inv_obj = cls.query().filter(cls.cache_key == key).scalar()
-        inv_obj.cache_active = True
-        Session().add(inv_obj)
-        Session().commit()
-
-    @classmethod
-    def get_cache_map(cls):
-
-        class cachemapdict(dict):
-
-            def __init__(self, *args, **kwargs):
-                self.fixkey = kwargs.pop('fixkey', False)
-                super(cachemapdict, self).__init__(*args, **kwargs)
-
-            def __getattr__(self, name):
-                cache_key = name
-                if self.fixkey:
-                    cache_key = cls._get_cache_key(name)
-                if cache_key in self.__dict__:
-                    return self.__dict__[cache_key]
-                else:
-                    return self[cache_key]
-
-            def __getitem__(self, name):
-                cache_key = name
-                if self.fixkey:
-                    cache_key = cls._get_cache_key(name)
-                try:
-                    return super(cachemapdict, self).__getitem__(cache_key)
-                except KeyError:
-                    return None
-
-        cache_map = cachemapdict(fixkey=True)
-        for obj in cls.query().all():
-            cache_map[obj.cache_key] = cachemapdict(obj.get_dict())
-        return cache_map
-
-
-class ChangesetComment(Base, BaseModel):
-    __tablename__ = 'changeset_comments'
-    __table_args__ = (
-        Index('cc_revision_idx', 'revision'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    revision = Column('revision', String(40), nullable=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-    line_no = Column('line_no', Unicode(10), nullable=True)
-    hl_lines = Column('hl_lines', Unicode(512), nullable=True)
-    f_path = Column('f_path', Unicode(1000), nullable=True)
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
-    text = Column('text', UnicodeText(25000), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    @classmethod
-    def get_users(cls, revision=None, pull_request_id=None):
-        """
-        Returns user associated with this ChangesetComment. ie those
-        who actually commented
-
-        :param cls:
-        :param revision:
-        """
-        q = Session().query(User)\
-                .join(ChangesetComment.author)
-        if revision:
-            q = q.filter(cls.revision == revision)
-        elif pull_request_id:
-            q = q.filter(cls.pull_request_id == pull_request_id)
-        return q.all()
-
-
-class ChangesetStatus(Base, BaseModel):
-    __tablename__ = 'changeset_statuses'
-    __table_args__ = (
-        Index('cs_revision_idx', 'revision'),
-        Index('cs_version_idx', 'version'),
-        UniqueConstraint('repo_id', 'revision', 'version'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
-    STATUS_APPROVED = 'approved'
-    STATUS_REJECTED = 'rejected'
-    STATUS_UNDER_REVIEW = 'under_review'
-
-    STATUSES = [
-        (STATUS_NOT_REVIEWED, _("Not Reviewed")),  # (no icon) and default
-        (STATUS_APPROVED, _("Approved")),
-        (STATUS_REJECTED, _("Rejected")),
-        (STATUS_UNDER_REVIEW, _("Under Review")),
-    ]
-
-    changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    revision = Column('revision', String(40), nullable=False)
-    status = Column('status', String(128), nullable=False, default=DEFAULT)
-    changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
-    modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
-    version = Column('version', Integer(), nullable=False, default=0)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    comment = relationship('ChangesetComment', lazy='joined')
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.status, self.author
-        )
-
-    @classmethod
-    def get_status_lbl(cls, value):
-        return dict(cls.STATUSES).get(value)
-
-    @property
-    def status_lbl(self):
-        return ChangesetStatus.get_status_lbl(self.status)
-
-
-class PullRequest(Base, BaseModel):
-    __tablename__ = 'pull_requests'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    STATUS_NEW = u'new'
-    STATUS_OPEN = u'open'
-    STATUS_CLOSED = u'closed'
-
-    pull_request_id = Column('pull_request_id', Integer(), nullable=False, primary_key=True)
-    title = Column('title', Unicode(256), nullable=True)
-    description = Column('description', UnicodeText(10240), nullable=True)
-    status = Column('status', Unicode(256), nullable=False, default=STATUS_NEW)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    _revisions = Column('revisions', UnicodeText(20500))  # 500 revisions max
-    org_repo_id = Column('org_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    org_ref = Column('org_ref', Unicode(256), nullable=False)
-    other_repo_id = Column('other_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    other_ref = Column('other_ref', Unicode(256), nullable=False)
-
-    @hybrid_property
-    def revisions(self):
-        return self._revisions.split(':')
-
-    @revisions.setter
-    def revisions(self, val):
-        self._revisions = ':'.join(val)
-
-    @property
-    def org_ref_parts(self):
-        return self.org_ref.split(':')
-
-    @property
-    def other_ref_parts(self):
-        return self.other_ref.split(':')
-
-    author = relationship('User', lazy='joined')
-    reviewers = relationship('PullRequestReviewers',
-                             cascade="all, delete, delete-orphan")
-    org_repo = relationship('Repository', primaryjoin='PullRequest.org_repo_id==Repository.repo_id')
-    other_repo = relationship('Repository', primaryjoin='PullRequest.other_repo_id==Repository.repo_id')
-    statuses = relationship('ChangesetStatus')
-    comments = relationship('ChangesetComment',
-                             cascade="all, delete, delete-orphan")
-
-    def is_closed(self):
-        return self.status == self.STATUS_CLOSED
-
-    @property
-    def last_review_status(self):
-        return self.statuses[-1].status if self.statuses else ''
-
-    def __json__(self):
-        return dict(
-          revisions=self.revisions
-        )
-
-
-class PullRequestReviewers(Base, BaseModel):
-    __tablename__ = 'pull_request_reviewers'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    def __init__(self, user=None, pull_request=None):
-        self.user = user
-        self.pull_request = pull_request
-
-    pull_requests_reviewers_id = Column('pull_requests_reviewers_id', Integer(), nullable=False, primary_key=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
-
-    user = relationship('User')
-    pull_request = relationship('PullRequest')
-
-
-class Notification(Base, BaseModel):
-    __tablename__ = 'notifications'
-    __table_args__ = (
-        Index('notification_type_idx', 'type'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    TYPE_CHANGESET_COMMENT = u'cs_comment'
-    TYPE_MESSAGE = u'message'
-    TYPE_MENTION = u'mention'
-    TYPE_REGISTRATION = u'registration'
-    TYPE_PULL_REQUEST = u'pull_request'
-    TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
-
-    notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
-    subject = Column('subject', Unicode(512), nullable=True)
-    body = Column('body', UnicodeText(50000), nullable=True)
-    created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    type_ = Column('type', Unicode(256))
-
-    created_by_user = relationship('User')
-    notifications_to_users = relationship('UserNotification', lazy='joined',
-                                          cascade="all, delete, delete-orphan")
-
-    @property
-    def recipients(self):
-        return [x.user for x in UserNotification.query()\
-                .filter(UserNotification.notification == self)\
-                .order_by(UserNotification.user_id.asc()).all()]
-
-    @classmethod
-    def create(cls, created_by, subject, body, recipients, type_=None):
-        if type_ is None:
-            type_ = Notification.TYPE_MESSAGE
-
-        notification = cls()
-        notification.created_by_user = created_by
-        notification.subject = subject
-        notification.body = body
-        notification.type_ = type_
-        notification.created_on = datetime.datetime.now()
-
-        for u in recipients:
-            assoc = UserNotification()
-            assoc.notification = notification
-            u.notifications.append(assoc)
-        Session().add(notification)
-        return notification
-
-    @property
-    def description(self):
-        from kallithea.model.notification import NotificationModel
-        return NotificationModel().make_description(self)
-
-
-class UserNotification(Base, BaseModel):
-    __tablename__ = 'user_to_notification'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'notification_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
-    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
-    read = Column('read', Boolean, default=False)
-    sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
-
-    user = relationship('User', lazy="joined")
-    notification = relationship('Notification', lazy="joined",
-                                order_by=lambda: Notification.created_on.desc(),)
-
-    def mark_as_read(self):
-        self.read = True
-        Session().add(self)
-
-
-class DbMigrateVersion(Base, BaseModel):
-    __tablename__ = 'db_migrate_version'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    repository_id = Column('repository_id', String(250), primary_key=True)
-    repository_path = Column('repository_path', Text)
-    version = Column('version', Integer)
--- a/kallithea/lib/dbmigrate/schema/db_1_7_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,2223 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate.schema.db_1_7_0
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Database Models for Kallithea
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Apr 08, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-import os
-import time
-import logging
-import datetime
-import traceback
-import hashlib
-import collections
-
-from sqlalchemy import *
-from sqlalchemy.ext.hybrid import hybrid_property
-from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
-from beaker.cache import cache_region, region_invalidate
-from webob.exc import HTTPNotFound
-
-from pylons.i18n.translation import lazy_ugettext as _
-
-from kallithea.lib.vcs import get_backend
-from kallithea.lib.vcs.utils.helpers import get_scm
-from kallithea.lib.vcs.exceptions import VCSError
-from kallithea.lib.vcs.utils.lazy import LazyProperty
-from kallithea.lib.vcs.backends.base import EmptyChangeset
-
-from kallithea.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
-    safe_unicode, remove_prefix, time_to_datetime
-from kallithea.lib.compat import json
-from kallithea.lib.caching_query import FromCache
-
-from kallithea.model.meta import Base, Session
-
-URL_SEP = '/'
-log = logging.getLogger(__name__)
-
-from kallithea import DB_PREFIX
-
-#==============================================================================
-# BASE CLASSES
-#==============================================================================
-
-_hash_key = lambda k: hashlib.md5(safe_str(k)).hexdigest()
-
-
-class BaseModel(object):
-    """
-    Base Model for all classess
-    """
-
-    @classmethod
-    def _get_keys(cls):
-        """return column names for this model """
-        return class_mapper(cls).c.keys()
-
-    def get_dict(self):
-        """
-        return dict with keys and values corresponding
-        to this model data """
-
-        d = {}
-        for k in self._get_keys():
-            d[k] = getattr(self, k)
-
-        # also use __json__() if present to get additional fields
-        _json_attr = getattr(self, '__json__', None)
-        if _json_attr:
-            # update with attributes from __json__
-            if callable(_json_attr):
-                _json_attr = _json_attr()
-            for k, val in _json_attr.iteritems():
-                d[k] = val
-        return d
-
-    def get_appstruct(self):
-        """return list with keys and values tuples corresponding
-        to this model data """
-
-        l = []
-        for k in self._get_keys():
-            l.append((k, getattr(self, k),))
-        return l
-
-    def populate_obj(self, populate_dict):
-        """populate model with data from given populate_dict"""
-
-        for k in self._get_keys():
-            if k in populate_dict:
-                setattr(self, k, populate_dict[k])
-
-    @classmethod
-    def query(cls):
-        return Session().query(cls)
-
-    @classmethod
-    def get(cls, id_):
-        if id_:
-            return cls.query().get(id_)
-
-    @classmethod
-    def get_or_404(cls, id_):
-        try:
-            id_ = int(id_)
-        except (TypeError, ValueError):
-            raise HTTPNotFound
-
-        res = cls.query().get(id_)
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def getAll(cls):
-        # deprecated and left for backward compatibility
-        return cls.get_all()
-
-    @classmethod
-    def get_all(cls):
-        return cls.query().all()
-
-    @classmethod
-    def delete(cls, id_):
-        obj = cls.query().get(id_)
-        Session().delete(obj)
-
-    def __repr__(self):
-        if hasattr(self, '__unicode__'):
-            # python repr needs to return str
-            return safe_str(self.__unicode__())
-        return '<DB:%s>' % (self.__class__.__name__)
-
-
-class Setting(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'settings'
-    __table_args__ = (
-        UniqueConstraint('app_settings_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    app_settings_name = Column("app_settings_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_value = Column("app_settings_value", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __init__(self, k='', v=''):
-        self.app_settings_name = k
-        self.app_settings_value = v
-
-    @validates('_app_settings_value')
-    def validate_settings_value(self, key, val):
-        assert type(val) == unicode
-        return val
-
-    @hybrid_property
-    def app_settings_value(self):
-        v = self._app_settings_value
-        if self.app_settings_name in ["ldap_active",
-                                      "default_repo_enable_statistics",
-                                      "default_repo_enable_locking",
-                                      "default_repo_private",
-                                      "default_repo_enable_downloads"]:
-            v = str2bool(v)
-        return v
-
-    @app_settings_value.setter
-    def app_settings_value(self, val):
-        """
-        Setter that will always make sure we use unicode in app_settings_value
-
-        :param val:
-        """
-        self._app_settings_value = safe_unicode(val)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.app_settings_name, self.app_settings_value
-        )
-
-    @classmethod
-    def get_by_name(cls, key):
-        return cls.query()\
-            .filter(cls.app_settings_name == key).scalar()
-
-    @classmethod
-    def get_by_name_or_create(cls, key):
-        res = cls.get_by_name(key)
-        if not res:
-            res = cls(key)
-        return res
-
-    @classmethod
-    def get_app_settings(cls, cache=False):
-
-        ret = cls.query()
-
-        if cache:
-            ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
-
-        if not ret:
-            raise Exception('Could not get application settings !')
-        settings = {}
-        for each in ret:
-            settings[each.app_settings_name] = \
-                each.app_settings_value
-
-        return settings
-
-    @classmethod
-    def get_ldap_settings(cls, cache=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('ldap_')).all()
-        fd = {}
-        for row in ret:
-            fd.update({row.app_settings_name: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_default_repo_settings(cls, cache=False, strip_prefix=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('default_')).all()
-        fd = {}
-        for row in ret:
-            key = row.app_settings_name
-            if strip_prefix:
-                key = remove_prefix(key, prefix='default_')
-            fd.update({key: row.app_settings_value})
-
-        return fd
-
-
-class Ui(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'ui'
-    __table_args__ = (
-        UniqueConstraint('ui_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    HOOK_UPDATE = 'changegroup.update'
-    HOOK_REPO_SIZE = 'changegroup.repo_size'
-    HOOK_PUSH = 'changegroup.push_logger'
-    HOOK_PRE_PUSH = 'prechangegroup.pre_push'
-    HOOK_PULL = 'outgoing.pull_logger'
-    HOOK_PRE_PULL = 'preoutgoing.pre_pull'
-
-    ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    ui_section = Column("ui_section", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_key = Column("ui_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_value = Column("ui_value", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.ui_key == key).scalar()
-
-    @classmethod
-    def get_builtin_hooks(cls):
-        q = cls.query()
-        q = q.filter(cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                     cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                     cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        return q.all()
-
-    @classmethod
-    def get_custom_hooks(cls):
-        q = cls.query()
-        q = q.filter(~cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                      cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                      cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        q = q.filter(cls.ui_section == 'hooks')
-        return q.all()
-
-    @classmethod
-    def get_repos_location(cls):
-        return cls.get_by_key('/').ui_value
-
-    @classmethod
-    def create_or_update_hook(cls, key, val):
-        new_ui = cls.get_by_key(key) or cls()
-        new_ui.ui_section = 'hooks'
-        new_ui.ui_active = True
-        new_ui.ui_key = key
-        new_ui.ui_value = val
-
-        Session().add(new_ui)
-
-    def __repr__(self):
-        return '<DB:%s[%s:%s]>' % (self.__class__.__name__, self.ui_key,
-                                   self.ui_value)
-
-
-class User(Base, BaseModel):
-    __tablename__ = 'users'
-    __table_args__ = (
-        UniqueConstraint('username'), UniqueConstraint('email'),
-        Index('u_username_idx', 'username'),
-        Index('u_email_idx', 'email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    DEFAULT_USER = 'default'
-
-    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    password = Column("password", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
-    name = Column("firstname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    lastname = Column("lastname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
-    ldap_dn = Column("ldap_dn", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    api_key = Column("api_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-
-    user_log = relationship('UserLog')
-    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
-
-    repositories = relationship('Repository')
-    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
-    followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
-
-    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
-
-    group_member = relationship('UserGroupMember', cascade='all')
-
-    notifications = relationship('UserNotification', cascade='all')
-    # notifications assigned to this user
-    user_created_notifications = relationship('Notification', cascade='all')
-    # comments created by this user
-    user_comments = relationship('ChangesetComment', cascade='all')
-    #extra emails for this user
-    user_emails = relationship('UserEmailMap', cascade='all')
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-    @property
-    def firstname(self):
-        # alias for future
-        return self.name
-
-    @property
-    def emails(self):
-        other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
-        return [self.email] + [x.email for x in other]
-
-    @property
-    def ip_addresses(self):
-        ret = UserIpMap.query().filter(UserIpMap.user == self).all()
-        return [x.ip_addr for x in ret]
-
-    @property
-    def username_and_name(self):
-        return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
-
-    @property
-    def full_name(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def full_name_or_username(self):
-        return ('%s %s' % (self.firstname, self.lastname)
-                if (self.firstname and self.lastname) else self.username)
-
-    @property
-    def full_contact(self):
-        return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
-
-    @property
-    def short_contact(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def is_admin(self):
-        return self.admin
-
-    @property
-    def AuthUser(self):
-        """
-        Returns instance of AuthUser for this user
-        """
-        from kallithea.lib.auth import AuthUser
-        return AuthUser(user_id=self.user_id, api_key=self.api_key,
-                        username=self.username)
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                     self.user_id, self.username)
-
-    @classmethod
-    def get_by_username(cls, username, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.username.ilike(username))
-        else:
-            q = cls.query().filter(cls.username == username)
-
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(username)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get_by_api_key(cls, api_key, cache=False):
-        q = cls.query().filter(cls.api_key == api_key)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_api_key_%s" % api_key))
-        return q.scalar()
-
-    @classmethod
-    def get_by_email(cls, email, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.email.ilike(email))
-        else:
-            q = cls.query().filter(cls.email == email)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_email_key_%s" % email))
-
-        ret = q.scalar()
-        if ret is None:
-            q = UserEmailMap.query()
-            # try fetching in alternate email map
-            if case_insensitive:
-                q = q.filter(UserEmailMap.email.ilike(email))
-            else:
-                q = q.filter(UserEmailMap.email == email)
-            q = q.options(joinedload(UserEmailMap.user))
-            if cache:
-                q = q.options(FromCache("sql_cache_short",
-                                        "get_email_map_key_%s" % email))
-            ret = getattr(q.scalar(), 'user', None)
-
-        return ret
-
-    @classmethod
-    def get_from_cs_author(cls, author):
-        """
-        Tries to get User objects out of commit author string
-
-        :param author:
-        """
-        from kallithea.lib.helpers import email, author_name
-        # Valid email in the attribute passed, see if they're in the system
-        _email = email(author)
-        if _email:
-            user = cls.get_by_email(_email, case_insensitive=True)
-            if user:
-                return user
-        # Maybe we can match by username?
-        _author = author_name(author)
-        user = cls.get_by_username(_author, case_insensitive=True)
-        if user:
-            return user
-
-    def update_lastlogin(self):
-        """Update user lastlogin"""
-        self.last_login = datetime.datetime.now()
-        Session().add(self)
-        log.debug('updated user %s lastlogin', self.username)
-
-    @classmethod
-    def get_first_admin(cls):
-        user = User.query().filter(User.admin == True).first()
-        if user is None:
-            raise Exception('Missing administrative account!')
-        return user
-
-    @classmethod
-    def get_default_user(cls, cache=False):
-        user = User.get_by_username(User.DEFAULT_USER, cache=cache)
-        if user is None:
-            raise Exception('Missing default account!')
-        return user
-
-    def get_api_data(self):
-        """
-        Common function for generating user related data for API
-        """
-        user = self
-        data = dict(
-            user_id=user.user_id,
-            username=user.username,
-            firstname=user.name,
-            lastname=user.lastname,
-            email=user.email,
-            emails=user.emails,
-            api_key=user.api_key,
-            active=user.active,
-            admin=user.admin,
-            ldap_dn=user.ldap_dn,
-            last_login=user.last_login,
-            ip_addresses=user.ip_addresses
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-            full_name=self.full_name,
-            full_name_or_username=self.full_name_or_username,
-            short_contact=self.short_contact,
-            full_contact=self.full_contact
-        )
-        data.update(self.get_api_data())
-        return data
-
-
-class UserEmailMap(Base, BaseModel):
-    __tablename__ = 'user_email_map'
-    __table_args__ = (
-        Index('uem_email_idx', 'email'),
-        UniqueConstraint('email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    __mapper_args__ = {}
-
-    email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    user = relationship('User', lazy='joined')
-
-    @validates('_email')
-    def validate_email(self, key, email):
-        # check if this email is not main one
-        main_email = Session().query(User).filter(User.email == email).scalar()
-        if main_email is not None:
-            raise AttributeError('email %s is present is user table' % email)
-        return email
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-
-class UserIpMap(Base, BaseModel):
-    __tablename__ = 'user_ip_map'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'ip_addr'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    __mapper_args__ = {}
-
-    ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    ip_addr = Column("ip_addr", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    user = relationship('User', lazy='joined')
-
-    @classmethod
-    def _get_ip_range(cls, ip_addr):
-        from kallithea.lib import ipaddr
-        net = ipaddr.IPNetwork(address=ip_addr)
-        return [str(net.network), str(net.broadcast)]
-
-    def __json__(self):
-        return dict(
-          ip_addr=self.ip_addr,
-          ip_range=self._get_ip_range(self.ip_addr)
-        )
-
-
-class UserLog(Base, BaseModel):
-    __tablename__ = 'user_logs'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
-    repository_name = Column("repository_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    user_ip = Column("user_ip", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action = Column("action", UnicodeText(1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.repository_name,
-                                      self.action)
-
-    @property
-    def action_as_day(self):
-        return datetime.date(*self.action_date.timetuple()[:3])
-
-    user = relationship('User')
-    repository = relationship('Repository', cascade='')
-
-
-class UserGroup(Base, BaseModel):
-    __tablename__ = 'users_groups'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_name = Column("users_group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-
-    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
-    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
-    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-    user_user_group_to_perm = relationship('UserUserGroupToPerm ', cascade='all')
-    user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
-
-    user = relationship('User')
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.users_group_id,
-                                      self.users_group_name)
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False,
-                          case_insensitive=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.users_group_name.ilike(group_name))
-        else:
-            q = cls.query().filter(cls.users_group_name == group_name)
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(group_name)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get(cls, users_group_id, cache=False):
-        users_group = cls.query()
-        if cache:
-            users_group = users_group.options(FromCache("sql_cache_short",
-                                    "get_users_group_%s" % users_group_id))
-        return users_group.get(users_group_id)
-
-    def get_api_data(self):
-        users_group = self
-
-        data = dict(
-            users_group_id=users_group.users_group_id,
-            group_name=users_group.users_group_name,
-            active=users_group.users_group_active,
-        )
-
-        return data
-
-
-class UserGroupMember(Base, BaseModel):
-    __tablename__ = 'users_groups_members'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User', lazy='joined')
-    users_group = relationship('UserGroup')
-
-    def __init__(self, gr_id='', u_id=''):
-        self.users_group_id = gr_id
-        self.user_id = u_id
-
-
-class RepositoryField(Base, BaseModel):
-    __tablename__ = 'repositories_fields'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'field_key'),  # no-multi field
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    PREFIX = 'ex_'  # prefix used in form to not conflict with already existing fields
-
-    repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-    field_key = Column("field_key", String(250, convert_unicode=False, assert_unicode=None))
-    field_label = Column("field_label", String(1024, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_value = Column("field_value", String(10000, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_desc = Column("field_desc", String(1024, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_type = Column("field_type", String(256), nullable=False, unique=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    repository = relationship('Repository')
-
-    @property
-    def field_key_prefixed(self):
-        return 'ex_%s' % self.field_key
-
-    @classmethod
-    def un_prefix_key(cls, key):
-        if key.startswith(cls.PREFIX):
-            return key[len(cls.PREFIX):]
-        return key
-
-    @classmethod
-    def get_by_key_name(cls, key, repo):
-        row = cls.query()\
-                .filter(cls.repository == repo)\
-                .filter(cls.field_key == key).scalar()
-        return row
-
-
-class Repository(Base, BaseModel):
-    __tablename__ = 'repositories'
-    __table_args__ = (
-        UniqueConstraint('repo_name'),
-        Index('r_repo_name_idx', 'repo_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repo_name = Column("repo_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    clone_uri = Column("clone_uri", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    repo_type = Column("repo_type", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
-    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
-    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
-    description = Column("description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    landing_rev = Column("landing_revision", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    _locked = Column("locked", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) #JSON data
-
-    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
-
-    user = relationship('User')
-    fork = relationship('Repository', remote_side=repo_id)
-    group = relationship('RepoGroup')
-    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    stats = relationship('Statistics', cascade='all', uselist=False)
-
-    followers = relationship('UserFollowing',
-                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
-                             cascade='all')
-    extra_fields = relationship('RepositoryField',
-                                cascade="all, delete, delete-orphan")
-
-    logs = relationship('UserLog')
-    comments = relationship('ChangesetComment', cascade="all, delete, delete-orphan")
-
-    pull_requests_org = relationship('PullRequest',
-                    primaryjoin='PullRequest.org_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    pull_requests_other = relationship('PullRequest',
-                    primaryjoin='PullRequest.other_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
-                                   safe_unicode(self.repo_name))
-
-    @hybrid_property
-    def locked(self):
-        # always should return [user_id, timelocked]
-        if self._locked:
-            _lock_info = self._locked.split(':')
-            return int(_lock_info[0]), _lock_info[1]
-        return [None, None]
-
-    @locked.setter
-    def locked(self, val):
-        if val and isinstance(val, (list, tuple)):
-            self._locked = ':'.join(map(str, val))
-        else:
-            self._locked = None
-
-    @hybrid_property
-    def changeset_cache(self):
-        from kallithea.lib.vcs.backends.base import EmptyChangeset
-        dummy = EmptyChangeset().__json__()
-        if not self._changeset_cache:
-            return dummy
-        try:
-            return json.loads(self._changeset_cache)
-        except TypeError:
-            return dummy
-
-    @changeset_cache.setter
-    def changeset_cache(self, val):
-        try:
-            self._changeset_cache = json.dumps(val)
-        except Exception:
-            log.error(traceback.format_exc())
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def normalize_repo_name(cls, repo_name):
-        """
-        Normalizes os specific repo_name to the format internally stored inside
-        dabatabase using URL_SEP
-
-        :param cls:
-        :param repo_name:
-        """
-        return cls.url_sep().join(repo_name.split(os.sep))
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        q = Session().query(cls).filter(cls.repo_name == repo_name)
-        q = q.options(joinedload(Repository.fork))\
-                .options(joinedload(Repository.user))\
-                .options(joinedload(Repository.group))
-        return q.scalar()
-
-    @classmethod
-    def get_by_full_path(cls, repo_full_path):
-        repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
-        repo_name = cls.normalize_repo_name(repo_name)
-        return cls.get_by_repo_name(repo_name.strip(URL_SEP))
-
-    @classmethod
-    def get_repo_forks(cls, repo_id):
-        return cls.query().filter(Repository.fork_id == repo_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all repos are stored
-
-        :param cls:
-        """
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == cls.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def forks(self):
-        """
-        Return forks of this repo
-        """
-        return Repository.get_repo_forks(self.repo_id)
-
-    @property
-    def parent(self):
-        """
-        Returns fork parent
-        """
-        return self.fork
-
-    @property
-    def just_name(self):
-        return self.repo_name.split(Repository.url_sep())[-1]
-
-    @property
-    def groups_with_parents(self):
-        groups = []
-        if self.group is None:
-            return groups
-
-        cur_gr = self.group
-        groups.insert(0, cur_gr)
-        while 1:
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            groups.insert(0, gr)
-
-        return groups
-
-    @property
-    def groups_and_repo(self):
-        return self.groups_with_parents, self.just_name, self.repo_name
-
-    @LazyProperty
-    def repo_path(self):
-        """
-        Returns base full path for that repository means where it actually
-        exists on a filesystem
-        """
-        q = Session().query(Ui).filter(Ui.ui_key ==
-                                              Repository.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def repo_full_path(self):
-        p = [self.repo_path]
-        # we need to split the name by / since this is how we store the
-        # names in the database, but that eventually needs to be converted
-        # into a valid system path
-        p += self.repo_name.split(Repository.url_sep())
-        return os.path.join(*map(safe_unicode, p))
-
-    @property
-    def cache_keys(self):
-        """
-        Returns associated cache keys for that repo
-        """
-        return CacheInvalidation.query()\
-            .filter(CacheInvalidation.cache_args == self.repo_name)\
-            .order_by(CacheInvalidation.cache_key)\
-            .all()
-
-    def get_new_name(self, repo_name):
-        """
-        returns new full repository name based on assigned group and new new
-
-        :param group_name:
-        """
-        path_prefix = self.group.full_path_splitted if self.group else []
-        return Repository.url_sep().join(path_prefix + [repo_name])
-
-    @property
-    def _ui(self):
-        """
-        Creates an db based ui object for this repository
-        """
-        from kallithea.lib.utils import make_ui
-        return make_ui('db', clear_session=False)
-
-    @classmethod
-    def is_valid(cls, repo_name):
-        """
-        returns True if given repo name is a valid filesystem repository
-
-        :param cls:
-        :param repo_name:
-        """
-        from kallithea.lib.utils import is_valid_repo
-
-        return is_valid_repo(repo_name, cls.base_path())
-
-    def get_api_data(self):
-        """
-        Common function for generating repo api data
-
-        """
-        repo = self
-        data = dict(
-            repo_id=repo.repo_id,
-            repo_name=repo.repo_name,
-            repo_type=repo.repo_type,
-            clone_uri=repo.clone_uri,
-            private=repo.private,
-            created_on=repo.created_on,
-            description=repo.description,
-            landing_rev=repo.landing_rev,
-            owner=repo.user.username,
-            fork_of=repo.fork.repo_name if repo.fork else None,
-            enable_statistics=repo.enable_statistics,
-            enable_locking=repo.enable_locking,
-            enable_downloads=repo.enable_downloads,
-            last_changeset=repo.changeset_cache,
-            locked_by=User.get(self.locked[0]).get_api_data() \
-                if self.locked[0] else None,
-            locked_date=time_to_datetime(self.locked[1]) \
-                if self.locked[1] else None
-        )
-        rc_config = Setting.get_app_settings()
-        repository_fields = str2bool(rc_config.get('repository_fields'))
-        if repository_fields:
-            for f in self.extra_fields:
-                data[f.field_key_prefixed] = f.field_value
-
-        return data
-
-    @classmethod
-    def lock(cls, repo, user_id, lock_time=None):
-        if not lock_time:
-            lock_time = time.time()
-        repo.locked = [user_id, lock_time]
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def unlock(cls, repo):
-        repo.locked = None
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def getlock(cls, repo):
-        return repo.locked
-
-    @property
-    def last_db_change(self):
-        return self.updated_on
-
-    def clone_url(self, **override):
-        import kallithea.lib.helpers as h
-        from urlparse import urlparse
-        import urllib
-        parsed_url = urlparse(h.canonical_url('home'))
-        default_clone_uri = '%(scheme)s://%(user)s%(pass)s%(netloc)s%(prefix)s%(path)s'
-        decoded_path = safe_unicode(urllib.unquote(parsed_url.path))
-        args = {
-           'user': '',
-           'pass': '',
-           'scheme': parsed_url.scheme,
-           'netloc': parsed_url.netloc,
-           'prefix': decoded_path,
-           'path': self.repo_name
-        }
-
-        args.update(override)
-        return default_clone_uri % args
-
-    #==========================================================================
-    # SCM PROPERTIES
-    #==========================================================================
-
-    def get_changeset(self, rev=None):
-        return get_changeset_safe(self.scm_instance, rev)
-
-    def get_landing_changeset(self):
-        """
-        Returns landing changeset, or if that doesn't exist returns the tip
-        """
-        cs = self.get_changeset(self.landing_rev) or self.get_changeset()
-        return cs
-
-    def update_changeset_cache(self, cs_cache=None):
-        """
-        Update cache of last changeset for repository, keys should be::
-
-            short_id
-            raw_id
-            revision
-            message
-            date
-            author
-
-        :param cs_cache:
-        """
-        from kallithea.lib.vcs.backends.base import BaseChangeset
-        if cs_cache is None:
-            cs_cache = EmptyChangeset()
-            # use no-cache version here
-            scm_repo = self.scm_instance_no_cache()
-            if scm_repo:
-                cs_cache = scm_repo.get_changeset()
-
-        if isinstance(cs_cache, BaseChangeset):
-            cs_cache = cs_cache.__json__()
-
-        if (cs_cache != self.changeset_cache or not self.changeset_cache):
-            _default = datetime.datetime.fromtimestamp(0)
-            last_change = cs_cache.get('date') or _default
-            log.debug('updated repo %s with new cs cache %s',
-                      self.repo_name, cs_cache)
-            self.updated_on = last_change
-            self.changeset_cache = cs_cache
-            Session().add(self)
-            Session().commit()
-        else:
-            log.debug('Skipping repo:%s already with latest changes',
-                      self.repo_name)
-
-    @property
-    def tip(self):
-        return self.get_changeset('tip')
-
-    @property
-    def author(self):
-        return self.tip.author
-
-    @property
-    def last_change(self):
-        return self.scm_instance.last_change
-
-    def get_comments(self, revisions=None):
-        """
-        Returns comments for this repository grouped by revisions
-
-        :param revisions: filter query by revisions only
-        """
-        cmts = ChangesetComment.query()\
-            .filter(ChangesetComment.repo == self)
-        if revisions:
-            cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
-        grouped = collections.defaultdict(list)
-        for cmt in cmts.all():
-            grouped[cmt.revision].append(cmt)
-        return grouped
-
-    def statuses(self, revisions=None):
-        """
-        Returns statuses for this repository
-
-        :param revisions: list of revisions to get statuses for
-        """
-
-        statuses = ChangesetStatus.query()\
-            .filter(ChangesetStatus.repo == self)\
-            .filter(ChangesetStatus.version == 0)
-        if revisions:
-            statuses = statuses.filter(ChangesetStatus.revision.in_(revisions))
-        grouped = {}
-
-        #maybe we have open new pullrequest without a status ?
-        stat = ChangesetStatus.STATUS_UNDER_REVIEW
-        status_lbl = ChangesetStatus.get_status_lbl(stat)
-        for pr in PullRequest.query().filter(PullRequest.org_repo == self).all():
-            for rev in pr.revisions:
-                pr_id = pr.pull_request_id
-                pr_repo = pr.other_repo.repo_name
-                grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
-
-        for stat in statuses.all():
-            pr_id = pr_repo = None
-            if stat.pull_request:
-                pr_id = stat.pull_request.pull_request_id
-                pr_repo = stat.pull_request.other_repo.repo_name
-            grouped[stat.revision] = [str(stat.status), stat.status_lbl,
-                                      pr_id, pr_repo]
-        return grouped
-
-    def _repo_size(self):
-        from kallithea.lib import helpers as h
-        log.debug('calculating repository size...')
-        return h.format_byte_size(self.scm_instance.size)
-
-    #==========================================================================
-    # SCM CACHE INSTANCE
-    #==========================================================================
-
-    def set_invalidate(self):
-        """
-        Mark caches of this repo as invalid.
-        """
-        CacheInvalidation.set_invalidate(self.repo_name)
-
-    def scm_instance_no_cache(self):
-        return self.__get_instance()
-
-    @property
-    def scm_instance(self):
-        import kallithea
-        full_cache = str2bool(kallithea.CONFIG.get('vcs_full_cache'))
-        if full_cache:
-            return self.scm_instance_cached()
-        return self.__get_instance()
-
-    def scm_instance_cached(self, valid_cache_keys=None):
-        @cache_region('long_term')
-        def _c(repo_name):
-            return self.__get_instance()
-        rn = self.repo_name
-
-        valid = CacheInvalidation.test_and_set_valid(rn, None, valid_cache_keys=valid_cache_keys)
-        if not valid:
-            log.debug('Cache for %s invalidated, getting new object', rn)
-            region_invalidate(_c, None, rn)
-        else:
-            log.debug('Getting obj for %s from cache', rn)
-        return _c(rn)
-
-    def __get_instance(self):
-        repo_full_path = self.repo_full_path
-        try:
-            alias = get_scm(repo_full_path)[0]
-            log.debug('Creating instance of %s repository from %s',
-                      alias, repo_full_path)
-            backend = get_backend(alias)
-        except VCSError:
-            log.error(traceback.format_exc())
-            log.error('Perhaps this repository is in db and not in '
-                      'filesystem run rescan repositories with '
-                      '"destroy old data " option from admin panel')
-            return
-
-        if alias == 'hg':
-
-            repo = backend(safe_str(repo_full_path), create=False,
-                           baseui=self._ui)
-        else:
-            repo = backend(repo_full_path, create=False)
-
-        return repo
-
-
-class RepoGroup(Base, BaseModel):
-    __tablename__ = 'groups'
-    __table_args__ = (
-        UniqueConstraint('group_name', 'group_parent_id'),
-        CheckConstraint('group_id != group_parent_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    __mapper_args__ = {'order_by': 'group_name'}
-
-    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    group_name = Column("group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
-    group_description = Column("group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-    parent_group = relationship('RepoGroup', remote_side=group_id)
-    user = relationship('User')
-
-    def __init__(self, group_name='', parent_group=None):
-        self.group_name = group_name
-        self.parent_group = parent_group
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
-                                      self.group_name)
-
-    @classmethod
-    def groups_choices(cls, groups=None, show_empty_group=True):
-        from webhelpers.html import literal as _literal
-        if not groups:
-            groups = cls.query().all()
-
-        repo_groups = []
-        if show_empty_group:
-            repo_groups = [('-1', '-- %s --' % _('top level'))]
-        sep = ' &raquo; '
-        _name = lambda k: _literal(sep.join(k))
-
-        repo_groups.extend([(x.group_id, _name(x.full_path_splitted))
-                              for x in groups])
-
-        repo_groups = sorted(repo_groups, key=lambda t: t[1].split(sep)[0])
-        return repo_groups
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
-        if case_insensitive:
-            gr = cls.query()\
-                .filter(cls.group_name.ilike(group_name))
-        else:
-            gr = cls.query()\
-                .filter(cls.group_name == group_name)
-        if cache:
-            gr = gr.options(FromCache(
-                            "sql_cache_short",
-                            "get_group_%s" % _hash_key(group_name)
-                            )
-            )
-        return gr.scalar()
-
-    @property
-    def parents(self):
-        parents_recursion_limit = 5
-        groups = []
-        if self.parent_group is None:
-            return groups
-        cur_gr = self.parent_group
-        groups.insert(0, cur_gr)
-        cnt = 0
-        while 1:
-            cnt += 1
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            if cnt == parents_recursion_limit:
-                # this will prevent accidental infinite loops
-                log.error('group nested more than %s',
-                          parents_recursion_limit)
-                break
-
-            groups.insert(0, gr)
-        return groups
-
-    @property
-    def children(self):
-        return RepoGroup.query().filter(RepoGroup.parent_group == self)
-
-    @property
-    def name(self):
-        return self.group_name.split(RepoGroup.url_sep())[-1]
-
-    @property
-    def full_path(self):
-        return self.group_name
-
-    @property
-    def full_path_splitted(self):
-        return self.group_name.split(RepoGroup.url_sep())
-
-    @property
-    def repositories(self):
-        return Repository.query()\
-                .filter(Repository.group == self)\
-                .order_by(Repository.repo_name)
-
-    @property
-    def repositories_recursive_count(self):
-        cnt = self.repositories.count()
-
-        def children_count(group):
-            cnt = 0
-            for child in group.children:
-                cnt += child.repositories.count()
-                cnt += children_count(child)
-            return cnt
-
-        return cnt + children_count(self)
-
-    def _recursive_objects(self, include_repos=True):
-        all_ = []
-
-        def _get_members(root_gr):
-            if include_repos:
-                for r in root_gr.repositories:
-                    all_.append(r)
-            childs = root_gr.children.all()
-            if childs:
-                for gr in childs:
-                    all_.append(gr)
-                    _get_members(gr)
-
-        _get_members(self)
-        return [self] + all_
-
-    def recursive_groups_and_repos(self):
-        """
-        Recursive return all groups, with repositories in those groups
-        """
-        return self._recursive_objects()
-
-    def recursive_groups(self):
-        """
-        Returns all children groups for this group including children of children
-        """
-        return self._recursive_objects(include_repos=False)
-
-    def get_new_name(self, group_name):
-        """
-        returns new full group name based on parent and new name
-
-        :param group_name:
-        """
-        path_prefix = (self.parent_group.full_path_splitted if
-                       self.parent_group else [])
-        return RepoGroup.url_sep().join(path_prefix + [group_name])
-
-
-class Permission(Base, BaseModel):
-    __tablename__ = 'permissions'
-    __table_args__ = (
-        Index('p_perm_name_idx', 'permission_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    PERMS = [
-        ('hg.admin', _('Kallithea Administrator')),
-
-        ('repository.none', _('Repository no access')),
-        ('repository.read', _('Repository read access')),
-        ('repository.write', _('Repository write access')),
-        ('repository.admin', _('Repository admin access')),
-
-        ('group.none', _('Repository group no access')),
-        ('group.read', _('Repository group read access')),
-        ('group.write', _('Repository group write access')),
-        ('group.admin', _('Repository group admin access')),
-
-        ('usergroup.none', _('User group no access')),
-        ('usergroup.read', _('User group read access')),
-        ('usergroup.write', _('User group write access')),
-        ('usergroup.admin', _('User group admin access')),
-
-        ('hg.repogroup.create.false', _('Repository Group creation disabled')),
-        ('hg.repogroup.create.true', _('Repository Group creation enabled')),
-
-        ('hg.usergroup.create.false', _('User Group creation disabled')),
-        ('hg.usergroup.create.true', _('User Group creation enabled')),
-
-        ('hg.create.none', _('Repository creation disabled')),
-        ('hg.create.repository', _('Repository creation enabled')),
-
-        ('hg.fork.none', _('Repository forking disabled')),
-        ('hg.fork.repository', _('Repository forking enabled')),
-
-        ('hg.register.none', _('Registration disabled')),
-        ('hg.register.manual_activate', _('User Registration with manual account activation')),
-        ('hg.register.auto_activate', _('User Registration with automatic account activation')),
-
-        ('hg.extern_activate.manual', _('Manual activation of external account')),
-        ('hg.extern_activate.auto', _('Automatic activation of external account')),
-
-    ]
-
-    #definition of system default permissions for DEFAULT user
-    DEFAULT_USER_PERMISSIONS = [
-        'repository.read',
-        'group.read',
-        'usergroup.read',
-        'hg.create.repository',
-        'hg.fork.repository',
-        'hg.register.manual_activate',
-        'hg.extern_activate.auto',
-    ]
-
-    # defines which permissions are more important higher the more important
-    # Weight defines which permissions are more important.
-    # The higher number the more important.
-    PERM_WEIGHTS = {
-        'repository.none': 0,
-        'repository.read': 1,
-        'repository.write': 3,
-        'repository.admin': 4,
-
-        'group.none': 0,
-        'group.read': 1,
-        'group.write': 3,
-        'group.admin': 4,
-
-        'usergroup.none': 0,
-        'usergroup.read': 1,
-        'usergroup.write': 3,
-        'usergroup.admin': 4,
-        'hg.repogroup.create.false': 0,
-        'hg.repogroup.create.true': 1,
-
-        'hg.usergroup.create.false': 0,
-        'hg.usergroup.create.true': 1,
-
-        'hg.fork.none': 0,
-        'hg.fork.repository': 1,
-        'hg.create.none': 0,
-        'hg.create.repository': 1
-    }
-
-    permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    permission_name = Column("permission_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    permission_longname = Column("permission_longname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__, self.permission_id, self.permission_name
-        )
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.permission_name == key).scalar()
-
-    @classmethod
-    def get_default_perms(cls, default_user_id):
-        q = Session().query(UserRepoToPerm, Repository, cls)\
-         .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
-         .join((cls, UserRepoToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_group_perms(cls, default_user_id):
-        q = Session().query(UserRepoGroupToPerm, RepoGroup, cls)\
-         .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
-         .join((cls, UserRepoGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_user_group_perms(cls, default_user_id):
-        q = Session().query(UserUserGroupToPerm, UserGroup, cls)\
-         .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
-         .join((cls, UserUserGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserUserGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-
-class UserRepoToPerm(Base, BaseModel):
-    __tablename__ = 'repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'repository_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    repository = relationship('Repository')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, repository, permission):
-        n = cls()
-        n.user = user
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.repository)
-
-
-class UserUserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_user_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    user_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, user_group, permission):
-        n = cls()
-        n.user = user
-        n.user_group = user_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.user_group)
-
-
-class UserToPerm(Base, BaseModel):
-    __tablename__ = 'user_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    permission = relationship('Permission', lazy='joined')
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.permission)
-
-
-class UserGroupRepoToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    repository = relationship('Repository')
-
-    @classmethod
-    def create(cls, users_group, repository, permission):
-        n = cls()
-        n.users_group = users_group
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
-
-
-class UserGroupUserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_group_user_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
-        CheckConstraint('target_user_group_id != user_group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-
-    target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
-    user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, target_user_group, user_group, permission):
-        n = cls()
-        n.target_user_group = target_user_group
-        n.user_group = user_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
-
-
-class UserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'permission_id',),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-
-class UserRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    group = relationship('RepoGroup')
-    permission = relationship('Permission')
-
-
-class UserGroupRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    group = relationship('RepoGroup')
-
-
-class Statistics(Base, BaseModel):
-    __tablename__ = 'statistics'
-    __table_args__ = (
-         UniqueConstraint('repository_id'),
-         {'extend_existing': True, 'mysql_engine': 'InnoDB',
-          'mysql_charset': 'utf8'}
-    )
-    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
-    stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
-    commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
-    commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
-    languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
-
-    repository = relationship('Repository', single_parent=True)
-
-
-class UserFollowing(Base, BaseModel):
-    __tablename__ = 'user_followings'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'follows_repository_id'),
-        UniqueConstraint('user_id', 'follows_user_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-
-    user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-
-    user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
-
-    follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relationship('Repository', order_by='Repository.repo_name')
-
-    @classmethod
-    def get_repo_followers(cls, repo_id):
-        return cls.query().filter(cls.follows_repo_id == repo_id)
-
-
-class CacheInvalidation(Base, BaseModel):
-    __tablename__ = 'cache_invalidation'
-    __table_args__ = (
-        UniqueConstraint('cache_key'),
-        Index('key_idx', 'cache_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    # cache_id, not used
-    cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    # cache_key as created by _get_cache_key
-    cache_key = Column("cache_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    # cache_args is a repo_name
-    cache_args = Column("cache_args", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    # instance sets cache_active True when it is caching,
-    # other instances set cache_active to False to indicate that this cache is invalid
-    cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
-
-    def __init__(self, cache_key, repo_name=''):
-        self.cache_key = cache_key
-        self.cache_args = repo_name
-        self.cache_active = False
-
-    def __unicode__(self):
-        return u"<%s('%s:%s[%s]')>" % (self.__class__.__name__,
-                            self.cache_id, self.cache_key, self.cache_active)
-
-    def _cache_key_partition(self):
-        prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
-        return prefix, repo_name, suffix
-
-    def get_prefix(self):
-        """
-        get prefix that might have been used in _get_cache_key to
-        generate self.cache_key. Only used for informational purposes
-        in repo_edit.html.
-        """
-        # prefix, repo_name, suffix
-        return self._cache_key_partition()[0]
-
-    def get_suffix(self):
-        """
-        get suffix that might have been used in _get_cache_key to
-        generate self.cache_key. Only used for informational purposes
-        in repo_edit.html.
-        """
-        # prefix, repo_name, suffix
-        return self._cache_key_partition()[2]
-
-    @classmethod
-    def clear_cache(cls):
-        """
-        Delete all cache keys from database.
-        Should only be run when all instances are down and all entries thus stale.
-        """
-        cls.query().delete()
-        Session().commit()
-
-    @classmethod
-    def _get_cache_key(cls, key):
-        """
-        Wrapper for generating a unique cache key for this instance and "key".
-        key must / will start with a repo_name which will be stored in .cache_args .
-        """
-        import kallithea
-        prefix = kallithea.CONFIG.get('instance_id', '')
-        return "%s%s" % (prefix, key)
-
-    @classmethod
-    def set_invalidate(cls, repo_name):
-        """
-        Mark all caches of a repo as invalid in the database.
-        """
-        inv_objs = Session().query(cls).filter(cls.cache_args == repo_name).all()
-
-        try:
-            for inv_obj in inv_objs:
-                log.debug('marking %s key for invalidation based on repo_name=%s',
-                          inv_obj, safe_str(repo_name))
-                inv_obj.cache_active = False
-                Session().add(inv_obj)
-            Session().commit()
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-
-    @classmethod
-    def test_and_set_valid(cls, repo_name, kind, valid_cache_keys=None):
-        """
-        Mark this cache key as active and currently cached.
-        Return True if the existing cache registration still was valid.
-        Return False to indicate that it had been invalidated and caches should be refreshed.
-        """
-
-        key = (repo_name + '_' + kind) if kind else repo_name
-        cache_key = cls._get_cache_key(key)
-
-        if valid_cache_keys and cache_key in valid_cache_keys:
-            return True
-
-        try:
-            inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
-            if not inv_obj:
-                inv_obj = CacheInvalidation(cache_key, repo_name)
-            was_valid = inv_obj.cache_active
-            inv_obj.cache_active = True
-            Session().add(inv_obj)
-            Session().commit()
-            return was_valid
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-            return False
-
-    @classmethod
-    def get_valid_cache_keys(cls):
-        """
-        Return opaque object with information of which caches still are valid
-        and can be used without checking for invalidation.
-        """
-        return set(inv_obj.cache_key for inv_obj in cls.query().filter(cls.cache_active).all())
-
-
-class ChangesetComment(Base, BaseModel):
-    __tablename__ = 'changeset_comments'
-    __table_args__ = (
-        Index('cc_revision_idx', 'revision'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    revision = Column('revision', String(40), nullable=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-    line_no = Column('line_no', Unicode(10), nullable=True)
-    hl_lines = Column('hl_lines', Unicode(512), nullable=True)
-    f_path = Column('f_path', Unicode(1000), nullable=True)
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
-    text = Column('text', UnicodeText(25000), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    @classmethod
-    def get_users(cls, revision=None, pull_request_id=None):
-        """
-        Returns user associated with this ChangesetComment. ie those
-        who actually commented
-
-        :param cls:
-        :param revision:
-        """
-        q = Session().query(User)\
-                .join(ChangesetComment.author)
-        if revision:
-            q = q.filter(cls.revision == revision)
-        elif pull_request_id:
-            q = q.filter(cls.pull_request_id == pull_request_id)
-        return q.all()
-
-
-class ChangesetStatus(Base, BaseModel):
-    __tablename__ = 'changeset_statuses'
-    __table_args__ = (
-        Index('cs_revision_idx', 'revision'),
-        Index('cs_version_idx', 'version'),
-        UniqueConstraint('repo_id', 'revision', 'version'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
-    STATUS_APPROVED = 'approved'
-    STATUS_REJECTED = 'rejected'
-    STATUS_UNDER_REVIEW = 'under_review'
-
-    STATUSES = [
-        (STATUS_NOT_REVIEWED, _("Not Reviewed")),  # (no icon) and default
-        (STATUS_APPROVED, _("Approved")),
-        (STATUS_REJECTED, _("Rejected")),
-        (STATUS_UNDER_REVIEW, _("Under Review")),
-    ]
-
-    changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    revision = Column('revision', String(40), nullable=False)
-    status = Column('status', String(128), nullable=False, default=DEFAULT)
-    changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
-    modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
-    version = Column('version', Integer(), nullable=False, default=0)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    comment = relationship('ChangesetComment', lazy='joined')
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.status, self.author
-        )
-
-    @classmethod
-    def get_status_lbl(cls, value):
-        return dict(cls.STATUSES).get(value)
-
-    @property
-    def status_lbl(self):
-        return ChangesetStatus.get_status_lbl(self.status)
-
-
-class PullRequest(Base, BaseModel):
-    __tablename__ = 'pull_requests'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    STATUS_NEW = u'new'
-    STATUS_OPEN = u'open'
-    STATUS_CLOSED = u'closed'
-
-    pull_request_id = Column('pull_request_id', Integer(), nullable=False, primary_key=True)
-    title = Column('title', Unicode(256), nullable=True)
-    description = Column('description', UnicodeText(10240), nullable=True)
-    status = Column('status', Unicode(256), nullable=False, default=STATUS_NEW)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    _revisions = Column('revisions', UnicodeText(20500))  # 500 revisions max
-    org_repo_id = Column('org_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    org_ref = Column('org_ref', Unicode(256), nullable=False)
-    other_repo_id = Column('other_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    other_ref = Column('other_ref', Unicode(256), nullable=False)
-
-    @hybrid_property
-    def revisions(self):
-        return self._revisions.split(':')
-
-    @revisions.setter
-    def revisions(self, val):
-        self._revisions = ':'.join(val)
-
-    @property
-    def org_ref_parts(self):
-        return self.org_ref.split(':')
-
-    @property
-    def other_ref_parts(self):
-        return self.other_ref.split(':')
-
-    author = relationship('User', lazy='joined')
-    reviewers = relationship('PullRequestReviewers',
-                             cascade="all, delete, delete-orphan")
-    org_repo = relationship('Repository', primaryjoin='PullRequest.org_repo_id==Repository.repo_id')
-    other_repo = relationship('Repository', primaryjoin='PullRequest.other_repo_id==Repository.repo_id')
-    statuses = relationship('ChangesetStatus')
-    comments = relationship('ChangesetComment',
-                             cascade="all, delete, delete-orphan")
-
-    def is_closed(self):
-        return self.status == self.STATUS_CLOSED
-
-    @property
-    def last_review_status(self):
-        return self.statuses[-1].status if self.statuses else ''
-
-    def __json__(self):
-        return dict(
-          revisions=self.revisions
-        )
-
-
-class PullRequestReviewers(Base, BaseModel):
-    __tablename__ = 'pull_request_reviewers'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    def __init__(self, user=None, pull_request=None):
-        self.user = user
-        self.pull_request = pull_request
-
-    pull_requests_reviewers_id = Column('pull_requests_reviewers_id', Integer(), nullable=False, primary_key=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
-
-    user = relationship('User')
-    pull_request = relationship('PullRequest')
-
-
-class Notification(Base, BaseModel):
-    __tablename__ = 'notifications'
-    __table_args__ = (
-        Index('notification_type_idx', 'type'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-
-    TYPE_CHANGESET_COMMENT = u'cs_comment'
-    TYPE_MESSAGE = u'message'
-    TYPE_MENTION = u'mention'
-    TYPE_REGISTRATION = u'registration'
-    TYPE_PULL_REQUEST = u'pull_request'
-    TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
-
-    notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
-    subject = Column('subject', Unicode(512), nullable=True)
-    body = Column('body', UnicodeText(50000), nullable=True)
-    created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    type_ = Column('type', Unicode(256))
-
-    created_by_user = relationship('User')
-    notifications_to_users = relationship('UserNotification', lazy='joined',
-                                          cascade="all, delete, delete-orphan")
-
-    @property
-    def recipients(self):
-        return [x.user for x in UserNotification.query()\
-                .filter(UserNotification.notification == self)\
-                .order_by(UserNotification.user_id.asc()).all()]
-
-    @classmethod
-    def create(cls, created_by, subject, body, recipients, type_=None):
-        if type_ is None:
-            type_ = Notification.TYPE_MESSAGE
-
-        notification = cls()
-        notification.created_by_user = created_by
-        notification.subject = subject
-        notification.body = body
-        notification.type_ = type_
-        notification.created_on = datetime.datetime.now()
-
-        for u in recipients:
-            assoc = UserNotification()
-            assoc.notification = notification
-            u.notifications.append(assoc)
-        Session().add(notification)
-        return notification
-
-    @property
-    def description(self):
-        from kallithea.model.notification import NotificationModel
-        return NotificationModel().make_description(self)
-
-
-class UserNotification(Base, BaseModel):
-    __tablename__ = 'user_to_notification'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'notification_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
-    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
-    read = Column('read', Boolean, default=False)
-    sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
-
-    user = relationship('User', lazy="joined")
-    notification = relationship('Notification', lazy="joined",
-                                order_by=lambda: Notification.created_on.desc(),)
-
-    def mark_as_read(self):
-        self.read = True
-        Session().add(self)
-
-
-class Gist(Base, BaseModel):
-    __tablename__ = 'gists'
-    __table_args__ = (
-        Index('g_gist_access_id_idx', 'gist_access_id'),
-        Index('g_created_on_idx', 'created_on'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'}
-    )
-    GIST_PUBLIC = u'public'
-    GIST_PRIVATE = u'private'
-
-    gist_id = Column('gist_id', Integer(), primary_key=True)
-    gist_access_id = Column('gist_access_id', Unicode(250))
-    gist_description = Column('gist_description', UnicodeText(1024))
-    gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
-    gist_expires = Column('gist_expires', Float(), nullable=False)
-    gist_type = Column('gist_type', Unicode(128), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    owner = relationship('User')
-
-    @classmethod
-    def get_or_404(cls, id_):
-        res = cls.query().filter(cls.gist_access_id == id_).scalar()
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def get_by_access_id(cls, gist_access_id):
-        return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
-
-    def gist_url(self):
-        import kallithea
-        alias_url = kallithea.CONFIG.get('gist_alias_url')
-        if alias_url:
-            return alias_url.replace('{gistid}', self.gist_access_id)
-
-        import kallithea.lib.helpers as h
-        return h.canonical_url('gist', gist_id=self.gist_access_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all gists are stored
-
-        :param cls:
-        """
-        from kallithea.model.gist import GIST_STORE_LOC
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == URL_SEP)
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return os.path.join(q.one().ui_value, GIST_STORE_LOC)
-
-    def get_api_data(self):
-        """
-        Common function for generating gist related data for API
-        """
-        gist = self
-        data = dict(
-            gist_id=gist.gist_id,
-            type=gist.gist_type,
-            access_id=gist.gist_access_id,
-            description=gist.gist_description,
-            url=gist.gist_url(),
-            expires=gist.gist_expires,
-            created_on=gist.created_on,
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-        )
-        data.update(self.get_api_data())
-        return data
-    ## SCM functions
-
-    @property
-    def scm_instance(self):
-        from kallithea.lib.vcs import get_repo
-        base_path = self.base_path()
-        return get_repo(os.path.join(*map(safe_str,
-                                          [base_path, self.gist_access_id])))
-
-
-class DbMigrateVersion(Base, BaseModel):
-    __tablename__ = 'db_migrate_version'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8'},
-    )
-    repository_id = Column('repository_id', String(250), primary_key=True)
-    repository_path = Column('repository_path', Text)
-    version = Column('version', Integer)
--- a/kallithea/lib/dbmigrate/schema/db_1_8_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,2270 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate.schema.db_1_8_0
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Database Models for Kallithea
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Apr 08, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-import os
-import time
-import logging
-import datetime
-import traceback
-import hashlib
-import collections
-
-from sqlalchemy import *
-from sqlalchemy.ext.hybrid import hybrid_property
-from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
-from beaker.cache import cache_region, region_invalidate
-from webob.exc import HTTPNotFound
-
-from pylons.i18n.translation import lazy_ugettext as _
-
-from kallithea.lib.vcs import get_backend
-from kallithea.lib.vcs.utils.helpers import get_scm
-from kallithea.lib.vcs.exceptions import VCSError
-from kallithea.lib.vcs.utils.lazy import LazyProperty
-from kallithea.lib.vcs.backends.base import EmptyChangeset
-
-from kallithea.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
-    safe_unicode, remove_prefix, time_to_datetime
-from kallithea.lib.compat import json
-from kallithea.lib.caching_query import FromCache
-
-from kallithea.model.meta import Base, Session
-
-URL_SEP = '/'
-log = logging.getLogger(__name__)
-
-from kallithea import DB_PREFIX
-
-#==============================================================================
-# BASE CLASSES
-#==============================================================================
-
-_hash_key = lambda k: hashlib.md5(safe_str(k)).hexdigest()
-
-
-class BaseModel(object):
-    """
-    Base Model for all classess
-    """
-
-    @classmethod
-    def _get_keys(cls):
-        """return column names for this model """
-        return class_mapper(cls).c.keys()
-
-    def get_dict(self):
-        """
-        return dict with keys and values corresponding
-        to this model data """
-
-        d = {}
-        for k in self._get_keys():
-            d[k] = getattr(self, k)
-
-        # also use __json__() if present to get additional fields
-        _json_attr = getattr(self, '__json__', None)
-        if _json_attr:
-            # update with attributes from __json__
-            if callable(_json_attr):
-                _json_attr = _json_attr()
-            for k, val in _json_attr.iteritems():
-                d[k] = val
-        return d
-
-    def get_appstruct(self):
-        """return list with keys and values tuples corresponding
-        to this model data """
-
-        l = []
-        for k in self._get_keys():
-            l.append((k, getattr(self, k),))
-        return l
-
-    def populate_obj(self, populate_dict):
-        """populate model with data from given populate_dict"""
-
-        for k in self._get_keys():
-            if k in populate_dict:
-                setattr(self, k, populate_dict[k])
-
-    @classmethod
-    def query(cls):
-        return Session().query(cls)
-
-    @classmethod
-    def get(cls, id_):
-        if id_:
-            return cls.query().get(id_)
-
-    @classmethod
-    def get_or_404(cls, id_):
-        try:
-            id_ = int(id_)
-        except (TypeError, ValueError):
-            raise HTTPNotFound
-
-        res = cls.query().get(id_)
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def getAll(cls):
-        # deprecated and left for backward compatibility
-        return cls.get_all()
-
-    @classmethod
-    def get_all(cls):
-        return cls.query().all()
-
-    @classmethod
-    def delete(cls, id_):
-        obj = cls.query().get(id_)
-        Session().delete(obj)
-
-    def __repr__(self):
-        if hasattr(self, '__unicode__'):
-            # python repr needs to return str
-            return safe_str(self.__unicode__())
-        return '<DB:%s>' % (self.__class__.__name__)
-
-
-class Setting(Base, BaseModel):
-    __tablename__ = DB_PREFIX +  'settings'
-    __table_args__ = (
-        UniqueConstraint('app_settings_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    app_settings_name = Column("app_settings_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_value = Column("app_settings_value", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_type = Column("app_settings_type", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __init__(self, key='', val='', type='unicode'):
-        self.app_settings_name = key
-        self.app_settings_value = val
-        self.app_settings_type = type
-
-    @validates('_app_settings_value')
-    def validate_settings_value(self, key, val):
-        assert type(val) == unicode
-        return val
-
-    @hybrid_property
-    def app_settings_value(self):
-        v = self._app_settings_value
-        if self.app_settings_name in ["ldap_active",
-                                      "default_repo_enable_statistics",
-                                      "default_repo_enable_locking",
-                                      "default_repo_private",
-                                      "default_repo_enable_downloads"]:
-            v = str2bool(v)
-        return v
-
-    @app_settings_value.setter
-    def app_settings_value(self, val):
-        """
-        Setter that will always make sure we use unicode in app_settings_value
-
-        :param val:
-        """
-        self._app_settings_value = safe_unicode(val)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.app_settings_name, self.app_settings_value
-        )
-
-    @classmethod
-    def get_by_name(cls, key):
-        return cls.query()\
-            .filter(cls.app_settings_name == key).scalar()
-
-    @classmethod
-    def get_by_name_or_create(cls, key):
-        res = cls.get_by_name(key)
-        if not res:
-            res = cls(key)
-        return res
-
-    @classmethod
-    def get_app_settings(cls, cache=False):
-
-        ret = cls.query()
-
-        if cache:
-            ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
-
-        if not ret:
-            raise Exception('Could not get application settings !')
-        settings = {}
-        for each in ret:
-            settings[each.app_settings_name] = \
-                each.app_settings_value
-
-        return settings
-
-    @classmethod
-    def get_ldap_settings(cls, cache=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('ldap_')).all()
-        fd = {}
-        for row in ret:
-            fd.update({row.app_settings_name: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_default_repo_settings(cls, cache=False, strip_prefix=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('default_')).all()
-        fd = {}
-        for row in ret:
-            key = row.app_settings_name
-            if strip_prefix:
-                key = remove_prefix(key, prefix='default_')
-            fd.update({key: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_server_info(cls):
-        import pkg_resources
-        import platform
-        import kallithea
-        from kallithea.lib.utils import check_git_version
-        mods = [(p.project_name, p.version) for p in pkg_resources.working_set]
-        mods += [('git', str(check_git_version()))]
-        info = {
-            'modules': sorted(mods, key=lambda k: k[0].lower()),
-            'py_version': platform.python_version(),
-            'platform': platform.platform(),
-            'kallithea_version': kallithea.__version__
-        }
-        return info
-
-
-class Ui(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'ui'
-    __table_args__ = (
-        UniqueConstraint('ui_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    HOOK_UPDATE = 'changegroup.update'
-    HOOK_REPO_SIZE = 'changegroup.repo_size'
-    HOOK_PUSH = 'changegroup.push_logger'
-    HOOK_PRE_PUSH = 'prechangegroup.pre_push'
-    HOOK_PULL = 'outgoing.pull_logger'
-    HOOK_PRE_PULL = 'preoutgoing.pre_pull'
-
-    ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    ui_section = Column("ui_section", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_key = Column("ui_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_value = Column("ui_value", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
-
-    # def __init__(self, section='', key='', value=''):
-    #     self.ui_section = section
-    #     self.ui_key = key
-    #     self.ui_value = value
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.ui_key == key).scalar()
-
-    @classmethod
-    def get_builtin_hooks(cls):
-        q = cls.query()
-        q = q.filter(cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                     cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                     cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        return q.all()
-
-    @classmethod
-    def get_custom_hooks(cls):
-        q = cls.query()
-        q = q.filter(~cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                      cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                      cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        q = q.filter(cls.ui_section == 'hooks')
-        return q.all()
-
-    @classmethod
-    def get_repos_location(cls):
-        return cls.get_by_key('/').ui_value
-
-    @classmethod
-    def create_or_update_hook(cls, key, val):
-        new_ui = cls.get_by_key(key) or cls()
-        new_ui.ui_section = 'hooks'
-        new_ui.ui_active = True
-        new_ui.ui_key = key
-        new_ui.ui_value = val
-
-        Session().add(new_ui)
-
-    def __repr__(self):
-        return '<DB:%s[%s:%s]>' % (self.__class__.__name__, self.ui_key,
-                                   self.ui_value)
-
-
-class User(Base, BaseModel):
-    __tablename__ = 'users'
-    __table_args__ = (
-        UniqueConstraint('username'), UniqueConstraint('email'),
-        Index('u_username_idx', 'username'),
-        Index('u_email_idx', 'email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    DEFAULT_USER = 'default'
-
-    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    password = Column("password", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
-    name = Column("firstname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    lastname = Column("lastname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
-    ldap_dn = Column("ldap_dn", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    api_key = Column("api_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-
-    user_log = relationship('UserLog')
-    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
-
-    repositories = relationship('Repository')
-    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
-    followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
-
-    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
-
-    group_member = relationship('UserGroupMember', cascade='all')
-
-    notifications = relationship('UserNotification', cascade='all')
-    # notifications assigned to this user
-    user_created_notifications = relationship('Notification', cascade='all')
-    # comments created by this user
-    user_comments = relationship('ChangesetComment', cascade='all')
-    #extra emails for this user
-    user_emails = relationship('UserEmailMap', cascade='all')
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-    @property
-    def firstname(self):
-        # alias for future
-        return self.name
-
-    @property
-    def emails(self):
-        other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
-        return [self.email] + [x.email for x in other]
-
-    @property
-    def ip_addresses(self):
-        ret = UserIpMap.query().filter(UserIpMap.user == self).all()
-        return [x.ip_addr for x in ret]
-
-    @property
-    def username_and_name(self):
-        return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
-
-    @property
-    def full_name(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def full_name_or_username(self):
-        return ('%s %s' % (self.firstname, self.lastname)
-                if (self.firstname and self.lastname) else self.username)
-
-    @property
-    def full_contact(self):
-        return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
-
-    @property
-    def short_contact(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def is_admin(self):
-        return self.admin
-
-    @property
-    def AuthUser(self):
-        """
-        Returns instance of AuthUser for this user
-        """
-        from kallithea.lib.auth import AuthUser
-        return AuthUser(user_id=self.user_id, api_key=self.api_key,
-                        username=self.username)
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                     self.user_id, self.username)
-
-    @classmethod
-    def get_by_username(cls, username, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.username.ilike(username))
-        else:
-            q = cls.query().filter(cls.username == username)
-
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(username)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get_by_api_key(cls, api_key, cache=False):
-        q = cls.query().filter(cls.api_key == api_key)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_api_key_%s" % api_key))
-        return q.scalar()
-
-    @classmethod
-    def get_by_email(cls, email, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.email.ilike(email))
-        else:
-            q = cls.query().filter(cls.email == email)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_email_key_%s" % email))
-
-        ret = q.scalar()
-        if ret is None:
-            q = UserEmailMap.query()
-            # try fetching in alternate email map
-            if case_insensitive:
-                q = q.filter(UserEmailMap.email.ilike(email))
-            else:
-                q = q.filter(UserEmailMap.email == email)
-            q = q.options(joinedload(UserEmailMap.user))
-            if cache:
-                q = q.options(FromCache("sql_cache_short",
-                                        "get_email_map_key_%s" % email))
-            ret = getattr(q.scalar(), 'user', None)
-
-        return ret
-
-    @classmethod
-    def get_from_cs_author(cls, author):
-        """
-        Tries to get User objects out of commit author string
-
-        :param author:
-        """
-        from kallithea.lib.helpers import email, author_name
-        # Valid email in the attribute passed, see if they're in the system
-        _email = email(author)
-        if _email:
-            user = cls.get_by_email(_email, case_insensitive=True)
-            if user:
-                return user
-        # Maybe we can match by username?
-        _author = author_name(author)
-        user = cls.get_by_username(_author, case_insensitive=True)
-        if user:
-            return user
-
-    def update_lastlogin(self):
-        """Update user lastlogin"""
-        self.last_login = datetime.datetime.now()
-        Session().add(self)
-        log.debug('updated user %s lastlogin', self.username)
-
-    @classmethod
-    def get_first_admin(cls):
-        user = User.query().filter(User.admin == True).first()
-        if user is None:
-            raise Exception('Missing administrative account!')
-        return user
-
-    @classmethod
-    def get_default_user(cls, cache=False):
-        user = User.get_by_username(User.DEFAULT_USER, cache=cache)
-        if user is None:
-            raise Exception('Missing default account!')
-        return user
-
-    def get_api_data(self):
-        """
-        Common function for generating user related data for API
-        """
-        user = self
-        data = dict(
-            user_id=user.user_id,
-            username=user.username,
-            firstname=user.name,
-            lastname=user.lastname,
-            email=user.email,
-            emails=user.emails,
-            api_key=user.api_key,
-            active=user.active,
-            admin=user.admin,
-            ldap_dn=user.ldap_dn,
-            last_login=user.last_login,
-            ip_addresses=user.ip_addresses
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-            full_name=self.full_name,
-            full_name_or_username=self.full_name_or_username,
-            short_contact=self.short_contact,
-            full_contact=self.full_contact
-        )
-        data.update(self.get_api_data())
-        return data
-
-
-class UserEmailMap(Base, BaseModel):
-    __tablename__ = 'user_email_map'
-    __table_args__ = (
-        Index('uem_email_idx', 'email'),
-        UniqueConstraint('email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    user = relationship('User', lazy='joined')
-
-    @validates('_email')
-    def validate_email(self, key, email):
-        # check if this email is not main one
-        main_email = Session().query(User).filter(User.email == email).scalar()
-        if main_email is not None:
-            raise AttributeError('email %s is present is user table' % email)
-        return email
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-
-class UserIpMap(Base, BaseModel):
-    __tablename__ = 'user_ip_map'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'ip_addr'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    ip_addr = Column("ip_addr", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    user = relationship('User', lazy='joined')
-
-    @classmethod
-    def _get_ip_range(cls, ip_addr):
-        from kallithea.lib import ipaddr
-        net = ipaddr.IPNetwork(address=ip_addr)
-        return [str(net.network), str(net.broadcast)]
-
-    def __json__(self):
-        return dict(
-          ip_addr=self.ip_addr,
-          ip_range=self._get_ip_range(self.ip_addr)
-        )
-
-
-class UserLog(Base, BaseModel):
-    __tablename__ = 'user_logs'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
-    repository_name = Column("repository_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    user_ip = Column("user_ip", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action = Column("action", UnicodeText(1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.repository_name,
-                                      self.action)
-
-    @property
-    def action_as_day(self):
-        return datetime.date(*self.action_date.timetuple()[:3])
-
-    user = relationship('User')
-    repository = relationship('Repository', cascade='')
-
-
-class UserGroup(Base, BaseModel):
-    __tablename__ = 'users_groups'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_name = Column("users_group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-
-    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
-    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
-    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-    user_user_group_to_perm = relationship('UserUserGroupToPerm ', cascade='all')
-    user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
-
-    user = relationship('User')
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.users_group_id,
-                                      self.users_group_name)
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False,
-                          case_insensitive=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.users_group_name.ilike(group_name))
-        else:
-            q = cls.query().filter(cls.users_group_name == group_name)
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(group_name)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get(cls, user_group_id, cache=False):
-        user_group = cls.query()
-        if cache:
-            user_group = user_group.options(FromCache("sql_cache_short",
-                                    "get_users_group_%s" % user_group_id))
-        return user_group.get(user_group_id)
-
-    def get_api_data(self, with_members=True):
-        user_group = self
-
-        data = dict(
-            users_group_id=user_group.users_group_id,
-            group_name=user_group.users_group_name,
-            active=user_group.users_group_active,
-            owner=user_group.user.username,
-        )
-        if with_members:
-            members = []
-            for user in user_group.members:
-                user = user.user
-                members.append(user.get_api_data())
-            data['members'] = members
-
-        return data
-
-
-class UserGroupMember(Base, BaseModel):
-    __tablename__ = 'users_groups_members'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User', lazy='joined')
-    users_group = relationship('UserGroup')
-
-    def __init__(self, gr_id='', u_id=''):
-        self.users_group_id = gr_id
-        self.user_id = u_id
-
-
-class RepositoryField(Base, BaseModel):
-    __tablename__ = 'repositories_fields'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'field_key'),  # no-multi field
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    PREFIX = 'ex_'  # prefix used in form to not conflict with already existing fields
-
-    repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-    field_key = Column("field_key", String(250, convert_unicode=False, assert_unicode=None))
-    field_label = Column("field_label", String(1024, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_value = Column("field_value", String(10000, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_desc = Column("field_desc", String(1024, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_type = Column("field_type", String(256), nullable=False, unique=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    repository = relationship('Repository')
-
-    @property
-    def field_key_prefixed(self):
-        return 'ex_%s' % self.field_key
-
-    @classmethod
-    def un_prefix_key(cls, key):
-        if key.startswith(cls.PREFIX):
-            return key[len(cls.PREFIX):]
-        return key
-
-    @classmethod
-    def get_by_key_name(cls, key, repo):
-        row = cls.query()\
-                .filter(cls.repository == repo)\
-                .filter(cls.field_key == key).scalar()
-        return row
-
-
-class Repository(Base, BaseModel):
-    __tablename__ = 'repositories'
-    __table_args__ = (
-        UniqueConstraint('repo_name'),
-        Index('r_repo_name_idx', 'repo_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repo_name = Column("repo_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    clone_uri = Column("clone_uri", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    repo_type = Column("repo_type", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
-    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
-    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
-    description = Column("description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    landing_rev = Column("landing_revision", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    _locked = Column("locked", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) #JSON data
-
-    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
-
-    user = relationship('User')
-    fork = relationship('Repository', remote_side=repo_id)
-    group = relationship('RepoGroup')
-    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    stats = relationship('Statistics', cascade='all', uselist=False)
-
-    followers = relationship('UserFollowing',
-                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
-                             cascade='all')
-    extra_fields = relationship('RepositoryField',
-                                cascade="all, delete, delete-orphan")
-
-    logs = relationship('UserLog')
-    comments = relationship('ChangesetComment', cascade="all, delete, delete-orphan")
-
-    pull_requests_org = relationship('PullRequest',
-                    primaryjoin='PullRequest.org_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    pull_requests_other = relationship('PullRequest',
-                    primaryjoin='PullRequest.other_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
-                                   safe_unicode(self.repo_name))
-
-    @hybrid_property
-    def locked(self):
-        # always should return [user_id, timelocked]
-        if self._locked:
-            _lock_info = self._locked.split(':')
-            return int(_lock_info[0]), _lock_info[1]
-        return [None, None]
-
-    @locked.setter
-    def locked(self, val):
-        if val and isinstance(val, (list, tuple)):
-            self._locked = ':'.join(map(str, val))
-        else:
-            self._locked = None
-
-    @hybrid_property
-    def changeset_cache(self):
-        from kallithea.lib.vcs.backends.base import EmptyChangeset
-        dummy = EmptyChangeset().__json__()
-        if not self._changeset_cache:
-            return dummy
-        try:
-            return json.loads(self._changeset_cache)
-        except TypeError:
-            return dummy
-
-    @changeset_cache.setter
-    def changeset_cache(self, val):
-        try:
-            self._changeset_cache = json.dumps(val)
-        except Exception:
-            log.error(traceback.format_exc())
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def normalize_repo_name(cls, repo_name):
-        """
-        Normalizes os specific repo_name to the format internally stored inside
-        dabatabase using URL_SEP
-
-        :param cls:
-        :param repo_name:
-        """
-        return cls.url_sep().join(repo_name.split(os.sep))
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        q = Session().query(cls).filter(cls.repo_name == repo_name)
-        q = q.options(joinedload(Repository.fork))\
-                .options(joinedload(Repository.user))\
-                .options(joinedload(Repository.group))
-        return q.scalar()
-
-    @classmethod
-    def get_by_full_path(cls, repo_full_path):
-        repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
-        repo_name = cls.normalize_repo_name(repo_name)
-        return cls.get_by_repo_name(repo_name.strip(URL_SEP))
-
-    @classmethod
-    def get_repo_forks(cls, repo_id):
-        return cls.query().filter(Repository.fork_id == repo_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all repos are stored
-
-        :param cls:
-        """
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == cls.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def forks(self):
-        """
-        Return forks of this repo
-        """
-        return Repository.get_repo_forks(self.repo_id)
-
-    @property
-    def parent(self):
-        """
-        Returns fork parent
-        """
-        return self.fork
-
-    @property
-    def just_name(self):
-        return self.repo_name.split(Repository.url_sep())[-1]
-
-    @property
-    def groups_with_parents(self):
-        groups = []
-        if self.group is None:
-            return groups
-
-        cur_gr = self.group
-        groups.insert(0, cur_gr)
-        while 1:
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            groups.insert(0, gr)
-
-        return groups
-
-    @property
-    def groups_and_repo(self):
-        return self.groups_with_parents, self.just_name, self.repo_name
-
-    @LazyProperty
-    def repo_path(self):
-        """
-        Returns base full path for that repository means where it actually
-        exists on a filesystem
-        """
-        q = Session().query(Ui).filter(Ui.ui_key ==
-                                              Repository.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def repo_full_path(self):
-        p = [self.repo_path]
-        # we need to split the name by / since this is how we store the
-        # names in the database, but that eventually needs to be converted
-        # into a valid system path
-        p += self.repo_name.split(Repository.url_sep())
-        return os.path.join(*map(safe_unicode, p))
-
-    @property
-    def cache_keys(self):
-        """
-        Returns associated cache keys for that repo
-        """
-        return CacheInvalidation.query()\
-            .filter(CacheInvalidation.cache_args == self.repo_name)\
-            .order_by(CacheInvalidation.cache_key)\
-            .all()
-
-    def get_new_name(self, repo_name):
-        """
-        returns new full repository name based on assigned group and new new
-
-        :param group_name:
-        """
-        path_prefix = self.group.full_path_splitted if self.group else []
-        return Repository.url_sep().join(path_prefix + [repo_name])
-
-    @property
-    def _ui(self):
-        """
-        Creates an db based ui object for this repository
-        """
-        from kallithea.lib.utils import make_ui
-        return make_ui('db', clear_session=False)
-
-    @classmethod
-    def is_valid(cls, repo_name):
-        """
-        returns True if given repo name is a valid filesystem repository
-
-        :param cls:
-        :param repo_name:
-        """
-        from kallithea.lib.utils import is_valid_repo
-
-        return is_valid_repo(repo_name, cls.base_path())
-
-    def get_api_data(self):
-        """
-        Common function for generating repo api data
-
-        """
-        repo = self
-        data = dict(
-            repo_id=repo.repo_id,
-            repo_name=repo.repo_name,
-            repo_type=repo.repo_type,
-            clone_uri=repo.clone_uri,
-            private=repo.private,
-            created_on=repo.created_on,
-            description=repo.description,
-            landing_rev=repo.landing_rev,
-            owner=repo.user.username,
-            fork_of=repo.fork.repo_name if repo.fork else None,
-            enable_statistics=repo.enable_statistics,
-            enable_locking=repo.enable_locking,
-            enable_downloads=repo.enable_downloads,
-            last_changeset=repo.changeset_cache,
-            locked_by=User.get(self.locked[0]).get_api_data() \
-                if self.locked[0] else None,
-            locked_date=time_to_datetime(self.locked[1]) \
-                if self.locked[1] else None
-        )
-        rc_config = Setting.get_app_settings()
-        repository_fields = str2bool(rc_config.get('repository_fields'))
-        if repository_fields:
-            for f in self.extra_fields:
-                data[f.field_key_prefixed] = f.field_value
-
-        return data
-
-    @classmethod
-    def lock(cls, repo, user_id, lock_time=None):
-        if not lock_time:
-            lock_time = time.time()
-        repo.locked = [user_id, lock_time]
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def unlock(cls, repo):
-        repo.locked = None
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def getlock(cls, repo):
-        return repo.locked
-
-    @property
-    def last_db_change(self):
-        return self.updated_on
-
-    def clone_url(self, **override):
-        import kallithea.lib.helpers as h
-        from urlparse import urlparse
-        import urllib
-        parsed_url = urlparse(h.canonical_url('home'))
-        default_clone_uri = '%(scheme)s://%(user)s%(pass)s%(netloc)s%(prefix)s%(path)s'
-        decoded_path = safe_unicode(urllib.unquote(parsed_url.path))
-        args = {
-           'user': '',
-           'pass': '',
-           'scheme': parsed_url.scheme,
-           'netloc': parsed_url.netloc,
-           'prefix': decoded_path,
-           'path': self.repo_name
-        }
-
-        args.update(override)
-        return default_clone_uri % args
-
-    #==========================================================================
-    # SCM PROPERTIES
-    #==========================================================================
-
-    def get_changeset(self, rev=None):
-        return get_changeset_safe(self.scm_instance, rev)
-
-    def get_landing_changeset(self):
-        """
-        Returns landing changeset, or if that doesn't exist returns the tip
-        """
-        cs = self.get_changeset(self.landing_rev) or self.get_changeset()
-        return cs
-
-    def update_changeset_cache(self, cs_cache=None):
-        """
-        Update cache of last changeset for repository, keys should be::
-
-            short_id
-            raw_id
-            revision
-            message
-            date
-            author
-
-        :param cs_cache:
-        """
-        from kallithea.lib.vcs.backends.base import BaseChangeset
-        if cs_cache is None:
-            cs_cache = EmptyChangeset()
-            # use no-cache version here
-            scm_repo = self.scm_instance_no_cache()
-            if scm_repo:
-                cs_cache = scm_repo.get_changeset()
-
-        if isinstance(cs_cache, BaseChangeset):
-            cs_cache = cs_cache.__json__()
-
-        if (cs_cache != self.changeset_cache or not self.changeset_cache):
-            _default = datetime.datetime.fromtimestamp(0)
-            last_change = cs_cache.get('date') or _default
-            log.debug('updated repo %s with new cs cache %s',
-                      self.repo_name, cs_cache)
-            self.updated_on = last_change
-            self.changeset_cache = cs_cache
-            Session().add(self)
-            Session().commit()
-        else:
-            log.debug('Skipping repo:%s already with latest changes',
-                      self.repo_name)
-
-    @property
-    def tip(self):
-        return self.get_changeset('tip')
-
-    @property
-    def author(self):
-        return self.tip.author
-
-    @property
-    def last_change(self):
-        return self.scm_instance.last_change
-
-    def get_comments(self, revisions=None):
-        """
-        Returns comments for this repository grouped by revisions
-
-        :param revisions: filter query by revisions only
-        """
-        cmts = ChangesetComment.query()\
-            .filter(ChangesetComment.repo == self)
-        if revisions:
-            cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
-        grouped = collections.defaultdict(list)
-        for cmt in cmts.all():
-            grouped[cmt.revision].append(cmt)
-        return grouped
-
-    def statuses(self, revisions=None):
-        """
-        Returns statuses for this repository
-
-        :param revisions: list of revisions to get statuses for
-        """
-
-        statuses = ChangesetStatus.query()\
-            .filter(ChangesetStatus.repo == self)\
-            .filter(ChangesetStatus.version == 0)
-        if revisions:
-            statuses = statuses.filter(ChangesetStatus.revision.in_(revisions))
-        grouped = {}
-
-        #maybe we have open new pullrequest without a status ?
-        stat = ChangesetStatus.STATUS_UNDER_REVIEW
-        status_lbl = ChangesetStatus.get_status_lbl(stat)
-        for pr in PullRequest.query().filter(PullRequest.org_repo == self).all():
-            for rev in pr.revisions:
-                pr_id = pr.pull_request_id
-                pr_repo = pr.other_repo.repo_name
-                grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
-
-        for stat in statuses.all():
-            pr_id = pr_repo = None
-            if stat.pull_request:
-                pr_id = stat.pull_request.pull_request_id
-                pr_repo = stat.pull_request.other_repo.repo_name
-            grouped[stat.revision] = [str(stat.status), stat.status_lbl,
-                                      pr_id, pr_repo]
-        return grouped
-
-    def _repo_size(self):
-        from kallithea.lib import helpers as h
-        log.debug('calculating repository size...')
-        return h.format_byte_size(self.scm_instance.size)
-
-    #==========================================================================
-    # SCM CACHE INSTANCE
-    #==========================================================================
-
-    def set_invalidate(self):
-        """
-        Mark caches of this repo as invalid.
-        """
-        CacheInvalidation.set_invalidate(self.repo_name)
-
-    def scm_instance_no_cache(self):
-        return self.__get_instance()
-
-    @property
-    def scm_instance(self):
-        import kallithea
-        full_cache = str2bool(kallithea.CONFIG.get('vcs_full_cache'))
-        if full_cache:
-            return self.scm_instance_cached()
-        return self.__get_instance()
-
-    def scm_instance_cached(self, valid_cache_keys=None):
-        @cache_region('long_term')
-        def _c(repo_name):
-            return self.__get_instance()
-        rn = self.repo_name
-
-        valid = CacheInvalidation.test_and_set_valid(rn, None, valid_cache_keys=valid_cache_keys)
-        if not valid:
-            log.debug('Cache for %s invalidated, getting new object', rn)
-            region_invalidate(_c, None, rn)
-        else:
-            log.debug('Getting obj for %s from cache', rn)
-        return _c(rn)
-
-    def __get_instance(self):
-        repo_full_path = self.repo_full_path
-        try:
-            alias = get_scm(repo_full_path)[0]
-            log.debug('Creating instance of %s repository from %s',
-                      alias, repo_full_path)
-            backend = get_backend(alias)
-        except VCSError:
-            log.error(traceback.format_exc())
-            log.error('Perhaps this repository is in db and not in '
-                      'filesystem run rescan repositories with '
-                      '"destroy old data " option from admin panel')
-            return
-
-        if alias == 'hg':
-
-            repo = backend(safe_str(repo_full_path), create=False,
-                           baseui=self._ui)
-        else:
-            repo = backend(repo_full_path, create=False)
-
-        return repo
-
-
-class RepoGroup(Base, BaseModel):
-    __tablename__ = 'groups'
-    __table_args__ = (
-        UniqueConstraint('group_name', 'group_parent_id'),
-        CheckConstraint('group_id != group_parent_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    __mapper_args__ = {'order_by': 'group_name'}
-
-    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    group_name = Column("group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
-    group_description = Column("group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-    parent_group = relationship('RepoGroup', remote_side=group_id)
-    user = relationship('User')
-
-    def __init__(self, group_name='', parent_group=None):
-        self.group_name = group_name
-        self.parent_group = parent_group
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
-                                      self.group_name)
-
-    @classmethod
-    def groups_choices(cls, groups=None, show_empty_group=True):
-        from webhelpers.html import literal as _literal
-        if not groups:
-            groups = cls.query().all()
-
-        repo_groups = []
-        if show_empty_group:
-            repo_groups = [('-1', u'-- %s --' % _('top level'))]
-        sep = ' &raquo; '
-        _name = lambda k: _literal(sep.join(k))
-
-        repo_groups.extend([(x.group_id, _name(x.full_path_splitted))
-                              for x in groups])
-
-        repo_groups = sorted(repo_groups, key=lambda t: t[1].split(sep)[0])
-        return repo_groups
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
-        if case_insensitive:
-            gr = cls.query()\
-                .filter(cls.group_name.ilike(group_name))
-        else:
-            gr = cls.query()\
-                .filter(cls.group_name == group_name)
-        if cache:
-            gr = gr.options(FromCache(
-                            "sql_cache_short",
-                            "get_group_%s" % _hash_key(group_name)
-                            )
-            )
-        return gr.scalar()
-
-    @property
-    def parents(self):
-        parents_recursion_limit = 5
-        groups = []
-        if self.parent_group is None:
-            return groups
-        cur_gr = self.parent_group
-        groups.insert(0, cur_gr)
-        cnt = 0
-        while 1:
-            cnt += 1
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            if cnt == parents_recursion_limit:
-                # this will prevent accidental infinite loops
-                log.error('group nested more than %s',
-                          parents_recursion_limit)
-                break
-
-            groups.insert(0, gr)
-        return groups
-
-    @property
-    def children(self):
-        return RepoGroup.query().filter(RepoGroup.parent_group == self)
-
-    @property
-    def name(self):
-        return self.group_name.split(RepoGroup.url_sep())[-1]
-
-    @property
-    def full_path(self):
-        return self.group_name
-
-    @property
-    def full_path_splitted(self):
-        return self.group_name.split(RepoGroup.url_sep())
-
-    @property
-    def repositories(self):
-        return Repository.query()\
-                .filter(Repository.group == self)\
-                .order_by(Repository.repo_name)
-
-    @property
-    def repositories_recursive_count(self):
-        cnt = self.repositories.count()
-
-        def children_count(group):
-            cnt = 0
-            for child in group.children:
-                cnt += child.repositories.count()
-                cnt += children_count(child)
-            return cnt
-
-        return cnt + children_count(self)
-
-    def _recursive_objects(self, include_repos=True):
-        all_ = []
-
-        def _get_members(root_gr):
-            if include_repos:
-                for r in root_gr.repositories:
-                    all_.append(r)
-            childs = root_gr.children.all()
-            if childs:
-                for gr in childs:
-                    all_.append(gr)
-                    _get_members(gr)
-
-        _get_members(self)
-        return [self] + all_
-
-    def recursive_groups_and_repos(self):
-        """
-        Recursive return all groups, with repositories in those groups
-        """
-        return self._recursive_objects()
-
-    def recursive_groups(self):
-        """
-        Returns all children groups for this group including children of children
-        """
-        return self._recursive_objects(include_repos=False)
-
-    def get_new_name(self, group_name):
-        """
-        returns new full group name based on parent and new name
-
-        :param group_name:
-        """
-        path_prefix = (self.parent_group.full_path_splitted if
-                       self.parent_group else [])
-        return RepoGroup.url_sep().join(path_prefix + [group_name])
-
-    def get_api_data(self):
-        """
-        Common function for generating api data
-
-        """
-        group = self
-        data = dict(
-            group_id=group.group_id,
-            group_name=group.group_name,
-            group_description=group.group_description,
-            parent_group=group.parent_group.group_name if group.parent_group else None,
-            repositories=[x.repo_name for x in group.repositories],
-            owner=group.user.username
-        )
-        return data
-
-
-class Permission(Base, BaseModel):
-    __tablename__ = 'permissions'
-    __table_args__ = (
-        Index('p_perm_name_idx', 'permission_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    PERMS = [
-        ('hg.admin', _('Kallithea Administrator')),
-
-        ('repository.none', _('Repository no access')),
-        ('repository.read', _('Repository read access')),
-        ('repository.write', _('Repository write access')),
-        ('repository.admin', _('Repository admin access')),
-
-        ('group.none', _('Repository group no access')),
-        ('group.read', _('Repository group read access')),
-        ('group.write', _('Repository group write access')),
-        ('group.admin', _('Repository group admin access')),
-
-        ('usergroup.none', _('User group no access')),
-        ('usergroup.read', _('User group read access')),
-        ('usergroup.write', _('User group write access')),
-        ('usergroup.admin', _('User group admin access')),
-
-        ('hg.repogroup.create.false', _('Repository Group creation disabled')),
-        ('hg.repogroup.create.true', _('Repository Group creation enabled')),
-
-        ('hg.usergroup.create.false', _('User Group creation disabled')),
-        ('hg.usergroup.create.true', _('User Group creation enabled')),
-
-        ('hg.create.none', _('Repository creation disabled')),
-        ('hg.create.repository', _('Repository creation enabled')),
-
-        ('hg.fork.none', _('Repository forking disabled')),
-        ('hg.fork.repository', _('Repository forking enabled')),
-
-        ('hg.register.none', _('Registration disabled')),
-        ('hg.register.manual_activate', _('User Registration with manual account activation')),
-        ('hg.register.auto_activate', _('User Registration with automatic account activation')),
-
-        ('hg.extern_activate.manual', _('Manual activation of external account')),
-        ('hg.extern_activate.auto', _('Automatic activation of external account')),
-
-    ]
-
-    #definition of system default permissions for DEFAULT user
-    DEFAULT_USER_PERMISSIONS = [
-        'repository.read',
-        'group.read',
-        'usergroup.read',
-        'hg.create.repository',
-        'hg.fork.repository',
-        'hg.register.manual_activate',
-        'hg.extern_activate.auto',
-    ]
-
-    # defines which permissions are more important higher the more important
-    # Weight defines which permissions are more important.
-    # The higher number the more important.
-    PERM_WEIGHTS = {
-        'repository.none': 0,
-        'repository.read': 1,
-        'repository.write': 3,
-        'repository.admin': 4,
-
-        'group.none': 0,
-        'group.read': 1,
-        'group.write': 3,
-        'group.admin': 4,
-
-        'usergroup.none': 0,
-        'usergroup.read': 1,
-        'usergroup.write': 3,
-        'usergroup.admin': 4,
-        'hg.repogroup.create.false': 0,
-        'hg.repogroup.create.true': 1,
-
-        'hg.usergroup.create.false': 0,
-        'hg.usergroup.create.true': 1,
-
-        'hg.fork.none': 0,
-        'hg.fork.repository': 1,
-        'hg.create.none': 0,
-        'hg.create.repository': 1
-    }
-
-    permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    permission_name = Column("permission_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    permission_longname = Column("permission_longname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__, self.permission_id, self.permission_name
-        )
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.permission_name == key).scalar()
-
-    @classmethod
-    def get_default_perms(cls, default_user_id):
-        q = Session().query(UserRepoToPerm, Repository, cls)\
-         .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
-         .join((cls, UserRepoToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_group_perms(cls, default_user_id):
-        q = Session().query(UserRepoGroupToPerm, RepoGroup, cls)\
-         .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
-         .join((cls, UserRepoGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_user_group_perms(cls, default_user_id):
-        q = Session().query(UserUserGroupToPerm, UserGroup, cls)\
-         .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
-         .join((cls, UserUserGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserUserGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-
-class UserRepoToPerm(Base, BaseModel):
-    __tablename__ = 'repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'repository_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    repository = relationship('Repository')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, repository, permission):
-        n = cls()
-        n.user = user
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.repository)
-
-
-class UserUserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_user_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    user_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, user_group, permission):
-        n = cls()
-        n.user = user
-        n.user_group = user_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.user_group)
-
-
-class UserToPerm(Base, BaseModel):
-    __tablename__ = 'user_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    permission = relationship('Permission', lazy='joined')
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.permission)
-
-
-class UserGroupRepoToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    repository = relationship('Repository')
-
-    @classmethod
-    def create(cls, users_group, repository, permission):
-        n = cls()
-        n.users_group = users_group
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
-
-
-class UserGroupUserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_group_user_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
-        CheckConstraint('target_user_group_id != user_group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-
-    target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
-    user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, target_user_group, user_group, permission):
-        n = cls()
-        n.target_user_group = target_user_group
-        n.user_group = user_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
-
-
-class UserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'permission_id',),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-
-class UserRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    group = relationship('RepoGroup')
-    permission = relationship('Permission')
-
-
-class UserGroupRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    group = relationship('RepoGroup')
-
-
-class Statistics(Base, BaseModel):
-    __tablename__ = 'statistics'
-    __table_args__ = (
-         UniqueConstraint('repository_id'),
-         {'extend_existing': True, 'mysql_engine': 'InnoDB',
-          'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
-    stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
-    commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
-    commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
-    languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
-
-    repository = relationship('Repository', single_parent=True)
-
-
-class UserFollowing(Base, BaseModel):
-    __tablename__ = 'user_followings'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'follows_repository_id'),
-        UniqueConstraint('user_id', 'follows_user_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-
-    user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
-
-    follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relationship('Repository', order_by='Repository.repo_name')
-
-    @classmethod
-    def get_repo_followers(cls, repo_id):
-        return cls.query().filter(cls.follows_repo_id == repo_id)
-
-
-class CacheInvalidation(Base, BaseModel):
-    __tablename__ = 'cache_invalidation'
-    __table_args__ = (
-        UniqueConstraint('cache_key'),
-        Index('key_idx', 'cache_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    # cache_id, not used
-    cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    # cache_key as created by _get_cache_key
-    cache_key = Column("cache_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    # cache_args is a repo_name
-    cache_args = Column("cache_args", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    # instance sets cache_active True when it is caching,
-    # other instances set cache_active to False to indicate that this cache is invalid
-    cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
-
-    def __init__(self, cache_key, repo_name=''):
-        self.cache_key = cache_key
-        self.cache_args = repo_name
-        self.cache_active = False
-
-    def __unicode__(self):
-        return u"<%s('%s:%s[%s]')>" % (self.__class__.__name__,
-                            self.cache_id, self.cache_key, self.cache_active)
-
-    def _cache_key_partition(self):
-        prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
-        return prefix, repo_name, suffix
-
-    def get_prefix(self):
-        """
-        get prefix that might have been used in _get_cache_key to
-        generate self.cache_key. Only used for informational purposes
-        in repo_edit.html.
-        """
-        # prefix, repo_name, suffix
-        return self._cache_key_partition()[0]
-
-    def get_suffix(self):
-        """
-        get suffix that might have been used in _get_cache_key to
-        generate self.cache_key. Only used for informational purposes
-        in repo_edit.html.
-        """
-        # prefix, repo_name, suffix
-        return self._cache_key_partition()[2]
-
-    @classmethod
-    def clear_cache(cls):
-        """
-        Delete all cache keys from database.
-        Should only be run when all instances are down and all entries thus stale.
-        """
-        cls.query().delete()
-        Session().commit()
-
-    @classmethod
-    def _get_cache_key(cls, key):
-        """
-        Wrapper for generating a unique cache key for this instance and "key".
-        key must / will start with a repo_name which will be stored in .cache_args .
-        """
-        import kallithea
-        prefix = kallithea.CONFIG.get('instance_id', '')
-        return "%s%s" % (prefix, key)
-
-    @classmethod
-    def set_invalidate(cls, repo_name):
-        """
-        Mark all caches of a repo as invalid in the database.
-        """
-        inv_objs = Session().query(cls).filter(cls.cache_args == repo_name).all()
-
-        try:
-            for inv_obj in inv_objs:
-                log.debug('marking %s key for invalidation based on repo_name=%s',
-                          inv_obj, safe_str(repo_name))
-                inv_obj.cache_active = False
-                Session().add(inv_obj)
-            Session().commit()
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-
-    @classmethod
-    def test_and_set_valid(cls, repo_name, kind, valid_cache_keys=None):
-        """
-        Mark this cache key as active and currently cached.
-        Return True if the existing cache registration still was valid.
-        Return False to indicate that it had been invalidated and caches should be refreshed.
-        """
-
-        key = (repo_name + '_' + kind) if kind else repo_name
-        cache_key = cls._get_cache_key(key)
-
-        if valid_cache_keys and cache_key in valid_cache_keys:
-            return True
-
-        try:
-            inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
-            if not inv_obj:
-                inv_obj = CacheInvalidation(cache_key, repo_name)
-            was_valid = inv_obj.cache_active
-            inv_obj.cache_active = True
-            Session().add(inv_obj)
-            Session().commit()
-            return was_valid
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-            return False
-
-    @classmethod
-    def get_valid_cache_keys(cls):
-        """
-        Return opaque object with information of which caches still are valid
-        and can be used without checking for invalidation.
-        """
-        return set(inv_obj.cache_key for inv_obj in cls.query().filter(cls.cache_active).all())
-
-
-class ChangesetComment(Base, BaseModel):
-    __tablename__ = 'changeset_comments'
-    __table_args__ = (
-        Index('cc_revision_idx', 'revision'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    revision = Column('revision', String(40), nullable=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-    line_no = Column('line_no', Unicode(10), nullable=True)
-    hl_lines = Column('hl_lines', Unicode(512), nullable=True)
-    f_path = Column('f_path', Unicode(1000), nullable=True)
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
-    text = Column('text', UnicodeText(25000), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    @classmethod
-    def get_users(cls, revision=None, pull_request_id=None):
-        """
-        Returns user associated with this ChangesetComment. ie those
-        who actually commented
-
-        :param cls:
-        :param revision:
-        """
-        q = Session().query(User)\
-                .join(ChangesetComment.author)
-        if revision:
-            q = q.filter(cls.revision == revision)
-        elif pull_request_id:
-            q = q.filter(cls.pull_request_id == pull_request_id)
-        return q.all()
-
-
-class ChangesetStatus(Base, BaseModel):
-    __tablename__ = 'changeset_statuses'
-    __table_args__ = (
-        Index('cs_revision_idx', 'revision'),
-        Index('cs_version_idx', 'version'),
-        UniqueConstraint('repo_id', 'revision', 'version'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
-    STATUS_APPROVED = 'approved'
-    STATUS_REJECTED = 'rejected'
-    STATUS_UNDER_REVIEW = 'under_review'
-
-    STATUSES = [
-        (STATUS_NOT_REVIEWED, _("Not Reviewed")),  # (no icon) and default
-        (STATUS_APPROVED, _("Approved")),
-        (STATUS_REJECTED, _("Rejected")),
-        (STATUS_UNDER_REVIEW, _("Under Review")),
-    ]
-
-    changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    revision = Column('revision', String(40), nullable=False)
-    status = Column('status', String(128), nullable=False, default=DEFAULT)
-    changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
-    modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
-    version = Column('version', Integer(), nullable=False, default=0)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    comment = relationship('ChangesetComment', lazy='joined')
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.status, self.author
-        )
-
-    @classmethod
-    def get_status_lbl(cls, value):
-        return dict(cls.STATUSES).get(value)
-
-    @property
-    def status_lbl(self):
-        return ChangesetStatus.get_status_lbl(self.status)
-
-
-class PullRequest(Base, BaseModel):
-    __tablename__ = 'pull_requests'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    # values for .status
-    STATUS_NEW = u'new'
-    STATUS_OPEN = u'open'
-    STATUS_CLOSED = u'closed'
-
-    pull_request_id = Column('pull_request_id', Integer(), nullable=False, primary_key=True)
-    title = Column('title', Unicode(256), nullable=True)
-    description = Column('description', UnicodeText(10240), nullable=True)
-    status = Column('status', Unicode(256), nullable=False, default=STATUS_NEW) # only for closedness, not approve/reject/etc
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    _revisions = Column('revisions', UnicodeText(20500))  # 500 revisions max
-    org_repo_id = Column('org_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    org_ref = Column('org_ref', Unicode(256), nullable=False)
-    other_repo_id = Column('other_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    other_ref = Column('other_ref', Unicode(256), nullable=False)
-
-    @hybrid_property
-    def revisions(self):
-        return self._revisions.split(':')
-
-    @revisions.setter
-    def revisions(self, val):
-        self._revisions = ':'.join(val)
-
-    @property
-    def org_ref_parts(self):
-        return self.org_ref.split(':')
-
-    @property
-    def other_ref_parts(self):
-        return self.other_ref.split(':')
-
-    author = relationship('User', lazy='joined')
-    reviewers = relationship('PullRequestReviewers',
-                             cascade="all, delete, delete-orphan")
-    org_repo = relationship('Repository', primaryjoin='PullRequest.org_repo_id==Repository.repo_id')
-    other_repo = relationship('Repository', primaryjoin='PullRequest.other_repo_id==Repository.repo_id')
-    statuses = relationship('ChangesetStatus')
-    comments = relationship('ChangesetComment',
-                             cascade="all, delete, delete-orphan")
-
-    def is_closed(self):
-        return self.status == self.STATUS_CLOSED
-
-    @property
-    def last_review_status(self):
-        return self.statuses[-1].status if self.statuses else ''
-
-    def __json__(self):
-        return dict(
-            revisions=self.revisions
-        )
-
-
-class PullRequestReviewers(Base, BaseModel):
-    __tablename__ = 'pull_request_reviewers'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    def __init__(self, user=None, pull_request=None):
-        self.user = user
-        self.pull_request = pull_request
-
-    pull_requests_reviewers_id = Column('pull_requests_reviewers_id', Integer(), nullable=False, primary_key=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
-
-    user = relationship('User')
-    pull_request = relationship('PullRequest')
-
-
-class Notification(Base, BaseModel):
-    __tablename__ = 'notifications'
-    __table_args__ = (
-        Index('notification_type_idx', 'type'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    TYPE_CHANGESET_COMMENT = u'cs_comment'
-    TYPE_MESSAGE = u'message'
-    TYPE_MENTION = u'mention'
-    TYPE_REGISTRATION = u'registration'
-    TYPE_PULL_REQUEST = u'pull_request'
-    TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
-
-    notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
-    subject = Column('subject', Unicode(512), nullable=True)
-    body = Column('body', UnicodeText(50000), nullable=True)
-    created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    type_ = Column('type', Unicode(256))
-
-    created_by_user = relationship('User')
-    notifications_to_users = relationship('UserNotification', lazy='joined',
-                                          cascade="all, delete, delete-orphan")
-
-    @property
-    def recipients(self):
-        return [x.user for x in UserNotification.query()\
-                .filter(UserNotification.notification == self)\
-                .order_by(UserNotification.user_id.asc()).all()]
-
-    @classmethod
-    def create(cls, created_by, subject, body, recipients, type_=None):
-        if type_ is None:
-            type_ = Notification.TYPE_MESSAGE
-
-        notification = cls()
-        notification.created_by_user = created_by
-        notification.subject = subject
-        notification.body = body
-        notification.type_ = type_
-        notification.created_on = datetime.datetime.now()
-
-        for u in recipients:
-            assoc = UserNotification()
-            assoc.notification = notification
-            u.notifications.append(assoc)
-        Session().add(notification)
-        return notification
-
-    @property
-    def description(self):
-        from kallithea.model.notification import NotificationModel
-        return NotificationModel().make_description(self)
-
-
-class UserNotification(Base, BaseModel):
-    __tablename__ = 'user_to_notification'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'notification_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
-    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
-    read = Column('read', Boolean, default=False)
-    sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
-
-    user = relationship('User', lazy="joined")
-    notification = relationship('Notification', lazy="joined",
-                                order_by=lambda: Notification.created_on.desc(),)
-
-    def mark_as_read(self):
-        self.read = True
-        Session().add(self)
-
-
-class Gist(Base, BaseModel):
-    __tablename__ = 'gists'
-    __table_args__ = (
-        Index('g_gist_access_id_idx', 'gist_access_id'),
-        Index('g_created_on_idx', 'created_on'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    GIST_PUBLIC = u'public'
-    GIST_PRIVATE = u'private'
-
-    gist_id = Column('gist_id', Integer(), primary_key=True)
-    gist_access_id = Column('gist_access_id', Unicode(250))
-    gist_description = Column('gist_description', UnicodeText(1024))
-    gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
-    gist_expires = Column('gist_expires', Float(53), nullable=False)
-    gist_type = Column('gist_type', Unicode(128), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    owner = relationship('User')
-
-    @classmethod
-    def get_or_404(cls, id_):
-        res = cls.query().filter(cls.gist_access_id == id_).scalar()
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def get_by_access_id(cls, gist_access_id):
-        return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
-
-    def gist_url(self):
-        import kallithea
-        alias_url = kallithea.CONFIG.get('gist_alias_url')
-        if alias_url:
-            return alias_url.replace('{gistid}', self.gist_access_id)
-
-        import kallithea.lib.helpers as h
-        return h.canonical_url('gist', gist_id=self.gist_access_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all gists are stored
-
-        :param cls:
-        """
-        from kallithea.model.gist import GIST_STORE_LOC
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == URL_SEP)
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return os.path.join(q.one().ui_value, GIST_STORE_LOC)
-
-    def get_api_data(self):
-        """
-        Common function for generating gist related data for API
-        """
-        gist = self
-        data = dict(
-            gist_id=gist.gist_id,
-            type=gist.gist_type,
-            access_id=gist.gist_access_id,
-            description=gist.gist_description,
-            url=gist.gist_url(),
-            expires=gist.gist_expires,
-            created_on=gist.created_on,
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-        )
-        data.update(self.get_api_data())
-        return data
-    ## SCM functions
-
-    @property
-    def scm_instance(self):
-        from kallithea.lib.vcs import get_repo
-        base_path = self.base_path()
-        return get_repo(os.path.join(*map(safe_str,
-                                          [base_path, self.gist_access_id])))
-
-
-class DbMigrateVersion(Base, BaseModel):
-    __tablename__ = 'db_migrate_version'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    repository_id = Column('repository_id', String(250), primary_key=True)
-    repository_path = Column('repository_path', Text)
-    version = Column('version', Integer)
--- a/kallithea/lib/dbmigrate/schema/db_2_0_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,2330 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate.schema.db_2_0_0
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Database Models for Kallithea
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Apr 08, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-import os
-import time
-import logging
-import datetime
-import traceback
-import hashlib
-import collections
-import functools
-
-from sqlalchemy import *
-from sqlalchemy.ext.hybrid import hybrid_property
-from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
-from beaker.cache import cache_region, region_invalidate
-from webob.exc import HTTPNotFound
-
-from pylons.i18n.translation import lazy_ugettext as _
-
-from kallithea.lib.vcs import get_backend
-from kallithea.lib.vcs.utils.helpers import get_scm
-from kallithea.lib.vcs.exceptions import VCSError
-from kallithea.lib.vcs.utils.lazy import LazyProperty
-from kallithea.lib.vcs.backends.base import EmptyChangeset
-
-from kallithea.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
-    safe_unicode, remove_prefix, time_to_datetime, aslist, Optional, safe_int
-from kallithea.lib.compat import json
-from kallithea.lib.caching_query import FromCache
-
-from kallithea.model.meta import Base, Session
-
-URL_SEP = '/'
-log = logging.getLogger(__name__)
-
-from kallithea import DB_PREFIX
-
-#==============================================================================
-# BASE CLASSES
-#==============================================================================
-
-_hash_key = lambda k: hashlib.md5(safe_str(k)).hexdigest()
-
-
-class BaseModel(object):
-    """
-    Base Model for all classess
-    """
-
-    @classmethod
-    def _get_keys(cls):
-        """return column names for this model """
-        return class_mapper(cls).c.keys()
-
-    def get_dict(self):
-        """
-        return dict with keys and values corresponding
-        to this model data """
-
-        d = {}
-        for k in self._get_keys():
-            d[k] = getattr(self, k)
-
-        # also use __json__() if present to get additional fields
-        _json_attr = getattr(self, '__json__', None)
-        if _json_attr:
-            # update with attributes from __json__
-            if callable(_json_attr):
-                _json_attr = _json_attr()
-            for k, val in _json_attr.iteritems():
-                d[k] = val
-        return d
-
-    def get_appstruct(self):
-        """return list with keys and values tuples corresponding
-        to this model data """
-
-        l = []
-        for k in self._get_keys():
-            l.append((k, getattr(self, k),))
-        return l
-
-    def populate_obj(self, populate_dict):
-        """populate model with data from given populate_dict"""
-
-        for k in self._get_keys():
-            if k in populate_dict:
-                setattr(self, k, populate_dict[k])
-
-    @classmethod
-    def query(cls):
-        return Session().query(cls)
-
-    @classmethod
-    def get(cls, id_):
-        if id_:
-            return cls.query().get(id_)
-
-    @classmethod
-    def get_or_404(cls, id_):
-        try:
-            id_ = int(id_)
-        except (TypeError, ValueError):
-            raise HTTPNotFound
-
-        res = cls.query().get(id_)
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def getAll(cls):
-        # deprecated and left for backward compatibility
-        return cls.get_all()
-
-    @classmethod
-    def get_all(cls):
-        return cls.query().all()
-
-    @classmethod
-    def delete(cls, id_):
-        obj = cls.query().get(id_)
-        Session().delete(obj)
-
-    def __repr__(self):
-        if hasattr(self, '__unicode__'):
-            # python repr needs to return str
-            return safe_str(self.__unicode__())
-        return '<DB:%s>' % (self.__class__.__name__)
-
-
-class Setting(Base, BaseModel):
-    SETTINGS_TYPES = {
-        'str': safe_str,
-        'int': safe_int,
-        'unicode': safe_unicode,
-        'bool': str2bool,
-        'list': functools.partial(aslist, sep=',')
-    }
-    __tablename__ = DB_PREFIX + 'settings'
-    __table_args__ = (
-        UniqueConstraint('app_settings_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    app_settings_name = Column("app_settings_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_value = Column("app_settings_value", String(4096, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_type = Column("app_settings_type", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __init__(self, key='', val='', type='unicode'):
-        self.app_settings_name = key
-        self.app_settings_value = val
-        self.app_settings_type = type
-
-    @validates('_app_settings_value')
-    def validate_settings_value(self, key, val):
-        assert type(val) == unicode
-        return val
-
-    @hybrid_property
-    def app_settings_value(self):
-        v = self._app_settings_value
-        _type = self.app_settings_type
-        converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
-        return converter(v)
-
-    @app_settings_value.setter
-    def app_settings_value(self, val):
-        """
-        Setter that will always make sure we use unicode in app_settings_value
-
-        :param val:
-        """
-        self._app_settings_value = safe_unicode(val)
-
-    @hybrid_property
-    def app_settings_type(self):
-        return self._app_settings_type
-
-    @app_settings_type.setter
-    def app_settings_type(self, val):
-        if val not in self.SETTINGS_TYPES:
-            raise Exception('type must be one of %s got %s'
-                            % (self.SETTINGS_TYPES.keys(), val))
-        self._app_settings_type = val
-
-    def __unicode__(self):
-        return u"<%s('%s:%s[%s]')>" % (
-            self.__class__.__name__,
-            self.app_settings_name, self.app_settings_value, self.app_settings_type
-        )
-
-    @classmethod
-    def get_by_name(cls, key):
-        return cls.query()\
-            .filter(cls.app_settings_name == key).scalar()
-
-    @classmethod
-    def get_by_name_or_create(cls, key, val='', type='unicode'):
-        res = cls.get_by_name(key)
-        if not res:
-            res = cls(key, val, type)
-        return res
-
-    @classmethod
-    def create_or_update(cls, key, val=Optional(''), type=Optional('unicode')):
-        """
-        Creates or updates Kallithea setting. If updates is triggered it will only
-        update parameters that are explicityl set Optional instance will be skipped
-
-        :param key:
-        :param val:
-        :param type:
-        :return:
-        """
-        res = cls.get_by_name(key)
-        if not res:
-            val = Optional.extract(val)
-            type = Optional.extract(type)
-            res = cls(key, val, type)
-        else:
-            res.app_settings_name = key
-            if not isinstance(val, Optional):
-                # update if set
-                res.app_settings_value = val
-            if not isinstance(type, Optional):
-                # update if set
-                res.app_settings_type = type
-        return res
-
-    @classmethod
-    def get_app_settings(cls, cache=False):
-
-        ret = cls.query()
-
-        if cache:
-            ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
-
-        if not ret:
-            raise Exception('Could not get application settings !')
-        settings = {}
-        for each in ret:
-            settings[each.app_settings_name] = \
-                each.app_settings_value
-
-        return settings
-
-    @classmethod
-    def get_auth_plugins(cls, cache=False):
-        auth_plugins = cls.get_by_name("auth_plugins").app_settings_value
-        return auth_plugins
-
-    @classmethod
-    def get_auth_settings(cls, cache=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('auth_')).all()
-        fd = {}
-        for row in ret:
-            fd.update({row.app_settings_name: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_default_repo_settings(cls, cache=False, strip_prefix=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('default_')).all()
-        fd = {}
-        for row in ret:
-            key = row.app_settings_name
-            if strip_prefix:
-                key = remove_prefix(key, prefix='default_')
-            fd.update({key: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_server_info(cls):
-        import pkg_resources
-        import platform
-        import kallithea
-        from kallithea.lib.utils import check_git_version
-        mods = [(p.project_name, p.version) for p in pkg_resources.working_set]
-        info = {
-            'modules': sorted(mods, key=lambda k: k[0].lower()),
-            'py_version': platform.python_version(),
-            'platform': platform.platform(),
-            'kallithea_version': kallithea.__version__,
-            'git_version': str(check_git_version()),
-            'git_path': kallithea.CONFIG.get('git_path')
-        }
-        return info
-
-
-class Ui(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'ui'
-    __table_args__ = (
-        UniqueConstraint('ui_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    HOOK_UPDATE = 'changegroup.update'
-    HOOK_REPO_SIZE = 'changegroup.repo_size'
-    HOOK_PUSH = 'changegroup.push_logger'
-    HOOK_PRE_PUSH = 'prechangegroup.pre_push'
-    HOOK_PULL = 'outgoing.pull_logger'
-    HOOK_PRE_PULL = 'preoutgoing.pre_pull'
-
-    ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    ui_section = Column("ui_section", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_key = Column("ui_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_value = Column("ui_value", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
-
-    # def __init__(self, section='', key='', value=''):
-    #     self.ui_section = section
-    #     self.ui_key = key
-    #     self.ui_value = value
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.ui_key == key).scalar()
-
-    @classmethod
-    def get_builtin_hooks(cls):
-        q = cls.query()
-        q = q.filter(cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                     cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                     cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        return q.all()
-
-    @classmethod
-    def get_custom_hooks(cls):
-        q = cls.query()
-        q = q.filter(~cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                      cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                      cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        q = q.filter(cls.ui_section == 'hooks')
-        return q.all()
-
-    @classmethod
-    def get_repos_location(cls):
-        return cls.get_by_key('/').ui_value
-
-    @classmethod
-    def create_or_update_hook(cls, key, val):
-        new_ui = cls.get_by_key(key) or cls()
-        new_ui.ui_section = 'hooks'
-        new_ui.ui_active = True
-        new_ui.ui_key = key
-        new_ui.ui_value = val
-
-        Session().add(new_ui)
-
-    def __repr__(self):
-        return '<DB:%s[%s:%s]>' % (self.__class__.__name__, self.ui_key,
-                                   self.ui_value)
-
-
-class User(Base, BaseModel):
-    __tablename__ = 'users'
-    __table_args__ = (
-        UniqueConstraint('username'), UniqueConstraint('email'),
-        Index('u_username_idx', 'username'),
-        Index('u_email_idx', 'email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    DEFAULT_USER = 'default'
-
-    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    password = Column("password", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
-    name = Column("firstname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    lastname = Column("lastname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
-    extern_type = Column("extern_type", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    extern_name = Column("extern_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    #for migration reasons, this is going to be later deleted
-    ldap_dn = Column("ldap_dn", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    api_key = Column("api_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    user_log = relationship('UserLog')
-    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
-
-    repositories = relationship('Repository')
-    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
-    followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
-
-    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
-
-    group_member = relationship('UserGroupMember', cascade='all')
-
-    notifications = relationship('UserNotification', cascade='all')
-    # notifications assigned to this user
-    user_created_notifications = relationship('Notification', cascade='all')
-    # comments created by this user
-    user_comments = relationship('ChangesetComment', cascade='all')
-    #extra emails for this user
-    user_emails = relationship('UserEmailMap', cascade='all')
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-    @property
-    def firstname(self):
-        # alias for future
-        return self.name
-
-    @property
-    def emails(self):
-        other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
-        return [self.email] + [x.email for x in other]
-
-    @property
-    def ip_addresses(self):
-        ret = UserIpMap.query().filter(UserIpMap.user == self).all()
-        return [x.ip_addr for x in ret]
-
-    @property
-    def username_and_name(self):
-        return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
-
-    @property
-    def full_name(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def full_name_or_username(self):
-        return ('%s %s' % (self.firstname, self.lastname)
-                if (self.firstname and self.lastname) else self.username)
-
-    @property
-    def full_contact(self):
-        return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
-
-    @property
-    def short_contact(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def is_admin(self):
-        return self.admin
-
-    @property
-    def AuthUser(self):
-        """
-        Returns instance of AuthUser for this user
-        """
-        from kallithea.lib.auth import AuthUser
-        return AuthUser(user_id=self.user_id, api_key=self.api_key,
-                        username=self.username)
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                     self.user_id, self.username)
-
-    @classmethod
-    def get_by_username(cls, username, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.username.ilike(username))
-        else:
-            q = cls.query().filter(cls.username == username)
-
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(username)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get_by_api_key(cls, api_key, cache=False):
-        q = cls.query().filter(cls.api_key == api_key)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_api_key_%s" % api_key))
-        return q.scalar()
-
-    @classmethod
-    def get_by_email(cls, email, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.email.ilike(email))
-        else:
-            q = cls.query().filter(cls.email == email)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_email_key_%s" % email))
-
-        ret = q.scalar()
-        if ret is None:
-            q = UserEmailMap.query()
-            # try fetching in alternate email map
-            if case_insensitive:
-                q = q.filter(UserEmailMap.email.ilike(email))
-            else:
-                q = q.filter(UserEmailMap.email == email)
-            q = q.options(joinedload(UserEmailMap.user))
-            if cache:
-                q = q.options(FromCache("sql_cache_short",
-                                        "get_email_map_key_%s" % email))
-            ret = getattr(q.scalar(), 'user', None)
-
-        return ret
-
-    @classmethod
-    def get_from_cs_author(cls, author):
-        """
-        Tries to get User objects out of commit author string
-
-        :param author:
-        """
-        from kallithea.lib.helpers import email, author_name
-        # Valid email in the attribute passed, see if they're in the system
-        _email = email(author)
-        if _email:
-            user = cls.get_by_email(_email, case_insensitive=True)
-            if user:
-                return user
-        # Maybe we can match by username?
-        _author = author_name(author)
-        user = cls.get_by_username(_author, case_insensitive=True)
-        if user:
-            return user
-
-    def update_lastlogin(self):
-        """Update user lastlogin"""
-        self.last_login = datetime.datetime.now()
-        Session().add(self)
-        log.debug('updated user %s lastlogin', self.username)
-
-    @classmethod
-    def get_first_admin(cls):
-        user = User.query().filter(User.admin == True).first()
-        if user is None:
-            raise Exception('Missing administrative account!')
-        return user
-
-    @classmethod
-    def get_default_user(cls, cache=False):
-        user = User.get_by_username(User.DEFAULT_USER, cache=cache)
-        if user is None:
-            raise Exception('Missing default account!')
-        return user
-
-    def get_api_data(self):
-        """
-        Common function for generating user related data for API
-        """
-        user = self
-        data = dict(
-            user_id=user.user_id,
-            username=user.username,
-            firstname=user.name,
-            lastname=user.lastname,
-            email=user.email,
-            emails=user.emails,
-            api_key=user.api_key,
-            active=user.active,
-            admin=user.admin,
-            extern_type=user.extern_type,
-            extern_name=user.extern_name,
-            last_login=user.last_login,
-            ip_addresses=user.ip_addresses
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-            full_name=self.full_name,
-            full_name_or_username=self.full_name_or_username,
-            short_contact=self.short_contact,
-            full_contact=self.full_contact
-        )
-        data.update(self.get_api_data())
-        return data
-
-
-class UserEmailMap(Base, BaseModel):
-    __tablename__ = 'user_email_map'
-    __table_args__ = (
-        Index('uem_email_idx', 'email'),
-        UniqueConstraint('email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    user = relationship('User', lazy='joined')
-
-    @validates('_email')
-    def validate_email(self, key, email):
-        # check if this email is not main one
-        main_email = Session().query(User).filter(User.email == email).scalar()
-        if main_email is not None:
-            raise AttributeError('email %s is present is user table' % email)
-        return email
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-
-class UserIpMap(Base, BaseModel):
-    __tablename__ = 'user_ip_map'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'ip_addr'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    ip_addr = Column("ip_addr", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    user = relationship('User', lazy='joined')
-
-    @classmethod
-    def _get_ip_range(cls, ip_addr):
-        from kallithea.lib import ipaddr
-        net = ipaddr.IPNetwork(address=ip_addr)
-        return [str(net.network), str(net.broadcast)]
-
-    def __json__(self):
-        return dict(
-          ip_addr=self.ip_addr,
-          ip_range=self._get_ip_range(self.ip_addr)
-        )
-
-
-class UserLog(Base, BaseModel):
-    __tablename__ = 'user_logs'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
-    repository_name = Column("repository_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    user_ip = Column("user_ip", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action = Column("action", UnicodeText(1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.repository_name,
-                                      self.action)
-
-    @property
-    def action_as_day(self):
-        return datetime.date(*self.action_date.timetuple()[:3])
-
-    user = relationship('User')
-    repository = relationship('Repository', cascade='')
-
-
-class UserGroup(Base, BaseModel):
-    __tablename__ = 'users_groups'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_name = Column("users_group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    user_group_description = Column("user_group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    # don't trigger lazy load for migrations
-    #members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
-    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
-    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-    user_user_group_to_perm = relationship('UserUserGroupToPerm ', cascade='all')
-    user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
-
-    user = relationship('User')
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.users_group_id,
-                                      self.users_group_name)
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False,
-                          case_insensitive=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.users_group_name.ilike(group_name))
-        else:
-            q = cls.query().filter(cls.users_group_name == group_name)
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(group_name)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get(cls, user_group_id, cache=False):
-        user_group = cls.query()
-        if cache:
-            user_group = user_group.options(FromCache("sql_cache_short",
-                                    "get_users_group_%s" % user_group_id))
-        return user_group.get(user_group_id)
-
-    def get_api_data(self, with_members=True):
-        user_group = self
-
-        data = dict(
-            users_group_id=user_group.users_group_id,
-            group_name=user_group.users_group_name,
-            group_description=user_group.user_group_description,
-            active=user_group.users_group_active,
-            owner=user_group.user.username,
-        )
-        if with_members:
-            members = []
-            for user in user_group.members:
-                user = user.user
-                members.append(user.get_api_data())
-            data['members'] = members
-
-        return data
-
-
-class UserGroupMember(Base, BaseModel):
-    __tablename__ = 'users_groups_members'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User', lazy='joined')
-    users_group = relationship('UserGroup')
-
-    def __init__(self, gr_id='', u_id=''):
-        self.users_group_id = gr_id
-        self.user_id = u_id
-
-
-class RepositoryField(Base, BaseModel):
-    __tablename__ = 'repositories_fields'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'field_key'),  # no-multi field
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    PREFIX = 'ex_'  # prefix used in form to not conflict with already existing fields
-
-    repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-    field_key = Column("field_key", String(250, convert_unicode=False, assert_unicode=None))
-    field_label = Column("field_label", String(1024, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_value = Column("field_value", String(10000, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_desc = Column("field_desc", String(1024, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_type = Column("field_type", String(256), nullable=False, unique=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    repository = relationship('Repository')
-
-    @property
-    def field_key_prefixed(self):
-        return 'ex_%s' % self.field_key
-
-    @classmethod
-    def un_prefix_key(cls, key):
-        if key.startswith(cls.PREFIX):
-            return key[len(cls.PREFIX):]
-        return key
-
-    @classmethod
-    def get_by_key_name(cls, key, repo):
-        row = cls.query()\
-                .filter(cls.repository == repo)\
-                .filter(cls.field_key == key).scalar()
-        return row
-
-
-class Repository(Base, BaseModel):
-    __tablename__ = 'repositories'
-    __table_args__ = (
-        UniqueConstraint('repo_name'),
-        Index('r_repo_name_idx', 'repo_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repo_name = Column("repo_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    clone_uri = Column("clone_uri", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    repo_type = Column("repo_type", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
-    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
-    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
-    description = Column("description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    landing_rev = Column("landing_revision", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    _locked = Column("locked", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) #JSON data
-
-    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
-
-    user = relationship('User')
-    fork = relationship('Repository', remote_side=repo_id)
-    group = relationship('RepoGroup')
-    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    stats = relationship('Statistics', cascade='all', uselist=False)
-
-    followers = relationship('UserFollowing',
-                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
-                             cascade='all')
-    extra_fields = relationship('RepositoryField',
-                                cascade="all, delete, delete-orphan")
-
-    logs = relationship('UserLog')
-    comments = relationship('ChangesetComment', cascade="all, delete, delete-orphan")
-
-    pull_requests_org = relationship('PullRequest',
-                    primaryjoin='PullRequest.org_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    pull_requests_other = relationship('PullRequest',
-                    primaryjoin='PullRequest.other_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
-                                   safe_unicode(self.repo_name))
-
-    @hybrid_property
-    def locked(self):
-        # always should return [user_id, timelocked]
-        if self._locked:
-            _lock_info = self._locked.split(':')
-            return int(_lock_info[0]), _lock_info[1]
-        return [None, None]
-
-    @locked.setter
-    def locked(self, val):
-        if val and isinstance(val, (list, tuple)):
-            self._locked = ':'.join(map(str, val))
-        else:
-            self._locked = None
-
-    @hybrid_property
-    def changeset_cache(self):
-        from kallithea.lib.vcs.backends.base import EmptyChangeset
-        dummy = EmptyChangeset().__json__()
-        if not self._changeset_cache:
-            return dummy
-        try:
-            return json.loads(self._changeset_cache)
-        except TypeError:
-            return dummy
-
-    @changeset_cache.setter
-    def changeset_cache(self, val):
-        try:
-            self._changeset_cache = json.dumps(val)
-        except Exception:
-            log.error(traceback.format_exc())
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def normalize_repo_name(cls, repo_name):
-        """
-        Normalizes os specific repo_name to the format internally stored inside
-        dabatabase using URL_SEP
-
-        :param cls:
-        :param repo_name:
-        """
-        return cls.url_sep().join(repo_name.split(os.sep))
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        q = Session().query(cls).filter(cls.repo_name == repo_name)
-        q = q.options(joinedload(Repository.fork))\
-                .options(joinedload(Repository.user))\
-                .options(joinedload(Repository.group))
-        return q.scalar()
-
-    @classmethod
-    def get_by_full_path(cls, repo_full_path):
-        repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
-        repo_name = cls.normalize_repo_name(repo_name)
-        return cls.get_by_repo_name(repo_name.strip(URL_SEP))
-
-    @classmethod
-    def get_repo_forks(cls, repo_id):
-        return cls.query().filter(Repository.fork_id == repo_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all repos are stored
-
-        :param cls:
-        """
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == cls.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def forks(self):
-        """
-        Return forks of this repo
-        """
-        return Repository.get_repo_forks(self.repo_id)
-
-    @property
-    def parent(self):
-        """
-        Returns fork parent
-        """
-        return self.fork
-
-    @property
-    def just_name(self):
-        return self.repo_name.split(Repository.url_sep())[-1]
-
-    @property
-    def groups_with_parents(self):
-        groups = []
-        if self.group is None:
-            return groups
-
-        cur_gr = self.group
-        groups.insert(0, cur_gr)
-        while 1:
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            groups.insert(0, gr)
-
-        return groups
-
-    @property
-    def groups_and_repo(self):
-        return self.groups_with_parents, self.just_name, self.repo_name
-
-    @LazyProperty
-    def repo_path(self):
-        """
-        Returns base full path for that repository means where it actually
-        exists on a filesystem
-        """
-        q = Session().query(Ui).filter(Ui.ui_key ==
-                                              Repository.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def repo_full_path(self):
-        p = [self.repo_path]
-        # we need to split the name by / since this is how we store the
-        # names in the database, but that eventually needs to be converted
-        # into a valid system path
-        p += self.repo_name.split(Repository.url_sep())
-        return os.path.join(*map(safe_unicode, p))
-
-    @property
-    def cache_keys(self):
-        """
-        Returns associated cache keys for that repo
-        """
-        return CacheInvalidation.query()\
-            .filter(CacheInvalidation.cache_args == self.repo_name)\
-            .order_by(CacheInvalidation.cache_key)\
-            .all()
-
-    def get_new_name(self, repo_name):
-        """
-        returns new full repository name based on assigned group and new new
-
-        :param group_name:
-        """
-        path_prefix = self.group.full_path_splitted if self.group else []
-        return Repository.url_sep().join(path_prefix + [repo_name])
-
-    @property
-    def _ui(self):
-        """
-        Creates an db based ui object for this repository
-        """
-        from kallithea.lib.utils import make_ui
-        return make_ui('db', clear_session=False)
-
-    @classmethod
-    def is_valid(cls, repo_name):
-        """
-        returns True if given repo name is a valid filesystem repository
-
-        :param cls:
-        :param repo_name:
-        """
-        from kallithea.lib.utils import is_valid_repo
-
-        return is_valid_repo(repo_name, cls.base_path())
-
-    def get_api_data(self):
-        """
-        Common function for generating repo api data
-
-        """
-        repo = self
-        data = dict(
-            repo_id=repo.repo_id,
-            repo_name=repo.repo_name,
-            repo_type=repo.repo_type,
-            clone_uri=repo.clone_uri,
-            private=repo.private,
-            created_on=repo.created_on,
-            description=repo.description,
-            landing_rev=repo.landing_rev,
-            owner=repo.user.username,
-            fork_of=repo.fork.repo_name if repo.fork else None,
-            enable_statistics=repo.enable_statistics,
-            enable_locking=repo.enable_locking,
-            enable_downloads=repo.enable_downloads,
-            last_changeset=repo.changeset_cache,
-            locked_by=User.get(self.locked[0]).get_api_data() \
-                if self.locked[0] else None,
-            locked_date=time_to_datetime(self.locked[1]) \
-                if self.locked[1] else None
-        )
-        rc_config = Setting.get_app_settings()
-        repository_fields = str2bool(rc_config.get('repository_fields'))
-        if repository_fields:
-            for f in self.extra_fields:
-                data[f.field_key_prefixed] = f.field_value
-
-        return data
-
-    @classmethod
-    def lock(cls, repo, user_id, lock_time=None):
-        if not lock_time:
-            lock_time = time.time()
-        repo.locked = [user_id, lock_time]
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def unlock(cls, repo):
-        repo.locked = None
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def getlock(cls, repo):
-        return repo.locked
-
-    @property
-    def last_db_change(self):
-        return self.updated_on
-
-    def clone_url(self, **override):
-        import kallithea.lib.helpers as h
-        from urlparse import urlparse
-        import urllib
-        parsed_url = urlparse(h.canonical_url('home'))
-        default_clone_uri = '%(scheme)s://%(user)s%(pass)s%(netloc)s%(prefix)s%(path)s'
-        decoded_path = safe_unicode(urllib.unquote(parsed_url.path))
-        args = {
-           'user': '',
-           'pass': '',
-           'scheme': parsed_url.scheme,
-           'netloc': parsed_url.netloc,
-           'prefix': decoded_path,
-           'path': self.repo_name
-        }
-
-        args.update(override)
-        return default_clone_uri % args
-
-    #==========================================================================
-    # SCM PROPERTIES
-    #==========================================================================
-
-    def get_changeset(self, rev=None):
-        return get_changeset_safe(self.scm_instance, rev)
-
-    def get_landing_changeset(self):
-        """
-        Returns landing changeset, or if that doesn't exist returns the tip
-        """
-        cs = self.get_changeset(self.landing_rev) or self.get_changeset()
-        return cs
-
-    def update_changeset_cache(self, cs_cache=None):
-        """
-        Update cache of last changeset for repository, keys should be::
-
-            short_id
-            raw_id
-            revision
-            message
-            date
-            author
-
-        :param cs_cache:
-        """
-        from kallithea.lib.vcs.backends.base import BaseChangeset
-        if cs_cache is None:
-            cs_cache = EmptyChangeset()
-            # use no-cache version here
-            scm_repo = self.scm_instance_no_cache()
-            if scm_repo:
-                cs_cache = scm_repo.get_changeset()
-
-        if isinstance(cs_cache, BaseChangeset):
-            cs_cache = cs_cache.__json__()
-
-        if (cs_cache != self.changeset_cache or not self.changeset_cache):
-            _default = datetime.datetime.fromtimestamp(0)
-            last_change = cs_cache.get('date') or _default
-            log.debug('updated repo %s with new cs cache %s',
-                      self.repo_name, cs_cache)
-            self.updated_on = last_change
-            self.changeset_cache = cs_cache
-            Session().add(self)
-            Session().commit()
-        else:
-            log.debug('Skipping repo:%s already with latest changes',
-                      self.repo_name)
-
-    @property
-    def tip(self):
-        return self.get_changeset('tip')
-
-    @property
-    def author(self):
-        return self.tip.author
-
-    @property
-    def last_change(self):
-        return self.scm_instance.last_change
-
-    def get_comments(self, revisions=None):
-        """
-        Returns comments for this repository grouped by revisions
-
-        :param revisions: filter query by revisions only
-        """
-        cmts = ChangesetComment.query()\
-            .filter(ChangesetComment.repo == self)
-        if revisions:
-            cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
-        grouped = collections.defaultdict(list)
-        for cmt in cmts.all():
-            grouped[cmt.revision].append(cmt)
-        return grouped
-
-    def statuses(self, revisions=None):
-        """
-        Returns statuses for this repository
-
-        :param revisions: list of revisions to get statuses for
-        """
-
-        statuses = ChangesetStatus.query()\
-            .filter(ChangesetStatus.repo == self)\
-            .filter(ChangesetStatus.version == 0)
-        if revisions:
-            statuses = statuses.filter(ChangesetStatus.revision.in_(revisions))
-        grouped = {}
-
-        #maybe we have open new pullrequest without a status ?
-        stat = ChangesetStatus.STATUS_UNDER_REVIEW
-        status_lbl = ChangesetStatus.get_status_lbl(stat)
-        for pr in PullRequest.query().filter(PullRequest.org_repo == self).all():
-            for rev in pr.revisions:
-                pr_id = pr.pull_request_id
-                pr_repo = pr.other_repo.repo_name
-                grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
-
-        for stat in statuses.all():
-            pr_id = pr_repo = None
-            if stat.pull_request:
-                pr_id = stat.pull_request.pull_request_id
-                pr_repo = stat.pull_request.other_repo.repo_name
-            grouped[stat.revision] = [str(stat.status), stat.status_lbl,
-                                      pr_id, pr_repo]
-        return grouped
-
-    def _repo_size(self):
-        from kallithea.lib import helpers as h
-        log.debug('calculating repository size...')
-        return h.format_byte_size(self.scm_instance.size)
-
-    #==========================================================================
-    # SCM CACHE INSTANCE
-    #==========================================================================
-
-    def set_invalidate(self):
-        """
-        Mark caches of this repo as invalid.
-        """
-        CacheInvalidation.set_invalidate(self.repo_name)
-
-    def scm_instance_no_cache(self):
-        return self.__get_instance()
-
-    @property
-    def scm_instance(self):
-        import kallithea
-        full_cache = str2bool(kallithea.CONFIG.get('vcs_full_cache'))
-        if full_cache:
-            return self.scm_instance_cached()
-        return self.__get_instance()
-
-    def scm_instance_cached(self, valid_cache_keys=None):
-        @cache_region('long_term')
-        def _c(repo_name):
-            return self.__get_instance()
-        rn = self.repo_name
-
-        valid = CacheInvalidation.test_and_set_valid(rn, None, valid_cache_keys=valid_cache_keys)
-        if not valid:
-            log.debug('Cache for %s invalidated, getting new object', rn)
-            region_invalidate(_c, None, rn)
-        else:
-            log.debug('Getting obj for %s from cache', rn)
-        return _c(rn)
-
-    def __get_instance(self):
-        repo_full_path = self.repo_full_path
-        try:
-            alias = get_scm(repo_full_path)[0]
-            log.debug('Creating instance of %s repository from %s',
-                      alias, repo_full_path)
-            backend = get_backend(alias)
-        except VCSError:
-            log.error(traceback.format_exc())
-            log.error('Perhaps this repository is in db and not in '
-                      'filesystem run rescan repositories with '
-                      '"destroy old data " option from admin panel')
-            return
-
-        if alias == 'hg':
-
-            repo = backend(safe_str(repo_full_path), create=False,
-                           baseui=self._ui)
-        else:
-            repo = backend(repo_full_path, create=False)
-
-        return repo
-
-
-class RepoGroup(Base, BaseModel):
-    __tablename__ = 'groups'
-    __table_args__ = (
-        UniqueConstraint('group_name', 'group_parent_id'),
-        CheckConstraint('group_id != group_parent_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    __mapper_args__ = {'order_by': 'group_name'}
-
-    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    group_name = Column("group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
-    group_description = Column("group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-    parent_group = relationship('RepoGroup', remote_side=group_id)
-    user = relationship('User')
-
-    def __init__(self, group_name='', parent_group=None):
-        self.group_name = group_name
-        self.parent_group = parent_group
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
-                                      self.group_name)
-
-    @classmethod
-    def groups_choices(cls, groups=None, show_empty_group=True):
-        from webhelpers.html import literal as _literal
-        if not groups:
-            groups = cls.query().all()
-
-        repo_groups = []
-        if show_empty_group:
-            repo_groups = [('-1', u'-- %s --' % _('top level'))]
-        sep = ' &raquo; '
-        _name = lambda k: _literal(sep.join(k))
-
-        repo_groups.extend([(x.group_id, _name(x.full_path_splitted))
-                              for x in groups])
-
-        repo_groups = sorted(repo_groups, key=lambda t: t[1].split(sep)[0])
-        return repo_groups
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
-        if case_insensitive:
-            gr = cls.query()\
-                .filter(cls.group_name.ilike(group_name))
-        else:
-            gr = cls.query()\
-                .filter(cls.group_name == group_name)
-        if cache:
-            gr = gr.options(FromCache(
-                            "sql_cache_short",
-                            "get_group_%s" % _hash_key(group_name)
-                            )
-            )
-        return gr.scalar()
-
-    @property
-    def parents(self):
-        parents_recursion_limit = 5
-        groups = []
-        if self.parent_group is None:
-            return groups
-        cur_gr = self.parent_group
-        groups.insert(0, cur_gr)
-        cnt = 0
-        while 1:
-            cnt += 1
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            if cnt == parents_recursion_limit:
-                # this will prevent accidental infinite loops
-                log.error('group nested more than %s',
-                          parents_recursion_limit)
-                break
-
-            groups.insert(0, gr)
-        return groups
-
-    @property
-    def children(self):
-        return RepoGroup.query().filter(RepoGroup.parent_group == self)
-
-    @property
-    def name(self):
-        return self.group_name.split(RepoGroup.url_sep())[-1]
-
-    @property
-    def full_path(self):
-        return self.group_name
-
-    @property
-    def full_path_splitted(self):
-        return self.group_name.split(RepoGroup.url_sep())
-
-    @property
-    def repositories(self):
-        return Repository.query()\
-                .filter(Repository.group == self)\
-                .order_by(Repository.repo_name)
-
-    @property
-    def repositories_recursive_count(self):
-        cnt = self.repositories.count()
-
-        def children_count(group):
-            cnt = 0
-            for child in group.children:
-                cnt += child.repositories.count()
-                cnt += children_count(child)
-            return cnt
-
-        return cnt + children_count(self)
-
-    def _recursive_objects(self, include_repos=True):
-        all_ = []
-
-        def _get_members(root_gr):
-            if include_repos:
-                for r in root_gr.repositories:
-                    all_.append(r)
-            childs = root_gr.children.all()
-            if childs:
-                for gr in childs:
-                    all_.append(gr)
-                    _get_members(gr)
-
-        _get_members(self)
-        return [self] + all_
-
-    def recursive_groups_and_repos(self):
-        """
-        Recursive return all groups, with repositories in those groups
-        """
-        return self._recursive_objects()
-
-    def recursive_groups(self):
-        """
-        Returns all children groups for this group including children of children
-        """
-        return self._recursive_objects(include_repos=False)
-
-    def get_new_name(self, group_name):
-        """
-        returns new full group name based on parent and new name
-
-        :param group_name:
-        """
-        path_prefix = (self.parent_group.full_path_splitted if
-                       self.parent_group else [])
-        return RepoGroup.url_sep().join(path_prefix + [group_name])
-
-    def get_api_data(self):
-        """
-        Common function for generating api data
-
-        """
-        group = self
-        data = dict(
-            group_id=group.group_id,
-            group_name=group.group_name,
-            group_description=group.group_description,
-            parent_group=group.parent_group.group_name if group.parent_group else None,
-            repositories=[x.repo_name for x in group.repositories],
-            owner=group.user.username
-        )
-        return data
-
-
-class Permission(Base, BaseModel):
-    __tablename__ = 'permissions'
-    __table_args__ = (
-        Index('p_perm_name_idx', 'permission_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    PERMS = [
-        ('hg.admin', _('Kallithea Administrator')),
-
-        ('repository.none', _('Repository no access')),
-        ('repository.read', _('Repository read access')),
-        ('repository.write', _('Repository write access')),
-        ('repository.admin', _('Repository admin access')),
-
-        ('group.none', _('Repository group no access')),
-        ('group.read', _('Repository group read access')),
-        ('group.write', _('Repository group write access')),
-        ('group.admin', _('Repository group admin access')),
-
-        ('usergroup.none', _('User group no access')),
-        ('usergroup.read', _('User group read access')),
-        ('usergroup.write', _('User group write access')),
-        ('usergroup.admin', _('User group admin access')),
-
-        ('hg.repogroup.create.false', _('Repository Group creation disabled')),
-        ('hg.repogroup.create.true', _('Repository Group creation enabled')),
-
-        ('hg.usergroup.create.false', _('User Group creation disabled')),
-        ('hg.usergroup.create.true', _('User Group creation enabled')),
-
-        ('hg.create.none', _('Repository creation disabled')),
-        ('hg.create.repository', _('Repository creation enabled')),
-
-        ('hg.fork.none', _('Repository forking disabled')),
-        ('hg.fork.repository', _('Repository forking enabled')),
-
-        ('hg.register.none', _('Registration disabled')),
-        ('hg.register.manual_activate', _('User Registration with manual account activation')),
-        ('hg.register.auto_activate', _('User Registration with automatic account activation')),
-
-        ('hg.extern_activate.manual', _('Manual activation of external account')),
-        ('hg.extern_activate.auto', _('Automatic activation of external account')),
-
-    ]
-
-    #definition of system default permissions for DEFAULT user
-    DEFAULT_USER_PERMISSIONS = [
-        'repository.read',
-        'group.read',
-        'usergroup.read',
-        'hg.create.repository',
-        'hg.fork.repository',
-        'hg.register.manual_activate',
-        'hg.extern_activate.auto',
-    ]
-
-    # defines which permissions are more important higher the more important
-    # Weight defines which permissions are more important.
-    # The higher number the more important.
-    PERM_WEIGHTS = {
-        'repository.none': 0,
-        'repository.read': 1,
-        'repository.write': 3,
-        'repository.admin': 4,
-
-        'group.none': 0,
-        'group.read': 1,
-        'group.write': 3,
-        'group.admin': 4,
-
-        'usergroup.none': 0,
-        'usergroup.read': 1,
-        'usergroup.write': 3,
-        'usergroup.admin': 4,
-        'hg.repogroup.create.false': 0,
-        'hg.repogroup.create.true': 1,
-
-        'hg.usergroup.create.false': 0,
-        'hg.usergroup.create.true': 1,
-
-        'hg.fork.none': 0,
-        'hg.fork.repository': 1,
-        'hg.create.none': 0,
-        'hg.create.repository': 1
-    }
-
-    permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    permission_name = Column("permission_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    permission_longname = Column("permission_longname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__, self.permission_id, self.permission_name
-        )
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.permission_name == key).scalar()
-
-    @classmethod
-    def get_default_perms(cls, default_user_id):
-        q = Session().query(UserRepoToPerm, Repository, cls)\
-         .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
-         .join((cls, UserRepoToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_group_perms(cls, default_user_id):
-        q = Session().query(UserRepoGroupToPerm, RepoGroup, cls)\
-         .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
-         .join((cls, UserRepoGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_user_group_perms(cls, default_user_id):
-        q = Session().query(UserUserGroupToPerm, UserGroup, cls)\
-         .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
-         .join((cls, UserUserGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserUserGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-
-class UserRepoToPerm(Base, BaseModel):
-    __tablename__ = 'repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'repository_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    repository = relationship('Repository')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, repository, permission):
-        n = cls()
-        n.user = user
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.repository)
-
-
-class UserUserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_user_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    user_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, user_group, permission):
-        n = cls()
-        n.user = user
-        n.user_group = user_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.user_group)
-
-
-class UserToPerm(Base, BaseModel):
-    __tablename__ = 'user_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    permission = relationship('Permission', lazy='joined')
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.permission)
-
-
-class UserGroupRepoToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    repository = relationship('Repository')
-
-    @classmethod
-    def create(cls, users_group, repository, permission):
-        n = cls()
-        n.users_group = users_group
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
-
-
-class UserGroupUserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_group_user_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
-        CheckConstraint('target_user_group_id != user_group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-
-    target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
-    user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, target_user_group, user_group, permission):
-        n = cls()
-        n.target_user_group = target_user_group
-        n.user_group = user_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
-
-
-class UserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'permission_id',),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-
-class UserRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    group = relationship('RepoGroup')
-    permission = relationship('Permission')
-
-
-class UserGroupRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    group = relationship('RepoGroup')
-
-
-class Statistics(Base, BaseModel):
-    __tablename__ = 'statistics'
-    __table_args__ = (
-         UniqueConstraint('repository_id'),
-         {'extend_existing': True, 'mysql_engine': 'InnoDB',
-          'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
-    stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
-    commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
-    commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
-    languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
-
-    repository = relationship('Repository', single_parent=True)
-
-
-class UserFollowing(Base, BaseModel):
-    __tablename__ = 'user_followings'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'follows_repository_id'),
-        UniqueConstraint('user_id', 'follows_user_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-
-    user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
-
-    follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relationship('Repository', order_by='Repository.repo_name')
-
-    @classmethod
-    def get_repo_followers(cls, repo_id):
-        return cls.query().filter(cls.follows_repo_id == repo_id)
-
-
-class CacheInvalidation(Base, BaseModel):
-    __tablename__ = 'cache_invalidation'
-    __table_args__ = (
-        UniqueConstraint('cache_key'),
-        Index('key_idx', 'cache_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    # cache_id, not used
-    cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    # cache_key as created by _get_cache_key
-    cache_key = Column("cache_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    # cache_args is a repo_name
-    cache_args = Column("cache_args", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    # instance sets cache_active True when it is caching,
-    # other instances set cache_active to False to indicate that this cache is invalid
-    cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
-
-    def __init__(self, cache_key, repo_name=''):
-        self.cache_key = cache_key
-        self.cache_args = repo_name
-        self.cache_active = False
-
-    def __unicode__(self):
-        return u"<%s('%s:%s[%s]')>" % (self.__class__.__name__,
-                            self.cache_id, self.cache_key, self.cache_active)
-
-    def _cache_key_partition(self):
-        prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
-        return prefix, repo_name, suffix
-
-    def get_prefix(self):
-        """
-        get prefix that might have been used in _get_cache_key to
-        generate self.cache_key. Only used for informational purposes
-        in repo_edit.html.
-        """
-        # prefix, repo_name, suffix
-        return self._cache_key_partition()[0]
-
-    def get_suffix(self):
-        """
-        get suffix that might have been used in _get_cache_key to
-        generate self.cache_key. Only used for informational purposes
-        in repo_edit.html.
-        """
-        # prefix, repo_name, suffix
-        return self._cache_key_partition()[2]
-
-    @classmethod
-    def clear_cache(cls):
-        """
-        Delete all cache keys from database.
-        Should only be run when all instances are down and all entries thus stale.
-        """
-        cls.query().delete()
-        Session().commit()
-
-    @classmethod
-    def _get_cache_key(cls, key):
-        """
-        Wrapper for generating a unique cache key for this instance and "key".
-        key must / will start with a repo_name which will be stored in .cache_args .
-        """
-        import kallithea
-        prefix = kallithea.CONFIG.get('instance_id', '')
-        return "%s%s" % (prefix, key)
-
-    @classmethod
-    def set_invalidate(cls, repo_name, delete=False):
-        """
-        Mark all caches of a repo as invalid in the database.
-        """
-        inv_objs = Session().query(cls).filter(cls.cache_args == repo_name).all()
-
-        try:
-            for inv_obj in inv_objs:
-                log.debug('marking %s key for invalidation based on repo_name=%s',
-                          inv_obj, safe_str(repo_name))
-                if delete:
-                    Session().delete(inv_obj)
-                else:
-                    inv_obj.cache_active = False
-                    Session().add(inv_obj)
-            Session().commit()
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-
-    @classmethod
-    def test_and_set_valid(cls, repo_name, kind, valid_cache_keys=None):
-        """
-        Mark this cache key as active and currently cached.
-        Return True if the existing cache registration still was valid.
-        Return False to indicate that it had been invalidated and caches should be refreshed.
-        """
-
-        key = (repo_name + '_' + kind) if kind else repo_name
-        cache_key = cls._get_cache_key(key)
-
-        if valid_cache_keys and cache_key in valid_cache_keys:
-            return True
-
-        try:
-            inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
-            if not inv_obj:
-                inv_obj = CacheInvalidation(cache_key, repo_name)
-            was_valid = inv_obj.cache_active
-            inv_obj.cache_active = True
-            Session().add(inv_obj)
-            Session().commit()
-            return was_valid
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-            return False
-
-    @classmethod
-    def get_valid_cache_keys(cls):
-        """
-        Return opaque object with information of which caches still are valid
-        and can be used without checking for invalidation.
-        """
-        return set(inv_obj.cache_key for inv_obj in cls.query().filter(cls.cache_active).all())
-
-
-class ChangesetComment(Base, BaseModel):
-    __tablename__ = 'changeset_comments'
-    __table_args__ = (
-        Index('cc_revision_idx', 'revision'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    revision = Column('revision', String(40), nullable=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-    line_no = Column('line_no', Unicode(10), nullable=True)
-    hl_lines = Column('hl_lines', Unicode(512), nullable=True)
-    f_path = Column('f_path', Unicode(1000), nullable=True)
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
-    text = Column('text', UnicodeText(25000), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    @classmethod
-    def get_users(cls, revision=None, pull_request_id=None):
-        """
-        Returns user associated with this ChangesetComment. ie those
-        who actually commented
-
-        :param cls:
-        :param revision:
-        """
-        q = Session().query(User)\
-                .join(ChangesetComment.author)
-        if revision:
-            q = q.filter(cls.revision == revision)
-        elif pull_request_id:
-            q = q.filter(cls.pull_request_id == pull_request_id)
-        return q.all()
-
-
-class ChangesetStatus(Base, BaseModel):
-    __tablename__ = 'changeset_statuses'
-    __table_args__ = (
-        Index('cs_revision_idx', 'revision'),
-        Index('cs_version_idx', 'version'),
-        UniqueConstraint('repo_id', 'revision', 'version'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
-    STATUS_APPROVED = 'approved'
-    STATUS_REJECTED = 'rejected'
-    STATUS_UNDER_REVIEW = 'under_review'
-
-    STATUSES = [
-        (STATUS_NOT_REVIEWED, _("Not Reviewed")),  # (no icon) and default
-        (STATUS_APPROVED, _("Approved")),
-        (STATUS_REJECTED, _("Rejected")),
-        (STATUS_UNDER_REVIEW, _("Under Review")),
-    ]
-
-    changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    revision = Column('revision', String(40), nullable=False)
-    status = Column('status', String(128), nullable=False, default=DEFAULT)
-    changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
-    modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
-    version = Column('version', Integer(), nullable=False, default=0)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    comment = relationship('ChangesetComment', lazy='joined')
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.status, self.author
-        )
-
-    @classmethod
-    def get_status_lbl(cls, value):
-        return dict(cls.STATUSES).get(value)
-
-    @property
-    def status_lbl(self):
-        return ChangesetStatus.get_status_lbl(self.status)
-
-
-class PullRequest(Base, BaseModel):
-    __tablename__ = 'pull_requests'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    # values for .status
-    STATUS_NEW = u'new'
-    STATUS_OPEN = u'open'
-    STATUS_CLOSED = u'closed'
-
-    pull_request_id = Column('pull_request_id', Integer(), nullable=False, primary_key=True)
-    title = Column('title', Unicode(256), nullable=True)
-    description = Column('description', UnicodeText(10240), nullable=True)
-    status = Column('status', Unicode(256), nullable=False, default=STATUS_NEW) # only for closedness, not approve/reject/etc
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    _revisions = Column('revisions', UnicodeText(20500))  # 500 revisions max
-    org_repo_id = Column('org_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    org_ref = Column('org_ref', Unicode(256), nullable=False)
-    other_repo_id = Column('other_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    other_ref = Column('other_ref', Unicode(256), nullable=False)
-
-    @hybrid_property
-    def revisions(self):
-        return self._revisions.split(':')
-
-    @revisions.setter
-    def revisions(self, val):
-        self._revisions = ':'.join(val)
-
-    @property
-    def org_ref_parts(self):
-        return self.org_ref.split(':')
-
-    @property
-    def other_ref_parts(self):
-        return self.other_ref.split(':')
-
-    author = relationship('User', lazy='joined')
-    reviewers = relationship('PullRequestReviewers',
-                             cascade="all, delete, delete-orphan")
-    org_repo = relationship('Repository', primaryjoin='PullRequest.org_repo_id==Repository.repo_id')
-    other_repo = relationship('Repository', primaryjoin='PullRequest.other_repo_id==Repository.repo_id')
-    statuses = relationship('ChangesetStatus')
-    comments = relationship('ChangesetComment',
-                             cascade="all, delete, delete-orphan")
-
-    def is_closed(self):
-        return self.status == self.STATUS_CLOSED
-
-    @property
-    def last_review_status(self):
-        return self.statuses[-1].status if self.statuses else ''
-
-    def __json__(self):
-        return dict(
-            revisions=self.revisions
-        )
-
-
-class PullRequestReviewers(Base, BaseModel):
-    __tablename__ = 'pull_request_reviewers'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    def __init__(self, user=None, pull_request=None):
-        self.user = user
-        self.pull_request = pull_request
-
-    pull_requests_reviewers_id = Column('pull_requests_reviewers_id', Integer(), nullable=False, primary_key=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
-
-    user = relationship('User')
-    pull_request = relationship('PullRequest')
-
-
-class Notification(Base, BaseModel):
-    __tablename__ = 'notifications'
-    __table_args__ = (
-        Index('notification_type_idx', 'type'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    TYPE_CHANGESET_COMMENT = u'cs_comment'
-    TYPE_MESSAGE = u'message'
-    TYPE_MENTION = u'mention'
-    TYPE_REGISTRATION = u'registration'
-    TYPE_PULL_REQUEST = u'pull_request'
-    TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
-
-    notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
-    subject = Column('subject', Unicode(512), nullable=True)
-    body = Column('body', UnicodeText(50000), nullable=True)
-    created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    type_ = Column('type', Unicode(256))
-
-    created_by_user = relationship('User')
-    notifications_to_users = relationship('UserNotification', lazy='joined',
-                                          cascade="all, delete, delete-orphan")
-
-    @property
-    def recipients(self):
-        return [x.user for x in UserNotification.query()\
-                .filter(UserNotification.notification == self)\
-                .order_by(UserNotification.user_id.asc()).all()]
-
-    @classmethod
-    def create(cls, created_by, subject, body, recipients, type_=None):
-        if type_ is None:
-            type_ = Notification.TYPE_MESSAGE
-
-        notification = cls()
-        notification.created_by_user = created_by
-        notification.subject = subject
-        notification.body = body
-        notification.type_ = type_
-        notification.created_on = datetime.datetime.now()
-
-        for u in recipients:
-            assoc = UserNotification()
-            assoc.notification = notification
-            u.notifications.append(assoc)
-        Session().add(notification)
-        return notification
-
-    @property
-    def description(self):
-        from kallithea.model.notification import NotificationModel
-        return NotificationModel().make_description(self)
-
-
-class UserNotification(Base, BaseModel):
-    __tablename__ = 'user_to_notification'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'notification_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
-    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
-    read = Column('read', Boolean, default=False)
-    sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
-
-    user = relationship('User', lazy="joined")
-    notification = relationship('Notification', lazy="joined",
-                                order_by=lambda: Notification.created_on.desc(),)
-
-    def mark_as_read(self):
-        self.read = True
-        Session().add(self)
-
-
-class Gist(Base, BaseModel):
-    __tablename__ = 'gists'
-    __table_args__ = (
-        Index('g_gist_access_id_idx', 'gist_access_id'),
-        Index('g_created_on_idx', 'created_on'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    GIST_PUBLIC = u'public'
-    GIST_PRIVATE = u'private'
-
-    gist_id = Column('gist_id', Integer(), primary_key=True)
-    gist_access_id = Column('gist_access_id', Unicode(250))
-    gist_description = Column('gist_description', UnicodeText(1024))
-    gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
-    gist_expires = Column('gist_expires', Float(53), nullable=False)
-    gist_type = Column('gist_type', Unicode(128), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    owner = relationship('User')
-
-    @classmethod
-    def get_or_404(cls, id_):
-        res = cls.query().filter(cls.gist_access_id == id_).scalar()
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def get_by_access_id(cls, gist_access_id):
-        return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
-
-    def gist_url(self):
-        import kallithea
-        alias_url = kallithea.CONFIG.get('gist_alias_url')
-        if alias_url:
-            return alias_url.replace('{gistid}', self.gist_access_id)
-
-        import kallithea.lib.helpers as h
-        return h.canonical_url('gist', gist_id=self.gist_access_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all gists are stored
-
-        :param cls:
-        """
-        from kallithea.model.gist import GIST_STORE_LOC
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == URL_SEP)
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return os.path.join(q.one().ui_value, GIST_STORE_LOC)
-
-    def get_api_data(self):
-        """
-        Common function for generating gist related data for API
-        """
-        gist = self
-        data = dict(
-            gist_id=gist.gist_id,
-            type=gist.gist_type,
-            access_id=gist.gist_access_id,
-            description=gist.gist_description,
-            url=gist.gist_url(),
-            expires=gist.gist_expires,
-            created_on=gist.created_on,
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-        )
-        data.update(self.get_api_data())
-        return data
-    ## SCM functions
-
-    @property
-    def scm_instance(self):
-        from kallithea.lib.vcs import get_repo
-        base_path = self.base_path()
-        return get_repo(os.path.join(*map(safe_str,
-                                          [base_path, self.gist_access_id])))
-
-
-class DbMigrateVersion(Base, BaseModel):
-    __tablename__ = 'db_migrate_version'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    repository_id = Column('repository_id', String(250), primary_key=True)
-    repository_path = Column('repository_path', Text)
-    version = Column('version', Integer)
--- a/kallithea/lib/dbmigrate/schema/db_2_0_1.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,2331 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate.schema.db_2_0_1
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Database Models for Kallithea
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Apr 08, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-import os
-import time
-import logging
-import datetime
-import traceback
-import hashlib
-import collections
-import functools
-
-from sqlalchemy import *
-from sqlalchemy.ext.hybrid import hybrid_property
-from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
-from beaker.cache import cache_region, region_invalidate
-from webob.exc import HTTPNotFound
-
-from pylons.i18n.translation import lazy_ugettext as _
-
-from kallithea.lib.vcs import get_backend
-from kallithea.lib.vcs.utils.helpers import get_scm
-from kallithea.lib.vcs.exceptions import VCSError
-from kallithea.lib.vcs.utils.lazy import LazyProperty
-from kallithea.lib.vcs.backends.base import EmptyChangeset
-
-from kallithea.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
-    safe_unicode, remove_prefix, time_to_datetime, aslist, Optional, safe_int
-from kallithea.lib.compat import json
-from kallithea.lib.caching_query import FromCache
-
-from kallithea.model.meta import Base, Session
-
-from kallithea import DB_PREFIX
-
-URL_SEP = '/'
-log = logging.getLogger(__name__)
-
-#==============================================================================
-# BASE CLASSES
-#==============================================================================
-
-_hash_key = lambda k: hashlib.md5(safe_str(k)).hexdigest()
-
-
-class BaseModel(object):
-    """
-    Base Model for all classess
-    """
-
-    @classmethod
-    def _get_keys(cls):
-        """return column names for this model """
-        return class_mapper(cls).c.keys()
-
-    def get_dict(self):
-        """
-        return dict with keys and values corresponding
-        to this model data """
-
-        d = {}
-        for k in self._get_keys():
-            d[k] = getattr(self, k)
-
-        # also use __json__() if present to get additional fields
-        _json_attr = getattr(self, '__json__', None)
-        if _json_attr:
-            # update with attributes from __json__
-            if callable(_json_attr):
-                _json_attr = _json_attr()
-            for k, val in _json_attr.iteritems():
-                d[k] = val
-        return d
-
-    def get_appstruct(self):
-        """return list with keys and values tuples corresponding
-        to this model data """
-
-        l = []
-        for k in self._get_keys():
-            l.append((k, getattr(self, k),))
-        return l
-
-    def populate_obj(self, populate_dict):
-        """populate model with data from given populate_dict"""
-
-        for k in self._get_keys():
-            if k in populate_dict:
-                setattr(self, k, populate_dict[k])
-
-    @classmethod
-    def query(cls):
-        return Session().query(cls)
-
-    @classmethod
-    def get(cls, id_):
-        if id_:
-            return cls.query().get(id_)
-
-    @classmethod
-    def get_or_404(cls, id_):
-        try:
-            id_ = int(id_)
-        except (TypeError, ValueError):
-            raise HTTPNotFound
-
-        res = cls.query().get(id_)
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def getAll(cls):
-        # deprecated and left for backward compatibility
-        return cls.get_all()
-
-    @classmethod
-    def get_all(cls):
-        return cls.query().all()
-
-    @classmethod
-    def delete(cls, id_):
-        obj = cls.query().get(id_)
-        Session().delete(obj)
-
-    def __repr__(self):
-        if hasattr(self, '__unicode__'):
-            # python repr needs to return str
-            try:
-                return safe_str(self.__unicode__())
-            except UnicodeDecodeError:
-                pass
-        return '<DB:%s>' % (self.__class__.__name__)
-
-
-class Setting(Base, BaseModel):
-    SETTINGS_TYPES = {
-        'str': safe_str,
-        'int': safe_int,
-        'unicode': safe_unicode,
-        'bool': str2bool,
-        'list': functools.partial(aslist, sep=',')
-    }
-    __tablename__ = DB_PREFIX + 'settings'
-    __table_args__ = (
-        UniqueConstraint('app_settings_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    app_settings_name = Column("app_settings_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_value = Column("app_settings_value", String(4096, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_type = Column("app_settings_type", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __init__(self, key='', val='', type='unicode'):
-        self.app_settings_name = key
-        self.app_settings_value = val
-        self.app_settings_type = type
-
-    @validates('_app_settings_value')
-    def validate_settings_value(self, key, val):
-        assert type(val) == unicode
-        return val
-
-    @hybrid_property
-    def app_settings_value(self):
-        v = self._app_settings_value
-        _type = self.app_settings_type
-        converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
-        return converter(v)
-
-    @app_settings_value.setter
-    def app_settings_value(self, val):
-        """
-        Setter that will always make sure we use unicode in app_settings_value
-
-        :param val:
-        """
-        self._app_settings_value = safe_unicode(val)
-
-    @hybrid_property
-    def app_settings_type(self):
-        return self._app_settings_type
-
-    @app_settings_type.setter
-    def app_settings_type(self, val):
-        if val not in self.SETTINGS_TYPES:
-            raise Exception('type must be one of %s got %s'
-                            % (self.SETTINGS_TYPES.keys(), val))
-        self._app_settings_type = val
-
-    def __unicode__(self):
-        return u"<%s('%s:%s[%s]')>" % (
-            self.__class__.__name__,
-            self.app_settings_name, self.app_settings_value, self.app_settings_type
-        )
-
-    @classmethod
-    def get_by_name(cls, key):
-        return cls.query()\
-            .filter(cls.app_settings_name == key).scalar()
-
-    @classmethod
-    def get_by_name_or_create(cls, key, val='', type='unicode'):
-        res = cls.get_by_name(key)
-        if not res:
-            res = cls(key, val, type)
-        return res
-
-    @classmethod
-    def create_or_update(cls, key, val=Optional(''), type=Optional('unicode')):
-        """
-        Creates or updates Kallithea setting. If updates is triggered it will only
-        update parameters that are explicityl set Optional instance will be skipped
-
-        :param key:
-        :param val:
-        :param type:
-        :return:
-        """
-        res = cls.get_by_name(key)
-        if not res:
-            val = Optional.extract(val)
-            type = Optional.extract(type)
-            res = cls(key, val, type)
-        else:
-            res.app_settings_name = key
-            if not isinstance(val, Optional):
-                # update if set
-                res.app_settings_value = val
-            if not isinstance(type, Optional):
-                # update if set
-                res.app_settings_type = type
-        return res
-
-    @classmethod
-    def get_app_settings(cls, cache=False):
-
-        ret = cls.query()
-
-        if cache:
-            ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
-
-        if not ret:
-            raise Exception('Could not get application settings !')
-        settings = {}
-        for each in ret:
-            settings[each.app_settings_name] = \
-                each.app_settings_value
-
-        return settings
-
-    @classmethod
-    def get_auth_plugins(cls, cache=False):
-        auth_plugins = cls.get_by_name("auth_plugins").app_settings_value
-        return auth_plugins
-
-    @classmethod
-    def get_auth_settings(cls, cache=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('auth_')).all()
-        fd = {}
-        for row in ret:
-            fd.update({row.app_settings_name: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_default_repo_settings(cls, cache=False, strip_prefix=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('default_')).all()
-        fd = {}
-        for row in ret:
-            key = row.app_settings_name
-            if strip_prefix:
-                key = remove_prefix(key, prefix='default_')
-            fd.update({key: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_server_info(cls):
-        import pkg_resources
-        import platform
-        import kallithea
-        from kallithea.lib.utils import check_git_version
-        mods = [(p.project_name, p.version) for p in pkg_resources.working_set]
-        info = {
-            'modules': sorted(mods, key=lambda k: k[0].lower()),
-            'py_version': platform.python_version(),
-            'platform': safe_unicode(platform.platform()),
-            'kallithea_version': kallithea.__version__,
-            'git_version': safe_unicode(check_git_version()),
-            'git_path': kallithea.CONFIG.get('git_path')
-        }
-        return info
-
-
-class Ui(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'ui'
-    __table_args__ = (
-        UniqueConstraint('ui_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    HOOK_UPDATE = 'changegroup.update'
-    HOOK_REPO_SIZE = 'changegroup.repo_size'
-    HOOK_PUSH = 'changegroup.push_logger'
-    HOOK_PRE_PUSH = 'prechangegroup.pre_push'
-    HOOK_PULL = 'outgoing.pull_logger'
-    HOOK_PRE_PULL = 'preoutgoing.pre_pull'
-
-    ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    ui_section = Column("ui_section", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_key = Column("ui_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_value = Column("ui_value", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
-
-    # def __init__(self, section='', key='', value=''):
-    #     self.ui_section = section
-    #     self.ui_key = key
-    #     self.ui_value = value
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.ui_key == key).scalar()
-
-    @classmethod
-    def get_builtin_hooks(cls):
-        q = cls.query()
-        q = q.filter(cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                     cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                     cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        return q.all()
-
-    @classmethod
-    def get_custom_hooks(cls):
-        q = cls.query()
-        q = q.filter(~cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                      cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                      cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        q = q.filter(cls.ui_section == 'hooks')
-        return q.all()
-
-    @classmethod
-    def get_repos_location(cls):
-        return cls.get_by_key('/').ui_value
-
-    @classmethod
-    def create_or_update_hook(cls, key, val):
-        new_ui = cls.get_by_key(key) or cls()
-        new_ui.ui_section = 'hooks'
-        new_ui.ui_active = True
-        new_ui.ui_key = key
-        new_ui.ui_value = val
-
-        Session().add(new_ui)
-
-    def __repr__(self):
-        return '<DB:%s[%s:%s]>' % (self.__class__.__name__, self.ui_key,
-                                   self.ui_value)
-
-
-class User(Base, BaseModel):
-    __tablename__ = 'users'
-    __table_args__ = (
-        UniqueConstraint('username'), UniqueConstraint('email'),
-        Index('u_username_idx', 'username'),
-        Index('u_email_idx', 'email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    DEFAULT_USER = 'default'
-
-    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    password = Column("password", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
-    name = Column("firstname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    lastname = Column("lastname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
-    extern_type = Column("extern_type", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    extern_name = Column("extern_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    api_key = Column("api_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    user_log = relationship('UserLog')
-    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
-
-    repositories = relationship('Repository')
-    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
-    followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
-
-    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
-
-    group_member = relationship('UserGroupMember', cascade='all')
-
-    notifications = relationship('UserNotification', cascade='all')
-    # notifications assigned to this user
-    user_created_notifications = relationship('Notification', cascade='all')
-    # comments created by this user
-    user_comments = relationship('ChangesetComment', cascade='all')
-    #extra emails for this user
-    user_emails = relationship('UserEmailMap', cascade='all')
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-    @property
-    def firstname(self):
-        # alias for future
-        return self.name
-
-    @property
-    def emails(self):
-        other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
-        return [self.email] + [x.email for x in other]
-
-    @property
-    def ip_addresses(self):
-        ret = UserIpMap.query().filter(UserIpMap.user == self).all()
-        return [x.ip_addr for x in ret]
-
-    @property
-    def username_and_name(self):
-        return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
-
-    @property
-    def full_name(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def full_name_or_username(self):
-        return ('%s %s' % (self.firstname, self.lastname)
-                if (self.firstname and self.lastname) else self.username)
-
-    @property
-    def full_contact(self):
-        return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
-
-    @property
-    def short_contact(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def is_admin(self):
-        return self.admin
-
-    @property
-    def AuthUser(self):
-        """
-        Returns instance of AuthUser for this user
-        """
-        from kallithea.lib.auth import AuthUser
-        return AuthUser(user_id=self.user_id, api_key=self.api_key,
-                        username=self.username)
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.user_id, self.username)
-
-    @classmethod
-    def get_by_username(cls, username, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.username.ilike(username))
-        else:
-            q = cls.query().filter(cls.username == username)
-
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(username)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get_by_api_key(cls, api_key, cache=False):
-        q = cls.query().filter(cls.api_key == api_key)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_api_key_%s" % api_key))
-        return q.scalar()
-
-    @classmethod
-    def get_by_email(cls, email, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.email.ilike(email))
-        else:
-            q = cls.query().filter(cls.email == email)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_email_key_%s" % email))
-
-        ret = q.scalar()
-        if ret is None:
-            q = UserEmailMap.query()
-            # try fetching in alternate email map
-            if case_insensitive:
-                q = q.filter(UserEmailMap.email.ilike(email))
-            else:
-                q = q.filter(UserEmailMap.email == email)
-            q = q.options(joinedload(UserEmailMap.user))
-            if cache:
-                q = q.options(FromCache("sql_cache_short",
-                                        "get_email_map_key_%s" % email))
-            ret = getattr(q.scalar(), 'user', None)
-
-        return ret
-
-    @classmethod
-    def get_from_cs_author(cls, author):
-        """
-        Tries to get User objects out of commit author string
-
-        :param author:
-        """
-        from kallithea.lib.helpers import email, author_name
-        # Valid email in the attribute passed, see if they're in the system
-        _email = email(author)
-        if _email:
-            user = cls.get_by_email(_email, case_insensitive=True)
-            if user:
-                return user
-        # Maybe we can match by username?
-        _author = author_name(author)
-        user = cls.get_by_username(_author, case_insensitive=True)
-        if user:
-            return user
-
-    def update_lastlogin(self):
-        """Update user lastlogin"""
-        self.last_login = datetime.datetime.now()
-        Session().add(self)
-        log.debug('updated user %s lastlogin', self.username)
-
-    @classmethod
-    def get_first_admin(cls):
-        user = User.query().filter(User.admin == True).first()
-        if user is None:
-            raise Exception('Missing administrative account!')
-        return user
-
-    @classmethod
-    def get_default_user(cls, cache=False):
-        user = User.get_by_username(User.DEFAULT_USER, cache=cache)
-        if user is None:
-            raise Exception('Missing default account!')
-        return user
-
-    def get_api_data(self):
-        """
-        Common function for generating user related data for API
-        """
-        user = self
-        data = dict(
-            user_id=user.user_id,
-            username=user.username,
-            firstname=user.name,
-            lastname=user.lastname,
-            email=user.email,
-            emails=user.emails,
-            api_key=user.api_key,
-            active=user.active,
-            admin=user.admin,
-            extern_type=user.extern_type,
-            extern_name=user.extern_name,
-            last_login=user.last_login,
-            ip_addresses=user.ip_addresses
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-            full_name=self.full_name,
-            full_name_or_username=self.full_name_or_username,
-            short_contact=self.short_contact,
-            full_contact=self.full_contact
-        )
-        data.update(self.get_api_data())
-        return data
-
-
-class UserEmailMap(Base, BaseModel):
-    __tablename__ = 'user_email_map'
-    __table_args__ = (
-        Index('uem_email_idx', 'email'),
-        UniqueConstraint('email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    user = relationship('User', lazy='joined')
-
-    @validates('_email')
-    def validate_email(self, key, email):
-        # check if this email is not main one
-        main_email = Session().query(User).filter(User.email == email).scalar()
-        if main_email is not None:
-            raise AttributeError('email %s is present is user table' % email)
-        return email
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-
-class UserIpMap(Base, BaseModel):
-    __tablename__ = 'user_ip_map'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'ip_addr'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    ip_addr = Column("ip_addr", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    user = relationship('User', lazy='joined')
-
-    @classmethod
-    def _get_ip_range(cls, ip_addr):
-        from kallithea.lib import ipaddr
-        net = ipaddr.IPNetwork(address=ip_addr)
-        return [str(net.network), str(net.broadcast)]
-
-    def __json__(self):
-        return dict(
-          ip_addr=self.ip_addr,
-          ip_range=self._get_ip_range(self.ip_addr)
-        )
-
-
-class UserLog(Base, BaseModel):
-    __tablename__ = 'user_logs'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
-    repository_name = Column("repository_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    user_ip = Column("user_ip", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action = Column("action", UnicodeText(1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.repository_name,
-                                      self.action)
-
-    @property
-    def action_as_day(self):
-        return datetime.date(*self.action_date.timetuple()[:3])
-
-    user = relationship('User')
-    repository = relationship('Repository', cascade='')
-
-
-class UserGroup(Base, BaseModel):
-    __tablename__ = 'users_groups'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_name = Column("users_group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    user_group_description = Column("user_group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
-    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
-    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-    user_user_group_to_perm = relationship('UserUserGroupToPerm ', cascade='all')
-    user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
-
-    user = relationship('User')
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.users_group_id,
-                                      self.users_group_name)
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False,
-                          case_insensitive=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.users_group_name.ilike(group_name))
-        else:
-            q = cls.query().filter(cls.users_group_name == group_name)
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(group_name)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get(cls, user_group_id, cache=False):
-        user_group = cls.query()
-        if cache:
-            user_group = user_group.options(FromCache("sql_cache_short",
-                                    "get_users_group_%s" % user_group_id))
-        return user_group.get(user_group_id)
-
-    def get_api_data(self, with_members=True):
-        user_group = self
-
-        data = dict(
-            users_group_id=user_group.users_group_id,
-            group_name=user_group.users_group_name,
-            group_description=user_group.user_group_description,
-            active=user_group.users_group_active,
-            owner=user_group.user.username,
-        )
-        if with_members:
-            members = []
-            for user in user_group.members:
-                user = user.user
-                members.append(user.get_api_data())
-            data['members'] = members
-
-        return data
-
-
-class UserGroupMember(Base, BaseModel):
-    __tablename__ = 'users_groups_members'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User', lazy='joined')
-    users_group = relationship('UserGroup')
-
-    def __init__(self, gr_id='', u_id=''):
-        self.users_group_id = gr_id
-        self.user_id = u_id
-
-
-class RepositoryField(Base, BaseModel):
-    __tablename__ = 'repositories_fields'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'field_key'),  # no-multi field
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    PREFIX = 'ex_'  # prefix used in form to not conflict with already existing fields
-
-    repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-    field_key = Column("field_key", String(250, convert_unicode=False, assert_unicode=None))
-    field_label = Column("field_label", String(1024, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_value = Column("field_value", String(10000, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_desc = Column("field_desc", String(1024, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_type = Column("field_type", String(256), nullable=False, unique=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    repository = relationship('Repository')
-
-    @property
-    def field_key_prefixed(self):
-        return 'ex_%s' % self.field_key
-
-    @classmethod
-    def un_prefix_key(cls, key):
-        if key.startswith(cls.PREFIX):
-            return key[len(cls.PREFIX):]
-        return key
-
-    @classmethod
-    def get_by_key_name(cls, key, repo):
-        row = cls.query()\
-                .filter(cls.repository == repo)\
-                .filter(cls.field_key == key).scalar()
-        return row
-
-
-class Repository(Base, BaseModel):
-    __tablename__ = 'repositories'
-    __table_args__ = (
-        UniqueConstraint('repo_name'),
-        Index('r_repo_name_idx', 'repo_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repo_name = Column("repo_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    clone_uri = Column("clone_uri", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    repo_type = Column("repo_type", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
-    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
-    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
-    description = Column("description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    landing_rev = Column("landing_revision", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    _locked = Column("locked", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) #JSON data
-
-    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
-
-    user = relationship('User')
-    fork = relationship('Repository', remote_side=repo_id)
-    group = relationship('RepoGroup')
-    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    stats = relationship('Statistics', cascade='all', uselist=False)
-
-    followers = relationship('UserFollowing',
-                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
-                             cascade='all')
-    extra_fields = relationship('RepositoryField',
-                                cascade="all, delete, delete-orphan")
-
-    logs = relationship('UserLog')
-    comments = relationship('ChangesetComment', cascade="all, delete, delete-orphan")
-
-    pull_requests_org = relationship('PullRequest',
-                    primaryjoin='PullRequest.org_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    pull_requests_other = relationship('PullRequest',
-                    primaryjoin='PullRequest.other_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
-                                   safe_unicode(self.repo_name))
-
-    @hybrid_property
-    def locked(self):
-        # always should return [user_id, timelocked]
-        if self._locked:
-            _lock_info = self._locked.split(':')
-            return int(_lock_info[0]), _lock_info[1]
-        return [None, None]
-
-    @locked.setter
-    def locked(self, val):
-        if val and isinstance(val, (list, tuple)):
-            self._locked = ':'.join(map(str, val))
-        else:
-            self._locked = None
-
-    @hybrid_property
-    def changeset_cache(self):
-        from kallithea.lib.vcs.backends.base import EmptyChangeset
-        dummy = EmptyChangeset().__json__()
-        if not self._changeset_cache:
-            return dummy
-        try:
-            return json.loads(self._changeset_cache)
-        except TypeError:
-            return dummy
-
-    @changeset_cache.setter
-    def changeset_cache(self, val):
-        try:
-            self._changeset_cache = json.dumps(val)
-        except Exception:
-            log.error(traceback.format_exc())
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def normalize_repo_name(cls, repo_name):
-        """
-        Normalizes os specific repo_name to the format internally stored inside
-        dabatabase using URL_SEP
-
-        :param cls:
-        :param repo_name:
-        """
-        return cls.url_sep().join(repo_name.split(os.sep))
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        q = Session().query(cls).filter(cls.repo_name == repo_name)
-        q = q.options(joinedload(Repository.fork))\
-                .options(joinedload(Repository.user))\
-                .options(joinedload(Repository.group))
-        return q.scalar()
-
-    @classmethod
-    def get_by_full_path(cls, repo_full_path):
-        repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
-        repo_name = cls.normalize_repo_name(repo_name)
-        return cls.get_by_repo_name(repo_name.strip(URL_SEP))
-
-    @classmethod
-    def get_repo_forks(cls, repo_id):
-        return cls.query().filter(Repository.fork_id == repo_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all repos are stored
-
-        :param cls:
-        """
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == cls.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def forks(self):
-        """
-        Return forks of this repo
-        """
-        return Repository.get_repo_forks(self.repo_id)
-
-    @property
-    def parent(self):
-        """
-        Returns fork parent
-        """
-        return self.fork
-
-    @property
-    def just_name(self):
-        return self.repo_name.split(Repository.url_sep())[-1]
-
-    @property
-    def groups_with_parents(self):
-        groups = []
-        if self.group is None:
-            return groups
-
-        cur_gr = self.group
-        groups.insert(0, cur_gr)
-        while 1:
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            groups.insert(0, gr)
-
-        return groups
-
-    @property
-    def groups_and_repo(self):
-        return self.groups_with_parents, self.just_name, self.repo_name
-
-    @LazyProperty
-    def repo_path(self):
-        """
-        Returns base full path for that repository means where it actually
-        exists on a filesystem
-        """
-        q = Session().query(Ui).filter(Ui.ui_key ==
-                                              Repository.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def repo_full_path(self):
-        p = [self.repo_path]
-        # we need to split the name by / since this is how we store the
-        # names in the database, but that eventually needs to be converted
-        # into a valid system path
-        p += self.repo_name.split(Repository.url_sep())
-        return os.path.join(*map(safe_unicode, p))
-
-    @property
-    def cache_keys(self):
-        """
-        Returns associated cache keys for that repo
-        """
-        return CacheInvalidation.query()\
-            .filter(CacheInvalidation.cache_args == self.repo_name)\
-            .order_by(CacheInvalidation.cache_key)\
-            .all()
-
-    def get_new_name(self, repo_name):
-        """
-        returns new full repository name based on assigned group and new new
-
-        :param group_name:
-        """
-        path_prefix = self.group.full_path_splitted if self.group else []
-        return Repository.url_sep().join(path_prefix + [repo_name])
-
-    @property
-    def _ui(self):
-        """
-        Creates an db based ui object for this repository
-        """
-        from kallithea.lib.utils import make_ui
-        return make_ui('db', clear_session=False)
-
-    @classmethod
-    def is_valid(cls, repo_name):
-        """
-        returns True if given repo name is a valid filesystem repository
-
-        :param cls:
-        :param repo_name:
-        """
-        from kallithea.lib.utils import is_valid_repo
-
-        return is_valid_repo(repo_name, cls.base_path())
-
-    def get_api_data(self):
-        """
-        Common function for generating repo api data
-
-        """
-        repo = self
-        data = dict(
-            repo_id=repo.repo_id,
-            repo_name=repo.repo_name,
-            repo_type=repo.repo_type,
-            clone_uri=repo.clone_uri,
-            private=repo.private,
-            created_on=repo.created_on,
-            description=repo.description,
-            landing_rev=repo.landing_rev,
-            owner=repo.user.username,
-            fork_of=repo.fork.repo_name if repo.fork else None,
-            enable_statistics=repo.enable_statistics,
-            enable_locking=repo.enable_locking,
-            enable_downloads=repo.enable_downloads,
-            last_changeset=repo.changeset_cache,
-            locked_by=User.get(self.locked[0]).get_api_data() \
-                if self.locked[0] else None,
-            locked_date=time_to_datetime(self.locked[1]) \
-                if self.locked[1] else None
-        )
-        rc_config = Setting.get_app_settings()
-        repository_fields = str2bool(rc_config.get('repository_fields'))
-        if repository_fields:
-            for f in self.extra_fields:
-                data[f.field_key_prefixed] = f.field_value
-
-        return data
-
-    @classmethod
-    def lock(cls, repo, user_id, lock_time=None):
-        if not lock_time:
-            lock_time = time.time()
-        repo.locked = [user_id, lock_time]
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def unlock(cls, repo):
-        repo.locked = None
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def getlock(cls, repo):
-        return repo.locked
-
-    @property
-    def last_db_change(self):
-        return self.updated_on
-
-    def clone_url(self, **override):
-        import kallithea.lib.helpers as h
-        from urlparse import urlparse
-        import urllib
-        parsed_url = urlparse(h.canonical_url('home'))
-        default_clone_uri = '%(scheme)s://%(user)s%(pass)s%(netloc)s%(prefix)s%(path)s'
-        decoded_path = safe_unicode(urllib.unquote(parsed_url.path))
-        args = {
-           'user': '',
-           'pass': '',
-           'scheme': parsed_url.scheme,
-           'netloc': parsed_url.netloc,
-           'prefix': decoded_path,
-           'path': self.repo_name
-        }
-
-        args.update(override)
-        return default_clone_uri % args
-
-    #==========================================================================
-    # SCM PROPERTIES
-    #==========================================================================
-
-    def get_changeset(self, rev=None):
-        return get_changeset_safe(self.scm_instance, rev)
-
-    def get_landing_changeset(self):
-        """
-        Returns landing changeset, or if that doesn't exist returns the tip
-        """
-        cs = self.get_changeset(self.landing_rev) or self.get_changeset()
-        return cs
-
-    def update_changeset_cache(self, cs_cache=None):
-        """
-        Update cache of last changeset for repository, keys should be::
-
-            short_id
-            raw_id
-            revision
-            message
-            date
-            author
-
-        :param cs_cache:
-        """
-        from kallithea.lib.vcs.backends.base import BaseChangeset
-        if cs_cache is None:
-            cs_cache = EmptyChangeset()
-            # use no-cache version here
-            scm_repo = self.scm_instance_no_cache()
-            if scm_repo:
-                cs_cache = scm_repo.get_changeset()
-
-        if isinstance(cs_cache, BaseChangeset):
-            cs_cache = cs_cache.__json__()
-
-        if (cs_cache != self.changeset_cache or not self.changeset_cache):
-            _default = datetime.datetime.fromtimestamp(0)
-            last_change = cs_cache.get('date') or _default
-            log.debug('updated repo %s with new cs cache %s',
-                      self.repo_name, cs_cache)
-            self.updated_on = last_change
-            self.changeset_cache = cs_cache
-            Session().add(self)
-            Session().commit()
-        else:
-            log.debug('Skipping repo:%s already with latest changes',
-                      self.repo_name)
-
-    @property
-    def tip(self):
-        return self.get_changeset('tip')
-
-    @property
-    def author(self):
-        return self.tip.author
-
-    @property
-    def last_change(self):
-        return self.scm_instance.last_change
-
-    def get_comments(self, revisions=None):
-        """
-        Returns comments for this repository grouped by revisions
-
-        :param revisions: filter query by revisions only
-        """
-        cmts = ChangesetComment.query()\
-            .filter(ChangesetComment.repo == self)
-        if revisions:
-            cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
-        grouped = collections.defaultdict(list)
-        for cmt in cmts.all():
-            grouped[cmt.revision].append(cmt)
-        return grouped
-
-    def statuses(self, revisions=None):
-        """
-        Returns statuses for this repository
-
-        :param revisions: list of revisions to get statuses for
-        """
-
-        statuses = ChangesetStatus.query()\
-            .filter(ChangesetStatus.repo == self)\
-            .filter(ChangesetStatus.version == 0)
-        if revisions:
-            statuses = statuses.filter(ChangesetStatus.revision.in_(revisions))
-        grouped = {}
-
-        #maybe we have open new pullrequest without a status ?
-        stat = ChangesetStatus.STATUS_UNDER_REVIEW
-        status_lbl = ChangesetStatus.get_status_lbl(stat)
-        for pr in PullRequest.query().filter(PullRequest.org_repo == self).all():
-            for rev in pr.revisions:
-                pr_id = pr.pull_request_id
-                pr_repo = pr.other_repo.repo_name
-                grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
-
-        for stat in statuses.all():
-            pr_id = pr_repo = None
-            if stat.pull_request:
-                pr_id = stat.pull_request.pull_request_id
-                pr_repo = stat.pull_request.other_repo.repo_name
-            grouped[stat.revision] = [str(stat.status), stat.status_lbl,
-                                      pr_id, pr_repo]
-        return grouped
-
-    def _repo_size(self):
-        from kallithea.lib import helpers as h
-        log.debug('calculating repository size...')
-        return h.format_byte_size(self.scm_instance.size)
-
-    #==========================================================================
-    # SCM CACHE INSTANCE
-    #==========================================================================
-
-    def set_invalidate(self):
-        """
-        Mark caches of this repo as invalid.
-        """
-        CacheInvalidation.set_invalidate(self.repo_name)
-
-    def scm_instance_no_cache(self):
-        return self.__get_instance()
-
-    @property
-    def scm_instance(self):
-        import kallithea
-        full_cache = str2bool(kallithea.CONFIG.get('vcs_full_cache'))
-        if full_cache:
-            return self.scm_instance_cached()
-        return self.__get_instance()
-
-    def scm_instance_cached(self, valid_cache_keys=None):
-        @cache_region('long_term')
-        def _c(repo_name):
-            return self.__get_instance()
-        rn = self.repo_name
-
-        valid = CacheInvalidation.test_and_set_valid(rn, None, valid_cache_keys=valid_cache_keys)
-        if not valid:
-            log.debug('Cache for %s invalidated, getting new object', rn)
-            region_invalidate(_c, None, rn)
-        else:
-            log.debug('Getting obj for %s from cache', rn)
-        return _c(rn)
-
-    def __get_instance(self):
-        repo_full_path = self.repo_full_path
-        try:
-            alias = get_scm(repo_full_path)[0]
-            log.debug('Creating instance of %s repository from %s',
-                      alias, repo_full_path)
-            backend = get_backend(alias)
-        except VCSError:
-            log.error(traceback.format_exc())
-            log.error('Perhaps this repository is in db and not in '
-                      'filesystem run rescan repositories with '
-                      '"destroy old data " option from admin panel')
-            return
-
-        if alias == 'hg':
-
-            repo = backend(safe_str(repo_full_path), create=False,
-                           baseui=self._ui)
-        else:
-            repo = backend(repo_full_path, create=False)
-
-        return repo
-
-
-class RepoGroup(Base, BaseModel):
-    __tablename__ = 'groups'
-    __table_args__ = (
-        UniqueConstraint('group_name', 'group_parent_id'),
-        CheckConstraint('group_id != group_parent_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    __mapper_args__ = {'order_by': 'group_name'}
-
-    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    group_name = Column("group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
-    group_description = Column("group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    #TODO: create this field in migrations
-    #created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-    parent_group = relationship('RepoGroup', remote_side=group_id)
-    user = relationship('User')
-
-    def __init__(self, group_name='', parent_group=None):
-        self.group_name = group_name
-        self.parent_group = parent_group
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
-                                      self.group_name)
-
-    @classmethod
-    def groups_choices(cls, groups=None, show_empty_group=True):
-        from webhelpers.html import literal as _literal
-        if not groups:
-            groups = cls.query().all()
-
-        repo_groups = []
-        if show_empty_group:
-            repo_groups = [('-1', u'-- %s --' % _('top level'))]
-        sep = ' &raquo; '
-        _name = lambda k: _literal(sep.join(k))
-
-        repo_groups.extend([(x.group_id, _name(x.full_path_splitted))
-                              for x in groups])
-
-        repo_groups = sorted(repo_groups, key=lambda t: t[1].split(sep)[0])
-        return repo_groups
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
-        if case_insensitive:
-            gr = cls.query()\
-                .filter(cls.group_name.ilike(group_name))
-        else:
-            gr = cls.query()\
-                .filter(cls.group_name == group_name)
-        if cache:
-            gr = gr.options(FromCache(
-                            "sql_cache_short",
-                            "get_group_%s" % _hash_key(group_name)
-                            )
-            )
-        return gr.scalar()
-
-    @property
-    def parents(self):
-        parents_recursion_limit = 5
-        groups = []
-        if self.parent_group is None:
-            return groups
-        cur_gr = self.parent_group
-        groups.insert(0, cur_gr)
-        cnt = 0
-        while 1:
-            cnt += 1
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            if cnt == parents_recursion_limit:
-                # this will prevent accidental infinite loops
-                log.error('group nested more than %s',
-                          parents_recursion_limit)
-                break
-
-            groups.insert(0, gr)
-        return groups
-
-    @property
-    def children(self):
-        return RepoGroup.query().filter(RepoGroup.parent_group == self)
-
-    @property
-    def name(self):
-        return self.group_name.split(RepoGroup.url_sep())[-1]
-
-    @property
-    def full_path(self):
-        return self.group_name
-
-    @property
-    def full_path_splitted(self):
-        return self.group_name.split(RepoGroup.url_sep())
-
-    @property
-    def repositories(self):
-        return Repository.query()\
-                .filter(Repository.group == self)\
-                .order_by(Repository.repo_name)
-
-    @property
-    def repositories_recursive_count(self):
-        cnt = self.repositories.count()
-
-        def children_count(group):
-            cnt = 0
-            for child in group.children:
-                cnt += child.repositories.count()
-                cnt += children_count(child)
-            return cnt
-
-        return cnt + children_count(self)
-
-    def _recursive_objects(self, include_repos=True):
-        all_ = []
-
-        def _get_members(root_gr):
-            if include_repos:
-                for r in root_gr.repositories:
-                    all_.append(r)
-            childs = root_gr.children.all()
-            if childs:
-                for gr in childs:
-                    all_.append(gr)
-                    _get_members(gr)
-
-        _get_members(self)
-        return [self] + all_
-
-    def recursive_groups_and_repos(self):
-        """
-        Recursive return all groups, with repositories in those groups
-        """
-        return self._recursive_objects()
-
-    def recursive_groups(self):
-        """
-        Returns all children groups for this group including children of children
-        """
-        return self._recursive_objects(include_repos=False)
-
-    def get_new_name(self, group_name):
-        """
-        returns new full group name based on parent and new name
-
-        :param group_name:
-        """
-        path_prefix = (self.parent_group.full_path_splitted if
-                       self.parent_group else [])
-        return RepoGroup.url_sep().join(path_prefix + [group_name])
-
-    def get_api_data(self):
-        """
-        Common function for generating api data
-
-        """
-        group = self
-        data = dict(
-            group_id=group.group_id,
-            group_name=group.group_name,
-            group_description=group.group_description,
-            parent_group=group.parent_group.group_name if group.parent_group else None,
-            repositories=[x.repo_name for x in group.repositories],
-            owner=group.user.username
-        )
-        return data
-
-
-class Permission(Base, BaseModel):
-    __tablename__ = 'permissions'
-    __table_args__ = (
-        Index('p_perm_name_idx', 'permission_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    PERMS = [
-        ('hg.admin', _('Kallithea Administrator')),
-
-        ('repository.none', _('Repository no access')),
-        ('repository.read', _('Repository read access')),
-        ('repository.write', _('Repository write access')),
-        ('repository.admin', _('Repository admin access')),
-
-        ('group.none', _('Repository group no access')),
-        ('group.read', _('Repository group read access')),
-        ('group.write', _('Repository group write access')),
-        ('group.admin', _('Repository group admin access')),
-
-        ('usergroup.none', _('User group no access')),
-        ('usergroup.read', _('User group read access')),
-        ('usergroup.write', _('User group write access')),
-        ('usergroup.admin', _('User group admin access')),
-
-        ('hg.repogroup.create.false', _('Repository Group creation disabled')),
-        ('hg.repogroup.create.true', _('Repository Group creation enabled')),
-
-        ('hg.usergroup.create.false', _('User Group creation disabled')),
-        ('hg.usergroup.create.true', _('User Group creation enabled')),
-
-        ('hg.create.none', _('Repository creation disabled')),
-        ('hg.create.repository', _('Repository creation enabled')),
-
-        ('hg.fork.none', _('Repository forking disabled')),
-        ('hg.fork.repository', _('Repository forking enabled')),
-
-        ('hg.register.none', _('Registration disabled')),
-        ('hg.register.manual_activate', _('User Registration with manual account activation')),
-        ('hg.register.auto_activate', _('User Registration with automatic account activation')),
-
-        ('hg.extern_activate.manual', _('Manual activation of external account')),
-        ('hg.extern_activate.auto', _('Automatic activation of external account')),
-
-    ]
-
-    #definition of system default permissions for DEFAULT user
-    DEFAULT_USER_PERMISSIONS = [
-        'repository.read',
-        'group.read',
-        'usergroup.read',
-        'hg.create.repository',
-        'hg.fork.repository',
-        'hg.register.manual_activate',
-        'hg.extern_activate.auto',
-    ]
-
-    # defines which permissions are more important higher the more important
-    # Weight defines which permissions are more important.
-    # The higher number the more important.
-    PERM_WEIGHTS = {
-        'repository.none': 0,
-        'repository.read': 1,
-        'repository.write': 3,
-        'repository.admin': 4,
-
-        'group.none': 0,
-        'group.read': 1,
-        'group.write': 3,
-        'group.admin': 4,
-
-        'usergroup.none': 0,
-        'usergroup.read': 1,
-        'usergroup.write': 3,
-        'usergroup.admin': 4,
-        'hg.repogroup.create.false': 0,
-        'hg.repogroup.create.true': 1,
-
-        'hg.usergroup.create.false': 0,
-        'hg.usergroup.create.true': 1,
-
-        'hg.fork.none': 0,
-        'hg.fork.repository': 1,
-        'hg.create.none': 0,
-        'hg.create.repository': 1
-    }
-
-    permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    permission_name = Column("permission_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    permission_longname = Column("permission_longname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__, self.permission_id, self.permission_name
-        )
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.permission_name == key).scalar()
-
-    @classmethod
-    def get_default_perms(cls, default_user_id):
-        q = Session().query(UserRepoToPerm, Repository, cls)\
-         .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
-         .join((cls, UserRepoToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_group_perms(cls, default_user_id):
-        q = Session().query(UserRepoGroupToPerm, RepoGroup, cls)\
-         .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
-         .join((cls, UserRepoGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_user_group_perms(cls, default_user_id):
-        q = Session().query(UserUserGroupToPerm, UserGroup, cls)\
-         .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
-         .join((cls, UserUserGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserUserGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-
-class UserRepoToPerm(Base, BaseModel):
-    __tablename__ = 'repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'repository_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    repository = relationship('Repository')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, repository, permission):
-        n = cls()
-        n.user = user
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.repository)
-
-
-class UserUserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_user_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    user_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, user_group, permission):
-        n = cls()
-        n.user = user
-        n.user_group = user_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.user_group)
-
-
-class UserToPerm(Base, BaseModel):
-    __tablename__ = 'user_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    permission = relationship('Permission', lazy='joined')
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.permission)
-
-
-class UserGroupRepoToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    repository = relationship('Repository')
-
-    @classmethod
-    def create(cls, users_group, repository, permission):
-        n = cls()
-        n.users_group = users_group
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
-
-
-class UserGroupUserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_group_user_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
-        CheckConstraint('target_user_group_id != user_group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-
-    target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
-    user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, target_user_group, user_group, permission):
-        n = cls()
-        n.target_user_group = target_user_group
-        n.user_group = user_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
-
-
-class UserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'permission_id',),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-
-class UserRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    group = relationship('RepoGroup')
-    permission = relationship('Permission')
-
-
-class UserGroupRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    group = relationship('RepoGroup')
-
-
-class Statistics(Base, BaseModel):
-    __tablename__ = 'statistics'
-    __table_args__ = (
-         UniqueConstraint('repository_id'),
-         {'extend_existing': True, 'mysql_engine': 'InnoDB',
-          'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
-    stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
-    commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
-    commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
-    languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
-
-    repository = relationship('Repository', single_parent=True)
-
-
-class UserFollowing(Base, BaseModel):
-    __tablename__ = 'user_followings'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'follows_repository_id'),
-        UniqueConstraint('user_id', 'follows_user_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-
-    user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
-
-    follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relationship('Repository', order_by='Repository.repo_name')
-
-    @classmethod
-    def get_repo_followers(cls, repo_id):
-        return cls.query().filter(cls.follows_repo_id == repo_id)
-
-
-class CacheInvalidation(Base, BaseModel):
-    __tablename__ = 'cache_invalidation'
-    __table_args__ = (
-        UniqueConstraint('cache_key'),
-        Index('key_idx', 'cache_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    # cache_id, not used
-    cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    # cache_key as created by _get_cache_key
-    cache_key = Column("cache_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    # cache_args is a repo_name
-    cache_args = Column("cache_args", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    # instance sets cache_active True when it is caching,
-    # other instances set cache_active to False to indicate that this cache is invalid
-    cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
-
-    def __init__(self, cache_key, repo_name=''):
-        self.cache_key = cache_key
-        self.cache_args = repo_name
-        self.cache_active = False
-
-    def __unicode__(self):
-        return u"<%s('%s:%s[%s]')>" % (self.__class__.__name__,
-                            self.cache_id, self.cache_key, self.cache_active)
-
-    def _cache_key_partition(self):
-        prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
-        return prefix, repo_name, suffix
-
-    def get_prefix(self):
-        """
-        get prefix that might have been used in _get_cache_key to
-        generate self.cache_key. Only used for informational purposes
-        in repo_edit.html.
-        """
-        # prefix, repo_name, suffix
-        return self._cache_key_partition()[0]
-
-    def get_suffix(self):
-        """
-        get suffix that might have been used in _get_cache_key to
-        generate self.cache_key. Only used for informational purposes
-        in repo_edit.html.
-        """
-        # prefix, repo_name, suffix
-        return self._cache_key_partition()[2]
-
-    @classmethod
-    def clear_cache(cls):
-        """
-        Delete all cache keys from database.
-        Should only be run when all instances are down and all entries thus stale.
-        """
-        cls.query().delete()
-        Session().commit()
-
-    @classmethod
-    def _get_cache_key(cls, key):
-        """
-        Wrapper for generating a unique cache key for this instance and "key".
-        key must / will start with a repo_name which will be stored in .cache_args .
-        """
-        import kallithea
-        prefix = kallithea.CONFIG.get('instance_id', '')
-        return "%s%s" % (prefix, key)
-
-    @classmethod
-    def set_invalidate(cls, repo_name, delete=False):
-        """
-        Mark all caches of a repo as invalid in the database.
-        """
-        inv_objs = Session().query(cls).filter(cls.cache_args == repo_name).all()
-
-        try:
-            for inv_obj in inv_objs:
-                log.debug('marking %s key for invalidation based on repo_name=%s',
-                          inv_obj, safe_str(repo_name))
-                if delete:
-                    Session().delete(inv_obj)
-                else:
-                    inv_obj.cache_active = False
-                    Session().add(inv_obj)
-            Session().commit()
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-
-    @classmethod
-    def test_and_set_valid(cls, repo_name, kind, valid_cache_keys=None):
-        """
-        Mark this cache key as active and currently cached.
-        Return True if the existing cache registration still was valid.
-        Return False to indicate that it had been invalidated and caches should be refreshed.
-        """
-
-        key = (repo_name + '_' + kind) if kind else repo_name
-        cache_key = cls._get_cache_key(key)
-
-        if valid_cache_keys and cache_key in valid_cache_keys:
-            return True
-
-        try:
-            inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
-            if not inv_obj:
-                inv_obj = CacheInvalidation(cache_key, repo_name)
-            was_valid = inv_obj.cache_active
-            inv_obj.cache_active = True
-            Session().add(inv_obj)
-            Session().commit()
-            return was_valid
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-            return False
-
-    @classmethod
-    def get_valid_cache_keys(cls):
-        """
-        Return opaque object with information of which caches still are valid
-        and can be used without checking for invalidation.
-        """
-        return set(inv_obj.cache_key for inv_obj in cls.query().filter(cls.cache_active).all())
-
-
-class ChangesetComment(Base, BaseModel):
-    __tablename__ = 'changeset_comments'
-    __table_args__ = (
-        Index('cc_revision_idx', 'revision'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    revision = Column('revision', String(40), nullable=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-    line_no = Column('line_no', Unicode(10), nullable=True)
-    hl_lines = Column('hl_lines', Unicode(512), nullable=True)
-    f_path = Column('f_path', Unicode(1000), nullable=True)
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
-    text = Column('text', UnicodeText(25000), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    @classmethod
-    def get_users(cls, revision=None, pull_request_id=None):
-        """
-        Returns user associated with this ChangesetComment. ie those
-        who actually commented
-
-        :param cls:
-        :param revision:
-        """
-        q = Session().query(User)\
-                .join(ChangesetComment.author)
-        if revision:
-            q = q.filter(cls.revision == revision)
-        elif pull_request_id:
-            q = q.filter(cls.pull_request_id == pull_request_id)
-        return q.all()
-
-
-class ChangesetStatus(Base, BaseModel):
-    __tablename__ = 'changeset_statuses'
-    __table_args__ = (
-        Index('cs_revision_idx', 'revision'),
-        Index('cs_version_idx', 'version'),
-        UniqueConstraint('repo_id', 'revision', 'version'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
-    STATUS_APPROVED = 'approved'
-    STATUS_REJECTED = 'rejected'
-    STATUS_UNDER_REVIEW = 'under_review'
-
-    STATUSES = [
-        (STATUS_NOT_REVIEWED, _("Not Reviewed")),  # (no icon) and default
-        (STATUS_APPROVED, _("Approved")),
-        (STATUS_REJECTED, _("Rejected")),
-        (STATUS_UNDER_REVIEW, _("Under Review")),
-    ]
-
-    changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    revision = Column('revision', String(40), nullable=False)
-    status = Column('status', String(128), nullable=False, default=DEFAULT)
-    changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
-    modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
-    version = Column('version', Integer(), nullable=False, default=0)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    comment = relationship('ChangesetComment', lazy='joined')
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.status, self.author
-        )
-
-    @classmethod
-    def get_status_lbl(cls, value):
-        return dict(cls.STATUSES).get(value)
-
-    @property
-    def status_lbl(self):
-        return ChangesetStatus.get_status_lbl(self.status)
-
-
-class PullRequest(Base, BaseModel):
-    __tablename__ = 'pull_requests'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    # values for .status
-    STATUS_NEW = u'new'
-    STATUS_OPEN = u'open'
-    STATUS_CLOSED = u'closed'
-
-    pull_request_id = Column('pull_request_id', Integer(), nullable=False, primary_key=True)
-    title = Column('title', Unicode(256), nullable=True)
-    description = Column('description', UnicodeText(10240), nullable=True)
-    status = Column('status', Unicode(256), nullable=False, default=STATUS_NEW) # only for closedness, not approve/reject/etc
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    _revisions = Column('revisions', UnicodeText(20500))  # 500 revisions max
-    org_repo_id = Column('org_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    org_ref = Column('org_ref', Unicode(256), nullable=False)
-    other_repo_id = Column('other_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    other_ref = Column('other_ref', Unicode(256), nullable=False)
-
-    @hybrid_property
-    def revisions(self):
-        return self._revisions.split(':')
-
-    @revisions.setter
-    def revisions(self, val):
-        self._revisions = ':'.join(val)
-
-    @property
-    def org_ref_parts(self):
-        return self.org_ref.split(':')
-
-    @property
-    def other_ref_parts(self):
-        return self.other_ref.split(':')
-
-    author = relationship('User', lazy='joined')
-    reviewers = relationship('PullRequestReviewers',
-                             cascade="all, delete, delete-orphan")
-    org_repo = relationship('Repository', primaryjoin='PullRequest.org_repo_id==Repository.repo_id')
-    other_repo = relationship('Repository', primaryjoin='PullRequest.other_repo_id==Repository.repo_id')
-    statuses = relationship('ChangesetStatus')
-    comments = relationship('ChangesetComment',
-                             cascade="all, delete, delete-orphan")
-
-    def is_closed(self):
-        return self.status == self.STATUS_CLOSED
-
-    @property
-    def last_review_status(self):
-        return self.statuses[-1].status if self.statuses else ''
-
-    def __json__(self):
-        return dict(
-            revisions=self.revisions
-        )
-
-
-class PullRequestReviewers(Base, BaseModel):
-    __tablename__ = 'pull_request_reviewers'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    def __init__(self, user=None, pull_request=None):
-        self.user = user
-        self.pull_request = pull_request
-
-    pull_requests_reviewers_id = Column('pull_requests_reviewers_id', Integer(), nullable=False, primary_key=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
-
-    user = relationship('User')
-    pull_request = relationship('PullRequest')
-
-
-class Notification(Base, BaseModel):
-    __tablename__ = 'notifications'
-    __table_args__ = (
-        Index('notification_type_idx', 'type'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    TYPE_CHANGESET_COMMENT = u'cs_comment'
-    TYPE_MESSAGE = u'message'
-    TYPE_MENTION = u'mention'
-    TYPE_REGISTRATION = u'registration'
-    TYPE_PULL_REQUEST = u'pull_request'
-    TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
-
-    notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
-    subject = Column('subject', Unicode(512), nullable=True)
-    body = Column('body', UnicodeText(50000), nullable=True)
-    created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    type_ = Column('type', Unicode(256))
-
-    created_by_user = relationship('User')
-    notifications_to_users = relationship('UserNotification', lazy='joined',
-                                          cascade="all, delete, delete-orphan")
-
-    @property
-    def recipients(self):
-        return [x.user for x in UserNotification.query()\
-                .filter(UserNotification.notification == self)\
-                .order_by(UserNotification.user_id.asc()).all()]
-
-    @classmethod
-    def create(cls, created_by, subject, body, recipients, type_=None):
-        if type_ is None:
-            type_ = Notification.TYPE_MESSAGE
-
-        notification = cls()
-        notification.created_by_user = created_by
-        notification.subject = subject
-        notification.body = body
-        notification.type_ = type_
-        notification.created_on = datetime.datetime.now()
-
-        for u in recipients:
-            assoc = UserNotification()
-            assoc.notification = notification
-            u.notifications.append(assoc)
-        Session().add(notification)
-        return notification
-
-    @property
-    def description(self):
-        from kallithea.model.notification import NotificationModel
-        return NotificationModel().make_description(self)
-
-
-class UserNotification(Base, BaseModel):
-    __tablename__ = 'user_to_notification'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'notification_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
-    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
-    read = Column('read', Boolean, default=False)
-    sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
-
-    user = relationship('User', lazy="joined")
-    notification = relationship('Notification', lazy="joined",
-                                order_by=lambda: Notification.created_on.desc(),)
-
-    def mark_as_read(self):
-        self.read = True
-        Session().add(self)
-
-
-class Gist(Base, BaseModel):
-    __tablename__ = 'gists'
-    __table_args__ = (
-        Index('g_gist_access_id_idx', 'gist_access_id'),
-        Index('g_created_on_idx', 'created_on'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    GIST_PUBLIC = u'public'
-    GIST_PRIVATE = u'private'
-
-    gist_id = Column('gist_id', Integer(), primary_key=True)
-    gist_access_id = Column('gist_access_id', Unicode(250))
-    gist_description = Column('gist_description', UnicodeText(1024))
-    gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
-    gist_expires = Column('gist_expires', Float(53), nullable=False)
-    gist_type = Column('gist_type', Unicode(128), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    owner = relationship('User')
-
-    @classmethod
-    def get_or_404(cls, id_):
-        res = cls.query().filter(cls.gist_access_id == id_).scalar()
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def get_by_access_id(cls, gist_access_id):
-        return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
-
-    def gist_url(self):
-        import kallithea
-        alias_url = kallithea.CONFIG.get('gist_alias_url')
-        if alias_url:
-            return alias_url.replace('{gistid}', self.gist_access_id)
-
-        import kallithea.lib.helpers as h
-        return h.canonical_url('gist', gist_id=self.gist_access_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all gists are stored
-
-        :param cls:
-        """
-        from kallithea.model.gist import GIST_STORE_LOC
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == URL_SEP)
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return os.path.join(q.one().ui_value, GIST_STORE_LOC)
-
-    def get_api_data(self):
-        """
-        Common function for generating gist related data for API
-        """
-        gist = self
-        data = dict(
-            gist_id=gist.gist_id,
-            type=gist.gist_type,
-            access_id=gist.gist_access_id,
-            description=gist.gist_description,
-            url=gist.gist_url(),
-            expires=gist.gist_expires,
-            created_on=gist.created_on,
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-        )
-        data.update(self.get_api_data())
-        return data
-    ## SCM functions
-
-    @property
-    def scm_instance(self):
-        from kallithea.lib.vcs import get_repo
-        base_path = self.base_path()
-        return get_repo(os.path.join(*map(safe_str,
-                                          [base_path, self.gist_access_id])))
-
-
-class DbMigrateVersion(Base, BaseModel):
-    __tablename__ = 'db_migrate_version'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    repository_id = Column('repository_id', String(250), primary_key=True)
-    repository_path = Column('repository_path', Text)
-    version = Column('version', Integer)
--- a/kallithea/lib/dbmigrate/schema/db_2_0_2.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,2352 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate.schema.db_2_0_2
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Database Models for Kallithea
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Apr 08, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-import os
-import time
-import logging
-import datetime
-import traceback
-import hashlib
-import collections
-import functools
-
-from sqlalchemy import *
-from sqlalchemy.ext.hybrid import hybrid_property
-from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
-from beaker.cache import cache_region, region_invalidate
-from webob.exc import HTTPNotFound
-
-from pylons.i18n.translation import lazy_ugettext as _
-
-from kallithea.lib.vcs import get_backend
-from kallithea.lib.vcs.utils.helpers import get_scm
-from kallithea.lib.vcs.exceptions import VCSError
-from kallithea.lib.vcs.utils.lazy import LazyProperty
-from kallithea.lib.vcs.backends.base import EmptyChangeset
-
-from kallithea.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
-    safe_unicode, remove_prefix, time_to_datetime, aslist, Optional, safe_int
-from kallithea.lib.compat import json
-from kallithea.lib.caching_query import FromCache
-
-from kallithea.model.meta import Base, Session
-
-URL_SEP = '/'
-log = logging.getLogger(__name__)
-
-from kallithea import DB_PREFIX
-
-#==============================================================================
-# BASE CLASSES
-#==============================================================================
-
-_hash_key = lambda k: hashlib.md5(safe_str(k)).hexdigest()
-
-
-class BaseModel(object):
-    """
-    Base Model for all classess
-    """
-
-    @classmethod
-    def _get_keys(cls):
-        """return column names for this model """
-        return class_mapper(cls).c.keys()
-
-    def get_dict(self):
-        """
-        return dict with keys and values corresponding
-        to this model data """
-
-        d = {}
-        for k in self._get_keys():
-            d[k] = getattr(self, k)
-
-        # also use __json__() if present to get additional fields
-        _json_attr = getattr(self, '__json__', None)
-        if _json_attr:
-            # update with attributes from __json__
-            if callable(_json_attr):
-                _json_attr = _json_attr()
-            for k, val in _json_attr.iteritems():
-                d[k] = val
-        return d
-
-    def get_appstruct(self):
-        """return list with keys and values tuples corresponding
-        to this model data """
-
-        l = []
-        for k in self._get_keys():
-            l.append((k, getattr(self, k),))
-        return l
-
-    def populate_obj(self, populate_dict):
-        """populate model with data from given populate_dict"""
-
-        for k in self._get_keys():
-            if k in populate_dict:
-                setattr(self, k, populate_dict[k])
-
-    @classmethod
-    def query(cls):
-        return Session().query(cls)
-
-    @classmethod
-    def get(cls, id_):
-        if id_:
-            return cls.query().get(id_)
-
-    @classmethod
-    def get_or_404(cls, id_):
-        try:
-            id_ = int(id_)
-        except (TypeError, ValueError):
-            raise HTTPNotFound
-
-        res = cls.query().get(id_)
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def getAll(cls):
-        # deprecated and left for backward compatibility
-        return cls.get_all()
-
-    @classmethod
-    def get_all(cls):
-        return cls.query().all()
-
-    @classmethod
-    def delete(cls, id_):
-        obj = cls.query().get(id_)
-        Session().delete(obj)
-
-    def __repr__(self):
-        if hasattr(self, '__unicode__'):
-            # python repr needs to return str
-            try:
-                return safe_str(self.__unicode__())
-            except UnicodeDecodeError:
-                pass
-        return '<DB:%s>' % (self.__class__.__name__)
-
-
-class Setting(Base, BaseModel):
-    SETTINGS_TYPES = {
-        'str': safe_str,
-        'int': safe_int,
-        'unicode': safe_unicode,
-        'bool': str2bool,
-        'list': functools.partial(aslist, sep=',')
-    }
-    __tablename__ = DB_PREFIX + 'settings'
-    __table_args__ = (
-        UniqueConstraint('app_settings_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    app_settings_name = Column("app_settings_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_value = Column("app_settings_value", String(4096, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_type = Column("app_settings_type", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __init__(self, key='', val='', type='unicode'):
-        self.app_settings_name = key
-        self.app_settings_value = val
-        self.app_settings_type = type
-
-    @validates('_app_settings_value')
-    def validate_settings_value(self, key, val):
-        assert type(val) == unicode
-        return val
-
-    @hybrid_property
-    def app_settings_value(self):
-        v = self._app_settings_value
-        _type = self.app_settings_type
-        converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
-        return converter(v)
-
-    @app_settings_value.setter
-    def app_settings_value(self, val):
-        """
-        Setter that will always make sure we use unicode in app_settings_value
-
-        :param val:
-        """
-        self._app_settings_value = safe_unicode(val)
-
-    @hybrid_property
-    def app_settings_type(self):
-        return self._app_settings_type
-
-    @app_settings_type.setter
-    def app_settings_type(self, val):
-        if val not in self.SETTINGS_TYPES:
-            raise Exception('type must be one of %s got %s'
-                            % (self.SETTINGS_TYPES.keys(), val))
-        self._app_settings_type = val
-
-    def __unicode__(self):
-        return u"<%s('%s:%s[%s]')>" % (
-            self.__class__.__name__,
-            self.app_settings_name, self.app_settings_value, self.app_settings_type
-        )
-
-    @classmethod
-    def get_by_name(cls, key):
-        return cls.query()\
-            .filter(cls.app_settings_name == key).scalar()
-
-    @classmethod
-    def get_by_name_or_create(cls, key, val='', type='unicode'):
-        res = cls.get_by_name(key)
-        if not res:
-            res = cls(key, val, type)
-        return res
-
-    @classmethod
-    def create_or_update(cls, key, val=Optional(''), type=Optional('unicode')):
-        """
-        Creates or updates Kallithea setting. If updates is triggered it will only
-        update parameters that are explicityl set Optional instance will be skipped
-
-        :param key:
-        :param val:
-        :param type:
-        :return:
-        """
-        res = cls.get_by_name(key)
-        if not res:
-            val = Optional.extract(val)
-            type = Optional.extract(type)
-            res = cls(key, val, type)
-        else:
-            res.app_settings_name = key
-            if not isinstance(val, Optional):
-                # update if set
-                res.app_settings_value = val
-            if not isinstance(type, Optional):
-                # update if set
-                res.app_settings_type = type
-        return res
-
-    @classmethod
-    def get_app_settings(cls, cache=False):
-
-        ret = cls.query()
-
-        if cache:
-            ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
-
-        if not ret:
-            raise Exception('Could not get application settings !')
-        settings = {}
-        for each in ret:
-            settings[each.app_settings_name] = \
-                each.app_settings_value
-
-        return settings
-
-    @classmethod
-    def get_auth_plugins(cls, cache=False):
-        auth_plugins = cls.get_by_name("auth_plugins").app_settings_value
-        return auth_plugins
-
-    @classmethod
-    def get_auth_settings(cls, cache=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('auth_')).all()
-        fd = {}
-        for row in ret:
-            fd.update({row.app_settings_name: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_default_repo_settings(cls, cache=False, strip_prefix=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('default_')).all()
-        fd = {}
-        for row in ret:
-            key = row.app_settings_name
-            if strip_prefix:
-                key = remove_prefix(key, prefix='default_')
-            fd.update({key: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_server_info(cls):
-        import pkg_resources
-        import platform
-        import kallithea
-        from kallithea.lib.utils import check_git_version
-        mods = [(p.project_name, p.version) for p in pkg_resources.working_set]
-        info = {
-            'modules': sorted(mods, key=lambda k: k[0].lower()),
-            'py_version': platform.python_version(),
-            'platform': safe_unicode(platform.platform()),
-            'kallithea_version': kallithea.__version__,
-            'git_version': safe_unicode(check_git_version()),
-            'git_path': kallithea.CONFIG.get('git_path')
-        }
-        return info
-
-
-class Ui(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'ui'
-    __table_args__ = (
-        UniqueConstraint('ui_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    HOOK_UPDATE = 'changegroup.update'
-    HOOK_REPO_SIZE = 'changegroup.repo_size'
-    HOOK_PUSH = 'changegroup.push_logger'
-    HOOK_PRE_PUSH = 'prechangegroup.pre_push'
-    HOOK_PULL = 'outgoing.pull_logger'
-    HOOK_PRE_PULL = 'preoutgoing.pre_pull'
-
-    ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    ui_section = Column("ui_section", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_key = Column("ui_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_value = Column("ui_value", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
-
-    # def __init__(self, section='', key='', value=''):
-    #     self.ui_section = section
-    #     self.ui_key = key
-    #     self.ui_value = value
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.ui_key == key).scalar()
-
-    @classmethod
-    def get_builtin_hooks(cls):
-        q = cls.query()
-        q = q.filter(cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                     cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                     cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        return q.all()
-
-    @classmethod
-    def get_custom_hooks(cls):
-        q = cls.query()
-        q = q.filter(~cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                      cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                      cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        q = q.filter(cls.ui_section == 'hooks')
-        return q.all()
-
-    @classmethod
-    def get_repos_location(cls):
-        return cls.get_by_key('/').ui_value
-
-    @classmethod
-    def create_or_update_hook(cls, key, val):
-        new_ui = cls.get_by_key(key) or cls()
-        new_ui.ui_section = 'hooks'
-        new_ui.ui_active = True
-        new_ui.ui_key = key
-        new_ui.ui_value = val
-
-        Session().add(new_ui)
-
-    def __repr__(self):
-        return '<DB:%s[%s:%s]>' % (self.__class__.__name__, self.ui_key,
-                                   self.ui_value)
-
-
-class User(Base, BaseModel):
-    __tablename__ = 'users'
-    __table_args__ = (
-        UniqueConstraint('username'), UniqueConstraint('email'),
-        Index('u_username_idx', 'username'),
-        Index('u_email_idx', 'email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    DEFAULT_USER = 'default'
-
-    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    password = Column("password", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
-    name = Column("firstname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    lastname = Column("lastname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
-    extern_type = Column("extern_type", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    extern_name = Column("extern_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    api_key = Column("api_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    user_log = relationship('UserLog')
-    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
-
-    repositories = relationship('Repository')
-    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
-    followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
-
-    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
-
-    group_member = relationship('UserGroupMember', cascade='all')
-
-    notifications = relationship('UserNotification', cascade='all')
-    # notifications assigned to this user
-    user_created_notifications = relationship('Notification', cascade='all')
-    # comments created by this user
-    user_comments = relationship('ChangesetComment', cascade='all')
-    #extra emails for this user
-    user_emails = relationship('UserEmailMap', cascade='all')
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-    @property
-    def firstname(self):
-        # alias for future
-        return self.name
-
-    @property
-    def emails(self):
-        other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
-        return [self.email] + [x.email for x in other]
-
-    @property
-    def ip_addresses(self):
-        ret = UserIpMap.query().filter(UserIpMap.user == self).all()
-        return [x.ip_addr for x in ret]
-
-    @property
-    def username_and_name(self):
-        return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
-
-    @property
-    def full_name(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def full_name_or_username(self):
-        return ('%s %s' % (self.firstname, self.lastname)
-                if (self.firstname and self.lastname) else self.username)
-
-    @property
-    def full_contact(self):
-        return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
-
-    @property
-    def short_contact(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def is_admin(self):
-        return self.admin
-
-    @property
-    def AuthUser(self):
-        """
-        Returns instance of AuthUser for this user
-        """
-        from kallithea.lib.auth import AuthUser
-        return AuthUser(user_id=self.user_id, api_key=self.api_key,
-                        username=self.username)
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.user_id, self.username)
-
-    @classmethod
-    def get_by_username(cls, username, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.username.ilike(username))
-        else:
-            q = cls.query().filter(cls.username == username)
-
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(username)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get_by_api_key(cls, api_key, cache=False):
-        q = cls.query().filter(cls.api_key == api_key)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_api_key_%s" % api_key))
-        return q.scalar()
-
-    @classmethod
-    def get_by_email(cls, email, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.email.ilike(email))
-        else:
-            q = cls.query().filter(cls.email == email)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_email_key_%s" % email))
-
-        ret = q.scalar()
-        if ret is None:
-            q = UserEmailMap.query()
-            # try fetching in alternate email map
-            if case_insensitive:
-                q = q.filter(UserEmailMap.email.ilike(email))
-            else:
-                q = q.filter(UserEmailMap.email == email)
-            q = q.options(joinedload(UserEmailMap.user))
-            if cache:
-                q = q.options(FromCache("sql_cache_short",
-                                        "get_email_map_key_%s" % email))
-            ret = getattr(q.scalar(), 'user', None)
-
-        return ret
-
-    @classmethod
-    def get_from_cs_author(cls, author):
-        """
-        Tries to get User objects out of commit author string
-
-        :param author:
-        """
-        from kallithea.lib.helpers import email, author_name
-        # Valid email in the attribute passed, see if they're in the system
-        _email = email(author)
-        if _email:
-            user = cls.get_by_email(_email, case_insensitive=True)
-            if user:
-                return user
-        # Maybe we can match by username?
-        _author = author_name(author)
-        user = cls.get_by_username(_author, case_insensitive=True)
-        if user:
-            return user
-
-    def update_lastlogin(self):
-        """Update user lastlogin"""
-        self.last_login = datetime.datetime.now()
-        Session().add(self)
-        log.debug('updated user %s lastlogin', self.username)
-
-    @classmethod
-    def get_first_admin(cls):
-        user = User.query().filter(User.admin == True).first()
-        if user is None:
-            raise Exception('Missing administrative account!')
-        return user
-
-    @classmethod
-    def get_default_user(cls, cache=False):
-        user = User.get_by_username(User.DEFAULT_USER, cache=cache)
-        if user is None:
-            raise Exception('Missing default account!')
-        return user
-
-    def get_api_data(self):
-        """
-        Common function for generating user related data for API
-        """
-        user = self
-        data = dict(
-            user_id=user.user_id,
-            username=user.username,
-            firstname=user.name,
-            lastname=user.lastname,
-            email=user.email,
-            emails=user.emails,
-            api_key=user.api_key,
-            active=user.active,
-            admin=user.admin,
-            extern_type=user.extern_type,
-            extern_name=user.extern_name,
-            last_login=user.last_login,
-            ip_addresses=user.ip_addresses
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-            full_name=self.full_name,
-            full_name_or_username=self.full_name_or_username,
-            short_contact=self.short_contact,
-            full_contact=self.full_contact
-        )
-        data.update(self.get_api_data())
-        return data
-
-
-class UserEmailMap(Base, BaseModel):
-    __tablename__ = 'user_email_map'
-    __table_args__ = (
-        Index('uem_email_idx', 'email'),
-        UniqueConstraint('email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    user = relationship('User', lazy='joined')
-
-    @validates('_email')
-    def validate_email(self, key, email):
-        # check if this email is not main one
-        main_email = Session().query(User).filter(User.email == email).scalar()
-        if main_email is not None:
-            raise AttributeError('email %s is present is user table' % email)
-        return email
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-
-class UserIpMap(Base, BaseModel):
-    __tablename__ = 'user_ip_map'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'ip_addr'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    ip_addr = Column("ip_addr", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    user = relationship('User', lazy='joined')
-
-    @classmethod
-    def _get_ip_range(cls, ip_addr):
-        from kallithea.lib import ipaddr
-        net = ipaddr.IPNetwork(address=ip_addr)
-        return [str(net.network), str(net.broadcast)]
-
-    def __json__(self):
-        return dict(
-          ip_addr=self.ip_addr,
-          ip_range=self._get_ip_range(self.ip_addr)
-        )
-
-
-class UserLog(Base, BaseModel):
-    __tablename__ = 'user_logs'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
-    repository_name = Column("repository_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    user_ip = Column("user_ip", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action = Column("action", UnicodeText(1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.repository_name,
-                                      self.action)
-
-    @property
-    def action_as_day(self):
-        return datetime.date(*self.action_date.timetuple()[:3])
-
-    user = relationship('User')
-    repository = relationship('Repository', cascade='')
-
-
-class UserGroup(Base, BaseModel):
-    __tablename__ = 'users_groups'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_name = Column("users_group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    user_group_description = Column("user_group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
-    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
-    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-    user_user_group_to_perm = relationship('UserUserGroupToPerm ', cascade='all')
-    user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
-
-    user = relationship('User')
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.users_group_id,
-                                      self.users_group_name)
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False,
-                          case_insensitive=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.users_group_name.ilike(group_name))
-        else:
-            q = cls.query().filter(cls.users_group_name == group_name)
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(group_name)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get(cls, user_group_id, cache=False):
-        user_group = cls.query()
-        if cache:
-            user_group = user_group.options(FromCache("sql_cache_short",
-                                    "get_users_group_%s" % user_group_id))
-        return user_group.get(user_group_id)
-
-    def get_api_data(self, with_members=True):
-        user_group = self
-
-        data = dict(
-            users_group_id=user_group.users_group_id,
-            group_name=user_group.users_group_name,
-            group_description=user_group.user_group_description,
-            active=user_group.users_group_active,
-            owner=user_group.user.username,
-        )
-        if with_members:
-            members = []
-            for user in user_group.members:
-                user = user.user
-                members.append(user.get_api_data())
-            data['members'] = members
-
-        return data
-
-
-class UserGroupMember(Base, BaseModel):
-    __tablename__ = 'users_groups_members'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User', lazy='joined')
-    users_group = relationship('UserGroup')
-
-    def __init__(self, gr_id='', u_id=''):
-        self.users_group_id = gr_id
-        self.user_id = u_id
-
-
-class RepositoryField(Base, BaseModel):
-    __tablename__ = 'repositories_fields'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'field_key'),  # no-multi field
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    PREFIX = 'ex_'  # prefix used in form to not conflict with already existing fields
-
-    repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-    field_key = Column("field_key", String(250, convert_unicode=False, assert_unicode=None))
-    field_label = Column("field_label", String(1024, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_value = Column("field_value", String(10000, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_desc = Column("field_desc", String(1024, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_type = Column("field_type", String(256), nullable=False, unique=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    repository = relationship('Repository')
-
-    @property
-    def field_key_prefixed(self):
-        return 'ex_%s' % self.field_key
-
-    @classmethod
-    def un_prefix_key(cls, key):
-        if key.startswith(cls.PREFIX):
-            return key[len(cls.PREFIX):]
-        return key
-
-    @classmethod
-    def get_by_key_name(cls, key, repo):
-        row = cls.query()\
-                .filter(cls.repository == repo)\
-                .filter(cls.field_key == key).scalar()
-        return row
-
-
-class Repository(Base, BaseModel):
-    __tablename__ = 'repositories'
-    __table_args__ = (
-        UniqueConstraint('repo_name'),
-        Index('r_repo_name_idx', 'repo_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repo_name = Column("repo_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    clone_uri = Column("clone_uri", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    repo_type = Column("repo_type", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
-    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
-    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
-    description = Column("description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    _landing_revision = Column("landing_revision", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    _locked = Column("locked", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) #JSON data
-
-    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
-
-    user = relationship('User')
-    fork = relationship('Repository', remote_side=repo_id)
-    group = relationship('RepoGroup')
-    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    stats = relationship('Statistics', cascade='all', uselist=False)
-
-    followers = relationship('UserFollowing',
-                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
-                             cascade='all')
-    extra_fields = relationship('RepositoryField',
-                                cascade="all, delete, delete-orphan")
-
-    logs = relationship('UserLog')
-    comments = relationship('ChangesetComment', cascade="all, delete, delete-orphan")
-
-    pull_requests_org = relationship('PullRequest',
-                    primaryjoin='PullRequest.org_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    pull_requests_other = relationship('PullRequest',
-                    primaryjoin='PullRequest.other_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
-                                   safe_unicode(self.repo_name))
-
-    @hybrid_property
-    def landing_rev(self):
-        # always should return [rev_type, rev]
-        if self._landing_revision:
-            _rev_info = self._landing_revision.split(':')
-            if len(_rev_info) < 2:
-                _rev_info.insert(0, 'rev')
-            return [_rev_info[0], _rev_info[1]]
-        return [None, None]
-
-    @landing_rev.setter
-    def landing_rev(self, val):
-        if ':' not in val:
-            raise ValueError('value must be delimited with `:` and consist '
-                             'of <rev_type>:<rev>, got %s instead' % val)
-        self._landing_revision = val
-
-    @hybrid_property
-    def locked(self):
-        # always should return [user_id, timelocked]
-        if self._locked:
-            _lock_info = self._locked.split(':')
-            return int(_lock_info[0]), _lock_info[1]
-        return [None, None]
-
-    @locked.setter
-    def locked(self, val):
-        if val and isinstance(val, (list, tuple)):
-            self._locked = ':'.join(map(str, val))
-        else:
-            self._locked = None
-
-    @hybrid_property
-    def changeset_cache(self):
-        from kallithea.lib.vcs.backends.base import EmptyChangeset
-        dummy = EmptyChangeset().__json__()
-        if not self._changeset_cache:
-            return dummy
-        try:
-            return json.loads(self._changeset_cache)
-        except TypeError:
-            return dummy
-
-    @changeset_cache.setter
-    def changeset_cache(self, val):
-        try:
-            self._changeset_cache = json.dumps(val)
-        except Exception:
-            log.error(traceback.format_exc())
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def normalize_repo_name(cls, repo_name):
-        """
-        Normalizes os specific repo_name to the format internally stored inside
-        dabatabase using URL_SEP
-
-        :param cls:
-        :param repo_name:
-        """
-        return cls.url_sep().join(repo_name.split(os.sep))
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        q = Session().query(cls).filter(cls.repo_name == repo_name)
-        q = q.options(joinedload(Repository.fork))\
-                .options(joinedload(Repository.user))\
-                .options(joinedload(Repository.group))
-        return q.scalar()
-
-    @classmethod
-    def get_by_full_path(cls, repo_full_path):
-        repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
-        repo_name = cls.normalize_repo_name(repo_name)
-        return cls.get_by_repo_name(repo_name.strip(URL_SEP))
-
-    @classmethod
-    def get_repo_forks(cls, repo_id):
-        return cls.query().filter(Repository.fork_id == repo_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all repos are stored
-
-        :param cls:
-        """
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == cls.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def forks(self):
-        """
-        Return forks of this repo
-        """
-        return Repository.get_repo_forks(self.repo_id)
-
-    @property
-    def parent(self):
-        """
-        Returns fork parent
-        """
-        return self.fork
-
-    @property
-    def just_name(self):
-        return self.repo_name.split(Repository.url_sep())[-1]
-
-    @property
-    def groups_with_parents(self):
-        groups = []
-        if self.group is None:
-            return groups
-
-        cur_gr = self.group
-        groups.insert(0, cur_gr)
-        while 1:
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            groups.insert(0, gr)
-
-        return groups
-
-    @property
-    def groups_and_repo(self):
-        return self.groups_with_parents, self.just_name, self.repo_name
-
-    @LazyProperty
-    def repo_path(self):
-        """
-        Returns base full path for that repository means where it actually
-        exists on a filesystem
-        """
-        q = Session().query(Ui).filter(Ui.ui_key ==
-                                              Repository.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def repo_full_path(self):
-        p = [self.repo_path]
-        # we need to split the name by / since this is how we store the
-        # names in the database, but that eventually needs to be converted
-        # into a valid system path
-        p += self.repo_name.split(Repository.url_sep())
-        return os.path.join(*map(safe_unicode, p))
-
-    @property
-    def cache_keys(self):
-        """
-        Returns associated cache keys for that repo
-        """
-        return CacheInvalidation.query()\
-            .filter(CacheInvalidation.cache_args == self.repo_name)\
-            .order_by(CacheInvalidation.cache_key)\
-            .all()
-
-    def get_new_name(self, repo_name):
-        """
-        returns new full repository name based on assigned group and new new
-
-        :param group_name:
-        """
-        path_prefix = self.group.full_path_splitted if self.group else []
-        return Repository.url_sep().join(path_prefix + [repo_name])
-
-    @property
-    def _ui(self):
-        """
-        Creates an db based ui object for this repository
-        """
-        from kallithea.lib.utils import make_ui
-        return make_ui('db', clear_session=False)
-
-    @classmethod
-    def is_valid(cls, repo_name):
-        """
-        returns True if given repo name is a valid filesystem repository
-
-        :param cls:
-        :param repo_name:
-        """
-        from kallithea.lib.utils import is_valid_repo
-
-        return is_valid_repo(repo_name, cls.base_path())
-
-    def get_api_data(self):
-        """
-        Common function for generating repo api data
-
-        """
-        repo = self
-        data = dict(
-            repo_id=repo.repo_id,
-            repo_name=repo.repo_name,
-            repo_type=repo.repo_type,
-            clone_uri=repo.clone_uri,
-            private=repo.private,
-            created_on=repo.created_on,
-            description=repo.description,
-            landing_rev=repo.landing_rev,
-            owner=repo.user.username,
-            fork_of=repo.fork.repo_name if repo.fork else None,
-            enable_statistics=repo.enable_statistics,
-            enable_locking=repo.enable_locking,
-            enable_downloads=repo.enable_downloads,
-            last_changeset=repo.changeset_cache,
-            locked_by=User.get(self.locked[0]).get_api_data() \
-                if self.locked[0] else None,
-            locked_date=time_to_datetime(self.locked[1]) \
-                if self.locked[1] else None
-        )
-        rc_config = Setting.get_app_settings()
-        repository_fields = str2bool(rc_config.get('repository_fields'))
-        if repository_fields:
-            for f in self.extra_fields:
-                data[f.field_key_prefixed] = f.field_value
-
-        return data
-
-    @classmethod
-    def lock(cls, repo, user_id, lock_time=None):
-        if not lock_time:
-            lock_time = time.time()
-        repo.locked = [user_id, lock_time]
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def unlock(cls, repo):
-        repo.locked = None
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def getlock(cls, repo):
-        return repo.locked
-
-    @property
-    def last_db_change(self):
-        return self.updated_on
-
-    def clone_url(self, **override):
-        import kallithea.lib.helpers as h
-        from urlparse import urlparse
-        import urllib
-        parsed_url = urlparse(h.canonical_url('home'))
-        default_clone_uri = '%(scheme)s://%(user)s%(pass)s%(netloc)s%(prefix)s%(path)s'
-        decoded_path = safe_unicode(urllib.unquote(parsed_url.path))
-        args = {
-           'user': '',
-           'pass': '',
-           'scheme': parsed_url.scheme,
-           'netloc': parsed_url.netloc,
-           'prefix': decoded_path,
-           'path': self.repo_name
-        }
-
-        args.update(override)
-        return default_clone_uri % args
-
-    #==========================================================================
-    # SCM PROPERTIES
-    #==========================================================================
-
-    def get_changeset(self, rev=None):
-        return get_changeset_safe(self.scm_instance, rev)
-
-    def get_landing_changeset(self):
-        """
-        Returns landing changeset, or if that doesn't exist returns the tip
-        """
-        _rev_type, _rev = self.landing_rev
-        cs = self.get_changeset(_rev)
-        if isinstance(cs, EmptyChangeset):
-            return self.get_changeset()
-        return cs
-
-    def update_changeset_cache(self, cs_cache=None):
-        """
-        Update cache of last changeset for repository, keys should be::
-
-            short_id
-            raw_id
-            revision
-            message
-            date
-            author
-
-        :param cs_cache:
-        """
-        from kallithea.lib.vcs.backends.base import BaseChangeset
-        if cs_cache is None:
-            cs_cache = EmptyChangeset()
-            # use no-cache version here
-            scm_repo = self.scm_instance_no_cache()
-            if scm_repo:
-                cs_cache = scm_repo.get_changeset()
-
-        if isinstance(cs_cache, BaseChangeset):
-            cs_cache = cs_cache.__json__()
-
-        if (cs_cache != self.changeset_cache or not self.changeset_cache):
-            _default = datetime.datetime.fromtimestamp(0)
-            last_change = cs_cache.get('date') or _default
-            log.debug('updated repo %s with new cs cache %s',
-                      self.repo_name, cs_cache)
-            self.updated_on = last_change
-            self.changeset_cache = cs_cache
-            Session().add(self)
-            Session().commit()
-        else:
-            log.debug('Skipping repo:%s already with latest changes',
-                      self.repo_name)
-
-    @property
-    def tip(self):
-        return self.get_changeset('tip')
-
-    @property
-    def author(self):
-        return self.tip.author
-
-    @property
-    def last_change(self):
-        return self.scm_instance.last_change
-
-    def get_comments(self, revisions=None):
-        """
-        Returns comments for this repository grouped by revisions
-
-        :param revisions: filter query by revisions only
-        """
-        cmts = ChangesetComment.query()\
-            .filter(ChangesetComment.repo == self)
-        if revisions:
-            cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
-        grouped = collections.defaultdict(list)
-        for cmt in cmts.all():
-            grouped[cmt.revision].append(cmt)
-        return grouped
-
-    def statuses(self, revisions=None):
-        """
-        Returns statuses for this repository
-
-        :param revisions: list of revisions to get statuses for
-        """
-
-        statuses = ChangesetStatus.query()\
-            .filter(ChangesetStatus.repo == self)\
-            .filter(ChangesetStatus.version == 0)
-        if revisions:
-            statuses = statuses.filter(ChangesetStatus.revision.in_(revisions))
-        grouped = {}
-
-        #maybe we have open new pullrequest without a status ?
-        stat = ChangesetStatus.STATUS_UNDER_REVIEW
-        status_lbl = ChangesetStatus.get_status_lbl(stat)
-        for pr in PullRequest.query().filter(PullRequest.org_repo == self).all():
-            for rev in pr.revisions:
-                pr_id = pr.pull_request_id
-                pr_repo = pr.other_repo.repo_name
-                grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
-
-        for stat in statuses.all():
-            pr_id = pr_repo = None
-            if stat.pull_request:
-                pr_id = stat.pull_request.pull_request_id
-                pr_repo = stat.pull_request.other_repo.repo_name
-            grouped[stat.revision] = [str(stat.status), stat.status_lbl,
-                                      pr_id, pr_repo]
-        return grouped
-
-    def _repo_size(self):
-        from kallithea.lib import helpers as h
-        log.debug('calculating repository size...')
-        return h.format_byte_size(self.scm_instance.size)
-
-    #==========================================================================
-    # SCM CACHE INSTANCE
-    #==========================================================================
-
-    def set_invalidate(self):
-        """
-        Mark caches of this repo as invalid.
-        """
-        CacheInvalidation.set_invalidate(self.repo_name)
-
-    def scm_instance_no_cache(self):
-        return self.__get_instance()
-
-    @property
-    def scm_instance(self):
-        import kallithea
-        full_cache = str2bool(kallithea.CONFIG.get('vcs_full_cache'))
-        if full_cache:
-            return self.scm_instance_cached()
-        return self.__get_instance()
-
-    def scm_instance_cached(self, valid_cache_keys=None):
-        @cache_region('long_term')
-        def _c(repo_name):
-            return self.__get_instance()
-        rn = self.repo_name
-
-        valid = CacheInvalidation.test_and_set_valid(rn, None, valid_cache_keys=valid_cache_keys)
-        if not valid:
-            log.debug('Cache for %s invalidated, getting new object', rn)
-            region_invalidate(_c, None, rn)
-        else:
-            log.debug('Getting obj for %s from cache', rn)
-        return _c(rn)
-
-    def __get_instance(self):
-        repo_full_path = self.repo_full_path
-        try:
-            alias = get_scm(repo_full_path)[0]
-            log.debug('Creating instance of %s repository from %s',
-                      alias, repo_full_path)
-            backend = get_backend(alias)
-        except VCSError:
-            log.error(traceback.format_exc())
-            log.error('Perhaps this repository is in db and not in '
-                      'filesystem run rescan repositories with '
-                      '"destroy old data " option from admin panel')
-            return
-
-        if alias == 'hg':
-
-            repo = backend(safe_str(repo_full_path), create=False,
-                           baseui=self._ui)
-        else:
-            repo = backend(repo_full_path, create=False)
-
-        return repo
-
-    def __json__(self):
-        return dict(landing_rev = self.landing_rev)
-
-class RepoGroup(Base, BaseModel):
-    __tablename__ = 'groups'
-    __table_args__ = (
-        UniqueConstraint('group_name', 'group_parent_id'),
-        CheckConstraint('group_id != group_parent_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    __mapper_args__ = {'order_by': 'group_name'}
-
-    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    group_name = Column("group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
-    group_description = Column("group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-    parent_group = relationship('RepoGroup', remote_side=group_id)
-    user = relationship('User')
-
-    def __init__(self, group_name='', parent_group=None):
-        self.group_name = group_name
-        self.parent_group = parent_group
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
-                                      self.group_name)
-
-    @classmethod
-    def groups_choices(cls, groups=None, show_empty_group=True):
-        from webhelpers.html import literal as _literal
-        if not groups:
-            groups = cls.query().all()
-
-        repo_groups = []
-        if show_empty_group:
-            repo_groups = [('-1', u'-- %s --' % _('top level'))]
-        sep = ' &raquo; '
-        _name = lambda k: _literal(sep.join(k))
-
-        repo_groups.extend([(x.group_id, _name(x.full_path_splitted))
-                              for x in groups])
-
-        repo_groups = sorted(repo_groups, key=lambda t: t[1].split(sep)[0])
-        return repo_groups
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
-        if case_insensitive:
-            gr = cls.query()\
-                .filter(cls.group_name.ilike(group_name))
-        else:
-            gr = cls.query()\
-                .filter(cls.group_name == group_name)
-        if cache:
-            gr = gr.options(FromCache(
-                            "sql_cache_short",
-                            "get_group_%s" % _hash_key(group_name)
-                            )
-            )
-        return gr.scalar()
-
-    @property
-    def parents(self):
-        parents_recursion_limit = 5
-        groups = []
-        if self.parent_group is None:
-            return groups
-        cur_gr = self.parent_group
-        groups.insert(0, cur_gr)
-        cnt = 0
-        while 1:
-            cnt += 1
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            if cnt == parents_recursion_limit:
-                # this will prevent accidental infinite loops
-                log.error('group nested more than %s',
-                          parents_recursion_limit)
-                break
-
-            groups.insert(0, gr)
-        return groups
-
-    @property
-    def children(self):
-        return RepoGroup.query().filter(RepoGroup.parent_group == self)
-
-    @property
-    def name(self):
-        return self.group_name.split(RepoGroup.url_sep())[-1]
-
-    @property
-    def full_path(self):
-        return self.group_name
-
-    @property
-    def full_path_splitted(self):
-        return self.group_name.split(RepoGroup.url_sep())
-
-    @property
-    def repositories(self):
-        return Repository.query()\
-                .filter(Repository.group == self)\
-                .order_by(Repository.repo_name)
-
-    @property
-    def repositories_recursive_count(self):
-        cnt = self.repositories.count()
-
-        def children_count(group):
-            cnt = 0
-            for child in group.children:
-                cnt += child.repositories.count()
-                cnt += children_count(child)
-            return cnt
-
-        return cnt + children_count(self)
-
-    def _recursive_objects(self, include_repos=True):
-        all_ = []
-
-        def _get_members(root_gr):
-            if include_repos:
-                for r in root_gr.repositories:
-                    all_.append(r)
-            childs = root_gr.children.all()
-            if childs:
-                for gr in childs:
-                    all_.append(gr)
-                    _get_members(gr)
-
-        _get_members(self)
-        return [self] + all_
-
-    def recursive_groups_and_repos(self):
-        """
-        Recursive return all groups, with repositories in those groups
-        """
-        return self._recursive_objects()
-
-    def recursive_groups(self):
-        """
-        Returns all children groups for this group including children of children
-        """
-        return self._recursive_objects(include_repos=False)
-
-    def get_new_name(self, group_name):
-        """
-        returns new full group name based on parent and new name
-
-        :param group_name:
-        """
-        path_prefix = (self.parent_group.full_path_splitted if
-                       self.parent_group else [])
-        return RepoGroup.url_sep().join(path_prefix + [group_name])
-
-    def get_api_data(self):
-        """
-        Common function for generating api data
-
-        """
-        group = self
-        data = dict(
-            group_id=group.group_id,
-            group_name=group.group_name,
-            group_description=group.group_description,
-            parent_group=group.parent_group.group_name if group.parent_group else None,
-            repositories=[x.repo_name for x in group.repositories],
-            owner=group.user.username
-        )
-        return data
-
-
-class Permission(Base, BaseModel):
-    __tablename__ = 'permissions'
-    __table_args__ = (
-        Index('p_perm_name_idx', 'permission_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    PERMS = [
-        ('hg.admin', _('Kallithea Administrator')),
-
-        ('repository.none', _('Repository no access')),
-        ('repository.read', _('Repository read access')),
-        ('repository.write', _('Repository write access')),
-        ('repository.admin', _('Repository admin access')),
-
-        ('group.none', _('Repository group no access')),
-        ('group.read', _('Repository group read access')),
-        ('group.write', _('Repository group write access')),
-        ('group.admin', _('Repository group admin access')),
-
-        ('usergroup.none', _('User group no access')),
-        ('usergroup.read', _('User group read access')),
-        ('usergroup.write', _('User group write access')),
-        ('usergroup.admin', _('User group admin access')),
-
-        ('hg.repogroup.create.false', _('Repository Group creation disabled')),
-        ('hg.repogroup.create.true', _('Repository Group creation enabled')),
-
-        ('hg.usergroup.create.false', _('User Group creation disabled')),
-        ('hg.usergroup.create.true', _('User Group creation enabled')),
-
-        ('hg.create.none', _('Repository creation disabled')),
-        ('hg.create.repository', _('Repository creation enabled')),
-
-        ('hg.fork.none', _('Repository forking disabled')),
-        ('hg.fork.repository', _('Repository forking enabled')),
-
-        ('hg.register.none', _('Registration disabled')),
-        ('hg.register.manual_activate', _('User Registration with manual account activation')),
-        ('hg.register.auto_activate', _('User Registration with automatic account activation')),
-
-        ('hg.extern_activate.manual', _('Manual activation of external account')),
-        ('hg.extern_activate.auto', _('Automatic activation of external account')),
-
-    ]
-
-    #definition of system default permissions for DEFAULT user
-    DEFAULT_USER_PERMISSIONS = [
-        'repository.read',
-        'group.read',
-        'usergroup.read',
-        'hg.create.repository',
-        'hg.fork.repository',
-        'hg.register.manual_activate',
-        'hg.extern_activate.auto',
-    ]
-
-    # defines which permissions are more important higher the more important
-    # Weight defines which permissions are more important.
-    # The higher number the more important.
-    PERM_WEIGHTS = {
-        'repository.none': 0,
-        'repository.read': 1,
-        'repository.write': 3,
-        'repository.admin': 4,
-
-        'group.none': 0,
-        'group.read': 1,
-        'group.write': 3,
-        'group.admin': 4,
-
-        'usergroup.none': 0,
-        'usergroup.read': 1,
-        'usergroup.write': 3,
-        'usergroup.admin': 4,
-        'hg.repogroup.create.false': 0,
-        'hg.repogroup.create.true': 1,
-
-        'hg.usergroup.create.false': 0,
-        'hg.usergroup.create.true': 1,
-
-        'hg.fork.none': 0,
-        'hg.fork.repository': 1,
-        'hg.create.none': 0,
-        'hg.create.repository': 1
-    }
-
-    permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    permission_name = Column("permission_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    permission_longname = Column("permission_longname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__, self.permission_id, self.permission_name
-        )
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.permission_name == key).scalar()
-
-    @classmethod
-    def get_default_perms(cls, default_user_id):
-        q = Session().query(UserRepoToPerm, Repository, cls)\
-         .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
-         .join((cls, UserRepoToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_group_perms(cls, default_user_id):
-        q = Session().query(UserRepoGroupToPerm, RepoGroup, cls)\
-         .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
-         .join((cls, UserRepoGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_user_group_perms(cls, default_user_id):
-        q = Session().query(UserUserGroupToPerm, UserGroup, cls)\
-         .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
-         .join((cls, UserUserGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserUserGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-
-class UserRepoToPerm(Base, BaseModel):
-    __tablename__ = 'repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'repository_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    repository = relationship('Repository')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, repository, permission):
-        n = cls()
-        n.user = user
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.repository)
-
-
-class UserUserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_user_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    user_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, user_group, permission):
-        n = cls()
-        n.user = user
-        n.user_group = user_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.user_group)
-
-
-class UserToPerm(Base, BaseModel):
-    __tablename__ = 'user_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    permission = relationship('Permission', lazy='joined')
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.permission)
-
-
-class UserGroupRepoToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    repository = relationship('Repository')
-
-    @classmethod
-    def create(cls, users_group, repository, permission):
-        n = cls()
-        n.users_group = users_group
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
-
-
-class UserGroupUserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_group_user_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
-        CheckConstraint('target_user_group_id != user_group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-
-    target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
-    user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, target_user_group, user_group, permission):
-        n = cls()
-        n.target_user_group = target_user_group
-        n.user_group = user_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
-
-
-class UserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'permission_id',),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-
-class UserRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    group = relationship('RepoGroup')
-    permission = relationship('Permission')
-
-
-class UserGroupRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    group = relationship('RepoGroup')
-
-
-class Statistics(Base, BaseModel):
-    __tablename__ = 'statistics'
-    __table_args__ = (
-         UniqueConstraint('repository_id'),
-         {'extend_existing': True, 'mysql_engine': 'InnoDB',
-          'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
-    stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
-    commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
-    commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
-    languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
-
-    repository = relationship('Repository', single_parent=True)
-
-
-class UserFollowing(Base, BaseModel):
-    __tablename__ = 'user_followings'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'follows_repository_id'),
-        UniqueConstraint('user_id', 'follows_user_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-
-    user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
-
-    follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relationship('Repository', order_by='Repository.repo_name')
-
-    @classmethod
-    def get_repo_followers(cls, repo_id):
-        return cls.query().filter(cls.follows_repo_id == repo_id)
-
-
-class CacheInvalidation(Base, BaseModel):
-    __tablename__ = 'cache_invalidation'
-    __table_args__ = (
-        UniqueConstraint('cache_key'),
-        Index('key_idx', 'cache_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    # cache_id, not used
-    cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    # cache_key as created by _get_cache_key
-    cache_key = Column("cache_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    # cache_args is a repo_name
-    cache_args = Column("cache_args", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    # instance sets cache_active True when it is caching,
-    # other instances set cache_active to False to indicate that this cache is invalid
-    cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
-
-    def __init__(self, cache_key, repo_name=''):
-        self.cache_key = cache_key
-        self.cache_args = repo_name
-        self.cache_active = False
-
-    def __unicode__(self):
-        return u"<%s('%s:%s[%s]')>" % (self.__class__.__name__,
-                            self.cache_id, self.cache_key, self.cache_active)
-
-    def _cache_key_partition(self):
-        prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
-        return prefix, repo_name, suffix
-
-    def get_prefix(self):
-        """
-        get prefix that might have been used in _get_cache_key to
-        generate self.cache_key. Only used for informational purposes
-        in repo_edit.html.
-        """
-        # prefix, repo_name, suffix
-        return self._cache_key_partition()[0]
-
-    def get_suffix(self):
-        """
-        get suffix that might have been used in _get_cache_key to
-        generate self.cache_key. Only used for informational purposes
-        in repo_edit.html.
-        """
-        # prefix, repo_name, suffix
-        return self._cache_key_partition()[2]
-
-    @classmethod
-    def clear_cache(cls):
-        """
-        Delete all cache keys from database.
-        Should only be run when all instances are down and all entries thus stale.
-        """
-        cls.query().delete()
-        Session().commit()
-
-    @classmethod
-    def _get_cache_key(cls, key):
-        """
-        Wrapper for generating a unique cache key for this instance and "key".
-        key must / will start with a repo_name which will be stored in .cache_args .
-        """
-        import kallithea
-        prefix = kallithea.CONFIG.get('instance_id', '')
-        return "%s%s" % (prefix, key)
-
-    @classmethod
-    def set_invalidate(cls, repo_name, delete=False):
-        """
-        Mark all caches of a repo as invalid in the database.
-        """
-        inv_objs = Session().query(cls).filter(cls.cache_args == repo_name).all()
-
-        try:
-            for inv_obj in inv_objs:
-                log.debug('marking %s key for invalidation based on repo_name=%s',
-                          inv_obj, safe_str(repo_name))
-                if delete:
-                    Session().delete(inv_obj)
-                else:
-                    inv_obj.cache_active = False
-                    Session().add(inv_obj)
-            Session().commit()
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-
-    @classmethod
-    def test_and_set_valid(cls, repo_name, kind, valid_cache_keys=None):
-        """
-        Mark this cache key as active and currently cached.
-        Return True if the existing cache registration still was valid.
-        Return False to indicate that it had been invalidated and caches should be refreshed.
-        """
-
-        key = (repo_name + '_' + kind) if kind else repo_name
-        cache_key = cls._get_cache_key(key)
-
-        if valid_cache_keys and cache_key in valid_cache_keys:
-            return True
-
-        try:
-            inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
-            if not inv_obj:
-                inv_obj = CacheInvalidation(cache_key, repo_name)
-            was_valid = inv_obj.cache_active
-            inv_obj.cache_active = True
-            Session().add(inv_obj)
-            Session().commit()
-            return was_valid
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-            return False
-
-    @classmethod
-    def get_valid_cache_keys(cls):
-        """
-        Return opaque object with information of which caches still are valid
-        and can be used without checking for invalidation.
-        """
-        return set(inv_obj.cache_key for inv_obj in cls.query().filter(cls.cache_active).all())
-
-
-class ChangesetComment(Base, BaseModel):
-    __tablename__ = 'changeset_comments'
-    __table_args__ = (
-        Index('cc_revision_idx', 'revision'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    revision = Column('revision', String(40), nullable=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-    line_no = Column('line_no', Unicode(10), nullable=True)
-    hl_lines = Column('hl_lines', Unicode(512), nullable=True)
-    f_path = Column('f_path', Unicode(1000), nullable=True)
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
-    text = Column('text', UnicodeText(25000), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    @classmethod
-    def get_users(cls, revision=None, pull_request_id=None):
-        """
-        Returns user associated with this ChangesetComment. ie those
-        who actually commented
-
-        :param cls:
-        :param revision:
-        """
-        q = Session().query(User)\
-                .join(ChangesetComment.author)
-        if revision:
-            q = q.filter(cls.revision == revision)
-        elif pull_request_id:
-            q = q.filter(cls.pull_request_id == pull_request_id)
-        return q.all()
-
-
-class ChangesetStatus(Base, BaseModel):
-    __tablename__ = 'changeset_statuses'
-    __table_args__ = (
-        Index('cs_revision_idx', 'revision'),
-        Index('cs_version_idx', 'version'),
-        UniqueConstraint('repo_id', 'revision', 'version'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
-    STATUS_APPROVED = 'approved'
-    STATUS_REJECTED = 'rejected'
-    STATUS_UNDER_REVIEW = 'under_review'
-
-    STATUSES = [
-        (STATUS_NOT_REVIEWED, _("Not Reviewed")),  # (no icon) and default
-        (STATUS_APPROVED, _("Approved")),
-        (STATUS_REJECTED, _("Rejected")),
-        (STATUS_UNDER_REVIEW, _("Under Review")),
-    ]
-
-    changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    revision = Column('revision', String(40), nullable=False)
-    status = Column('status', String(128), nullable=False, default=DEFAULT)
-    changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
-    modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
-    version = Column('version', Integer(), nullable=False, default=0)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    comment = relationship('ChangesetComment', lazy='joined')
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.status, self.author
-        )
-
-    @classmethod
-    def get_status_lbl(cls, value):
-        return dict(cls.STATUSES).get(value)
-
-    @property
-    def status_lbl(self):
-        return ChangesetStatus.get_status_lbl(self.status)
-
-
-class PullRequest(Base, BaseModel):
-    __tablename__ = 'pull_requests'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    # values for .status
-    STATUS_NEW = u'new'
-    STATUS_OPEN = u'open'
-    STATUS_CLOSED = u'closed'
-
-    pull_request_id = Column('pull_request_id', Integer(), nullable=False, primary_key=True)
-    title = Column('title', Unicode(256), nullable=True)
-    description = Column('description', UnicodeText(10240), nullable=True)
-    status = Column('status', Unicode(256), nullable=False, default=STATUS_NEW) # only for closedness, not approve/reject/etc
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    _revisions = Column('revisions', UnicodeText(20500))  # 500 revisions max
-    org_repo_id = Column('org_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    org_ref = Column('org_ref', Unicode(256), nullable=False)
-    other_repo_id = Column('other_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    other_ref = Column('other_ref', Unicode(256), nullable=False)
-
-    @hybrid_property
-    def revisions(self):
-        return self._revisions.split(':')
-
-    @revisions.setter
-    def revisions(self, val):
-        self._revisions = ':'.join(val)
-
-    @property
-    def org_ref_parts(self):
-        return self.org_ref.split(':')
-
-    @property
-    def other_ref_parts(self):
-        return self.other_ref.split(':')
-
-    author = relationship('User', lazy='joined')
-    reviewers = relationship('PullRequestReviewers',
-                             cascade="all, delete, delete-orphan")
-    org_repo = relationship('Repository', primaryjoin='PullRequest.org_repo_id==Repository.repo_id')
-    other_repo = relationship('Repository', primaryjoin='PullRequest.other_repo_id==Repository.repo_id')
-    statuses = relationship('ChangesetStatus')
-    comments = relationship('ChangesetComment',
-                             cascade="all, delete, delete-orphan")
-
-    def is_closed(self):
-        return self.status == self.STATUS_CLOSED
-
-    @property
-    def last_review_status(self):
-        return self.statuses[-1].status if self.statuses else ''
-
-    def __json__(self):
-        return dict(
-            revisions=self.revisions
-        )
-
-
-class PullRequestReviewers(Base, BaseModel):
-    __tablename__ = 'pull_request_reviewers'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    def __init__(self, user=None, pull_request=None):
-        self.user = user
-        self.pull_request = pull_request
-
-    pull_requests_reviewers_id = Column('pull_requests_reviewers_id', Integer(), nullable=False, primary_key=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
-
-    user = relationship('User')
-    pull_request = relationship('PullRequest')
-
-
-class Notification(Base, BaseModel):
-    __tablename__ = 'notifications'
-    __table_args__ = (
-        Index('notification_type_idx', 'type'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    TYPE_CHANGESET_COMMENT = u'cs_comment'
-    TYPE_MESSAGE = u'message'
-    TYPE_MENTION = u'mention'
-    TYPE_REGISTRATION = u'registration'
-    TYPE_PULL_REQUEST = u'pull_request'
-    TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
-
-    notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
-    subject = Column('subject', Unicode(512), nullable=True)
-    body = Column('body', UnicodeText(50000), nullable=True)
-    created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    type_ = Column('type', Unicode(256))
-
-    created_by_user = relationship('User')
-    notifications_to_users = relationship('UserNotification', lazy='joined',
-                                          cascade="all, delete, delete-orphan")
-
-    @property
-    def recipients(self):
-        return [x.user for x in UserNotification.query()\
-                .filter(UserNotification.notification == self)\
-                .order_by(UserNotification.user_id.asc()).all()]
-
-    @classmethod
-    def create(cls, created_by, subject, body, recipients, type_=None):
-        if type_ is None:
-            type_ = Notification.TYPE_MESSAGE
-
-        notification = cls()
-        notification.created_by_user = created_by
-        notification.subject = subject
-        notification.body = body
-        notification.type_ = type_
-        notification.created_on = datetime.datetime.now()
-
-        for u in recipients:
-            assoc = UserNotification()
-            assoc.notification = notification
-            u.notifications.append(assoc)
-        Session().add(notification)
-        return notification
-
-    @property
-    def description(self):
-        from kallithea.model.notification import NotificationModel
-        return NotificationModel().make_description(self)
-
-
-class UserNotification(Base, BaseModel):
-    __tablename__ = 'user_to_notification'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'notification_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
-    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
-    read = Column('read', Boolean, default=False)
-    sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
-
-    user = relationship('User', lazy="joined")
-    notification = relationship('Notification', lazy="joined",
-                                order_by=lambda: Notification.created_on.desc(),)
-
-    def mark_as_read(self):
-        self.read = True
-        Session().add(self)
-
-
-class Gist(Base, BaseModel):
-    __tablename__ = 'gists'
-    __table_args__ = (
-        Index('g_gist_access_id_idx', 'gist_access_id'),
-        Index('g_created_on_idx', 'created_on'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    GIST_PUBLIC = u'public'
-    GIST_PRIVATE = u'private'
-
-    gist_id = Column('gist_id', Integer(), primary_key=True)
-    gist_access_id = Column('gist_access_id', Unicode(250))
-    gist_description = Column('gist_description', UnicodeText(1024))
-    gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
-    gist_expires = Column('gist_expires', Float(53), nullable=False)
-    gist_type = Column('gist_type', Unicode(128), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    owner = relationship('User')
-
-    @classmethod
-    def get_or_404(cls, id_):
-        res = cls.query().filter(cls.gist_access_id == id_).scalar()
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def get_by_access_id(cls, gist_access_id):
-        return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
-
-    def gist_url(self):
-        import kallithea
-        alias_url = kallithea.CONFIG.get('gist_alias_url')
-        if alias_url:
-            return alias_url.replace('{gistid}', self.gist_access_id)
-
-        import kallithea.lib.helpers as h
-        return h.canonical_url('gist', gist_id=self.gist_access_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all gists are stored
-
-        :param cls:
-        """
-        from kallithea.model.gist import GIST_STORE_LOC
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == URL_SEP)
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return os.path.join(q.one().ui_value, GIST_STORE_LOC)
-
-    def get_api_data(self):
-        """
-        Common function for generating gist related data for API
-        """
-        gist = self
-        data = dict(
-            gist_id=gist.gist_id,
-            type=gist.gist_type,
-            access_id=gist.gist_access_id,
-            description=gist.gist_description,
-            url=gist.gist_url(),
-            expires=gist.gist_expires,
-            created_on=gist.created_on,
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-        )
-        data.update(self.get_api_data())
-        return data
-    ## SCM functions
-
-    @property
-    def scm_instance(self):
-        from kallithea.lib.vcs import get_repo
-        base_path = self.base_path()
-        return get_repo(os.path.join(*map(safe_str,
-                                          [base_path, self.gist_access_id])))
-
-
-class DbMigrateVersion(Base, BaseModel):
-    __tablename__ = 'db_migrate_version'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    repository_id = Column('repository_id', String(250), primary_key=True)
-    repository_path = Column('repository_path', Text)
-    version = Column('version', Integer)
--- a/kallithea/lib/dbmigrate/schema/db_2_1_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,2391 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate.schema.db_2_1_0
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Database Models for Kallithea
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Apr 08, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-import os
-import time
-import logging
-import datetime
-import traceback
-import hashlib
-import collections
-import functools
-
-from sqlalchemy import *
-from sqlalchemy.ext.hybrid import hybrid_property
-from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
-from beaker.cache import cache_region, region_invalidate
-from webob.exc import HTTPNotFound
-
-from pylons.i18n.translation import lazy_ugettext as _
-
-from kallithea.lib.vcs import get_backend
-from kallithea.lib.vcs.utils.helpers import get_scm
-from kallithea.lib.vcs.exceptions import VCSError
-from kallithea.lib.vcs.utils.lazy import LazyProperty
-from kallithea.lib.vcs.backends.base import EmptyChangeset
-
-from kallithea.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
-    safe_unicode, remove_prefix, time_to_datetime, aslist, Optional, safe_int
-from kallithea.lib.compat import json
-from kallithea.lib.caching_query import FromCache
-
-from kallithea.model.meta import Base, Session
-
-URL_SEP = '/'
-log = logging.getLogger(__name__)
-
-from kallithea import DB_PREFIX
-
-#==============================================================================
-# BASE CLASSES
-#==============================================================================
-
-_hash_key = lambda k: hashlib.md5(safe_str(k)).hexdigest()
-
-
-class BaseModel(object):
-    """
-    Base Model for all classess
-    """
-
-    @classmethod
-    def _get_keys(cls):
-        """return column names for this model """
-        return class_mapper(cls).c.keys()
-
-    def get_dict(self):
-        """
-        return dict with keys and values corresponding
-        to this model data """
-
-        d = {}
-        for k in self._get_keys():
-            d[k] = getattr(self, k)
-
-        # also use __json__() if present to get additional fields
-        _json_attr = getattr(self, '__json__', None)
-        if _json_attr:
-            # update with attributes from __json__
-            if callable(_json_attr):
-                _json_attr = _json_attr()
-            for k, val in _json_attr.iteritems():
-                d[k] = val
-        return d
-
-    def get_appstruct(self):
-        """return list with keys and values tuples corresponding
-        to this model data """
-
-        l = []
-        for k in self._get_keys():
-            l.append((k, getattr(self, k),))
-        return l
-
-    def populate_obj(self, populate_dict):
-        """populate model with data from given populate_dict"""
-
-        for k in self._get_keys():
-            if k in populate_dict:
-                setattr(self, k, populate_dict[k])
-
-    @classmethod
-    def query(cls):
-        return Session().query(cls)
-
-    @classmethod
-    def get(cls, id_):
-        if id_:
-            return cls.query().get(id_)
-
-    @classmethod
-    def get_or_404(cls, id_):
-        try:
-            id_ = int(id_)
-        except (TypeError, ValueError):
-            raise HTTPNotFound
-
-        res = cls.query().get(id_)
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def getAll(cls):
-        # deprecated and left for backward compatibility
-        return cls.get_all()
-
-    @classmethod
-    def get_all(cls):
-        return cls.query().all()
-
-    @classmethod
-    def delete(cls, id_):
-        obj = cls.query().get(id_)
-        Session().delete(obj)
-
-    def __repr__(self):
-        if hasattr(self, '__unicode__'):
-            # python repr needs to return str
-            try:
-                return safe_str(self.__unicode__())
-            except UnicodeDecodeError:
-                pass
-        return '<DB:%s>' % (self.__class__.__name__)
-
-
-class Setting(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'settings'
-    __table_args__ = (
-        UniqueConstraint('app_settings_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    SETTINGS_TYPES = {
-        'str': safe_str,
-        'int': safe_int,
-        'unicode': safe_unicode,
-        'bool': str2bool,
-        'list': functools.partial(aslist, sep=',')
-    }
-    DEFAULT_UPDATE_URL = ''
-
-    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    app_settings_name = Column("app_settings_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_value = Column("app_settings_value", String(4096, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _app_settings_type = Column("app_settings_type", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __init__(self, key='', val='', type='unicode'):
-        self.app_settings_name = key
-        self.app_settings_value = val
-        self.app_settings_type = type
-
-    @validates('_app_settings_value')
-    def validate_settings_value(self, key, val):
-        assert type(val) == unicode
-        return val
-
-    @hybrid_property
-    def app_settings_value(self):
-        v = self._app_settings_value
-        _type = self.app_settings_type
-        converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
-        return converter(v)
-
-    @app_settings_value.setter
-    def app_settings_value(self, val):
-        """
-        Setter that will always make sure we use unicode in app_settings_value
-
-        :param val:
-        """
-        self._app_settings_value = safe_unicode(val)
-
-    @hybrid_property
-    def app_settings_type(self):
-        return self._app_settings_type
-
-    @app_settings_type.setter
-    def app_settings_type(self, val):
-        if val not in self.SETTINGS_TYPES:
-            raise Exception('type must be one of %s got %s'
-                            % (self.SETTINGS_TYPES.keys(), val))
-        self._app_settings_type = val
-
-    def __unicode__(self):
-        return u"<%s('%s:%s[%s]')>" % (
-            self.__class__.__name__,
-            self.app_settings_name, self.app_settings_value, self.app_settings_type
-        )
-
-    @classmethod
-    def get_by_name(cls, key):
-        return cls.query()\
-            .filter(cls.app_settings_name == key).scalar()
-
-    @classmethod
-    def get_by_name_or_create(cls, key, val='', type='unicode'):
-        res = cls.get_by_name(key)
-        if not res:
-            res = cls(key, val, type)
-        return res
-
-    @classmethod
-    def create_or_update(cls, key, val=Optional(''), type=Optional('unicode')):
-        """
-        Creates or updates Kallithea setting. If updates is triggered it will only
-        update parameters that are explicityl set Optional instance will be skipped
-
-        :param key:
-        :param val:
-        :param type:
-        :return:
-        """
-        res = cls.get_by_name(key)
-        if not res:
-            val = Optional.extract(val)
-            type = Optional.extract(type)
-            res = cls(key, val, type)
-        else:
-            res.app_settings_name = key
-            if not isinstance(val, Optional):
-                # update if set
-                res.app_settings_value = val
-            if not isinstance(type, Optional):
-                # update if set
-                res.app_settings_type = type
-        return res
-
-    @classmethod
-    def get_app_settings(cls, cache=False):
-
-        ret = cls.query()
-
-        if cache:
-            ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
-
-        if not ret:
-            raise Exception('Could not get application settings !')
-        settings = {}
-        for each in ret:
-            settings[each.app_settings_name] = \
-                each.app_settings_value
-
-        return settings
-
-    @classmethod
-    def get_auth_plugins(cls, cache=False):
-        auth_plugins = cls.get_by_name("auth_plugins").app_settings_value
-        return auth_plugins
-
-    @classmethod
-    def get_auth_settings(cls, cache=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('auth_')).all()
-        fd = {}
-        for row in ret:
-            fd.update({row.app_settings_name: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_default_repo_settings(cls, cache=False, strip_prefix=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('default_')).all()
-        fd = {}
-        for row in ret:
-            key = row.app_settings_name
-            if strip_prefix:
-                key = remove_prefix(key, prefix='default_')
-            fd.update({key: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_server_info(cls):
-        import pkg_resources
-        import platform
-        import kallithea
-        from kallithea.lib.utils import check_git_version
-        mods = [(p.project_name, p.version) for p in pkg_resources.working_set]
-        info = {
-            'modules': sorted(mods, key=lambda k: k[0].lower()),
-            'py_version': platform.python_version(),
-            'platform': safe_unicode(platform.platform()),
-            'kallithea_version': kallithea.__version__,
-            'git_version': safe_unicode(check_git_version()),
-            'git_path': kallithea.CONFIG.get('git_path')
-        }
-        return info
-
-
-class Ui(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'ui'
-    __table_args__ = (
-        UniqueConstraint('ui_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    HOOK_UPDATE = 'changegroup.update'
-    HOOK_REPO_SIZE = 'changegroup.repo_size'
-    HOOK_PUSH = 'changegroup.push_logger'
-    HOOK_PRE_PUSH = 'prechangegroup.pre_push'
-    HOOK_PULL = 'outgoing.pull_logger'
-    HOOK_PRE_PULL = 'preoutgoing.pre_pull'
-
-    ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    ui_section = Column("ui_section", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_key = Column("ui_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_value = Column("ui_value", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
-
-    # def __init__(self, section='', key='', value=''):
-    #     self.ui_section = section
-    #     self.ui_key = key
-    #     self.ui_value = value
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.ui_key == key).scalar()
-
-    @classmethod
-    def get_builtin_hooks(cls):
-        q = cls.query()
-        q = q.filter(cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                     cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                     cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        return q.all()
-
-    @classmethod
-    def get_custom_hooks(cls):
-        q = cls.query()
-        q = q.filter(~cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                      cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                      cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        q = q.filter(cls.ui_section == 'hooks')
-        return q.all()
-
-    @classmethod
-    def get_repos_location(cls):
-        return cls.get_by_key('/').ui_value
-
-    @classmethod
-    def create_or_update_hook(cls, key, val):
-        new_ui = cls.get_by_key(key) or cls()
-        new_ui.ui_section = 'hooks'
-        new_ui.ui_active = True
-        new_ui.ui_key = key
-        new_ui.ui_value = val
-
-        Session().add(new_ui)
-
-    def __repr__(self):
-        return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
-                                    self.ui_key, self.ui_value)
-
-
-class User(Base, BaseModel):
-    __tablename__ = 'users'
-    __table_args__ = (
-        UniqueConstraint('username'), UniqueConstraint('email'),
-        Index('u_username_idx', 'username'),
-        Index('u_email_idx', 'email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    DEFAULT_USER = 'default'
-    DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
-
-    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    password = Column("password", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
-    name = Column("firstname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    lastname = Column("lastname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
-    extern_type = Column("extern_type", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    extern_name = Column("extern_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    api_key = Column("api_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    user_log = relationship('UserLog')
-    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
-
-    repositories = relationship('Repository')
-    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
-    followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
-
-    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
-
-    group_member = relationship('UserGroupMember', cascade='all')
-
-    notifications = relationship('UserNotification', cascade='all')
-    # notifications assigned to this user
-    user_created_notifications = relationship('Notification', cascade='all')
-    # comments created by this user
-    user_comments = relationship('ChangesetComment', cascade='all')
-    #extra emails for this user
-    user_emails = relationship('UserEmailMap', cascade='all')
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-    @property
-    def firstname(self):
-        # alias for future
-        return self.name
-
-    @property
-    def emails(self):
-        other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
-        return [self.email] + [x.email for x in other]
-
-    @property
-    def ip_addresses(self):
-        ret = UserIpMap.query().filter(UserIpMap.user == self).all()
-        return [x.ip_addr for x in ret]
-
-    @property
-    def username_and_name(self):
-        return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
-
-    @property
-    def full_name(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def full_name_or_username(self):
-        return ('%s %s' % (self.firstname, self.lastname)
-                if (self.firstname and self.lastname) else self.username)
-
-    @property
-    def full_contact(self):
-        return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
-
-    @property
-    def short_contact(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def is_admin(self):
-        return self.admin
-
-    @property
-    def AuthUser(self):
-        """
-        Returns instance of AuthUser for this user
-        """
-        from kallithea.lib.auth import AuthUser
-        return AuthUser(user_id=self.user_id, api_key=self.api_key,
-                        username=self.username)
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.user_id, self.username)
-
-    @classmethod
-    def get_by_username(cls, username, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.username.ilike(username))
-        else:
-            q = cls.query().filter(cls.username == username)
-
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(username)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get_by_api_key(cls, api_key, cache=False, fallback=True):
-        q = cls.query().filter(cls.api_key == api_key)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_api_key_%s" % api_key))
-        res = q.scalar()
-
-        if fallback and not res:
-            #fallback to additional keys
-            _res = UserApiKeys.query()\
-                .filter(UserApiKeys.api_key == api_key)\
-                .filter(or_(UserApiKeys.expires == -1,
-                            UserApiKeys.expires >= time.time()))\
-                .first()
-            if _res:
-                res = _res.user
-        return res
-
-    @classmethod
-    def get_by_email(cls, email, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.email.ilike(email))
-        else:
-            q = cls.query().filter(cls.email == email)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_email_key_%s" % email))
-
-        ret = q.scalar()
-        if ret is None:
-            q = UserEmailMap.query()
-            # try fetching in alternate email map
-            if case_insensitive:
-                q = q.filter(UserEmailMap.email.ilike(email))
-            else:
-                q = q.filter(UserEmailMap.email == email)
-            q = q.options(joinedload(UserEmailMap.user))
-            if cache:
-                q = q.options(FromCache("sql_cache_short",
-                                        "get_email_map_key_%s" % email))
-            ret = getattr(q.scalar(), 'user', None)
-
-        return ret
-
-    @classmethod
-    def get_from_cs_author(cls, author):
-        """
-        Tries to get User objects out of commit author string
-
-        :param author:
-        """
-        from kallithea.lib.helpers import email, author_name
-        # Valid email in the attribute passed, see if they're in the system
-        _email = email(author)
-        if _email:
-            user = cls.get_by_email(_email, case_insensitive=True)
-            if user:
-                return user
-        # Maybe we can match by username?
-        _author = author_name(author)
-        user = cls.get_by_username(_author, case_insensitive=True)
-        if user:
-            return user
-
-    def update_lastlogin(self):
-        """Update user lastlogin"""
-        self.last_login = datetime.datetime.now()
-        Session().add(self)
-        log.debug('updated user %s lastlogin', self.username)
-
-    @classmethod
-    def get_first_admin(cls):
-        user = User.query().filter(User.admin == True).first()
-        if user is None:
-            raise Exception('Missing administrative account!')
-        return user
-
-    @classmethod
-    def get_default_user(cls, cache=False):
-        user = User.get_by_username(User.DEFAULT_USER, cache=cache)
-        if user is None:
-            raise Exception('Missing default account!')
-        return user
-
-    def get_api_data(self):
-        """
-        Common function for generating user related data for API
-        """
-        user = self
-        data = dict(
-            user_id=user.user_id,
-            username=user.username,
-            firstname=user.name,
-            lastname=user.lastname,
-            email=user.email,
-            emails=user.emails,
-            api_key=user.api_key,
-            active=user.active,
-            admin=user.admin,
-            extern_type=user.extern_type,
-            extern_name=user.extern_name,
-            last_login=user.last_login,
-            ip_addresses=user.ip_addresses
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-            full_name=self.full_name,
-            full_name_or_username=self.full_name_or_username,
-            short_contact=self.short_contact,
-            full_contact=self.full_contact
-        )
-        data.update(self.get_api_data())
-        return data
-
-
-class UserApiKeys(Base, BaseModel):
-    __tablename__ = 'user_api_keys'
-    __table_args__ = (
-        Index('uak_api_key_idx', 'api_key'),
-        UniqueConstraint('api_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    api_key = Column("api_key", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True)
-    description = Column('description', UnicodeText(1024))
-    expires = Column('expires', Float(53), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    user = relationship('User', lazy='joined')
-
-
-class UserEmailMap(Base, BaseModel):
-    __tablename__ = 'user_email_map'
-    __table_args__ = (
-        Index('uem_email_idx', 'email'),
-        UniqueConstraint('email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    user = relationship('User', lazy='joined')
-
-    @validates('_email')
-    def validate_email(self, key, email):
-        # check if this email is not main one
-        main_email = Session().query(User).filter(User.email == email).scalar()
-        if main_email is not None:
-            raise AttributeError('email %s is present is user table' % email)
-        return email
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-
-class UserIpMap(Base, BaseModel):
-    __tablename__ = 'user_ip_map'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'ip_addr'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    ip_addr = Column("ip_addr", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    user = relationship('User', lazy='joined')
-
-    @classmethod
-    def _get_ip_range(cls, ip_addr):
-        from kallithea.lib import ipaddr
-        net = ipaddr.IPNetwork(address=ip_addr)
-        return [str(net.network), str(net.broadcast)]
-
-    def __json__(self):
-        return dict(
-          ip_addr=self.ip_addr,
-          ip_range=self._get_ip_range(self.ip_addr)
-        )
-
-    def __unicode__(self):
-        return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
-                                            self.user_id, self.ip_addr)
-
-class UserLog(Base, BaseModel):
-    __tablename__ = 'user_logs'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    username = Column("username", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
-    repository_name = Column("repository_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    user_ip = Column("user_ip", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action = Column("action", UnicodeText(1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.repository_name,
-                                      self.action)
-
-    @property
-    def action_as_day(self):
-        return datetime.date(*self.action_date.timetuple()[:3])
-
-    user = relationship('User')
-    repository = relationship('Repository', cascade='')
-
-
-class UserGroup(Base, BaseModel):
-    __tablename__ = 'users_groups'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_name = Column("users_group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    user_group_description = Column("user_group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
-    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
-    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-    user_user_group_to_perm = relationship('UserUserGroupToPerm ', cascade='all')
-    user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
-
-    user = relationship('User')
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.users_group_id,
-                                      self.users_group_name)
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False,
-                          case_insensitive=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.users_group_name.ilike(group_name))
-        else:
-            q = cls.query().filter(cls.users_group_name == group_name)
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(group_name)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get(cls, user_group_id, cache=False):
-        user_group = cls.query()
-        if cache:
-            user_group = user_group.options(FromCache("sql_cache_short",
-                                    "get_users_group_%s" % user_group_id))
-        return user_group.get(user_group_id)
-
-    def get_api_data(self, with_members=True):
-        user_group = self
-
-        data = dict(
-            users_group_id=user_group.users_group_id,
-            group_name=user_group.users_group_name,
-            group_description=user_group.user_group_description,
-            active=user_group.users_group_active,
-            owner=user_group.user.username,
-        )
-        if with_members:
-            members = []
-            for user in user_group.members:
-                user = user.user
-                members.append(user.get_api_data())
-            data['members'] = members
-
-        return data
-
-
-class UserGroupMember(Base, BaseModel):
-    __tablename__ = 'users_groups_members'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User', lazy='joined')
-    users_group = relationship('UserGroup')
-
-    def __init__(self, gr_id='', u_id=''):
-        self.users_group_id = gr_id
-        self.user_id = u_id
-
-
-class RepositoryField(Base, BaseModel):
-    __tablename__ = 'repositories_fields'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'field_key'),  # no-multi field
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    PREFIX = 'ex_'  # prefix used in form to not conflict with already existing fields
-
-    repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-    field_key = Column("field_key", String(250, convert_unicode=False, assert_unicode=None))
-    field_label = Column("field_label", String(1024, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_value = Column("field_value", String(10000, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_desc = Column("field_desc", String(1024, convert_unicode=False, assert_unicode=None), nullable=False)
-    field_type = Column("field_type", String(256), nullable=False, unique=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    repository = relationship('Repository')
-
-    @property
-    def field_key_prefixed(self):
-        return 'ex_%s' % self.field_key
-
-    @classmethod
-    def un_prefix_key(cls, key):
-        if key.startswith(cls.PREFIX):
-            return key[len(cls.PREFIX):]
-        return key
-
-    @classmethod
-    def get_by_key_name(cls, key, repo):
-        row = cls.query()\
-                .filter(cls.repository == repo)\
-                .filter(cls.field_key == key).scalar()
-        return row
-
-
-class Repository(Base, BaseModel):
-    __tablename__ = 'repositories'
-    __table_args__ = (
-        UniqueConstraint('repo_name'),
-        Index('r_repo_name_idx', 'repo_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
-
-    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repo_name = Column("repo_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    clone_uri = Column("clone_uri", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    repo_type = Column("repo_type", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
-    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
-    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
-    description = Column("description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    _landing_revision = Column("landing_revision", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    _locked = Column("locked", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
-    _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) #JSON data
-
-    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
-
-    user = relationship('User')
-    fork = relationship('Repository', remote_side=repo_id)
-    group = relationship('RepoGroup')
-    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    stats = relationship('Statistics', cascade='all', uselist=False)
-
-    followers = relationship('UserFollowing',
-                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
-                             cascade='all')
-    extra_fields = relationship('RepositoryField',
-                                cascade="all, delete, delete-orphan")
-
-    logs = relationship('UserLog')
-    comments = relationship('ChangesetComment', cascade="all, delete, delete-orphan")
-
-    pull_requests_org = relationship('PullRequest',
-                    primaryjoin='PullRequest.org_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    pull_requests_other = relationship('PullRequest',
-                    primaryjoin='PullRequest.other_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
-                                   safe_unicode(self.repo_name))
-
-    @hybrid_property
-    def landing_rev(self):
-        # always should return [rev_type, rev]
-        if self._landing_revision:
-            _rev_info = self._landing_revision.split(':')
-            if len(_rev_info) < 2:
-                _rev_info.insert(0, 'rev')
-            return [_rev_info[0], _rev_info[1]]
-        return [None, None]
-
-    @landing_rev.setter
-    def landing_rev(self, val):
-        if ':' not in val:
-            raise ValueError('value must be delimited with `:` and consist '
-                             'of <rev_type>:<rev>, got %s instead' % val)
-        self._landing_revision = val
-
-    @hybrid_property
-    def locked(self):
-        # always should return [user_id, timelocked]
-        if self._locked:
-            _lock_info = self._locked.split(':')
-            return int(_lock_info[0]), _lock_info[1]
-        return [None, None]
-
-    @locked.setter
-    def locked(self, val):
-        if val and isinstance(val, (list, tuple)):
-            self._locked = ':'.join(map(str, val))
-        else:
-            self._locked = None
-
-    @hybrid_property
-    def changeset_cache(self):
-        from kallithea.lib.vcs.backends.base import EmptyChangeset
-        dummy = EmptyChangeset().__json__()
-        if not self._changeset_cache:
-            return dummy
-        try:
-            return json.loads(self._changeset_cache)
-        except TypeError:
-            return dummy
-
-    @changeset_cache.setter
-    def changeset_cache(self, val):
-        try:
-            self._changeset_cache = json.dumps(val)
-        except Exception:
-            log.error(traceback.format_exc())
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def normalize_repo_name(cls, repo_name):
-        """
-        Normalizes os specific repo_name to the format internally stored inside
-        dabatabase using URL_SEP
-
-        :param cls:
-        :param repo_name:
-        """
-        return cls.url_sep().join(repo_name.split(os.sep))
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        q = Session().query(cls).filter(cls.repo_name == repo_name)
-        q = q.options(joinedload(Repository.fork))\
-                .options(joinedload(Repository.user))\
-                .options(joinedload(Repository.group))
-        return q.scalar()
-
-    @classmethod
-    def get_by_full_path(cls, repo_full_path):
-        repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
-        repo_name = cls.normalize_repo_name(repo_name)
-        return cls.get_by_repo_name(repo_name.strip(URL_SEP))
-
-    @classmethod
-    def get_repo_forks(cls, repo_id):
-        return cls.query().filter(Repository.fork_id == repo_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all repos are stored
-
-        :param cls:
-        """
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == cls.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def forks(self):
-        """
-        Return forks of this repo
-        """
-        return Repository.get_repo_forks(self.repo_id)
-
-    @property
-    def parent(self):
-        """
-        Returns fork parent
-        """
-        return self.fork
-
-    @property
-    def just_name(self):
-        return self.repo_name.split(Repository.url_sep())[-1]
-
-    @property
-    def groups_with_parents(self):
-        groups = []
-        if self.group is None:
-            return groups
-
-        cur_gr = self.group
-        groups.insert(0, cur_gr)
-        while 1:
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            groups.insert(0, gr)
-
-        return groups
-
-    @property
-    def groups_and_repo(self):
-        return self.groups_with_parents, self.just_name, self.repo_name
-
-    @LazyProperty
-    def repo_path(self):
-        """
-        Returns base full path for that repository means where it actually
-        exists on a filesystem
-        """
-        q = Session().query(Ui).filter(Ui.ui_key ==
-                                              Repository.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def repo_full_path(self):
-        p = [self.repo_path]
-        # we need to split the name by / since this is how we store the
-        # names in the database, but that eventually needs to be converted
-        # into a valid system path
-        p += self.repo_name.split(Repository.url_sep())
-        return os.path.join(*map(safe_unicode, p))
-
-    @property
-    def cache_keys(self):
-        """
-        Returns associated cache keys for that repo
-        """
-        return CacheInvalidation.query()\
-            .filter(CacheInvalidation.cache_args == self.repo_name)\
-            .order_by(CacheInvalidation.cache_key)\
-            .all()
-
-    def get_new_name(self, repo_name):
-        """
-        returns new full repository name based on assigned group and new new
-
-        :param group_name:
-        """
-        path_prefix = self.group.full_path_splitted if self.group else []
-        return Repository.url_sep().join(path_prefix + [repo_name])
-
-    @property
-    def _ui(self):
-        """
-        Creates an db based ui object for this repository
-        """
-        from kallithea.lib.utils import make_ui
-        return make_ui('db', clear_session=False)
-
-    @classmethod
-    def is_valid(cls, repo_name):
-        """
-        returns True if given repo name is a valid filesystem repository
-
-        :param cls:
-        :param repo_name:
-        """
-        from kallithea.lib.utils import is_valid_repo
-
-        return is_valid_repo(repo_name, cls.base_path())
-
-    def get_api_data(self):
-        """
-        Common function for generating repo api data
-
-        """
-        repo = self
-        data = dict(
-            repo_id=repo.repo_id,
-            repo_name=repo.repo_name,
-            repo_type=repo.repo_type,
-            clone_uri=repo.clone_uri,
-            private=repo.private,
-            created_on=repo.created_on,
-            description=repo.description,
-            landing_rev=repo.landing_rev,
-            owner=repo.user.username,
-            fork_of=repo.fork.repo_name if repo.fork else None,
-            enable_statistics=repo.enable_statistics,
-            enable_locking=repo.enable_locking,
-            enable_downloads=repo.enable_downloads,
-            last_changeset=repo.changeset_cache,
-            locked_by=User.get(self.locked[0]).get_api_data() \
-                if self.locked[0] else None,
-            locked_date=time_to_datetime(self.locked[1]) \
-                if self.locked[1] else None
-        )
-        rc_config = Setting.get_app_settings()
-        repository_fields = str2bool(rc_config.get('repository_fields'))
-        if repository_fields:
-            for f in self.extra_fields:
-                data[f.field_key_prefixed] = f.field_value
-
-        return data
-
-    @classmethod
-    def lock(cls, repo, user_id, lock_time=None):
-        if not lock_time:
-            lock_time = time.time()
-        repo.locked = [user_id, lock_time]
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def unlock(cls, repo):
-        repo.locked = None
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def getlock(cls, repo):
-        return repo.locked
-
-    @property
-    def last_db_change(self):
-        return self.updated_on
-
-    def clone_url(self, **override):
-        import kallithea.lib.helpers as h
-        from urlparse import urlparse
-        import urllib
-        parsed_url = urlparse(h.canonical_url('home'))
-        default_clone_uri = '%(scheme)s://%(user)s%(pass)s%(netloc)s%(prefix)s%(path)s'
-        decoded_path = safe_unicode(urllib.unquote(parsed_url.path))
-        args = {
-           'user': '',
-           'pass': '',
-           'scheme': parsed_url.scheme,
-           'netloc': parsed_url.netloc,
-           'prefix': decoded_path,
-           'path': self.repo_name
-        }
-
-        args.update(override)
-        return default_clone_uri % args
-
-    #==========================================================================
-    # SCM PROPERTIES
-    #==========================================================================
-
-    def get_changeset(self, rev=None):
-        return get_changeset_safe(self.scm_instance, rev)
-
-    def get_landing_changeset(self):
-        """
-        Returns landing changeset, or if that doesn't exist returns the tip
-        """
-        _rev_type, _rev = self.landing_rev
-        cs = self.get_changeset(_rev)
-        if isinstance(cs, EmptyChangeset):
-            return self.get_changeset()
-        return cs
-
-    def update_changeset_cache(self, cs_cache=None):
-        """
-        Update cache of last changeset for repository, keys should be::
-
-            short_id
-            raw_id
-            revision
-            message
-            date
-            author
-
-        :param cs_cache:
-        """
-        from kallithea.lib.vcs.backends.base import BaseChangeset
-        if cs_cache is None:
-            cs_cache = EmptyChangeset()
-            # use no-cache version here
-            scm_repo = self.scm_instance_no_cache()
-            if scm_repo:
-                cs_cache = scm_repo.get_changeset()
-
-        if isinstance(cs_cache, BaseChangeset):
-            cs_cache = cs_cache.__json__()
-
-        if (cs_cache != self.changeset_cache or not self.changeset_cache):
-            _default = datetime.datetime.fromtimestamp(0)
-            last_change = cs_cache.get('date') or _default
-            log.debug('updated repo %s with new cs cache %s',
-                      self.repo_name, cs_cache)
-            self.updated_on = last_change
-            self.changeset_cache = cs_cache
-            Session().add(self)
-            Session().commit()
-        else:
-            log.debug('Skipping repo:%s already with latest changes',
-                      self.repo_name)
-
-    @property
-    def tip(self):
-        return self.get_changeset('tip')
-
-    @property
-    def author(self):
-        return self.tip.author
-
-    @property
-    def last_change(self):
-        return self.scm_instance.last_change
-
-    def get_comments(self, revisions=None):
-        """
-        Returns comments for this repository grouped by revisions
-
-        :param revisions: filter query by revisions only
-        """
-        cmts = ChangesetComment.query()\
-            .filter(ChangesetComment.repo == self)
-        if revisions:
-            cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
-        grouped = collections.defaultdict(list)
-        for cmt in cmts.all():
-            grouped[cmt.revision].append(cmt)
-        return grouped
-
-    def statuses(self, revisions=None):
-        """
-        Returns statuses for this repository
-
-        :param revisions: list of revisions to get statuses for
-        """
-
-        statuses = ChangesetStatus.query()\
-            .filter(ChangesetStatus.repo == self)\
-            .filter(ChangesetStatus.version == 0)
-        if revisions:
-            statuses = statuses.filter(ChangesetStatus.revision.in_(revisions))
-        grouped = {}
-
-        #maybe we have open new pullrequest without a status ?
-        stat = ChangesetStatus.STATUS_UNDER_REVIEW
-        status_lbl = ChangesetStatus.get_status_lbl(stat)
-        for pr in PullRequest.query().filter(PullRequest.org_repo == self).all():
-            for rev in pr.revisions:
-                pr_id = pr.pull_request_id
-                pr_repo = pr.other_repo.repo_name
-                grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
-
-        for stat in statuses.all():
-            pr_id = pr_repo = None
-            if stat.pull_request:
-                pr_id = stat.pull_request.pull_request_id
-                pr_repo = stat.pull_request.other_repo.repo_name
-            grouped[stat.revision] = [str(stat.status), stat.status_lbl,
-                                      pr_id, pr_repo]
-        return grouped
-
-    def _repo_size(self):
-        from kallithea.lib import helpers as h
-        log.debug('calculating repository size...')
-        return h.format_byte_size(self.scm_instance.size)
-
-    #==========================================================================
-    # SCM CACHE INSTANCE
-    #==========================================================================
-
-    def set_invalidate(self):
-        """
-        Mark caches of this repo as invalid.
-        """
-        CacheInvalidation.set_invalidate(self.repo_name)
-
-    def scm_instance_no_cache(self):
-        return self.__get_instance()
-
-    @property
-    def scm_instance(self):
-        import kallithea
-        full_cache = str2bool(kallithea.CONFIG.get('vcs_full_cache'))
-        if full_cache:
-            return self.scm_instance_cached()
-        return self.__get_instance()
-
-    def scm_instance_cached(self, valid_cache_keys=None):
-        @cache_region('long_term')
-        def _c(repo_name):
-            return self.__get_instance()
-        rn = self.repo_name
-
-        valid = CacheInvalidation.test_and_set_valid(rn, None, valid_cache_keys=valid_cache_keys)
-        if not valid:
-            log.debug('Cache for %s invalidated, getting new object', rn)
-            region_invalidate(_c, None, rn)
-        else:
-            log.debug('Getting obj for %s from cache', rn)
-        return _c(rn)
-
-    def __get_instance(self):
-        repo_full_path = self.repo_full_path
-        try:
-            alias = get_scm(repo_full_path)[0]
-            log.debug('Creating instance of %s repository from %s',
-                      alias, repo_full_path)
-            backend = get_backend(alias)
-        except VCSError:
-            log.error(traceback.format_exc())
-            log.error('Perhaps this repository is in db and not in '
-                      'filesystem run rescan repositories with '
-                      '"destroy old data " option from admin panel')
-            return
-
-        if alias == 'hg':
-
-            repo = backend(safe_str(repo_full_path), create=False,
-                           baseui=self._ui)
-        else:
-            repo = backend(repo_full_path, create=False)
-
-        return repo
-
-    def __json__(self):
-        return dict(landing_rev = self.landing_rev)
-
-class RepoGroup(Base, BaseModel):
-    __tablename__ = 'groups'
-    __table_args__ = (
-        UniqueConstraint('group_name', 'group_parent_id'),
-        CheckConstraint('group_id != group_parent_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    __mapper_args__ = {'order_by': 'group_name'}
-
-    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    group_name = Column("group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
-    group_description = Column("group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-    parent_group = relationship('RepoGroup', remote_side=group_id)
-    user = relationship('User')
-
-    def __init__(self, group_name='', parent_group=None):
-        self.group_name = group_name
-        self.parent_group = parent_group
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
-                                      self.group_name)
-
-    @classmethod
-    def groups_choices(cls, groups=None, show_empty_group=True):
-        from webhelpers.html import literal as _literal
-        if not groups:
-            groups = cls.query().all()
-
-        repo_groups = []
-        if show_empty_group:
-            repo_groups = [('-1', u'-- %s --' % _('top level'))]
-        sep = ' &raquo; '
-        _name = lambda k: _literal(sep.join(k))
-
-        repo_groups.extend([(x.group_id, _name(x.full_path_splitted))
-                              for x in groups])
-
-        repo_groups = sorted(repo_groups, key=lambda t: t[1].split(sep)[0])
-        return repo_groups
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
-        if case_insensitive:
-            gr = cls.query()\
-                .filter(cls.group_name.ilike(group_name))
-        else:
-            gr = cls.query()\
-                .filter(cls.group_name == group_name)
-        if cache:
-            gr = gr.options(FromCache(
-                            "sql_cache_short",
-                            "get_group_%s" % _hash_key(group_name)
-                            )
-            )
-        return gr.scalar()
-
-    @property
-    def parents(self):
-        parents_recursion_limit = 5
-        groups = []
-        if self.parent_group is None:
-            return groups
-        cur_gr = self.parent_group
-        groups.insert(0, cur_gr)
-        cnt = 0
-        while 1:
-            cnt += 1
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            if cnt == parents_recursion_limit:
-                # this will prevent accidental infinite loops
-                log.error('group nested more than %s',
-                          parents_recursion_limit)
-                break
-
-            groups.insert(0, gr)
-        return groups
-
-    @property
-    def children(self):
-        return RepoGroup.query().filter(RepoGroup.parent_group == self)
-
-    @property
-    def name(self):
-        return self.group_name.split(RepoGroup.url_sep())[-1]
-
-    @property
-    def full_path(self):
-        return self.group_name
-
-    @property
-    def full_path_splitted(self):
-        return self.group_name.split(RepoGroup.url_sep())
-
-    @property
-    def repositories(self):
-        return Repository.query()\
-                .filter(Repository.group == self)\
-                .order_by(Repository.repo_name)
-
-    @property
-    def repositories_recursive_count(self):
-        cnt = self.repositories.count()
-
-        def children_count(group):
-            cnt = 0
-            for child in group.children:
-                cnt += child.repositories.count()
-                cnt += children_count(child)
-            return cnt
-
-        return cnt + children_count(self)
-
-    def _recursive_objects(self, include_repos=True):
-        all_ = []
-
-        def _get_members(root_gr):
-            if include_repos:
-                for r in root_gr.repositories:
-                    all_.append(r)
-            childs = root_gr.children.all()
-            if childs:
-                for gr in childs:
-                    all_.append(gr)
-                    _get_members(gr)
-
-        _get_members(self)
-        return [self] + all_
-
-    def recursive_groups_and_repos(self):
-        """
-        Recursive return all groups, with repositories in those groups
-        """
-        return self._recursive_objects()
-
-    def recursive_groups(self):
-        """
-        Returns all children groups for this group including children of children
-        """
-        return self._recursive_objects(include_repos=False)
-
-    def get_new_name(self, group_name):
-        """
-        returns new full group name based on parent and new name
-
-        :param group_name:
-        """
-        path_prefix = (self.parent_group.full_path_splitted if
-                       self.parent_group else [])
-        return RepoGroup.url_sep().join(path_prefix + [group_name])
-
-    def get_api_data(self):
-        """
-        Common function for generating api data
-
-        """
-        group = self
-        data = dict(
-            group_id=group.group_id,
-            group_name=group.group_name,
-            group_description=group.group_description,
-            parent_group=group.parent_group.group_name if group.parent_group else None,
-            repositories=[x.repo_name for x in group.repositories],
-            owner=group.user.username
-        )
-        return data
-
-
-class Permission(Base, BaseModel):
-    __tablename__ = 'permissions'
-    __table_args__ = (
-        Index('p_perm_name_idx', 'permission_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    PERMS = [
-        ('hg.admin', _('Kallithea Administrator')),
-
-        ('repository.none', _('Repository no access')),
-        ('repository.read', _('Repository read access')),
-        ('repository.write', _('Repository write access')),
-        ('repository.admin', _('Repository admin access')),
-
-        ('group.none', _('Repository group no access')),
-        ('group.read', _('Repository group read access')),
-        ('group.write', _('Repository group write access')),
-        ('group.admin', _('Repository group admin access')),
-
-        ('usergroup.none', _('User group no access')),
-        ('usergroup.read', _('User group read access')),
-        ('usergroup.write', _('User group write access')),
-        ('usergroup.admin', _('User group admin access')),
-
-        ('hg.repogroup.create.false', _('Repository Group creation disabled')),
-        ('hg.repogroup.create.true', _('Repository Group creation enabled')),
-
-        ('hg.usergroup.create.false', _('User Group creation disabled')),
-        ('hg.usergroup.create.true', _('User Group creation enabled')),
-
-        ('hg.create.none', _('Repository creation disabled')),
-        ('hg.create.repository', _('Repository creation enabled')),
-
-        ('hg.fork.none', _('Repository forking disabled')),
-        ('hg.fork.repository', _('Repository forking enabled')),
-
-        ('hg.register.none', _('Registration disabled')),
-        ('hg.register.manual_activate', _('User Registration with manual account activation')),
-        ('hg.register.auto_activate', _('User Registration with automatic account activation')),
-
-        ('hg.extern_activate.manual', _('Manual activation of external account')),
-        ('hg.extern_activate.auto', _('Automatic activation of external account')),
-
-    ]
-
-    #definition of system default permissions for DEFAULT user
-    DEFAULT_USER_PERMISSIONS = [
-        'repository.read',
-        'group.read',
-        'usergroup.read',
-        'hg.create.repository',
-        'hg.fork.repository',
-        'hg.register.manual_activate',
-        'hg.extern_activate.auto',
-    ]
-
-    # defines which permissions are more important higher the more important
-    # Weight defines which permissions are more important.
-    # The higher number the more important.
-    PERM_WEIGHTS = {
-        'repository.none': 0,
-        'repository.read': 1,
-        'repository.write': 3,
-        'repository.admin': 4,
-
-        'group.none': 0,
-        'group.read': 1,
-        'group.write': 3,
-        'group.admin': 4,
-
-        'usergroup.none': 0,
-        'usergroup.read': 1,
-        'usergroup.write': 3,
-        'usergroup.admin': 4,
-        'hg.repogroup.create.false': 0,
-        'hg.repogroup.create.true': 1,
-
-        'hg.usergroup.create.false': 0,
-        'hg.usergroup.create.true': 1,
-
-        'hg.fork.none': 0,
-        'hg.fork.repository': 1,
-        'hg.create.none': 0,
-        'hg.create.repository': 1
-    }
-
-    permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    permission_name = Column("permission_name", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    permission_longname = Column("permission_longname", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__, self.permission_id, self.permission_name
-        )
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.permission_name == key).scalar()
-
-    @classmethod
-    def get_default_perms(cls, default_user_id):
-        q = Session().query(UserRepoToPerm, Repository, cls)\
-         .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
-         .join((cls, UserRepoToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_group_perms(cls, default_user_id):
-        q = Session().query(UserRepoGroupToPerm, RepoGroup, cls)\
-         .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
-         .join((cls, UserRepoGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_user_group_perms(cls, default_user_id):
-        q = Session().query(UserUserGroupToPerm, UserGroup, cls)\
-         .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
-         .join((cls, UserUserGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserUserGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-
-class UserRepoToPerm(Base, BaseModel):
-    __tablename__ = 'repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'repository_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    repository = relationship('Repository')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, repository, permission):
-        n = cls()
-        n.user = user
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.repository)
-
-
-class UserUserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_user_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    user_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, user_group, permission):
-        n = cls()
-        n.user = user
-        n.user_group = user_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.user_group)
-
-
-class UserToPerm(Base, BaseModel):
-    __tablename__ = 'user_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    permission = relationship('Permission', lazy='joined')
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.permission)
-
-
-class UserGroupRepoToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    repository = relationship('Repository')
-
-    @classmethod
-    def create(cls, users_group, repository, permission):
-        n = cls()
-        n.users_group = users_group
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
-
-
-class UserGroupUserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_group_user_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
-        CheckConstraint('target_user_group_id != user_group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-
-    target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
-    user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, target_user_group, user_group, permission):
-        n = cls()
-        n.target_user_group = target_user_group
-        n.user_group = user_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
-
-
-class UserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'permission_id',),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-
-class UserRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    group = relationship('RepoGroup')
-    permission = relationship('Permission')
-
-
-class UserGroupRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    group = relationship('RepoGroup')
-
-
-class Statistics(Base, BaseModel):
-    __tablename__ = 'statistics'
-    __table_args__ = (
-         UniqueConstraint('repository_id'),
-         {'extend_existing': True, 'mysql_engine': 'InnoDB',
-          'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
-    stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
-    commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
-    commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
-    languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
-
-    repository = relationship('Repository', single_parent=True)
-
-
-class UserFollowing(Base, BaseModel):
-    __tablename__ = 'user_followings'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'follows_repository_id'),
-        UniqueConstraint('user_id', 'follows_user_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-
-    user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
-
-    follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relationship('Repository', order_by='Repository.repo_name')
-
-    @classmethod
-    def get_repo_followers(cls, repo_id):
-        return cls.query().filter(cls.follows_repo_id == repo_id)
-
-
-class CacheInvalidation(Base, BaseModel):
-    __tablename__ = 'cache_invalidation'
-    __table_args__ = (
-        UniqueConstraint('cache_key'),
-        Index('key_idx', 'cache_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    # cache_id, not used
-    cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    # cache_key as created by _get_cache_key
-    cache_key = Column("cache_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    # cache_args is a repo_name
-    cache_args = Column("cache_args", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    # instance sets cache_active True when it is caching,
-    # other instances set cache_active to False to indicate that this cache is invalid
-    cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
-
-    def __init__(self, cache_key, repo_name=''):
-        self.cache_key = cache_key
-        self.cache_args = repo_name
-        self.cache_active = False
-
-    def __unicode__(self):
-        return u"<%s('%s:%s[%s]')>" % (self.__class__.__name__,
-                            self.cache_id, self.cache_key, self.cache_active)
-
-    def _cache_key_partition(self):
-        prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
-        return prefix, repo_name, suffix
-
-    def get_prefix(self):
-        """
-        get prefix that might have been used in _get_cache_key to
-        generate self.cache_key. Only used for informational purposes
-        in repo_edit.html.
-        """
-        # prefix, repo_name, suffix
-        return self._cache_key_partition()[0]
-
-    def get_suffix(self):
-        """
-        get suffix that might have been used in _get_cache_key to
-        generate self.cache_key. Only used for informational purposes
-        in repo_edit.html.
-        """
-        # prefix, repo_name, suffix
-        return self._cache_key_partition()[2]
-
-    @classmethod
-    def clear_cache(cls):
-        """
-        Delete all cache keys from database.
-        Should only be run when all instances are down and all entries thus stale.
-        """
-        cls.query().delete()
-        Session().commit()
-
-    @classmethod
-    def _get_cache_key(cls, key):
-        """
-        Wrapper for generating a unique cache key for this instance and "key".
-        key must / will start with a repo_name which will be stored in .cache_args .
-        """
-        import kallithea
-        prefix = kallithea.CONFIG.get('instance_id', '')
-        return "%s%s" % (prefix, key)
-
-    @classmethod
-    def set_invalidate(cls, repo_name, delete=False):
-        """
-        Mark all caches of a repo as invalid in the database.
-        """
-        inv_objs = Session().query(cls).filter(cls.cache_args == repo_name).all()
-
-        try:
-            for inv_obj in inv_objs:
-                log.debug('marking %s key for invalidation based on repo_name=%s',
-                          inv_obj, safe_str(repo_name))
-                if delete:
-                    Session().delete(inv_obj)
-                else:
-                    inv_obj.cache_active = False
-                    Session().add(inv_obj)
-            Session().commit()
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-
-    @classmethod
-    def test_and_set_valid(cls, repo_name, kind, valid_cache_keys=None):
-        """
-        Mark this cache key as active and currently cached.
-        Return True if the existing cache registration still was valid.
-        Return False to indicate that it had been invalidated and caches should be refreshed.
-        """
-
-        key = (repo_name + '_' + kind) if kind else repo_name
-        cache_key = cls._get_cache_key(key)
-
-        if valid_cache_keys and cache_key in valid_cache_keys:
-            return True
-
-        try:
-            inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
-            if not inv_obj:
-                inv_obj = CacheInvalidation(cache_key, repo_name)
-            was_valid = inv_obj.cache_active
-            inv_obj.cache_active = True
-            Session().add(inv_obj)
-            Session().commit()
-            return was_valid
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-            return False
-
-    @classmethod
-    def get_valid_cache_keys(cls):
-        """
-        Return opaque object with information of which caches still are valid
-        and can be used without checking for invalidation.
-        """
-        return set(inv_obj.cache_key for inv_obj in cls.query().filter(cls.cache_active).all())
-
-
-class ChangesetComment(Base, BaseModel):
-    __tablename__ = 'changeset_comments'
-    __table_args__ = (
-        Index('cc_revision_idx', 'revision'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    revision = Column('revision', String(40), nullable=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-    line_no = Column('line_no', Unicode(10), nullable=True)
-    hl_lines = Column('hl_lines', Unicode(512), nullable=True)
-    f_path = Column('f_path', Unicode(1000), nullable=True)
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
-    text = Column('text', UnicodeText(25000), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    @classmethod
-    def get_users(cls, revision=None, pull_request_id=None):
-        """
-        Returns user associated with this ChangesetComment. ie those
-        who actually commented
-
-        :param cls:
-        :param revision:
-        """
-        q = Session().query(User)\
-                .join(ChangesetComment.author)
-        if revision:
-            q = q.filter(cls.revision == revision)
-        elif pull_request_id:
-            q = q.filter(cls.pull_request_id == pull_request_id)
-        return q.all()
-
-
-class ChangesetStatus(Base, BaseModel):
-    __tablename__ = 'changeset_statuses'
-    __table_args__ = (
-        Index('cs_revision_idx', 'revision'),
-        Index('cs_version_idx', 'version'),
-        UniqueConstraint('repo_id', 'revision', 'version'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
-    STATUS_APPROVED = 'approved'
-    STATUS_REJECTED = 'rejected'
-    STATUS_UNDER_REVIEW = 'under_review'
-
-    STATUSES = [
-        (STATUS_NOT_REVIEWED, _("Not Reviewed")),  # (no icon) and default
-        (STATUS_APPROVED, _("Approved")),
-        (STATUS_REJECTED, _("Rejected")),
-        (STATUS_UNDER_REVIEW, _("Under Review")),
-    ]
-
-    changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    revision = Column('revision', String(40), nullable=False)
-    status = Column('status', String(128), nullable=False, default=DEFAULT)
-    changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
-    modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
-    version = Column('version', Integer(), nullable=False, default=0)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    comment = relationship('ChangesetComment', lazy='joined')
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.status, self.author
-        )
-
-    @classmethod
-    def get_status_lbl(cls, value):
-        return dict(cls.STATUSES).get(value)
-
-    @property
-    def status_lbl(self):
-        return ChangesetStatus.get_status_lbl(self.status)
-
-
-class PullRequest(Base, BaseModel):
-    __tablename__ = 'pull_requests'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    # values for .status
-    STATUS_NEW = u'new'
-    STATUS_OPEN = u'open'
-    STATUS_CLOSED = u'closed'
-
-    pull_request_id = Column('pull_request_id', Integer(), nullable=False, primary_key=True)
-    title = Column('title', Unicode(256), nullable=True)
-    description = Column('description', UnicodeText(10240), nullable=True)
-    status = Column('status', Unicode(256), nullable=False, default=STATUS_NEW) # only for closedness, not approve/reject/etc
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    _revisions = Column('revisions', UnicodeText(20500))  # 500 revisions max
-    org_repo_id = Column('org_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    org_ref = Column('org_ref', Unicode(256), nullable=False)
-    other_repo_id = Column('other_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    other_ref = Column('other_ref', Unicode(256), nullable=False)
-
-    @hybrid_property
-    def revisions(self):
-        return self._revisions.split(':')
-
-    @revisions.setter
-    def revisions(self, val):
-        self._revisions = ':'.join(val)
-
-    @property
-    def org_ref_parts(self):
-        return self.org_ref.split(':')
-
-    @property
-    def other_ref_parts(self):
-        return self.other_ref.split(':')
-
-    author = relationship('User', lazy='joined')
-    reviewers = relationship('PullRequestReviewers',
-                             cascade="all, delete, delete-orphan")
-    org_repo = relationship('Repository', primaryjoin='PullRequest.org_repo_id==Repository.repo_id')
-    other_repo = relationship('Repository', primaryjoin='PullRequest.other_repo_id==Repository.repo_id')
-    statuses = relationship('ChangesetStatus')
-    comments = relationship('ChangesetComment',
-                             cascade="all, delete, delete-orphan")
-
-    def is_closed(self):
-        return self.status == self.STATUS_CLOSED
-
-    @property
-    def last_review_status(self):
-        return self.statuses[-1].status if self.statuses else ''
-
-    def __json__(self):
-        return dict(
-            revisions=self.revisions
-        )
-
-
-class PullRequestReviewers(Base, BaseModel):
-    __tablename__ = 'pull_request_reviewers'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    def __init__(self, user=None, pull_request=None):
-        self.user = user
-        self.pull_request = pull_request
-
-    pull_requests_reviewers_id = Column('pull_requests_reviewers_id', Integer(), nullable=False, primary_key=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
-
-    user = relationship('User')
-    pull_request = relationship('PullRequest')
-
-
-class Notification(Base, BaseModel):
-    __tablename__ = 'notifications'
-    __table_args__ = (
-        Index('notification_type_idx', 'type'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    TYPE_CHANGESET_COMMENT = u'cs_comment'
-    TYPE_MESSAGE = u'message'
-    TYPE_MENTION = u'mention'
-    TYPE_REGISTRATION = u'registration'
-    TYPE_PULL_REQUEST = u'pull_request'
-    TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
-
-    notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
-    subject = Column('subject', Unicode(512), nullable=True)
-    body = Column('body', UnicodeText(50000), nullable=True)
-    created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    type_ = Column('type', Unicode(256))
-
-    created_by_user = relationship('User')
-    notifications_to_users = relationship('UserNotification', lazy='joined',
-                                          cascade="all, delete, delete-orphan")
-
-    @property
-    def recipients(self):
-        return [x.user for x in UserNotification.query()\
-                .filter(UserNotification.notification == self)\
-                .order_by(UserNotification.user_id.asc()).all()]
-
-    @classmethod
-    def create(cls, created_by, subject, body, recipients, type_=None):
-        if type_ is None:
-            type_ = Notification.TYPE_MESSAGE
-
-        notification = cls()
-        notification.created_by_user = created_by
-        notification.subject = subject
-        notification.body = body
-        notification.type_ = type_
-        notification.created_on = datetime.datetime.now()
-
-        for u in recipients:
-            assoc = UserNotification()
-            assoc.notification = notification
-            u.notifications.append(assoc)
-        Session().add(notification)
-        return notification
-
-    @property
-    def description(self):
-        from kallithea.model.notification import NotificationModel
-        return NotificationModel().make_description(self)
-
-
-class UserNotification(Base, BaseModel):
-    __tablename__ = 'user_to_notification'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'notification_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
-    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
-    read = Column('read', Boolean, default=False)
-    sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
-
-    user = relationship('User', lazy="joined")
-    notification = relationship('Notification', lazy="joined",
-                                order_by=lambda: Notification.created_on.desc(),)
-
-    def mark_as_read(self):
-        self.read = True
-        Session().add(self)
-
-
-class Gist(Base, BaseModel):
-    __tablename__ = 'gists'
-    __table_args__ = (
-        Index('g_gist_access_id_idx', 'gist_access_id'),
-        Index('g_created_on_idx', 'created_on'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    GIST_PUBLIC = u'public'
-    GIST_PRIVATE = u'private'
-
-    gist_id = Column('gist_id', Integer(), primary_key=True)
-    gist_access_id = Column('gist_access_id', Unicode(250))
-    gist_description = Column('gist_description', UnicodeText(1024))
-    gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
-    gist_expires = Column('gist_expires', Float(53), nullable=False)
-    gist_type = Column('gist_type', Unicode(128), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    owner = relationship('User')
-
-    @classmethod
-    def get_or_404(cls, id_):
-        res = cls.query().filter(cls.gist_access_id == id_).scalar()
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def get_by_access_id(cls, gist_access_id):
-        return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
-
-    def gist_url(self):
-        import kallithea
-        alias_url = kallithea.CONFIG.get('gist_alias_url')
-        if alias_url:
-            return alias_url.replace('{gistid}', self.gist_access_id)
-
-        import kallithea.lib.helpers as h
-        return h.canonical_url('gist', gist_id=self.gist_access_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all gists are stored
-
-        :param cls:
-        """
-        from kallithea.model.gist import GIST_STORE_LOC
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == URL_SEP)
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return os.path.join(q.one().ui_value, GIST_STORE_LOC)
-
-    def get_api_data(self):
-        """
-        Common function for generating gist related data for API
-        """
-        gist = self
-        data = dict(
-            gist_id=gist.gist_id,
-            type=gist.gist_type,
-            access_id=gist.gist_access_id,
-            description=gist.gist_description,
-            url=gist.gist_url(),
-            expires=gist.gist_expires,
-            created_on=gist.created_on,
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-        )
-        data.update(self.get_api_data())
-        return data
-    ## SCM functions
-
-    @property
-    def scm_instance(self):
-        from kallithea.lib.vcs import get_repo
-        base_path = self.base_path()
-        return get_repo(os.path.join(*map(safe_str,
-                                          [base_path, self.gist_access_id])))
-
-
-class DbMigrateVersion(Base, BaseModel):
-    __tablename__ = 'db_migrate_version'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    repository_id = Column('repository_id', String(250), primary_key=True)
-    repository_path = Column('repository_path', Text)
-    version = Column('version', Integer)
--- a/kallithea/lib/dbmigrate/schema/db_2_2_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,2448 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate.schema.db_2_2_0
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Database Models for Kallithea
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Apr 08, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-import os
-import time
-import logging
-import datetime
-import traceback
-import hashlib
-import collections
-import functools
-
-from sqlalchemy import *
-from sqlalchemy.ext.hybrid import hybrid_property
-from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
-from beaker.cache import cache_region, region_invalidate
-from webob.exc import HTTPNotFound
-
-from pylons.i18n.translation import lazy_ugettext as _
-
-from kallithea.lib.vcs import get_backend
-from kallithea.lib.vcs.utils.helpers import get_scm
-from kallithea.lib.vcs.exceptions import VCSError
-from kallithea.lib.vcs.utils.lazy import LazyProperty
-from kallithea.lib.vcs.backends.base import EmptyChangeset
-
-from kallithea.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
-    safe_unicode, remove_prefix, time_to_datetime, aslist, Optional, safe_int, \
-    get_clone_url
-from kallithea.lib.compat import json
-from kallithea.lib.caching_query import FromCache
-
-from kallithea.model.meta import Base, Session
-
-URL_SEP = '/'
-log = logging.getLogger(__name__)
-
-from kallithea import DB_PREFIX
-
-#==============================================================================
-# BASE CLASSES
-#==============================================================================
-
-_hash_key = lambda k: hashlib.md5(safe_str(k)).hexdigest()
-
-
-class BaseModel(object):
-    """
-    Base Model for all classess
-    """
-
-    @classmethod
-    def _get_keys(cls):
-        """return column names for this model """
-        return class_mapper(cls).c.keys()
-
-    def get_dict(self):
-        """
-        return dict with keys and values corresponding
-        to this model data """
-
-        d = {}
-        for k in self._get_keys():
-            d[k] = getattr(self, k)
-
-        # also use __json__() if present to get additional fields
-        _json_attr = getattr(self, '__json__', None)
-        if _json_attr:
-            # update with attributes from __json__
-            if callable(_json_attr):
-                _json_attr = _json_attr()
-            for k, val in _json_attr.iteritems():
-                d[k] = val
-        return d
-
-    def get_appstruct(self):
-        """return list with keys and values tuples corresponding
-        to this model data """
-
-        l = []
-        for k in self._get_keys():
-            l.append((k, getattr(self, k),))
-        return l
-
-    def populate_obj(self, populate_dict):
-        """populate model with data from given populate_dict"""
-
-        for k in self._get_keys():
-            if k in populate_dict:
-                setattr(self, k, populate_dict[k])
-
-    @classmethod
-    def query(cls):
-        return Session().query(cls)
-
-    @classmethod
-    def get(cls, id_):
-        if id_:
-            return cls.query().get(id_)
-
-    @classmethod
-    def get_or_404(cls, id_):
-        try:
-            id_ = int(id_)
-        except (TypeError, ValueError):
-            raise HTTPNotFound
-
-        res = cls.query().get(id_)
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def getAll(cls):
-        # deprecated and left for backward compatibility
-        return cls.get_all()
-
-    @classmethod
-    def get_all(cls):
-        return cls.query().all()
-
-    @classmethod
-    def delete(cls, id_):
-        obj = cls.query().get(id_)
-        Session().delete(obj)
-
-    def __repr__(self):
-        if hasattr(self, '__unicode__'):
-            # python repr needs to return str
-            try:
-                return safe_str(self.__unicode__())
-            except UnicodeDecodeError:
-                pass
-        return '<DB:%s>' % (self.__class__.__name__)
-
-
-class Setting(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'settings'
-    __table_args__ = (
-        UniqueConstraint('app_settings_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    SETTINGS_TYPES = {
-        'str': safe_str,
-        'int': safe_int,
-        'unicode': safe_unicode,
-        'bool': str2bool,
-        'list': functools.partial(aslist, sep=',')
-    }
-    DEFAULT_UPDATE_URL = ''
-
-    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    app_settings_name = Column("app_settings_name", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    _app_settings_value = Column("app_settings_value", String(4096, convert_unicode=False), nullable=True, unique=None, default=None)
-    _app_settings_type = Column("app_settings_type", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-
-    def __init__(self, key='', val='', type='unicode'):
-        self.app_settings_name = key
-        self.app_settings_value = val
-        self.app_settings_type = type
-
-    @validates('_app_settings_value')
-    def validate_settings_value(self, key, val):
-        assert type(val) == unicode
-        return val
-
-    @hybrid_property
-    def app_settings_value(self):
-        v = self._app_settings_value
-        _type = self.app_settings_type
-        converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
-        return converter(v)
-
-    @app_settings_value.setter
-    def app_settings_value(self, val):
-        """
-        Setter that will always make sure we use unicode in app_settings_value
-
-        :param val:
-        """
-        self._app_settings_value = safe_unicode(val)
-
-    @hybrid_property
-    def app_settings_type(self):
-        return self._app_settings_type
-
-    @app_settings_type.setter
-    def app_settings_type(self, val):
-        if val not in self.SETTINGS_TYPES:
-            raise Exception('type must be one of %s got %s'
-                            % (self.SETTINGS_TYPES.keys(), val))
-        self._app_settings_type = val
-
-    def __unicode__(self):
-        return u"<%s('%s:%s[%s]')>" % (
-            self.__class__.__name__,
-            self.app_settings_name, self.app_settings_value, self.app_settings_type
-        )
-
-    @classmethod
-    def get_by_name(cls, key):
-        return cls.query()\
-            .filter(cls.app_settings_name == key).scalar()
-
-    @classmethod
-    def get_by_name_or_create(cls, key, val='', type='unicode'):
-        res = cls.get_by_name(key)
-        if not res:
-            res = cls(key, val, type)
-        return res
-
-    @classmethod
-    def create_or_update(cls, key, val=Optional(''), type=Optional('unicode')):
-        """
-        Creates or updates Kallithea setting. If updates is triggered it will only
-        update parameters that are explicityl set Optional instance will be skipped
-
-        :param key:
-        :param val:
-        :param type:
-        :return:
-        """
-        res = cls.get_by_name(key)
-        if not res:
-            val = Optional.extract(val)
-            type = Optional.extract(type)
-            res = cls(key, val, type)
-        else:
-            res.app_settings_name = key
-            if not isinstance(val, Optional):
-                # update if set
-                res.app_settings_value = val
-            if not isinstance(type, Optional):
-                # update if set
-                res.app_settings_type = type
-        return res
-
-    @classmethod
-    def get_app_settings(cls, cache=False):
-
-        ret = cls.query()
-
-        if cache:
-            ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
-
-        if not ret:
-            raise Exception('Could not get application settings !')
-        settings = {}
-        for each in ret:
-            settings[each.app_settings_name] = \
-                each.app_settings_value
-
-        return settings
-
-    @classmethod
-    def get_auth_plugins(cls, cache=False):
-        auth_plugins = cls.get_by_name("auth_plugins").app_settings_value
-        return auth_plugins
-
-    @classmethod
-    def get_auth_settings(cls, cache=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('auth_')).all()
-        fd = {}
-        for row in ret:
-            fd.update({row.app_settings_name: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_default_repo_settings(cls, cache=False, strip_prefix=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('default_')).all()
-        fd = {}
-        for row in ret:
-            key = row.app_settings_name
-            if strip_prefix:
-                key = remove_prefix(key, prefix='default_')
-            fd.update({key: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_server_info(cls):
-        import pkg_resources
-        import platform
-        import kallithea
-        from kallithea.lib.utils import check_git_version
-        mods = [(p.project_name, p.version) for p in pkg_resources.working_set]
-        info = {
-            'modules': sorted(mods, key=lambda k: k[0].lower()),
-            'py_version': platform.python_version(),
-            'platform': safe_unicode(platform.platform()),
-            'kallithea_version': kallithea.__version__,
-            'git_version': safe_unicode(check_git_version()),
-            'git_path': kallithea.CONFIG.get('git_path')
-        }
-        return info
-
-
-class Ui(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'ui'
-    __table_args__ = (
-        UniqueConstraint('ui_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    HOOK_UPDATE = 'changegroup.update'
-    HOOK_REPO_SIZE = 'changegroup.repo_size'
-    HOOK_PUSH = 'changegroup.push_logger'
-    HOOK_PRE_PUSH = 'prechangegroup.pre_push'
-    HOOK_PULL = 'outgoing.pull_logger'
-    HOOK_PRE_PULL = 'preoutgoing.pre_pull'
-
-    ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    ui_section = Column("ui_section", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    ui_key = Column("ui_key", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    ui_value = Column("ui_value", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
-
-    # def __init__(self, section='', key='', value=''):
-    #     self.ui_section = section
-    #     self.ui_key = key
-    #     self.ui_value = value
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.ui_key == key).scalar()
-
-    @classmethod
-    def get_builtin_hooks(cls):
-        q = cls.query()
-        q = q.filter(cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                     cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                     cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        return q.all()
-
-    @classmethod
-    def get_custom_hooks(cls):
-        q = cls.query()
-        q = q.filter(~cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                      cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                      cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        q = q.filter(cls.ui_section == 'hooks')
-        return q.all()
-
-    @classmethod
-    def get_repos_location(cls):
-        return cls.get_by_key('/').ui_value
-
-    @classmethod
-    def create_or_update_hook(cls, key, val):
-        new_ui = cls.get_by_key(key) or cls()
-        new_ui.ui_section = 'hooks'
-        new_ui.ui_active = True
-        new_ui.ui_key = key
-        new_ui.ui_value = val
-
-        Session().add(new_ui)
-
-    def __repr__(self):
-        return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
-                                    self.ui_key, self.ui_value)
-
-
-class User(Base, BaseModel):
-    __tablename__ = 'users'
-    __table_args__ = (
-        UniqueConstraint('username'), UniqueConstraint('email'),
-        Index('u_username_idx', 'username'),
-        Index('u_email_idx', 'email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    DEFAULT_USER = 'default'
-    DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
-
-    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    username = Column("username", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    password = Column("password", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
-    name = Column("firstname", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    lastname = Column("lastname", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
-    extern_type = Column("extern_type", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    extern_name = Column("extern_name", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    api_key = Column("api_key", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    #_user_data = Column("user_data", LargeBinary(), nullable=True)  # JSON data
-
-    user_log = relationship('UserLog')
-    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
-
-    repositories = relationship('Repository')
-    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
-    followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
-
-    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
-
-    group_member = relationship('UserGroupMember', cascade='all')
-
-    notifications = relationship('UserNotification', cascade='all')
-    # notifications assigned to this user
-    user_created_notifications = relationship('Notification', cascade='all')
-    # comments created by this user
-    user_comments = relationship('ChangesetComment', cascade='all')
-    #extra emails for this user
-    user_emails = relationship('UserEmailMap', cascade='all')
-    #extra API keys
-    user_api_keys = relationship('UserApiKeys', cascade='all')
-
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-    @property
-    def firstname(self):
-        # alias for future
-        return self.name
-
-    @property
-    def emails(self):
-        other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
-        return [self.email] + [x.email for x in other]
-
-    @property
-    def api_keys(self):
-        other = UserApiKeys.query().filter(UserApiKeys.user==self).all()
-        return [self.api_key] + [x.api_key for x in other]
-
-    @property
-    def ip_addresses(self):
-        ret = UserIpMap.query().filter(UserIpMap.user == self).all()
-        return [x.ip_addr for x in ret]
-
-    @property
-    def username_and_name(self):
-        return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
-
-    @property
-    def full_name(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def full_name_or_username(self):
-        return ('%s %s' % (self.firstname, self.lastname)
-                if (self.firstname and self.lastname) else self.username)
-
-    @property
-    def full_contact(self):
-        return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
-
-    @property
-    def short_contact(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def is_admin(self):
-        return self.admin
-
-    @property
-    def AuthUser(self):
-        """
-        Returns instance of AuthUser for this user
-        """
-        from kallithea.lib.auth import AuthUser
-        return AuthUser(user_id=self.user_id, api_key=self.api_key,
-                        username=self.username)
-
-    @hybrid_property
-    def user_data(self):
-        if not self._user_data:
-            return {}
-
-        try:
-            return json.loads(self._user_data)
-        except TypeError:
-            return {}
-
-    @user_data.setter
-    def user_data(self, val):
-        try:
-            self._user_data = json.dumps(val)
-        except Exception:
-            log.error(traceback.format_exc())
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.user_id, self.username)
-
-    @classmethod
-    def get_by_username(cls, username, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.username.ilike(username))
-        else:
-            q = cls.query().filter(cls.username == username)
-
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(username)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get_by_api_key(cls, api_key, cache=False, fallback=True):
-        q = cls.query().filter(cls.api_key == api_key)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_api_key_%s" % api_key))
-        res = q.scalar()
-
-        if fallback and not res:
-            #fallback to additional keys
-            _res = UserApiKeys.query()\
-                .filter(UserApiKeys.api_key == api_key)\
-                .filter(or_(UserApiKeys.expires == -1,
-                            UserApiKeys.expires >= time.time()))\
-                .first()
-            if _res:
-                res = _res.user
-        return res
-
-    @classmethod
-    def get_by_email(cls, email, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.email.ilike(email))
-        else:
-            q = cls.query().filter(cls.email == email)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_email_key_%s" % email))
-
-        ret = q.scalar()
-        if ret is None:
-            q = UserEmailMap.query()
-            # try fetching in alternate email map
-            if case_insensitive:
-                q = q.filter(UserEmailMap.email.ilike(email))
-            else:
-                q = q.filter(UserEmailMap.email == email)
-            q = q.options(joinedload(UserEmailMap.user))
-            if cache:
-                q = q.options(FromCache("sql_cache_short",
-                                        "get_email_map_key_%s" % email))
-            ret = getattr(q.scalar(), 'user', None)
-
-        return ret
-
-    @classmethod
-    def get_from_cs_author(cls, author):
-        """
-        Tries to get User objects out of commit author string
-
-        :param author:
-        """
-        from kallithea.lib.helpers import email, author_name
-        # Valid email in the attribute passed, see if they're in the system
-        _email = email(author)
-        if _email:
-            user = cls.get_by_email(_email, case_insensitive=True)
-            if user:
-                return user
-        # Maybe we can match by username?
-        _author = author_name(author)
-        user = cls.get_by_username(_author, case_insensitive=True)
-        if user:
-            return user
-
-    def update_lastlogin(self):
-        """Update user lastlogin"""
-        self.last_login = datetime.datetime.now()
-        Session().add(self)
-        log.debug('updated user %s lastlogin', self.username)
-
-    @classmethod
-    def get_first_admin(cls):
-        user = User.query().filter(User.admin == True).first()
-        if user is None:
-            raise Exception('Missing administrative account!')
-        return user
-
-    @classmethod
-    def get_default_user(cls, cache=False):
-        user = User.get_by_username(User.DEFAULT_USER, cache=cache)
-        if user is None:
-            raise Exception('Missing default account!')
-        return user
-
-    def get_api_data(self):
-        """
-        Common function for generating user related data for API
-        """
-        user = self
-        data = dict(
-            user_id=user.user_id,
-            username=user.username,
-            firstname=user.name,
-            lastname=user.lastname,
-            email=user.email,
-            emails=user.emails,
-            api_key=user.api_key,
-            api_keys=user.api_keys,
-            active=user.active,
-            admin=user.admin,
-            extern_type=user.extern_type,
-            extern_name=user.extern_name,
-            last_login=user.last_login,
-            ip_addresses=user.ip_addresses
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-            full_name=self.full_name,
-            full_name_or_username=self.full_name_or_username,
-            short_contact=self.short_contact,
-            full_contact=self.full_contact
-        )
-        data.update(self.get_api_data())
-        return data
-
-
-class UserApiKeys(Base, BaseModel):
-    __tablename__ = 'user_api_keys'
-    __table_args__ = (
-        Index('uak_api_key_idx', 'api_key'),
-        Index('uak_api_key_expires_idx', 'api_key', 'expires'),
-        UniqueConstraint('api_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    api_key = Column("api_key", String(255, convert_unicode=False), nullable=False, unique=True)
-    description = Column('description', UnicodeText(1024))
-    expires = Column('expires', Float(53), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    user = relationship('User', lazy='joined')
-
-    @property
-    def expired(self):
-        if self.expires == -1:
-            return False
-        return time.time() > self.expires
-
-
-class UserEmailMap(Base, BaseModel):
-    __tablename__ = 'user_email_map'
-    __table_args__ = (
-        Index('uem_email_idx', 'email'),
-        UniqueConstraint('email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False), nullable=True, unique=False, default=None)
-    user = relationship('User', lazy='joined')
-
-    @validates('_email')
-    def validate_email(self, key, email):
-        # check if this email is not main one
-        main_email = Session().query(User).filter(User.email == email).scalar()
-        if main_email is not None:
-            raise AttributeError('email %s is present is user table' % email)
-        return email
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-
-class UserIpMap(Base, BaseModel):
-    __tablename__ = 'user_ip_map'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'ip_addr'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    ip_addr = Column("ip_addr", String(255, convert_unicode=False), nullable=True, unique=False, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    user = relationship('User', lazy='joined')
-
-    @classmethod
-    def _get_ip_range(cls, ip_addr):
-        from kallithea.lib import ipaddr
-        net = ipaddr.IPNetwork(address=ip_addr)
-        return [str(net.network), str(net.broadcast)]
-
-    def __json__(self):
-        return dict(
-          ip_addr=self.ip_addr,
-          ip_range=self._get_ip_range(self.ip_addr)
-        )
-
-    def __unicode__(self):
-        return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
-                                            self.user_id, self.ip_addr)
-
-class UserLog(Base, BaseModel):
-    __tablename__ = 'user_logs'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    username = Column("username", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
-    repository_name = Column("repository_name", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    user_ip = Column("user_ip", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    action = Column("action", UnicodeText(1200000, convert_unicode=False), nullable=True, unique=None, default=None)
-    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.repository_name,
-                                      self.action)
-
-    @property
-    def action_as_day(self):
-        return datetime.date(*self.action_date.timetuple()[:3])
-
-    user = relationship('User')
-    repository = relationship('Repository', cascade='')
-
-
-class UserGroup(Base, BaseModel):
-    __tablename__ = 'users_groups'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_name = Column("users_group_name", String(255, convert_unicode=False), nullable=False, unique=True, default=None)
-    user_group_description = Column("user_group_description", String(10000, convert_unicode=False), nullable=True, unique=None, default=None)
-    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
-    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
-    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-    user_user_group_to_perm = relationship('UserUserGroupToPerm ', cascade='all')
-    user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
-
-    user = relationship('User')
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.users_group_id,
-                                      self.users_group_name)
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False,
-                          case_insensitive=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.users_group_name.ilike(group_name))
-        else:
-            q = cls.query().filter(cls.users_group_name == group_name)
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(group_name)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get(cls, user_group_id, cache=False):
-        user_group = cls.query()
-        if cache:
-            user_group = user_group.options(FromCache("sql_cache_short",
-                                    "get_users_group_%s" % user_group_id))
-        return user_group.get(user_group_id)
-
-    def get_api_data(self, with_members=True):
-        user_group = self
-
-        data = dict(
-            users_group_id=user_group.users_group_id,
-            group_name=user_group.users_group_name,
-            group_description=user_group.user_group_description,
-            active=user_group.users_group_active,
-            owner=user_group.user.username,
-        )
-        if with_members:
-            members = []
-            for user in user_group.members:
-                user = user.user
-                members.append(user.get_api_data())
-            data['members'] = members
-
-        return data
-
-
-class UserGroupMember(Base, BaseModel):
-    __tablename__ = 'users_groups_members'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User', lazy='joined')
-    users_group = relationship('UserGroup')
-
-    def __init__(self, gr_id='', u_id=''):
-        self.users_group_id = gr_id
-        self.user_id = u_id
-
-
-class RepositoryField(Base, BaseModel):
-    __tablename__ = 'repositories_fields'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'field_key'),  # no-multi field
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    PREFIX = 'ex_'  # prefix used in form to not conflict with already existing fields
-
-    repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-    field_key = Column("field_key", String(250, convert_unicode=False))
-    field_label = Column("field_label", String(1024, convert_unicode=False), nullable=False)
-    field_value = Column("field_value", String(10000, convert_unicode=False), nullable=False)
-    field_desc = Column("field_desc", String(1024, convert_unicode=False), nullable=False)
-    field_type = Column("field_type", String(256), nullable=False, unique=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    repository = relationship('Repository')
-
-    @property
-    def field_key_prefixed(self):
-        return 'ex_%s' % self.field_key
-
-    @classmethod
-    def un_prefix_key(cls, key):
-        if key.startswith(cls.PREFIX):
-            return key[len(cls.PREFIX):]
-        return key
-
-    @classmethod
-    def get_by_key_name(cls, key, repo):
-        row = cls.query()\
-                .filter(cls.repository == repo)\
-                .filter(cls.field_key == key).scalar()
-        return row
-
-
-class Repository(Base, BaseModel):
-    __tablename__ = 'repositories'
-    __table_args__ = (
-        UniqueConstraint('repo_name'),
-        Index('r_repo_name_idx', 'repo_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
-    DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
-
-    STATE_CREATED = 'repo_state_created'
-    STATE_PENDING = 'repo_state_pending'
-    STATE_ERROR = 'repo_state_error'
-
-    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repo_name = Column("repo_name", String(255, convert_unicode=False), nullable=False, unique=True, default=None)
-    clone_uri = Column("clone_uri", String(255, convert_unicode=False), nullable=True, unique=False, default=None)
-    repo_type = Column("repo_type", String(255, convert_unicode=False), nullable=False, unique=False, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
-    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
-    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
-    description = Column("description", String(10000, convert_unicode=False), nullable=True, unique=None, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    _landing_revision = Column("landing_revision", String(255, convert_unicode=False), nullable=False, unique=False, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    _locked = Column("locked", String(255, convert_unicode=False), nullable=True, unique=False, default=None)
-    _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) #JSON data
-
-    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
-
-    user = relationship('User')
-    fork = relationship('Repository', remote_side=repo_id)
-    group = relationship('RepoGroup')
-    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    stats = relationship('Statistics', cascade='all', uselist=False)
-
-    followers = relationship('UserFollowing',
-                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
-                             cascade='all')
-    extra_fields = relationship('RepositoryField',
-                                cascade="all, delete, delete-orphan")
-
-    logs = relationship('UserLog')
-    comments = relationship('ChangesetComment', cascade="all, delete, delete-orphan")
-
-    pull_requests_org = relationship('PullRequest',
-                    primaryjoin='PullRequest.org_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    pull_requests_other = relationship('PullRequest',
-                    primaryjoin='PullRequest.other_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
-                                   safe_unicode(self.repo_name))
-
-    @hybrid_property
-    def landing_rev(self):
-        # always should return [rev_type, rev]
-        if self._landing_revision:
-            _rev_info = self._landing_revision.split(':')
-            if len(_rev_info) < 2:
-                _rev_info.insert(0, 'rev')
-            return [_rev_info[0], _rev_info[1]]
-        return [None, None]
-
-    @landing_rev.setter
-    def landing_rev(self, val):
-        if ':' not in val:
-            raise ValueError('value must be delimited with `:` and consist '
-                             'of <rev_type>:<rev>, got %s instead' % val)
-        self._landing_revision = val
-
-    @hybrid_property
-    def locked(self):
-        # always should return [user_id, timelocked]
-        if self._locked:
-            _lock_info = self._locked.split(':')
-            return int(_lock_info[0]), _lock_info[1]
-        return [None, None]
-
-    @locked.setter
-    def locked(self, val):
-        if val and isinstance(val, (list, tuple)):
-            self._locked = ':'.join(map(str, val))
-        else:
-            self._locked = None
-
-    @hybrid_property
-    def changeset_cache(self):
-        from kallithea.lib.vcs.backends.base import EmptyChangeset
-        dummy = EmptyChangeset().__json__()
-        if not self._changeset_cache:
-            return dummy
-        try:
-            return json.loads(self._changeset_cache)
-        except TypeError:
-            return dummy
-
-    @changeset_cache.setter
-    def changeset_cache(self, val):
-        try:
-            self._changeset_cache = json.dumps(val)
-        except Exception:
-            log.error(traceback.format_exc())
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def normalize_repo_name(cls, repo_name):
-        """
-        Normalizes os specific repo_name to the format internally stored inside
-        dabatabase using URL_SEP
-
-        :param cls:
-        :param repo_name:
-        """
-        return cls.url_sep().join(repo_name.split(os.sep))
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        q = Session().query(cls).filter(cls.repo_name == repo_name)
-        q = q.options(joinedload(Repository.fork))\
-                .options(joinedload(Repository.user))\
-                .options(joinedload(Repository.group))
-        return q.scalar()
-
-    @classmethod
-    def get_by_full_path(cls, repo_full_path):
-        repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
-        repo_name = cls.normalize_repo_name(repo_name)
-        return cls.get_by_repo_name(repo_name.strip(URL_SEP))
-
-    @classmethod
-    def get_repo_forks(cls, repo_id):
-        return cls.query().filter(Repository.fork_id == repo_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all repos are stored
-
-        :param cls:
-        """
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == cls.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def forks(self):
-        """
-        Return forks of this repo
-        """
-        return Repository.get_repo_forks(self.repo_id)
-
-    @property
-    def parent(self):
-        """
-        Returns fork parent
-        """
-        return self.fork
-
-    @property
-    def just_name(self):
-        return self.repo_name.split(Repository.url_sep())[-1]
-
-    @property
-    def groups_with_parents(self):
-        groups = []
-        if self.group is None:
-            return groups
-
-        cur_gr = self.group
-        groups.insert(0, cur_gr)
-        while 1:
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            groups.insert(0, gr)
-
-        return groups
-
-    @property
-    def groups_and_repo(self):
-        return self.groups_with_parents, self.just_name, self.repo_name
-
-    @LazyProperty
-    def repo_path(self):
-        """
-        Returns base full path for that repository means where it actually
-        exists on a filesystem
-        """
-        q = Session().query(Ui).filter(Ui.ui_key ==
-                                              Repository.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def repo_full_path(self):
-        p = [self.repo_path]
-        # we need to split the name by / since this is how we store the
-        # names in the database, but that eventually needs to be converted
-        # into a valid system path
-        p += self.repo_name.split(Repository.url_sep())
-        return os.path.join(*map(safe_unicode, p))
-
-    @property
-    def cache_keys(self):
-        """
-        Returns associated cache keys for that repo
-        """
-        return CacheInvalidation.query()\
-            .filter(CacheInvalidation.cache_args == self.repo_name)\
-            .order_by(CacheInvalidation.cache_key)\
-            .all()
-
-    def get_new_name(self, repo_name):
-        """
-        returns new full repository name based on assigned group and new new
-
-        :param group_name:
-        """
-        path_prefix = self.group.full_path_splitted if self.group else []
-        return Repository.url_sep().join(path_prefix + [repo_name])
-
-    @property
-    def _ui(self):
-        """
-        Creates an db based ui object for this repository
-        """
-        from kallithea.lib.utils import make_ui
-        return make_ui('db', clear_session=False)
-
-    @classmethod
-    def is_valid(cls, repo_name):
-        """
-        returns True if given repo name is a valid filesystem repository
-
-        :param cls:
-        :param repo_name:
-        """
-        from kallithea.lib.utils import is_valid_repo
-
-        return is_valid_repo(repo_name, cls.base_path())
-
-    def get_api_data(self):
-        """
-        Common function for generating repo api data
-
-        """
-        repo = self
-        data = dict(
-            repo_id=repo.repo_id,
-            repo_name=repo.repo_name,
-            repo_type=repo.repo_type,
-            clone_uri=repo.clone_uri,
-            private=repo.private,
-            created_on=repo.created_on,
-            description=repo.description,
-            landing_rev=repo.landing_rev,
-            owner=repo.user.username,
-            fork_of=repo.fork.repo_name if repo.fork else None,
-            enable_statistics=repo.enable_statistics,
-            enable_locking=repo.enable_locking,
-            enable_downloads=repo.enable_downloads,
-            last_changeset=repo.changeset_cache,
-            locked_by=User.get(self.locked[0]).get_api_data() \
-                if self.locked[0] else None,
-            locked_date=time_to_datetime(self.locked[1]) \
-                if self.locked[1] else None
-        )
-        rc_config = Setting.get_app_settings()
-        repository_fields = str2bool(rc_config.get('repository_fields'))
-        if repository_fields:
-            for f in self.extra_fields:
-                data[f.field_key_prefixed] = f.field_value
-
-        return data
-
-    @classmethod
-    def lock(cls, repo, user_id, lock_time=None):
-        if not lock_time:
-            lock_time = time.time()
-        repo.locked = [user_id, lock_time]
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def unlock(cls, repo):
-        repo.locked = None
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def getlock(cls, repo):
-        return repo.locked
-
-    @property
-    def last_db_change(self):
-        return self.updated_on
-
-    def clone_url(self, **override):
-        import kallithea.lib.helpers as h
-        qualified_home_url = h.canonical_url('home')
-
-        uri_tmpl = None
-        if 'uri_tmpl' in override:
-            uri_tmpl = override['uri_tmpl']
-            del override['uri_tmpl']
-
-        # we didn't override our tmpl from **overrides
-        if not uri_tmpl:
-            uri_tmpl = self.DEFAULT_CLONE_URI
-            try:
-                from pylons import tmpl_context as c
-                uri_tmpl = c.clone_uri_tmpl
-            except Exception:
-                # in any case if we call this outside of request context,
-                # ie, not having tmpl_context set up
-                pass
-
-        return get_clone_url(uri_tmpl=uri_tmpl,
-                             qualified_home_url=qualified_home_url,
-                             repo_name=self.repo_name,
-                             repo_id=self.repo_id, **override)
-
-    #==========================================================================
-    # SCM PROPERTIES
-    #==========================================================================
-
-    def get_changeset(self, rev=None):
-        return get_changeset_safe(self.scm_instance, rev)
-
-    def get_landing_changeset(self):
-        """
-        Returns landing changeset, or if that doesn't exist returns the tip
-        """
-        _rev_type, _rev = self.landing_rev
-        cs = self.get_changeset(_rev)
-        if isinstance(cs, EmptyChangeset):
-            return self.get_changeset()
-        return cs
-
-    def update_changeset_cache(self, cs_cache=None):
-        """
-        Update cache of last changeset for repository, keys should be::
-
-            short_id
-            raw_id
-            revision
-            message
-            date
-            author
-
-        :param cs_cache:
-        """
-        from kallithea.lib.vcs.backends.base import BaseChangeset
-        if cs_cache is None:
-            cs_cache = EmptyChangeset()
-            # use no-cache version here
-            scm_repo = self.scm_instance_no_cache()
-            if scm_repo:
-                cs_cache = scm_repo.get_changeset()
-
-        if isinstance(cs_cache, BaseChangeset):
-            cs_cache = cs_cache.__json__()
-
-        if (cs_cache != self.changeset_cache or not self.changeset_cache):
-            _default = datetime.datetime.fromtimestamp(0)
-            last_change = cs_cache.get('date') or _default
-            log.debug('updated repo %s with new cs cache %s',
-                      self.repo_name, cs_cache)
-            self.updated_on = last_change
-            self.changeset_cache = cs_cache
-            Session().add(self)
-            Session().commit()
-        else:
-            log.debug('Skipping repo:%s already with latest changes',
-                      self.repo_name)
-
-    @property
-    def tip(self):
-        return self.get_changeset('tip')
-
-    @property
-    def author(self):
-        return self.tip.author
-
-    @property
-    def last_change(self):
-        return self.scm_instance.last_change
-
-    def get_comments(self, revisions=None):
-        """
-        Returns comments for this repository grouped by revisions
-
-        :param revisions: filter query by revisions only
-        """
-        cmts = ChangesetComment.query()\
-            .filter(ChangesetComment.repo == self)
-        if revisions:
-            cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
-        grouped = collections.defaultdict(list)
-        for cmt in cmts.all():
-            grouped[cmt.revision].append(cmt)
-        return grouped
-
-    def statuses(self, revisions=None):
-        """
-        Returns statuses for this repository
-
-        :param revisions: list of revisions to get statuses for
-        """
-
-        statuses = ChangesetStatus.query()\
-            .filter(ChangesetStatus.repo == self)\
-            .filter(ChangesetStatus.version == 0)
-        if revisions:
-            statuses = statuses.filter(ChangesetStatus.revision.in_(revisions))
-        grouped = {}
-
-        #maybe we have open new pullrequest without a status ?
-        stat = ChangesetStatus.STATUS_UNDER_REVIEW
-        status_lbl = ChangesetStatus.get_status_lbl(stat)
-        for pr in PullRequest.query().filter(PullRequest.org_repo == self).all():
-            for rev in pr.revisions:
-                pr_id = pr.pull_request_id
-                pr_repo = pr.other_repo.repo_name
-                grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
-
-        for stat in statuses.all():
-            pr_id = pr_repo = None
-            if stat.pull_request:
-                pr_id = stat.pull_request.pull_request_id
-                pr_repo = stat.pull_request.other_repo.repo_name
-            grouped[stat.revision] = [str(stat.status), stat.status_lbl,
-                                      pr_id, pr_repo]
-        return grouped
-
-    def _repo_size(self):
-        from kallithea.lib import helpers as h
-        log.debug('calculating repository size...')
-        return h.format_byte_size(self.scm_instance.size)
-
-    #==========================================================================
-    # SCM CACHE INSTANCE
-    #==========================================================================
-
-    def set_invalidate(self):
-        """
-        Mark caches of this repo as invalid.
-        """
-        CacheInvalidation.set_invalidate(self.repo_name)
-
-    def scm_instance_no_cache(self):
-        return self.__get_instance()
-
-    @property
-    def scm_instance(self):
-        import kallithea
-        full_cache = str2bool(kallithea.CONFIG.get('vcs_full_cache'))
-        if full_cache:
-            return self.scm_instance_cached()
-        return self.__get_instance()
-
-    def scm_instance_cached(self, valid_cache_keys=None):
-        @cache_region('long_term')
-        def _c(repo_name):
-            return self.__get_instance()
-        rn = self.repo_name
-
-        valid = CacheInvalidation.test_and_set_valid(rn, None, valid_cache_keys=valid_cache_keys)
-        if not valid:
-            log.debug('Cache for %s invalidated, getting new object', rn)
-            region_invalidate(_c, None, rn)
-        else:
-            log.debug('Getting obj for %s from cache', rn)
-        return _c(rn)
-
-    def __get_instance(self):
-        repo_full_path = self.repo_full_path
-        try:
-            alias = get_scm(repo_full_path)[0]
-            log.debug('Creating instance of %s repository from %s',
-                      alias, repo_full_path)
-            backend = get_backend(alias)
-        except VCSError:
-            log.error(traceback.format_exc())
-            log.error('Perhaps this repository is in db and not in '
-                      'filesystem run rescan repositories with '
-                      '"destroy old data " option from admin panel')
-            return
-
-        if alias == 'hg':
-
-            repo = backend(safe_str(repo_full_path), create=False,
-                           baseui=self._ui)
-        else:
-            repo = backend(repo_full_path, create=False)
-
-        return repo
-
-    def __json__(self):
-        return dict(landing_rev = self.landing_rev)
-
-class RepoGroup(Base, BaseModel):
-    __tablename__ = 'groups'
-    __table_args__ = (
-        UniqueConstraint('group_name', 'group_parent_id'),
-        CheckConstraint('group_id != group_parent_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    __mapper_args__ = {'order_by': 'group_name'}
-
-    SEP = ' &raquo; '
-
-    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    group_name = Column("group_name", String(255, convert_unicode=False), nullable=False, unique=True, default=None)
-    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
-    group_description = Column("group_description", String(10000, convert_unicode=False), nullable=True, unique=None, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-    parent_group = relationship('RepoGroup', remote_side=group_id)
-    user = relationship('User')
-
-    def __init__(self, group_name='', parent_group=None):
-        self.group_name = group_name
-        self.parent_group = parent_group
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
-                                      self.group_name)
-
-    @classmethod
-    def _generate_choice(cls, repo_group):
-        from webhelpers.html import literal as _literal
-        _name = lambda k: _literal(cls.SEP.join(k))
-        return repo_group.group_id, _name(repo_group.full_path_splitted)
-
-    @classmethod
-    def groups_choices(cls, groups=None, show_empty_group=True):
-        if not groups:
-            groups = cls.query().all()
-
-        repo_groups = []
-        if show_empty_group:
-            repo_groups = [('-1', u'-- %s --' % _('top level'))]
-
-        repo_groups.extend([cls._generate_choice(x) for x in groups])
-
-        repo_groups = sorted(repo_groups, key=lambda t: t[1].split(cls.SEP)[0])
-        return repo_groups
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
-        if case_insensitive:
-            gr = cls.query()\
-                .filter(cls.group_name.ilike(group_name))
-        else:
-            gr = cls.query()\
-                .filter(cls.group_name == group_name)
-        if cache:
-            gr = gr.options(FromCache(
-                            "sql_cache_short",
-                            "get_group_%s" % _hash_key(group_name)
-                            )
-            )
-        return gr.scalar()
-
-    @property
-    def parents(self):
-        parents_recursion_limit = 5
-        groups = []
-        if self.parent_group is None:
-            return groups
-        cur_gr = self.parent_group
-        groups.insert(0, cur_gr)
-        cnt = 0
-        while 1:
-            cnt += 1
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            if cnt == parents_recursion_limit:
-                # this will prevent accidental infinite loops
-                log.error('group nested more than %s',
-                          parents_recursion_limit)
-                break
-
-            groups.insert(0, gr)
-        return groups
-
-    @property
-    def children(self):
-        return RepoGroup.query().filter(RepoGroup.parent_group == self)
-
-    @property
-    def name(self):
-        return self.group_name.split(RepoGroup.url_sep())[-1]
-
-    @property
-    def full_path(self):
-        return self.group_name
-
-    @property
-    def full_path_splitted(self):
-        return self.group_name.split(RepoGroup.url_sep())
-
-    @property
-    def repositories(self):
-        return Repository.query()\
-                .filter(Repository.group == self)\
-                .order_by(Repository.repo_name)
-
-    @property
-    def repositories_recursive_count(self):
-        cnt = self.repositories.count()
-
-        def children_count(group):
-            cnt = 0
-            for child in group.children:
-                cnt += child.repositories.count()
-                cnt += children_count(child)
-            return cnt
-
-        return cnt + children_count(self)
-
-    def _recursive_objects(self, include_repos=True):
-        all_ = []
-
-        def _get_members(root_gr):
-            if include_repos:
-                for r in root_gr.repositories:
-                    all_.append(r)
-            childs = root_gr.children.all()
-            if childs:
-                for gr in childs:
-                    all_.append(gr)
-                    _get_members(gr)
-
-        _get_members(self)
-        return [self] + all_
-
-    def recursive_groups_and_repos(self):
-        """
-        Recursive return all groups, with repositories in those groups
-        """
-        return self._recursive_objects()
-
-    def recursive_groups(self):
-        """
-        Returns all children groups for this group including children of children
-        """
-        return self._recursive_objects(include_repos=False)
-
-    def get_new_name(self, group_name):
-        """
-        returns new full group name based on parent and new name
-
-        :param group_name:
-        """
-        path_prefix = (self.parent_group.full_path_splitted if
-                       self.parent_group else [])
-        return RepoGroup.url_sep().join(path_prefix + [group_name])
-
-    def get_api_data(self):
-        """
-        Common function for generating api data
-
-        """
-        group = self
-        data = dict(
-            group_id=group.group_id,
-            group_name=group.group_name,
-            group_description=group.group_description,
-            parent_group=group.parent_group.group_name if group.parent_group else None,
-            repositories=[x.repo_name for x in group.repositories],
-            owner=group.user.username
-        )
-        return data
-
-
-class Permission(Base, BaseModel):
-    __tablename__ = 'permissions'
-    __table_args__ = (
-        Index('p_perm_name_idx', 'permission_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    PERMS = [
-        ('hg.admin', _('Kallithea Administrator')),
-
-        ('repository.none', _('Repository no access')),
-        ('repository.read', _('Repository read access')),
-        ('repository.write', _('Repository write access')),
-        ('repository.admin', _('Repository admin access')),
-
-        ('group.none', _('Repository group no access')),
-        ('group.read', _('Repository group read access')),
-        ('group.write', _('Repository group write access')),
-        ('group.admin', _('Repository group admin access')),
-
-        ('usergroup.none', _('User group no access')),
-        ('usergroup.read', _('User group read access')),
-        ('usergroup.write', _('User group write access')),
-        ('usergroup.admin', _('User group admin access')),
-
-        ('hg.repogroup.create.false', _('Repository Group creation disabled')),
-        ('hg.repogroup.create.true', _('Repository Group creation enabled')),
-
-        ('hg.usergroup.create.false', _('User Group creation disabled')),
-        ('hg.usergroup.create.true', _('User Group creation enabled')),
-
-        ('hg.create.none', _('Repository creation disabled')),
-        ('hg.create.repository', _('Repository creation enabled')),
-        ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
-        ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
-
-        ('hg.fork.none', _('Repository forking disabled')),
-        ('hg.fork.repository', _('Repository forking enabled')),
-
-        ('hg.register.none', _('Registration disabled')),
-        ('hg.register.manual_activate', _('User Registration with manual account activation')),
-        ('hg.register.auto_activate', _('User Registration with automatic account activation')),
-
-        ('hg.extern_activate.manual', _('Manual activation of external account')),
-        ('hg.extern_activate.auto', _('Automatic activation of external account')),
-
-    ]
-
-    #definition of system default permissions for DEFAULT user
-    DEFAULT_USER_PERMISSIONS = [
-        'repository.read',
-        'group.read',
-        'usergroup.read',
-        'hg.create.repository',
-        'hg.create.write_on_repogroup.true',
-        'hg.fork.repository',
-        'hg.register.manual_activate',
-        'hg.extern_activate.auto',
-    ]
-
-    # defines which permissions are more important higher the more important
-    # Weight defines which permissions are more important.
-    # The higher number the more important.
-    PERM_WEIGHTS = {
-        'repository.none': 0,
-        'repository.read': 1,
-        'repository.write': 3,
-        'repository.admin': 4,
-
-        'group.none': 0,
-        'group.read': 1,
-        'group.write': 3,
-        'group.admin': 4,
-
-        'usergroup.none': 0,
-        'usergroup.read': 1,
-        'usergroup.write': 3,
-        'usergroup.admin': 4,
-        'hg.repogroup.create.false': 0,
-        'hg.repogroup.create.true': 1,
-
-        'hg.usergroup.create.false': 0,
-        'hg.usergroup.create.true': 1,
-
-        'hg.fork.none': 0,
-        'hg.fork.repository': 1,
-        'hg.create.none': 0,
-        'hg.create.repository': 1
-    }
-
-    permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    permission_name = Column("permission_name", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    permission_longname = Column("permission_longname", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__, self.permission_id, self.permission_name
-        )
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.permission_name == key).scalar()
-
-    @classmethod
-    def get_default_perms(cls, default_user_id):
-        q = Session().query(UserRepoToPerm, Repository, cls)\
-         .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
-         .join((cls, UserRepoToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_group_perms(cls, default_user_id):
-        q = Session().query(UserRepoGroupToPerm, RepoGroup, cls)\
-         .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
-         .join((cls, UserRepoGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_user_group_perms(cls, default_user_id):
-        q = Session().query(UserUserGroupToPerm, UserGroup, cls)\
-         .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
-         .join((cls, UserUserGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserUserGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-
-class UserRepoToPerm(Base, BaseModel):
-    __tablename__ = 'repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'repository_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    repository = relationship('Repository')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, repository, permission):
-        n = cls()
-        n.user = user
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.repository)
-
-
-class UserUserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_user_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    user_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, user_group, permission):
-        n = cls()
-        n.user = user
-        n.user_group = user_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.user_group)
-
-
-class UserToPerm(Base, BaseModel):
-    __tablename__ = 'user_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    permission = relationship('Permission', lazy='joined')
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.permission)
-
-
-class UserGroupRepoToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    repository = relationship('Repository')
-
-    @classmethod
-    def create(cls, users_group, repository, permission):
-        n = cls()
-        n.users_group = users_group
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
-
-
-class UserGroupUserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_group_user_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
-        CheckConstraint('target_user_group_id != user_group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-
-    target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
-    user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, target_user_group, user_group, permission):
-        n = cls()
-        n.target_user_group = target_user_group
-        n.user_group = user_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
-
-
-class UserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'permission_id',),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-
-class UserRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    group = relationship('RepoGroup')
-    permission = relationship('Permission')
-
-
-class UserGroupRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    group = relationship('RepoGroup')
-
-
-class Statistics(Base, BaseModel):
-    __tablename__ = 'statistics'
-    __table_args__ = (
-         UniqueConstraint('repository_id'),
-         {'extend_existing': True, 'mysql_engine': 'InnoDB',
-          'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
-    stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
-    commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
-    commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
-    languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
-
-    repository = relationship('Repository', single_parent=True)
-
-
-class UserFollowing(Base, BaseModel):
-    __tablename__ = 'user_followings'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'follows_repository_id'),
-        UniqueConstraint('user_id', 'follows_user_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-
-    user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
-
-    follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relationship('Repository', order_by='Repository.repo_name')
-
-    @classmethod
-    def get_repo_followers(cls, repo_id):
-        return cls.query().filter(cls.follows_repo_id == repo_id)
-
-
-class CacheInvalidation(Base, BaseModel):
-    __tablename__ = 'cache_invalidation'
-    __table_args__ = (
-        UniqueConstraint('cache_key'),
-        Index('key_idx', 'cache_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    # cache_id, not used
-    cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    # cache_key as created by _get_cache_key
-    cache_key = Column("cache_key", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    # cache_args is a repo_name
-    cache_args = Column("cache_args", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    # instance sets cache_active True when it is caching,
-    # other instances set cache_active to False to indicate that this cache is invalid
-    cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
-
-    def __init__(self, cache_key, repo_name=''):
-        self.cache_key = cache_key
-        self.cache_args = repo_name
-        self.cache_active = False
-
-    def __unicode__(self):
-        return u"<%s('%s:%s[%s]')>" % (self.__class__.__name__,
-                            self.cache_id, self.cache_key, self.cache_active)
-
-    def _cache_key_partition(self):
-        prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
-        return prefix, repo_name, suffix
-
-    def get_prefix(self):
-        """
-        get prefix that might have been used in _get_cache_key to
-        generate self.cache_key. Only used for informational purposes
-        in repo_edit.html.
-        """
-        # prefix, repo_name, suffix
-        return self._cache_key_partition()[0]
-
-    def get_suffix(self):
-        """
-        get suffix that might have been used in _get_cache_key to
-        generate self.cache_key. Only used for informational purposes
-        in repo_edit.html.
-        """
-        # prefix, repo_name, suffix
-        return self._cache_key_partition()[2]
-
-    @classmethod
-    def clear_cache(cls):
-        """
-        Delete all cache keys from database.
-        Should only be run when all instances are down and all entries thus stale.
-        """
-        cls.query().delete()
-        Session().commit()
-
-    @classmethod
-    def _get_cache_key(cls, key):
-        """
-        Wrapper for generating a unique cache key for this instance and "key".
-        key must / will start with a repo_name which will be stored in .cache_args .
-        """
-        import kallithea
-        prefix = kallithea.CONFIG.get('instance_id', '')
-        return "%s%s" % (prefix, key)
-
-    @classmethod
-    def set_invalidate(cls, repo_name, delete=False):
-        """
-        Mark all caches of a repo as invalid in the database.
-        """
-        inv_objs = Session().query(cls).filter(cls.cache_args == repo_name).all()
-        log.debug('for repo %s got %s invalidation objects', repo_name, inv_objs)
-        try:
-            for inv_obj in inv_objs:
-                log.debug('marking %s key for invalidation based on repo_name=%s',
-                          inv_obj, safe_str(repo_name))
-                if delete:
-                    Session().delete(inv_obj)
-                else:
-                    inv_obj.cache_active = False
-                    Session().add(inv_obj)
-            Session().commit()
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-
-    @classmethod
-    def test_and_set_valid(cls, repo_name, kind, valid_cache_keys=None):
-        """
-        Mark this cache key as active and currently cached.
-        Return True if the existing cache registration still was valid.
-        Return False to indicate that it had been invalidated and caches should be refreshed.
-        """
-
-        key = (repo_name + '_' + kind) if kind else repo_name
-        cache_key = cls._get_cache_key(key)
-
-        if valid_cache_keys and cache_key in valid_cache_keys:
-            return True
-
-        try:
-            inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
-            if not inv_obj:
-                inv_obj = CacheInvalidation(cache_key, repo_name)
-            was_valid = inv_obj.cache_active
-            inv_obj.cache_active = True
-            Session().add(inv_obj)
-            Session().commit()
-            return was_valid
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-            return False
-
-    @classmethod
-    def get_valid_cache_keys(cls):
-        """
-        Return opaque object with information of which caches still are valid
-        and can be used without checking for invalidation.
-        """
-        return set(inv_obj.cache_key for inv_obj in cls.query().filter(cls.cache_active).all())
-
-
-class ChangesetComment(Base, BaseModel):
-    __tablename__ = 'changeset_comments'
-    __table_args__ = (
-        Index('cc_revision_idx', 'revision'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    revision = Column('revision', String(40), nullable=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-    line_no = Column('line_no', Unicode(10), nullable=True)
-    hl_lines = Column('hl_lines', Unicode(512), nullable=True)
-    f_path = Column('f_path', Unicode(1000), nullable=True)
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
-    text = Column('text', UnicodeText(25000), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    @classmethod
-    def get_users(cls, revision=None, pull_request_id=None):
-        """
-        Returns user associated with this ChangesetComment. ie those
-        who actually commented
-
-        :param cls:
-        :param revision:
-        """
-        q = Session().query(User)\
-                .join(ChangesetComment.author)
-        if revision:
-            q = q.filter(cls.revision == revision)
-        elif pull_request_id:
-            q = q.filter(cls.pull_request_id == pull_request_id)
-        return q.all()
-
-
-class ChangesetStatus(Base, BaseModel):
-    __tablename__ = 'changeset_statuses'
-    __table_args__ = (
-        Index('cs_revision_idx', 'revision'),
-        Index('cs_version_idx', 'version'),
-        UniqueConstraint('repo_id', 'revision', 'version'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
-    STATUS_APPROVED = 'approved'
-    STATUS_REJECTED = 'rejected'
-    STATUS_UNDER_REVIEW = 'under_review'
-
-    STATUSES = [
-        (STATUS_NOT_REVIEWED, _("Not Reviewed")),  # (no icon) and default
-        (STATUS_APPROVED, _("Approved")),
-        (STATUS_REJECTED, _("Rejected")),
-        (STATUS_UNDER_REVIEW, _("Under Review")),
-    ]
-
-    changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    revision = Column('revision', String(40), nullable=False)
-    status = Column('status', String(128), nullable=False, default=DEFAULT)
-    changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
-    modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
-    version = Column('version', Integer(), nullable=False, default=0)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    comment = relationship('ChangesetComment', lazy='joined')
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.status, self.author
-        )
-
-    @classmethod
-    def get_status_lbl(cls, value):
-        return dict(cls.STATUSES).get(value)
-
-    @property
-    def status_lbl(self):
-        return ChangesetStatus.get_status_lbl(self.status)
-
-
-class PullRequest(Base, BaseModel):
-    __tablename__ = 'pull_requests'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    # values for .status
-    STATUS_NEW = u'new'
-    STATUS_OPEN = u'open'
-    STATUS_CLOSED = u'closed'
-
-    pull_request_id = Column('pull_request_id', Integer(), nullable=False, primary_key=True)
-    title = Column('title', Unicode(256), nullable=True)
-    description = Column('description', UnicodeText(10240), nullable=True)
-    status = Column('status', Unicode(256), nullable=False, default=STATUS_NEW) # only for closedness, not approve/reject/etc
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    _revisions = Column('revisions', UnicodeText(20500))  # 500 revisions max
-    org_repo_id = Column('org_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    org_ref = Column('org_ref', Unicode(256), nullable=False)
-    other_repo_id = Column('other_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    other_ref = Column('other_ref', Unicode(256), nullable=False)
-
-    @hybrid_property
-    def revisions(self):
-        return self._revisions.split(':')
-
-    @revisions.setter
-    def revisions(self, val):
-        self._revisions = ':'.join(val)
-
-    @property
-    def org_ref_parts(self):
-        return self.org_ref.split(':')
-
-    @property
-    def other_ref_parts(self):
-        return self.other_ref.split(':')
-
-    author = relationship('User', lazy='joined')
-    reviewers = relationship('PullRequestReviewers',
-                             cascade="all, delete, delete-orphan")
-    org_repo = relationship('Repository', primaryjoin='PullRequest.org_repo_id==Repository.repo_id')
-    other_repo = relationship('Repository', primaryjoin='PullRequest.other_repo_id==Repository.repo_id')
-    statuses = relationship('ChangesetStatus')
-    comments = relationship('ChangesetComment',
-                             cascade="all, delete, delete-orphan")
-
-    def is_closed(self):
-        return self.status == self.STATUS_CLOSED
-
-    @property
-    def last_review_status(self):
-        return self.statuses[-1].status if self.statuses else ''
-
-    def __json__(self):
-        return dict(
-            revisions=self.revisions
-        )
-
-
-class PullRequestReviewers(Base, BaseModel):
-    __tablename__ = 'pull_request_reviewers'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    def __init__(self, user=None, pull_request=None):
-        self.user = user
-        self.pull_request = pull_request
-
-    pull_requests_reviewers_id = Column('pull_requests_reviewers_id', Integer(), nullable=False, primary_key=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
-
-    user = relationship('User')
-    pull_request = relationship('PullRequest')
-
-
-class Notification(Base, BaseModel):
-    __tablename__ = 'notifications'
-    __table_args__ = (
-        Index('notification_type_idx', 'type'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    TYPE_CHANGESET_COMMENT = u'cs_comment'
-    TYPE_MESSAGE = u'message'
-    TYPE_MENTION = u'mention'
-    TYPE_REGISTRATION = u'registration'
-    TYPE_PULL_REQUEST = u'pull_request'
-    TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
-
-    notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
-    subject = Column('subject', Unicode(512), nullable=True)
-    body = Column('body', UnicodeText(50000), nullable=True)
-    created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    type_ = Column('type', Unicode(256))
-
-    created_by_user = relationship('User')
-    notifications_to_users = relationship('UserNotification', lazy='joined',
-                                          cascade="all, delete, delete-orphan")
-
-    @property
-    def recipients(self):
-        return [x.user for x in UserNotification.query()\
-                .filter(UserNotification.notification == self)\
-                .order_by(UserNotification.user_id.asc()).all()]
-
-    @classmethod
-    def create(cls, created_by, subject, body, recipients, type_=None):
-        if type_ is None:
-            type_ = Notification.TYPE_MESSAGE
-
-        notification = cls()
-        notification.created_by_user = created_by
-        notification.subject = subject
-        notification.body = body
-        notification.type_ = type_
-        notification.created_on = datetime.datetime.now()
-
-        for u in recipients:
-            assoc = UserNotification()
-            assoc.notification = notification
-            u.notifications.append(assoc)
-        Session().add(notification)
-        return notification
-
-    @property
-    def description(self):
-        from kallithea.model.notification import NotificationModel
-        return NotificationModel().make_description(self)
-
-
-class UserNotification(Base, BaseModel):
-    __tablename__ = 'user_to_notification'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'notification_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
-    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
-    read = Column('read', Boolean, default=False)
-    sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
-
-    user = relationship('User', lazy="joined")
-    notification = relationship('Notification', lazy="joined",
-                                order_by=lambda: Notification.created_on.desc(),)
-
-    def mark_as_read(self):
-        self.read = True
-        Session().add(self)
-
-
-class Gist(Base, BaseModel):
-    __tablename__ = 'gists'
-    __table_args__ = (
-        Index('g_gist_access_id_idx', 'gist_access_id'),
-        Index('g_created_on_idx', 'created_on'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    GIST_PUBLIC = u'public'
-    GIST_PRIVATE = u'private'
-    DEFAULT_FILENAME = u'gistfile1.txt'
-
-    gist_id = Column('gist_id', Integer(), primary_key=True)
-    gist_access_id = Column('gist_access_id', Unicode(250))
-    gist_description = Column('gist_description', UnicodeText(1024))
-    gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
-    gist_expires = Column('gist_expires', Float(53), nullable=False)
-    gist_type = Column('gist_type', Unicode(128), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    owner = relationship('User')
-
-    def __repr__(self):
-        return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
-
-    @classmethod
-    def get_or_404(cls, id_):
-        res = cls.query().filter(cls.gist_access_id == id_).scalar()
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def get_by_access_id(cls, gist_access_id):
-        return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
-
-    def gist_url(self):
-        import kallithea
-        alias_url = kallithea.CONFIG.get('gist_alias_url')
-        if alias_url:
-            return alias_url.replace('{gistid}', self.gist_access_id)
-
-        import kallithea.lib.helpers as h
-        return h.canonical_url('gist', gist_id=self.gist_access_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all gists are stored
-
-        :param cls:
-        """
-        from kallithea.model.gist import GIST_STORE_LOC
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == URL_SEP)
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return os.path.join(q.one().ui_value, GIST_STORE_LOC)
-
-    def get_api_data(self):
-        """
-        Common function for generating gist related data for API
-        """
-        gist = self
-        data = dict(
-            gist_id=gist.gist_id,
-            type=gist.gist_type,
-            access_id=gist.gist_access_id,
-            description=gist.gist_description,
-            url=gist.gist_url(),
-            expires=gist.gist_expires,
-            created_on=gist.created_on,
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-        )
-        data.update(self.get_api_data())
-        return data
-    ## SCM functions
-
-    @property
-    def scm_instance(self):
-        from kallithea.lib.vcs import get_repo
-        base_path = self.base_path()
-        return get_repo(os.path.join(*map(safe_str,
-                                          [base_path, self.gist_access_id])))
-
-
-class DbMigrateVersion(Base, BaseModel):
-    __tablename__ = 'db_migrate_version'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    repository_id = Column('repository_id', String(250), primary_key=True)
-    repository_path = Column('repository_path', Text)
-    version = Column('version', Integer)
--- a/kallithea/lib/dbmigrate/schema/db_2_2_3.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,2494 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate.schema.db_2_2_3
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Database Models for Kallithea
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Apr 08, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-import os
-import time
-import logging
-import datetime
-import traceback
-import hashlib
-import collections
-import functools
-
-from sqlalchemy import *
-from sqlalchemy.ext.hybrid import hybrid_property
-from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
-from beaker.cache import cache_region, region_invalidate
-from webob.exc import HTTPNotFound
-
-from pylons.i18n.translation import lazy_ugettext as _
-
-from kallithea.lib.vcs import get_backend
-from kallithea.lib.vcs.utils.helpers import get_scm
-from kallithea.lib.vcs.exceptions import VCSError
-from kallithea.lib.vcs.utils.lazy import LazyProperty
-from kallithea.lib.vcs.backends.base import EmptyChangeset
-
-from kallithea.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
-    safe_unicode, remove_prefix, time_to_datetime, aslist, Optional, safe_int, \
-    get_clone_url
-from kallithea.lib.compat import json
-from kallithea.lib.caching_query import FromCache
-
-from kallithea.model.meta import Base, Session
-
-URL_SEP = '/'
-log = logging.getLogger(__name__)
-
-from kallithea import DB_PREFIX
-
-#==============================================================================
-# BASE CLASSES
-#==============================================================================
-
-_hash_key = lambda k: hashlib.md5(safe_str(k)).hexdigest()
-
-
-class BaseModel(object):
-    """
-    Base Model for all classess
-    """
-
-    @classmethod
-    def _get_keys(cls):
-        """return column names for this model """
-        return class_mapper(cls).c.keys()
-
-    def get_dict(self):
-        """
-        return dict with keys and values corresponding
-        to this model data """
-
-        d = {}
-        for k in self._get_keys():
-            d[k] = getattr(self, k)
-
-        # also use __json__() if present to get additional fields
-        _json_attr = getattr(self, '__json__', None)
-        if _json_attr:
-            # update with attributes from __json__
-            if callable(_json_attr):
-                _json_attr = _json_attr()
-            for k, val in _json_attr.iteritems():
-                d[k] = val
-        return d
-
-    def get_appstruct(self):
-        """return list with keys and values tuples corresponding
-        to this model data """
-
-        l = []
-        for k in self._get_keys():
-            l.append((k, getattr(self, k),))
-        return l
-
-    def populate_obj(self, populate_dict):
-        """populate model with data from given populate_dict"""
-
-        for k in self._get_keys():
-            if k in populate_dict:
-                setattr(self, k, populate_dict[k])
-
-    @classmethod
-    def query(cls):
-        return Session().query(cls)
-
-    @classmethod
-    def get(cls, id_):
-        if id_:
-            return cls.query().get(id_)
-
-    @classmethod
-    def get_or_404(cls, id_):
-        try:
-            id_ = int(id_)
-        except (TypeError, ValueError):
-            raise HTTPNotFound
-
-        res = cls.query().get(id_)
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def getAll(cls):
-        # deprecated and left for backward compatibility
-        return cls.get_all()
-
-    @classmethod
-    def get_all(cls):
-        return cls.query().all()
-
-    @classmethod
-    def delete(cls, id_):
-        obj = cls.query().get(id_)
-        Session().delete(obj)
-
-    def __repr__(self):
-        if hasattr(self, '__unicode__'):
-            # python repr needs to return str
-            try:
-                return safe_str(self.__unicode__())
-            except UnicodeDecodeError:
-                pass
-        return '<DB:%s>' % (self.__class__.__name__)
-
-
-class Setting(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'settings'
-    __table_args__ = (
-        UniqueConstraint('app_settings_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    SETTINGS_TYPES = {
-        'str': safe_str,
-        'int': safe_int,
-        'unicode': safe_unicode,
-        'bool': str2bool,
-        'list': functools.partial(aslist, sep=',')
-    }
-    DEFAULT_UPDATE_URL = ''
-
-    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    app_settings_name = Column("app_settings_name", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    _app_settings_value = Column("app_settings_value", String(4096, convert_unicode=False), nullable=True, unique=None, default=None)
-    _app_settings_type = Column("app_settings_type", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-
-    def __init__(self, key='', val='', type='unicode'):
-        self.app_settings_name = key
-        self.app_settings_value = val
-        self.app_settings_type = type
-
-    @validates('_app_settings_value')
-    def validate_settings_value(self, key, val):
-        assert type(val) == unicode
-        return val
-
-    @hybrid_property
-    def app_settings_value(self):
-        v = self._app_settings_value
-        _type = self.app_settings_type
-        converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
-        return converter(v)
-
-    @app_settings_value.setter
-    def app_settings_value(self, val):
-        """
-        Setter that will always make sure we use unicode in app_settings_value
-
-        :param val:
-        """
-        self._app_settings_value = safe_unicode(val)
-
-    @hybrid_property
-    def app_settings_type(self):
-        return self._app_settings_type
-
-    @app_settings_type.setter
-    def app_settings_type(self, val):
-        if val not in self.SETTINGS_TYPES:
-            raise Exception('type must be one of %s got %s'
-                            % (self.SETTINGS_TYPES.keys(), val))
-        self._app_settings_type = val
-
-    def __unicode__(self):
-        return u"<%s('%s:%s[%s]')>" % (
-            self.__class__.__name__,
-            self.app_settings_name, self.app_settings_value, self.app_settings_type
-        )
-
-    @classmethod
-    def get_by_name(cls, key):
-        return cls.query()\
-            .filter(cls.app_settings_name == key).scalar()
-
-    @classmethod
-    def get_by_name_or_create(cls, key, val='', type='unicode'):
-        res = cls.get_by_name(key)
-        if not res:
-            res = cls(key, val, type)
-        return res
-
-    @classmethod
-    def create_or_update(cls, key, val=Optional(''), type=Optional('unicode')):
-        """
-        Creates or updates Kallithea setting. If updates is triggered it will only
-        update parameters that are explicityl set Optional instance will be skipped
-
-        :param key:
-        :param val:
-        :param type:
-        :return:
-        """
-        res = cls.get_by_name(key)
-        if not res:
-            val = Optional.extract(val)
-            type = Optional.extract(type)
-            res = cls(key, val, type)
-        else:
-            res.app_settings_name = key
-            if not isinstance(val, Optional):
-                # update if set
-                res.app_settings_value = val
-            if not isinstance(type, Optional):
-                # update if set
-                res.app_settings_type = type
-        return res
-
-    @classmethod
-    def get_app_settings(cls, cache=False):
-
-        ret = cls.query()
-
-        if cache:
-            ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
-
-        if not ret:
-            raise Exception('Could not get application settings !')
-        settings = {}
-        for each in ret:
-            settings[each.app_settings_name] = \
-                each.app_settings_value
-
-        return settings
-
-    @classmethod
-    def get_auth_plugins(cls, cache=False):
-        auth_plugins = cls.get_by_name("auth_plugins").app_settings_value
-        return auth_plugins
-
-    @classmethod
-    def get_auth_settings(cls, cache=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('auth_')).all()
-        fd = {}
-        for row in ret:
-            fd.update({row.app_settings_name: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_default_repo_settings(cls, cache=False, strip_prefix=False):
-        ret = cls.query()\
-                .filter(cls.app_settings_name.startswith('default_')).all()
-        fd = {}
-        for row in ret:
-            key = row.app_settings_name
-            if strip_prefix:
-                key = remove_prefix(key, prefix='default_')
-            fd.update({key: row.app_settings_value})
-
-        return fd
-
-    @classmethod
-    def get_server_info(cls):
-        import pkg_resources
-        import platform
-        import kallithea
-        from kallithea.lib.utils import check_git_version
-        mods = [(p.project_name, p.version) for p in pkg_resources.working_set]
-        info = {
-            'modules': sorted(mods, key=lambda k: k[0].lower()),
-            'py_version': platform.python_version(),
-            'platform': safe_unicode(platform.platform()),
-            'kallithea_version': kallithea.__version__,
-            'git_version': safe_unicode(check_git_version()),
-            'git_path': kallithea.CONFIG.get('git_path')
-        }
-        return info
-
-
-class Ui(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'ui'
-    __table_args__ = (
-        UniqueConstraint('ui_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    HOOK_UPDATE = 'changegroup.update'
-    HOOK_REPO_SIZE = 'changegroup.repo_size'
-    HOOK_PUSH = 'changegroup.push_logger'
-    HOOK_PRE_PUSH = 'prechangegroup.pre_push'
-    HOOK_PULL = 'outgoing.pull_logger'
-    HOOK_PRE_PULL = 'preoutgoing.pre_pull'
-
-    ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    ui_section = Column("ui_section", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    ui_key = Column("ui_key", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    ui_value = Column("ui_value", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
-
-    # def __init__(self, section='', key='', value=''):
-    #     self.ui_section = section
-    #     self.ui_key = key
-    #     self.ui_value = value
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.ui_key == key).scalar()
-
-    @classmethod
-    def get_builtin_hooks(cls):
-        q = cls.query()
-        q = q.filter(cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                     cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                     cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        return q.all()
-
-    @classmethod
-    def get_custom_hooks(cls):
-        q = cls.query()
-        q = q.filter(~cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
-                                      cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
-                                      cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
-        q = q.filter(cls.ui_section == 'hooks')
-        return q.all()
-
-    @classmethod
-    def get_repos_location(cls):
-        return cls.get_by_key('/').ui_value
-
-    @classmethod
-    def create_or_update_hook(cls, key, val):
-        new_ui = cls.get_by_key(key) or cls()
-        new_ui.ui_section = 'hooks'
-        new_ui.ui_active = True
-        new_ui.ui_key = key
-        new_ui.ui_value = val
-
-        Session().add(new_ui)
-
-    def __repr__(self):
-        return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
-                                    self.ui_key, self.ui_value)
-
-
-class User(Base, BaseModel):
-    __tablename__ = 'users'
-    __table_args__ = (
-        UniqueConstraint('username'), UniqueConstraint('email'),
-        Index('u_username_idx', 'username'),
-        Index('u_email_idx', 'email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    DEFAULT_USER = 'default'
-    DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
-
-    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    username = Column("username", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    password = Column("password", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
-    name = Column("firstname", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    lastname = Column("lastname", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
-    extern_type = Column("extern_type", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    extern_name = Column("extern_name", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    api_key = Column("api_key", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    _user_data = Column("user_data", LargeBinary(), nullable=True)  # JSON data
-
-    user_log = relationship('UserLog')
-    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
-
-    repositories = relationship('Repository')
-    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
-    followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
-
-    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
-
-    group_member = relationship('UserGroupMember', cascade='all')
-
-    notifications = relationship('UserNotification', cascade='all')
-    # notifications assigned to this user
-    user_created_notifications = relationship('Notification', cascade='all')
-    # comments created by this user
-    user_comments = relationship('ChangesetComment', cascade='all')
-    #extra emails for this user
-    user_emails = relationship('UserEmailMap', cascade='all')
-    #extra API keys
-    user_api_keys = relationship('UserApiKeys', cascade='all')
-
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-    @property
-    def firstname(self):
-        # alias for future
-        return self.name
-
-    @property
-    def emails(self):
-        other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
-        return [self.email] + [x.email for x in other]
-
-    @property
-    def api_keys(self):
-        other = UserApiKeys.query().filter(UserApiKeys.user==self).all()
-        return [self.api_key] + [x.api_key for x in other]
-
-    @property
-    def ip_addresses(self):
-        ret = UserIpMap.query().filter(UserIpMap.user == self).all()
-        return [x.ip_addr for x in ret]
-
-    @property
-    def username_and_name(self):
-        return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
-
-    @property
-    def full_name(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def full_name_or_username(self):
-        return ('%s %s' % (self.firstname, self.lastname)
-                if (self.firstname and self.lastname) else self.username)
-
-    @property
-    def full_contact(self):
-        return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
-
-    @property
-    def short_contact(self):
-        return '%s %s' % (self.firstname, self.lastname)
-
-    @property
-    def is_admin(self):
-        return self.admin
-
-    @property
-    def AuthUser(self):
-        """
-        Returns instance of AuthUser for this user
-        """
-        from kallithea.lib.auth import AuthUser
-        return AuthUser(user_id=self.user_id, api_key=self.api_key,
-                        username=self.username)
-
-    @hybrid_property
-    def user_data(self):
-        if not self._user_data:
-            return {}
-
-        try:
-            return json.loads(self._user_data)
-        except TypeError:
-            return {}
-
-    @user_data.setter
-    def user_data(self, val):
-        try:
-            self._user_data = json.dumps(val)
-        except Exception:
-            log.error(traceback.format_exc())
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.user_id, self.username)
-
-    @classmethod
-    def get_by_username(cls, username, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.username.ilike(username))
-        else:
-            q = cls.query().filter(cls.username == username)
-
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(username)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get_by_api_key(cls, api_key, cache=False, fallback=True):
-        q = cls.query().filter(cls.api_key == api_key)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_api_key_%s" % api_key))
-        res = q.scalar()
-
-        if fallback and not res:
-            #fallback to additional keys
-            _res = UserApiKeys.query()\
-                .filter(UserApiKeys.api_key == api_key)\
-                .filter(or_(UserApiKeys.expires == -1,
-                            UserApiKeys.expires >= time.time()))\
-                .first()
-            if _res:
-                res = _res.user
-        return res
-
-    @classmethod
-    def get_by_email(cls, email, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.email.ilike(email))
-        else:
-            q = cls.query().filter(cls.email == email)
-
-        if cache:
-            q = q.options(FromCache("sql_cache_short",
-                                    "get_email_key_%s" % email))
-
-        ret = q.scalar()
-        if ret is None:
-            q = UserEmailMap.query()
-            # try fetching in alternate email map
-            if case_insensitive:
-                q = q.filter(UserEmailMap.email.ilike(email))
-            else:
-                q = q.filter(UserEmailMap.email == email)
-            q = q.options(joinedload(UserEmailMap.user))
-            if cache:
-                q = q.options(FromCache("sql_cache_short",
-                                        "get_email_map_key_%s" % email))
-            ret = getattr(q.scalar(), 'user', None)
-
-        return ret
-
-    @classmethod
-    def get_from_cs_author(cls, author):
-        """
-        Tries to get User objects out of commit author string
-
-        :param author:
-        """
-        from kallithea.lib.helpers import email, author_name
-        # Valid email in the attribute passed, see if they're in the system
-        _email = email(author)
-        if _email:
-            user = cls.get_by_email(_email, case_insensitive=True)
-            if user:
-                return user
-        # Maybe we can match by username?
-        _author = author_name(author)
-        user = cls.get_by_username(_author, case_insensitive=True)
-        if user:
-            return user
-
-    def update_lastlogin(self):
-        """Update user lastlogin"""
-        self.last_login = datetime.datetime.now()
-        Session().add(self)
-        log.debug('updated user %s lastlogin', self.username)
-
-    @classmethod
-    def get_first_admin(cls):
-        user = User.query().filter(User.admin == True).first()
-        if user is None:
-            raise Exception('Missing administrative account!')
-        return user
-
-    @classmethod
-    def get_default_user(cls, cache=False):
-        user = User.get_by_username(User.DEFAULT_USER, cache=cache)
-        if user is None:
-            raise Exception('Missing default account!')
-        return user
-
-    def get_api_data(self):
-        """
-        Common function for generating user related data for API
-        """
-        user = self
-        data = dict(
-            user_id=user.user_id,
-            username=user.username,
-            firstname=user.name,
-            lastname=user.lastname,
-            email=user.email,
-            emails=user.emails,
-            api_key=user.api_key,
-            api_keys=user.api_keys,
-            active=user.active,
-            admin=user.admin,
-            extern_type=user.extern_type,
-            extern_name=user.extern_name,
-            last_login=user.last_login,
-            ip_addresses=user.ip_addresses
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-            full_name=self.full_name,
-            full_name_or_username=self.full_name_or_username,
-            short_contact=self.short_contact,
-            full_contact=self.full_contact
-        )
-        data.update(self.get_api_data())
-        return data
-
-
-class UserApiKeys(Base, BaseModel):
-    __tablename__ = 'user_api_keys'
-    __table_args__ = (
-        Index('uak_api_key_idx', 'api_key'),
-        Index('uak_api_key_expires_idx', 'api_key', 'expires'),
-        UniqueConstraint('api_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    api_key = Column("api_key", String(255, convert_unicode=False), nullable=False, unique=True)
-    description = Column('description', UnicodeText(1024))
-    expires = Column('expires', Float(53), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    user = relationship('User', lazy='joined')
-
-    @property
-    def expired(self):
-        if self.expires == -1:
-            return False
-        return time.time() > self.expires
-
-
-class UserEmailMap(Base, BaseModel):
-    __tablename__ = 'user_email_map'
-    __table_args__ = (
-        Index('uem_email_idx', 'email'),
-        UniqueConstraint('email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False), nullable=True, unique=False, default=None)
-    user = relationship('User', lazy='joined')
-
-    @validates('_email')
-    def validate_email(self, key, email):
-        # check if this email is not main one
-        main_email = Session().query(User).filter(User.email == email).scalar()
-        if main_email is not None:
-            raise AttributeError('email %s is present is user table' % email)
-        return email
-
-    @hybrid_property
-    def email(self):
-        return self._email
-
-    @email.setter
-    def email(self, val):
-        self._email = val.lower() if val else None
-
-
-class UserIpMap(Base, BaseModel):
-    __tablename__ = 'user_ip_map'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'ip_addr'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    __mapper_args__ = {}
-
-    ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    ip_addr = Column("ip_addr", String(255, convert_unicode=False), nullable=True, unique=False, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=True)
-    user = relationship('User', lazy='joined')
-
-    @classmethod
-    def _get_ip_range(cls, ip_addr):
-        from kallithea.lib import ipaddr
-        net = ipaddr.IPNetwork(address=ip_addr)
-        return [str(net.network), str(net.broadcast)]
-
-    def __json__(self):
-        return dict(
-          ip_addr=self.ip_addr,
-          ip_range=self._get_ip_range(self.ip_addr)
-        )
-
-    def __unicode__(self):
-        return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
-                                            self.user_id, self.ip_addr)
-
-class UserLog(Base, BaseModel):
-    __tablename__ = 'user_logs'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    username = Column("username", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
-    repository_name = Column("repository_name", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    user_ip = Column("user_ip", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    action = Column("action", UnicodeText(1200000, convert_unicode=False), nullable=True, unique=None, default=None)
-    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.repository_name,
-                                      self.action)
-
-    @property
-    def action_as_day(self):
-        return datetime.date(*self.action_date.timetuple()[:3])
-
-    user = relationship('User')
-    repository = relationship('Repository', cascade='')
-
-
-class UserGroup(Base, BaseModel):
-    __tablename__ = 'users_groups'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_name = Column("users_group_name", String(255, convert_unicode=False), nullable=False, unique=True, default=None)
-    user_group_description = Column("user_group_description", String(10000, convert_unicode=False), nullable=True, unique=None, default=None)
-    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    _group_data = Column("group_data", LargeBinary(), nullable=True)  # JSON data
-
-    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
-    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
-    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-    user_user_group_to_perm = relationship('UserUserGroupToPerm ', cascade='all')
-    user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
-
-    user = relationship('User')
-
-    @hybrid_property
-    def group_data(self):
-        if not self._group_data:
-            return {}
-
-        try:
-            return json.loads(self._group_data)
-        except TypeError:
-            return {}
-
-    @group_data.setter
-    def group_data(self, val):
-        try:
-            self._group_data = json.dumps(val)
-        except Exception:
-            log.error(traceback.format_exc())
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
-                                      self.users_group_id,
-                                      self.users_group_name)
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False,
-                          case_insensitive=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.users_group_name.ilike(group_name))
-        else:
-            q = cls.query().filter(cls.users_group_name == group_name)
-        if cache:
-            q = q.options(FromCache(
-                            "sql_cache_short",
-                            "get_user_%s" % _hash_key(group_name)
-                          )
-            )
-        return q.scalar()
-
-    @classmethod
-    def get(cls, user_group_id, cache=False):
-        user_group = cls.query()
-        if cache:
-            user_group = user_group.options(FromCache("sql_cache_short",
-                                    "get_users_group_%s" % user_group_id))
-        return user_group.get(user_group_id)
-
-    def get_api_data(self, with_members=True):
-        user_group = self
-
-        data = dict(
-            users_group_id=user_group.users_group_id,
-            group_name=user_group.users_group_name,
-            group_description=user_group.user_group_description,
-            active=user_group.users_group_active,
-            owner=user_group.user.username,
-        )
-        if with_members:
-            members = []
-            for user in user_group.members:
-                user = user.user
-                members.append(user.get_api_data())
-            data['members'] = members
-
-        return data
-
-
-class UserGroupMember(Base, BaseModel):
-    __tablename__ = 'users_groups_members'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User', lazy='joined')
-    users_group = relationship('UserGroup')
-
-    def __init__(self, gr_id='', u_id=''):
-        self.users_group_id = gr_id
-        self.user_id = u_id
-
-
-class RepositoryField(Base, BaseModel):
-    __tablename__ = 'repositories_fields'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'field_key'),  # no-multi field
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    PREFIX = 'ex_'  # prefix used in form to not conflict with already existing fields
-
-    repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-    field_key = Column("field_key", String(250, convert_unicode=False))
-    field_label = Column("field_label", String(1024, convert_unicode=False), nullable=False)
-    field_value = Column("field_value", String(10000, convert_unicode=False), nullable=False)
-    field_desc = Column("field_desc", String(1024, convert_unicode=False), nullable=False)
-    field_type = Column("field_type", String(256), nullable=False, unique=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    repository = relationship('Repository')
-
-    @property
-    def field_key_prefixed(self):
-        return 'ex_%s' % self.field_key
-
-    @classmethod
-    def un_prefix_key(cls, key):
-        if key.startswith(cls.PREFIX):
-            return key[len(cls.PREFIX):]
-        return key
-
-    @classmethod
-    def get_by_key_name(cls, key, repo):
-        row = cls.query()\
-                .filter(cls.repository == repo)\
-                .filter(cls.field_key == key).scalar()
-        return row
-
-
-class Repository(Base, BaseModel):
-    __tablename__ = 'repositories'
-    __table_args__ = (
-        UniqueConstraint('repo_name'),
-        Index('r_repo_name_idx', 'repo_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
-    DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
-
-    STATE_CREATED = 'repo_state_created'
-    STATE_PENDING = 'repo_state_pending'
-    STATE_ERROR = 'repo_state_error'
-
-    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repo_name = Column("repo_name", String(255, convert_unicode=False), nullable=False, unique=True, default=None)
-    repo_state = Column("repo_state", String(255), nullable=True)
-
-    clone_uri = Column("clone_uri", String(255, convert_unicode=False), nullable=True, unique=False, default=None)
-    repo_type = Column("repo_type", String(255, convert_unicode=False), nullable=False, unique=False, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
-    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
-    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
-    description = Column("description", String(10000, convert_unicode=False), nullable=True, unique=None, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-    _landing_revision = Column("landing_revision", String(255, convert_unicode=False), nullable=False, unique=False, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    _locked = Column("locked", String(255, convert_unicode=False), nullable=True, unique=False, default=None)
-    _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) #JSON data
-
-    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
-
-    user = relationship('User')
-    fork = relationship('Repository', remote_side=repo_id)
-    group = relationship('RepoGroup')
-    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
-    stats = relationship('Statistics', cascade='all', uselist=False)
-
-    followers = relationship('UserFollowing',
-                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
-                             cascade='all')
-    extra_fields = relationship('RepositoryField',
-                                cascade="all, delete, delete-orphan")
-
-    logs = relationship('UserLog')
-    comments = relationship('ChangesetComment', cascade="all, delete, delete-orphan")
-
-    pull_requests_org = relationship('PullRequest',
-                    primaryjoin='PullRequest.org_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    pull_requests_other = relationship('PullRequest',
-                    primaryjoin='PullRequest.other_repo_id==Repository.repo_id',
-                    cascade="all, delete, delete-orphan")
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
-                                   safe_unicode(self.repo_name))
-
-    @hybrid_property
-    def landing_rev(self):
-        # always should return [rev_type, rev]
-        if self._landing_revision:
-            _rev_info = self._landing_revision.split(':')
-            if len(_rev_info) < 2:
-                _rev_info.insert(0, 'rev')
-            return [_rev_info[0], _rev_info[1]]
-        return [None, None]
-
-    @landing_rev.setter
-    def landing_rev(self, val):
-        if ':' not in val:
-            raise ValueError('value must be delimited with `:` and consist '
-                             'of <rev_type>:<rev>, got %s instead' % val)
-        self._landing_revision = val
-
-    @hybrid_property
-    def locked(self):
-        # always should return [user_id, timelocked]
-        if self._locked:
-            _lock_info = self._locked.split(':')
-            return int(_lock_info[0]), _lock_info[1]
-        return [None, None]
-
-    @locked.setter
-    def locked(self, val):
-        if val and isinstance(val, (list, tuple)):
-            self._locked = ':'.join(map(str, val))
-        else:
-            self._locked = None
-
-    @hybrid_property
-    def changeset_cache(self):
-        from kallithea.lib.vcs.backends.base import EmptyChangeset
-        dummy = EmptyChangeset().__json__()
-        if not self._changeset_cache:
-            return dummy
-        try:
-            return json.loads(self._changeset_cache)
-        except TypeError:
-            return dummy
-
-    @changeset_cache.setter
-    def changeset_cache(self, val):
-        try:
-            self._changeset_cache = json.dumps(val)
-        except Exception:
-            log.error(traceback.format_exc())
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def normalize_repo_name(cls, repo_name):
-        """
-        Normalizes os specific repo_name to the format internally stored inside
-        dabatabase using URL_SEP
-
-        :param cls:
-        :param repo_name:
-        """
-        return cls.url_sep().join(repo_name.split(os.sep))
-
-    @classmethod
-    def get_by_repo_name(cls, repo_name):
-        q = Session().query(cls).filter(cls.repo_name == repo_name)
-        q = q.options(joinedload(Repository.fork))\
-                .options(joinedload(Repository.user))\
-                .options(joinedload(Repository.group))
-        return q.scalar()
-
-    @classmethod
-    def get_by_full_path(cls, repo_full_path):
-        repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
-        repo_name = cls.normalize_repo_name(repo_name)
-        return cls.get_by_repo_name(repo_name.strip(URL_SEP))
-
-    @classmethod
-    def get_repo_forks(cls, repo_id):
-        return cls.query().filter(Repository.fork_id == repo_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all repos are stored
-
-        :param cls:
-        """
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == cls.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def forks(self):
-        """
-        Return forks of this repo
-        """
-        return Repository.get_repo_forks(self.repo_id)
-
-    @property
-    def parent(self):
-        """
-        Returns fork parent
-        """
-        return self.fork
-
-    @property
-    def just_name(self):
-        return self.repo_name.split(Repository.url_sep())[-1]
-
-    @property
-    def groups_with_parents(self):
-        groups = []
-        if self.group is None:
-            return groups
-
-        cur_gr = self.group
-        groups.insert(0, cur_gr)
-        while 1:
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            groups.insert(0, gr)
-
-        return groups
-
-    @property
-    def groups_and_repo(self):
-        return self.groups_with_parents, self.just_name, self.repo_name
-
-    @LazyProperty
-    def repo_path(self):
-        """
-        Returns base full path for that repository means where it actually
-        exists on a filesystem
-        """
-        q = Session().query(Ui).filter(Ui.ui_key ==
-                                              Repository.url_sep())
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return q.one().ui_value
-
-    @property
-    def repo_full_path(self):
-        p = [self.repo_path]
-        # we need to split the name by / since this is how we store the
-        # names in the database, but that eventually needs to be converted
-        # into a valid system path
-        p += self.repo_name.split(Repository.url_sep())
-        return os.path.join(*map(safe_unicode, p))
-
-    @property
-    def cache_keys(self):
-        """
-        Returns associated cache keys for that repo
-        """
-        return CacheInvalidation.query()\
-            .filter(CacheInvalidation.cache_args == self.repo_name)\
-            .order_by(CacheInvalidation.cache_key)\
-            .all()
-
-    def get_new_name(self, repo_name):
-        """
-        returns new full repository name based on assigned group and new new
-
-        :param group_name:
-        """
-        path_prefix = self.group.full_path_splitted if self.group else []
-        return Repository.url_sep().join(path_prefix + [repo_name])
-
-    @property
-    def _ui(self):
-        """
-        Creates an db based ui object for this repository
-        """
-        from kallithea.lib.utils import make_ui
-        return make_ui('db', clear_session=False)
-
-    @classmethod
-    def is_valid(cls, repo_name):
-        """
-        returns True if given repo name is a valid filesystem repository
-
-        :param cls:
-        :param repo_name:
-        """
-        from kallithea.lib.utils import is_valid_repo
-
-        return is_valid_repo(repo_name, cls.base_path())
-
-    def get_api_data(self):
-        """
-        Common function for generating repo api data
-
-        """
-        repo = self
-        data = dict(
-            repo_id=repo.repo_id,
-            repo_name=repo.repo_name,
-            repo_type=repo.repo_type,
-            clone_uri=repo.clone_uri,
-            private=repo.private,
-            created_on=repo.created_on,
-            description=repo.description,
-            landing_rev=repo.landing_rev,
-            owner=repo.user.username,
-            fork_of=repo.fork.repo_name if repo.fork else None,
-            enable_statistics=repo.enable_statistics,
-            enable_locking=repo.enable_locking,
-            enable_downloads=repo.enable_downloads,
-            last_changeset=repo.changeset_cache,
-            locked_by=User.get(self.locked[0]).get_api_data() \
-                if self.locked[0] else None,
-            locked_date=time_to_datetime(self.locked[1]) \
-                if self.locked[1] else None
-        )
-        rc_config = Setting.get_app_settings()
-        repository_fields = str2bool(rc_config.get('repository_fields'))
-        if repository_fields:
-            for f in self.extra_fields:
-                data[f.field_key_prefixed] = f.field_value
-
-        return data
-
-    @classmethod
-    def lock(cls, repo, user_id, lock_time=None):
-        if not lock_time:
-            lock_time = time.time()
-        repo.locked = [user_id, lock_time]
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def unlock(cls, repo):
-        repo.locked = None
-        Session().add(repo)
-        Session().commit()
-
-    @classmethod
-    def getlock(cls, repo):
-        return repo.locked
-
-    @property
-    def last_db_change(self):
-        return self.updated_on
-
-    def clone_url(self, **override):
-        import kallithea.lib.helpers as h
-        qualified_home_url = h.canonical_url('home')
-
-        uri_tmpl = None
-        if 'with_id' in override:
-            uri_tmpl = self.DEFAULT_CLONE_URI_ID
-            del override['with_id']
-
-        if 'uri_tmpl' in override:
-            uri_tmpl = override['uri_tmpl']
-            del override['uri_tmpl']
-
-        # we didn't override our tmpl from **overrides
-        if not uri_tmpl:
-            uri_tmpl = self.DEFAULT_CLONE_URI
-            try:
-                from pylons import tmpl_context as c
-                uri_tmpl = c.clone_uri_tmpl
-            except Exception:
-                # in any case if we call this outside of request context,
-                # ie, not having tmpl_context set up
-                pass
-
-        return get_clone_url(uri_tmpl=uri_tmpl,
-                             qualified_home_url=qualified_home_url,
-                             repo_name=self.repo_name,
-                             repo_id=self.repo_id, **override)
-
-    def set_state(self, state):
-        self.repo_state = state
-        Session().add(self)
-    #==========================================================================
-    # SCM PROPERTIES
-    #==========================================================================
-
-    def get_changeset(self, rev=None):
-        return get_changeset_safe(self.scm_instance, rev)
-
-    def get_landing_changeset(self):
-        """
-        Returns landing changeset, or if that doesn't exist returns the tip
-        """
-        _rev_type, _rev = self.landing_rev
-        cs = self.get_changeset(_rev)
-        if isinstance(cs, EmptyChangeset):
-            return self.get_changeset()
-        return cs
-
-    def update_changeset_cache(self, cs_cache=None):
-        """
-        Update cache of last changeset for repository, keys should be::
-
-            short_id
-            raw_id
-            revision
-            message
-            date
-            author
-
-        :param cs_cache:
-        """
-        from kallithea.lib.vcs.backends.base import BaseChangeset
-        if cs_cache is None:
-            cs_cache = EmptyChangeset()
-            # use no-cache version here
-            scm_repo = self.scm_instance_no_cache()
-            if scm_repo:
-                cs_cache = scm_repo.get_changeset()
-
-        if isinstance(cs_cache, BaseChangeset):
-            cs_cache = cs_cache.__json__()
-
-        if (cs_cache != self.changeset_cache or not self.changeset_cache):
-            _default = datetime.datetime.fromtimestamp(0)
-            last_change = cs_cache.get('date') or _default
-            log.debug('updated repo %s with new cs cache %s',
-                      self.repo_name, cs_cache)
-            self.updated_on = last_change
-            self.changeset_cache = cs_cache
-            Session().add(self)
-            Session().commit()
-        else:
-            log.debug('Skipping repo:%s already with latest changes',
-                      self.repo_name)
-
-    @property
-    def tip(self):
-        return self.get_changeset('tip')
-
-    @property
-    def author(self):
-        return self.tip.author
-
-    @property
-    def last_change(self):
-        return self.scm_instance.last_change
-
-    def get_comments(self, revisions=None):
-        """
-        Returns comments for this repository grouped by revisions
-
-        :param revisions: filter query by revisions only
-        """
-        cmts = ChangesetComment.query()\
-            .filter(ChangesetComment.repo == self)
-        if revisions:
-            cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
-        grouped = collections.defaultdict(list)
-        for cmt in cmts.all():
-            grouped[cmt.revision].append(cmt)
-        return grouped
-
-    def statuses(self, revisions=None):
-        """
-        Returns statuses for this repository
-
-        :param revisions: list of revisions to get statuses for
-        """
-
-        statuses = ChangesetStatus.query()\
-            .filter(ChangesetStatus.repo == self)\
-            .filter(ChangesetStatus.version == 0)
-        if revisions:
-            statuses = statuses.filter(ChangesetStatus.revision.in_(revisions))
-        grouped = {}
-
-        #maybe we have open new pullrequest without a status ?
-        stat = ChangesetStatus.STATUS_UNDER_REVIEW
-        status_lbl = ChangesetStatus.get_status_lbl(stat)
-        for pr in PullRequest.query().filter(PullRequest.org_repo == self).all():
-            for rev in pr.revisions:
-                pr_id = pr.pull_request_id
-                pr_repo = pr.other_repo.repo_name
-                grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
-
-        for stat in statuses.all():
-            pr_id = pr_repo = None
-            if stat.pull_request:
-                pr_id = stat.pull_request.pull_request_id
-                pr_repo = stat.pull_request.other_repo.repo_name
-            grouped[stat.revision] = [str(stat.status), stat.status_lbl,
-                                      pr_id, pr_repo]
-        return grouped
-
-    def _repo_size(self):
-        from kallithea.lib import helpers as h
-        log.debug('calculating repository size...')
-        return h.format_byte_size(self.scm_instance.size)
-
-    #==========================================================================
-    # SCM CACHE INSTANCE
-    #==========================================================================
-
-    def set_invalidate(self):
-        """
-        Mark caches of this repo as invalid.
-        """
-        CacheInvalidation.set_invalidate(self.repo_name)
-
-    def scm_instance_no_cache(self):
-        return self.__get_instance()
-
-    @property
-    def scm_instance(self):
-        import kallithea
-        full_cache = str2bool(kallithea.CONFIG.get('vcs_full_cache'))
-        if full_cache:
-            return self.scm_instance_cached()
-        return self.__get_instance()
-
-    def scm_instance_cached(self, valid_cache_keys=None):
-        @cache_region('long_term')
-        def _c(repo_name):
-            return self.__get_instance()
-        rn = self.repo_name
-
-        valid = CacheInvalidation.test_and_set_valid(rn, None, valid_cache_keys=valid_cache_keys)
-        if not valid:
-            log.debug('Cache for %s invalidated, getting new object', rn)
-            region_invalidate(_c, None, rn)
-        else:
-            log.debug('Getting obj for %s from cache', rn)
-        return _c(rn)
-
-    def __get_instance(self):
-        repo_full_path = self.repo_full_path
-        try:
-            alias = get_scm(repo_full_path)[0]
-            log.debug('Creating instance of %s repository from %s',
-                      alias, repo_full_path)
-            backend = get_backend(alias)
-        except VCSError:
-            log.error(traceback.format_exc())
-            log.error('Perhaps this repository is in db and not in '
-                      'filesystem run rescan repositories with '
-                      '"destroy old data " option from admin panel')
-            return
-
-        if alias == 'hg':
-
-            repo = backend(safe_str(repo_full_path), create=False,
-                           baseui=self._ui)
-        else:
-            repo = backend(repo_full_path, create=False)
-
-        return repo
-
-    def __json__(self):
-        return dict(landing_rev = self.landing_rev)
-
-class RepoGroup(Base, BaseModel):
-    __tablename__ = 'groups'
-    __table_args__ = (
-        UniqueConstraint('group_name', 'group_parent_id'),
-        CheckConstraint('group_id != group_parent_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    __mapper_args__ = {'order_by': 'group_name'}
-
-    SEP = ' &raquo; '
-
-    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    group_name = Column("group_name", String(255, convert_unicode=False), nullable=False, unique=True, default=None)
-    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
-    group_description = Column("group_description", String(10000, convert_unicode=False), nullable=True, unique=None, default=None)
-    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
-    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
-    parent_group = relationship('RepoGroup', remote_side=group_id)
-    user = relationship('User')
-
-    def __init__(self, group_name='', parent_group=None):
-        self.group_name = group_name
-        self.parent_group = parent_group
-
-    def __unicode__(self):
-        return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
-                                      self.group_name)
-
-    @classmethod
-    def _generate_choice(cls, repo_group):
-        from webhelpers.html import literal as _literal
-        _name = lambda k: _literal(cls.SEP.join(k))
-        return repo_group.group_id, _name(repo_group.full_path_splitted)
-
-    @classmethod
-    def groups_choices(cls, groups=None, show_empty_group=True):
-        if not groups:
-            groups = cls.query().all()
-
-        repo_groups = []
-        if show_empty_group:
-            repo_groups = [('-1', u'-- %s --' % _('top level'))]
-
-        repo_groups.extend([cls._generate_choice(x) for x in groups])
-
-        repo_groups = sorted(repo_groups, key=lambda t: t[1].split(cls.SEP)[0])
-        return repo_groups
-
-    @classmethod
-    def url_sep(cls):
-        return URL_SEP
-
-    @classmethod
-    def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
-        if case_insensitive:
-            gr = cls.query()\
-                .filter(cls.group_name.ilike(group_name))
-        else:
-            gr = cls.query()\
-                .filter(cls.group_name == group_name)
-        if cache:
-            gr = gr.options(FromCache(
-                            "sql_cache_short",
-                            "get_group_%s" % _hash_key(group_name)
-                            )
-            )
-        return gr.scalar()
-
-    @property
-    def parents(self):
-        parents_recursion_limit = 5
-        groups = []
-        if self.parent_group is None:
-            return groups
-        cur_gr = self.parent_group
-        groups.insert(0, cur_gr)
-        cnt = 0
-        while 1:
-            cnt += 1
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            if cnt == parents_recursion_limit:
-                # this will prevent accidental infinite loops
-                log.error('group nested more than %s',
-                          parents_recursion_limit)
-                break
-
-            groups.insert(0, gr)
-        return groups
-
-    @property
-    def children(self):
-        return RepoGroup.query().filter(RepoGroup.parent_group == self)
-
-    @property
-    def name(self):
-        return self.group_name.split(RepoGroup.url_sep())[-1]
-
-    @property
-    def full_path(self):
-        return self.group_name
-
-    @property
-    def full_path_splitted(self):
-        return self.group_name.split(RepoGroup.url_sep())
-
-    @property
-    def repositories(self):
-        return Repository.query()\
-                .filter(Repository.group == self)\
-                .order_by(Repository.repo_name)
-
-    @property
-    def repositories_recursive_count(self):
-        cnt = self.repositories.count()
-
-        def children_count(group):
-            cnt = 0
-            for child in group.children:
-                cnt += child.repositories.count()
-                cnt += children_count(child)
-            return cnt
-
-        return cnt + children_count(self)
-
-    def _recursive_objects(self, include_repos=True):
-        all_ = []
-
-        def _get_members(root_gr):
-            if include_repos:
-                for r in root_gr.repositories:
-                    all_.append(r)
-            childs = root_gr.children.all()
-            if childs:
-                for gr in childs:
-                    all_.append(gr)
-                    _get_members(gr)
-
-        _get_members(self)
-        return [self] + all_
-
-    def recursive_groups_and_repos(self):
-        """
-        Recursive return all groups, with repositories in those groups
-        """
-        return self._recursive_objects()
-
-    def recursive_groups(self):
-        """
-        Returns all children groups for this group including children of children
-        """
-        return self._recursive_objects(include_repos=False)
-
-    def get_new_name(self, group_name):
-        """
-        returns new full group name based on parent and new name
-
-        :param group_name:
-        """
-        path_prefix = (self.parent_group.full_path_splitted if
-                       self.parent_group else [])
-        return RepoGroup.url_sep().join(path_prefix + [group_name])
-
-    def get_api_data(self):
-        """
-        Common function for generating api data
-
-        """
-        group = self
-        data = dict(
-            group_id=group.group_id,
-            group_name=group.group_name,
-            group_description=group.group_description,
-            parent_group=group.parent_group.group_name if group.parent_group else None,
-            repositories=[x.repo_name for x in group.repositories],
-            owner=group.user.username
-        )
-        return data
-
-
-class Permission(Base, BaseModel):
-    __tablename__ = 'permissions'
-    __table_args__ = (
-        Index('p_perm_name_idx', 'permission_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    PERMS = [
-        ('hg.admin', _('Kallithea Administrator')),
-
-        ('repository.none', _('Repository no access')),
-        ('repository.read', _('Repository read access')),
-        ('repository.write', _('Repository write access')),
-        ('repository.admin', _('Repository admin access')),
-
-        ('group.none', _('Repository group no access')),
-        ('group.read', _('Repository group read access')),
-        ('group.write', _('Repository group write access')),
-        ('group.admin', _('Repository group admin access')),
-
-        ('usergroup.none', _('User group no access')),
-        ('usergroup.read', _('User group read access')),
-        ('usergroup.write', _('User group write access')),
-        ('usergroup.admin', _('User group admin access')),
-
-        ('hg.repogroup.create.false', _('Repository Group creation disabled')),
-        ('hg.repogroup.create.true', _('Repository Group creation enabled')),
-
-        ('hg.usergroup.create.false', _('User Group creation disabled')),
-        ('hg.usergroup.create.true', _('User Group creation enabled')),
-
-        ('hg.create.none', _('Repository creation disabled')),
-        ('hg.create.repository', _('Repository creation enabled')),
-        ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
-        ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
-
-        ('hg.fork.none', _('Repository forking disabled')),
-        ('hg.fork.repository', _('Repository forking enabled')),
-
-        ('hg.register.none', _('Registration disabled')),
-        ('hg.register.manual_activate', _('User Registration with manual account activation')),
-        ('hg.register.auto_activate', _('User Registration with automatic account activation')),
-
-        ('hg.extern_activate.manual', _('Manual activation of external account')),
-        ('hg.extern_activate.auto', _('Automatic activation of external account')),
-
-    ]
-
-    #definition of system default permissions for DEFAULT user
-    DEFAULT_USER_PERMISSIONS = [
-        'repository.read',
-        'group.read',
-        'usergroup.read',
-        'hg.create.repository',
-        'hg.create.write_on_repogroup.true',
-        'hg.fork.repository',
-        'hg.register.manual_activate',
-        'hg.extern_activate.auto',
-    ]
-
-    # defines which permissions are more important higher the more important
-    # Weight defines which permissions are more important.
-    # The higher number the more important.
-    PERM_WEIGHTS = {
-        'repository.none': 0,
-        'repository.read': 1,
-        'repository.write': 3,
-        'repository.admin': 4,
-
-        'group.none': 0,
-        'group.read': 1,
-        'group.write': 3,
-        'group.admin': 4,
-
-        'usergroup.none': 0,
-        'usergroup.read': 1,
-        'usergroup.write': 3,
-        'usergroup.admin': 4,
-        'hg.repogroup.create.false': 0,
-        'hg.repogroup.create.true': 1,
-
-        'hg.usergroup.create.false': 0,
-        'hg.usergroup.create.true': 1,
-
-        'hg.fork.none': 0,
-        'hg.fork.repository': 1,
-        'hg.create.none': 0,
-        'hg.create.repository': 1
-    }
-
-    permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    permission_name = Column("permission_name", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    permission_longname = Column("permission_longname", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__, self.permission_id, self.permission_name
-        )
-
-    @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.permission_name == key).scalar()
-
-    @classmethod
-    def get_default_perms(cls, default_user_id):
-        q = Session().query(UserRepoToPerm, Repository, cls)\
-         .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
-         .join((cls, UserRepoToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_group_perms(cls, default_user_id):
-        q = Session().query(UserRepoGroupToPerm, RepoGroup, cls)\
-         .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
-         .join((cls, UserRepoGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserRepoGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-    @classmethod
-    def get_default_user_group_perms(cls, default_user_id):
-        q = Session().query(UserUserGroupToPerm, UserGroup, cls)\
-         .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
-         .join((cls, UserUserGroupToPerm.permission_id == cls.permission_id))\
-         .filter(UserUserGroupToPerm.user_id == default_user_id)
-
-        return q.all()
-
-
-class UserRepoToPerm(Base, BaseModel):
-    __tablename__ = 'repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'repository_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    repository = relationship('Repository')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, repository, permission):
-        n = cls()
-        n.user = user
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.repository)
-
-
-class UserUserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_user_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    user_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, user_group, permission):
-        n = cls()
-        n.user = user
-        n.user_group = user_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.user_group)
-
-
-class UserToPerm(Base, BaseModel):
-    __tablename__ = 'user_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    permission = relationship('Permission', lazy='joined')
-
-    def __unicode__(self):
-        return u'<%s => %s >' % (self.user, self.permission)
-
-
-class UserGroupRepoToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_to_perm'
-    __table_args__ = (
-        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    repository = relationship('Repository')
-
-    @classmethod
-    def create(cls, users_group, repository, permission):
-        n = cls()
-        n.users_group = users_group
-        n.repository = repository
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
-
-
-class UserGroupUserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_group_user_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
-        CheckConstraint('target_user_group_id != user_group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-
-    target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
-    user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, target_user_group, user_group, permission):
-        n = cls()
-        n.target_user_group = target_user_group
-        n.user_group = user_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-    def __unicode__(self):
-        return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
-
-
-class UserGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'permission_id',),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-
-
-class UserRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'user_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relationship('User')
-    group = relationship('RepoGroup')
-    permission = relationship('Permission')
-
-    @classmethod
-    def create(cls, user, repository_group, permission):
-        n = cls()
-        n.user = user
-        n.group = repository_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-
-class UserGroupRepoGroupToPerm(Base, BaseModel):
-    __tablename__ = 'users_group_repo_group_to_perm'
-    __table_args__ = (
-        UniqueConstraint('users_group_id', 'group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    users_group = relationship('UserGroup')
-    permission = relationship('Permission')
-    group = relationship('RepoGroup')
-
-    @classmethod
-    def create(cls, user_group, repository_group, permission):
-        n = cls()
-        n.users_group = user_group
-        n.group = repository_group
-        n.permission = permission
-        Session().add(n)
-        return n
-
-
-class Statistics(Base, BaseModel):
-    __tablename__ = 'statistics'
-    __table_args__ = (
-         UniqueConstraint('repository_id'),
-         {'extend_existing': True, 'mysql_engine': 'InnoDB',
-          'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
-    stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
-    commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
-    commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
-    languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
-
-    repository = relationship('Repository', single_parent=True)
-
-
-class UserFollowing(Base, BaseModel):
-    __tablename__ = 'user_followings'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'follows_repository_id'),
-        UniqueConstraint('user_id', 'follows_user_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-
-    user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
-
-    user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
-
-    follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relationship('Repository', order_by='Repository.repo_name')
-
-    @classmethod
-    def get_repo_followers(cls, repo_id):
-        return cls.query().filter(cls.follows_repo_id == repo_id)
-
-
-class CacheInvalidation(Base, BaseModel):
-    __tablename__ = 'cache_invalidation'
-    __table_args__ = (
-        UniqueConstraint('cache_key'),
-        Index('key_idx', 'cache_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    # cache_id, not used
-    cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    # cache_key as created by _get_cache_key
-    cache_key = Column("cache_key", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    # cache_args is a repo_name
-    cache_args = Column("cache_args", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    # instance sets cache_active True when it is caching,
-    # other instances set cache_active to False to indicate that this cache is invalid
-    cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
-
-    def __init__(self, cache_key, repo_name=''):
-        self.cache_key = cache_key
-        self.cache_args = repo_name
-        self.cache_active = False
-
-    def __unicode__(self):
-        return u"<%s('%s:%s[%s]')>" % (self.__class__.__name__,
-                            self.cache_id, self.cache_key, self.cache_active)
-
-    def _cache_key_partition(self):
-        prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
-        return prefix, repo_name, suffix
-
-    def get_prefix(self):
-        """
-        get prefix that might have been used in _get_cache_key to
-        generate self.cache_key. Only used for informational purposes
-        in repo_edit.html.
-        """
-        # prefix, repo_name, suffix
-        return self._cache_key_partition()[0]
-
-    def get_suffix(self):
-        """
-        get suffix that might have been used in _get_cache_key to
-        generate self.cache_key. Only used for informational purposes
-        in repo_edit.html.
-        """
-        # prefix, repo_name, suffix
-        return self._cache_key_partition()[2]
-
-    @classmethod
-    def clear_cache(cls):
-        """
-        Delete all cache keys from database.
-        Should only be run when all instances are down and all entries thus stale.
-        """
-        cls.query().delete()
-        Session().commit()
-
-    @classmethod
-    def _get_cache_key(cls, key):
-        """
-        Wrapper for generating a unique cache key for this instance and "key".
-        key must / will start with a repo_name which will be stored in .cache_args .
-        """
-        import kallithea
-        prefix = kallithea.CONFIG.get('instance_id', '')
-        return "%s%s" % (prefix, key)
-
-    @classmethod
-    def set_invalidate(cls, repo_name, delete=False):
-        """
-        Mark all caches of a repo as invalid in the database.
-        """
-        inv_objs = Session().query(cls).filter(cls.cache_args == repo_name).all()
-        log.debug('for repo %s got %s invalidation objects',
-                  safe_str(repo_name), inv_objs)
-        try:
-            for inv_obj in inv_objs:
-                log.debug('marking %s key for invalidation based on repo_name=%s',
-                          inv_obj, safe_str(repo_name))
-                if delete:
-                    Session().delete(inv_obj)
-                else:
-                    inv_obj.cache_active = False
-                    Session().add(inv_obj)
-            Session().commit()
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-
-    @classmethod
-    def test_and_set_valid(cls, repo_name, kind, valid_cache_keys=None):
-        """
-        Mark this cache key as active and currently cached.
-        Return True if the existing cache registration still was valid.
-        Return False to indicate that it had been invalidated and caches should be refreshed.
-        """
-
-        key = (repo_name + '_' + kind) if kind else repo_name
-        cache_key = cls._get_cache_key(key)
-
-        if valid_cache_keys and cache_key in valid_cache_keys:
-            return True
-
-        try:
-            inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
-            if not inv_obj:
-                inv_obj = CacheInvalidation(cache_key, repo_name)
-            was_valid = inv_obj.cache_active
-            inv_obj.cache_active = True
-            Session().add(inv_obj)
-            Session().commit()
-            return was_valid
-        except Exception:
-            log.error(traceback.format_exc())
-            Session().rollback()
-            return False
-
-    @classmethod
-    def get_valid_cache_keys(cls):
-        """
-        Return opaque object with information of which caches still are valid
-        and can be used without checking for invalidation.
-        """
-        return set(inv_obj.cache_key for inv_obj in cls.query().filter(cls.cache_active).all())
-
-
-class ChangesetComment(Base, BaseModel):
-    __tablename__ = 'changeset_comments'
-    __table_args__ = (
-        Index('cc_revision_idx', 'revision'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    revision = Column('revision', String(40), nullable=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-    line_no = Column('line_no', Unicode(10), nullable=True)
-    hl_lines = Column('hl_lines', Unicode(512), nullable=True)
-    f_path = Column('f_path', Unicode(1000), nullable=True)
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
-    text = Column('text', UnicodeText(25000), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    @classmethod
-    def get_users(cls, revision=None, pull_request_id=None):
-        """
-        Returns user associated with this ChangesetComment. ie those
-        who actually commented
-
-        :param cls:
-        :param revision:
-        """
-        q = Session().query(User)\
-                .join(ChangesetComment.author)
-        if revision:
-            q = q.filter(cls.revision == revision)
-        elif pull_request_id:
-            q = q.filter(cls.pull_request_id == pull_request_id)
-        return q.all()
-
-
-class ChangesetStatus(Base, BaseModel):
-    __tablename__ = 'changeset_statuses'
-    __table_args__ = (
-        Index('cs_revision_idx', 'revision'),
-        Index('cs_version_idx', 'version'),
-        UniqueConstraint('repo_id', 'revision', 'version'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
-    STATUS_APPROVED = 'approved'
-    STATUS_REJECTED = 'rejected'
-    STATUS_UNDER_REVIEW = 'under_review'
-
-    STATUSES = [
-        (STATUS_NOT_REVIEWED, _("Not Reviewed")),  # (no icon) and default
-        (STATUS_APPROVED, _("Approved")),
-        (STATUS_REJECTED, _("Rejected")),
-        (STATUS_UNDER_REVIEW, _("Under Review")),
-    ]
-
-    changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
-    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    revision = Column('revision', String(40), nullable=False)
-    status = Column('status', String(128), nullable=False, default=DEFAULT)
-    changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
-    modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
-    version = Column('version', Integer(), nullable=False, default=0)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
-
-    author = relationship('User', lazy='joined')
-    repo = relationship('Repository')
-    comment = relationship('ChangesetComment', lazy='joined')
-    pull_request = relationship('PullRequest', lazy='joined')
-
-    def __unicode__(self):
-        return u"<%s('%s:%s')>" % (
-            self.__class__.__name__,
-            self.status, self.author
-        )
-
-    @classmethod
-    def get_status_lbl(cls, value):
-        return dict(cls.STATUSES).get(value)
-
-    @property
-    def status_lbl(self):
-        return ChangesetStatus.get_status_lbl(self.status)
-
-
-class PullRequest(Base, BaseModel):
-    __tablename__ = 'pull_requests'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    # values for .status
-    STATUS_NEW = u'new'
-    STATUS_OPEN = u'open'
-    STATUS_CLOSED = u'closed'
-
-    pull_request_id = Column('pull_request_id', Integer(), nullable=False, primary_key=True)
-    title = Column('title', Unicode(256), nullable=True)
-    description = Column('description', UnicodeText(10240), nullable=True)
-    status = Column('status', Unicode(256), nullable=False, default=STATUS_NEW) # only for closedness, not approve/reject/etc
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    updated_on = Column('updated_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    _revisions = Column('revisions', UnicodeText(20500))  # 500 revisions max
-    org_repo_id = Column('org_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    org_ref = Column('org_ref', Unicode(256), nullable=False)
-    other_repo_id = Column('other_repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    other_ref = Column('other_ref', Unicode(256), nullable=False)
-
-    @hybrid_property
-    def revisions(self):
-        return self._revisions.split(':')
-
-    @revisions.setter
-    def revisions(self, val):
-        self._revisions = ':'.join(val)
-
-    @property
-    def org_ref_parts(self):
-        return self.org_ref.split(':')
-
-    @property
-    def other_ref_parts(self):
-        return self.other_ref.split(':')
-
-    author = relationship('User', lazy='joined')
-    reviewers = relationship('PullRequestReviewers',
-                             cascade="all, delete, delete-orphan")
-    org_repo = relationship('Repository', primaryjoin='PullRequest.org_repo_id==Repository.repo_id')
-    other_repo = relationship('Repository', primaryjoin='PullRequest.other_repo_id==Repository.repo_id')
-    statuses = relationship('ChangesetStatus')
-    comments = relationship('ChangesetComment',
-                             cascade="all, delete, delete-orphan")
-
-    def is_closed(self):
-        return self.status == self.STATUS_CLOSED
-
-    @property
-    def last_review_status(self):
-        return self.statuses[-1].status if self.statuses else ''
-
-    def __json__(self):
-        return dict(
-            revisions=self.revisions
-        )
-
-
-class PullRequestReviewers(Base, BaseModel):
-    __tablename__ = 'pull_request_reviewers'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    def __init__(self, user=None, pull_request=None):
-        self.user = user
-        self.pull_request = pull_request
-
-    pull_requests_reviewers_id = Column('pull_requests_reviewers_id', Integer(), nullable=False, primary_key=True)
-    pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
-
-    user = relationship('User')
-    pull_request = relationship('PullRequest')
-
-
-class Notification(Base, BaseModel):
-    __tablename__ = 'notifications'
-    __table_args__ = (
-        Index('notification_type_idx', 'type'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-
-    TYPE_CHANGESET_COMMENT = u'cs_comment'
-    TYPE_MESSAGE = u'message'
-    TYPE_MENTION = u'mention'
-    TYPE_REGISTRATION = u'registration'
-    TYPE_PULL_REQUEST = u'pull_request'
-    TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
-
-    notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
-    subject = Column('subject', Unicode(512), nullable=True)
-    body = Column('body', UnicodeText(50000), nullable=True)
-    created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    type_ = Column('type', Unicode(256))
-
-    created_by_user = relationship('User')
-    notifications_to_users = relationship('UserNotification', lazy='joined',
-                                          cascade="all, delete, delete-orphan")
-
-    @property
-    def recipients(self):
-        return [x.user for x in UserNotification.query()\
-                .filter(UserNotification.notification == self)\
-                .order_by(UserNotification.user_id.asc()).all()]
-
-    @classmethod
-    def create(cls, created_by, subject, body, recipients, type_=None):
-        if type_ is None:
-            type_ = Notification.TYPE_MESSAGE
-
-        notification = cls()
-        notification.created_by_user = created_by
-        notification.subject = subject
-        notification.body = body
-        notification.type_ = type_
-        notification.created_on = datetime.datetime.now()
-
-        for u in recipients:
-            assoc = UserNotification()
-            assoc.notification = notification
-            u.notifications.append(assoc)
-        Session().add(notification)
-        return notification
-
-    @property
-    def description(self):
-        from kallithea.model.notification import NotificationModel
-        return NotificationModel().make_description(self)
-
-
-class UserNotification(Base, BaseModel):
-    __tablename__ = 'user_to_notification'
-    __table_args__ = (
-        UniqueConstraint('user_id', 'notification_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
-    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
-    read = Column('read', Boolean, default=False)
-    sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
-
-    user = relationship('User', lazy="joined")
-    notification = relationship('Notification', lazy="joined",
-                                order_by=lambda: Notification.created_on.desc(),)
-
-    def mark_as_read(self):
-        self.read = True
-        Session().add(self)
-
-
-class Gist(Base, BaseModel):
-    __tablename__ = 'gists'
-    __table_args__ = (
-        Index('g_gist_access_id_idx', 'gist_access_id'),
-        Index('g_created_on_idx', 'created_on'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
-    )
-    GIST_PUBLIC = u'public'
-    GIST_PRIVATE = u'private'
-    DEFAULT_FILENAME = u'gistfile1.txt'
-
-    gist_id = Column('gist_id', Integer(), primary_key=True)
-    gist_access_id = Column('gist_access_id', Unicode(250))
-    gist_description = Column('gist_description', UnicodeText(1024))
-    gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
-    gist_expires = Column('gist_expires', Float(53), nullable=False)
-    gist_type = Column('gist_type', Unicode(128), nullable=False)
-    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-
-    owner = relationship('User')
-
-    def __repr__(self):
-        return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
-
-    @classmethod
-    def get_or_404(cls, id_):
-        res = cls.query().filter(cls.gist_access_id == id_).scalar()
-        if not res:
-            raise HTTPNotFound
-        return res
-
-    @classmethod
-    def get_by_access_id(cls, gist_access_id):
-        return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
-
-    def gist_url(self):
-        import kallithea
-        alias_url = kallithea.CONFIG.get('gist_alias_url')
-        if alias_url:
-            return alias_url.replace('{gistid}', self.gist_access_id)
-
-        import kallithea.lib.helpers as h
-        return h.canonical_url('gist', gist_id=self.gist_access_id)
-
-    @classmethod
-    def base_path(cls):
-        """
-        Returns base path when all gists are stored
-
-        :param cls:
-        """
-        from kallithea.model.gist import GIST_STORE_LOC
-        q = Session().query(Ui)\
-            .filter(Ui.ui_key == URL_SEP)
-        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
-        return os.path.join(q.one().ui_value, GIST_STORE_LOC)
-
-    def get_api_data(self):
-        """
-        Common function for generating gist related data for API
-        """
-        gist = self
-        data = dict(
-            gist_id=gist.gist_id,
-            type=gist.gist_type,
-            access_id=gist.gist_access_id,
-            description=gist.gist_description,
-            url=gist.gist_url(),
-            expires=gist.gist_expires,
-            created_on=gist.created_on,
-        )
-        return data
-
-    def __json__(self):
-        data = dict(
-        )
-        data.update(self.get_api_data())
-        return data
-    ## SCM functions
-
-    @property
-    def scm_instance(self):
-        from kallithea.lib.vcs import get_repo
-        base_path = self.base_path()
-        return get_repo(os.path.join(*map(safe_str,
-                                          [base_path, self.gist_access_id])))
-
-
-class DbMigrateVersion(Base, BaseModel):
-    __tablename__ = 'db_migrate_version'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    repository_id = Column('repository_id', String(250), primary_key=True)
-    repository_path = Column('repository_path', Text)
-    version = Column('version', Integer)
--- a/kallithea/lib/dbmigrate/versions/001_initial_release.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,207 +0,0 @@
-#==============================================================================
-# DB INITIAL MODEL
-#==============================================================================
-import logging
-import datetime
-
-from sqlalchemy import *
-from sqlalchemy.exc import DatabaseError
-from sqlalchemy.orm import relation
-from sqlalchemy.orm.session import Session
-from kallithea.model.meta import Base
-
-from kallithea.lib.dbmigrate.migrate import *
-
-from kallithea import DB_PREFIX
-
-log = logging.getLogger(__name__)
-
-class Setting(Base):
-    __tablename__ = DB_PREFIX + 'settings'
-    __table_args__ = (UniqueConstraint('app_settings_name'), {'useexisting':True})
-    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    app_settings_name = Column("app_settings_name", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    app_settings_value = Column("app_settings_value", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __init__(self, k, v):
-        self.app_settings_name = k
-        self.app_settings_value = v
-
-    def __repr__(self):
-        return "<Setting('%s:%s')>" % (self.app_settings_name,
-                                                self.app_settings_value)
-
-class Ui(Base):
-    __tablename__ = DB_PREFIX + 'ui'
-    __table_args__ = {'useexisting':True}
-    ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    ui_section = Column("ui_section", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_key = Column("ui_key", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_value = Column("ui_value", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
-
-
-class User(Base):
-    __tablename__ = 'users'
-    __table_args__ = (UniqueConstraint('username'), UniqueConstraint('email'), {'useexisting':True})
-    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    username = Column("username", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    password = Column("password", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    active = Column("active", Boolean(), nullable=True, unique=None, default=None)
-    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
-    name = Column("name", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    lastname = Column("lastname", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    email = Column("email", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
-    is_ldap = Column("is_ldap", Boolean(), nullable=False, unique=None, default=False)
-
-    user_log = relation('UserLog', cascade='all')
-    user_perms = relation('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
-
-    repositories = relation('Repository')
-    user_followers = relation('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
-
-    @property
-    def full_contact(self):
-        return '%s %s <%s>' % (self.name, self.lastname, self.email)
-
-    def __repr__(self):
-        return "<User('id:%s:%s')>" % (self.user_id, self.username)
-
-    def update_lastlogin(self):
-        """Update user lastlogin"""
-
-        try:
-            session = Session.object_session(self)
-            self.last_login = datetime.datetime.now()
-            session.add(self)
-            session.commit()
-            log.debug('updated user %s lastlogin', self.username)
-        except (DatabaseError,):
-            session.rollback()
-
-
-class UserLog(Base):
-    __tablename__ = 'user_logs'
-    __table_args__ = {'useexisting':True}
-    user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey(u'users.user_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(length=None, convert_unicode=False, assert_unicode=None), ForeignKey(u'repositories.repo_id'), nullable=False, unique=None, default=None)
-    repository_name = Column("repository_name", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    user_ip = Column("user_ip", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action = Column("action", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
-
-    user = relation('User')
-    repository = relation('Repository')
-
-class Repository(Base):
-    __tablename__ = 'repositories'
-    __table_args__ = (UniqueConstraint('repo_name'), {'useexisting':True},)
-    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repo_name = Column("repo_name", String(length=None, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
-    repo_type = Column("repo_type", String(length=None, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
-    user_id = Column("user_id", Integer(), ForeignKey(u'users.user_id'), nullable=False, unique=False, default=None)
-    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
-    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
-    description = Column("description", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    fork_id = Column("fork_id", Integer(), ForeignKey(u'repositories.repo_id'), nullable=True, unique=False, default=None)
-
-    user = relation('User')
-    fork = relation('Repository', remote_side=repo_id)
-    repo_to_perm = relation('UserRepoToPerm', cascade='all')
-    stats = relation('Statistics', cascade='all', uselist=False)
-
-    repo_followers = relation('UserFollowing', primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', cascade='all')
-
-
-    def __repr__(self):
-        return "<Repository('%s:%s')>" % (self.repo_id, self.repo_name)
-
-class Permission(Base):
-    __tablename__ = 'permissions'
-    __table_args__ = {'useexisting':True}
-    permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    permission_name = Column("permission_name", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    permission_longname = Column("permission_longname", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-
-    def __repr__(self):
-        return "<Permission('%s:%s')>" % (self.permission_id, self.permission_name)
-
-class UserRepoToPerm(Base):
-    __tablename__ = 'repo_to_perm'
-    __table_args__ = (UniqueConstraint('user_id', 'repository_id'), {'useexisting':True})
-    repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey(u'users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey(u'permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column("repository_id", Integer(), ForeignKey(u'repositories.repo_id'), nullable=False, unique=None, default=None)
-
-    user = relation('User')
-    permission = relation('Permission')
-    repository = relation('Repository')
-
-class UserToPerm(Base):
-    __tablename__ = 'user_to_perm'
-    __table_args__ = (UniqueConstraint('user_id', 'permission_id'), {'useexisting':True})
-    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey(u'users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column("permission_id", Integer(), ForeignKey(u'permissions.permission_id'), nullable=False, unique=None, default=None)
-
-    user = relation('User')
-    permission = relation('Permission')
-
-class Statistics(Base):
-    __tablename__ = 'statistics'
-    __table_args__ = (UniqueConstraint('repository_id'), {'useexisting':True})
-    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    repository_id = Column("repository_id", Integer(), ForeignKey(u'repositories.repo_id'), nullable=False, unique=True, default=None)
-    stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
-    commit_activity = Column("commit_activity", LargeBinary(), nullable=False)#JSON data
-    commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
-    languages = Column("languages", LargeBinary(), nullable=False)#JSON data
-
-    repository = relation('Repository', single_parent=True)
-
-class UserFollowing(Base):
-    __tablename__ = 'user_followings'
-    __table_args__ = (UniqueConstraint('user_id', 'follows_repository_id'),
-                      UniqueConstraint('user_id', 'follows_user_id')
-                      , {'useexisting':True})
-
-    user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    user_id = Column("user_id", Integer(), ForeignKey(u'users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey(u'repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column("follows_user_id", Integer(), ForeignKey(u'users.user_id'), nullable=True, unique=None, default=None)
-
-    user = relation('User', primaryjoin='User.user_id==UserFollowing.user_id')
-
-    follows_user = relation('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relation('Repository')
-
-
-class CacheInvalidation(Base):
-    __tablename__ = 'cache_invalidation'
-    __table_args__ = (UniqueConstraint('cache_key'), {'useexisting':True})
-    cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
-    cache_key = Column("cache_key", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    cache_args = Column("cache_args", String(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
-
-
-    def __init__(self, cache_key, cache_args=''):
-        self.cache_key = cache_key
-        self.cache_args = cache_args
-        self.cache_active = False
-
-    def __repr__(self):
-        return "<CacheInvalidation('%s:%s')>" % (self.cache_id, self.cache_key)
-
-
-def upgrade(migrate_engine):
-    # Upgrade operations go here. Don't create your own engine; bind migrate_engine
-    # to your metadata
-    Base.metadata.create_all(bind=migrate_engine, checkfirst=False)
-
-def downgrade(migrate_engine):
-    # Operations to reverse the above upgrade go here.
-    Base.metadata.drop_all(bind=migrate_engine, checkfirst=False)
--- a/kallithea/lib/dbmigrate/versions/002_version_1_1_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,80 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """ Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-
-    #==========================================================================
-    # Upgrade of `users` table
-    #==========================================================================
-    tblname = 'users'
-    tbl = Table(tblname, MetaData(bind=migrate_engine), autoload=True,
-                    autoload_with=migrate_engine)
-
-    #ADD is_ldap column
-    is_ldap = Column("is_ldap", Boolean(), nullable=True,
-                     unique=None, default=False)
-    is_ldap.create(tbl, populate_default=True)
-    is_ldap.alter(nullable=False)
-
-    #==========================================================================
-    # Upgrade of `user_logs` table
-    #==========================================================================
-
-    tblname = 'users'
-    tbl = Table(tblname, MetaData(bind=migrate_engine), autoload=True,
-                    autoload_with=migrate_engine)
-
-    #ADD revision column
-    revision = Column('revision', TEXT(length=None, convert_unicode=False,
-                                       assert_unicode=None),
-                      nullable=True, unique=None, default=None)
-    revision.create(tbl)
-
-    #==========================================================================
-    # Upgrade of `repositories` table
-    #==========================================================================
-    tblname = 'repositories'
-    tbl = Table(tblname, MetaData(bind=migrate_engine), autoload=True,
-                    autoload_with=migrate_engine)
-
-    #ADD repo_type column#
-    repo_type = Column("repo_type", String(length=None, convert_unicode=False,
-                                           assert_unicode=None),
-                       nullable=True, unique=False, default='hg')
-
-    repo_type.create(tbl, populate_default=True)
-    #repo_type.alter(nullable=False)
-
-    #ADD statistics column#
-    enable_statistics = Column("statistics", Boolean(), nullable=True,
-                               unique=None, default=True)
-    enable_statistics.create(tbl)
-
-    #==========================================================================
-    # Add table `user_followings`
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_1_0 import UserFollowing
-    UserFollowing().__table__.create()
-
-    #==========================================================================
-    # Add table `cache_invalidation`
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_1_0 import CacheInvalidation
-    CacheInvalidation().__table__.create()
-
-    return
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
--- a/kallithea/lib/dbmigrate/versions/003_version_1_2_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,114 +0,0 @@
-import logging
-import datetime
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """ Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-
-    #==========================================================================
-    # Add table `groups``
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_2_0 import Group as Group
-    Group().__table__.create()
-
-    #==========================================================================
-    # Add table `group_to_perm`
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_2_0 import UserRepoGroupToPerm
-    UserRepoGroupToPerm().__table__.create()
-
-    #==========================================================================
-    # Add table `users_groups`
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_2_0 import UserGroup
-    UserGroup().__table__.create()
-
-    #==========================================================================
-    # Add table `users_groups_members`
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_2_0 import UserGroupMember
-    UserGroupMember().__table__.create()
-
-    #==========================================================================
-    # Add table `users_group_repo_to_perm`
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_2_0 import UserGroupRepoToPerm
-    UserGroupRepoToPerm().__table__.create()
-
-    #==========================================================================
-    # Add table `users_group_to_perm`
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_2_0 import UserGroupToPerm
-    UserGroupToPerm().__table__.create()
-
-    #==========================================================================
-    # Upgrade of `users` table
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_2_0 import User
-
-    #add column
-    ldap_dn = Column("ldap_dn", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    ldap_dn.create(User().__table__)
-
-    api_key = Column("api_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
-    api_key.create(User().__table__)
-
-    #remove old column
-    is_ldap = Column("is_ldap", Boolean(), nullable=False, unique=None, default=False)
-    is_ldap.drop(User().__table__)
-
-    #==========================================================================
-    # Upgrade of `repositories` table
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_2_0 import Repository
-
-    #ADD clone_uri column#
-
-    clone_uri = Column("clone_uri", String(length=255, convert_unicode=False,
-                                           assert_unicode=None),
-                        nullable=True, unique=False, default=None)
-
-    clone_uri.create(Repository().__table__)
-
-    #ADD downloads column#
-    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
-    enable_downloads.create(Repository().__table__)
-
-    #ADD column created_on
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True,
-                        unique=None, default=datetime.datetime.now)
-    created_on.create(Repository().__table__)
-
-    #ADD group_id column#
-    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'),
-                  nullable=True, unique=False, default=None)
-
-    group_id.create(Repository().__table__)
-
-    #==========================================================================
-    # Upgrade of `user_followings` table
-    #==========================================================================
-
-    from kallithea.lib.dbmigrate.schema.db_1_2_0 import UserFollowing
-
-    follows_from = Column('follows_from', DateTime(timezone=False),
-                          nullable=True, unique=None,
-                          default=datetime.datetime.now)
-    follows_from.create(UserFollowing().__table__)
-
-    return
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
--- a/kallithea/lib/dbmigrate/versions/004_version_1_3_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,69 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """ Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    #==========================================================================
-    # Add table `users_group_repo_group_to_perm`
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_3_0 import UserGroupRepoGroupToPerm
-    UserGroupRepoGroupToPerm().__table__.create()
-
-    #==========================================================================
-    # Add table `changeset_comments`
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_3_0 import ChangesetComment
-    ChangesetComment().__table__.create()
-
-    #==========================================================================
-    # Add table `notifications`
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_3_0 import Notification
-    Notification().__table__.create()
-
-    #==========================================================================
-    # Add table `user_to_notification`
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_3_0 import UserNotification
-    UserNotification().__table__.create()
-
-    #==========================================================================
-    # Add unique to table `users_group_to_perm`
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_3_0 import UserGroupToPerm
-    tbl = UserGroupToPerm().__table__
-    cons = UniqueConstraint('users_group_id', 'permission_id', table=tbl)
-    cons.create()
-
-    #==========================================================================
-    # Fix unique constrain on table `user_logs`
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_3_0 import UserLog
-    tbl = UserLog().__table__
-    col = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'),
-                 nullable=False, unique=None, default=None)
-    col.alter(nullable=True, table=tbl)
-
-    #==========================================================================
-    # Rename table `group_to_perm` to `user_repo_group_to_perm`
-    #==========================================================================
-    tbl = Table('group_to_perm', MetaData(bind=migrate_engine), autoload=True,
-                    autoload_with=migrate_engine)
-    tbl.rename('user_repo_group_to_perm')
-
-    return
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
--- a/kallithea/lib/dbmigrate/versions/005_version_1_3_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,74 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """ Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-
-    #==========================================================================
-    # Change unique constraints of table `repo_to_perm`
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_3_0 import UserRepoToPerm
-    tbl = UserRepoToPerm().__table__
-    new_cons = UniqueConstraint('user_id', 'repository_id', 'permission_id', table=tbl)
-    new_cons.create()
-    old_cons = None
-    if migrate_engine.name in ['mysql']:
-        old_cons = UniqueConstraint('user_id', 'repository_id', table=tbl, name="user_id")
-    elif migrate_engine.name in ['postgresql']:
-        old_cons = UniqueConstraint('user_id', 'repository_id', table=tbl)
-    else:
-        # sqlite doesn't support dropping constraints...
-        print """Please manually drop UniqueConstraint('user_id', 'repository_id')"""
-
-    if old_cons:
-        try:
-            old_cons.drop()
-        except Exception as e:
-            # we don't care if this fails really... better to pass migration than
-            # leave this in intermidiate state
-            print 'Failed to remove Unique for user_id, repository_id reason %s' % e
-
-
-    #==========================================================================
-    # fix uniques of table `user_repo_group_to_perm`
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_3_0 import UserRepoGroupToPerm
-    tbl = UserRepoGroupToPerm().__table__
-    new_cons = UniqueConstraint('group_id', 'permission_id', 'user_id', table=tbl)
-    new_cons.create()
-    old_cons = None
-
-    # fix uniqueConstraints
-    if migrate_engine.name in ['mysql']:
-        #mysql is givinig troubles here...
-        old_cons = UniqueConstraint('group_id', 'permission_id', table=tbl, name="group_id")
-    elif migrate_engine.name in ['postgresql']:
-        old_cons = UniqueConstraint('group_id', 'permission_id', table=tbl, name='group_to_perm_group_id_permission_id_key')
-    else:
-        # sqlite doesn't support dropping constraints...
-        print """Please manually drop UniqueConstraint('group_id', 'permission_id')"""
-
-    if old_cons:
-        try:
-            old_cons.drop()
-        except Exception as e:
-            # we don't care if this fails really... better to pass migration than
-            # leave this in intermidiate state
-            print 'Failed to remove Unique for user_id, repository_id reason %s' % e
-
-    return
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
--- a/kallithea/lib/dbmigrate/versions/006_version_1_4_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,171 +0,0 @@
-import logging
-import datetime
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.lib.dbmigrate.versions import _reset_base
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-
-    #==========================================================================
-    # USEREMAILMAP
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_4_0 import UserEmailMap
-    tbl = UserEmailMap.__table__
-    tbl.create()
-    #==========================================================================
-    # PULL REQUEST
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_4_0 import PullRequest
-    tbl = PullRequest.__table__
-    tbl.create()
-
-    #==========================================================================
-    # PULL REQUEST REVIEWERS
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_4_0 import PullRequestReviewers
-    tbl = PullRequestReviewers.__table__
-    tbl.create()
-
-    #==========================================================================
-    # CHANGESET STATUS
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_4_0 import ChangesetStatus
-    tbl = ChangesetStatus.__table__
-    tbl.create()
-
-    _reset_base(migrate_engine)
-
-    #==========================================================================
-    # USERS TABLE
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_3_0 import User
-    tbl = User.__table__
-
-    # change column name -> firstname
-    col = User.__table__.columns.name
-    col.alter(index=Index('u_username_idx', 'username'))
-    col.alter(index=Index('u_email_idx', 'email'))
-    col.alter(name="firstname", table=tbl)
-
-    # add inherit_default_permission column
-    inherit_default_permissions = Column("inherit_default_permissions",
-                                         Boolean(), nullable=True, unique=None,
-                                         default=True)
-    inherit_default_permissions.create(table=tbl)
-    inherit_default_permissions.alter(nullable=False, default=True, table=tbl)
-
-    #==========================================================================
-    # USERS GROUP TABLE
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_3_0 import UserGroup
-    tbl = UserGroup.__table__
-    # add inherit_default_permission column
-    gr_inherit_default_permissions = Column(
-                                    "users_group_inherit_default_permissions",
-                                    Boolean(), nullable=True, unique=None,
-                                    default=True)
-    gr_inherit_default_permissions.create(table=tbl)
-    gr_inherit_default_permissions.alter(nullable=False, default=True, table=tbl)
-
-    #==========================================================================
-    # REPOSITORIES
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_3_0 import Repository
-    tbl = Repository.__table__
-
-    # add enable locking column
-    enable_locking = Column("enable_locking", Boolean(), nullable=True,
-                            unique=None, default=False)
-    enable_locking.create(table=tbl)
-    enable_locking.alter(nullable=False, default=False, table=tbl)
-
-    # add locked column
-    _locked = Column("locked", String(255), nullable=True, unique=False,
-                     default=None)
-    _locked.create(table=tbl)
-
-    #add langing revision column
-    landing_rev = Column("landing_revision", String(255), nullable=True,
-                         unique=False, default='tip')
-    landing_rev.create(table=tbl)
-    landing_rev.alter(nullable=False, default='tip', table=tbl)
-
-    #==========================================================================
-    # GROUPS
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_3_0 import RepoGroup
-    tbl = RepoGroup.__table__
-
-    # add enable locking column
-    enable_locking = Column("enable_locking", Boolean(), nullable=True,
-                            unique=None, default=False)
-    enable_locking.create(table=tbl)
-    enable_locking.alter(nullable=False, default=False)
-
-    #==========================================================================
-    # CACHE INVALIDATION
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_3_0 import CacheInvalidation
-    tbl = CacheInvalidation.__table__
-
-    # add INDEX for cache keys
-    col = CacheInvalidation.__table__.columns.cache_key
-    col.alter(index=Index('key_idx', 'cache_key'))
-
-    #==========================================================================
-    # NOTIFICATION
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_3_0 import Notification
-    tbl = Notification.__table__
-
-    # add index for notification type
-    col = Notification.__table__.columns.type
-    col.alter(index=Index('notification_type_idx', 'type'),)
-
-    #==========================================================================
-    # CHANGESET_COMMENTS
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_3_0 import ChangesetComment
-
-    tbl = ChangesetComment.__table__
-    col = ChangesetComment.__table__.columns.revision
-
-    # add index for revisions
-    col.alter(index=Index('cc_revision_idx', 'revision'),)
-
-    # add hl_lines column
-    hl_lines = Column('hl_lines', Unicode(512), nullable=True)
-    hl_lines.create(table=tbl)
-
-    # add created_on column
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True,
-                        default=datetime.datetime.now)
-    created_on.create(table=tbl)
-    created_on.alter(nullable=False, default=datetime.datetime.now)
-
-    modified_at = Column('modified_at', DateTime(timezone=False), nullable=False,
-                         default=datetime.datetime.now)
-    modified_at.alter(type=DateTime(timezone=False), table=tbl)
-
-    # add FK to pull_request
-    pull_request_id = Column("pull_request_id", Integer(),
-                             ForeignKey('pull_requests.pull_request_id'),
-                             nullable=True)
-    pull_request_id.create(table=tbl)
-    _reset_base(migrate_engine)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
--- a/kallithea/lib/dbmigrate/versions/007_version_1_4_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,44 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-
-    #==========================================================================
-    # CHANGESET_COMMENTS
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_4_0 import ChangesetComment
-    tbl_name = ChangesetComment.__tablename__
-    tbl = Table(tbl_name,
-                MetaData(bind=migrate_engine), autoload=True,
-                autoload_with=migrate_engine)
-    col = tbl.columns.revision
-
-    # remove nullability from revision field
-    col.alter(nullable=True)
-
-    #==========================================================================
-    # REPOSITORY
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_4_0 import Repository
-    tbl = Repository.__table__
-    updated_on = Column('updated_on', DateTime(timezone=False),
-                        nullable=True, unique=None)
-    # create created on column for future lightweight main page
-    updated_on.create(table=tbl)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
--- a/kallithea/lib/dbmigrate/versions/008_version_1_5_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,123 +0,0 @@
-import logging
-
-from sqlalchemy import *
-from sqlalchemy.orm import joinedload
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_1_5_0
-    #==========================================================================
-    # USER LOGS
-    #==========================================================================
-
-    tbl = db_1_5_0.UserLog.__table__
-    username = Column("username", String(255, convert_unicode=False,
-                                         assert_unicode=None), nullable=True,
-                      unique=None, default=None)
-    # create username column
-    username.create(table=tbl)
-
-    _Session = meta.Session()
-    ## after adding that column fix all usernames
-    users_log = _Session.query(db_1_5_0.UserLog)\
-            .options(joinedload(db_1_5_0.UserLog.user))\
-            .options(joinedload(db_1_5_0.UserLog.repository)).all()
-
-    for entry in users_log:
-        entry.username = entry.user.username
-        _Session.add(entry)
-    _Session.commit()
-
-    #alter username to not null
-    tbl_name = db_1_5_0.UserLog.__tablename__
-    tbl = Table(tbl_name,
-                MetaData(bind=migrate_engine), autoload=True,
-                autoload_with=migrate_engine)
-    col = tbl.columns.username
-
-    # remove nullability from revision field
-    col.alter(nullable=False)
-
-    # issue fixups
-    fixups(db_1_5_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    # ** create default permissions ** #
-    #=====================================
-    for p in models.Permission.PERMS:
-        if not models.Permission.get_by_key(p[0]):
-            new_perm = models.Permission()
-            new_perm.permission_name = p[0]
-            new_perm.permission_longname = p[0]  #translation err with p[1]
-            print 'Creating new permission %s' % p[0]
-            _SESSION().add(new_perm)
-
-    _SESSION().commit()
-
-    # ** populate default permissions ** #
-    #=====================================
-
-    user = models.User.query().filter(models.User.username == 'default').scalar()
-
-    def _make_perm(perm):
-        new_perm = models.UserToPerm()
-        new_perm.user = user
-        new_perm.permission = models.Permission.get_by_key(perm)
-        return new_perm
-
-    def _get_group(perm_name):
-        return '.'.join(perm_name.split('.')[:1])
-
-    perms = models.UserToPerm.query().filter(models.UserToPerm.user == user).all()
-    defined_perms_groups = map(_get_group,
-                              (x.permission.permission_name for x in perms))
-    log.debug('GOT ALREADY DEFINED:%s', perms)
-    DEFAULT_PERMS = models.Permission.DEFAULT_USER_PERMISSIONS
-
-    # for every default permission that needs to be created, we check if
-    # it's group is already defined, if it's not we create default perm
-    for perm_name in DEFAULT_PERMS:
-        gr = _get_group(perm_name)
-        if gr not in defined_perms_groups:
-            log.debug('GR:%s not found, creating permission %s',
-                      gr, perm_name)
-            new_perm = _make_perm(perm_name)
-            _SESSION().add(new_perm)
-    _SESSION().commit()
-
-    # ** create default options ** #
-    #===============================
-    skip_existing = True
-    for k, v in [
-        ('default_repo_enable_locking',  False),
-        ('default_repo_enable_downloads', False),
-        ('default_repo_enable_statistics', False),
-        ('default_repo_private', False),
-        ('default_repo_type', 'hg')]:
-
-        if skip_existing and models.Setting.get_by_name(k) is not None:
-            log.debug('Skipping option %s', k)
-            continue
-        setting = models.Setting(k, v)
-        _SESSION().add(setting)
-
-    _SESSION().commit()
--- a/kallithea/lib/dbmigrate/versions/009_version_1_5_1.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,21 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    pass
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
--- a/kallithea/lib/dbmigrate/versions/010_version_1_5_2.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,50 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base, notify
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_1_5_2
-    #==========================================================================
-    # USER LOGS
-    #==========================================================================
-    tbl = db_1_5_2.UserIpMap.__table__
-    tbl.create()
-
-    #==========================================================================
-    # REPOSITORIES
-    #==========================================================================
-    tbl = db_1_5_2.Repository.__table__
-    changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True)
-    # create username column
-    changeset_cache.create(table=tbl)
-
-    # issue fixups
-    fixups(db_1_5_2, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    notify('Upgrading repositories Caches')
-    repositories = models.Repository.getAll()
-    for repo in repositories:
-        print repo
-        repo.update_changeset_cache()
-        _SESSION().commit()
--- a/kallithea/lib/dbmigrate/versions/011_version_1_6_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,43 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base, notify
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_1_6_0
-
-    #==========================================================================
-    # USER LOGS
-    #==========================================================================
-    tbl = db_1_6_0.RepositoryField.__table__
-    tbl.create()
-
-    # issue fixups
-    fixups(db_1_6_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    notify('Upgrading repositories Caches')
-    repositories = models.Repository.getAll()
-    for repo in repositories:
-        print repo
-        repo.update_changeset_cache()
-        _SESSION().commit()
--- a/kallithea/lib/dbmigrate/versions/012_version_1_7_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,144 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_1_7_0
-
-    #==========================================================================
-    # UserUserGroupToPerm
-    #==========================================================================
-    tbl = db_1_7_0.UserUserGroupToPerm.__table__
-    tbl.create()
-
-    #==========================================================================
-    # UserGroupUserGroupToPerm
-    #==========================================================================
-    tbl = db_1_7_0.UserGroupUserGroupToPerm.__table__
-    tbl.create()
-
-    #==========================================================================
-    # Gist
-    #==========================================================================
-    tbl = db_1_7_0.Gist.__table__
-    tbl.create()
-
-    #==========================================================================
-    # UserGroup
-    #==========================================================================
-    tbl = db_1_7_0.UserGroup.__table__
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'),
-                     nullable=True, unique=False, default=None)
-    # create username column
-    user_id.create(table=tbl)
-
-    #==========================================================================
-    # RepoGroup
-    #==========================================================================
-    tbl = db_1_7_0.RepoGroup.__table__
-    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'),
-                     nullable=True, unique=False, default=None)
-    # create username column
-    user_id.create(table=tbl)
-
-    # issue fixups
-    fixups(db_1_7_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    # ** create default permissions ** #
-    #=====================================
-    for p in models.Permission.PERMS:
-        if not models.Permission.get_by_key(p[0]):
-            new_perm = models.Permission()
-            new_perm.permission_name = p[0]
-            new_perm.permission_longname = p[0]  #translation err with p[1]
-            _SESSION().add(new_perm)
-
-    _SESSION().commit()
-
-    # ** populate default permissions ** #
-    #=====================================
-
-    user = models.User.query().filter(models.User.username == 'default').scalar()
-
-    def _make_perm(perm):
-        new_perm = models.UserToPerm()
-        new_perm.user = user
-        new_perm.permission = models.Permission.get_by_key(perm)
-        return new_perm
-
-    def _get_group(perm_name):
-        return '.'.join(perm_name.split('.')[:1])
-
-    perms = models.UserToPerm.query().filter(models.UserToPerm.user == user).all()
-    defined_perms_groups = map(_get_group,
-                              (x.permission.permission_name for x in perms))
-    log.debug('GOT ALREADY DEFINED:%s', perms)
-    DEFAULT_PERMS = models.Permission.DEFAULT_USER_PERMISSIONS
-
-    # for every default permission that needs to be created, we check if
-    # it's group is already defined, if it's not we create default perm
-    for perm_name in DEFAULT_PERMS:
-        gr = _get_group(perm_name)
-        if gr not in defined_perms_groups:
-            log.debug('GR:%s not found, creating permission %s',
-                      gr, perm_name)
-            new_perm = _make_perm(perm_name)
-            _SESSION().add(new_perm)
-    _SESSION().commit()
-
-    #fix all usergroups
-
-    def _create_default_perms(user_group):
-        # create default permission
-        default_perm = 'usergroup.read'
-        def_user = models.User.get_default_user()
-        for p in def_user.user_perms:
-            if p.permission.permission_name.startswith('usergroup.'):
-                default_perm = p.permission.permission_name
-                break
-
-        user_group_to_perm = models.UserUserGroupToPerm()
-        user_group_to_perm.permission = models.Permission.get_by_key(default_perm)
-
-        user_group_to_perm.user_group = user_group
-        user_group_to_perm.user_id = def_user.user_id
-        return user_group_to_perm
-
-    for ug in models.UserGroup.get_all():
-        perm_obj = _create_default_perms(ug)
-        _SESSION().add(perm_obj)
-    _SESSION().commit()
-
-    adm = models.User.get_first_admin()
-    # fix owners of UserGroup
-    for ug in _SESSION().query(models.UserGroup).all():
-        ug.user_id = adm.user_id
-        _SESSION().add(ug)
-    _SESSION().commit()
-
-    # fix owners of RepoGroup
-    for ug in _SESSION().query(models.RepoGroup).all():
-        ug.user_id = adm.user_id
-        _SESSION().add(ug)
-    _SESSION().commit()
--- a/kallithea/lib/dbmigrate/versions/013_version_1_7_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,40 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.lib.dbmigrate.versions import _reset_base
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-
-
-    #==========================================================================
-    # UserGroup
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_7_0 import UserGroup
-    tbl = UserGroup.__table__
-    user_id = tbl.columns.user_id
-    user_id.alter(nullable=False)
-
-    #==========================================================================
-    # RepoGroup
-    #==========================================================================
-    from kallithea.lib.dbmigrate.schema.db_1_7_0 import RepoGroup
-    tbl = RepoGroup.__table__
-    user_id = tbl.columns.user_id
-    user_id.alter(nullable=False)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
--- a/kallithea/lib/dbmigrate/versions/014_version_1_7_1.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,45 +0,0 @@
-import logging
-import datetime
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_1_7_0
-
-    #==========================================================================
-    # Gist
-    #==========================================================================
-    tbl = db_1_7_0.Gist.__table__
-    user_id = tbl.columns.gist_expires
-    user_id.alter(type=Float(53))
-
-    # issue fixups
-    fixups(db_1_7_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    # fix nullable columns on last_update
-    for r in models.Repository().get_all():
-        if r.updated_on is None:
-            r.updated_on = datetime.datetime.fromtimestamp(0)
-            _SESSION().add(r)
-    _SESSION().commit()
--- a/kallithea/lib/dbmigrate/versions/015_version_1_8_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,76 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base, notify
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_1_8_0
-    tbl = db_1_8_0.Setting.__table__
-    app_settings_type = Column("app_settings_type",
-                               String(255, convert_unicode=False, assert_unicode=None),
-                               nullable=True, unique=None, default=None)
-    app_settings_type.create(table=tbl)
-
-    # issue fixups
-    fixups(db_1_8_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    notify('Fixing default options now...')
-
-    settings = [
-        #general
-        ('realm', '', 'unicode'),
-        ('title', '', 'unicode'),
-        ('ga_code', '', 'unicode'),
-        ('show_public_icon', False, 'bool'),
-        ('show_private_icon', True, 'bool'),
-        ('stylify_metatags', True, 'bool'),
-
-        # defaults
-        ('default_repo_enable_locking',  False, 'bool'),
-        ('default_repo_enable_downloads', False, 'bool'),
-        ('default_repo_enable_statistics', False, 'bool'),
-        ('default_repo_private', False, 'bool'),
-        ('default_repo_type', 'hg', 'unicode'),
-
-        #other
-        ('dashboard_items', 100, 'int'),
-        ('show_version', True, 'bool')
-    ]
-
-    for name, default, type_ in settings:
-        setting = models.Setting.get_by_name(name)
-        if not setting:
-            # if we don't have this option create it
-            setting = models.Setting(name, default, type_)
-
-        # fix certain key to new defaults
-        if name in ['title', 'show_public_icon']:
-            # change title if it's only the default
-            if name == 'title' and setting.app_settings_value == 'Kallithea':
-                setting.app_settings_value = default
-            else:
-                setting.app_settings_value = default
-
-        setting._app_settings_type = type_
-        _SESSION().add(setting)
-        _SESSION().commit()
--- a/kallithea/lib/dbmigrate/versions/016_version_2_0_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-import logging
-import datetime
-
-from sqlalchemy import *
-
-from kallithea import EXTERN_TYPE_INTERNAL
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base, notify
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_2_0_0
-    tbl = db_2_0_0.User.__table__
-
-    extern_type = Column("extern_type",
-                         String(255, convert_unicode=False, assert_unicode=None),
-                         nullable=True, unique=None, default=None)
-    extern_type.create(table=tbl)
-
-    extern_name = Column("extern_name", String(255, convert_unicode=False, assert_unicode=None),
-                         nullable=True, unique=None, default=None)
-    extern_name.create(table=tbl)
-
-    created_on = Column('created_on', DateTime(timezone=False),
-                        nullable=True, default=datetime.datetime.now)
-    created_on.create(table=tbl)
-
-    # issue fixups
-    fixups(db_2_0_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    notify('Fixing default created on')
-
-    for usr in models.User.get_all():
-        usr.created_on = datetime.datetime.now()
-        _SESSION().add(usr)
-        _SESSION().commit()
-
-    notify('Migrating LDAP attribute to extern')
-    for usr in models.User.get_all():
-        ldap_dn = usr.ldap_dn
-        if ldap_dn:
-            usr.extern_name = ldap_dn
-            usr.extern_type = 'ldap'
-        else:
-            usr.extern_name = EXTERN_TYPE_INTERNAL
-            usr.extern_type = EXTERN_TYPE_INTERNAL
-        _SESSION().add(usr)
-        _SESSION().commit()
--- a/kallithea/lib/dbmigrate/versions/017_version_2_0_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,48 +0,0 @@
-import logging
-import datetime
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base, notify
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_2_0_0
-    tbl = db_2_0_0.UserGroup.__table__
-
-    user_group_description = Column("user_group_description",
-                                    String(10000, convert_unicode=False,
-                                           assert_unicode=None), nullable=True,
-                                    unique=None, default=None)
-    user_group_description.create(table=tbl)
-
-    created_on = Column('created_on', DateTime(timezone=False),
-                        nullable=True, default=datetime.datetime.now)
-    created_on.create(table=tbl)
-
-    # issue fixups
-    fixups(db_2_0_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    notify('Fixing default created on')
-
-    for gr in models.UserGroup.get_all():
-        gr.created_on = datetime.datetime.now()
-        _SESSION().commit()
--- a/kallithea/lib/dbmigrate/versions/018_version_2_0_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,74 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-from kallithea.lib.utils2 import str2bool
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base, notify
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_2_0_0
-
-    # issue fixups
-    fixups(db_2_0_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    notify('Fixing default auth modules')
-    plugins = 'kallithea.lib.auth_modules.auth_internal'
-    opts = []
-    ldap_enabled = str2bool(getattr(
-        models.Setting.get_by_name('ldap_active'),
-        'app_settings_value', False))
-    if ldap_enabled:
-        plugins += ',kallithea.lib.auth_modules.auth_ldap'
-        opts.append(('auth_ldap_enabled', 'True', 'bool'))
-
-    opts.append(('auth_plugins', plugins, 'list'),)
-    opts.append(('auth_internal_enabled', 'True', 'bool'))
-
-    for name, default, type_ in opts:
-        setting = models.Setting.get_by_name(name)
-        if not setting:
-            # if we don't have this option create it
-            setting = models.Setting(name, default, type_)
-
-        _SESSION().add(setting)
-        _SESSION().commit()
-
-    #copy over the LDAP settings
-    old_ldap = [('ldap_active', 'false', 'bool'), ('ldap_host', '', 'unicode'),
-                ('ldap_port', '389', 'int'), ('ldap_tls_kind', 'PLAIN', 'unicode'),
-                ('ldap_tls_reqcert', '', 'unicode'), ('ldap_dn_user', '', 'unicode'),
-                ('ldap_dn_pass', '', 'unicode'), ('ldap_base_dn', '', 'unicode'),
-                ('ldap_filter', '', 'unicode'), ('ldap_search_scope', '', 'unicode'),
-                ('ldap_attr_login', '', 'unicode'), ('ldap_attr_firstname', '', 'unicode'),
-                ('ldap_attr_lastname', '', 'unicode'), ('ldap_attr_email', '', 'unicode')]
-    for k, v, t in old_ldap:
-        old_setting = models.Setting.get_by_name(k)
-        name = 'auth_%s' % k
-        setting = models.Setting.get_by_name(name)
-        if setting is None:
-            # if we don't have this option create it
-            if old_setting is not None:
-                v = old_setting.app_settings_value
-            setting = models.Setting(name, v, t)
-
-        _SESSION().add(setting)
-        _SESSION().commit()
--- a/kallithea/lib/dbmigrate/versions/019_version_2_0_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,35 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_2_0_0
-    tbl = db_2_0_0.Setting.__table__
-    settings_value = tbl.columns.app_settings_value
-    settings_value.alter(type=String(4096))
-
-    # issue fixups
-    fixups(db_2_0_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    return
--- a/kallithea/lib/dbmigrate/versions/020_version_2_0_1.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,39 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea import EXTERN_TYPE_INTERNAL
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_2_0_1
-
-    # issue fixups
-    fixups(db_2_0_1, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    #fix all empty extern type users to default 'internal'
-    for usr in models.User.query().all():
-        if not usr.extern_name:
-            usr.extern_name = EXTERN_TYPE_INTERNAL
-            usr.extern_type = EXTERN_TYPE_INTERNAL
-            _SESSION().add(usr)
-            _SESSION().commit()
--- a/kallithea/lib/dbmigrate/versions/021_version_2_0_2.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,70 +0,0 @@
-import os
-import logging
-import datetime
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base, notify
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_2_0_1
-    tbl = db_2_0_1.RepoGroup.__table__
-
-    created_on = Column('created_on', DateTime(timezone=False), nullable=True,
-                        default=datetime.datetime.now)
-    created_on.create(table=tbl)
-
-    #fix null values on certain columns when upgrading from older releases
-    tbl = db_2_0_1.UserLog.__table__
-    col = tbl.columns.user_id
-    col.alter(nullable=True)
-
-    tbl = db_2_0_1.UserFollowing.__table__
-    col = tbl.columns.follows_repository_id
-    col.alter(nullable=True)
-
-    tbl = db_2_0_1.UserFollowing.__table__
-    col = tbl.columns.follows_user_id
-    col.alter(nullable=True)
-
-    # issue fixups
-    fixups(db_2_0_1, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    notify('Fixing default created on for repo groups')
-
-    for gr in models.RepoGroup.get_all():
-        gr.created_on = datetime.datetime.now()
-        _SESSION().add(gr)
-        _SESSION().commit()
-
-    repo_store_path = models.Ui.get_repos_location()
-    _store = os.path.join(repo_store_path, '.cache', 'largefiles')
-    notify('Setting largefiles usercache')
-    print _store
-
-    if not models.Ui.get_by_key('usercache'):
-        largefiles = models.Ui()
-        largefiles.ui_section = 'largefiles'
-        largefiles.ui_key = 'usercache'
-        largefiles.ui_value = _store
-        _SESSION().add(largefiles)
-        _SESSION().commit()
--- a/kallithea/lib/dbmigrate/versions/022_version_2_0_2.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,63 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base, notify
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_2_0_2
-
-    # issue fixups
-    fixups(db_2_0_2, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    notify('fixing new schema for landing_rev')
-
-    for repo in models.Repository.get_all():
-        print u'repo %s old landing rev is: %s' % (repo, repo.landing_rev)
-        _rev = repo.landing_rev[1]
-        _rev_type = 'rev'  # default
-
-        if _rev in ['default', 'master']:
-            _rev_type = 'branch'
-        elif _rev in ['tip']:
-            _rev_type = 'rev'
-        else:
-            try:
-                scm = repo.scm_instance
-                if scm:
-                    known_branches = scm.branches.keys()
-                    known_bookmarks = scm.bookmarks.keys()
-                    if _rev in known_branches:
-                        _rev_type = 'branch'
-                    elif _rev in known_bookmarks:
-                        _rev_type = 'book'
-            except Exception as e:
-                print e
-                print 'continue...'
-                #we don't want any error to break the process
-                pass
-
-        _new_landing_rev = '%s:%s' % (_rev_type, _rev)
-        print u'setting to %s' % _new_landing_rev
-        repo.landing_rev = _new_landing_rev
-        _SESSION().add(repo)
-        _SESSION().commit()
--- a/kallithea/lib/dbmigrate/versions/023_version_2_1_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,35 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_2_1_0
-
-    tbl = db_2_1_0.UserApiKeys.__table__
-    tbl.create()
-
-    # issue fixups
-    fixups(db_2_1_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    pass
--- a/kallithea/lib/dbmigrate/versions/024_version_2_1_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,61 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base, notify
-
-from kallithea.lib.utils2 import str2bool
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_2_1_0
-
-    # issue fixups
-    fixups(db_2_1_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    from pylons import config
-
-    notify('migrating options from .ini file')
-    use_gravatar = str2bool(config.get('use_gravatar'))
-    print('Setting gravatar use to: %s' % use_gravatar)
-    sett = models.Setting.create_or_update('use_gravatar',
-                                                    use_gravatar, 'bool')
-    _SESSION().add(sett)
-    _SESSION.commit()
-    #set the new format of gravatar URL
-    gravatar_url = models.User.DEFAULT_GRAVATAR_URL
-    if config.get('alternative_gravatar_url'):
-        gravatar_url = config.get('alternative_gravatar_url')
-
-    print('Setting gravatar url to:%s' % gravatar_url)
-    sett = models.Setting.create_or_update('gravatar_url',
-                                                    gravatar_url, 'unicode')
-    _SESSION().add(sett)
-    _SESSION.commit()
-
-    #now create new changed value of clone_url
-    clone_uri_tmpl = models.Repository.DEFAULT_CLONE_URI
-    print('settings new clone url template to %s' % clone_uri_tmpl)
-
-    sett = models.Setting.create_or_update('clone_uri_tmpl',
-                                                    clone_uri_tmpl, 'unicode')
-    _SESSION().add(sett)
-    _SESSION.commit()
--- a/kallithea/lib/dbmigrate/versions/025_version_2_1_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,36 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base, notify
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_2_1_0
-
-    # issue fixups
-    fixups(db_2_1_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    notify('Creating upgrade URL')
-    sett = models.Setting.create_or_update('update_url',
-                            models.Setting.DEFAULT_UPDATE_URL, 'unicode')
-    _SESSION().add(sett)
-    _SESSION.commit()
--- a/kallithea/lib/dbmigrate/versions/026_version_2_2_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,37 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_2_2_0
-
-    tbl = db_2_2_0.User.__table__
-
-    user_data = Column("user_data", LargeBinary(), nullable=True)  # JSON data
-    user_data.create(table=tbl)
-
-    # issue fixups
-    fixups(db_2_2_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    pass
--- a/kallithea/lib/dbmigrate/versions/027_version_2_2_0.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,52 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_2_2_0
-
-    # issue fixups
-    fixups(db_2_2_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    # ** create default permissions ** #
-    #=====================================
-    for p in models.Permission.PERMS:
-        if not models.Permission.get_by_key(p[0]):
-            new_perm = models.Permission()
-            new_perm.permission_name = p[0]
-            new_perm.permission_longname = p[0]  #translation err with p[1]
-            print 'Creating new permission %s' % p[0]
-            _SESSION().add(new_perm)
-
-    _SESSION().commit()
-
-    # ** set default create_on_write to active
-    user = models.User.get_default_user()
-    _def = 'hg.create.write_on_repogroup.true'
-    new = models.UserToPerm()
-    new.user = user
-    new.permission = models.Permission.get_by_key(_def)
-    print 'Setting default to %s' % _def
-    _SESSION().add(new)
-    _SESSION().commit()
--- a/kallithea/lib/dbmigrate/versions/028_version_2_2_3.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,37 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_2_2_0
-
-    tbl = db_2_2_0.UserGroup.__table__
-
-    user_data = Column("group_data", LargeBinary(), nullable=True)  # JSON data
-    user_data.create(table=tbl)
-
-    # issue fixups
-    fixups(db_2_2_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    pass
--- a/kallithea/lib/dbmigrate/versions/029_version_2_2_3.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,45 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base, notify
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_2_2_0
-
-    # issue fixups
-    fixups(db_2_2_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    notify('Adding grid items options now...')
-
-    settings = [
-        ('admin_grid_items', 25, 'int'),  # old hardcoded value was 25
-    ]
-
-    for name, default, type_ in settings:
-        setting = models.Setting.get_by_name(name)
-        if not setting:
-            # if we don't have this option create it
-            setting = models.Setting(name, default, type_)
-        setting._app_settings_type = type_
-        _SESSION().add(setting)
-        _SESSION().commit()
--- a/kallithea/lib/dbmigrate/versions/030_version_2_2_3.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,37 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_2_2_0
-
-    tbl = db_2_2_0.Repository.__table__
-
-    repo_state = Column("repo_state", String(255), nullable=True)
-    repo_state.create(table=tbl)
-
-    # issue fixups
-    fixups(db_2_2_0, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    pass
--- a/kallithea/lib/dbmigrate/versions/031_version_2_2_3.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,38 +0,0 @@
-import logging
-
-from sqlalchemy import *
-
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-from kallithea.lib.dbmigrate.versions import _reset_base, notify
-
-log = logging.getLogger(__name__)
-
-
-def upgrade(migrate_engine):
-    """
-    Upgrade operations go here.
-    Don't create your own engine; bind migrate_engine to your metadata
-    """
-    _reset_base(migrate_engine)
-    from kallithea.lib.dbmigrate.schema import db_2_2_3
-
-    # issue fixups
-    fixups(db_2_2_3, meta.Session)
-
-
-def downgrade(migrate_engine):
-    meta = MetaData()
-    meta.bind = migrate_engine
-
-
-def fixups(models, _SESSION):
-    notify('Creating repository states')
-    for repo in models.Repository.get_all():
-        _state = models.Repository.STATE_CREATED
-        print 'setting repo %s state to "%s"' % (repo, _state)
-        repo.repo_state = _state
-        _SESSION().add(repo)
-        _SESSION().commit()
--- a/kallithea/lib/dbmigrate/versions/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,59 +0,0 @@
-# -*- coding: utf-8 -*-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-"""
-kallithea.lib.dbmigrate.versions
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Package containing new versions of database models
-
-This file was forked by the Kallithea project in July 2014.
-Original author and date, and relevant copyright and licensing information is below:
-:created_on: Dec 11, 2010
-:author: marcink
-:copyright: (c) 2013 RhodeCode GmbH, and others.
-:license: GPLv3, see LICENSE.md for more details.
-"""
-
-from sqlalchemy import *
-from sqlalchemy.ext.declarative import declarative_base
-from kallithea.lib.dbmigrate.migrate import *
-from kallithea.lib.dbmigrate.migrate.changeset import *
-
-from kallithea.model import meta
-
-
-def notify(msg, caps=True):
-    """
-    Notification for migrations messages
-    """
-    ml = len(msg) + (4 * 2)
-    formatted_msg = ('\n%s\n*** %s ***\n%s' % ('*' * ml, msg, '*' * ml))
-    if caps:
-        formatted_msg = formatted_msg.upper()
-    print(formatted_msg)
-
-
-def _reset_base(migrate_engine):
-    ## RESET COMPLETLY THE metadata for sqlalchemy to use previous declared Base
-    Base = declarative_base()
-    Base.metadata.clear()
-    Base.metadata = MetaData()
-    Base.metadata.bind = migrate_engine
-
-    # new session and base
-    #meta.Session = scoped_session(sessionmaker(expire_on_commit=True,))
-    #meta.Session.configure(bind=migrate_engine)
-    meta.Base = Base
-
-    notify('SQLA BASE RESET !')
--- a/kallithea/lib/diffs.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/diffs.py	Fri Nov 18 01:11:13 2016 +0100
@@ -62,27 +62,34 @@
     if filenode_old is None:
         filenode_old = FileNode(filenode_new.path, '', EmptyChangeset())
 
+    op = None
+    a_path = filenode_old.path # default, might be overriden by actual rename in diff
     if filenode_old.is_binary or filenode_new.is_binary:
         diff = wrap_to_table(_('Binary file'))
         stats = (0, 0)
-        size = 0
 
-    elif cut_off_limit != -1 and (cut_off_limit is None or
-    (filenode_old.size < cut_off_limit and filenode_new.size < cut_off_limit)):
+    elif cut_off_limit != -1 and (
+            cut_off_limit is None or
+            (filenode_old.size < cut_off_limit and filenode_new.size < cut_off_limit)):
 
         f_gitdiff = get_gitdiff(filenode_old, filenode_new,
                                 ignore_whitespace=ignore_whitespace,
                                 context=line_context)
         diff_processor = DiffProcessor(f_gitdiff, format='gitdiff')
+        _parsed = diff_processor.prepare()
+        if _parsed: # there should be exactly one element, for the specified file
+            f = _parsed[0]
+            op = f['operation']
+            a_path = f['old_filename']
 
         diff = diff_processor.as_html(enable_comments=enable_comments)
         stats = diff_processor.stat()
-        size = len(diff or '')
+
     else:
         diff = wrap_to_table(_('Changeset was too big and was cut off, use '
                                'diff menu to display this diff'))
         stats = (0, 0)
-        size = 0
+
     if not diff:
         submodules = filter(lambda o: isinstance(o, SubModuleNode),
                             [filenode_new, filenode_old])
@@ -94,7 +101,7 @@
     cs1 = filenode_old.changeset.raw_id
     cs2 = filenode_new.changeset.raw_id
 
-    return size, cs1, cs2, diff, stats
+    return cs1, cs2, a_path, diff, stats, op
 
 
 def get_gitdiff(filenode_old, filenode_new, ignore_whitespace=True, context=3):
@@ -283,15 +290,13 @@
             self.removes += 1
         return safe_unicode(l)
 
-    def _highlight_line_difflib(self, line, next_):
+    def _highlight_line_difflib(self, old, new):
         """
         Highlight inline changes in both lines.
         """
 
-        if line['action'] == 'del':
-            old, new = line, next_
-        else:
-            old, new = next_, line
+        assert old['action'] == 'del'
+        assert new['action'] == 'add'
 
         oldwords = self._token_re.split(old['line'])
         newwords = self._token_re.split(new['line'])
@@ -364,7 +369,7 @@
         groups = match.groupdict()
         rest = diff_chunk[match.end():]
         if rest and not rest.startswith('@') and not rest.startswith('literal ') and not rest.startswith('delta '):
-            raise Exception('cannot parse diff header: %r followed by %r' % (diff_chunk[:match.end()], rest[:1000]))
+            raise Exception('cannot parse %s diff header: %r followed by %r' % (self.vcs, diff_chunk[:match.end()], rest[:1000]))
         difflines = imap(self._escaper, re.findall(r'.*\n|.+$', rest)) # don't split on \r as str.splitlines do
         return groups, difflines
 
@@ -473,6 +478,7 @@
                   if _op not in [MOD_FILENODE]])
 
             _files.append({
+                'old_filename':     head['a_path'],
                 'filename':         head['b_path'],
                 'old_revision':     head['a_blob_id'],
                 'new_revision':     head['b_blob_id'],
@@ -484,19 +490,34 @@
         if not inline_diff:
             return diff_container(_files)
 
-        # highlight inline changes
+        # highlight inline changes when one del is followed by one add
         for diff_data in _files:
             for chunk in diff_data['chunks']:
                 lineiter = iter(chunk)
                 try:
-                    while 1:
-                        line = lineiter.next()
-                        if line['action'] not in ['unmod', 'context']:
-                            nextline = lineiter.next()
-                            if nextline['action'] in ['unmod', 'context'] or \
-                               nextline['action'] == line['action']:
-                                continue
-                            self.differ(line, nextline)
+                    peekline = lineiter.next()
+                    while True:
+                        # find a first del line
+                        while peekline['action'] != 'del':
+                            peekline = lineiter.next()
+                        delline = peekline
+                        peekline = lineiter.next()
+                        # if not followed by add, eat all following del lines
+                        if peekline['action'] != 'add':
+                            while peekline['action'] == 'del':
+                                peekline = lineiter.next()
+                            continue
+                        # found an add - make sure it is the only one
+                        addline = peekline
+                        try:
+                            peekline = lineiter.next()
+                        except StopIteration:
+                            # add was last line - ok
+                            self.differ(delline, addline)
+                            raise
+                        if peekline['action'] != 'add':
+                            # there was only one add line - ok
+                            self.differ(delline, addline)
                 except StopIteration:
                     pass
 
@@ -625,7 +646,7 @@
 
     def prepare(self, inline_diff=True):
         """
-        Prepare the passed udiff for HTML rendering. It'l return a list
+        Prepare the passed udiff for HTML rendering. It'll return a list
         of dicts with diff information
         """
         parsed = self._parser(inline_diff=inline_diff)
@@ -710,7 +731,7 @@
                     })
 
                     _html.append('''%(link)s''' % {
-                        'link': _link_to_if(True, change['old_lineno'],
+                        'link': _link_to_if(not no_lineno, change['old_lineno'],
                                             '#%s' % anchor_old)
                     })
                     _html.append('''</td>\n''')
--- a/kallithea/lib/graphmod.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/graphmod.py	Fri Nov 18 01:11:13 2016 +0100
@@ -21,9 +21,14 @@
 
 def _first_known_ancestors(parentrev_func, minrev, knownrevs, head):
     """
-    Walk DAG defined by parentrev_func.
-    Return most immediate ancestors of head that are in knownrevs.
-    minrev is lower bound on knownrevs.
+    Return the apparent parents of the head revision in a filtered DAG.
+    This is like calling plain parentrev_func, except that if the parent has
+    been filtered (isn't in knownrevs), recurse on its parents.
+    For ancestors that are unknown in knownrevs, the revision number is negated.
+    (This means that a Mercurial revision can have more than 2 "parents".)
+
+    parentrev_func defines the full DAG.
+    knownrevs contains the subset we care about. minrev is lower bound on knownrevs.
     """
     pending = set([head])
     seen = set()
@@ -57,6 +62,7 @@
     return list(_colored(repo, dag))
 
 def _dagwalker(repo, revs):
+    """Iterate over revs, yielding revs (highest first) and parents to show in the graph."""
     if not revs:
         return
 
@@ -66,7 +72,7 @@
         def parentrev_func(rev):
             return [x.revision for x in repo[rev].parents]
 
-    minrev = revs[-1] # assuming sorted reverse
+    minrev = revs[-1] # assuming sorted with highest revision numbers first
     knownrevs = set(revs)
     acache = {}
     for rev in revs:
@@ -97,14 +103,17 @@
     """
     branch_cache = {}
     def branch(rev):
+        """Return branch for rev, using cache for efficiency.
+        For Mercurial, always return the named branch name (which may be 'default').
+        For Git, return a branch name for branch heads, otherwise None."""
         if rev not in branch_cache:
             branch_cache[rev] = repo[rev].branch
         return branch_cache[rev]
 
-    row = []
-    colors = {}
-    obs = {}
-    newcolor = 1
+    row = []  # the ancestor revision that each column is tracking
+    colors = {}  # color number for revisions - set by descendants
+    obs = {}  # obsolete flag for revisions - set by descendants
+    newcolor = 1  # the next available color
 
     for (rev, dagparents) in dag:
 
@@ -121,24 +130,26 @@
         # Add unknown parents to nextrow
         tmprow = row[:]
         tmprow[col:col + 1] = reversed(addparents) # highest revs first (to the right), dead ends last (to the left)
-        # Stop looking for non-existing ancestors
+        # Filter old fake parents but keep new ones
         nextrow = []
         for r in tmprow:
-            if r > nullrev or r in dagparents:
+            if r >= 0 or r in dagparents:
                 nextrow.append(r)
             else:
                 colors.pop(r)
                 obs.pop(r)
 
-        # Set colors for the parents
+        # Let color and obs for this rev be "inherited" by the first "parent"
         color = colors.pop(rev)
         if addparents:
             b = branch(rev)
+            searching = True
             for p in reversed(addparents):
                 obs[p] = int(repo[p].obsolete)
-                if b and branch(abs(p)) == b:
+                if searching and branch(abs(p)) in [b, None]:
+                    # This is the first parent on the same branch - inherit the color
                     colors[p] = color
-                    b = None
+                    searching = False # make sure we don't give the color away twice
                 else:
                     colors[p] = newcolor
                     newcolor += 1
@@ -155,5 +166,9 @@
         # Yield and move on
         closing = int(repo[rev].closesbranch)
         obsolete = int(repo[rev].obsolete)
-        yield ((col, color), edges, closing, obsolete)
+        bumped = int(repo[rev].bumped)
+        divergent = int(repo[rev].divergent)
+        extinct = int(repo[rev].extinct)
+        unstable = int(repo[rev].unstable)
+        yield ((col, color), edges, closing, obsolete, bumped, divergent, extinct, unstable)
         row = nextrow
--- a/kallithea/lib/helpers.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/helpers.py	Fri Nov 18 01:11:13 2016 +0100
@@ -19,49 +19,34 @@
 """
 import hashlib
 import StringIO
-import math
 import logging
 import re
 import urlparse
 import textwrap
 
+from beaker.cache import cache_region
 from pygments.formatters.html import HtmlFormatter
 from pygments import highlight as code_highlight
-from pylons import url
-from pylons.i18n.translation import _, ungettext
+from pylons.i18n.translation import _
 
 from webhelpers.html import literal, HTML, escape
-from webhelpers.html.tools import *
-from webhelpers.html.builder import make_tag
-from webhelpers.html.tags import auto_discovery_link, checkbox, css_classes, \
-    end_form, file, hidden, image, javascript_link, link_to, \
-    link_to_if, link_to_unless, ol, required_legend, select, stylesheet_link, \
-    submit, text, password, textarea, title, ul, xml_declaration, radio, \
-    form as insecure_form
-from webhelpers.html.tools import auto_link, button_to, highlight, \
-    js_obfuscate, mail_to, strip_links, strip_tags, tag_re
-from webhelpers.number import format_byte_size, format_bit_size
+from webhelpers.html.tags import checkbox, end_form, hidden, link_to, \
+    select, submit, text, password, textarea, radio, form as insecure_form
+from webhelpers.number import format_byte_size
 from webhelpers.pylonslib import Flash as _Flash
 from webhelpers.pylonslib.secure_form import secure_form, authentication_token
-from webhelpers.text import chop_at, collapse, convert_accented_entities, \
-    convert_misc_entities, lchop, plural, rchop, remove_formatting, \
-    replace_whitespace, urlify, truncate, wrap_paragraphs
-from webhelpers.date import time_ago_in_words
-from webhelpers.paginate import Page as _Page
+from webhelpers.text import chop_at, truncate, wrap_paragraphs
 from webhelpers.html.tags import _set_input_attrs, _set_id_attr, \
     convert_boolean_attrs, NotGiven, _make_safe_id_component
 
+from kallithea.config.routing import url
 from kallithea.lib.annotate import annotate_highlight
-from kallithea.lib.utils import repo_name_slug, get_custom_lexer
+from kallithea.lib.pygmentsutils import get_custom_lexer
 from kallithea.lib.utils2 import str2bool, safe_unicode, safe_str, \
-    get_changeset_safe, datetime_to_time, time_to_datetime, AttributeDict,\
-    safe_int
-from kallithea.lib.markup_renderer import MarkupRenderer, url_re
+    time_to_datetime, AttributeDict, safe_int, MENTIONS_REGEX
+from kallithea.lib.markup_renderer import url_re
 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError
 from kallithea.lib.vcs.backends.base import BaseChangeset, EmptyChangeset
-from kallithea.config.conf import DATE_FORMAT, DATETIME_FORMAT
-from kallithea.model.changeset_status import ChangesetStatusModel
-from kallithea.model.db import URL_SEP, Permission
 
 log = logging.getLogger(__name__)
 
@@ -100,8 +85,12 @@
         .replace("'", "&apos;")
         )
 
-def shorter(s, size=20):
-    postfix = '...'
+def shorter(s, size=20, firstline=False, postfix='...'):
+    """Truncate s to size, including the postfix string if truncating.
+    If firstline, truncate at newline.
+    """
+    if firstline:
+        s = s.split('\n', 1)[0].rstrip()
     if len(s) > size:
         return s[:size - len(postfix)] + postfix
     return s
@@ -132,22 +121,6 @@
     return 'C-%s-%s' % (short_id(raw_id), hashlib.md5(safe_str(path)).hexdigest()[:12])
 
 
-class _GetError(object):
-    """Get error from form_errors, and represent it as span wrapped error
-    message
-
-    :param field_name: field to fetch errors for
-    :param form_errors: form errors dict
-    """
-
-    def __call__(self, field_name, form_errors):
-        tmpl = """<span class="error_msg">%s</span>"""
-        if form_errors and field_name in form_errors:
-            return literal(tmpl % form_errors.get(field_name))
-
-get_error = _GetError()
-
-
 class _FilesBreadCrumbs(object):
 
     def __call__(self, repo_name, rev, paths):
@@ -348,8 +321,9 @@
                     url('changeset_home', repo_name=repo_name,
                         revision=changeset.raw_id),
                     style=get_color_string(changeset.raw_id),
-                    class_='tooltip safe-html-title',
-                    title=tooltip_html
+                    class_='safe-html-title',
+                    title=tooltip_html,
+                    **{'data-toggle': 'tooltip'}
                   )
 
             uri += '\n'
@@ -359,10 +333,6 @@
     return literal(markup_whitespace(annotate_highlight(filenode, url_func(repo_name), **kwargs)))
 
 
-def is_following_repo(repo_name, user_id):
-    from kallithea.model.scm import ScmModel
-    return ScmModel().is_following_repo(repo_name, user_id)
-
 class _Message(object):
     """A message returned by ``Flash.pop_messages()``.
 
@@ -423,7 +393,6 @@
 #==============================================================================
 from kallithea.lib.vcs.utils import author_name, author_email
 from kallithea.lib.utils2 import credentials_filter, age as _age
-from kallithea.model.db import User, ChangesetStatus, PullRequest
 
 age = lambda  x, y=False: _age(x, y)
 capitalize = lambda x: x.capitalize()
@@ -477,20 +446,18 @@
     return _type == 'hg'
 
 
+@cache_region('long_term', 'user_or_none')
 def user_or_none(author):
+    """Try to match email part of VCS committer string with a local user - or return None"""
+    from kallithea.model.db import User
     email = author_email(author)
     if email:
-        user = User.get_by_email(email, case_insensitive=True, cache=True)
-        if user is not None:
-            return user
-
-    user = User.get_by_username(author_name(author), case_insensitive=True, cache=True)
-    if user is not None:
-        return user
-
+        return User.get_by_email(email, cache=True) # cache will only use sql_cache_short
     return None
 
 def email_or_none(author):
+    """Try to match email part of VCS committer string with a local user.
+    Return primary email of user, email part of the specified author name, or None."""
     if not author:
         return None
     user = user_or_none(author)
@@ -508,6 +475,7 @@
 def person(author, show_attr="username"):
     """Find the user identified by 'author', return one of the users attributes,
     default to the username attribute, None if there is no user"""
+    from kallithea.model.db import User
     # attr to return from fetched user
     person_getter = lambda usr: getattr(usr, show_attr)
 
@@ -524,6 +492,7 @@
 
 
 def person_by_id(id_, show_attr="username"):
+    from kallithea.model.db import User
     # attr to return from fetched user
     person_getter = lambda usr: getattr(usr, show_attr)
 
@@ -536,29 +505,6 @@
     return id_
 
 
-def desc_stylize(value):
-    """
-    converts tags from value into html equivalent
-
-    :param value:
-    """
-    if not value:
-        return ''
-
-    value = re.sub(r'\[see\ \=&gt;\ *([a-zA-Z0-9\/\=\?\&\ \:\/\.\-]*)\]',
-                   '<div class="metatag" tag="see">see =&gt; \\1 </div>', value)
-    value = re.sub(r'\[license\ \=&gt;\ *([a-zA-Z0-9\/\=\?\&\ \:\/\.\-]*)\]',
-                   '<div class="metatag" tag="license"><a href="http:\/\/www.opensource.org/licenses/\\1">\\1</a></div>', value)
-    value = re.sub(r'\[(requires|recommends|conflicts|base)\ \=&gt;\ *([a-zA-Z0-9\-\/]*)\]',
-                   '<div class="metatag" tag="\\1">\\1 =&gt; <a href="/\\2">\\2</a></div>', value)
-    value = re.sub(r'\[(lang|language)\ \=&gt;\ *([a-zA-Z\-\/\#\+]*)\]',
-                   '<div class="metatag" tag="lang">\\2</div>', value)
-    value = re.sub(r'\[([a-z]+)\]',
-                  '<div class="metatag" tag="\\1">\\1</div>', value)
-
-    return value
-
-
 def boolicon(value):
     """Returns boolean value of a value, represented as small html image of true/false
     icons
@@ -620,7 +566,7 @@
             else:
                 # changeset cannot be found - it might have been stripped or removed
                 lbl = rev[:12]
-                title_ = _('Changeset not found')
+                title_ = _('Changeset %s not found') % lbl
             if parse_cs:
                 return link_to(lbl, url_, title=title_, class_='tooltip')
             return link_to(lbl, url_, raw_id=rev.raw_id, repo_name=repo_name,
@@ -667,7 +613,7 @@
         _rev = '%s...%s' % (_name1, _name2)
 
         compare_view = (
-            ' <div class="compare_view tooltip" title="%s">'
+            ' <div class="compare_view" data-toggle="tooltip" title="%s">'
             '<a href="%s">%s</a> </div>' % (
                 _('Show all combined changesets %s->%s') % (
                     revs_ids[0][:12], revs_ids[-1][:12]
@@ -731,6 +677,7 @@
         return group_name
 
     def get_pull_request():
+        from kallithea.model.db import PullRequest
         pull_request_id = action_params
         nice_id = PullRequest.make_nice_id(pull_request_id)
 
@@ -802,8 +749,8 @@
     if feed:
         action = action_str[0].replace('[', '').replace(']', '')
     else:
-        action = action_str[0]\
-            .replace('[', '<span class="journal_highlight">')\
+        action = action_str[0] \
+            .replace('[', '<span class="journal_highlight">') \
             .replace(']', '</span>')
 
     action_params_func = lambda: ""
@@ -831,15 +778,33 @@
 #==============================================================================
 # PERMS
 #==============================================================================
-from kallithea.lib.auth import HasPermissionAny, HasPermissionAll, \
-HasRepoPermissionAny, HasRepoPermissionAll, HasRepoGroupPermissionAll, \
-HasRepoGroupPermissionAny
+from kallithea.lib.auth import HasPermissionAny, \
+    HasRepoPermissionAny, HasRepoGroupPermissionAny
 
 
 #==============================================================================
 # GRAVATAR URL
 #==============================================================================
-def gravatar(email_address, cls='', size=30, ssl_enabled=True):
+def gravatar_div(email_address, cls='', size=30, **div_attributes):
+    """Return an html literal with a div around a gravatar if they are enabled.
+    Extra keyword parameters starting with 'div_' will get the prefix removed
+    and '_' changed to '-' and be used as attributes on the div. The default
+    class is 'gravatar'.
+    """
+    from pylons import tmpl_context as c
+    if not c.visual.use_gravatar:
+        return ''
+    if 'div_class' not in div_attributes:
+        div_attributes['div_class'] = "gravatar"
+    attributes = []
+    for k, v in sorted(div_attributes.items()):
+        assert k.startswith('div_'), k
+        attributes.append(' %s="%s"' % (k[4:].replace('_', '-'), escape(v)))
+    return literal("""<div%s>%s</div>""" %
+                   (''.join(attributes),
+                    gravatar(email_address, cls=cls, size=size)))
+
+def gravatar(email_address, cls='', size=30):
     """return html element of the gravatar
 
     This method will return an <img> with the resolution double the size (for
@@ -847,268 +812,47 @@
     empty then we fallback to using an icon.
 
     """
-    src = gravatar_url(email_address, size*2, ssl_enabled)
+    from pylons import tmpl_context as c
+    if not c.visual.use_gravatar:
+        return ''
 
-    #  here it makes sense to use style="width: ..." (instead of, say, a
-    # stylesheet) because we using this to generate a high-res (retina) size
-    tmpl = '<img alt="" class="{cls}" style="width: {size}px; height: {size}px" src="{src}"/>'
+    src = gravatar_url(email_address, size * 2)
 
-    # if src is empty then there was no gravatar, so we use a font icon
-    if not src:
-        tmpl = """<i class="icon-user {cls}" style="font-size: {size}px;"></i>"""
-
-    tmpl = tmpl.format(cls=cls, size=size, src=src)
-    return literal(tmpl)
+    if src:
+        # here it makes sense to use style="width: ..." (instead of, say, a
+        # stylesheet) because we using this to generate a high-res (retina) size
+        html = ('<img alt="" class="{cls}" style="width: {size}px; height: {size}px" src="{src}"/>'
+            .format(cls=cls, size=size, src=src))
 
-def gravatar_url(email_address, size=30, ssl_enabled=True):
-    # doh, we need to re-import those to mock it later
-    from pylons import url
-    from pylons import tmpl_context as c
+    else:
+        # if src is empty then there was no gravatar, so we use a font icon
+        html = ("""<i class="icon-user {cls}" style="font-size: {size}px;"></i>"""
+            .format(cls=cls, size=size, src=src))
+
+    return literal(html)
 
-    _def = 'anonymous@kallithea-scm.org'  # default gravatar
-    _use_gravatar = c.visual.use_gravatar
-    _gravatar_url = c.visual.gravatar_url or User.DEFAULT_GRAVATAR_URL
-
-    email_address = email_address or _def
-
-    if not _use_gravatar or not email_address or email_address == _def:
+def gravatar_url(email_address, size=30, default=''):
+    # doh, we need to re-import those to mock it later
+    from kallithea.config.routing import url
+    from kallithea.model.db import User
+    from pylons import tmpl_context as c
+    if not c.visual.use_gravatar:
         return ""
 
-    if _use_gravatar:
-        _md5 = lambda s: hashlib.md5(s).hexdigest()
-
-        tmpl = _gravatar_url
-        parsed_url = urlparse.urlparse(url.current(qualified=True))
-        tmpl = tmpl.replace('{email}', email_address)\
-                   .replace('{md5email}', _md5(safe_str(email_address).lower())) \
-                   .replace('{netloc}', parsed_url.netloc)\
-                   .replace('{scheme}', parsed_url.scheme)\
-                   .replace('{size}', safe_str(size))
-        return tmpl
-
-class Page(_Page):
-    """
-    Custom pager to match rendering style with YUI paginator
-    """
-
-    def _get_pos(self, cur_page, max_page, items):
-        edge = (items / 2) + 1
-        if (cur_page <= edge):
-            radius = max(items / 2, items - cur_page)
-        elif (max_page - cur_page) < edge:
-            radius = (items - 1) - (max_page - cur_page)
-        else:
-            radius = items / 2
-
-        left = max(1, (cur_page - (radius)))
-        right = min(max_page, cur_page + (radius))
-        return left, cur_page, right
-
-    def _range(self, regexp_match):
-        """
-        Return range of linked pages (e.g. '1 2 [3] 4 5 6 7 8').
-
-        Arguments:
-
-        regexp_match
-            A "re" (regular expressions) match object containing the
-            radius of linked pages around the current page in
-            regexp_match.group(1) as a string
-
-        This function is supposed to be called as a callable in
-        re.sub.
-
-        """
-        radius = int(regexp_match.group(1))
-
-        # Compute the first and last page number within the radius
-        # e.g. '1 .. 5 6 [7] 8 9 .. 12'
-        # -> leftmost_page  = 5
-        # -> rightmost_page = 9
-        leftmost_page, _cur, rightmost_page = self._get_pos(self.page,
-                                                            self.last_page,
-                                                            (radius * 2) + 1)
-        nav_items = []
+    _def = 'anonymous@kallithea-scm.org'  # default gravatar
+    email_address = email_address or _def
 
-        # Create a link to the first page (unless we are on the first page
-        # or there would be no need to insert '..' spacers)
-        if self.page != self.first_page and self.first_page < leftmost_page:
-            nav_items.append(self._pagerlink(self.first_page, self.first_page))
-
-        # Insert dots if there are pages between the first page
-        # and the currently displayed page range
-        if leftmost_page - self.first_page > 1:
-            # Wrap in a SPAN tag if nolink_attr is set
-            text_ = '..'
-            if self.dotdot_attr:
-                text_ = HTML.span(c=text_, **self.dotdot_attr)
-            nav_items.append(text_)
-
-        for thispage in xrange(leftmost_page, rightmost_page + 1):
-            # Highlight the current page number and do not use a link
-            text_ = str(thispage)
-            if thispage == self.page:
-                # Wrap in a SPAN tag if nolink_attr is set
-                if self.curpage_attr:
-                    text_ = HTML.span(c=text_, **self.curpage_attr)
-                nav_items.append(text_)
-            # Otherwise create just a link to that page
-            else:
-                nav_items.append(self._pagerlink(thispage, text_))
-
-        # Insert dots if there are pages between the displayed
-        # page numbers and the end of the page range
-        if self.last_page - rightmost_page > 1:
-            text_ = '..'
-            # Wrap in a SPAN tag if nolink_attr is set
-            if self.dotdot_attr:
-                text_ = HTML.span(c=text_, **self.dotdot_attr)
-            nav_items.append(text_)
-
-        # Create a link to the very last page (unless we are on the last
-        # page or there would be no need to insert '..' spacers)
-        if self.page != self.last_page and rightmost_page < self.last_page:
-            nav_items.append(self._pagerlink(self.last_page, self.last_page))
-
-        #_page_link = url.current()
-        #nav_items.append(literal('<link rel="prerender" href="%s?page=%s">' % (_page_link, str(int(self.page)+1))))
-        #nav_items.append(literal('<link rel="prefetch" href="%s?page=%s">' % (_page_link, str(int(self.page)+1))))
-        return self.separator.join(nav_items)
-
-    def pager(self, format='~2~', page_param='page', partial_param='partial',
-        show_if_single_page=False, separator=' ', onclick=None,
-        symbol_first='<<', symbol_last='>>',
-        symbol_previous='<', symbol_next='>',
-        link_attr={'class': 'pager_link', 'rel': 'prerender'},
-        curpage_attr={'class': 'pager_curpage'},
-        dotdot_attr={'class': 'pager_dotdot'}, **kwargs):
-
-        self.curpage_attr = curpage_attr
-        self.separator = separator
-        self.pager_kwargs = kwargs
-        self.page_param = page_param
-        self.partial_param = partial_param
-        self.onclick = onclick
-        self.link_attr = link_attr
-        self.dotdot_attr = dotdot_attr
+    if email_address == _def:
+        return default
 
-        # Don't show navigator if there is no more than one page
-        if self.page_count == 0 or (self.page_count == 1 and not show_if_single_page):
-            return ''
-
-        from string import Template
-        # Replace ~...~ in token format by range of pages
-        result = re.sub(r'~(\d+)~', self._range, format)
-
-        # Interpolate '%' variables
-        result = Template(result).safe_substitute({
-            'first_page': self.first_page,
-            'last_page': self.last_page,
-            'page': self.page,
-            'page_count': self.page_count,
-            'items_per_page': self.items_per_page,
-            'first_item': self.first_item,
-            'last_item': self.last_item,
-            'item_count': self.item_count,
-            'link_first': self.page > self.first_page and \
-                    self._pagerlink(self.first_page, symbol_first) or '',
-            'link_last': self.page < self.last_page and \
-                    self._pagerlink(self.last_page, symbol_last) or '',
-            'link_previous': self.previous_page and \
-                    self._pagerlink(self.previous_page, symbol_previous) \
-                    or HTML.span(symbol_previous, class_="yui-pg-previous"),
-            'link_next': self.next_page and \
-                    self._pagerlink(self.next_page, symbol_next) \
-                    or HTML.span(symbol_next, class_="yui-pg-next")
-        })
-
-        return literal(result)
-
-
-#==============================================================================
-# REPO PAGER, PAGER FOR REPOSITORY
-#==============================================================================
-class RepoPage(Page):
-
-    def __init__(self, collection, page=1, items_per_page=20,
-                 item_count=None, url=None, **kwargs):
-
-        """Create a "RepoPage" instance. special pager for paging
-        repository
-        """
-        self._url_generator = url
-
-        # Safe the kwargs class-wide so they can be used in the pager() method
-        self.kwargs = kwargs
-
-        # Save a reference to the collection
-        self.original_collection = collection
-
-        self.collection = collection
-
-        # The self.page is the number of the current page.
-        # The first page has the number 1!
-        try:
-            self.page = int(page)  # make it int() if we get it as a string
-        except (ValueError, TypeError):
-            self.page = 1
-
-        self.items_per_page = items_per_page
-
-        # Unless the user tells us how many items the collections has
-        # we calculate that ourselves.
-        if item_count is not None:
-            self.item_count = item_count
-        else:
-            self.item_count = len(self.collection)
-
-        # Compute the number of the first and last available page
-        if self.item_count > 0:
-            self.first_page = 1
-            self.page_count = int(math.ceil(float(self.item_count) /
-                                            self.items_per_page))
-            self.last_page = self.first_page + self.page_count - 1
-
-            # Make sure that the requested page number is the range of
-            # valid pages
-            if self.page > self.last_page:
-                self.page = self.last_page
-            elif self.page < self.first_page:
-                self.page = self.first_page
-
-            # Note: the number of items on this page can be less than
-            #       items_per_page if the last page is not full
-            self.first_item = max(0, (self.item_count) - (self.page *
-                                                          items_per_page))
-            self.last_item = ((self.item_count - 1) - items_per_page *
-                              (self.page - 1))
-
-            self.items = list(self.collection[self.first_item:self.last_item + 1])
-
-            # Links to previous and next page
-            if self.page > self.first_page:
-                self.previous_page = self.page - 1
-            else:
-                self.previous_page = None
-
-            if self.page < self.last_page:
-                self.next_page = self.page + 1
-            else:
-                self.next_page = None
-
-        # No items available
-        else:
-            self.first_page = None
-            self.page_count = 0
-            self.last_page = None
-            self.first_item = None
-            self.last_item = None
-            self.previous_page = None
-            self.next_page = None
-            self.items = []
-
-        # This is a subclass of the 'list' type. Initialise the list now.
-        list.__init__(self, reversed(self.items))
+    parsed_url = urlparse.urlparse(url.current(qualified=True))
+    url = (c.visual.gravatar_url or User.DEFAULT_GRAVATAR_URL ) \
+               .replace('{email}', email_address) \
+               .replace('{md5email}', hashlib.md5(safe_str(email_address).lower()).hexdigest()) \
+               .replace('{netloc}', parsed_url.netloc) \
+               .replace('{scheme}', parsed_url.scheme) \
+               .replace('{size}', safe_str(size))
+    return url
 
 
 def changed_tooltip(nodes):
@@ -1129,27 +873,6 @@
         return ': ' + _('No files')
 
 
-def repo_link(groups_and_repos):
-    """
-    Makes a breadcrumbs link to repo within a group
-    joins &raquo; on each group to create a fancy link
-
-    ex::
-        group >> subgroup >> repo
-
-    :param groups_and_repos:
-    :param last_url:
-    """
-    groups, just_name, repo_name = groups_and_repos
-    last_url = url('summary_home', repo_name=repo_name)
-    last_link = link_to(just_name, last_url)
-
-    def make_link(group):
-        return link_to(group.name,
-                       url('repos_group_home', group_name=group.group_name))
-    return literal(' &raquo; '.join(map(make_link, groups) + ['<span>%s</span>' % last_link]))
-
-
 def fancy_file_stats(stats):
     """
     Displays a fancy two colored bar for number of added/deleted
@@ -1241,151 +964,186 @@
     return literal('<div style="width:%spx">%s%s</div>' % (width, d_a, d_d))
 
 
-def _urlify_text(s):
-    """
-    Extract urls from text and make html links out of them
+_URLIFY_RE = re.compile(r'''
+# URL markup
+(?P<url>%s) |
+# @mention markup
+(?P<mention>%s) |
+# Changeset hash markup
+(?<!\w|[-_])
+  (?P<hash>[0-9a-f]{12,40})
+(?!\w|[-_]) |
+# Markup of *bold text*
+(?:
+  (?:^|(?<=\s))
+  (?P<bold> [*] (?!\s) [^*\n]* (?<!\s) [*] )
+  (?![*\w])
+) |
+# "Stylize" markup
+\[see\ \=&gt;\ *(?P<seen>[a-zA-Z0-9\/\=\?\&\ \:\/\.\-]*)\] |
+\[license\ \=&gt;\ *(?P<license>[a-zA-Z0-9\/\=\?\&\ \:\/\.\-]*)\] |
+\[(?P<tagtype>requires|recommends|conflicts|base)\ \=&gt;\ *(?P<tagvalue>[a-zA-Z0-9\-\/]*)\] |
+\[(?:lang|language)\ \=&gt;\ *(?P<lang>[a-zA-Z\-\/\#\+]*)\] |
+\[(?P<tag>[a-z]+)\]
+''' % (url_re.pattern, MENTIONS_REGEX.pattern),
+    re.VERBOSE | re.MULTILINE | re.IGNORECASE)
+
+
+
+def urlify_text(s, repo_name=None, link_=None, truncate=None, stylize=False, truncatef=truncate):
     """
-    def url_func(match_obj):
-        url_full = match_obj.group(1)
-        return '<a href="%(url)s">%(url)s</a>' % ({'url': url_full})
-    return url_re.sub(url_func, s)
+    Parses given text message and make literal html with markup.
+    The text will be truncated to the specified length.
+    Hashes are turned into changeset links to specified repository.
+    URLs links to what they say.
+    Issues are linked to given issue-server.
+    If link_ is provided, all text not already linking somewhere will link there.
+    """
 
-def urlify_text(s, truncate=None, stylize=False, truncatef=truncate):
-    """
-    Extract urls from text and make literal html links out of them
-    """
-    if truncate is not None:
-        s = truncatef(s, truncate)
+    def _replace(match_obj):
+        url = match_obj.group('url')
+        if url is not None:
+            return '<a href="%(url)s">%(url)s</a>' % {'url': url}
+        mention = match_obj.group('mention')
+        if mention is not None:
+            return '<b>%s</b>' % mention
+        hash_ = match_obj.group('hash')
+        if hash_ is not None and repo_name is not None:
+            from kallithea.config.routing import url  # doh, we need to re-import url to mock it later
+            return '<a class="revision-link" href="%(url)s">%(hash)s</a>' % {
+                 'url': url('changeset_home', repo_name=repo_name, revision=hash_),
+                 'hash': hash_,
+                }
+        bold = match_obj.group('bold')
+        if bold is not None:
+            return '<b>*%s*</b>' % _urlify(bold[1:-1])
+        if stylize:
+            seen = match_obj.group('seen')
+            if seen:
+                return '<div class="metatag" tag="see">see =&gt; %s</div>' % seen
+            license = match_obj.group('license')
+            if license:
+                return '<div class="metatag" tag="license"><a href="http:\/\/www.opensource.org/licenses/%s">%s</a></div>' % (license, license)
+            tagtype = match_obj.group('tagtype')
+            if tagtype:
+                tagvalue = match_obj.group('tagvalue')
+                return '<div class="metatag" tag="%s">%s =&gt; <a href="/%s">%s</a></div>' % (tagtype, tagtype, tagvalue, tagvalue)
+            lang = match_obj.group('lang')
+            if lang:
+                return '<div class="metatag" tag="lang">%s</div>' % lang
+            tag = match_obj.group('tag')
+            if tag:
+                return '<div class="metatag" tag="%s">%s</div>' % (tag, tag)
+        return match_obj.group(0)
+
+    def _urlify(s):
+        """
+        Extract urls from text and make html links out of them
+        """
+        return _URLIFY_RE.sub(_replace, s)
+
+    if truncate is None:
+        s = s.rstrip()
+    else:
+        s = truncatef(s, truncate, whole_word=True)
     s = html_escape(s)
-    if stylize:
-        s = desc_stylize(s)
-    s = _urlify_text(s)
+    s = _urlify(s)
+    if repo_name is not None:
+        s = urlify_issues(s, repo_name)
+    if link_ is not None:
+        # make href around everything that isn't a href already
+        s = linkify_others(s, link_)
+    s = s.replace('\r\n', '<br/>').replace('\n', '<br/>')
     return literal(s)
 
-def urlify_changesets(text_, repository):
-    """
-    Extract revision ids from changeset and make link from them
-
-    :param text_:
-    :param repository: repo name to build the URL with
-    """
-    from pylons import url  # doh, we need to re-import url to mock it later
-
-    def url_func(match_obj):
-        rev = match_obj.group(0)
-        return '<a class="revision-link" href="%(url)s">%(rev)s</a>' % {
-         'url': url('changeset_home', repo_name=repository, revision=rev),
-         'rev': rev,
-        }
-
-    return re.sub(r'(?:^|(?<=[\s(),]))([0-9a-fA-F]{12,40})(?=$|\s|[.,:()])', url_func, text_)
 
 def linkify_others(t, l):
+    """Add a default link to html with links.
+    HTML doesn't allow nesting of links, so the outer link must be broken up
+    in pieces and give space for other links.
+    """
     urls = re.compile(r'(\<a.*?\<\/a\>)',)
     links = []
     for e in urls.split(t):
-        if not urls.match(e):
+        if e.strip() and not urls.match(e):
             links.append('<a class="message-link" href="%s">%s</a>' % (l, e))
         else:
             links.append(e)
 
     return ''.join(links)
 
-def urlify_commit(text_, repository, link_=None):
-    """
-    Parses given text message and makes proper links.
-    issues are linked to given issue-server, and rest is a changeset link
-    if link_ is given, in other case it's a plain text
 
-    :param text_:
-    :param repository:
-    :param link_: changeset link
-    """
-    newtext = html_escape(text_)
-
-    # urlify changesets - extract revisions and make link out of them
-    newtext = urlify_changesets(newtext, repository)
-
-    # extract http/https links and make them real urls
-    newtext = _urlify_text(newtext)
-
-    newtext = urlify_issues(newtext, repository, link_)
-
-    return literal(newtext)
-
-def urlify_issues(newtext, repository, link_=None):
-    from kallithea import CONFIG as conf
-
-    # allow multiple issue servers to be used
-    valid_indices = [
-        x.group(1)
-        for x in map(lambda x: re.match(r'issue_pat(.*)', x), conf.keys())
-        if x and 'issue_server_link%s' % x.group(1) in conf
-        and 'issue_prefix%s' % x.group(1) in conf
-    ]
-
-    if valid_indices:
-        log.debug('found issue server suffixes `%s` during valuation of: %s',
-                  ','.join(valid_indices), newtext)
-
-    for pattern_index in valid_indices:
-        ISSUE_PATTERN = conf.get('issue_pat%s' % pattern_index)
-        ISSUE_SERVER_LNK = conf.get('issue_server_link%s' % pattern_index)
-        ISSUE_PREFIX = conf.get('issue_prefix%s' % pattern_index)
-
-        log.debug('pattern suffix `%s` PAT:%s SERVER_LINK:%s PREFIX:%s',
-                  pattern_index, ISSUE_PATTERN, ISSUE_SERVER_LNK,
-                     ISSUE_PREFIX)
-
-        URL_PAT = re.compile(ISSUE_PATTERN)
-
-        def url_func(match_obj):
-            pref = ''
-            if match_obj.group().startswith(' '):
-                pref = ' '
-
-            issue_id = ''.join(match_obj.groups())
-            issue_url = ISSUE_SERVER_LNK.replace('{id}', issue_id)
-            if repository:
-                issue_url = issue_url.replace('{repo}', repository)
-                repo_name = repository.split(URL_SEP)[-1]
-                issue_url = issue_url.replace('{repo_name}', repo_name)
-
-            return (
-                '%(pref)s<a class="%(cls)s" href="%(url)s">'
-                '%(issue-prefix)s%(id-repr)s'
-                '</a>'
-                ) % {
-                 'pref': pref,
-                 'cls': 'issue-tracker-link',
-                 'url': issue_url,
-                 'id-repr': issue_id,
-                 'issue-prefix': ISSUE_PREFIX,
-                 'serv': ISSUE_SERVER_LNK,
-                }
-        newtext = URL_PAT.sub(url_func, newtext)
-        log.debug('processed prefix:`%s` => %s', pattern_index, newtext)
-
-    # if we actually did something above
-    if link_:
-        # wrap not links into final link => link_
-        newtext = linkify_others(newtext, link_)
-    return newtext
+# Global variable that will hold the actual urlify_issues function body.
+# Will be set on first use when the global configuration has been read.
+_urlify_issues_f = None
 
 
-def rst(source):
-    return literal('<div class="rst-block">%s</div>' %
-                   MarkupRenderer.rst(source))
+def urlify_issues(newtext, repo_name):
+    """Urlify issue references according to .ini configuration"""
+    global _urlify_issues_f
+    if _urlify_issues_f is None:
+        from kallithea import CONFIG
+        from kallithea.model.db import URL_SEP
+        assert CONFIG['sqlalchemy.url'] # make sure config has been loaded
+
+        # Build chain of urlify functions, starting with not doing any transformation
+        tmp_urlify_issues_f = lambda s: s
+
+        issue_pat_re = re.compile(r'issue_pat(.*)')
+        for k in CONFIG.keys():
+            # Find all issue_pat* settings that also have corresponding server_link and prefix configuration
+            m = issue_pat_re.match(k)
+            if m is None:
+                continue
+            suffix = m.group(1)
+            issue_pat = CONFIG.get(k)
+            issue_server_link = CONFIG.get('issue_server_link%s' % suffix)
+            issue_prefix = CONFIG.get('issue_prefix%s' % suffix)
+            if issue_pat and issue_server_link and issue_prefix:
+                log.debug('issue pattern %r: %r -> %r %r', suffix, issue_pat, issue_server_link, issue_prefix)
+            else:
+                log.error('skipping incomplete issue pattern %r: %r -> %r %r', suffix, issue_pat, issue_server_link, issue_prefix)
+                continue
+
+            # Wrap tmp_urlify_issues_f with substitution of this pattern, while making sure all loop variables (and compiled regexpes) are bound
+            issue_re = re.compile(issue_pat)
+            def issues_replace(match_obj,
+                               issue_server_link=issue_server_link, issue_prefix=issue_prefix):
+                leadingspace = ' ' if match_obj.group().startswith(' ') else ''
+                issue_id = ''.join(match_obj.groups())
+                issue_url = issue_server_link.replace('{id}', issue_id)
+                issue_url = issue_url.replace('{repo}', repo_name)
+                issue_url = issue_url.replace('{repo_name}', repo_name.split(URL_SEP)[-1])
+                return (
+                    '%(leadingspace)s<a class="issue-tracker-link" href="%(url)s">'
+                    '%(issue-prefix)s%(id-repr)s'
+                    '</a>'
+                    ) % {
+                     'leadingspace': leadingspace,
+                     'url': issue_url,
+                     'id-repr': issue_id,
+                     'issue-prefix': issue_prefix,
+                     'serv': issue_server_link,
+                    }
+            tmp_urlify_issues_f = (lambda s,
+                                          issue_re=issue_re, issues_replace=issues_replace, chain_f=tmp_urlify_issues_f:
+                                   issue_re.sub(issues_replace, chain_f(s)))
+
+        # Set tmp function globally - atomically
+        _urlify_issues_f = tmp_urlify_issues_f
+
+    return _urlify_issues_f(newtext)
 
 
-def rst_w_mentions(source):
+def render_w_mentions(source, repo_name=None):
     """
-    Wrapped rst renderer with @mention highlighting
+    Render plain text with revision hashes and issue references urlified
+    and with @mention highlighting.
+    """
+    s = safe_unicode(source)
+    s = urlify_text(s, repo_name=repo_name)
+    return literal('<div class="formatted-fixed">%s</div>' % s)
 
-    :param source:
-    """
-    return literal('<div class="rst-block">%s</div>' %
-                   MarkupRenderer.rst_with_mentions(source))
 
 def short_ref(ref_type, ref_name):
     if ref_type == 'rev':
@@ -1410,14 +1168,17 @@
     return l
 
 def changeset_status(repo, revision):
+    from kallithea.model.changeset_status import ChangesetStatusModel
     return ChangesetStatusModel().get_status(repo, revision)
 
 
 def changeset_status_lbl(changeset_status):
-    return dict(ChangesetStatus.STATUSES).get(changeset_status)
+    from kallithea.model.db import ChangesetStatus
+    return ChangesetStatus.get_status_lbl(changeset_status)
 
 
 def get_permission_name(key):
+    from kallithea.model.db import Permission
     return dict(Permission.PERMS).get(key)
 
 
--- a/kallithea/lib/hooks.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/hooks.py	Fri Nov 18 01:11:13 2016 +0100
@@ -35,7 +35,7 @@
 from kallithea.lib.utils import action_logger
 from kallithea.lib.vcs.backends.base import EmptyChangeset
 from kallithea.lib.exceptions import HTTPLockedRC, UserCreationError
-from kallithea.lib.utils2 import safe_str, _extract_extras
+from kallithea.lib.utils2 import safe_str, safe_unicode, _extract_extras
 from kallithea.model.db import Repository, User
 
 
@@ -79,12 +79,11 @@
 
     last_cs = repo[len(repo) - 1]
 
-    msg = ('Repository size .hg:%s repo:%s total:%s\n'
+    msg = ('Repository size .hg: %s Checkout: %s Total: %s\n'
            'Last revision is now r%s:%s\n') % (
         size_hg_f, size_root_f, size_total_f, last_cs.rev(), last_cs.hex()[:12]
     )
-
-    sys.stdout.write(msg)
+    ui.status(msg)
 
 
 def pre_push(ui, repo, **kwargs):
@@ -100,14 +99,13 @@
         _http_ret = HTTPLockedRC(ex.repository, locked_by)
         if str(_http_ret.code).startswith('2'):
             #2xx Codes don't raise exceptions
-            sys.stdout.write(_http_ret.title)
+            ui.status(safe_str(_http_ret.title))
         else:
             raise _http_ret
 
 
 def pre_pull(ui, repo, **kwargs):
-    # pre push function, currently used to ban pushing when
-    # repository is locked
+    # pre pull function ...
     ex = _extract_extras()
     if ex.locked_by[0]:
         locked_by = User.get(ex.locked_by[0]).username
@@ -116,7 +114,7 @@
         _http_ret = HTTPLockedRC(ex.repository, locked_by)
         if str(_http_ret.code).startswith('2'):
             #2xx Codes don't raise exceptions
-            sys.stdout.write(_http_ret.title)
+            ui.status(safe_str(_http_ret.title))
         else:
             raise _http_ret
 
@@ -144,14 +142,14 @@
     if ex.make_lock is not None and ex.make_lock:
         Repository.lock(Repository.get_by_repo_name(ex.repository), user.user_id)
         #msg = 'Made lock on repo `%s`' % repository
-        #sys.stdout.write(msg)
+        #ui.status(msg)
 
     if ex.locked_by[0]:
         locked_by = User.get(ex.locked_by[0]).username
         _http_ret = HTTPLockedRC(ex.repository, locked_by)
         if str(_http_ret.code).startswith('2'):
             #2xx Codes don't raise exceptions
-            sys.stdout.write(_http_ret.title)
+            ui.status(safe_str(_http_ret.title))
     return 0
 
 
@@ -199,15 +197,14 @@
 
     if ex.make_lock is not None and not ex.make_lock:
         Repository.unlock(Repository.get_by_repo_name(ex.repository))
-        msg = 'Released lock on repo `%s`\n' % ex.repository
-        sys.stdout.write(msg)
+        ui.status(safe_str('Released lock on repo `%s`\n' % ex.repository))
 
     if ex.locked_by[0]:
         locked_by = User.get(ex.locked_by[0]).username
         _http_ret = HTTPLockedRC(ex.repository, locked_by)
         if str(_http_ret.code).startswith('2'):
             #2xx Codes don't raise exceptions
-            sys.stdout.write(_http_ret.title)
+            ui.status(safe_str(_http_ret.title))
 
     return 0
 
@@ -227,7 +224,7 @@
      'created_on',
      'enable_downloads',
      'repo_id',
-     'user_id',
+     'owner_id',
      'enable_statistics',
      'clone_uri',
      'fork_id',
@@ -309,7 +306,7 @@
      'created_on',
      'enable_downloads',
      'repo_id',
-     'user_id',
+     'owner_id',
      'enable_statistics',
      'clone_uri',
      'fork_id',
@@ -376,8 +373,8 @@
 def handle_git_receive(repo_path, revs, env, hook_type):
     """
     A really hacky method that is run by git post-receive hook and logs
-    an push action together with pushed revisions. It's executed by subprocess
-    thus needs all info to be able to create a on the fly pylons environment,
+    a push action together with pushed revisions. It's executed by subprocess
+    thus needs all info to be able to create an on the fly app environment,
     connect to database and run the logging code. Hacky as sh*t but works.
 
     :param repo_path:
@@ -387,17 +384,18 @@
     from paste.deploy import appconfig
     from sqlalchemy import engine_from_config
     from kallithea.config.environment import load_environment
-    from kallithea.model import init_model
+    from kallithea.model.base import init_model
     from kallithea.model.db import Ui
     from kallithea.lib.utils import make_ui
     extras = _extract_extras(env)
 
+    repo_path = safe_unicode(repo_path)
     path, ini_name = os.path.split(extras['config'])
     conf = appconfig('config:%s' % ini_name, relative_to=path)
     load_environment(conf.global_conf, conf.local_conf, test_env=False,
                      test_index=False)
 
-    engine = engine_from_config(conf, 'sqlalchemy.db1.')
+    engine = engine_from_config(conf, 'sqlalchemy.')
     init_model(engine)
 
     baseui = make_ui('db')
@@ -425,14 +423,14 @@
     elif hook_type == 'post' and _hooks.get(Ui.HOOK_PUSH):
         rev_data = []
         for l in revs:
-            old_rev, new_rev, ref = l.split(' ')
+            old_rev, new_rev, ref = l.strip().split(' ')
             _ref_data = ref.split('/')
             if _ref_data[1] in ['tags', 'heads']:
                 rev_data.append({'old_rev': old_rev,
                                  'new_rev': new_rev,
                                  'ref': ref,
                                  'type': _ref_data[1],
-                                 'name': _ref_data[2].strip()})
+                                 'name': '/'.join(_ref_data[2:])})
 
         git_revs = []
 
--- a/kallithea/lib/indexers/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/indexers/__init__.py	Fri Nov 18 01:11:13 2016 +0100
@@ -28,10 +28,10 @@
 import os
 import sys
 import logging
-from os.path import dirname as dn, join as jn
+from os.path import dirname
 
 # Add location of top level folder to sys.path
-sys.path.append(dn(dn(dn(os.path.realpath(__file__)))))
+sys.path.append(dirname(dirname(dirname(os.path.realpath(__file__)))))
 
 from whoosh.analysis import RegexTokenizer, LowercaseFilter
 from whoosh.fields import TEXT, ID, STORED, NUMERIC, BOOLEAN, Schema, FieldType, DATETIME
@@ -140,7 +140,7 @@
         res = self.searcher.stored_fields(docid[0])
         log.debug('result: %s', res)
         if self.search_type == 'content':
-            full_repo_path = jn(self.repo_location, res['repository'])
+            full_repo_path = os.path.join(self.repo_location, res['repository'])
             f_path = res['path'].split(full_repo_path)[-1]
             f_path = f_path.lstrip(os.sep)
             content_short = self.get_short_content(res, docid[1])
@@ -149,7 +149,7 @@
                         'f_path': f_path
             })
         elif self.search_type == 'path':
-            full_repo_path = jn(self.repo_location, res['repository'])
+            full_repo_path = os.path.join(self.repo_location, res['repository'])
             f_path = res['path'].split(full_repo_path)[-1]
             f_path = f_path.lstrip(os.sep)
             res.update({'f_path': f_path})
--- a/kallithea/lib/indexers/daemon.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/indexers/daemon.py	Fri Nov 18 01:11:13 2016 +0100
@@ -34,14 +34,13 @@
 from shutil import rmtree
 from time import mktime
 
-from os.path import dirname as dn
-from os.path import join as jn
+from os.path import dirname
 
 # Add location of top level folder to sys.path
-project_path = dn(dn(dn(dn(os.path.realpath(__file__)))))
+project_path = dirname(dirname(dirname(dirname(os.path.realpath(__file__)))))
 sys.path.append(project_path)
 
-from kallithea.config.conf import INDEX_EXTENSIONS
+from kallithea.config.conf import INDEX_EXTENSIONS, INDEX_FILENAMES
 from kallithea.model.scm import ScmModel
 from kallithea.model.db import Repository
 from kallithea.lib.utils2 import safe_unicode, safe_str
@@ -136,7 +135,7 @@
             cs = self._get_index_changeset(repo)
             for _topnode, _dirs, files in cs.walk('/'):
                 for f in files:
-                    index_paths_.add(jn(safe_str(repo.path), safe_str(f.path)))
+                    index_paths_.add(os.path.join(safe_str(repo.path), safe_str(f.path)))
 
         except RepositoryError:
             log.debug(traceback.format_exc())
@@ -162,6 +161,13 @@
         node = cs.get_node(node_path)
         return node
 
+    def is_indexable_node(self, node):
+        """
+        Just index the content of chosen files, skipping binary files
+        """
+        return (node.extension in INDEX_EXTENSIONS or node.name in INDEX_FILENAMES) and \
+               not node.is_binary
+
     def get_node_mtime(self, node):
         return mktime(node.last_changeset.date.timetuple())
 
@@ -177,8 +183,7 @@
             return 0, 0
 
         indexed = indexed_w_content = 0
-        # we just index the content of chosen files, and skip binary files
-        if node.extension in INDEX_EXTENSIONS and not node.is_binary:
+        if self.is_indexable_node(node):
             u_content = node.content
             if not isinstance(u_content, unicode):
                 log.warning('  >> %s Could not get this content as unicode '
--- a/kallithea/lib/ipaddr.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/ipaddr.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1245,7 +1245,7 @@
               '192.168.1.1'
               '192.168.1.1/255.255.255.255'
               '192.168.1.1/32'
-              are also functionaly equivalent. That is to say, failing to
+              are also functionally equivalent. That is to say, failing to
               provide a subnetmask will create an object with a mask of /32.
 
               If the mask (portion after the / in the argument) is given in
--- a/kallithea/lib/markup_renderer.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/markup_renderer.py	Fri Nov 18 01:11:13 2016 +0100
@@ -35,8 +35,9 @@
 log = logging.getLogger(__name__)
 
 
-url_re = re.compile(r'''(\bhttps?://(?:[\da-zA-Z0-9@:.-]+)'''
-                    r'''(?:[/a-zA-Z0-9_=@#~&+%.,:;?!*()-]*[/a-zA-Z0-9_=@#~])?)''')
+url_re = re.compile(r'''\bhttps?://(?:[\da-zA-Z0-9@:.-]+)'''
+                    r'''(?:[/a-zA-Z0-9_=@#~&+%.,:;?!*()-]*[/a-zA-Z0-9_=@#~])?''')
+
 
 class MarkupRenderer(object):
     RESTRUCTUREDTEXT_DISALLOWED_DIRECTIVES = ['include', 'meta', 'raw']
@@ -132,7 +133,7 @@
             source = newline.join(source.splitlines())
 
         def url_func(match_obj):
-            url_full = match_obj.groups()[0]
+            url_full = match_obj.group(0)
             return '<a href="%(url)s">%(url)s</a>' % ({'url': url_full})
         source = url_re.sub(url_func, source)
         return '<br />' + source.replace("\n", '<br />')
@@ -189,10 +190,9 @@
 
     @classmethod
     def rst_with_mentions(cls, source):
-        mention_pat = re.compile(MENTIONS_REGEX)
 
         def wrapp(match_obj):
             uname = match_obj.groups()[0]
             return '\ **@%(uname)s**\ ' % {'uname': uname}
-        mention_hl = mention_pat.sub(wrapp, source).strip()
+        mention_hl = MENTIONS_REGEX.sub(wrapp, source).strip()
         return cls.rst(mention_hl)
--- a/kallithea/lib/middleware/pygrack.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/middleware/pygrack.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,3 +1,30 @@
+# -*- coding: utf-8 -*-
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+"""
+kallithea.lib.middleware.pygrack
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Python implementation of git-http-backend's Smart HTTP protocol
+
+Based on original code from git_http_backend.py project.
+
+Copyright (c) 2010 Daniel Dotsenko <dotsa@hotmail.com>
+Copyright (c) 2012 Marcin Kuzminski <marcin@python-works.com>
+
+This file was forked by the Kallithea project in July 2014.
+"""
+
 import os
 import socket
 import logging
@@ -7,6 +34,7 @@
 
 import kallithea
 from kallithea.lib.vcs import subprocessio
+from kallithea.lib.utils2 import safe_unicode
 
 log = logging.getLogger(__name__)
 
@@ -59,7 +87,9 @@
 
         :param path:
         """
-        return path.split(self.repo_name, 1)[-1].strip('/')
+        path = safe_unicode(path)
+        assert path.startswith('/' + self.repo_name + '/')
+        return path[len(self.repo_name) + 2:].strip('/')
 
     def inforefs(self, request, environ):
         """
@@ -72,14 +102,17 @@
             log.debug('command %s not allowed', git_command)
             return exc.HTTPMethodNotAllowed()
 
-        # note to self:
-        # please, resist the urge to add '\n' to git capture and increment
-        # line count by 1.
-        # The code in Git client not only does NOT need '\n', but actually
-        # blows up if you sprinkle "flush" (0000) as "0001\n".
-        # It reads binary, per number of bytes specified.
-        # if you do add '\n' as part of data, count it.
-        server_advert = '# service=%s' % git_command
+        # From Documentation/technical/http-protocol.txt shipped with Git:
+        #
+        # Clients MUST verify the first pkt-line is `# service=$servicename`.
+        # Servers MUST set $servicename to be the request parameter value.
+        # Servers SHOULD include an LF at the end of this line.
+        # Clients MUST ignore an LF at the end of the line.
+        #
+        #  smart_reply     =  PKT-LINE("# service=$servicename" LF)
+        #                     ref_list
+        #                     "0000"
+        server_advert = '# service=%s\n' % git_command
         packet_len = str(hex(len(server_advert) + 4)[2:].rjust(4, '0')).lower()
         _git_path = kallithea.CONFIG.get('git_path', 'git')
         cmd = [_git_path, git_command[4:],
--- a/kallithea/lib/middleware/simplegit.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/middleware/simplegit.py	Fri Nov 18 01:11:13 2016 +0100
@@ -38,7 +38,7 @@
     HTTPNotAcceptable
 from kallithea.model.db import User, Ui
 
-from kallithea.lib.utils2 import safe_str, safe_unicode, fix_PATH, get_server_url,\
+from kallithea.lib.utils2 import safe_str, safe_unicode, fix_PATH, get_server_url, \
     _set_extras
 from kallithea.lib.base import BaseVCSController, WSGIResultCloseCallback
 from kallithea.lib.utils import make_ui, is_valid_repo
@@ -66,8 +66,6 @@
     def _handle_request(self, environ, start_response):
         if not is_git(environ):
             return self.application(environ, start_response)
-        if not self._check_ssl(environ):
-            return HTTPNotAcceptable('SSL REQUIRED !')(environ, start_response)
 
         ip_addr = self._get_ip_addr(environ)
         username = None
@@ -99,7 +97,7 @@
         # CHECK ANONYMOUS PERMISSION
         #======================================================================
         if action in ['pull', 'push']:
-            anonymous_user = self.__get_user('default')
+            anonymous_user = User.get_default_user(cache=True)
             username = anonymous_user.username
             if anonymous_user.active:
                 # ONLY check permissions if the user is activated
@@ -146,7 +144,7 @@
                 # CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME
                 #==============================================================
                 try:
-                    user = self.__get_user(username)
+                    user = User.get_by_username_or_email(username)
                     if user is None or not user.active:
                         return HTTPForbidden()(environ, start_response)
                     username = user.username
@@ -210,8 +208,7 @@
                     lambda: self._invalidate_cache(repo_name))
             return result
         except HTTPLockedRC as e:
-            _code = CONFIG.get('lock_ret_code')
-            log.debug('Repository LOCKED ret code %s!', _code)
+            log.debug('Locked, response %s: %s', e.code, e.title)
             return e(environ, start_response)
         except Exception:
             log.error(traceback.format_exc())
@@ -228,7 +225,7 @@
         from kallithea.lib.middleware.pygrack import make_wsgi_app
         app = make_wsgi_app(
             repo_root=safe_str(self.basepath),
-            repo_name=repo_name,
+            repo_name=safe_unicode(repo_name),
             extras=extras,
         )
         return app
@@ -248,9 +245,6 @@
 
         return repo_name
 
-    def __get_user(self, username):
-        return User.get_by_username(username)
-
     def __get_action(self, environ):
         """
         Maps git request commands into a pull or push command.
@@ -295,12 +289,11 @@
         if action == 'pull' and _hooks.get(Ui.HOOK_PULL):
             log_pull_action(ui=baseui, repo=_repo._repo)
 
-    def __inject_extras(self, repo_path, baseui, extras={}):
+    def __inject_extras(self, repo_path, baseui, extras=None):
         """
         Injects some extra params into baseui instance
 
         :param baseui: baseui instance
         :param extras: dict with extra params to put into baseui
         """
-
-        _set_extras(extras)
+        _set_extras(extras or {})
--- a/kallithea/lib/middleware/simplehg.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/middleware/simplehg.py	Fri Nov 18 01:11:13 2016 +0100
@@ -37,7 +37,7 @@
     HTTPNotAcceptable
 from kallithea.model.db import User
 
-from kallithea.lib.utils2 import safe_str, safe_unicode, fix_PATH, get_server_url,\
+from kallithea.lib.utils2 import safe_str, safe_unicode, fix_PATH, get_server_url, \
     _set_extras
 from kallithea.lib.base import BaseVCSController, WSGIResultCloseCallback
 from kallithea.lib.utils import make_ui, is_valid_repo, ui_sections
@@ -71,8 +71,6 @@
     def _handle_request(self, environ, start_response):
         if not is_mercurial(environ):
             return self.application(environ, start_response)
-        if not self._check_ssl(environ):
-            return HTTPNotAcceptable('SSL REQUIRED !')(environ, start_response)
 
         ip_addr = self._get_ip_addr(environ)
         username = None
@@ -105,7 +103,7 @@
         # CHECK ANONYMOUS PERMISSION
         #======================================================================
         if action in ['pull', 'push']:
-            anonymous_user = self.__get_user('default')
+            anonymous_user = User.get_default_user(cache=True)
             username = anonymous_user.username
             if anonymous_user.active:
                 # ONLY check permissions if the user is activated
@@ -152,7 +150,7 @@
                 # CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME
                 #==============================================================
                 try:
-                    user = self.__get_user(username)
+                    user = User.get_by_username_or_email(username)
                     if user is None or not user.active:
                         return HTTPForbidden()(environ, start_response)
                     username = user.username
@@ -217,8 +215,8 @@
             if str(e).find('not found') != -1:
                 return HTTPNotFound()(environ, start_response)
         except HTTPLockedRC as e:
-            _code = CONFIG.get('lock_ret_code')
-            log.debug('Repository LOCKED ret code %s!', _code)
+            # Before Mercurial 3.6, lock exceptions were caught here
+            log.debug('Locked, response %s: %s', e.code, e.title)
             return e(environ, start_response)
         except Exception:
             log.error(traceback.format_exc())
@@ -229,7 +227,18 @@
         Make an wsgi application using hgweb, and inject generated baseui
         instance, additionally inject some extras into ui object
         """
-        return hgweb_mod.hgweb(repo_name, name=repo_name, baseui=baseui)
+        class HgWebWrapper(hgweb_mod.hgweb):
+            # Work-around for Mercurial 3.6+ causing lock exceptions to be
+            # thrown late
+            def _runwsgi(self, req, repo):
+                try:
+                    return super(HgWebWrapper, self)._runwsgi(req, repo)
+                except HTTPLockedRC as e:
+                    log.debug('Locked, response %s: %s', e.code, e.title)
+                    req.respond(e.status, 'text/plain')
+                    return ''
+
+        return HgWebWrapper(repo_name, name=repo_name, baseui=baseui)
 
     def __get_repository(self, environ):
         """
@@ -248,9 +257,6 @@
 
         return repo_name
 
-    def __get_user(self, username):
-        return User.get_by_username(username)
-
     def __get_action(self, environ):
         """
         Maps mercurial request commands into a clone,pull or push command.
@@ -275,7 +281,7 @@
         raise Exception('Unable to detect pull/push action !!'
                         'Are you using non standard command or client ?')
 
-    def __inject_extras(self, repo_path, baseui, extras={}):
+    def __inject_extras(self, repo_path, baseui, extras=None):
         """
         Injects some extra params into baseui instance
 
@@ -294,4 +300,4 @@
             for section in ui_sections:
                 for k, v in repoui.configitems(section):
                     baseui.setconfig(section, k, v)
-        _set_extras(extras)
+        _set_extras(extras or {})
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/lib/page.py	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,247 @@
+# -*- coding: utf-8 -*-
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+"""
+Custom paging classes
+"""
+
+import math
+import re
+from kallithea.config.routing import url
+from webhelpers.html import literal, HTML
+from webhelpers.paginate import Page as _Page
+
+class Page(_Page):
+    """
+    Custom pager to match rendering style with YUI paginator
+    """
+
+    def __init__(self, *args, **kwargs):
+        kwargs.setdefault('url', url.current)
+        _Page.__init__(self, *args, **kwargs)
+
+    def _get_pos(self, cur_page, max_page, items):
+        edge = (items / 2) + 1
+        if (cur_page <= edge):
+            radius = max(items / 2, items - cur_page)
+        elif (max_page - cur_page) < edge:
+            radius = (items - 1) - (max_page - cur_page)
+        else:
+            radius = items / 2
+
+        left = max(1, (cur_page - (radius)))
+        right = min(max_page, cur_page + (radius))
+        return left, cur_page, right
+
+    def _range(self, regexp_match):
+        """
+        Return range of linked pages (e.g. '1 2 [3] 4 5 6 7 8').
+
+        Arguments:
+
+        regexp_match
+            A "re" (regular expressions) match object containing the
+            radius of linked pages around the current page in
+            regexp_match.group(1) as a string
+
+        This function is supposed to be called as a callable in
+        re.sub.
+
+        """
+        radius = int(regexp_match.group(1))
+
+        # Compute the first and last page number within the radius
+        # e.g. '1 .. 5 6 [7] 8 9 .. 12'
+        # -> leftmost_page  = 5
+        # -> rightmost_page = 9
+        leftmost_page, _cur, rightmost_page = self._get_pos(self.page,
+                                                            self.last_page,
+                                                            (radius * 2) + 1)
+        nav_items = []
+
+        # Create a link to the first page (unless we are on the first page
+        # or there would be no need to insert '..' spacers)
+        if self.page != self.first_page and self.first_page < leftmost_page:
+            nav_items.append(HTML.li(self._pagerlink(self.first_page, self.first_page)))
+
+        # Insert dots if there are pages between the first page
+        # and the currently displayed page range
+        if leftmost_page - self.first_page > 1:
+            # Wrap in a SPAN tag if nolink_attr is set
+            text_ = '..'
+            if self.dotdot_attr:
+                text_ = HTML.span(c=text_, **self.dotdot_attr)
+            nav_items.append(HTML.li(text_))
+
+        for thispage in xrange(leftmost_page, rightmost_page + 1):
+            # Highlight the current page number and do not use a link
+            text_ = str(thispage)
+            if thispage == self.page:
+                # Wrap in a SPAN tag if nolink_attr is set
+                if self.curpage_attr:
+                    text_ = HTML.li(HTML.span(c=text_), **self.curpage_attr)
+                nav_items.append(text_)
+            # Otherwise create just a link to that page
+            else:
+                nav_items.append(HTML.li(self._pagerlink(thispage, text_)))
+
+        # Insert dots if there are pages between the displayed
+        # page numbers and the end of the page range
+        if self.last_page - rightmost_page > 1:
+            text_ = '..'
+            # Wrap in a SPAN tag if nolink_attr is set
+            if self.dotdot_attr:
+                text_ = HTML.span(c=text_, **self.dotdot_attr)
+            nav_items.append(HTML.li(text_))
+
+        # Create a link to the very last page (unless we are on the last
+        # page or there would be no need to insert '..' spacers)
+        if self.page != self.last_page and rightmost_page < self.last_page:
+            nav_items.append(HTML.li(self._pagerlink(self.last_page, self.last_page)))
+
+        #_page_link = url.current()
+        #nav_items.append(literal('<link rel="prerender" href="%s?page=%s">' % (_page_link, str(int(self.page)+1))))
+        #nav_items.append(literal('<link rel="prefetch" href="%s?page=%s">' % (_page_link, str(int(self.page)+1))))
+        return self.separator.join(nav_items)
+
+    def pager(self, format='$link_previous ~2~ $link_next', page_param='page', partial_param='partial',
+        show_if_single_page=False, separator=' ', onclick=None,
+        symbol_first='<<', symbol_last='>>',
+        symbol_previous='<', symbol_next='>',
+        link_attr=None,
+        curpage_attr=None,
+        dotdot_attr=None, **kwargs):
+        self.curpage_attr = curpage_attr or {'class': 'active'}
+        self.separator = separator
+        self.pager_kwargs = kwargs
+        self.page_param = page_param
+        self.partial_param = partial_param
+        self.onclick = onclick
+        self.link_attr = link_attr or {'class': 'pager_link', 'rel': 'prerender'}
+        self.dotdot_attr = dotdot_attr or {'class': 'pager_dotdot'}
+
+        # Don't show navigator if there is no more than one page
+        if self.page_count == 0 or (self.page_count == 1 and not show_if_single_page):
+            return ''
+
+        from string import Template
+        # Replace ~...~ in token format by range of pages
+        result = re.sub(r'~(\d+)~', self._range, format)
+
+        # Interpolate '%' variables
+        result = Template(result).safe_substitute({
+            'first_page': self.first_page,
+            'last_page': self.last_page,
+            'page': self.page,
+            'page_count': self.page_count,
+            'items_per_page': self.items_per_page,
+            'first_item': self.first_item,
+            'last_item': self.last_item,
+            'item_count': self.item_count,
+            'link_first': self.page > self.first_page and \
+                    self._pagerlink(self.first_page, symbol_first) or '',
+            'link_last': self.page < self.last_page and \
+                    self._pagerlink(self.last_page, symbol_last) or '',
+            'link_previous': HTML.li(self.previous_page and \
+                    self._pagerlink(self.previous_page, symbol_previous) \
+                    or HTML.a(symbol_previous)),
+            'link_next': HTML.li(self.next_page and \
+                    self._pagerlink(self.next_page, symbol_next) \
+                    or HTML.a(symbol_next))
+        })
+
+        return literal(result)
+
+
+class RepoPage(Page):
+
+    def __init__(self, collection, page=1, items_per_page=20,
+                 item_count=None, **kwargs):
+
+        """Create a "RepoPage" instance. special pager for paging
+        repository
+        """
+        # TODO: call baseclass __init__
+        self._url_generator = kwargs.pop('url', url.current)
+
+        # Safe the kwargs class-wide so they can be used in the pager() method
+        self.kwargs = kwargs
+
+        # Save a reference to the collection
+        self.original_collection = collection
+
+        self.collection = collection
+
+        # The self.page is the number of the current page.
+        # The first page has the number 1!
+        try:
+            self.page = int(page)  # make it int() if we get it as a string
+        except (ValueError, TypeError):
+            self.page = 1
+
+        self.items_per_page = items_per_page
+
+        # Unless the user tells us how many items the collections has
+        # we calculate that ourselves.
+        if item_count is not None:
+            self.item_count = item_count
+        else:
+            self.item_count = len(self.collection)
+
+        # Compute the number of the first and last available page
+        if self.item_count > 0:
+            self.first_page = 1
+            self.page_count = int(math.ceil(float(self.item_count) /
+                                            self.items_per_page))
+            self.last_page = self.first_page + self.page_count - 1
+
+            # Make sure that the requested page number is the range of
+            # valid pages
+            if self.page > self.last_page:
+                self.page = self.last_page
+            elif self.page < self.first_page:
+                self.page = self.first_page
+
+            # Note: the number of items on this page can be less than
+            #       items_per_page if the last page is not full
+            self.first_item = max(0, (self.item_count) - (self.page *
+                                                          items_per_page))
+            self.last_item = ((self.item_count - 1) - items_per_page *
+                              (self.page - 1))
+
+            self.items = list(self.collection[self.first_item:self.last_item + 1])
+
+            # Links to previous and next page
+            if self.page > self.first_page:
+                self.previous_page = self.page - 1
+            else:
+                self.previous_page = None
+
+            if self.page < self.last_page:
+                self.next_page = self.page + 1
+            else:
+                self.next_page = None
+
+        # No items available
+        else:
+            self.first_page = None
+            self.page_count = 0
+            self.last_page = None
+            self.first_item = None
+            self.last_item = None
+            self.previous_page = None
+            self.next_page = None
+            self.items = []
+
+        # This is a subclass of the 'list' type. Initialise the list now.
+        list.__init__(self, reversed(self.items))
--- a/kallithea/lib/paster_commands/cache_keys.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/paster_commands/cache_keys.py	Fri Nov 18 01:11:13 2016 +0100
@@ -29,19 +29,12 @@
 
 import os
 import sys
-import logging
 
+from kallithea.lib.paster_commands.common import BasePasterCommand
 from kallithea.model.meta import Session
-from kallithea.lib.utils import BasePasterCommand
+from kallithea.lib.utils2 import safe_str
 from kallithea.model.db import CacheInvalidation
 
-# Add location of top level folder to sys.path
-from os.path import dirname as dn
-rc_path = dn(dn(dn(os.path.realpath(__file__))))
-sys.path.append(rc_path)
-
-log = logging.getLogger(__name__)
-
 
 class Command(BasePasterCommand):
 
@@ -57,18 +50,18 @@
     def command(self):
         #get SqlAlchemy session
         self._init_session()
+
         _caches = CacheInvalidation.query().order_by(CacheInvalidation.cache_key).all()
         if self.options.show:
             for c_obj in _caches:
-                print 'key:%s active:%s' % (c_obj.cache_key, c_obj.cache_active)
+                print 'key:%s active:%s' % (safe_str(c_obj.cache_key), c_obj.cache_active)
         elif self.options.cleanup:
             for c_obj in _caches:
                 Session().delete(c_obj)
-                print 'removing key:%s' % (c_obj.cache_key)
-                Session().commit()
+                print 'Removing key: %s' % (safe_str(c_obj.cache_key))
+            Session().commit()
         else:
-            print 'nothing done exiting...'
-        sys.exit(0)
+            print 'Nothing done, exiting...'
 
     def update_parser(self):
         self.parser.add_option(
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/lib/paster_commands/celeryd.py	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,46 @@
+# -*- coding: utf-8 -*-
+
+import kallithea
+from kallithea.lib.paster_commands.common import BasePasterCommand
+from kallithea.lib.utils import load_rcextensions
+from kallithea.lib.utils2 import str2bool
+
+__all__ = ['Command']
+
+
+class Command(BasePasterCommand):
+    """Start the celery worker
+
+    Starts the celery worker that uses a paste.deploy configuration
+    file.
+    """
+
+    usage = 'CONFIG_FILE [celeryd options...]'
+    summary = __doc__.splitlines()[0]
+    description = "".join(__doc__.splitlines()[2:])
+    group_name = "Kallithea"
+
+    parser = BasePasterCommand.standard_parser(quiet=True)
+
+    def update_parser(self):
+        from kallithea.lib import celerypylons
+        cmd = celerypylons.worker.worker(celerypylons.app.app_or_default())
+        for x in cmd.get_options():
+            self.parser.add_option(x)
+
+    def command(self):
+        from kallithea.lib import celerypylons
+        from pylons import config
+        try:
+            CELERY_ON = str2bool(config['app_conf'].get('use_celery'))
+        except KeyError:
+            CELERY_ON = False
+
+        if not CELERY_ON:
+            raise Exception('Please set use_celery = true in .ini config '
+                            'file before running celeryd')
+        kallithea.CELERY_ON = CELERY_ON
+
+        load_rcextensions(config['here'])
+        cmd = celerypylons.worker.worker(celerypylons.app.app_or_default())
+        return cmd.run(**vars(self.options))
--- a/kallithea/lib/paster_commands/cleanup.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/paster_commands/cleanup.py	Fri Nov 18 01:11:13 2016 +0100
@@ -22,7 +22,7 @@
 Original author and date, and relevant copyright and licensing information is below:
 :created_on: Jul 14, 2012
 :author: marcink
-:copyright: (c) 2013 RhodeCode GmbH.
+:copyright: (c) 2013 RhodeCode GmbH, and others.
 :license: GPLv3, see LICENSE.md for more details.
 """
 
@@ -31,20 +31,13 @@
 import sys
 import re
 import shutil
-import logging
 import datetime
 
-from kallithea.lib.utils import BasePasterCommand, ask_ok, REMOVED_REPO_PAT
+from kallithea.lib.paster_commands.common import ask_ok, BasePasterCommand
+from kallithea.lib.utils import REMOVED_REPO_PAT
 from kallithea.lib.utils2 import safe_str
 from kallithea.model.db import Ui
 
-# Add location of top level folder to sys.path
-from os.path import dirname as dn
-rc_path = dn(dn(dn(os.path.realpath(__file__))))
-sys.path.append(rc_path)
-
-log = logging.getLogger(__name__)
-
 
 class Command(BasePasterCommand):
 
@@ -76,7 +69,7 @@
 
         :param name:
         """
-        date_part = name[4:19]  # 4:19 since we don't parse milisecods
+        date_part = name[4:19]  # 4:19 since we don't parse milliseconds
         return datetime.datetime.strptime(date_part, '%Y%m%d_%H%M%S')
 
     def command(self):
@@ -97,6 +90,8 @@
                                       self._extract_date(loc)])
                 else:
                     dirs.append(loc)
+            if dirs:
+                print 'Scanning: %s' % dn_
 
         #filter older than (if present)!
         now = datetime.datetime.now()
@@ -110,27 +105,25 @@
                     to_remove_filtered.append([name, date_])
 
             to_remove = to_remove_filtered
-            print >> sys.stdout, 'removing %s deleted repos older than %s (%s)' \
+            print 'Removing %s deleted repos older than %s (%s)' \
                 % (len(to_remove), older_than, older_than_date)
         else:
-            print >> sys.stdout, 'removing all [%s] deleted repos' \
-                % len(to_remove)
+            print 'Removing all %s deleted repos' % len(to_remove)
         if self.options.dont_ask or not to_remove:
             # don't ask just remove !
             remove = True
         else:
             remove = ask_ok('the following repositories will be deleted completely:\n%s\n'
                             'are you sure you want to remove them [y/n]?'
-                            % ', \n'.join(['%s removed on %s'
-                    % (safe_str(x[0]), safe_str(x[1])) for x in to_remove]))
+                            % '\n'.join(['%s removed on %s' % (safe_str(x[0]), safe_str(x[1]))
+                                         for x in to_remove]))
 
         if remove:
             for path, date_ in to_remove:
-                print >> sys.stdout, 'removing repository %s' % path
+                print 'Removing repository %s' % path
                 shutil.rmtree(path)
         else:
-            print 'nothing done exiting...'
-            sys.exit(0)
+            print 'Nothing done, exiting...'
 
     def update_parser(self):
         self.parser.add_option(
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/lib/paster_commands/common.py	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,107 @@
+# -*- coding: utf-8 -*-
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+"""
+kallithea.lib.paster_commands.common
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Common code for Paster commands.
+
+This file was forked by the Kallithea project in July 2014.
+Original author and date, and relevant copyright and licensing information is below:
+:created_on: Apr 18, 2010
+:author: marcink
+:copyright: (c) 2013 RhodeCode GmbH, and others.
+:license: GPLv3, see LICENSE.md for more details.
+"""
+
+import os
+import logging
+
+import paste
+from paste.script.command import Command, BadCommand
+
+from kallithea.lib.utils import setup_cache_regions
+
+
+def ask_ok(prompt, retries=4, complaint='Yes or no please!'):
+    while True:
+        ok = raw_input(prompt)
+        if ok in ('y', 'ye', 'yes'):
+            return True
+        if ok in ('n', 'no', 'nop', 'nope'):
+            return False
+        retries = retries - 1
+        if retries < 0:
+            raise IOError
+        print complaint
+
+
+class BasePasterCommand(Command):
+    """
+    Abstract Base Class for paster commands.
+    """
+    min_args = 1
+    min_args_error = "Please provide a paster config file as an argument."
+    takes_config_file = 1
+    requires_config_file = True
+
+    def run(self, args):
+        """
+        Overrides Command.run
+
+        Checks for a config file argument and loads it.
+        """
+        if len(args) < self.min_args:
+            raise BadCommand(
+                self.min_args_error % {'min_args': self.min_args,
+                                       'actual_args': len(args)})
+
+        # Decrement because we're going to lob off the first argument.
+        # @@ This is hacky
+        self.min_args -= 1
+        self.bootstrap_config(args[0])
+        self.update_parser()
+        return super(BasePasterCommand, self).run(args[1:])
+
+    def update_parser(self):
+        """
+        Abstract method.  Allows for the class's parser to be updated
+        before the superclass's `run` method is called.  Necessary to
+        allow options/arguments to be passed through to the underlying
+        celery command.
+        """
+        raise NotImplementedError("Abstract Method.")
+
+    def bootstrap_config(self, conf):
+        """
+        Loads the app configuration.
+        """
+        from pylons import config as pylonsconfig
+
+        self.path_to_ini_file = os.path.realpath(conf)
+        conf = paste.deploy.appconfig('config:' + self.path_to_ini_file)
+        pylonsconfig.init_app(conf.global_conf, conf.local_conf)
+
+    def _init_session(self):
+        """
+        Inits SqlAlchemy Session
+        """
+        logging.config.fileConfig(self.path_to_ini_file)
+
+        from pylons import config
+        from kallithea.model.base import init_model
+        from kallithea.lib.utils2 import engine_from_config
+        setup_cache_regions(config)
+        engine = engine_from_config(config, 'sqlalchemy.')
+        init_model(engine)
--- a/kallithea/lib/paster_commands/install_iis.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/paster_commands/install_iis.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,12 +1,29 @@
+# -*- coding: utf-8 -*-
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+"""
+kallithea.lib.paster_commands.install_iis
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+IIS installation tools for Kallithea
+"""
+
+
 import os
 import sys
 from paste.script.appinstall import AbstractInstallCommand
 from paste.script.command import BadCommand
 
-# Add location of top level folder to sys.path
-from os.path import dirname as dn
-rc_path = dn(dn(dn(os.path.realpath(__file__))))
-sys.path.append(rc_path)
 
 class Command(AbstractInstallCommand):
     default_verbosity = 1
@@ -37,7 +54,9 @@
         except ImportError:
             raise BadCommand('missing requirement: isapi-wsgi not installed')
 
-        file = '''import sys
+        file = '''\
+# Created by Kallithea install_iis
+import sys
 
 if hasattr(sys, "isapidllhandle"):
     import win32traceutil
@@ -78,8 +97,8 @@
 
         dispatchfile = os.path.join(os.getcwd(), 'dispatch.py')
         self.ensure_file(dispatchfile, outdata, False)
-        print 'generating', dispatchfile
+        print 'Generating %s' % (dispatchfile,)
 
-        print ('run \'python "%s" install\' with administrative privileges '
+        print ('Run \'python "%s" install\' with administrative privileges '
             'to generate the _dispatch.dll file and install it into the '
             'default web site') % (dispatchfile,)
--- a/kallithea/lib/paster_commands/ishell.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/paster_commands/ishell.py	Fri Nov 18 01:11:13 2016 +0100
@@ -28,16 +28,14 @@
 
 import os
 import sys
-import logging
-
-from kallithea.lib.utils import BasePasterCommand
 
-# Add location of top level folder to sys.path
-from os.path import dirname as dn
-rc_path = dn(dn(dn(os.path.realpath(__file__))))
-sys.path.append(rc_path)
+# imports, used in IPython shell
+import time
+import shutil
+import datetime
+from kallithea.model.db import *
 
-log = logging.getLogger(__name__)
+from kallithea.lib.paster_commands.common import BasePasterCommand
 
 
 class Command(BasePasterCommand):
@@ -55,14 +53,6 @@
         #get SqlAlchemy session
         self._init_session()
 
-        # imports, used in ipython shell
-        import os
-        import sys
-        import time
-        import shutil
-        import datetime
-        from kallithea.model.db import *
-
         try:
             from IPython import embed
             from IPython.config.loader import Config
@@ -70,7 +60,7 @@
             cfg.InteractiveShellEmbed.confirm_exit = False
             embed(config=cfg, banner1="Kallithea IShell.")
         except ImportError:
-            print 'ipython installation required for ishell'
+            print 'Kallithea ishell requires the IPython Python package'
             sys.exit(-1)
 
     def update_parser(self):
--- a/kallithea/lib/paster_commands/make_index.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/paster_commands/make_index.py	Fri Nov 18 01:11:13 2016 +0100
@@ -23,22 +23,16 @@
 :author: marcink
 :copyright: (c) 2013 RhodeCode GmbH, and others.
 :license: GPLv3, see LICENSE.md for more details.
-
 """
 
 
 import os
 import sys
-import logging
 
 from string import strip
 from kallithea.model.repo import RepoModel
-from kallithea.lib.utils import BasePasterCommand, load_rcextensions
-
-# Add location of top level folder to sys.path
-from os.path import dirname as dn
-rc_path = dn(dn(dn(os.path.realpath(__file__))))
-sys.path.append(rc_path)
+from kallithea.lib.paster_commands.common import BasePasterCommand
+from kallithea.lib.utils import load_rcextensions
 
 
 class Command(BasePasterCommand):
@@ -53,7 +47,6 @@
     summary = "Creates or updates full text search index"
 
     def command(self):
-        logging.config.fileConfig(self.path_to_ini_file)
         #get SqlAlchemy session
         self._init_session()
         from pylons import config
@@ -74,12 +67,12 @@
         from kallithea.lib.pidlock import LockHeld, DaemonLock
         from kallithea.lib.indexers.daemon import WhooshIndexingDaemon
         try:
-            l = DaemonLock(file_=os.path.join(dn(dn(index_location)),
+            l = DaemonLock(file_=os.path.join(dirname(dirname(index_location)),
                                               'make_index.lock'))
             WhooshIndexingDaemon(index_location=index_location,
                                  repo_location=repo_location,
                                  repo_list=repo_list,
-                                 repo_update_list=repo_update_list)\
+                                 repo_update_list=repo_update_list) \
                 .run(full_index=self.options.full_index)
             l.release()
         except LockHeld:
--- a/kallithea/lib/paster_commands/make_rcextensions.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/paster_commands/make_rcextensions.py	Fri Nov 18 01:11:13 2016 +0100
@@ -23,7 +23,6 @@
 :author: marcink
 :copyright: (c) 2013 RhodeCode GmbH, and others.
 :license: GPLv3, see LICENSE.md for more details.
-
 """
 
 
@@ -31,12 +30,7 @@
 import sys
 import pkg_resources
 
-from kallithea.lib.utils import BasePasterCommand, ask_ok
-
-# Add location of top level folder to sys.path
-from os.path import dirname as dn
-rc_path = dn(dn(dn(os.path.realpath(__file__))))
-sys.path.append(rc_path)
+from kallithea.lib.paster_commands.common import ask_ok, BasePasterCommand
 
 
 class Command(BasePasterCommand):
@@ -67,7 +61,7 @@
             msg = ('Extension file already exists, do you want '
                    'to overwrite it ? [y/n]')
             if not ask_ok(msg):
-                print 'Nothing done...'
+                print 'Nothing done, exiting...'
                 return
 
         dirname = os.path.dirname(ext_file)
--- a/kallithea/lib/paster_commands/repo_scan.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/paster_commands/repo_scan.py	Fri Nov 18 01:11:13 2016 +0100
@@ -28,17 +28,10 @@
 
 import os
 import sys
-import logging
 
 from kallithea.model.scm import ScmModel
-from kallithea.lib.utils import BasePasterCommand, repo2db_mapper
-
-# Add location of top level folder to sys.path
-from os.path import dirname as dn
-rc_path = dn(dn(dn(os.path.realpath(__file__))))
-sys.path.append(rc_path)
-
-log = logging.getLogger(__name__)
+from kallithea.lib.paster_commands.common import BasePasterCommand
+from kallithea.lib.utils import repo2db_mapper
 
 
 class Command(BasePasterCommand):
@@ -61,7 +54,12 @@
                                         remove_obsolete=rm_obsolete)
         added = ', '.join(added) or '-'
         removed = ', '.join(removed) or '-'
-        print 'Scan completed added: %s removed: %s' % (added, removed)
+        print 'Scan completed.'
+        print 'Added: %s' % added
+        if rm_obsolete:
+            print 'Removed: %s' % removed
+        else:
+            print 'Missing: %s' % removed
 
     def update_parser(self):
         self.parser.add_option(
--- a/kallithea/lib/paster_commands/setup_db.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/paster_commands/setup_db.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,14 +1,30 @@
+# -*- coding: utf-8 -*-
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+"""
+kallithea.lib.paster_commands.setup_db
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Databaset setup paster command for Kallithea
+"""
+
+
 import os
 import sys
 from paste.script.appinstall import AbstractInstallCommand
 from paste.script.command import BadCommand
 from paste.deploy import appconfig
 
-# Add location of top level folder to sys.path
-from os.path import dirname as dn
-rc_path = dn(dn(dn(os.path.realpath(__file__))))
-sys.path.append(rc_path)
-
 
 class Command(AbstractInstallCommand):
 
@@ -20,11 +36,10 @@
     group_name = "Kallithea"
 
     description = """\
-
-    Setup Kallithea according to its configuration file.  This is
-    the second part of a two-phase web application installation
-    process (the first phase is prepare-app).  The setup process
-    consist of things like setting up databases, creating super user
+        Setup Kallithea according to its configuration file.  This is
+        the second part of a two-phase web application installation
+        process (the first phase is prepare-app).  The setup process
+        consist of things like setting up databases, creating super user
     """
 
     parser = AbstractInstallCommand.standard_parser(
@@ -74,6 +89,7 @@
                        dest='public_access',
                        default=None,
                        help='Disable public access on this installation ')
+
     def command(self):
         config_spec = self.args[0]
         section = self.options.section_name
@@ -100,7 +116,7 @@
         dist = conf.context.distribution
         if dist is None:
             raise BadCommand(
-                "The section %r is not the application (probably a filter).  "
+                "The section %r is not the application (probably a filter). "
                 "You should add #section_name, where section_name is the "
                 "section that configures your application" % plain_section)
         installer = self.get_installer(dist, ep_group, ep_name)
--- a/kallithea/lib/paster_commands/update_repoinfo.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/paster_commands/update_repoinfo.py	Fri Nov 18 01:11:13 2016 +0100
@@ -28,21 +28,14 @@
 
 import os
 import sys
-import logging
 import string
 
-from kallithea.lib.utils import BasePasterCommand
+from kallithea.lib.paster_commands.common import BasePasterCommand
+from kallithea.lib.utils2 import safe_unicode
 from kallithea.model.db import Repository
 from kallithea.model.repo import RepoModel
 from kallithea.model.meta import Session
 
-# Add location of top level folder to sys.path
-from os.path import dirname as dn
-rc_path = dn(dn(dn(os.path.realpath(__file__))))
-sys.path.append(rc_path)
-
-log = logging.getLogger(__name__)
-
 
 class Command(BasePasterCommand):
 
@@ -59,22 +52,24 @@
         #get SqlAlchemy session
         self._init_session()
 
-        repo_update_list = map(string.strip,
-                               self.options.repo_update_list.split(',')) \
-                               if self.options.repo_update_list else None
 
-        if repo_update_list is not None:
-            repo_list = list(Repository.query()\
-                .filter(Repository.repo_name.in_(repo_update_list)))
+        if self.options.repo_update_list is None:
+            repo_list = Repository.query().all()
         else:
-            repo_list = Repository.getAll()
-        RepoModel.update_repoinfo(repositories=repo_list)
+            repo_names = [safe_unicode(n.strip())
+                          for n in self.options.repo_update_list.split(',')]
+            repo_list = list(Repository.query()
+                .filter(Repository.repo_name.in_(repo_names)))
+        for repo in repo_list:
+            repo.update_changeset_cache()
         Session().commit()
 
         if self.options.invalidate_cache:
             for r in repo_list:
                 r.set_invalidate()
-        print 'Updated cache for %s repositories' % (len(repo_list))
+            print 'Updated repo info and invalidated cache for %s repositories' % (len(repo_list))
+        else:
+            print 'Updated repo info for %s repositories' % (len(repo_list))
 
     def update_parser(self):
         self.parser.add_option('--update-only',
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/lib/pygmentsutils.py	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,92 @@
+# -*- coding: utf-8 -*-
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+"""
+kallithea.lib.pygmentsutils
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Functions for extracting internal Pygments data.
+
+This file was forked by the Kallithea project in July 2014.
+Original author and date, and relevant copyright and licensing information is below:
+:created_on: Jan 5, 2011
+:author: marcink
+:copyright: (c) 2013 RhodeCode GmbH, and others.
+:license: GPLv3, see LICENSE.md for more details.
+"""
+
+from collections import defaultdict
+from itertools import ifilter
+from string import lower
+
+from pygments import lexers
+
+
+def get_lem():
+    """
+    Get language extension map based on what's inside pygments lexers
+    """
+    d = defaultdict(lambda: [])
+
+    def __clean(s):
+        s = s.lstrip('*')
+        s = s.lstrip('.')
+
+        if s.find('[') != -1:
+            exts = []
+            start, stop = s.find('['), s.find(']')
+
+            for suffix in s[start + 1:stop]:
+                exts.append(s[:s.find('[')] + suffix)
+            return map(lower, exts)
+        else:
+            return map(lower, [s])
+
+    for lx, t in sorted(lexers.LEXERS.items()):
+        m = map(__clean, t[-2])
+        if m:
+            m = reduce(lambda x, y: x + y, m)
+            for ext in m:
+                desc = lx.replace('Lexer', '')
+                d[ext].append(desc)
+
+    return dict(d)
+
+
+def get_index_filenames():
+    """
+    Get list of known indexable filenames from pygment lexer internals
+    """
+
+    filenames = []
+
+    def likely_filename(s):
+        return s.find('*') == -1 and s.find('[') == -1
+
+    for lx, t in sorted(lexers.LEXERS.items()):
+        for f in ifilter(likely_filename, t[-2]):
+            filenames.append(f)
+
+    return filenames
+
+
+def get_custom_lexer(extension):
+    """
+    returns a custom lexer if it's defined in rcextensions module, or None
+    if there's no custom lexer defined
+    """
+    import kallithea
+    #check if we didn't define this extension as other lexer
+    if kallithea.EXTENSIONS and extension in kallithea.EXTENSIONS.EXTRA_LEXERS:
+        _lexer_name = kallithea.EXTENSIONS.EXTRA_LEXERS[extension]
+        return lexers.get_lexer_by_name(_lexer_name)
--- a/kallithea/lib/rcmail/smtp_mailer.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/rcmail/smtp_mailer.py	Fri Nov 18 01:11:13 2016 +0100
@@ -60,9 +60,9 @@
         self.debug = debug
         self.auth = smtp_auth
 
-    def send(self, recipients=[], subject='', body='', html='',
+    def send(self, recipients=None, subject='', body='', html='',
              attachment_files=None, headers=None):
-
+        recipients = recipients or []
         if isinstance(recipients, basestring):
             recipients = [recipients]
         if headers is None:
--- a/kallithea/lib/utils.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/utils.py	Fri Nov 18 01:11:13 2016 +0100
@@ -37,15 +37,11 @@
 import decorator
 import warnings
 from os.path import abspath
-from os.path import dirname as dn, join as jn
-
-from paste.script.command import Command, BadCommand
+from os.path import dirname
 
 from webhelpers.text import collapse, remove_formatting, strip_tags
 from beaker.cache import _cache_decorate
 
-from kallithea import BRAND
-
 from kallithea.lib.vcs.utils.hgcompat import ui, config
 from kallithea.lib.vcs.utils.helpers import get_scm
 from kallithea.lib.vcs.exceptions import VCSError
@@ -53,7 +49,6 @@
 from kallithea.model import meta
 from kallithea.model.db import Repository, User, Ui, \
     UserLog, RepoGroup, Setting, UserGroup
-from kallithea.model.meta import Session
 from kallithea.model.repo_group import RepoGroupModel
 from kallithea.lib.utils2 import safe_str, safe_unicode, get_current_authuser
 from kallithea.lib.vcs.utils.fakemod import create_module
@@ -186,7 +181,7 @@
         repo_obj = Repository.get_by_repo_name(repo_name)
     else:
         repo_obj = None
-        repo_name = ''
+        repo_name = u''
 
     user_log = UserLog()
     user_log.user_id = user_obj.user_id
@@ -206,7 +201,7 @@
         sa.commit()
 
 
-def get_filesystem_repos(path, recursive=False, skip_removed_repos=True):
+def get_filesystem_repos(path):
     """
     Scans given path for repos and return (name,(type,path)) tuple
 
@@ -215,41 +210,51 @@
     """
 
     # remove ending slash for better results
-    path = path.rstrip(os.sep)
-    log.debug('now scanning in %s location recursive:%s...', path, recursive)
+    path = safe_str(path.rstrip(os.sep))
+    log.debug('now scanning in %s', path)
+
+    def isdir(*n):
+        return os.path.isdir(os.path.join(*n))
 
-    def _get_repos(p):
-        if not os.access(p, os.R_OK) or not os.access(p, os.X_OK):
-            log.warning('ignoring repo path without access: %s', p)
-            return
-        if not os.access(p, os.W_OK):
-            log.warning('repo path without write access: %s', p)
-        for dirpath in os.listdir(p):
-            if os.path.isfile(os.path.join(p, dirpath)):
+    for root, dirs, _files in os.walk(path):
+        recurse_dirs = []
+        for subdir in dirs:
+            # skip removed repos
+            if REMOVED_REPO_PAT.match(subdir):
                 continue
-            cur_path = os.path.join(p, dirpath)
 
-            # skip removed repos
-            if skip_removed_repos and REMOVED_REPO_PAT.match(dirpath):
+            #skip .<something> dirs TODO: rly? then we should prevent creating them ...
+            if subdir.startswith('.'):
                 continue
 
-            #skip .<somethin> dirs
-            if dirpath.startswith('.'):
-                continue
+            cur_path = os.path.join(root, subdir)
+            if (isdir(cur_path, '.hg') or
+                isdir(cur_path, '.git') or
+                isdir(cur_path, '.svn') or
+                isdir(cur_path, 'objects') and (isdir(cur_path, 'refs') or
+                                                os.path.isfile(os.path.join(cur_path, 'packed-refs')))):
+
+                if not os.access(cur_path, os.R_OK) or not os.access(cur_path, os.X_OK):
+                    log.warning('ignoring repo path without access: %s', cur_path)
+                    continue
+
+                if not os.access(cur_path, os.W_OK):
+                    log.warning('repo path without write access: %s', cur_path)
 
-            try:
-                scm_info = get_scm(cur_path)
-                yield scm_info[1].split(path, 1)[-1].lstrip(os.sep), scm_info
-            except VCSError:
-                if not recursive:
-                    continue
-                #check if this dir containts other repos for recursive scan
-                rec_path = os.path.join(p, dirpath)
-                if not os.path.islink(rec_path) and os.path.isdir(rec_path):
-                    for inner_scm in _get_repos(rec_path):
-                        yield inner_scm
+                try:
+                    scm_info = get_scm(cur_path)
+                    assert cur_path.startswith(path)
+                    repo_path = cur_path[len(path) + 1:]
+                    yield repo_path, scm_info
+                    continue # no recursion
+                except VCSError:
+                    # We should perhaps ignore such broken repos, but especially
+                    # the bare git detection is unreliable so we dive into it
+                    pass
 
-    return _get_repos(path)
+            recurse_dirs.append(subdir)
+
+        dirs[:] = recurse_dirs
 
 
 def is_valid_repo(repo_name, base_path, scm=None):
@@ -304,18 +309,6 @@
     return False
 
 
-def ask_ok(prompt, retries=4, complaint='Yes or no please!'):
-    while True:
-        ok = raw_input(prompt)
-        if ok in ('y', 'ye', 'yes'):
-            return True
-        if ok in ('n', 'no', 'nop', 'nope'):
-            return False
-        retries = retries - 1
-        if retries < 0:
-            raise IOError
-        print complaint
-
 #propagated from mercurial documentation
 ui_sections = ['alias', 'auth',
                 'decode/encode', 'defaults',
@@ -365,21 +358,17 @@
         hg_ui = ret
         for ui_ in hg_ui:
             if ui_.ui_active:
-                ui_val = safe_str(ui_.ui_value)
-                if ui_.ui_section == 'hooks' and BRAND != 'kallithea' and ui_val.startswith('python:' + BRAND + '.lib.hooks.'):
-                    ui_val = ui_val.replace('python:' + BRAND + '.lib.hooks.', 'python:kallithea.lib.hooks.')
-                log.debug('settings ui from db: [%s] %s=%s', ui_.ui_section,
+                ui_val = '' if ui_.ui_value is None else safe_str(ui_.ui_value)
+                log.debug('settings ui from db: [%s] %s=%r', ui_.ui_section,
                           ui_.ui_key, ui_val)
                 baseui.setconfig(safe_str(ui_.ui_section), safe_str(ui_.ui_key),
                                  ui_val)
-            if ui_.ui_key == 'push_ssl':
-                # force set push_ssl requirement to False, kallithea
-                # handles that
-                baseui.setconfig(safe_str(ui_.ui_section), safe_str(ui_.ui_key),
-                                 False)
         if clear_session:
             meta.Session.remove()
 
+        # force set push_ssl requirement to False, Kallithea handles that
+        baseui.setconfig('web', 'push_ssl', False)
+        baseui.setconfig('web', 'allow_push', '*')
         # prevent interactive questions for ssh password / passphrase
         ssh = baseui.config('ui', 'ssh', default='ssh')
         baseui.setconfig('ui', 'ssh', '%s -oBatchMode=yes -oIdentitiesOnly=yes' % ssh)
@@ -389,7 +378,7 @@
 
 def set_app_settings(config):
     """
-    Updates pylons config with new settings from database
+    Updates app config with new settings from database
 
     :param config:
     """
@@ -418,6 +407,21 @@
                                                         'utf8'), sep=',')
 
 
+def set_indexer_config(config):
+    """
+    Update Whoosh index mapping
+
+    :param config: kallithea.CONFIG
+    """
+    from kallithea.config import conf
+
+    log.debug('adding extra into INDEX_EXTENSIONS')
+    conf.INDEX_EXTENSIONS.extend(re.split('\s+', config.get('index.extensions', '')))
+
+    log.debug('adding extra into INDEX_FILENAMES')
+    conf.INDEX_FILENAMES.extend(re.split('\s+', config.get('index.filenames', '')))
+
+
 def map_groups(path):
     """
     Given a full path to a repository, create all nested groups that this
@@ -436,7 +440,7 @@
     rgm = RepoGroupModel(sa)
     owner = User.get_first_admin()
     for lvl, group_name in enumerate(groups):
-        group_name = '/'.join(groups[:lvl] + [group_name])
+        group_name = u'/'.join(groups[:lvl] + [group_name])
         group = RepoGroup.get_by_group_name(group_name)
         desc = '%s group' % group_name
 
@@ -449,7 +453,7 @@
                       lvl, group_name)
             group = RepoGroup(group_name, parent)
             group.group_description = desc
-            group.user = owner
+            group.owner = owner
             sa.add(group)
             perm_obj = rgm._create_default_perms(group)
             sa.add(perm_obj)
@@ -528,8 +532,9 @@
 
     removed = []
     # remove from database those repositories that are not in the filesystem
+    unicode_initial_repo_list = set(safe_unicode(name) for name in initial_repo_list)
     for repo in sa.query(Repository).all():
-        if repo.repo_name not in initial_repo_list.keys():
+        if repo.repo_name not in unicode_initial_repo_list:
             if remove_obsolete:
                 log.debug("Removing non-existing repository found in db `%s`",
                           repo.repo_name)
@@ -544,34 +549,6 @@
     return added, removed
 
 
-# set cache regions for beaker so celery can utilise it
-def add_cache(settings):
-    cache_settings = {'regions': None}
-    for key in settings.keys():
-        for prefix in ['beaker.cache.', 'cache.']:
-            if key.startswith(prefix):
-                name = key.split(prefix)[1].strip()
-                cache_settings[name] = settings[key].strip()
-    if cache_settings['regions']:
-        for region in cache_settings['regions'].split(','):
-            region = region.strip()
-            region_settings = {}
-            for key, value in cache_settings.items():
-                if key.startswith(region):
-                    region_settings[key.split('.')[1]] = value
-            region_settings['expire'] = int(region_settings.get('expire',
-                                                                60))
-            region_settings.setdefault('lock_dir',
-                                       cache_settings.get('lock_dir'))
-            region_settings.setdefault('data_dir',
-                                       cache_settings.get('data_dir'))
-
-            if 'type' not in region_settings:
-                region_settings['type'] = cache_settings.get('type',
-                                                             'memory')
-            beaker.cache.cache_regions[region] = region_settings
-
-
 def load_rcextensions(root_path):
     import kallithea
     from kallithea.config import conf
@@ -603,19 +580,6 @@
         #        setattr(EXT, k, getattr(rcextensions, k))
 
 
-def get_custom_lexer(extension):
-    """
-    returns a custom lexer if it's defined in rcextensions module, or None
-    if there's no custom lexer defined
-    """
-    import kallithea
-    from pygments import lexers
-    #check if we didn't define this extension as other lexer
-    if kallithea.EXTENSIONS and extension in kallithea.EXTENSIONS.EXTRA_LEXERS:
-        _lexer_name = kallithea.EXTENSIONS.EXTRA_LEXERS[extension]
-        return lexers.get_lexer_by_name(_lexer_name)
-
-
 #==============================================================================
 # TEST FUNCTIONS AND CREATORS
 #==============================================================================
@@ -637,9 +601,9 @@
         os.makedirs(index_location)
 
     try:
-        l = DaemonLock(file_=jn(dn(index_location), 'make_index.lock'))
+        l = DaemonLock(file_=os.path.join(dirname(index_location), 'make_index.lock'))
         WhooshIndexingDaemon(index_location=index_location,
-                             repo_location=repo_location)\
+                             repo_location=repo_location) \
             .run(full_index=full_index)
         l.release()
     except LockHeld:
@@ -652,10 +616,10 @@
     install test repository into tmp dir
     """
     from kallithea.lib.db_manage import DbManage
-    from kallithea.tests import HG_REPO, GIT_REPO, TESTS_TMP_PATH
+    from kallithea.tests.base import HG_REPO, GIT_REPO, TESTS_TMP_PATH
 
     # PART ONE create db
-    dbconf = config['sqlalchemy.db1.url']
+    dbconf = config['sqlalchemy.url']
     log.debug('making test db %s', dbconf)
 
     # create test dir if it doesn't exist
@@ -672,7 +636,7 @@
     dbmanage.admin_prompt()
     dbmanage.create_permissions()
     dbmanage.populate_default_permissions()
-    Session().commit()
+    meta.Session().commit()
     # PART TWO make test repo
     log.debug('making test vcs repositories')
 
@@ -689,14 +653,14 @@
         shutil.rmtree(data_path)
 
     #CREATE DEFAULT TEST REPOS
-    cur_dir = dn(dn(abspath(__file__)))
-    tar = tarfile.open(jn(cur_dir, 'tests', 'fixtures', "vcs_test_hg.tar.gz"))
-    tar.extractall(jn(TESTS_TMP_PATH, HG_REPO))
+    cur_dir = dirname(dirname(abspath(__file__)))
+    tar = tarfile.open(os.path.join(cur_dir, 'tests', 'fixtures', "vcs_test_hg.tar.gz"))
+    tar.extractall(os.path.join(TESTS_TMP_PATH, HG_REPO))
     tar.close()
 
-    cur_dir = dn(dn(abspath(__file__)))
-    tar = tarfile.open(jn(cur_dir, 'tests', 'fixtures', "vcs_test_git.tar.gz"))
-    tar.extractall(jn(TESTS_TMP_PATH, GIT_REPO))
+    cur_dir = dirname(dirname(abspath(__file__)))
+    tar = tarfile.open(os.path.join(cur_dir, 'tests', 'fixtures', "vcs_test_git.tar.gz"))
+    tar.extractall(os.path.join(TESTS_TMP_PATH, GIT_REPO))
     tar.close()
 
     #LOAD VCS test stuff
@@ -704,87 +668,6 @@
     setup_package()
 
 
-#==============================================================================
-# PASTER COMMANDS
-#==============================================================================
-class BasePasterCommand(Command):
-    """
-    Abstract Base Class for paster commands.
-
-    The celery commands are somewhat aggressive about loading
-    celery.conf, and since our module sets the `CELERY_LOADER`
-    environment variable to our loader, we have to bootstrap a bit and
-    make sure we've had a chance to load the pylons config off of the
-    command line, otherwise everything fails.
-    """
-    min_args = 1
-    min_args_error = "Please provide a paster config file as an argument."
-    takes_config_file = 1
-    requires_config_file = True
-
-    def notify_msg(self, msg, log=False):
-        """Make a notification to user, additionally if logger is passed
-        it logs this action using given logger
-
-        :param msg: message that will be printed to user
-        :param log: logging instance, to use to additionally log this message
-
-        """
-        if log and isinstance(log, logging):
-            log(msg)
-
-    def run(self, args):
-        """
-        Overrides Command.run
-
-        Checks for a config file argument and loads it.
-        """
-        if len(args) < self.min_args:
-            raise BadCommand(
-                self.min_args_error % {'min_args': self.min_args,
-                                       'actual_args': len(args)})
-
-        # Decrement because we're going to lob off the first argument.
-        # @@ This is hacky
-        self.min_args -= 1
-        self.bootstrap_config(args[0])
-        self.update_parser()
-        return super(BasePasterCommand, self).run(args[1:])
-
-    def update_parser(self):
-        """
-        Abstract method.  Allows for the class's parser to be updated
-        before the superclass's `run` method is called.  Necessary to
-        allow options/arguments to be passed through to the underlying
-        celery command.
-        """
-        raise NotImplementedError("Abstract Method.")
-
-    def bootstrap_config(self, conf):
-        """
-        Loads the pylons configuration.
-        """
-        from pylons import config as pylonsconfig
-
-        self.path_to_ini_file = os.path.realpath(conf)
-        conf = paste.deploy.appconfig('config:' + self.path_to_ini_file)
-        pylonsconfig.init_app(conf.global_conf, conf.local_conf)
-
-    def _init_session(self):
-        """
-        Inits SqlAlchemy Session
-        """
-        logging.config.fileConfig(self.path_to_ini_file)
-        from pylons import config
-        from kallithea.model import init_model
-        from kallithea.lib.utils2 import engine_from_config
-
-        #get to remove repos !!
-        add_cache(config)
-        engine = engine_from_config(config, 'sqlalchemy.db1.')
-        init_model(engine)
-
-
 def check_git_version():
     """
     Checks what version of git is installed in system, and issues a warning
@@ -835,15 +718,52 @@
     pylons.response.headers['Content-Type'] = 'application/json; charset=utf-8'
     data = func(*args, **kwargs)
     if isinstance(data, (list, tuple)):
+        # A JSON list response is syntactically valid JavaScript and can be
+        # loaded and executed as JavaScript by a malicious third-party site
+        # using <script>, which can lead to cross-site data leaks.
+        # JSON responses should therefore be scalars or objects (i.e. Python
+        # dicts), because a JSON object is a syntax error if intepreted as JS.
         msg = "JSON responses with Array envelopes are susceptible to " \
               "cross-site data leak attacks, see " \
-              "http://wiki.pylonshq.com/display/pylonsfaq/Warnings"
+              "https://web.archive.org/web/20120519231904/http://wiki.pylonshq.com/display/pylonsfaq/Warnings"
         warnings.warn(msg, Warning, 2)
         log.warning(msg)
     log.debug("Returning JSON wrapped action output")
     return json.dumps(data, encoding='utf-8')
 
 
+#===============================================================================
+# CACHE RELATED METHODS
+#===============================================================================
+
+# set cache regions for beaker so celery can utilise it
+def setup_cache_regions(settings):
+    cache_settings = {'regions': None}
+    for key in settings.keys():
+        for prefix in ['beaker.cache.', 'cache.']:
+            if key.startswith(prefix):
+                name = key.split(prefix)[1].strip()
+                cache_settings[name] = settings[key].strip()
+    if cache_settings['regions']:
+        for region in cache_settings['regions'].split(','):
+            region = region.strip()
+            region_settings = {}
+            for key, value in cache_settings.items():
+                if key.startswith(region):
+                    region_settings[key.split('.')[1]] = value
+            region_settings['expire'] = int(region_settings.get('expire',
+                                                                60))
+            region_settings.setdefault('lock_dir',
+                                       cache_settings.get('lock_dir'))
+            region_settings.setdefault('data_dir',
+                                       cache_settings.get('data_dir'))
+
+            if 'type' not in region_settings:
+                region_settings['type'] = cache_settings.get('type',
+                                                             'memory')
+            beaker.cache.cache_regions[region] = region_settings
+
+
 def conditional_cache(region, prefix, condition, func):
     """
 
@@ -852,8 +772,8 @@
             #heavy computation function
             return data
 
-        # denpending from condition the compute is wrapped in cache or not
-        compute = conditional_cache('short_term', 'cache_desc', codnition=True, func=func)
+        # depending from condition the compute is wrapped in cache or not
+        compute = conditional_cache('short_term', 'cache_desc', condition=True, func=func)
         return compute(arg)
 
     :param region: name of cache region
--- a/kallithea/lib/utils2.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/utils2.py	Fri Nov 18 01:11:13 2016 +0100
@@ -43,44 +43,9 @@
 from kallithea.lib.compat import json
 
 
-def __get_lem():
-    """
-    Get language extension map based on what's inside pygments lexers
-    """
-    from pygments import lexers
-    from string import lower
-    from collections import defaultdict
-
-    d = defaultdict(lambda: [])
-
-    def __clean(s):
-        s = s.lstrip('*')
-        s = s.lstrip('.')
-
-        if s.find('[') != -1:
-            exts = []
-            start, stop = s.find('['), s.find(']')
-
-            for suffix in s[start + 1:stop]:
-                exts.append(s[:s.find('[')] + suffix)
-            return map(lower, exts)
-        else:
-            return map(lower, [s])
-
-    for lx, t in sorted(lexers.LEXERS.items()):
-        m = map(__clean, t[-2])
-        if m:
-            m = reduce(lambda x, y: x + y, m)
-            for ext in m:
-                desc = lx.replace('Lexer', '')
-                d[ext].append(desc)
-
-    return dict(d)
-
-
 def str2bool(_str):
     """
-    returs True/False value from given string, it tries to translate the
+    returns True/False value from given string, it tries to translate the
     string into boolean
 
     :param _str: string value to translate into boolean
@@ -352,7 +317,7 @@
     example: 2days ago, instead of 2 days and 23 hours ago.
 
     :param prevdate: datetime object
-    :param show_short_version: if it should aproximate the date and return a shorter string
+    :param show_short_version: if it should approximate the date and return a shorter string
     :rtype: unicode
     :returns: unicode words describing age
     """
@@ -553,25 +518,30 @@
                 return
         return datetime.datetime.fromtimestamp(tm)
 
+
 # Must match regexp in kallithea/public/js/base.js MentionsAutoComplete()
 # Check char before @ - it must not look like we are in an email addresses.
-# Matching is gready so we don't have to look beyond the end.
+# Matching is greedy so we don't have to look beyond the end.
 MENTIONS_REGEX = re.compile(r'(?:^|(?<=[^a-zA-Z0-9]))@([a-zA-Z0-9][-_.a-zA-Z0-9]*[a-zA-Z0-9])')
 
-def extract_mentioned_users(s):
+def extract_mentioned_usernames(text):
     r"""
-    Returns unique usernames from given string s that have @mention
+    Returns list of (possible) usernames @mentioned in given text.
 
-    :param s: string to get mentions
-
-    >>> extract_mentioned_users('@1-2.a_X,@1234 not@not @ddd@not @n @ee @ff @gg, @gg;@hh @n\n@zz,')
+    >>> extract_mentioned_usernames('@1-2.a_X,@1234 not@not @ddd@not @n @ee @ff @gg, @gg;@hh @n\n@zz,')
     ['1-2.a_X', '1234', 'ddd', 'ee', 'ff', 'gg', 'hh', 'zz']
     """
-    usrs = set()
-    for username in MENTIONS_REGEX.findall(s):
-        usrs.add(username)
+    return MENTIONS_REGEX.findall(text)
 
-    return sorted(list(usrs), key=lambda k: k.lower())
+def extract_mentioned_users(text):
+    """ Returns set of actual database Users @mentioned in given text. """
+    from kallithea.model.db import User
+    result = set()
+    for name in extract_mentioned_usernames(text):
+        user = User.get_by_username(name, case_insensitive=True)
+        if user is not None and user.username != User.DEFAULT_USER:
+            result.add(user)
+    return result
 
 
 class AttributeDict(dict):
@@ -637,7 +607,7 @@
 
 
 def _set_extras(extras):
-    # RC_SCM_DATA can probably be removed in the future, but for compatibilty now...
+    # RC_SCM_DATA can probably be removed in the future, but for compatibility now...
     os.environ['KALLITHEA_EXTRAS'] = os.environ['RC_SCM_DATA'] = json.dumps(extras)
 
 
--- a/kallithea/lib/vcs/backends/base.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/vcs/backends/base.py	Fri Nov 18 01:11:13 2016 +0100
@@ -137,9 +137,6 @@
     def is_empty(self):
         return self._empty
 
-    def get_last_change(self):
-        self.get_changesets()
-
     #==========================================================================
     # CHANGESETS
     #==========================================================================
@@ -668,6 +665,26 @@
     def obsolete(self):
         return False
 
+    @LazyProperty
+    def bumped(self):
+        return False
+
+    @LazyProperty
+    def divergent(self):
+        return False
+
+    @LazyProperty
+    def extinct(self):
+        return False
+
+    @LazyProperty
+    def unstable(self):
+        return False
+
+    @LazyProperty
+    def phase(self):
+        return ''
+
 class BaseWorkdir(object):
     """
     Working directory representation of single repository.
--- a/kallithea/lib/vcs/backends/git/inmemory.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/vcs/backends/git/inmemory.py	Fri Nov 18 01:11:13 2016 +0100
@@ -40,7 +40,7 @@
         ENCODING = "UTF-8"
 
         # Create tree and populates it with blobs
-        commit_tree = self.parents[0] and repo[self.parents[0]._commit.tree] or\
+        commit_tree = self.parents[0] and repo[self.parents[0]._commit.tree] or \
             objects.Tree()
         for node in self.added + self.changed:
             # Compute subdirs if needed
--- a/kallithea/lib/vcs/backends/git/repository.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/vcs/backends/git/repository.py	Fri Nov 18 01:11:13 2016 +0100
@@ -58,7 +58,7 @@
     def __init__(self, repo_path, create=False, src_url=None,
                  update_after_clone=False, bare=False):
 
-        self.path = abspath(repo_path)
+        self.path = safe_unicode(abspath(repo_path))
         repo = self._get_repo(create, src_url, update_after_clone, bare)
         self.bare = repo.bare
 
--- a/kallithea/lib/vcs/backends/hg/changeset.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/vcs/backends/hg/changeset.py	Fri Nov 18 01:11:13 2016 +0100
@@ -41,11 +41,36 @@
 
     @LazyProperty
     def closesbranch(self):
-        return  self._ctx.closesbranch()
+        return self._ctx.closesbranch()
 
     @LazyProperty
     def obsolete(self):
-        return  self._ctx.obsolete()
+        return self._ctx.obsolete()
+
+    @LazyProperty
+    def bumped(self):
+        return self._ctx.bumped()
+
+    @LazyProperty
+    def divergent(self):
+        return self._ctx.divergent()
+
+    @LazyProperty
+    def extinct(self):
+        return self._ctx.extinct()
+
+    @LazyProperty
+    def unstable(self):
+        return self._ctx.unstable()
+
+    @LazyProperty
+    def phase(self):
+        if(self._ctx.phase() == 1):
+            return 'Draft'
+        elif(self._ctx.phase() == 2):
+            return 'Secret'
+        else:
+            return ''
 
     @LazyProperty
     def successors(self):
@@ -268,9 +293,9 @@
         """
 
         fctx = self._get_filectx(path)
-        for i, annotate_data in enumerate(fctx.annotate()):
+        for i, annotate_data in enumerate(fctx.annotate(linenumber=False)):
             ln_no = i + 1
-            sha = hex(annotate_data[0].node())
+            sha = hex(annotate_data[0][0].node())
             yield (ln_no, sha, lambda: self.repository.get_changeset(sha), annotate_data[1],)
 
     def fill_archive(self, stream=None, kind='tgz', prefix=None,
--- a/kallithea/lib/vcs/backends/hg/inmemory.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/vcs/backends/hg/inmemory.py	Fri Nov 18 01:11:13 2016 +0100
@@ -83,7 +83,7 @@
                 parents[i] = parent._ctx.node()
 
         if date and isinstance(date, datetime.datetime):
-            date = date.ctime()
+            date = date.strftime('%a, %d %b %Y %H:%M:%S')
 
         commit_ctx = memctx(repo=self.repository._repo,
             parents=parents,
--- a/kallithea/lib/vcs/backends/hg/repository.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/vcs/backends/hg/repository.py	Fri Nov 18 01:11:13 2016 +0100
@@ -172,7 +172,7 @@
                 changeset.short_id)
 
         if date is None:
-            date = datetime.datetime.now().ctime()
+            date = datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S')
 
         try:
             self._repo.tag(name, changeset._ctx.node(), message, local, user,
@@ -202,7 +202,7 @@
         if message is None:
             message = "Removed tag %s" % name
         if date is None:
-            date = datetime.datetime.now().ctime()
+            date = datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S')
         local = False
 
         try:
@@ -361,10 +361,10 @@
             return localrepository(self.baseui, self.path, create=create)
         except (Abort, RepoError) as err:
             if create:
-                msg = "Cannot create repository at %s. Original error was %s"\
+                msg = "Cannot create repository at %s. Original error was %s" \
                     % (self.path, err)
             else:
-                msg = "Not valid repository at %s. Original error was %s"\
+                msg = "Not valid repository at %s. Original error was %s" \
                     % (self.path, err)
             raise RepositoryError(msg)
 
--- a/kallithea/lib/vcs/subprocessio.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/vcs/subprocessio.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,8 +1,8 @@
 """
 Module provides a class allowing to wrap communication over subprocess.Popen
-input, output, error streams into a meaningfull, non-blocking, concurrent
+input, output, error streams into a meaningful, non-blocking, concurrent
 stream processor exposing the output data as an iterator fitting to be a
-return value passed by a WSGI applicaiton to a WSGI server per PEP 3333.
+return value passed by a WSGI application to a WSGI server per PEP 3333.
 
 Copyright (c) 2011  Daniel Dotsenko <dotsa[at]hotmail.com>
 
@@ -24,10 +24,11 @@
 """
 import os
 import subprocess
-from kallithea.lib.vcs.utils.compat import deque, Event, Thread, _bytes, _bytearray
+import collections
+import threading
 
 
-class StreamFeeder(Thread):
+class StreamFeeder(threading.Thread):
     """
     Normal writing into pipe-like is blocking once the buffer is filled.
     This thread allows a thread to seep data from a file-like into a pipe
@@ -39,9 +40,9 @@
         super(StreamFeeder, self).__init__()
         self.daemon = True
         filelike = False
-        self.bytes = _bytes()
-        if type(source) in (type(''), _bytes, _bytearray):  # string-like
-            self.bytes = _bytes(source)
+        self.bytes = bytes()
+        if type(source) in (type(''), bytes, bytearray):  # string-like
+            self.bytes = bytes(source)
         else:  # can be either file pointer or file-like
             if type(source) in (int, long):  # file pointer it is
                 ## converting file descriptor (int) stdin into file-like
@@ -71,7 +72,7 @@
         return self.readiface
 
 
-class InputStreamChunker(Thread):
+class InputStreamChunker(threading.Thread):
     def __init__(self, source, target, buffer_size, chunk_size):
 
         super(InputStreamChunker, self).__init__()
@@ -83,16 +84,16 @@
         self.chunk_count_max = int(buffer_size / chunk_size) + 1
         self.chunk_size = chunk_size
 
-        self.data_added = Event()
+        self.data_added = threading.Event()
         self.data_added.clear()
 
-        self.keep_reading = Event()
+        self.keep_reading = threading.Event()
         self.keep_reading.set()
 
-        self.EOF = Event()
+        self.EOF = threading.Event()
         self.EOF.clear()
 
-        self.go = Event()
+        self.go = threading.Event()
         self.go.set()
 
     def stop(self):
@@ -156,14 +157,14 @@
     """
 
     def __init__(self, source, buffer_size=65536, chunk_size=4096,
-                 starting_values=[], bottomless=False):
-
+                 starting_values=None, bottomless=False):
+        starting_values = starting_values or []
         if bottomless:
             maxlen = int(buffer_size / chunk_size)
         else:
             maxlen = None
 
-        self.data = deque(starting_values, maxlen)
+        self.data = collections.deque(starting_values, maxlen)
         self.worker = InputStreamChunker(source, self.data, buffer_size,
                                          chunk_size)
         if starting_values:
@@ -183,7 +184,7 @@
             self.worker.data_added.wait(0.2)
         if len(self.data):
             self.worker.keep_reading.set()
-            return _bytes(self.data.popleft())
+            return bytes(self.data.popleft())
         elif self.worker.EOF.is_set():
             raise StopIteration
 
@@ -233,7 +234,7 @@
         Iterator might have done reading from underlying source, but the read
         chunks might still be available for serving through .next() method.
 
-        :returns: An Event class instance.
+        :returns: An threading.Event class instance.
         """
         return self.worker.EOF
 
@@ -326,7 +327,7 @@
     """
 
     def __init__(self, cmd, inputstream=None, buffer_size=65536,
-                 chunk_size=4096, starting_values=[], **kwargs):
+                 chunk_size=4096, starting_values=None, **kwargs):
         """
         Initializes SubprocessIOChunker
 
@@ -336,7 +337,7 @@
         :param chunk_size: (Default: 4096) A max size of a chunk. Actual chunk may be smaller.
         :param starting_values: (Default: []) An array of strings to put in front of output que.
         """
-
+        starting_values = starting_values or []
         if inputstream:
             input_streamer = StreamFeeder(inputstream)
             input_streamer.start()
@@ -355,7 +356,7 @@
                                    starting_values)
         bg_err = BufferedGenerator(_p.stderr, 16000, 1, bottomless=True)
 
-        while not bg_out.done_reading and not bg_out.reading_paused and not bg_err.length:
+        while not bg_out.done_reading and not bg_out.reading_paused:
             # doing this until we reach either end of file, or end of buffer.
             bg_out.data_added_event.wait(1)
             bg_out.data_added_event.clear()
@@ -364,12 +365,9 @@
         # Either way, if error (returned by ended process, or implied based on
         # presence of stuff in stderr output) we error out.
         # Else, we are happy.
-        _returncode = _p.poll()
-        if _returncode or (_returncode is None and bg_err.length):
-            try:
-                _p.terminate()
-            except Exception:
-                pass
+        returncode = _p.poll()
+        if (returncode is not None # process has terminated
+            and returncode != 0): # and it failed
             bg_out.stop()
             out = ''.join(bg_out)
             bg_err.stop()
@@ -384,7 +382,7 @@
                     "Subprocess exited due to an error:\n" + err)
             else:
                 raise EnvironmentError(
-                    "Subprocess exited with non 0 ret code:%s" % _returncode)
+                    "Subprocess exited with non 0 ret code: %s" % returncode)
         self.process = _p
         self.output = bg_out
         self.error = bg_err
@@ -394,9 +392,14 @@
         return self
 
     def next(self):
-        if self.process and self.process.poll():
-            err = ''.join(self.error)
-            raise EnvironmentError("Subprocess exited due to an error:\n" + err)
+        if self.process:
+            returncode = self.process.poll()
+            if (returncode is not None # process has terminated
+                and returncode != 0): # and it failed
+                self.output.stop()
+                self.error.stop()
+                err = ''.join(self.error)
+                raise EnvironmentError("Subprocess exited due to an error:\n" + err)
         return self.output.next()
 
     def throw(self, type, value=None, traceback=None):
--- a/kallithea/lib/vcs/utils/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/vcs/utils/__init__.py	Fri Nov 18 01:11:13 2016 +0100
@@ -5,6 +5,7 @@
 
 import time
 import datetime
+import re
 
 
 def makedate():
@@ -150,30 +151,33 @@
         return unicode_.encode(to_encoding[0], 'replace')
 
 
+# Regex taken from http://www.regular-expressions.info/email.html
+email_re = re.compile(
+    r"""[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@"""
+    r"""(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?""",
+    re.IGNORECASE)
+
 def author_email(author):
     """
-    returns email address of given author.
-    If any of <,> sign are found, it fallbacks to regex findall()
-    and returns first found result or empty string
+    Returns email address of given author string.
+    If author contains <> brackets, only look inside that.
+    If any RFC valid email address is found, return that.
+    Else, return empty string.
 
-    Regex taken from http://www.regular-expressions.info/email.html
     """
     if not author:
         return ''
-    import re
-    r = author.find('>')
-    l = author.find('<')
 
-    if l == -1 or r == -1:
-        # fallback to regex match of email out of a string
-        email_re = re.compile(r"""[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!"""
-                              r"""#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z"""
-                              r"""0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]"""
-                              r"""*[a-z0-9])?""", re.IGNORECASE)
-        m = re.findall(email_re, author)
-        return m[0] if m else ''
+    l = author.find('<') + 1
+    if l != 0:
+        r = author.find('>', l)
+        if r != -1:
+            author = author[l:r]
 
-    return author[l + 1:r].strip()
+    m = email_re.search(author)
+    if m is None:
+        return ''
+    return safe_str(m.group(0))
 
 
 def author_name(author):
@@ -186,5 +190,5 @@
         return ''
     if not '@' in author:
         return author
-    return author.replace(author_email(author), '').replace('<', '')\
+    return author.replace(author_email(author), '').replace('<', '') \
         .replace('>', '').strip()
--- a/kallithea/lib/vcs/utils/annotate.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/vcs/utils/annotate.py	Fri Nov 18 01:11:13 2016 +0100
@@ -41,7 +41,7 @@
         following function as ``annotate_from_changeset_func``::
 
             def changeset_to_anchor(changeset):
-                return '<a href="/changesets/%s/">%s</a>\n' %\
+                return '<a href="/changesets/%s/">%s</a>\n' % \
                        (changeset.id, changeset.id)
 
         :param annotate_from_changeset_func: see above
--- a/kallithea/lib/vcs/utils/compat.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/vcs/utils/compat.py	Fri Nov 18 01:11:13 2016 +0100
@@ -4,6 +4,7 @@
 Those utilities may be deleted once ``vcs`` stops support for older Python
 versions.
 """
+
 import sys
 import array
 
@@ -11,308 +12,3 @@
     unittest = __import__('unittest')
 else:
     unittest = __import__('unittest2')
-
-
-if sys.version_info >= (2, 6):
-    _bytes = bytes
-else:
-    # in py2.6 bytes is a synonym for str
-    _bytes = str
-
-if sys.version_info >= (2, 6):
-    _bytearray = bytearray
-else:
-    # no idea if this is correct but all integration tests are passing
-    # i think we never use bytearray anyway
-    _bytearray = array
-
-if sys.version_info >= (2, 6):
-    from collections import deque
-else:
-    #need to implement our own deque with maxlen
-    class deque(object):
-
-        def __init__(self, iterable=(), maxlen= -1):
-            if not hasattr(self, 'data'):
-                self.left = self.right = 0
-                self.data = {}
-            self.maxlen = maxlen or -1
-            self.extend(iterable)
-
-        def append(self, x):
-            self.data[self.right] = x
-            self.right += 1
-            if self.maxlen != -1 and len(self) > self.maxlen:
-                self.popleft()
-
-        def appendleft(self, x):
-            self.left -= 1
-            self.data[self.left] = x
-            if self.maxlen != -1 and len(self) > self.maxlen:
-                self.pop()
-
-        def pop(self):
-            if self.left == self.right:
-                raise IndexError('cannot pop from empty deque')
-            self.right -= 1
-            elem = self.data[self.right]
-            del self.data[self.right]
-            return elem
-
-        def popleft(self):
-            if self.left == self.right:
-                raise IndexError('cannot pop from empty deque')
-            elem = self.data[self.left]
-            del self.data[self.left]
-            self.left += 1
-            return elem
-
-        def clear(self):
-            self.data.clear()
-            self.left = self.right = 0
-
-        def extend(self, iterable):
-            for elem in iterable:
-                self.append(elem)
-
-        def extendleft(self, iterable):
-            for elem in iterable:
-                self.appendleft(elem)
-
-        def rotate(self, n=1):
-            if self:
-                n %= len(self)
-                for i in xrange(n):
-                    self.appendleft(self.pop())
-
-        def __getitem__(self, i):
-            if i < 0:
-                i += len(self)
-            try:
-                return self.data[i + self.left]
-            except KeyError:
-                raise IndexError
-
-        def __setitem__(self, i, value):
-            if i < 0:
-                i += len(self)
-            try:
-                self.data[i + self.left] = value
-            except KeyError:
-                raise IndexError
-
-        def __delitem__(self, i):
-            size = len(self)
-            if not (-size <= i < size):
-                raise IndexError
-            data = self.data
-            if i < 0:
-                i += size
-            for j in xrange(self.left + i, self.right - 1):
-                data[j] = data[j + 1]
-            self.pop()
-
-        def __len__(self):
-            return self.right - self.left
-
-        def __cmp__(self, other):
-            if type(self) != type(other):
-                return cmp(type(self), type(other))
-            return cmp(list(self), list(other))
-
-        def __repr__(self, _track=[]):
-            if id(self) in _track:
-                return '...'
-            _track.append(id(self))
-            r = 'deque(%r, maxlen=%s)' % (list(self), self.maxlen)
-            _track.remove(id(self))
-            return r
-
-        def __getstate__(self):
-            return (tuple(self),)
-
-        def __setstate__(self, s):
-            self.__init__(s[0])
-
-        def __hash__(self):
-            raise TypeError
-
-        def __copy__(self):
-            return self.__class__(self)
-
-        def __deepcopy__(self, memo={}):
-            from copy import deepcopy
-            result = self.__class__()
-            memo[id(self)] = result
-            result.__init__(deepcopy(tuple(self), memo))
-            return result
-
-
-#==============================================================================
-# threading.Event
-#==============================================================================
-
-if sys.version_info >= (2, 6):
-    from threading import Event, Thread
-else:
-    from threading import _Verbose, Lock, Thread, _time, \
-        _allocate_lock, RLock, _sleep
-
-    def Condition(*args, **kwargs):
-        return _Condition(*args, **kwargs)
-
-    class _Condition(_Verbose):
-
-        def __init__(self, lock=None, verbose=None):
-            _Verbose.__init__(self, verbose)
-            if lock is None:
-                lock = RLock()
-            self.__lock = lock
-            # Export the lock's acquire() and release() methods
-            self.acquire = lock.acquire
-            self.release = lock.release
-            # If the lock defines _release_save() and/or _acquire_restore(),
-            # these override the default implementations (which just call
-            # release() and acquire() on the lock).  Ditto for _is_owned().
-            try:
-                self._release_save = lock._release_save
-            except AttributeError:
-                pass
-            try:
-                self._acquire_restore = lock._acquire_restore
-            except AttributeError:
-                pass
-            try:
-                self._is_owned = lock._is_owned
-            except AttributeError:
-                pass
-            self.__waiters = []
-
-        def __enter__(self):
-            return self.__lock.__enter__()
-
-        def __exit__(self, *args):
-            return self.__lock.__exit__(*args)
-
-        def __repr__(self):
-            return "<Condition(%s, %d)>" % (self.__lock, len(self.__waiters))
-
-        def _release_save(self):
-            self.__lock.release()           # No state to save
-
-        def _acquire_restore(self, x):
-            self.__lock.acquire()           # Ignore saved state
-
-        def _is_owned(self):
-            # Return True if lock is owned by current_thread.
-            # This method is called only if __lock doesn't have _is_owned().
-            if self.__lock.acquire(0):
-                self.__lock.release()
-                return False
-            else:
-                return True
-
-        def wait(self, timeout=None):
-            if not self._is_owned():
-                raise RuntimeError("cannot wait on un-acquired lock")
-            waiter = _allocate_lock()
-            waiter.acquire()
-            self.__waiters.append(waiter)
-            saved_state = self._release_save()
-            try:    # restore state no matter what (e.g., KeyboardInterrupt)
-                if timeout is None:
-                    waiter.acquire()
-                    if __debug__:
-                        self._note("%s.wait(): got it", self)
-                else:
-                    # Balancing act:  We can't afford a pure busy loop, so we
-                    # have to sleep; but if we sleep the whole timeout time,
-                    # we'll be unresponsive.  The scheme here sleeps very
-                    # little at first, longer as time goes on, but never longer
-                    # than 20 times per second (or the timeout time remaining).
-                    endtime = _time() + timeout
-                    delay = 0.0005 # 500 us -> initial delay of 1 ms
-                    while True:
-                        gotit = waiter.acquire(0)
-                        if gotit:
-                            break
-                        remaining = endtime - _time()
-                        if remaining <= 0:
-                            break
-                        delay = min(delay * 2, remaining, .05)
-                        _sleep(delay)
-                    if not gotit:
-                        if __debug__:
-                            self._note("%s.wait(%s): timed out", self, timeout)
-                        try:
-                            self.__waiters.remove(waiter)
-                        except ValueError:
-                            pass
-                    else:
-                        if __debug__:
-                            self._note("%s.wait(%s): got it", self, timeout)
-            finally:
-                self._acquire_restore(saved_state)
-
-        def notify(self, n=1):
-            if not self._is_owned():
-                raise RuntimeError("cannot notify on un-acquired lock")
-            __waiters = self.__waiters
-            waiters = __waiters[:n]
-            if not waiters:
-                if __debug__:
-                    self._note("%s.notify(): no waiters", self)
-                return
-            self._note("%s.notify(): notifying %d waiter%s", self, n,
-                       n != 1 and "s" or "")
-            for waiter in waiters:
-                waiter.release()
-                try:
-                    __waiters.remove(waiter)
-                except ValueError:
-                    pass
-
-        def notifyAll(self):
-            self.notify(len(self.__waiters))
-
-        notify_all = notifyAll
-
-    def Event(*args, **kwargs):
-        return _Event(*args, **kwargs)
-
-    class _Event(_Verbose):
-
-        # After Tim Peters' event class (without is_posted())
-
-        def __init__(self, verbose=None):
-            _Verbose.__init__(self, verbose)
-            self.__cond = Condition(Lock())
-            self.__flag = False
-
-        def isSet(self):
-            return self.__flag
-
-        is_set = isSet
-
-        def set(self):
-            self.__cond.acquire()
-            try:
-                self.__flag = True
-                self.__cond.notify_all()
-            finally:
-                self.__cond.release()
-
-        def clear(self):
-            self.__cond.acquire()
-            try:
-                self.__flag = False
-            finally:
-                self.__cond.release()
-
-        def wait(self, timeout=None):
-            self.__cond.acquire()
-            try:
-                if not self.__flag:
-                    self.__cond.wait(timeout)
-            finally:
-                self.__cond.release()
--- a/kallithea/lib/vcs/utils/diffs.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/vcs/utils/diffs.py	Fri Nov 18 01:11:13 2016 +0100
@@ -335,7 +335,7 @@
 
     def prepare(self):
         """
-        Prepare the passed udiff for HTML rendering. It'l return a list
+        Prepare the passed udiff for HTML rendering. It'll return a list
         of dicts
         """
         return self._parse_udiff()
@@ -389,15 +389,15 @@
         diff_lines = self.prepare()
         _html_empty = True
         _html = []
-        _html.append('''<table class="%(table_class)s">\n''' \
-                                            % {'table_class': table_class})
+        _html.append('''<table class="%(table_class)s">\n'''
+                     % {'table_class': table_class})
         for diff in diff_lines:
             for line in diff['chunks']:
                 _html_empty = False
                 for change in line:
-                    _html.append('''<tr class="%(line_class)s %(action)s">\n''' \
-                        % {'line_class': line_class,
-                           'action': change['action']})
+                    _html.append('''<tr class="%(line_class)s %(action)s">\n'''
+                                 % {'line_class': line_class,
+                                    'action': change['action']})
                     anchor_old_id = ''
                     anchor_new_id = ''
                     anchor_old = "%(filename)s_o%(oldline_no)s" % \
@@ -417,35 +417,32 @@
                     ###########################################################
                     # OLD LINE NUMBER
                     ###########################################################
-                    _html.append('''\t<td %(a_id)s class="%(old_lineno_cls)s">''' \
-                                    % {'a_id': anchor_old_id,
-                                       'old_lineno_cls': old_lineno_class})
+                    _html.append('''\t<td %(a_id)s class="%(old_lineno_cls)s">'''
+                                  % {'a_id': anchor_old_id,
+                                     'old_lineno_cls': old_lineno_class})
 
-                    _html.append('''<pre>%(link)s</pre>''' \
-                        % {'link':
-                        _link_to_if(cond_old, change['old_lineno'], '#%s' \
-                                                                % anchor_old)})
+                    _html.append('''<pre>%(link)s</pre>'''
+                                 % {'link':
+                                    _link_to_if(cond_old, change['old_lineno'], '#%s' % anchor_old)})
                     _html.append('''</td>\n''')
                     ###########################################################
                     # NEW LINE NUMBER
                     ###########################################################
 
-                    _html.append('''\t<td %(a_id)s class="%(new_lineno_cls)s">''' \
-                                    % {'a_id': anchor_new_id,
-                                       'new_lineno_cls': new_lineno_class})
+                    _html.append('''\t<td %(a_id)s class="%(new_lineno_cls)s">'''
+                                  % {'a_id': anchor_new_id,
+                                     'new_lineno_cls': new_lineno_class})
 
-                    _html.append('''<pre>%(link)s</pre>''' \
-                        % {'link':
-                        _link_to_if(cond_new, change['new_lineno'], '#%s' \
-                                                                % anchor_new)})
+                    _html.append('''<pre>%(link)s</pre>'''
+                                 % {'link': _link_to_if(cond_new, change['new_lineno'], '#%s' % anchor_new)})
                     _html.append('''</td>\n''')
                     ###########################################################
                     # CODE
                     ###########################################################
-                    _html.append('''\t<td class="%(code_class)s">''' \
-                                                % {'code_class': code_class})
-                    _html.append('''\n\t\t<pre>%(code)s</pre>\n''' \
-                                                % {'code': change['line']})
+                    _html.append('''\t<td class="%(code_class)s">'''
+                                 % {'code_class': code_class})
+                    _html.append('''\n\t\t<pre>%(code)s</pre>\n'''
+                                 % {'code': change['line']})
                     _html.append('''\t</td>''')
                     _html.append('''\n</tr>\n''')
         _html.append('''</table>''')
--- a/kallithea/lib/vcs/utils/imports.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/vcs/utils/imports.py	Fri Nov 18 01:11:13 2016 +0100
@@ -19,7 +19,7 @@
     try:
         class_mod = __import__(mod_path, {}, {}, [class_name])
     except ImportError as err:
-        msg = "There was problem while trying to import backend class. "\
+        msg = "There was problem while trying to import backend class. " \
             "Original error was:\n%s" % err
         raise VCSError(msg)
     cls = getattr(class_mod, class_name)
--- a/kallithea/lib/vcs/utils/termcolors.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/vcs/utils/termcolors.py	Fri Nov 18 01:11:13 2016 +0100
@@ -123,7 +123,7 @@
 def parse_color_setting(config_string):
     """Parse a DJANGO_COLORS environment variable to produce the system palette
 
-    The general form of a pallete definition is:
+    The general form of a palette definition is:
 
         "palette;role=fg;role=fg/bg;role=fg,option,option;role=fg/bg,option,option"
 
@@ -135,7 +135,7 @@
         option is a display options.
 
     Specifying a named palette is the same as manually specifying the individual
-    definitions for each role. Any individual definitions following the pallete
+    definitions for each role. Any individual definitions following the palette
     definition will augment the base palette definition.
 
     Valid roles:
--- a/kallithea/lib/verlib.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/lib/verlib.py	Fri Nov 18 01:11:13 2016 +0100
@@ -251,7 +251,7 @@
     rs = re.sub(r"dev$", r"dev0", rs)
 
     # if we have something like "b-2" or "a.2" at the end of the
-    # version, that is pobably beta, alpha, etc
+    # version, that is probably beta, alpha, etc
     # let's remove the dash or dot
     rs = re.sub(r"([abc|rc])[\-\.](\d+)$", r"\1\2", rs)
 
--- a/kallithea/model/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/__init__.py	Fri Nov 18 01:11:13 2016 +0100
@@ -23,119 +23,4 @@
 :author: marcink
 :copyright: (c) 2013 RhodeCode GmbH, and others.
 :license: GPLv3, see LICENSE.md for more details.
-
-
-:example:
-
-    .. code-block:: python
-
-       from paste.deploy import appconfig
-       from pylons import config
-       from sqlalchemy import engine_from_config
-       from kallithea.config.environment import load_environment
-
-       conf = appconfig('config:development.ini', relative_to = './../../')
-       load_environment(conf.global_conf, conf.local_conf)
-
-       engine = engine_from_config(config, 'sqlalchemy.')
-       init_model(engine)
-       # RUN YOUR CODE HERE
-
 """
-
-
-import logging
-from kallithea.model import meta
-from kallithea.lib.utils2 import safe_str, obfuscate_url_pw
-
-log = logging.getLogger(__name__)
-
-
-def init_model(engine):
-    """
-    Initializes db session, bind the engine with the metadata,
-    Call this before using any of the tables or classes in the model,
-    preferably once in application start
-
-    :param engine: engine to bind to
-    """
-    engine_str = obfuscate_url_pw(str(engine.url))
-    log.info("initializing db for %s", engine_str)
-    meta.Base.metadata.bind = engine
-
-
-class BaseModel(object):
-    """
-    Base Model for all Kallithea models, it adds sql alchemy session
-    into instance of model
-
-    :param sa: If passed it reuses this session instead of creating a new one
-    """
-
-    cls = None  # override in child class
-
-    def __init__(self, sa=None):
-        if sa is not None:
-            self.sa = sa
-        else:
-            self.sa = meta.Session()
-
-    def _get_instance(self, cls, instance, callback=None):
-        """
-        Gets instance of given cls using some simple lookup mechanism.
-
-        :param cls: class to fetch
-        :param instance: int or Instance
-        :param callback: callback to call if all lookups failed
-        """
-
-        if isinstance(instance, cls):
-            return instance
-        elif isinstance(instance, (int, long)) or safe_str(instance).isdigit():
-            return cls.get(instance)
-        else:
-            if instance is not None:
-                if callback is None:
-                    raise Exception(
-                        'given object must be int, long or Instance of %s '
-                        'got %s, no callback provided' % (cls, type(instance))
-                    )
-                else:
-                    return callback(instance)
-
-    def _get_user(self, user):
-        """
-        Helper method to get user by ID, or username fallback
-
-        :param user: UserID, username, or User instance
-        """
-        from kallithea.model.db import User
-        return self._get_instance(User, user,
-                                  callback=User.get_by_username)
-
-    def _get_repo(self, repository):
-        """
-        Helper method to get repository by ID, or repository name
-
-        :param repository: RepoID, repository name or Repository Instance
-        """
-        from kallithea.model.db import Repository
-        return self._get_instance(Repository, repository,
-                                  callback=Repository.get_by_repo_name)
-
-    def _get_perm(self, permission):
-        """
-        Helper method to get permission by ID, or permission name
-
-        :param permission: PermissionID, permission_name or Permission instance
-        """
-        from kallithea.model.db import Permission
-        return self._get_instance(Permission, permission,
-                                  callback=Permission.get_by_key)
-
-    @classmethod
-    def get_all(cls):
-        """
-        Returns all instances of what is defined in `cls` class variable
-        """
-        return cls.cls.getAll()
--- a/kallithea/model/api_key.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/api_key.py	Fri Nov 18 01:11:13 2016 +0100
@@ -30,7 +30,7 @@
 from sqlalchemy import or_
 
 from kallithea.lib.utils2 import generate_api_key
-from kallithea.model import BaseModel
+from kallithea.model.base import BaseModel
 from kallithea.model.db import UserApiKeys
 from kallithea.model.meta import Session
 
@@ -38,7 +38,6 @@
 
 
 class ApiKeyModel(BaseModel):
-    cls = UserApiKeys
 
     def create(self, user, description, lifetime=-1):
         """
@@ -73,10 +72,10 @@
 
     def get_api_keys(self, user, show_expired=True):
         user = self._get_user(user)
-        user_api_keys = UserApiKeys.query()\
+        user_api_keys = UserApiKeys.query() \
             .filter(UserApiKeys.user_id == user.user_id)
         if not show_expired:
-            user_api_keys = user_api_keys\
+            user_api_keys = user_api_keys \
                 .filter(or_(UserApiKeys.expires == -1,
                             UserApiKeys.expires >= time.time()))
         return user_api_keys
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/model/base.py	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,109 @@
+# -*- coding: utf-8 -*-
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+"""
+kallithea.model.base
+~~~~~~~~~~~~~~~~~~~~
+
+The application's model objects
+
+This file was forked by the Kallithea project in July 2014.
+Original author and date, and relevant copyright and licensing information is below:
+:created_on: Nov 25, 2010
+:author: marcink
+:copyright: (c) 2013 RhodeCode GmbH, and others.
+:license: GPLv3, see LICENSE.md for more details.
+
+
+:example:
+
+    .. code-block:: python
+
+       from paste.deploy import appconfig
+       from pylons import config
+       from sqlalchemy import engine_from_config
+       from kallithea.config.environment import load_environment
+
+       conf = appconfig('config:development.ini', relative_to = './../../')
+       load_environment(conf.global_conf, conf.local_conf)
+
+       engine = engine_from_config(config, 'sqlalchemy.')
+       init_model(engine)
+       # RUN YOUR CODE HERE
+
+"""
+
+
+import logging
+from kallithea.model import meta
+from kallithea.lib.utils2 import obfuscate_url_pw
+
+log = logging.getLogger(__name__)
+
+
+def init_model(engine):
+    """
+    Initializes db session, bind the engine with the metadata,
+    Call this before using any of the tables or classes in the model,
+    preferably once in application start
+
+    :param engine: engine to bind to
+    """
+    engine_str = obfuscate_url_pw(str(engine.url))
+    log.info("initializing db for %s", engine_str)
+    meta.Base.metadata.bind = engine
+
+
+class BaseModel(object):
+    """
+    Base Model for all Kallithea models, it adds sql alchemy session
+    into instance of model
+
+    :param sa: If passed it reuses this session instead of creating a new one
+    """
+
+    def __init__(self, sa=None):
+        if sa is not None:
+            self.sa = sa
+        else:
+            self.sa = meta.Session()
+
+    def _get_user(self, user):
+        """
+        Helper method to get user by ID, or username fallback
+
+        :param user: UserID, username, or User instance
+        """
+        from kallithea.model.db import User
+        return User.guess_instance(user,
+                                  callback=User.get_by_username)
+
+    def _get_repo(self, repository):
+        """
+        Helper method to get repository by ID, or repository name
+
+        :param repository: RepoID, repository name or Repository Instance
+        """
+        from kallithea.model.db import Repository
+        return Repository.guess_instance(repository,
+                                  callback=Repository.get_by_repo_name)
+
+    def _get_perm(self, permission):
+        """
+        Helper method to get permission by ID, or permission name
+
+        :param permission: PermissionID, permission_name or Permission instance
+        """
+        from kallithea.model.db import Permission
+        return Permission.guess_instance(permission,
+                                  callback=Permission.get_by_key)
--- a/kallithea/model/changeset_status.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/changeset_status.py	Fri Nov 18 01:11:13 2016 +0100
@@ -28,7 +28,7 @@
 import logging
 from sqlalchemy.orm import joinedload
 
-from kallithea.model import BaseModel
+from kallithea.model.base import BaseModel
 from kallithea.model.db import ChangesetStatus, PullRequest
 from kallithea.lib.exceptions import StatusChangeOnClosedPullRequestError
 
@@ -37,27 +37,20 @@
 
 class ChangesetStatusModel(BaseModel):
 
-    cls = ChangesetStatus
-
-    def __get_changeset_status(self, changeset_status):
-        return self._get_instance(ChangesetStatus, changeset_status)
-
-    def __get_pull_request(self, pull_request):
-        return self._get_instance(PullRequest, pull_request)
-
     def _get_status_query(self, repo, revision, pull_request,
                           with_revisions=False):
         repo = self._get_repo(repo)
 
-        q = ChangesetStatus.query()\
+        q = ChangesetStatus.query() \
             .filter(ChangesetStatus.repo == repo)
         if not with_revisions:
+            # only report the latest vote across all users! TODO: be smarter!
             q = q.filter(ChangesetStatus.version == 0)
 
         if revision:
             q = q.filter(ChangesetStatus.revision == revision)
         elif pull_request:
-            pull_request = self.__get_pull_request(pull_request)
+            pull_request = PullRequest.guess_instance(pull_request)
             q = q.filter(ChangesetStatus.pull_request == pull_request)
         else:
             raise Exception('Please specify revision or pull_request')
@@ -98,14 +91,14 @@
         pull_request_reviewers = []
         pull_request_pending_reviewers = []
         relevant_statuses = []
-        for r in pull_request.reviewers:
-            st = cs_statuses.get(r.user.username)
+        for user in pull_request.get_reviewer_users():
+            st = cs_statuses.get(user.username)
             relevant_statuses.append(st)
-            if not st or st.status in (ChangesetStatus.STATUS_NOT_REVIEWED,
-                                       ChangesetStatus.STATUS_UNDER_REVIEW):
-                st = None
-                pull_request_pending_reviewers.append(r.user)
-            pull_request_reviewers.append((r.user, st))
+            status = ChangesetStatus.STATUS_NOT_REVIEWED if st is None else st.status
+            if status in (ChangesetStatus.STATUS_NOT_REVIEWED,
+                          ChangesetStatus.STATUS_UNDER_REVIEW):
+                pull_request_pending_reviewers.append(user)
+            pull_request_reviewers.append((user, status))
 
         result = self._calculate_status(relevant_statuses)
 
@@ -166,7 +159,7 @@
             revisions = [revision]
         else:
             assert pull_request is not None
-            pull_request = self.__get_pull_request(pull_request)
+            pull_request = PullRequest.guess_instance(pull_request)
             repo = pull_request.org_repo
             q = q.filter(ChangesetStatus.repo == repo)
             q = q.filter(ChangesetStatus.revision.in_(pull_request.revisions))
--- a/kallithea/model/comment.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/comment.py	Fri Nov 18 01:11:13 2016 +0100
@@ -32,7 +32,7 @@
 
 from kallithea.lib.utils2 import extract_mentioned_users, safe_unicode
 from kallithea.lib import helpers as h
-from kallithea.model import BaseModel
+from kallithea.model.base import BaseModel
 from kallithea.model.db import ChangesetComment, User, \
     Notification, PullRequest
 from kallithea.model.notification import NotificationModel
@@ -43,23 +43,7 @@
 
 class ChangesetCommentsModel(BaseModel):
 
-    cls = ChangesetComment
-
-    def __get_changeset_comment(self, changeset_comment):
-        return self._get_instance(ChangesetComment, changeset_comment)
-
-    def __get_pull_request(self, pull_request):
-        return self._get_instance(PullRequest, pull_request)
-
-    def _extract_mentions(self, s):
-        user_objects = []
-        for username in extract_mentioned_users(s):
-            user_obj = User.get_by_username(username, case_insensitive=True)
-            if user_obj:
-                user_objects.append(user_obj)
-        return user_objects
-
-    def _get_notification_data(self, repo, comment, user, comment_text,
+    def _get_notification_data(self, repo, comment, author, comment_text,
                                line_no=None, revision=None, pull_request=None,
                                status_change=None, closing_pr=False):
         """
@@ -96,19 +80,23 @@
             cs_author = User.get_from_cs_author(cs.author)
             if not cs_author:
                 #use repo owner if we cannot extract the author correctly
-                cs_author = repo.user
+                # FIXME: just use committer name even if not a user
+                cs_author = repo.owner
             recipients += [cs_author]
             email_kwargs = {
                 'status_change': status_change,
-                'cs_comment_user': user.full_name_and_username,
+                'cs_comment_user': author.full_name_and_username,
                 'cs_target_repo': h.canonical_url('summary_home', repo_name=repo.repo_name),
                 'cs_comment_url': comment_url,
+                'cs_url': h.canonical_url('changeset_home', repo_name=repo.repo_name, revision=revision),
                 'raw_id': revision,
                 'message': cs.message,
+                'message_short': h.shorter(cs.message, 50, firstline=True),
+                'cs_author': cs_author,
                 'repo_name': repo.repo_name,
                 'short_id': h.short_id(revision),
                 'branch': cs.branch,
-                'comment_username': user.username,
+                'comment_username': author.username,
                 'threading': threading,
             }
         #pull request
@@ -116,6 +104,7 @@
             notification_type = Notification.TYPE_PULL_REQUEST_COMMENT
             desc = comment.pull_request.title
             _org_ref_type, org_ref_name, _org_rev = comment.pull_request.org_ref.split(':')
+            _other_ref_type, other_ref_name, _other_rev = comment.pull_request.other_ref.split(':')
             threading = ['%s-pr-%s@%s' % (pull_request.other_repo.repo_name,
                                           pull_request.pull_request_id,
                                           h.canonical_hostname())]
@@ -139,27 +128,34 @@
             recipients += [pull_request.owner]
 
             # add the reviewers to notification
-            recipients += [x.user for x in pull_request.reviewers]
+            recipients += pull_request.get_reviewer_users()
 
             #set some variables for email notification
             email_kwargs = {
                 'pr_title': pull_request.title,
+                'pr_title_short': h.shorter(pull_request.title, 50),
                 'pr_nice_id': pull_request.nice_id(),
                 'status_change': status_change,
                 'closing_pr': closing_pr,
                 'pr_comment_url': comment_url,
-                'pr_comment_user': user.full_name_and_username,
+                'pr_url': pull_request.url(canonical=True),
+                'pr_comment_user': author.full_name_and_username,
                 'pr_target_repo': h.canonical_url('summary_home',
                                    repo_name=pull_request.other_repo.repo_name),
+                'pr_target_branch': other_ref_name,
+                'pr_source_repo': h.canonical_url('summary_home',
+                                   repo_name=pull_request.org_repo.repo_name),
+                'pr_source_branch': org_ref_name,
+                'pr_owner': pull_request.owner,
+                'pr_owner_username': pull_request.owner.username,
                 'repo_name': pull_request.other_repo.repo_name,
-                'ref': org_ref_name,
-                'comment_username': user.username,
+                'comment_username': author.username,
                 'threading': threading,
             }
 
         return subj, body, recipients, notification_type, email_kwargs
 
-    def create(self, text, repo, user, revision=None, pull_request=None,
+    def create(self, text, repo, author, revision=None, pull_request=None,
                f_path=None, line_no=None, status_change=None, closing_pr=False,
                send_email=True):
         """
@@ -173,10 +169,10 @@
             return None
 
         repo = self._get_repo(repo)
-        user = self._get_user(user)
+        author = self._get_user(author)
         comment = ChangesetComment()
         comment.repo = repo
-        comment.author = user
+        comment.author = author
         comment.text = text
         comment.f_path = f_path
         comment.line_no = line_no
@@ -184,7 +180,7 @@
         if revision is not None:
             comment.revision = revision
         elif pull_request is not None:
-            pull_request = self.__get_pull_request(pull_request)
+            pull_request = PullRequest.guess_instance(pull_request)
             comment.pull_request = pull_request
         else:
             raise Exception('Please specify revision or pull_request_id')
@@ -195,7 +191,7 @@
         if send_email:
             (subj, body, recipients, notification_type,
              email_kwargs) = self._get_notification_data(
-                                repo, comment, user,
+                                repo, comment, author,
                                 comment_text=text,
                                 line_no=line_no,
                                 revision=revision,
@@ -205,18 +201,18 @@
             email_kwargs['is_mention'] = False
             # create notification objects, and emails
             NotificationModel().create(
-                created_by=user, subject=subj, body=body,
+                created_by=author, subject=subj, body=body,
                 recipients=recipients, type_=notification_type,
                 email_kwargs=email_kwargs,
             )
 
-            mention_recipients = set(self._extract_mentions(body))\
-                                    .difference(recipients)
+            mention_recipients = extract_mentioned_users(body).difference(recipients)
             if mention_recipients:
                 email_kwargs['is_mention'] = True
                 subj = _('[Mention]') + ' ' + subj
+                # FIXME: this subject is wrong and unused!
                 NotificationModel().create(
-                    created_by=user, subject=subj, body=body,
+                    created_by=author, subject=subj, body=body,
                     recipients=mention_recipients,
                     type_=notification_type,
                     email_kwargs=email_kwargs
@@ -225,7 +221,7 @@
         return comment
 
     def delete(self, comment):
-        comment = self.__get_changeset_comment(comment)
+        comment = ChangesetComment.guess_instance(comment)
         Session().delete(comment)
 
         return comment
@@ -260,17 +256,17 @@
         q = Session().query(ChangesetComment)
 
         if inline:
-            q = q.filter(ChangesetComment.line_no != None)\
+            q = q.filter(ChangesetComment.line_no != None) \
                 .filter(ChangesetComment.f_path != None)
         else:
-            q = q.filter(ChangesetComment.line_no == None)\
+            q = q.filter(ChangesetComment.line_no == None) \
                 .filter(ChangesetComment.f_path == None)
 
-        if revision:
-            q = q.filter(ChangesetComment.revision == revision)\
+        if revision is not None:
+            q = q.filter(ChangesetComment.revision == revision) \
                 .filter(ChangesetComment.repo_id == repo_id)
-        elif pull_request:
-            pull_request = self.__get_pull_request(pull_request)
+        elif pull_request is not None:
+            pull_request = PullRequest.guess_instance(pull_request)
             q = q.filter(ChangesetComment.pull_request == pull_request)
         else:
             raise Exception('Please specify either revision or pull_request')
--- a/kallithea/model/db.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/db.py	Fri Nov 18 01:11:13 2016 +0100
@@ -43,7 +43,6 @@
 
 from pylons.i18n.translation import lazy_ugettext as _
 
-from kallithea import DB_PREFIX
 from kallithea.lib.exceptions import DefaultUserException
 from kallithea.lib.vcs import get_backend
 from kallithea.lib.vcs.utils.helpers import get_scm
@@ -68,7 +67,7 @@
 _hash_key = lambda k: hashlib.md5(safe_str(k)).hexdigest()
 
 
-class BaseModel(object):
+class BaseDbModel(object):
     """
     Base Model for all classes
     """
@@ -123,6 +122,32 @@
             return cls.query().get(id_)
 
     @classmethod
+    def guess_instance(cls, value, callback=None):
+        """Haphazardly attempt to convert `value` to a `cls` instance.
+
+        If `value` is None or already a `cls` instance, return it. If `value`
+        is a number (or looks like one if you squint just right), assume it's
+        a database primary key and let SQLAlchemy sort things out. Otherwise,
+        fall back to resolving it using `callback` (if specified); this could
+        e.g. be a function that looks up instances by name (though that won't
+        work if the name begins with a digit). Otherwise, raise Exception.
+        """
+
+        if value is None:
+            return None
+        if isinstance(value, cls):
+            return value
+        if isinstance(value, (int, long)) or safe_str(value).isdigit():
+            return cls.get(value)
+        if callback is not None:
+            return callback(value)
+
+        raise Exception(
+            'given object must be int, long or Instance of %s '
+            'got %s, no callback provided' % (cls, type(value))
+        )
+
+    @classmethod
     def get_or_404(cls, id_):
         try:
             id_ = int(id_)
@@ -135,15 +160,6 @@
         return res
 
     @classmethod
-    def getAll(cls):
-        # deprecated and left for backward compatibility
-        return cls.get_all()
-
-    @classmethod
-    def get_all(cls):
-        return cls.query().all()
-
-    @classmethod
     def delete(cls, id_):
         obj = cls.query().get(id_)
         Session().delete(obj)
@@ -158,13 +174,16 @@
         return '<DB:%s>' % (self.__class__.__name__)
 
 
-class Setting(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'settings'
-
+_table_args_default_dict = {'extend_existing': True,
+                            'mysql_engine': 'InnoDB',
+                            'mysql_charset': 'utf8',
+                            'sqlite_autoincrement': True,
+                           }
+
+class Setting(Base, BaseDbModel):
+    __tablename__ = 'settings'
     __table_args__ = (
-        UniqueConstraint('app_settings_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        _table_args_default_dict,
     )
 
     SETTINGS_TYPES = {
@@ -176,10 +195,10 @@
     }
     DEFAULT_UPDATE_URL = ''
 
-    app_settings_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    app_settings_name = Column(String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    _app_settings_value = Column("app_settings_value", String(4096, convert_unicode=False), nullable=True, unique=None, default=None)
-    _app_settings_type = Column("app_settings_type", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
+    app_settings_id = Column(Integer(), primary_key=True)
+    app_settings_name = Column(String(255), nullable=False, unique=True)
+    _app_settings_value = Column("app_settings_value", Unicode(4096), nullable=False)
+    _app_settings_type = Column("app_settings_type", String(255), nullable=True) # FIXME: not nullable?
 
     def __init__(self, key='', val='', type='unicode'):
         self.app_settings_name = key
@@ -226,7 +245,7 @@
 
     @classmethod
     def get_by_name(cls, key):
-        return cls.query()\
+        return cls.query() \
             .filter(cls.app_settings_name == key).scalar()
 
     @classmethod
@@ -252,6 +271,7 @@
             val = Optional.extract(val)
             type = Optional.extract(type)
             res = cls(key, val, type)
+            Session().add(res)
         else:
             res.app_settings_name = key
             if not isinstance(val, Optional):
@@ -286,7 +306,7 @@
 
     @classmethod
     def get_auth_settings(cls, cache=False):
-        ret = cls.query()\
+        ret = cls.query() \
                 .filter(cls.app_settings_name.startswith('auth_')).all()
         fd = {}
         for row in ret:
@@ -295,7 +315,7 @@
 
     @classmethod
     def get_default_repo_settings(cls, cache=False, strip_prefix=False):
-        ret = cls.query()\
+        ret = cls.query() \
                 .filter(cls.app_settings_name.startswith('default_')).all()
         fd = {}
         for row in ret:
@@ -324,12 +344,14 @@
         return info
 
 
-class Ui(Base, BaseModel):
-    __tablename__ = DB_PREFIX + 'ui'
+class Ui(Base, BaseDbModel):
+    __tablename__ = 'ui'
     __table_args__ = (
+        # FIXME: ui_key as key is wrong and should be removed when the corresponding
+        # Ui.get_by_key has been replaced by the composite key
         UniqueConstraint('ui_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        UniqueConstraint('ui_section', 'ui_key'),
+        _table_args_default_dict,
     )
 
     HOOK_UPDATE = 'changegroup.update'
@@ -339,20 +361,25 @@
     HOOK_PULL = 'outgoing.pull_logger'
     HOOK_PRE_PULL = 'preoutgoing.pre_pull'
 
-    ui_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    ui_section = Column(String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    ui_key = Column(String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    ui_value = Column(String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    ui_active = Column(Boolean(), nullable=True, unique=None, default=True)
-
-    # def __init__(self, section='', key='', value=''):
-    #     self.ui_section = section
-    #     self.ui_key = key
-    #     self.ui_value = value
+    ui_id = Column(Integer(), primary_key=True)
+    ui_section = Column(String(255), nullable=False)
+    ui_key = Column(String(255), nullable=False)
+    ui_value = Column(String(255), nullable=True) # FIXME: not nullable?
+    ui_active = Column(Boolean(), nullable=False, default=True)
 
     @classmethod
-    def get_by_key(cls, key):
-        return cls.query().filter(cls.ui_key == key).scalar()
+    def get_by_key(cls, section, key):
+        """ Return specified Ui object, or None if not found. """
+        return cls.query().filter_by(ui_section=section, ui_key=key).scalar()
+
+    @classmethod
+    def get_or_create(cls, section, key):
+        """ Return specified Ui object, creating it if necessary. """
+        setting = cls.get_by_key(section, key)
+        if setting is None:
+            setting = cls(ui_section=section, ui_key=key)
+            Session().add(setting)
+        return setting
 
     @classmethod
     def get_builtin_hooks(cls):
@@ -360,6 +387,7 @@
         q = q.filter(cls.ui_key.in_([cls.HOOK_UPDATE, cls.HOOK_REPO_SIZE,
                                      cls.HOOK_PUSH, cls.HOOK_PRE_PUSH,
                                      cls.HOOK_PULL, cls.HOOK_PRE_PULL]))
+        q = q.filter(cls.ui_section == 'hooks')
         return q.all()
 
     @classmethod
@@ -373,50 +401,47 @@
 
     @classmethod
     def get_repos_location(cls):
-        return cls.get_by_key('/').ui_value
+        return cls.get_by_key('paths', '/').ui_value
 
     @classmethod
     def create_or_update_hook(cls, key, val):
-        new_ui = cls.get_by_key(key) or cls()
-        new_ui.ui_section = 'hooks'
+        new_ui = cls.get_or_create('hooks', key)
         new_ui.ui_active = True
-        new_ui.ui_key = key
         new_ui.ui_value = val
 
-        Session().add(new_ui)
-
     def __repr__(self):
         return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
                                     self.ui_key, self.ui_value)
 
 
-class User(Base, BaseModel):
+class User(Base, BaseDbModel):
     __tablename__ = 'users'
     __table_args__ = (
-        UniqueConstraint('username'), UniqueConstraint('email'),
         Index('u_username_idx', 'username'),
         Index('u_email_idx', 'email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        _table_args_default_dict,
     )
+
     DEFAULT_USER = 'default'
     DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
-
-    user_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    username = Column(String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    password = Column(String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    active = Column(Boolean(), nullable=True, unique=None, default=True)
-    admin = Column(Boolean(), nullable=True, unique=None, default=False)
-    name = Column("firstname", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    lastname = Column(String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    last_login = Column(DateTime(timezone=False), nullable=True, unique=None, default=None)
-    extern_type = Column(String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    extern_name = Column(String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    api_key = Column(String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column(Boolean(), nullable=False, unique=None, default=True)
+    # The name of the default auth type in extern_type, 'internal' lives in auth_internal.py
+    DEFAULT_AUTH_TYPE = 'internal'
+
+    user_id = Column(Integer(), primary_key=True)
+    username = Column(String(255), nullable=False, unique=True)
+    password = Column(String(255), nullable=False)
+    active = Column(Boolean(), nullable=False, default=True)
+    admin = Column(Boolean(), nullable=False, default=False)
+    name = Column("firstname", Unicode(255), nullable=False)
+    lastname = Column(Unicode(255), nullable=False)
+    _email = Column("email", String(255), nullable=True, unique=True) # FIXME: not nullable?
+    last_login = Column(DateTime(timezone=False), nullable=True)
+    extern_type = Column(String(255), nullable=True) # FIXME: not nullable?
+    extern_name = Column(String(255), nullable=True) # FIXME: not nullable?
+    api_key = Column(String(255), nullable=False)
+    inherit_default_permissions = Column(Boolean(), nullable=False, default=True)
     created_on = Column(DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    _user_data = Column("user_data", LargeBinary(), nullable=True)  # JSON data
+    _user_data = Column("user_data", LargeBinary(), nullable=True)  # JSON data # FIXME: not nullable?
 
     user_log = relationship('UserLog')
     user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
@@ -537,7 +562,7 @@
     @classmethod
     def get_or_404(cls, id_, allow_default=True):
         '''
-        Overridden version of BaseModel.get_or_404, with an extra check on
+        Overridden version of BaseDbModel.get_or_404, with an extra check on
         the default user.
         '''
         user = super(User, cls).get_or_404(id_)
@@ -547,9 +572,23 @@
         return user
 
     @classmethod
+    def get_by_username_or_email(cls, username_or_email, case_insensitive=False, cache=False):
+        """
+        For anything that looks like an email address, look up by the email address (matching
+        case insensitively).
+        For anything else, try to look up by the user name.
+
+        This assumes no normal username can have '@' symbol.
+        """
+        if '@' in username_or_email:
+            return User.get_by_email(username_or_email, cache=cache)
+        else:
+            return User.get_by_username(username_or_email, case_insensitive=case_insensitive, cache=cache)
+
+    @classmethod
     def get_by_username(cls, username, case_insensitive=False, cache=False):
         if case_insensitive:
-            q = cls.query().filter(cls.username.ilike(username))
+            q = cls.query().filter(func.lower(cls.username) == func.lower(username))
         else:
             q = cls.query().filter(cls.username == username)
 
@@ -575,21 +614,18 @@
 
         if fallback and not res:
             #fallback to additional keys
-            _res = UserApiKeys.query()\
-                .filter(UserApiKeys.api_key == api_key)\
+            _res = UserApiKeys.query() \
+                .filter(UserApiKeys.api_key == api_key) \
                 .filter(or_(UserApiKeys.expires == -1,
-                            UserApiKeys.expires >= time.time()))\
+                            UserApiKeys.expires >= time.time())) \
                 .first()
             if _res:
                 res = _res.user
         return res
 
     @classmethod
-    def get_by_email(cls, email, case_insensitive=False, cache=False):
-        if case_insensitive:
-            q = cls.query().filter(cls.email.ilike(email))
-        else:
-            q = cls.query().filter(cls.email == email)
+    def get_by_email(cls, email, cache=False):
+        q = cls.query().filter(func.lower(cls.email) == func.lower(email))
 
         if cache:
             q = q.options(FromCache("sql_cache_short",
@@ -599,10 +635,7 @@
         if ret is None:
             q = UserEmailMap.query()
             # try fetching in alternate email map
-            if case_insensitive:
-                q = q.filter(UserEmailMap.email.ilike(email))
-            else:
-                q = q.filter(UserEmailMap.email == email)
+            q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
             q = q.options(joinedload(UserEmailMap.user))
             if cache:
                 q = q.options(FromCache("sql_cache_short",
@@ -622,7 +655,7 @@
         # Valid email in the attribute passed, see if they're in the system
         _email = email(author)
         if _email:
-            user = cls.get_by_email(_email, case_insensitive=True)
+            user = cls.get_by_email(_email)
             if user is not None:
                 return user
         # Maybe we can match by username?
@@ -634,7 +667,6 @@
     def update_lastlogin(self):
         """Update user lastlogin"""
         self.last_login = datetime.datetime.now()
-        Session().add(self)
         log.debug('updated user %s lastlogin', self.username)
 
     @classmethod
@@ -688,21 +720,19 @@
         return data
 
 
-class UserApiKeys(Base, BaseModel):
+class UserApiKeys(Base, BaseDbModel):
     __tablename__ = 'user_api_keys'
     __table_args__ = (
         Index('uak_api_key_idx', 'api_key'),
         Index('uak_api_key_expires_idx', 'api_key', 'expires'),
-        UniqueConstraint('api_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        _table_args_default_dict,
     )
     __mapper_args__ = {}
 
-    user_api_key_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    api_key = Column(String(255, convert_unicode=False), nullable=False, unique=True)
-    description = Column(UnicodeText(1024))
+    user_api_key_id = Column(Integer(), primary_key=True)
+    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False)
+    api_key = Column(String(255), nullable=False, unique=True)
+    description = Column(UnicodeText(), nullable=False)
     expires = Column(Float(53), nullable=False)
     created_on = Column(DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
 
@@ -715,19 +745,17 @@
         return time.time() > self.expires
 
 
-class UserEmailMap(Base, BaseModel):
+class UserEmailMap(Base, BaseDbModel):
     __tablename__ = 'user_email_map'
     __table_args__ = (
         Index('uem_email_idx', 'email'),
-        UniqueConstraint('email'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        _table_args_default_dict,
     )
     __mapper_args__ = {}
 
-    email_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    _email = Column("email", String(255, convert_unicode=False), nullable=True, unique=False, default=None)
+    email_id = Column(Integer(), primary_key=True)
+    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False)
+    _email = Column("email", String(255), nullable=False, unique=True)
     user = relationship('User')
 
     @validates('_email')
@@ -747,19 +775,18 @@
         self._email = val.lower() if val else None
 
 
-class UserIpMap(Base, BaseModel):
+class UserIpMap(Base, BaseDbModel):
     __tablename__ = 'user_ip_map'
     __table_args__ = (
         UniqueConstraint('user_id', 'ip_addr'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        _table_args_default_dict,
     )
     __mapper_args__ = {}
 
-    ip_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    ip_addr = Column(String(255, convert_unicode=False), nullable=True, unique=False, default=None)
-    active = Column(Boolean(), nullable=True, unique=None, default=True)
+    ip_id = Column(Integer(), primary_key=True)
+    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False)
+    ip_addr = Column(String(255), nullable=False)
+    active = Column(Boolean(), nullable=False, default=True)
     user = relationship('User')
 
     @classmethod
@@ -778,20 +805,20 @@
         return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
                                             self.user_id, self.ip_addr)
 
-class UserLog(Base, BaseModel):
+class UserLog(Base, BaseDbModel):
     __tablename__ = 'user_logs'
     __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
+        _table_args_default_dict,
     )
-    user_log_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    username = Column(String(255, convert_unicode=False), nullable=True, unique=None, default=None)
+
+    user_log_id = Column(Integer(), primary_key=True)
+    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=True)
+    username = Column(String(255), nullable=False)
     repository_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=True)
-    repository_name = Column(String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    user_ip = Column(String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    action = Column(UnicodeText(1200000, convert_unicode=False), nullable=True, unique=None, default=None)
-    action_date = Column(DateTime(timezone=False), nullable=True, unique=None, default=None)
+    repository_name = Column(Unicode(255), nullable=False)
+    user_ip = Column(String(255), nullable=True)
+    action = Column(UnicodeText(), nullable=False)
+    action_date = Column(DateTime(timezone=False), nullable=False)
 
     def __unicode__(self):
         return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
@@ -806,21 +833,20 @@
     repository = relationship('Repository', cascade='')
 
 
-class UserGroup(Base, BaseModel):
+class UserGroup(Base, BaseDbModel):
     __tablename__ = 'users_groups'
     __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
+        _table_args_default_dict,
     )
 
-    users_group_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    users_group_name = Column(String(255, convert_unicode=False), nullable=False, unique=True, default=None)
-    user_group_description = Column(String(10000, convert_unicode=False), nullable=True, unique=None, default=None)
-    users_group_active = Column(Boolean(), nullable=True, unique=None, default=None)
-    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
+    users_group_id = Column(Integer(), primary_key=True)
+    users_group_name = Column(Unicode(255), nullable=False, unique=True)
+    user_group_description = Column(Unicode(10000), nullable=True) # FIXME: not nullable?
+    users_group_active = Column(Boolean(), nullable=False)
+    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, default=True)
+    owner_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
     created_on = Column(DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    _group_data = Column("group_data", LargeBinary(), nullable=True)  # JSON data
+    _group_data = Column("group_data", LargeBinary(), nullable=True)  # JSON data # FIXME: not nullable?
 
     members = relationship('UserGroupMember', cascade="all, delete-orphan")
     users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
@@ -829,7 +855,7 @@
     user_user_group_to_perm = relationship('UserUserGroupToPerm ', cascade='all')
     user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
 
-    user = relationship('User')
+    owner = relationship('User')
 
     @hybrid_property
     def group_data(self):
@@ -857,7 +883,7 @@
     def get_by_group_name(cls, group_name, cache=False,
                           case_insensitive=False):
         if case_insensitive:
-            q = cls.query().filter(cls.users_group_name.ilike(group_name))
+            q = cls.query().filter(func.lower(cls.users_group_name) == func.lower(group_name))
         else:
             q = cls.query().filter(cls.users_group_name == group_name)
         if cache:
@@ -884,7 +910,7 @@
             group_name=user_group.users_group_name,
             group_description=user_group.user_group_description,
             active=user_group.users_group_active,
-            owner=user_group.user.username,
+            owner=user_group.owner.username,
         )
         if with_members:
             members = []
@@ -896,16 +922,15 @@
         return data
 
 
-class UserGroupMember(Base, BaseModel):
+class UserGroupMember(Base, BaseDbModel):
     __tablename__ = 'users_groups_members'
     __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
+        _table_args_default_dict,
     )
 
-    users_group_member_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    users_group_id = Column(Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
+    users_group_member_id = Column(Integer(), primary_key=True)
+    users_group_id = Column(Integer(), ForeignKey('users_groups.users_group_id'), nullable=False)
+    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False)
 
     user = relationship('User')
     users_group = relationship('UserGroup')
@@ -915,22 +940,22 @@
         self.user_id = u_id
 
 
-class RepositoryField(Base, BaseModel):
+class RepositoryField(Base, BaseDbModel):
     __tablename__ = 'repositories_fields'
     __table_args__ = (
         UniqueConstraint('repository_id', 'field_key'),  # no-multi field
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
+        _table_args_default_dict,
     )
+
     PREFIX = 'ex_'  # prefix used in form to not conflict with already existing fields
 
-    repo_field_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    repository_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
-    field_key = Column(String(250, convert_unicode=False))
-    field_label = Column(String(1024, convert_unicode=False), nullable=False)
-    field_value = Column(String(10000, convert_unicode=False), nullable=False)
-    field_desc = Column(String(1024, convert_unicode=False), nullable=False)
-    field_type = Column(String(255), nullable=False, unique=None)
+    repo_field_id = Column(Integer(), primary_key=True)
+    repository_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=False)
+    field_key = Column(String(250), nullable=False)
+    field_label = Column(String(1024), nullable=False)
+    field_value = Column(String(10000), nullable=False)
+    field_desc = Column(String(1024), nullable=False)
+    field_type = Column(String(255), nullable=False)
     created_on = Column(DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
 
     repository = relationship('Repository')
@@ -947,49 +972,48 @@
 
     @classmethod
     def get_by_key_name(cls, key, repo):
-        row = cls.query()\
-                .filter(cls.repository == repo)\
+        row = cls.query() \
+                .filter(cls.repository == repo) \
                 .filter(cls.field_key == key).scalar()
         return row
 
 
-class Repository(Base, BaseModel):
+class Repository(Base, BaseDbModel):
     __tablename__ = 'repositories'
     __table_args__ = (
-        UniqueConstraint('repo_name'),
         Index('r_repo_name_idx', 'repo_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
+        _table_args_default_dict,
     )
+
     DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
     DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
 
-    STATE_CREATED = 'repo_state_created'
-    STATE_PENDING = 'repo_state_pending'
-    STATE_ERROR = 'repo_state_error'
-
-    repo_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    repo_name = Column(String(255, convert_unicode=False), nullable=False, unique=True, default=None)
-    repo_state = Column(String(255), nullable=True)
-
-    clone_uri = Column(String(255, convert_unicode=False), nullable=True, unique=False, default=None)
-    repo_type = Column(String(255, convert_unicode=False), nullable=False, unique=False, default=None)
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
-    private = Column(Boolean(), nullable=True, unique=None, default=None)
-    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
-    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
-    description = Column(String(10000, convert_unicode=False), nullable=True, unique=None, default=None)
-    created_on = Column(DateTime(timezone=False), nullable=False, unique=None, default=datetime.datetime.now)
-    updated_on = Column(DateTime(timezone=False), nullable=False, unique=None, default=datetime.datetime.now)
-    _landing_revision = Column("landing_revision", String(255, convert_unicode=False), nullable=False, unique=False, default=None)
-    enable_locking = Column(Boolean(), nullable=False, unique=None, default=False)
-    _locked = Column("locked", String(255, convert_unicode=False), nullable=True, unique=False, default=None)
-    _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) #JSON data
-
-    fork_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
-    group_id = Column(Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
-
-    user = relationship('User')
+    STATE_CREATED = u'repo_state_created'
+    STATE_PENDING = u'repo_state_pending'
+    STATE_ERROR = u'repo_state_error'
+
+    repo_id = Column(Integer(), primary_key=True)
+    repo_name = Column(Unicode(255), nullable=False, unique=True)
+    repo_state = Column(String(255), nullable=False)
+
+    clone_uri = Column(String(255), nullable=True) # FIXME: not nullable?
+    repo_type = Column(String(255), nullable=False)
+    owner_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
+    private = Column(Boolean(), nullable=False)
+    enable_statistics = Column("statistics", Boolean(), nullable=False, default=True)
+    enable_downloads = Column("downloads", Boolean(), nullable=False, default=True)
+    description = Column(Unicode(10000), nullable=False)
+    created_on = Column(DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
+    updated_on = Column(DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
+    _landing_revision = Column("landing_revision", String(255), nullable=False)
+    enable_locking = Column(Boolean(), nullable=False, default=False)
+    _locked = Column("locked", String(255), nullable=True) # FIXME: not nullable?
+    _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) # JSON data # FIXME: not nullable?
+
+    fork_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=True)
+    group_id = Column(Integer(), ForeignKey('groups.group_id'), nullable=True)
+
+    owner = relationship('User')
     fork = relationship('Repository', remote_side=repo_id)
     group = relationship('RepoGroup')
     repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
@@ -997,7 +1021,7 @@
     stats = relationship('Statistics', cascade='all', uselist=False)
 
     followers = relationship('UserFollowing',
-                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
+                             primaryjoin='UserFollowing.follows_repository_id==Repository.repo_id',
                              cascade='all')
     extra_fields = relationship('RepositoryField',
                                 cascade="all, delete-orphan")
@@ -1066,6 +1090,19 @@
             log.error(traceback.format_exc())
 
     @classmethod
+    def query(cls, sorted=False):
+        """Add Repository-specific helpers for common query constructs.
+
+        sorted: if True, apply the default ordering (name, case insensitive).
+        """
+        q = super(Repository, cls).query()
+
+        if sorted:
+            q = q.order_by(func.lower(Repository.repo_name))
+
+        return q
+
+    @classmethod
     def url_sep(cls):
         return URL_SEP
 
@@ -1083,14 +1120,17 @@
     @classmethod
     def get_by_repo_name(cls, repo_name):
         q = Session().query(cls).filter(cls.repo_name == repo_name)
-        q = q.options(joinedload(Repository.fork))\
-                .options(joinedload(Repository.user))\
+        q = q.options(joinedload(Repository.fork)) \
+                .options(joinedload(Repository.owner)) \
                 .options(joinedload(Repository.group))
         return q.scalar()
 
     @classmethod
     def get_by_full_path(cls, repo_full_path):
-        repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
+        base_full_path = os.path.realpath(cls.base_path())
+        repo_full_path = os.path.realpath(repo_full_path)
+        assert repo_full_path.startswith(base_full_path + os.path.sep)
+        repo_name = repo_full_path[len(base_full_path) + 1:]
         repo_name = cls.normalize_repo_name(repo_name)
         return cls.get_by_repo_name(repo_name.strip(URL_SEP))
 
@@ -1105,7 +1145,7 @@
 
         :param cls:
         """
-        q = Session().query(Ui)\
+        q = Session().query(Ui) \
             .filter(Ui.ui_key == cls.url_sep())
         q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
         return q.one().ui_value
@@ -1131,24 +1171,14 @@
     @property
     def groups_with_parents(self):
         groups = []
-        if self.group is None:
-            return groups
-
-        cur_gr = self.group
-        groups.insert(0, cur_gr)
-        while 1:
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            groups.insert(0, gr)
-
+        group = self.group
+        while group is not None:
+            groups.append(group)
+            group = group.parent_group
+            assert group not in groups, group # avoid recursion on bad db content
+        groups.reverse()
         return groups
 
-    @property
-    def groups_and_repo(self):
-        return self.groups_with_parents, self.just_name, self.repo_name
-
     @LazyProperty
     def repo_path(self):
         """
@@ -1174,9 +1204,9 @@
         """
         Returns associated cache keys for that repo
         """
-        return CacheInvalidation.query()\
-            .filter(CacheInvalidation.cache_args == self.repo_name)\
-            .order_by(CacheInvalidation.cache_key)\
+        return CacheInvalidation.query() \
+            .filter(CacheInvalidation.cache_args == self.repo_name) \
+            .order_by(CacheInvalidation.cache_key) \
             .all()
 
     def get_new_name(self, repo_name):
@@ -1223,7 +1253,7 @@
             created_on=repo.created_on,
             description=repo.description,
             landing_rev=repo.landing_rev,
-            owner=repo.user.username,
+            owner=repo.owner.username,
             fork_of=repo.fork.repo_name if repo.fork else None,
             enable_statistics=repo.enable_statistics,
             enable_locking=repo.enable_locking,
@@ -1247,13 +1277,11 @@
         if lock_time is not None:
             lock_time = time.time()
         repo.locked = [user_id, lock_time]
-        Session().add(repo)
         Session().commit()
 
     @classmethod
     def unlock(cls, repo):
         repo.locked = None
-        Session().add(repo)
         Session().commit()
 
     @classmethod
@@ -1305,7 +1333,7 @@
 
     def set_state(self, state):
         self.repo_state = state
-        Session().add(self)
+
     #==========================================================================
     # SCM PROPERTIES
     #==========================================================================
@@ -1354,7 +1382,6 @@
                       self.repo_name, cs_cache)
             self.updated_on = last_change
             self.changeset_cache = cs_cache
-            Session().add(self)
             Session().commit()
         else:
             log.debug('changeset_cache for %s already up to date with %s',
@@ -1378,11 +1405,11 @@
 
         :param revisions: filter query by revisions only
         """
-        cmts = ChangesetComment.query()\
+        cmts = ChangesetComment.query() \
             .filter(ChangesetComment.repo == self)
         if revisions is not None:
             if not revisions:
-                return [] # don't use sql 'in' on empty set
+                return {} # don't use sql 'in' on empty set
             cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
         grouped = collections.defaultdict(list)
         for cmt in cmts.all():
@@ -1399,9 +1426,9 @@
         if not revisions:
             return {}
 
-        statuses = ChangesetStatus.query()\
-            .filter(ChangesetStatus.repo == self)\
-            .filter(ChangesetStatus.version == 0)\
+        statuses = ChangesetStatus.query() \
+            .filter(ChangesetStatus.repo == self) \
+            .filter(ChangesetStatus.version == 0) \
             .filter(ChangesetStatus.revision.in_(revisions))
 
         grouped = {}
@@ -1412,7 +1439,8 @@
                 pr_nice_id = PullRequest.make_nice_id(pr_id)
                 pr_repo = stat.pull_request.other_repo.repo_name
             grouped[stat.revision] = [str(stat.status), stat.status_lbl,
-                                      pr_id, pr_repo, pr_nice_id]
+                                      pr_id, pr_repo, pr_nice_id,
+                                      stat.author]
         return grouped
 
     def _repo_size(self):
@@ -1430,41 +1458,38 @@
         """
         CacheInvalidation.set_invalidate(self.repo_name)
 
-    def scm_instance_no_cache(self):
-        return self.__get_instance()
+    _scm_instance = None
 
     @property
     def scm_instance(self):
-        import kallithea
-        full_cache = str2bool(kallithea.CONFIG.get('vcs_full_cache'))
-        if full_cache:
-            return self.scm_instance_cached()
-        return self.__get_instance()
+        if self._scm_instance is None:
+            self._scm_instance = self.scm_instance_cached()
+        return self._scm_instance
 
     def scm_instance_cached(self, valid_cache_keys=None):
-        @cache_region('long_term')
-        def _c(repo_name):
-            return self.__get_instance()
+        @cache_region('long_term', 'scm_instance_cached')
+        def _c(repo_name): # repo_name is just for the cache key
+            log.debug('Creating new %s scm_instance and populating cache', repo_name)
+            return self.scm_instance_no_cache()
         rn = self.repo_name
 
         valid = CacheInvalidation.test_and_set_valid(rn, None, valid_cache_keys=valid_cache_keys)
         if not valid:
             log.debug('Cache for %s invalidated, getting new object', rn)
-            region_invalidate(_c, None, rn)
+            region_invalidate(_c, None, 'scm_instance_cached', rn)
         else:
-            log.debug('Getting scm_instance of %s from cache', rn)
+            log.debug('Trying to get scm_instance of %s from cache', rn)
         return _c(rn)
 
-    def __get_instance(self):
-        repo_full_path = self.repo_full_path
-
-        alias = get_scm(safe_str(repo_full_path))[0]
+    def scm_instance_no_cache(self):
+        repo_full_path = safe_str(self.repo_full_path)
+        alias = get_scm(repo_full_path)[0]
         log.debug('Creating instance of %s repository from %s',
-                  alias, repo_full_path)
+                  alias, self.repo_full_path)
         backend = get_backend(alias)
 
         if alias == 'hg':
-            repo = backend(safe_str(repo_full_path), create=False,
+            repo = backend(repo_full_path, create=False,
                            baseui=self._ui)
         else:
             repo = backend(repo_full_path, create=False)
@@ -1474,30 +1499,41 @@
     def __json__(self):
         return dict(landing_rev = self.landing_rev)
 
-class RepoGroup(Base, BaseModel):
+class RepoGroup(Base, BaseDbModel):
     __tablename__ = 'groups'
     __table_args__ = (
-        UniqueConstraint('group_name', 'group_parent_id'),
-        CheckConstraint('group_id != group_parent_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
+        CheckConstraint('group_id != group_parent_id', name='ck_groups_no_self_parent'),
+        _table_args_default_dict,
     )
-    __mapper_args__ = {'order_by': 'group_name'}
+    __mapper_args__ = {'order_by': 'group_name'} # TODO: Deprecated as of SQLAlchemy 1.1.
 
     SEP = ' &raquo; '
 
-    group_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    group_name = Column(String(255, convert_unicode=False), nullable=False, unique=True, default=None)
-    group_parent_id = Column(Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
-    group_description = Column(String(10000, convert_unicode=False), nullable=True, unique=None, default=None)
-    enable_locking = Column(Boolean(), nullable=False, unique=None, default=False)
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
+    group_id = Column(Integer(), primary_key=True)
+    group_name = Column(Unicode(255), nullable=False, unique=True) # full path
+    parent_group_id = Column('group_parent_id', Integer(), ForeignKey('groups.group_id'), nullable=True)
+    group_description = Column(Unicode(10000), nullable=False)
+    enable_locking = Column(Boolean(), nullable=False, default=False)
+    owner_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
     created_on = Column(DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
 
     repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
     users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
     parent_group = relationship('RepoGroup', remote_side=group_id)
-    user = relationship('User')
+    owner = relationship('User')
+
+    @classmethod
+    def query(cls, sorted=False):
+        """Add RepoGroup-specific helpers for common query constructs.
+
+        sorted: if True, apply the default ordering (name, case insensitive).
+        """
+        q = super(RepoGroup, cls).query()
+
+        if sorted:
+            q = q.order_by(func.lower(RepoGroup.group_name))
+
+        return q
 
     def __init__(self, group_name='', parent_group=None):
         self.group_name = group_name
@@ -1527,11 +1563,12 @@
 
     @classmethod
     def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
+        group_name = group_name.rstrip('/')
         if case_insensitive:
-            gr = cls.query()\
-                .filter(cls.group_name.ilike(group_name))
+            gr = cls.query() \
+                .filter(func.lower(cls.group_name) == func.lower(group_name))
         else:
-            gr = cls.query()\
+            gr = cls.query() \
                 .filter(cls.group_name == group_name)
         if cache:
             gr = gr.options(FromCache(
@@ -1543,26 +1580,13 @@
 
     @property
     def parents(self):
-        parents_recursion_limit = 10
         groups = []
-        if self.parent_group is None:
-            return groups
-        cur_gr = self.parent_group
-        groups.insert(0, cur_gr)
-        cnt = 0
-        while 1:
-            cnt += 1
-            gr = getattr(cur_gr, 'parent_group', None)
-            cur_gr = cur_gr.parent_group
-            if gr is None:
-                break
-            if cnt == parents_recursion_limit:
-                # this will prevent accidental infinite loops
-                log.error(('more than %s parents found for group %s, stopping '
-                           'recursive parent fetching' % (parents_recursion_limit, self)))
-                break
-
-            groups.insert(0, gr)
+        group = self.parent_group
+        while group is not None:
+            groups.append(group)
+            group = group.parent_group
+            assert group not in groups, group # avoid recursion on bad db content
+        groups.reverse()
         return groups
 
     @property
@@ -1583,9 +1607,7 @@
 
     @property
     def repositories(self):
-        return Repository.query()\
-                .filter(Repository.group == self)\
-                .order_by(Repository.repo_name)
+        return Repository.query(sorted=True).filter_by(group=self)
 
     @property
     def repositories_recursive_count(self):
@@ -1650,18 +1672,18 @@
             group_description=group.group_description,
             parent_group=group.parent_group.group_name if group.parent_group else None,
             repositories=[x.repo_name for x in group.repositories],
-            owner=group.user.username
+            owner=group.owner.username
         )
         return data
 
 
-class Permission(Base, BaseModel):
+class Permission(Base, BaseDbModel):
     __tablename__ = 'permissions'
     __table_args__ = (
         Index('p_perm_name_idx', 'permission_name'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
+        _table_args_default_dict,
     )
+
     PERMS = [
         ('hg.admin', _('Kallithea Administrator')),
 
@@ -1747,9 +1769,8 @@
         'hg.create.repository': 1
     }
 
-    permission_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    permission_name = Column(String(255, convert_unicode=False), nullable=True, unique=None, default=None)
-    permission_longname = Column(String(255, convert_unicode=False), nullable=True, unique=None, default=None)
+    permission_id = Column(Integer(), primary_key=True)
+    permission_name = Column(String(255), nullable=False)
 
     def __unicode__(self):
         return u"<%s('%s:%s')>" % (
@@ -1762,43 +1783,43 @@
 
     @classmethod
     def get_default_perms(cls, default_user_id):
-        q = Session().query(UserRepoToPerm, Repository, cls)\
-         .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
-         .join((cls, UserRepoToPerm.permission_id == cls.permission_id))\
+        q = Session().query(UserRepoToPerm, Repository, cls) \
+         .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id)) \
+         .join((cls, UserRepoToPerm.permission_id == cls.permission_id)) \
          .filter(UserRepoToPerm.user_id == default_user_id)
 
         return q.all()
 
     @classmethod
     def get_default_group_perms(cls, default_user_id):
-        q = Session().query(UserRepoGroupToPerm, RepoGroup, cls)\
-         .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
-         .join((cls, UserRepoGroupToPerm.permission_id == cls.permission_id))\
+        q = Session().query(UserRepoGroupToPerm, RepoGroup, cls) \
+         .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id)) \
+         .join((cls, UserRepoGroupToPerm.permission_id == cls.permission_id)) \
          .filter(UserRepoGroupToPerm.user_id == default_user_id)
 
         return q.all()
 
     @classmethod
     def get_default_user_group_perms(cls, default_user_id):
-        q = Session().query(UserUserGroupToPerm, UserGroup, cls)\
-         .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
-         .join((cls, UserUserGroupToPerm.permission_id == cls.permission_id))\
+        q = Session().query(UserUserGroupToPerm, UserGroup, cls) \
+         .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id)) \
+         .join((cls, UserUserGroupToPerm.permission_id == cls.permission_id)) \
          .filter(UserUserGroupToPerm.user_id == default_user_id)
 
         return q.all()
 
 
-class UserRepoToPerm(Base, BaseModel):
+class UserRepoToPerm(Base, BaseDbModel):
     __tablename__ = 'repo_to_perm'
     __table_args__ = (
         UniqueConstraint('user_id', 'repository_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        _table_args_default_dict,
     )
-    repo_to_perm_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column(Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
+
+    repo_to_perm_id = Column(Integer(), primary_key=True)
+    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False)
+    permission_id = Column(Integer(), ForeignKey('permissions.permission_id'), nullable=False)
+    repository_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=False)
 
     user = relationship('User')
     repository = relationship('Repository')
@@ -1817,17 +1838,17 @@
         return u'<%s => %s >' % (self.user, self.repository)
 
 
-class UserUserGroupToPerm(Base, BaseModel):
+class UserUserGroupToPerm(Base, BaseDbModel):
     __tablename__ = 'user_user_group_to_perm'
     __table_args__ = (
         UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        _table_args_default_dict,
     )
-    user_user_group_to_perm_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column(Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column(Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
+
+    user_user_group_to_perm_id = Column(Integer(), primary_key=True)
+    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False)
+    permission_id = Column(Integer(), ForeignKey('permissions.permission_id'), nullable=False)
+    user_group_id = Column(Integer(), ForeignKey('users_groups.users_group_id'), nullable=False)
 
     user = relationship('User')
     user_group = relationship('UserGroup')
@@ -1846,16 +1867,16 @@
         return u'<%s => %s >' % (self.user, self.user_group)
 
 
-class UserToPerm(Base, BaseModel):
+class UserToPerm(Base, BaseDbModel):
     __tablename__ = 'user_to_perm'
     __table_args__ = (
         UniqueConstraint('user_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        _table_args_default_dict,
     )
-    user_to_perm_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    permission_id = Column(Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
+
+    user_to_perm_id = Column(Integer(), primary_key=True)
+    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False)
+    permission_id = Column(Integer(), ForeignKey('permissions.permission_id'), nullable=False)
 
     user = relationship('User')
     permission = relationship('Permission')
@@ -1864,17 +1885,17 @@
         return u'<%s => %s >' % (self.user, self.permission)
 
 
-class UserGroupRepoToPerm(Base, BaseModel):
+class UserGroupRepoToPerm(Base, BaseDbModel):
     __tablename__ = 'users_group_repo_to_perm'
     __table_args__ = (
         UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        _table_args_default_dict,
     )
-    users_group_to_perm_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    users_group_id = Column(Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column(Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    repository_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
+
+    users_group_to_perm_id = Column(Integer(), primary_key=True)
+    users_group_id = Column(Integer(), ForeignKey('users_groups.users_group_id'), nullable=False)
+    permission_id = Column(Integer(), ForeignKey('permissions.permission_id'), nullable=False)
+    repository_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=False)
 
     users_group = relationship('UserGroup')
     permission = relationship('Permission')
@@ -1893,18 +1914,18 @@
         return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
 
 
-class UserGroupUserGroupToPerm(Base, BaseModel):
+class UserGroupUserGroupToPerm(Base, BaseDbModel):
     __tablename__ = 'user_group_user_group_to_perm'
     __table_args__ = (
         UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
-        CheckConstraint('target_user_group_id != user_group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        CheckConstraint('target_user_group_id != user_group_id', name='ck_user_group_user_group_to_perm_no_self_target'),
+        _table_args_default_dict,
     )
-    user_group_user_group_to_perm_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    target_user_group_id = Column(Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column(Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
-    user_group_id = Column(Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
+
+    user_group_user_group_to_perm_id = Column(Integer(), primary_key=True)
+    target_user_group_id = Column(Integer(), ForeignKey('users_groups.users_group_id'), nullable=False)
+    permission_id = Column(Integer(), ForeignKey('permissions.permission_id'), nullable=False)
+    user_group_id = Column(Integer(), ForeignKey('users_groups.users_group_id'), nullable=False)
 
     target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
     user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
@@ -1923,33 +1944,32 @@
         return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
 
 
-class UserGroupToPerm(Base, BaseModel):
+class UserGroupToPerm(Base, BaseDbModel):
     __tablename__ = 'users_group_to_perm'
     __table_args__ = (
         UniqueConstraint('users_group_id', 'permission_id',),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        _table_args_default_dict,
     )
-    users_group_to_perm_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    users_group_id = Column(Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column(Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
+
+    users_group_to_perm_id = Column(Integer(), primary_key=True)
+    users_group_id = Column(Integer(), ForeignKey('users_groups.users_group_id'), nullable=False)
+    permission_id = Column(Integer(), ForeignKey('permissions.permission_id'), nullable=False)
 
     users_group = relationship('UserGroup')
     permission = relationship('Permission')
 
 
-class UserRepoGroupToPerm(Base, BaseModel):
+class UserRepoGroupToPerm(Base, BaseDbModel):
     __tablename__ = 'user_repo_group_to_perm'
     __table_args__ = (
         UniqueConstraint('user_id', 'group_id', 'permission_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        _table_args_default_dict,
     )
 
-    group_to_perm_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    group_id = Column(Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column(Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
+    group_to_perm_id = Column(Integer(), primary_key=True)
+    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False)
+    group_id = Column(Integer(), ForeignKey('groups.group_id'), nullable=False)
+    permission_id = Column(Integer(), ForeignKey('permissions.permission_id'), nullable=False)
 
     user = relationship('User')
     group = relationship('RepoGroup')
@@ -1965,18 +1985,17 @@
         return n
 
 
-class UserGroupRepoGroupToPerm(Base, BaseModel):
+class UserGroupRepoGroupToPerm(Base, BaseDbModel):
     __tablename__ = 'users_group_repo_group_to_perm'
     __table_args__ = (
         UniqueConstraint('users_group_id', 'group_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        _table_args_default_dict,
     )
 
-    users_group_repo_group_to_perm_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    users_group_id = Column(Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
-    group_id = Column(Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
-    permission_id = Column(Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
+    users_group_repo_group_to_perm_id = Column(Integer(), primary_key=True)
+    users_group_id = Column(Integer(), ForeignKey('users_groups.users_group_id'), nullable=False)
+    group_id = Column(Integer(), ForeignKey('groups.group_id'), nullable=False)
+    permission_id = Column(Integer(), ForeignKey('permissions.permission_id'), nullable=False)
 
     users_group = relationship('UserGroup')
     permission = relationship('Permission')
@@ -1992,15 +2011,14 @@
         return n
 
 
-class Statistics(Base, BaseModel):
+class Statistics(Base, BaseDbModel):
     __tablename__ = 'statistics'
     __table_args__ = (
-         UniqueConstraint('repository_id'),
-         {'extend_existing': True, 'mysql_engine': 'InnoDB',
-          'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+         _table_args_default_dict,
     )
-    stat_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    repository_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
+
+    stat_id = Column(Integer(), primary_key=True)
+    repository_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True)
     stat_on_revision = Column(Integer(), nullable=False)
     commit_activity = Column(LargeBinary(1000000), nullable=False)#JSON data
     commit_activity_combined = Column(LargeBinary(), nullable=False)#JSON data
@@ -2009,48 +2027,46 @@
     repository = relationship('Repository', single_parent=True)
 
 
-class UserFollowing(Base, BaseModel):
+class UserFollowing(Base, BaseDbModel):
     __tablename__ = 'user_followings'
     __table_args__ = (
-        UniqueConstraint('user_id', 'follows_repository_id'),
-        UniqueConstraint('user_id', 'follows_user_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        UniqueConstraint('user_id', 'follows_repository_id', name='uq_user_followings_user_repo'),
+        UniqueConstraint('user_id', 'follows_user_id', name='uq_user_followings_user_user'),
+        _table_args_default_dict,
     )
 
-    user_following_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
-    follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
-    follows_user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
-    follows_from = Column(DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
+    user_following_id = Column(Integer(), primary_key=True)
+    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False)
+    follows_repository_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=True)
+    follows_user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=True)
+    follows_from = Column(DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
 
     user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
 
     follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
-    follows_repository = relationship('Repository', order_by='Repository.repo_name')
+    follows_repository = relationship('Repository', order_by=lambda: func.lower(Repository.repo_name))
 
     @classmethod
     def get_repo_followers(cls, repo_id):
-        return cls.query().filter(cls.follows_repo_id == repo_id)
-
-
-class CacheInvalidation(Base, BaseModel):
+        return cls.query().filter(cls.follows_repository_id == repo_id)
+
+
+class CacheInvalidation(Base, BaseDbModel):
     __tablename__ = 'cache_invalidation'
     __table_args__ = (
-        UniqueConstraint('cache_key'),
         Index('key_idx', 'cache_key'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
+        _table_args_default_dict,
     )
+
     # cache_id, not used
-    cache_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
+    cache_id = Column(Integer(), primary_key=True)
     # cache_key as created by _get_cache_key
-    cache_key = Column(String(255, convert_unicode=False))
+    cache_key = Column(Unicode(255), nullable=False, unique=True)
     # cache_args is a repo_name
-    cache_args = Column(String(255, convert_unicode=False))
+    cache_args = Column(Unicode(255), nullable=False)
     # instance sets cache_active True when it is caching, other instances set
     # cache_active to False to indicate that this cache is invalid
-    cache_active = Column(Boolean(), nullable=True, unique=None, default=False)
+    cache_active = Column(Boolean(), nullable=False, default=False)
 
     def __init__(self, cache_key, repo_name=''):
         self.cache_key = cache_key
@@ -2104,7 +2120,7 @@
         return "%s%s" % (prefix, key)
 
     @classmethod
-    def set_invalidate(cls, repo_name, delete=False):
+    def set_invalidate(cls, repo_name):
         """
         Mark all caches of a repo as invalid in the database.
         """
@@ -2115,11 +2131,7 @@
         for inv_obj in inv_objs:
             log.debug('marking %s key for invalidation based on repo_name=%s',
                       inv_obj, safe_str(repo_name))
-            if delete:
-                Session().delete(inv_obj)
-            else:
-                inv_obj.cache_active = False
-                Session().add(inv_obj)
+            Session().delete(inv_obj)
         Session().commit()
 
     @classmethod
@@ -2138,11 +2150,11 @@
 
         inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
         if inv_obj is None:
-            inv_obj = CacheInvalidation(cache_key, repo_name)
+            inv_obj = cls(cache_key, repo_name)
+            Session().add(inv_obj)
         elif inv_obj.cache_active:
             return True
         inv_obj.cache_active = True
-        Session().add(inv_obj)
         try:
             Session().commit()
         except sqlalchemy.exc.IntegrityError:
@@ -2164,22 +2176,22 @@
         return set(inv_obj.cache_key for inv_obj in cls.query().filter(cls.cache_active).all())
 
 
-class ChangesetComment(Base, BaseModel):
+class ChangesetComment(Base, BaseDbModel):
     __tablename__ = 'changeset_comments'
     __table_args__ = (
         Index('cc_revision_idx', 'revision'),
         Index('cc_pull_request_id_idx', 'pull_request_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
+        _table_args_default_dict,
     )
-    comment_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
+
+    comment_id = Column(Integer(), primary_key=True)
     repo_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    revision = Column(String(40))
-    pull_request_id = Column(Integer(), ForeignKey('pull_requests.pull_request_id'))
-    line_no = Column(Unicode(10))
-    f_path = Column(Unicode(1000))
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False)
-    text = Column(UnicodeText(25000), nullable=False)
+    revision = Column(String(40), nullable=True)
+    pull_request_id = Column(Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
+    line_no = Column(Unicode(10), nullable=True)
+    f_path = Column(Unicode(1000), nullable=True)
+    author_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
+    text = Column(UnicodeText(), nullable=False)
     created_on = Column(DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
     modified_at = Column(DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
 
@@ -2201,7 +2213,7 @@
         :param cls:
         :param revision:
         """
-        q = Session().query(User)\
+        q = Session().query(User) \
                 .join(ChangesetComment.author)
         if revision is not None:
             q = q.filter(cls.revision == revision)
@@ -2217,7 +2229,11 @@
         elif self.pull_request_id is not None:
             return self.pull_request.url(anchor=anchor)
 
-class ChangesetStatus(Base, BaseModel):
+    def deletable(self):
+        return self.created_on > datetime.datetime.now() - datetime.timedelta(minutes=5)
+
+
+class ChangesetStatus(Base, BaseDbModel):
     __tablename__ = 'changeset_statuses'
     __table_args__ = (
         Index('cs_revision_idx', 'revision'),
@@ -2225,28 +2241,30 @@
         Index('cs_pull_request_id_idx', 'pull_request_id'),
         Index('cs_changeset_comment_id_idx', 'changeset_comment_id'),
         Index('cs_pull_request_id_user_id_version_idx', 'pull_request_id', 'user_id', 'version'),
+        Index('cs_repo_id_pull_request_id_idx', 'repo_id', 'pull_request_id'),
         UniqueConstraint('repo_id', 'revision', 'version'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        _table_args_default_dict,
     )
+
     STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
     STATUS_APPROVED = 'approved'
-    STATUS_REJECTED = 'rejected'
+    STATUS_REJECTED = 'rejected' # is shown as "Not approved" - TODO: change database content / scheme
     STATUS_UNDER_REVIEW = 'under_review'
 
     STATUSES = [
         (STATUS_NOT_REVIEWED, _("Not reviewed")),  # (no icon) and default
+        (STATUS_UNDER_REVIEW, _("Under review")),
+        (STATUS_REJECTED, _("Not approved")),
         (STATUS_APPROVED, _("Approved")),
-        (STATUS_REJECTED, _("Rejected")),
-        (STATUS_UNDER_REVIEW, _("Under review")),
     ]
-
-    changeset_status_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
+    STATUSES_DICT = dict(STATUSES)
+
+    changeset_status_id = Column(Integer(), primary_key=True)
     repo_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=False)
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    revision = Column(String(40), nullable=False)
+    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False)
+    revision = Column(String(40), nullable=True)
     status = Column(String(128), nullable=False, default=DEFAULT)
-    changeset_comment_id = Column(Integer(), ForeignKey('changeset_comments.comment_id'), nullable=False)
+    comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=False)
     modified_at = Column(DateTime(), nullable=False, default=datetime.datetime.now)
     version = Column(Integer(), nullable=False, default=0)
     pull_request_id = Column(Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
@@ -2264,34 +2282,33 @@
 
     @classmethod
     def get_status_lbl(cls, value):
-        return dict(cls.STATUSES).get(value)
+        return cls.STATUSES_DICT.get(value)
 
     @property
     def status_lbl(self):
         return ChangesetStatus.get_status_lbl(self.status)
 
 
-class PullRequest(Base, BaseModel):
+class PullRequest(Base, BaseDbModel):
     __tablename__ = 'pull_requests'
     __table_args__ = (
         Index('pr_org_repo_id_idx', 'org_repo_id'),
         Index('pr_other_repo_id_idx', 'other_repo_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
+        _table_args_default_dict,
     )
 
     # values for .status
     STATUS_NEW = u'new'
     STATUS_CLOSED = u'closed'
 
-    pull_request_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    title = Column(Unicode(255), nullable=True)
-    description = Column(UnicodeText(10240))
+    pull_request_id = Column(Integer(), primary_key=True)
+    title = Column(Unicode(255), nullable=False)
+    description = Column(UnicodeText(), nullable=False)
     status = Column(Unicode(255), nullable=False, default=STATUS_NEW) # only for closedness, not approve/reject/etc
     created_on = Column(DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
     updated_on = Column(DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
-    _revisions = Column('revisions', UnicodeText(20500))  # 500 revisions max
+    owner_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
+    _revisions = Column('revisions', UnicodeText(), nullable=False)
     org_repo_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=False)
     org_ref = Column(Unicode(255), nullable=False)
     other_repo_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=False)
@@ -2314,24 +2331,55 @@
         return self.other_ref.split(':')
 
     owner = relationship('User')
-    reviewers = relationship('PullRequestReviewers',
+    reviewers = relationship('PullRequestReviewer',
                              cascade="all, delete-orphan")
     org_repo = relationship('Repository', primaryjoin='PullRequest.org_repo_id==Repository.repo_id')
     other_repo = relationship('Repository', primaryjoin='PullRequest.other_repo_id==Repository.repo_id')
-    statuses = relationship('ChangesetStatus')
-    comments = relationship('ChangesetComment',
+    statuses = relationship('ChangesetStatus', order_by='ChangesetStatus.changeset_status_id')
+    comments = relationship('ChangesetComment', order_by='ChangesetComment.comment_id',
                              cascade="all, delete-orphan")
 
+    @classmethod
+    def query(cls, reviewer_id=None, include_closed=True, sorted=False):
+        """Add PullRequest-specific helpers for common query constructs.
+
+        reviewer_id: only PRs with the specified user added as reviewer.
+
+        include_closed: if False, do not include closed PRs.
+
+        sorted: if True, apply the default ordering (newest first).
+        """
+        q = super(PullRequest, cls).query()
+
+        if reviewer_id is not None:
+            q = q.join(PullRequestReviewer).filter(PullRequestReviewer.user_id == reviewer_id)
+
+        if not include_closed:
+            q = q.filter(PullRequest.status != PullRequest.STATUS_CLOSED)
+
+        if sorted:
+            q = q.order_by(PullRequest.created_on.desc())
+
+        return q
+
+    def get_reviewer_users(self):
+        """Like .reviewers, but actually returning the users"""
+        return User.query() \
+            .join(PullRequestReviewer) \
+            .filter(PullRequestReviewer.pull_request == self) \
+            .order_by(PullRequestReviewer.pull_request_reviewers_id) \
+            .all()
+
     def is_closed(self):
         return self.status == self.STATUS_CLOSED
 
     def user_review_status(self, user_id):
         """Return the user's latest status votes on PR"""
         # note: no filtering on repo - that would be redundant
-        status = ChangesetStatus.query()\
-            .filter(ChangesetStatus.pull_request == self)\
-            .filter(ChangesetStatus.user_id == user_id)\
-            .order_by(ChangesetStatus.version)\
+        status = ChangesetStatus.query() \
+            .filter(ChangesetStatus.pull_request == self) \
+            .filter(ChangesetStatus.user_id == user_id) \
+            .order_by(ChangesetStatus.version) \
             .first()
         return str(status.status) if status else ''
 
@@ -2364,46 +2412,45 @@
         return h.url('pullrequest_show', repo_name=self.other_repo.repo_name,
                      pull_request_id=self.pull_request_id, **kwargs)
 
-class PullRequestReviewers(Base, BaseModel):
+class PullRequestReviewer(Base, BaseDbModel):
     __tablename__ = 'pull_request_reviewers'
     __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
+        Index('pull_request_reviewers_user_id_idx', 'user_id'),
+        _table_args_default_dict,
     )
 
     def __init__(self, user=None, pull_request=None):
         self.user = user
         self.pull_request = pull_request
 
-    pull_requests_reviewers_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
+    pull_request_reviewers_id = Column('pull_requests_reviewers_id', Integer(), primary_key=True)
     pull_request_id = Column(Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
-    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=True)
+    user_id = Column(Integer(), ForeignKey('users.user_id'), nullable=False)
 
     user = relationship('User')
     pull_request = relationship('PullRequest')
 
 
-class Notification(Base, BaseModel):
+class Notification(Base, BaseDbModel):
     __tablename__ = 'notifications'
     __table_args__ = (
         Index('notification_type_idx', 'type'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
+        _table_args_default_dict,
     )
 
     TYPE_CHANGESET_COMMENT = u'cs_comment'
     TYPE_MESSAGE = u'message'
-    TYPE_MENTION = u'mention'
+    TYPE_MENTION = u'mention' # not used
     TYPE_REGISTRATION = u'registration'
     TYPE_PULL_REQUEST = u'pull_request'
     TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
 
-    notification_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    subject = Column(Unicode(512), nullable=True)
-    body = Column(UnicodeText(50000), nullable=True)
-    created_by = Column(Integer(), ForeignKey('users.user_id'), nullable=True)
+    notification_id = Column(Integer(), primary_key=True)
+    subject = Column(Unicode(512), nullable=False)
+    body = Column(UnicodeText(), nullable=False)
+    created_by = Column(Integer(), ForeignKey('users.user_id'), nullable=False)
     created_on = Column(DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
-    type_ = Column('type', Unicode(255))
+    type_ = Column('type', Unicode(255), nullable=False)
 
     created_by_user = relationship('User')
     notifications_to_users = relationship('UserNotification', cascade="all, delete-orphan")
@@ -2426,13 +2473,17 @@
         notification.type_ = type_
         notification.created_on = datetime.datetime.now()
 
-        for u in recipients:
-            assoc = UserNotification()
-            assoc.notification = notification
-            assoc.user_id = u.user_id
-            Session().add(assoc)
+        for recipient in recipients:
+            un = UserNotification()
+            un.notification = notification
+            un.user_id = recipient.user_id
+            # Mark notifications to self "pre-read" - should perhaps just be skipped
+            if recipient == created_by:
+                un.read = True
+            Session().add(un)
+
         Session().add(notification)
-        Session().flush() # assign notificaiton.notification_id
+        Session().flush() # assign notification.notification_id
         return notification
 
     @property
@@ -2441,42 +2492,41 @@
         return NotificationModel().make_description(self)
 
 
-class UserNotification(Base, BaseModel):
+class UserNotification(Base, BaseDbModel):
     __tablename__ = 'user_to_notification'
     __table_args__ = (
         UniqueConstraint('user_id', 'notification_id'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        _table_args_default_dict,
     )
+
     user_id = Column(Integer(), ForeignKey('users.user_id'), primary_key=True)
     notification_id = Column(Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
-    read = Column(Boolean, default=False)
-    sent_on = Column(DateTime(timezone=False), nullable=True, unique=None)
+    read = Column(Boolean, nullable=False, default=False)
+    sent_on = Column(DateTime(timezone=False), nullable=True) # FIXME: not nullable?
 
     user = relationship('User')
     notification = relationship('Notification')
 
     def mark_as_read(self):
         self.read = True
-        Session().add(self)
-
-
-class Gist(Base, BaseModel):
+
+
+class Gist(Base, BaseDbModel):
     __tablename__ = 'gists'
     __table_args__ = (
         Index('g_gist_access_id_idx', 'gist_access_id'),
         Index('g_created_on_idx', 'created_on'),
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
+        _table_args_default_dict,
     )
+
     GIST_PUBLIC = u'public'
     GIST_PRIVATE = u'private'
     DEFAULT_FILENAME = u'gistfile1.txt'
 
-    gist_id = Column(Integer(), nullable=False, unique=True, primary_key=True)
-    gist_access_id = Column(Unicode(250))
-    gist_description = Column(UnicodeText(1024))
-    gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
+    gist_id = Column(Integer(), primary_key=True)
+    gist_access_id = Column(Unicode(250), nullable=False)
+    gist_description = Column(UnicodeText(), nullable=False)
+    owner_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
     gist_expires = Column(Float(53), nullable=False)
     gist_type = Column(Unicode(128), nullable=False)
     created_on = Column(DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
@@ -2515,7 +2565,7 @@
         :param cls:
         """
         from kallithea.model.gist import GIST_STORE_LOC
-        q = Session().query(Ui)\
+        q = Session().query(Ui) \
             .filter(Ui.ui_key == URL_SEP)
         q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
         return os.path.join(q.one().ui_value, GIST_STORE_LOC)
@@ -2549,14 +2599,3 @@
         base_path = self.base_path()
         return get_repo(os.path.join(*map(safe_str,
                                           [base_path, self.gist_access_id])))
-
-
-class DbMigrateVersion(Base, BaseModel):
-    __tablename__ = 'db_migrate_version'
-    __table_args__ = (
-        {'extend_existing': True, 'mysql_engine': 'InnoDB',
-         'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
-    )
-    repository_id = Column(String(250), nullable=False, unique=True, primary_key=True)
-    repository_path = Column(Text)
-    version = Column(Integer)
--- a/kallithea/model/forms.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/forms.py	Fri Nov 18 01:11:13 2016 +0100
@@ -86,7 +86,8 @@
     return _PasswordChangeForm
 
 
-def UserForm(edit=False, old_data={}):
+def UserForm(edit=False, old_data=None):
+    old_data = old_data or {}
     class _UserForm(formencode.Schema):
         allow_extra_fields = True
         filter_extra_fields = True
@@ -125,7 +126,9 @@
     return _UserForm
 
 
-def UserGroupForm(edit=False, old_data={}, available_members=[]):
+def UserGroupForm(edit=False, old_data=None, available_members=None):
+    old_data = old_data or {}
+    available_members = available_members or []
     class _UserGroupForm(formencode.Schema):
         allow_extra_fields = True
         filter_extra_fields = True
@@ -148,8 +151,10 @@
     return _UserGroupForm
 
 
-def RepoGroupForm(edit=False, old_data={}, repo_groups=[],
+def RepoGroupForm(edit=False, old_data=None, repo_groups=None,
                    can_create_in_root=False):
+    old_data = old_data or {}
+    repo_groups = repo_groups or []
     repo_group_ids = [rg[0] for rg in repo_groups]
     class _RepoGroupForm(formencode.Schema):
         allow_extra_fields = True
@@ -167,7 +172,7 @@
             #its children
             pass
 
-        group_parent_id = All(v.CanCreateGroup(can_create_in_root),
+        parent_group_id = All(v.CanCreateGroup(can_create_in_root),
                               v.OneOf(repo_group_ids, hideList=False,
                                       testValueList=True,
                                       if_missing=None, not_empty=True),
@@ -178,7 +183,7 @@
     return _RepoGroupForm
 
 
-def RegisterForm(edit=False, old_data={}):
+def RegisterForm(edit=False, old_data=None):
     class _RegisterForm(formencode.Schema):
         allow_extra_fields = True
         filter_extra_fields = True
@@ -227,8 +232,11 @@
                                                     'password_confirm')]
     return _PasswordResetConfirmationForm
 
-def RepoForm(edit=False, old_data={}, supported_backends=BACKENDS.keys(),
-             repo_groups=[], landing_revs=[]):
+def RepoForm(edit=False, old_data=None, supported_backends=BACKENDS.keys(),
+             repo_groups=None, landing_revs=None):
+    old_data = old_data or {}
+    repo_groups = repo_groups or []
+    landing_revs = landing_revs or []
     repo_group_ids = [rg[0] for rg in repo_groups]
     class _RepoForm(formencode.Schema):
         allow_extra_fields = True
@@ -251,8 +259,7 @@
         repo_enable_locking = v.StringBoolean(if_missing=False)
 
         if edit:
-            #this is repo owner
-            user = All(v.UnicodeString(not_empty=True), v.ValidRepoUser())
+            owner = All(v.UnicodeString(not_empty=True), v.ValidRepoUser())
             # Not a real field - just for reference for validation:
             # clone_uri_hidden = v.UnicodeString(if_missing='')
 
@@ -302,8 +309,11 @@
     return _RepoFieldForm
 
 
-def RepoForkForm(edit=False, old_data={}, supported_backends=BACKENDS.keys(),
-                 repo_groups=[], landing_revs=[]):
+def RepoForkForm(edit=False, old_data=None, supported_backends=BACKENDS.keys(),
+                 repo_groups=None, landing_revs=None):
+    old_data = old_data or {}
+    repo_groups = repo_groups or []
+    landing_revs = landing_revs or []
     repo_group_ids = [rg[0] for rg in repo_groups]
     class _RepoForkForm(formencode.Schema):
         allow_extra_fields = True
@@ -348,7 +358,7 @@
 
         repository_fields = v.StringBoolean(if_missing=False)
         lightweight_journal = v.StringBoolean(if_missing=False)
-        dashboard_items = v.Int(min=5, not_empty=True)
+        page_size = v.Int(min=5, not_empty=True)
         admin_grid_items = v.Int(min=5, not_empty=True)
         show_version = v.StringBoolean(if_missing=False)
         use_gravatar = v.StringBoolean(if_missing=False)
@@ -362,7 +372,6 @@
     class _ApplicationUiSettingsForm(formencode.Schema):
         allow_extra_fields = True
         filter_extra_fields = False
-        web_push_ssl = v.StringBoolean(if_missing=False)
         paths_root_path = All(
             v.ValidPath(),
             v.UnicodeString(strip=True, min=1, not_empty=True)
@@ -421,7 +430,7 @@
     return _CustomDefaultPermissionsForm
 
 
-def DefaultsForm(edit=False, old_data={}, supported_backends=BACKENDS.keys()):
+def DefaultsForm(edit=False, old_data=None, supported_backends=BACKENDS.keys()):
     class _DefaultsForm(formencode.Schema):
         allow_extra_fields = True
         filter_extra_fields = True
@@ -515,7 +524,6 @@
         org_ref = v.UnicodeString(strip=True, required=True)
         other_repo = v.UnicodeString(strip=True, required=True)
         other_ref = v.UnicodeString(strip=True, required=True)
-        review_members = v.Set()
 
         pullrequest_title = v.UnicodeString(strip=True, required=True)
         pullrequest_desc = v.UnicodeString(strip=True, required=False)
@@ -530,6 +538,7 @@
 
         pullrequest_title = v.UnicodeString(strip=True, required=True)
         pullrequest_desc = v.UnicodeString(strip=True, required=False)
+        org_review_members = v.Set()
         review_members = v.Set()
         updaterev = v.UnicodeString(strip=True, required=False, if_missing=None)
         owner = All(v.UnicodeString(strip=True, required=True),
--- a/kallithea/model/gist.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/gist.py	Fri Nov 18 01:11:13 2016 +0100
@@ -34,7 +34,7 @@
 from kallithea.lib.utils2 import safe_unicode, unique_id, safe_int, \
     time_to_datetime, AttributeDict
 from kallithea.lib.compat import json
-from kallithea.model import BaseModel
+from kallithea.model.base import BaseModel
 from kallithea.model.db import Gist
 from kallithea.model.repo import RepoModel
 from kallithea.model.scm import ScmModel
@@ -46,7 +46,6 @@
 
 
 class GistModel(BaseModel):
-    cls = Gist
 
     def _get_gist(self, gist):
         """
@@ -54,7 +53,7 @@
 
         :param gist: GistID, gist_access_id, or Gist instance
         """
-        return self._get_instance(Gist, gist, callback=Gist.get_by_access_id)
+        return Gist.guess_instance(gist, callback=Gist.get_by_access_id)
 
     def __delete_gist(self, gist):
         """
@@ -119,11 +118,11 @@
         gist = Gist()
         gist.gist_description = description
         gist.gist_access_id = gist_id
-        gist.gist_owner = owner.user_id
+        gist.owner_id = owner.user_id
         gist.gist_expires = gist_expires
         gist.gist_type = safe_unicode(gist_type)
         self.sa.add(gist)
-        self.sa.flush()
+        self.sa.flush() # make database assign gist.gist_id
         if gist_type == Gist.GIST_PUBLIC:
             # use DB ID for easy to use GIST ID
             gist_id = safe_unicode(gist.gist_id)
@@ -212,8 +211,6 @@
         gist.gist_expires = gist_expires
         gist.owner = owner
         gist.gist_type = gist_type
-        self.sa.add(gist)
-        self.sa.flush()
 
         message = 'updated file'
         message += 's: ' if len(gist_mapping) > 1 else ': '
--- a/kallithea/model/meta.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/meta.py	Fri Nov 18 01:11:13 2016 +0100
@@ -40,3 +40,18 @@
 
 #to use cache use this in query
 #.options(FromCache("sqlalchemy_cache_type", "cachekey"))
+
+
+# Define naming conventions for foreign keys, primary keys, indexes,
+# check constraints, and unique constraints, respectively.
+Base.metadata.naming_convention = {
+    'fk': 'fk_%(table_name)s_%(column_0_name)s',
+    'pk': 'pk_%(table_name)s',
+    'ix': 'ix_%(column_0_label)s',
+    'ck': 'ck_%(table_name)s_%(column_0_name)s',
+    'uq': 'uq_%(table_name)s_%(column_0_name)s',
+}
+# For custom CheckConstraints (not those autogenerated e.g. for Boolean
+# types), a name should be given explicitly, since "column_0" is here a
+# rather vague notion. A custom name is also necesarry if the generated
+# name is very long, since MySQL limits identifiers to 64 characters.
--- a/kallithea/model/notification.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/notification.py	Fri Nov 18 01:11:13 2016 +0100
@@ -36,7 +36,7 @@
 import kallithea
 from kallithea.lib import helpers as h
 from kallithea.lib.utils2 import safe_unicode
-from kallithea.model import BaseModel
+from kallithea.model.base import BaseModel
 from kallithea.model.db import Notification, User, UserNotification
 from kallithea.model.meta import Session
 
@@ -45,21 +45,9 @@
 
 class NotificationModel(BaseModel):
 
-    cls = Notification
-
-    def __get_notification(self, notification):
-        if isinstance(notification, Notification):
-            return notification
-        elif isinstance(notification, (int, long)):
-            return Notification.get(notification)
-        else:
-            if notification is not None:
-                raise Exception('notification must be int, long or Instance'
-                                ' of Notification got %s' % type(notification))
-
     def create(self, created_by, subject, body, recipients=None,
                type_=Notification.TYPE_MESSAGE, with_email=True,
-               email_kwargs={}):
+               email_kwargs=None, repo_name=None):
         """
 
         Creates notification of given type
@@ -74,8 +62,8 @@
         :param with_email: send email with this notification
         :param email_kwargs: additional dict to pass as args to email template
         """
-        from kallithea.lib.celerylib import tasks, run_task
-
+        from kallithea.lib.celerylib import tasks
+        email_kwargs = email_kwargs or {}
         if recipients and not getattr(recipients, '__iter__', False):
             raise Exception('recipients must be a list or iterable')
 
@@ -114,16 +102,17 @@
         #don't send email to person who created this comment
         rec_objs = set(recipients_objs).difference(set([created_by_obj]))
 
-        headers = None
+        headers = {}
+        headers['X-Kallithea-Notification-Type'] = type_
         if 'threading' in email_kwargs:
-            headers = {'References': ' '.join('<%s>' % x for x in email_kwargs['threading'])}
+            headers['References'] = ' '.join('<%s>' % x for x in email_kwargs['threading'])
 
         # send email with notification to all other participants
         for rec in rec_objs:
             ## this is passed into template
             html_kwargs = {
                       'subject': subject,
-                      'body': h.rst_w_mentions(body),
+                      'body': h.render_w_mentions(body, repo_name),
                       'when': h.fmt_date(notif.created_on),
                       'user': notif.created_by_user.username,
                       }
@@ -137,14 +126,14 @@
 
             html_kwargs.update(email_kwargs)
             txt_kwargs.update(email_kwargs)
-            email_subject = EmailNotificationModel()\
+            email_subject = EmailNotificationModel() \
                                 .get_email_description(type_, **txt_kwargs)
-            email_txt_body = EmailNotificationModel()\
+            email_txt_body = EmailNotificationModel() \
                                 .get_email_tmpl(type_, 'txt', **txt_kwargs)
-            email_html_body = EmailNotificationModel()\
+            email_html_body = EmailNotificationModel() \
                                 .get_email_tmpl(type_, 'html', **html_kwargs)
 
-            run_task(tasks.send_email, [rec.email], email_subject, email_txt_body,
+            tasks.send_email([rec.email], email_subject, email_txt_body,
                      email_html_body, headers, author=created_by_obj)
 
         return notif
@@ -152,13 +141,13 @@
     def delete(self, user, notification):
         # we don't want to remove actual notification just the assignment
         try:
-            notification = self.__get_notification(notification)
+            notification = Notification.guess_instance(notification)
             user = self._get_user(user)
             if notification and user:
-                obj = UserNotification.query()\
-                        .filter(UserNotification.user == user)\
+                obj = UserNotification.query() \
+                        .filter(UserNotification.user == user) \
                         .filter(UserNotification.notification
-                                == notification)\
+                                == notification) \
                         .one()
                 Session().delete(obj)
                 return True
@@ -166,7 +155,7 @@
             log.error(traceback.format_exc())
             raise
 
-    def get_for_user(self, user, filter_=None):
+    def query_for_user(self, user, filter_=None):
         """
         Get notifications for given user, filter them if filter dict is given
 
@@ -175,31 +164,30 @@
         """
         user = self._get_user(user)
 
-        q = UserNotification.query()\
-            .filter(UserNotification.user == user)\
+        q = UserNotification.query() \
+            .filter(UserNotification.user == user) \
             .join((Notification, UserNotification.notification_id ==
-                                 Notification.notification_id))\
-            .options(joinedload('notification'))\
-            .options(subqueryload('notification.created_by_user'))\
+                                 Notification.notification_id)) \
+            .options(joinedload('notification')) \
+            .options(subqueryload('notification.created_by_user')) \
             .order_by(Notification.created_on.desc())
 
         if filter_:
             q = q.filter(Notification.type_.in_(filter_))
 
-        return q.all()
+        return q
 
     def mark_read(self, user, notification):
         try:
-            notification = self.__get_notification(notification)
+            notification = Notification.guess_instance(notification)
             user = self._get_user(user)
             if notification and user:
-                obj = UserNotification.query()\
-                        .filter(UserNotification.user == user)\
+                obj = UserNotification.query() \
+                        .filter(UserNotification.user == user) \
                         .filter(UserNotification.notification
-                                == notification)\
+                                == notification) \
                         .one()
                 obj.read = True
-                Session().add(obj)
                 return True
         except Exception:
             log.error(traceback.format_exc())
@@ -207,9 +195,9 @@
 
     def mark_all_read_for_user(self, user, filter_=None):
         user = self._get_user(user)
-        q = UserNotification.query()\
-            .filter(UserNotification.user == user)\
-            .filter(UserNotification.read == False)\
+        q = UserNotification.query() \
+            .filter(UserNotification.user == user) \
+            .filter(UserNotification.read == False) \
             .join((Notification, UserNotification.notification_id ==
                                  Notification.notification_id))
         if filter_:
@@ -217,28 +205,27 @@
 
         # this is a little inefficient but sqlalchemy doesn't support
         # update on joined tables :(
-        for obj in q.all():
+        for obj in q:
             obj.read = True
-            Session().add(obj)
 
     def get_unread_cnt_for_user(self, user):
         user = self._get_user(user)
-        return UserNotification.query()\
-                .filter(UserNotification.read == False)\
+        return UserNotification.query() \
+                .filter(UserNotification.read == False) \
                 .filter(UserNotification.user == user).count()
 
     def get_unread_for_user(self, user):
         user = self._get_user(user)
-        return [x.notification for x in UserNotification.query()\
-                .filter(UserNotification.read == False)\
+        return [x.notification for x in UserNotification.query() \
+                .filter(UserNotification.read == False) \
                 .filter(UserNotification.user == user).all()]
 
     def get_user_notification(self, user, notification):
         user = self._get_user(user)
-        notification = self.__get_notification(notification)
+        notification = Notification.guess_instance(notification)
 
-        return UserNotification.query()\
-            .filter(UserNotification.notification == notification)\
+        return UserNotification.query() \
+            .filter(UserNotification.notification == notification) \
             .filter(UserNotification.user == user).scalar()
 
     def make_description(self, notification, show_age=True):
@@ -299,13 +286,13 @@
             self.TYPE_PULL_REQUEST_COMMENT: 'pull_request_comment',
         }
         self._subj_map = {
-            self.TYPE_CHANGESET_COMMENT: _('[Comment] %(repo_name)s changeset %(short_id)s on %(branch)s'),
+            self.TYPE_CHANGESET_COMMENT: _('[Comment] %(repo_name)s changeset %(short_id)s "%(message_short)s" on %(branch)s'),
             self.TYPE_MESSAGE: 'Test Message',
             # self.TYPE_PASSWORD_RESET
             self.TYPE_REGISTRATION: _('New user %(new_username)s registered'),
             # self.TYPE_DEFAULT
-            self.TYPE_PULL_REQUEST: _('[Added] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s'),
-            self.TYPE_PULL_REQUEST_COMMENT: _('[Comment] %(repo_name)s pull request %(pr_nice_id)s from %(ref)s'),
+            self.TYPE_PULL_REQUEST: _('[Review] %(repo_name)s PR %(pr_nice_id)s "%(pr_title_short)s" from %(pr_source_branch)s by %(pr_owner_username)s'),
+            self.TYPE_PULL_REQUEST_COMMENT: _('[Comment] %(repo_name)s PR %(pr_nice_id)s "%(pr_title_short)s" from %(pr_source_branch)s by %(pr_owner_username)s'),
         }
 
     def get_email_description(self, type_, **kwargs):
@@ -338,5 +325,21 @@
                    'h': h,
                    'c': c}
         _kwargs.update(kwargs)
+        if content_type == 'html':
+            _kwargs.update({
+                "color_text": "#202020",
+                "color_emph": "#395fa0",
+                "color_link": "#395fa0",
+                "color_border": "#ddd",
+                "color_background_grey": "#f9f9f9",
+                "color_button": "#395fa0",
+                "monospace_style": "font-family:Lucida Console,Consolas,Monaco,Inconsolata,Liberation Mono,monospace",
+                "sans_style": "font-family:Helvetica,Arial,sans-serif",
+                })
+            _kwargs.update({
+                "default_style": "%(sans_style)s;font-weight:200;font-size:14px;line-height:17px;color:%(color_text)s" % _kwargs,
+                "comment_style": "%(monospace_style)s;white-space:pre-wrap" % _kwargs,
+                })
+
         log.debug('rendering tmpl %s with kwargs %s', base, _kwargs)
         return email_template.render(**_kwargs)
--- a/kallithea/model/permission.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/permission.py	Fri Nov 18 01:11:13 2016 +0100
@@ -31,8 +31,8 @@
 
 from sqlalchemy.exc import DatabaseError
 
-from kallithea.model import BaseModel
-from kallithea.model.db import User, Permission, UserToPerm, UserRepoToPerm,\
+from kallithea.model.base import BaseModel
+from kallithea.model.db import User, Permission, UserToPerm, UserRepoToPerm, \
     UserRepoGroupToPerm, UserUserGroupToPerm
 from kallithea.lib.utils2 import str2bool
 
@@ -44,8 +44,6 @@
     Permissions model for Kallithea
     """
 
-    cls = Permission
-
     def create_permissions(self):
         """
         Create permissions for whole system
@@ -54,7 +52,6 @@
             if not Permission.get_by_key(p[0]):
                 new_perm = Permission()
                 new_perm.permission_name = p[0]
-                new_perm.permission_longname = p[0]  #translation err with p[1]
                 self.sa.add(new_perm)
 
     def create_default_permissions(self, user, force=False):
@@ -116,8 +113,8 @@
             # clear current entries, to make this function idempotent
             # it will fix even if we define more permissions or permissions
             # are somehow missing
-            u2p = self.sa.query(UserToPerm)\
-                .filter(UserToPerm.user == perm_user)\
+            u2p = self.sa.query(UserToPerm) \
+                .filter(UserToPerm.user == perm_user) \
                 .all()
             for p in u2p:
                 self.sa.delete(p)
@@ -140,8 +137,8 @@
                 _def_name = form_result['default_repo_perm'].split('repository.')[-1]
                 _def = Permission.get_by_key('repository.' + _def_name)
                 # repos
-                for r2p in self.sa.query(UserRepoToPerm)\
-                               .filter(UserRepoToPerm.user == perm_user)\
+                for r2p in self.sa.query(UserRepoToPerm) \
+                               .filter(UserRepoToPerm.user == perm_user) \
                                .all():
 
                     #don't reset PRIVATE repositories
@@ -153,8 +150,8 @@
                 _def_name = form_result['default_group_perm'].split('group.')[-1]
                 # groups
                 _def = Permission.get_by_key('group.' + _def_name)
-                for g2p in self.sa.query(UserRepoGroupToPerm)\
-                               .filter(UserRepoGroupToPerm.user == perm_user)\
+                for g2p in self.sa.query(UserRepoGroupToPerm) \
+                               .filter(UserRepoGroupToPerm.user == perm_user) \
                                .all():
                     g2p.permission = _def
                     self.sa.add(g2p)
@@ -163,8 +160,8 @@
                 _def_name = form_result['default_user_group_perm'].split('usergroup.')[-1]
                 # groups
                 _def = Permission.get_by_key('usergroup.' + _def_name)
-                for g2p in self.sa.query(UserUserGroupToPerm)\
-                               .filter(UserUserGroupToPerm.user == perm_user)\
+                for g2p in self.sa.query(UserUserGroupToPerm) \
+                               .filter(UserUserGroupToPerm.user == perm_user) \
                                .all():
                     g2p.permission = _def
                     self.sa.add(g2p)
--- a/kallithea/model/pull_request.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/pull_request.py	Fri Nov 18 01:11:13 2016 +0100
@@ -30,11 +30,13 @@
 
 from pylons.i18n.translation import _
 
+from sqlalchemy.orm import joinedload
+
 from kallithea.model.meta import Session
 from kallithea.lib import helpers as h
 from kallithea.lib.exceptions import UserInvalidException
-from kallithea.model import BaseModel
-from kallithea.model.db import PullRequest, PullRequestReviewers, Notification,\
+from kallithea.model.base import BaseModel
+from kallithea.model.db import PullRequest, PullRequestReviewer, Notification, \
     ChangesetStatus, User
 from kallithea.model.notification import NotificationModel
 from kallithea.lib.utils2 import extract_mentioned_users, safe_unicode
@@ -45,87 +47,64 @@
 
 class PullRequestModel(BaseModel):
 
-    cls = PullRequest
-
-    def __get_pull_request(self, pull_request):
-        return self._get_instance(PullRequest, pull_request)
-
-    def get_pullrequest_cnt_for_user(self, user):
-        return PullRequest.query()\
-                                .join(PullRequestReviewers)\
-                                .filter(PullRequestReviewers.user_id == user)\
-                                .filter(PullRequest.status != PullRequest.STATUS_CLOSED)\
-                                .count()
-
-    def get_all(self, repo_name, from_=False, closed=False):
-        """Get all PRs for repo.
-        Default is all PRs to the repo, PRs from the repo if from_.
-        Closed PRs are only included if closed is true."""
-        repo = self._get_repo(repo_name)
-        q = PullRequest.query()
-        if from_:
-            q = q.filter(PullRequest.org_repo == repo)
-        else:
-            q = q.filter(PullRequest.other_repo == repo)
-        if not closed:
-            q = q.filter(PullRequest.status != PullRequest.STATUS_CLOSED)
-        return q.order_by(PullRequest.created_on.desc()).all()
+    def _get_valid_reviewers(self, seq):
+        """ Generate User objects from a sequence of user IDs, usernames or
+        User objects. Raises UserInvalidException if the DEFAULT user is
+        specified, or if a given ID or username does not match any user.
+        """
+        for user_spec in seq:
+            user = self._get_user(user_spec)
+            if user is None or user.username == User.DEFAULT_USER:
+                raise UserInvalidException(user_spec)
+            yield user
 
     def create(self, created_by, org_repo, org_ref, other_repo, other_ref,
-               revisions, reviewers, title, description=None):
-        from kallithea.model.changeset_status import ChangesetStatusModel
-
-        created_by_user = self._get_user(created_by)
-        org_repo = self._get_repo(org_repo)
-        other_repo = self._get_repo(other_repo)
-
-        new = PullRequest()
-        new.org_repo = org_repo
-        new.org_ref = org_ref
-        new.other_repo = other_repo
-        new.other_ref = other_ref
-        new.revisions = revisions
-        new.title = title
-        new.description = description
-        new.owner = created_by_user
-        Session().add(new)
-        Session().flush()
+               revisions, title, description, reviewers):
+        pr = PullRequest()
+        pr.org_repo = org_repo
+        pr.org_ref = org_ref
+        pr.other_repo = other_repo
+        pr.other_ref = other_ref
+        pr.revisions = revisions
+        pr.title = title
+        pr.description = description
+        pr.owner = created_by
+        Session().add(pr)
+        Session().flush() # make database assign pull_request_id
 
         #reset state to under-review
+        from kallithea.model.changeset_status import ChangesetStatusModel
         from kallithea.model.comment import ChangesetCommentsModel
         comment = ChangesetCommentsModel().create(
             text=u'',
             repo=org_repo,
-            user=new.owner,
-            pull_request=new,
+            author=created_by,
+            pull_request=pr,
             send_email=False,
             status_change=ChangesetStatus.STATUS_UNDER_REVIEW,
         )
         ChangesetStatusModel().set_status(
             org_repo,
             ChangesetStatus.STATUS_UNDER_REVIEW,
-            new.owner,
+            created_by,
             comment,
-            pull_request=new
+            pull_request=pr,
         )
 
-        mention_recipients = set(User.get_by_username(username, case_insensitive=True)
-                                 for username in extract_mentioned_users(new.description))
-        self.__add_reviewers(created_by_user, new, reviewers, mention_recipients)
+        reviewers = set(self._get_valid_reviewers(reviewers))
+        mention_recipients = extract_mentioned_users(description)
+        self.add_reviewers(created_by, pr, reviewers, mention_recipients)
 
-        return new
+        return pr
 
-    def __add_reviewers(self, user, pr, reviewers, mention_recipients=None):
+    def add_reviewers(self, user, pr, reviewers, mention_recipients=None):
+        """Add reviewer and send notification to them.
+        """
+        reviewer_users = set(self._get_valid_reviewers(reviewers))
         #members
-        for member in set(reviewers):
-            _usr = self._get_user(member)
-            if _usr is None:
-                raise UserInvalidException(member)
-            reviewer = PullRequestReviewers(_usr, pr)
-            Session().add(reviewer)
-
-        revision_data = [(x.raw_id, x.message)
-                         for x in map(pr.org_repo.get_changeset, pr.revisions)]
+        for reviewer in reviewer_users:
+            prr = PullRequestReviewer(reviewer, pr)
+            Session().add(prr)
 
         #notification to reviewers
         pr_url = pr.url(canonical=True)
@@ -142,15 +121,27 @@
             )
         body = pr.description
         _org_ref_type, org_ref_name, _org_rev = pr.org_ref.split(':')
+        _other_ref_type, other_ref_name, _other_rev = pr.other_ref.split(':')
+        revision_data = [(x.raw_id, x.message)
+                         for x in map(pr.org_repo.get_changeset, pr.revisions)]
         email_kwargs = {
             'pr_title': pr.title,
+            'pr_title_short': h.shorter(pr.title, 50),
             'pr_user_created': user.full_name_and_username,
             'pr_repo_url': h.canonical_url('summary_home', repo_name=pr.other_repo.repo_name),
             'pr_url': pr_url,
             'pr_revisions': revision_data,
             'repo_name': pr.other_repo.repo_name,
+            'org_repo_name': pr.org_repo.repo_name,
             'pr_nice_id': pr.nice_id(),
-            'ref': org_ref_name,
+            'pr_target_repo': h.canonical_url('summary_home',
+                               repo_name=pr.other_repo.repo_name),
+            'pr_target_branch': other_ref_name,
+            'pr_source_repo': h.canonical_url('summary_home',
+                               repo_name=pr.org_repo.repo_name),
+            'pr_source_branch': org_ref_name,
+            'pr_owner': pr.owner,
+            'pr_owner_username': pr.owner.username,
             'pr_username': user.username,
             'threading': threading,
             'is_mention': False,
@@ -161,56 +152,39 @@
                                        type_=Notification.TYPE_PULL_REQUEST,
                                        email_kwargs=email_kwargs)
 
+        mention_recipient_users = set()
         if mention_recipients:
-            mention_recipients.discard(None)
-            mention_recipients.difference_update(reviewers)
-        if mention_recipients:
+            mention_recipient_users = set(self._get_valid_reviewers(mention_recipients))
+            mention_recipient_users.difference_update(reviewers)
+        if mention_recipient_users:
             email_kwargs['is_mention'] = True
             subject = _('[Mention]') + ' ' + subject
+            # FIXME: this subject is wrong and unused!
             NotificationModel().create(created_by=user, subject=subject, body=body,
-                                       recipients=mention_recipients,
+                                       recipients=mention_recipient_users,
                                        type_=Notification.TYPE_PULL_REQUEST,
                                        email_kwargs=email_kwargs)
 
     def mention_from_description(self, user, pr, old_description=''):
-        mention_recipients = set(User.get_by_username(username, case_insensitive=True)
-                                 for username in extract_mentioned_users(pr.description))
-        mention_recipients.difference_update(User.get_by_username(username, case_insensitive=True)
-                                             for username in extract_mentioned_users(old_description))
+        mention_recipients = (extract_mentioned_users(pr.description) -
+                              extract_mentioned_users(old_description))
 
         log.debug("Mentioning %s", mention_recipients)
-        self.__add_reviewers(user, pr, [], mention_recipients)
+        self.add_reviewers(user, pr, set(), mention_recipients)
 
-    def update_reviewers(self, user, pull_request, reviewers_ids):
-        reviewers_ids = set(reviewers_ids)
-        pull_request = self.__get_pull_request(pull_request)
-        current_reviewers = PullRequestReviewers.query()\
-                            .filter(PullRequestReviewers.pull_request==
-                                   pull_request)\
-                            .all()
-        current_reviewers_ids = set([x.user.user_id for x in current_reviewers])
+    def remove_reviewers(self, user, pull_request, reviewer_ids):
+        """Remove users in the given user_id list from being reviewers of the PR."""
 
-        to_add = reviewers_ids.difference(current_reviewers_ids)
-        to_remove = current_reviewers_ids.difference(reviewers_ids)
-
-        log.debug("Adding %s reviewers", to_add)
-        self.__add_reviewers(user, pull_request, to_add)
-
-        log.debug("Removing %s reviewers", to_remove)
-        for uid in to_remove:
-            reviewer = PullRequestReviewers.query()\
-                    .filter(PullRequestReviewers.user_id==uid,
-                            PullRequestReviewers.pull_request==pull_request)\
-                    .scalar()
-            if reviewer:
-                Session().delete(reviewer)
+        PullRequestReviewer.query() \
+            .filter_by(pull_request=pull_request) \
+            .filter(PullRequestReviewer.user_id.in_(reviewer_ids)) \
+            .delete(synchronize_session='fetch') # the default of 'evaluate' is not available
 
     def delete(self, pull_request):
-        pull_request = self.__get_pull_request(pull_request)
+        pull_request = PullRequest.guess_instance(pull_request)
         Session().delete(pull_request)
 
     def close_pull_request(self, pull_request):
-        pull_request = self.__get_pull_request(pull_request)
+        pull_request = PullRequest.guess_instance(pull_request)
         pull_request.status = PullRequest.STATUS_CLOSED
         pull_request.updated_on = datetime.datetime.now()
-        Session().add(pull_request)
--- a/kallithea/model/repo.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/repo.py	Fri Nov 18 01:11:13 2016 +0100
@@ -41,7 +41,7 @@
 from kallithea.lib.caching_query import FromCache
 from kallithea.lib.hooks import log_delete_repository
 
-from kallithea.model import BaseModel
+from kallithea.model.base import BaseModel
 from kallithea.model.db import Repository, UserRepoToPerm, UserGroupRepoToPerm, \
     UserRepoGroupToPerm, UserGroupRepoGroupToPerm, User, Permission, \
     Statistics, UserGroup, Ui, RepoGroup, RepositoryField
@@ -56,15 +56,14 @@
 
 class RepoModel(BaseModel):
 
-    cls = Repository
     URL_SEPARATOR = Repository.url_sep()
 
     def _get_user_group(self, users_group):
-        return self._get_instance(UserGroup, users_group,
+        return UserGroup.guess_instance(users_group,
                                   callback=UserGroup.get_by_group_name)
 
     def _get_repo_group(self, repo_group):
-        return self._get_instance(RepoGroup, repo_group,
+        return RepoGroup.guess_instance(repo_group,
                                   callback=RepoGroup.get_by_group_name)
 
     def _create_default_perms(self, repository, private):
@@ -124,7 +123,7 @@
         """
         from kallithea.lib.auth import AuthUser
         user = self._get_user(user)
-        repos = AuthUser(user_id=user.user_id).permissions['repositories']
+        repos = AuthUser(dbuser=user).permissions['repositories']
         access_check = lambda r: r[1] in ['repository.read',
                                           'repository.write',
                                           'repository.admin']
@@ -132,14 +131,17 @@
         return Repository.query().filter(Repository.repo_name.in_(repos))
 
     def get_users_js(self):
-        users = self.sa.query(User).filter(User.active == True).all()
+        users = self.sa.query(User) \
+            .filter(User.active == True) \
+            .order_by(User.name, User.lastname) \
+            .all()
         return json.dumps([
             {
                 'id': u.user_id,
                 'fname': h.escape(u.name),
                 'lname': h.escape(u.lastname),
                 'nname': u.username,
-                'gravatar_lnk': h.gravatar_url(u.email, size=28),
+                'gravatar_lnk': h.gravatar_url(u.email, size=28, default='default'),
                 'gravatar_size': 14,
             } for u in users]
         )
@@ -147,6 +149,7 @@
     def get_user_groups_js(self):
         user_groups = self.sa.query(UserGroup) \
             .filter(UserGroup.users_group_active == True) \
+            .order_by(UserGroup.users_group_name) \
             .options(subqueryload(UserGroup.members)) \
             .all()
         user_groups = UserGroupList(user_groups, perm_set=['usergroup.read',
@@ -173,15 +176,8 @@
         kwargs.update(dict(_=_, h=h, c=c))
         return tmpl.render(*args, **kwargs)
 
-    @classmethod
-    def update_repoinfo(cls, repositories=None):
-        if repositories is None:
-            repositories = Repository.getAll()
-        for repo in repositories:
-            repo.update_changeset_cache()
-
     def get_repos_as_dict(self, repos_list=None, admin=False, perm_check=True,
-                          super_user_actions=False):
+                          super_user_actions=False, short_name=False):
         _render = self._render_datatable
         from pylons import tmpl_context as c
 
@@ -190,7 +186,7 @@
 
         def repo_lnk(name, rtype, rstate, private, fork_of):
             return _render('repo_name', name, rtype, rstate, private, fork_of,
-                           short_name=not admin, admin=False)
+                           short_name=short_name, admin=False)
 
         def last_change(last_change):
             return _render("last_change", last_change)
@@ -207,7 +203,7 @@
                            cs_cache.get('message'))
 
         def desc(desc):
-            return h.urlify_text(desc, truncate=60, stylize=c.visual.stylify_metatags)
+            return h.urlify_text(desc, truncate=80, stylize=c.visual.stylify_metatags)
 
         def state(repo_state):
             return _render("repo_state", repo_state)
@@ -215,8 +211,8 @@
         def repo_actions(repo_name):
             return _render('repo_actions', repo_name, super_user_actions)
 
-        def owner_actions(user_id, username):
-            return _render('user_name', user_id, username)
+        def owner_actions(owner_id, username):
+            return _render('user_name', owner_id, username)
 
         repos_data = []
         for repo in repos_list:
@@ -230,14 +226,15 @@
             cs_cache = repo.changeset_cache
             row = {
                 "menu": quick_menu(repo.repo_name),
-                "raw_name": repo.repo_name.lower(),
+                "raw_name": repo.repo_name,
                 "name": repo_lnk(repo.repo_name, repo.repo_type,
                                  repo.repo_state, repo.private, repo.fork),
+                "last_change_iso": repo.last_db_change.isoformat(),
                 "last_change": last_change(repo.last_db_change),
                 "last_changeset": last_rev(repo.repo_name, cs_cache),
                 "last_rev_raw": cs_cache.get('revision'),
                 "desc": desc(repo.description),
-                "owner": h.person(repo.user),
+                "owner": h.person(repo.owner),
                 "state": state(repo.repo_state),
                 "rss": rss_lnk(repo.repo_name),
                 "atom": atom_lnk(repo.repo_name),
@@ -246,8 +243,8 @@
             if admin:
                 row.update({
                     "action": repo_actions(repo.repo_name),
-                    "owner": owner_actions(repo.user.user_id,
-                                           h.person(repo.user))
+                    "owner": owner_actions(repo.owner_id,
+                                           h.person(repo.owner))
                 })
             repos_data.append(row)
 
@@ -273,10 +270,8 @@
             return None
 
         defaults = repo_info.get_dict()
-        group, repo_name, repo_name_full = repo_info.groups_and_repo
-        defaults['repo_name'] = repo_name
-        defaults['repo_group'] = getattr(group[-1] if group else None,
-                                         'group_id', None)
+        defaults['repo_name'] = repo_info.just_name
+        defaults['repo_group'] = repo_info.group_id
 
         for strip, k in [(0, 'repo_type'), (1, 'repo_enable_downloads'),
                          (1, 'repo_description'), (1, 'repo_enable_locking'),
@@ -294,12 +289,12 @@
                 defaults['clone_uri_hidden'] = repo_info.clone_uri_hidden
 
         # fill owner
-        if repo_info.user:
-            defaults.update({'user': repo_info.user.username})
+        if repo_info.owner:
+            defaults.update({'owner': repo_info.owner.username})
         else:
             replacement_user = User.query().filter(User.admin ==
                                                    True).first().username
-            defaults.update({'user': replacement_user})
+            defaults.update({'owner': replacement_user})
 
         # fill repository users
         for p in repo_info.repo_to_perm:
@@ -317,8 +312,8 @@
         try:
             cur_repo = self._get_repo(repo)
             org_repo_name = cur_repo.repo_name
-            if 'user' in kwargs:
-                cur_repo.user = User.get_by_username(kwargs['user'])
+            if 'owner' in kwargs:
+                cur_repo.owner = User.get_by_username(kwargs['owner'])
 
             if 'repo_group' in kwargs:
                 cur_repo.group = RepoGroup.get(kwargs['repo_group'])
@@ -395,7 +390,7 @@
             new_repo.enable_statistics = False
             new_repo.repo_name = repo_name_full
             new_repo.repo_type = repo_type
-            new_repo.user = owner
+            new_repo.owner = owner
             new_repo.group = repo_group
             new_repo.description = description or repo_name
             new_repo.private = private
@@ -469,8 +464,8 @@
         :param form_data:
         :param cur_user:
         """
-        from kallithea.lib.celerylib import tasks, run_task
-        return run_task(tasks.create_repo, form_data, cur_user)
+        from kallithea.lib.celerylib import tasks
+        return tasks.create_repo(form_data, cur_user)
 
     def _update_permissions(self, repo, perms_new=None, perms_updates=None,
                             check_perms=True):
@@ -518,8 +513,8 @@
         :param form_data:
         :param cur_user:
         """
-        from kallithea.lib.celerylib import tasks, run_task
-        return run_task(tasks.create_repo_fork, form_data, cur_user)
+        from kallithea.lib.celerylib import tasks
+        return tasks.create_repo_fork(form_data, cur_user)
 
     def delete(self, repo, forks=None, fs_remove=True, cur_user=None):
         """
@@ -769,4 +764,7 @@
         if repo.group:
             args = repo.group.full_path_splitted + [_d]
             _d = os.path.join(*args)
-        shutil.move(rm_path, safe_str(os.path.join(self.repos_path, _d)))
+        if os.path.exists(rm_path):
+            shutil.move(rm_path, safe_str(os.path.join(self.repos_path, _d)))
+        else:
+            log.error("Can't find repo to delete in %r", rm_path)
--- a/kallithea/model/repo_group.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/repo_group.py	Fri Nov 18 01:11:13 2016 +0100
@@ -34,7 +34,7 @@
 
 from kallithea.lib.utils2 import LazyProperty
 
-from kallithea.model import BaseModel
+from kallithea.model.base import BaseModel
 from kallithea.model.db import RepoGroup, Ui, UserRepoGroupToPerm, \
     User, Permission, UserGroupRepoGroupToPerm, UserGroup, Repository
 
@@ -43,14 +43,12 @@
 
 class RepoGroupModel(BaseModel):
 
-    cls = RepoGroup
-
     def _get_user_group(self, users_group):
-        return self._get_instance(UserGroup, users_group,
+        return UserGroup.guess_instance(users_group,
                                   callback=UserGroup.get_by_group_name)
 
     def _get_repo_group(self, repo_group):
-        return self._get_instance(RepoGroup, repo_group,
+        return RepoGroup.guess_instance(repo_group,
                                   callback=RepoGroup.get_by_group_name)
 
     @LazyProperty
@@ -59,7 +57,7 @@
         Gets the repositories root path from database
         """
 
-        q = Ui.get_by_key('/')
+        q = Ui.get_by_key('paths', '/')
         return q.ui_value
 
     def _create_default_perms(self, new_group):
@@ -145,10 +143,10 @@
     def create(self, group_name, group_description, owner, parent=None,
                just_db=False, copy_permissions=False):
         try:
-            user = self._get_user(owner)
+            owner = self._get_user(owner)
             parent_group = self._get_repo_group(parent)
             new_repo_group = RepoGroup()
-            new_repo_group.user = user
+            new_repo_group.owner = owner
             new_repo_group.group_description = group_description or group_name
             new_repo_group.parent_group = parent_group
             new_repo_group.group_name = new_repo_group.get_new_name(group_name)
@@ -157,7 +155,7 @@
 
             # create an ADMIN permission for owner except if we're super admin,
             # later owner should go into the owner field of groups
-            if not user.is_admin:
+            if not owner.is_admin:
                 self.grant_user_permission(repo_group=new_repo_group,
                                            user=owner, perm='group.admin')
 
@@ -173,7 +171,7 @@
                     # don't copy over the permission for user who is creating
                     # this group, if he is not super admin he get's admin
                     # permission set above
-                    if perm.user != user or user.is_admin:
+                    if perm.user != owner or owner.is_admin:
                         UserRepoGroupToPerm.create(perm.user, new_repo_group, perm.permission)
 
                 for perm in group_perms:
@@ -292,10 +290,10 @@
 
             # change properties
             repo_group.group_description = form_data['group_description']
-            repo_group.group_parent_id = form_data['group_parent_id']
+            repo_group.parent_group_id = form_data['parent_group_id']
             repo_group.enable_locking = form_data['enable_locking']
 
-            repo_group.parent_group = RepoGroup.get(form_data['group_parent_id'])
+            repo_group.parent_group = RepoGroup.get(form_data['parent_group_id'])
             repo_group.group_name = repo_group.get_new_name(form_data['group_name'])
             new_path = repo_group.full_path
             self.sa.add(repo_group)
@@ -455,9 +453,9 @@
         permission = self._get_perm(perm)
 
         # check if we have that permission already
-        obj = self.sa.query(UserRepoGroupToPerm)\
-            .filter(UserRepoGroupToPerm.user == user)\
-            .filter(UserRepoGroupToPerm.group == repo_group)\
+        obj = self.sa.query(UserRepoGroupToPerm) \
+            .filter(UserRepoGroupToPerm.user == user) \
+            .filter(UserRepoGroupToPerm.group == repo_group) \
             .scalar()
         if obj is None:
             # create new !
@@ -481,9 +479,9 @@
         repo_group = self._get_repo_group(repo_group)
         user = self._get_user(user)
 
-        obj = self.sa.query(UserRepoGroupToPerm)\
-            .filter(UserRepoGroupToPerm.user == user)\
-            .filter(UserRepoGroupToPerm.group == repo_group)\
+        obj = self.sa.query(UserRepoGroupToPerm) \
+            .filter(UserRepoGroupToPerm.user == user) \
+            .filter(UserRepoGroupToPerm.group == repo_group) \
             .scalar()
         if obj is not None:
             self.sa.delete(obj)
@@ -505,9 +503,9 @@
         permission = self._get_perm(perm)
 
         # check if we have that permission already
-        obj = self.sa.query(UserGroupRepoGroupToPerm)\
-            .filter(UserGroupRepoGroupToPerm.group == repo_group)\
-            .filter(UserGroupRepoGroupToPerm.users_group == group_name)\
+        obj = self.sa.query(UserGroupRepoGroupToPerm) \
+            .filter(UserGroupRepoGroupToPerm.group == repo_group) \
+            .filter(UserGroupRepoGroupToPerm.users_group == group_name) \
             .scalar()
 
         if obj is None:
@@ -533,9 +531,9 @@
         repo_group = self._get_repo_group(repo_group)
         group_name = self._get_user_group(group_name)
 
-        obj = self.sa.query(UserGroupRepoGroupToPerm)\
-            .filter(UserGroupRepoGroupToPerm.group == repo_group)\
-            .filter(UserGroupRepoGroupToPerm.users_group == group_name)\
+        obj = self.sa.query(UserGroupRepoGroupToPerm) \
+            .filter(UserGroupRepoGroupToPerm.group == repo_group) \
+            .filter(UserGroupRepoGroupToPerm.users_group == group_name) \
             .scalar()
         if obj is not None:
             self.sa.delete(obj)
--- a/kallithea/model/repo_permission.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/repo_permission.py	Fri Nov 18 01:11:13 2016 +0100
@@ -24,7 +24,7 @@
 """
 
 import logging
-from kallithea.model import BaseModel
+from kallithea.model.base import BaseModel
 from kallithea.model.db import UserRepoToPerm, UserGroupRepoToPerm, \
     Permission
 
@@ -33,8 +33,6 @@
 
 class RepositoryPermissionModel(BaseModel):
 
-    cls = UserRepoToPerm
-
     def get_user_permission(self, repository, user):
         repository = self._get_repo(repository)
         user = self._get_user(user)
--- a/kallithea/model/scm.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/scm.py	Fri Nov 18 01:11:13 2016 +0100
@@ -26,13 +26,14 @@
 """
 
 import os
+import sys
+import posixpath
 import re
 import time
 import traceback
 import logging
 import cStringIO
 import pkg_resources
-from os.path import join as jn
 
 from sqlalchemy import func
 from pylons.i18n.translation import _
@@ -46,13 +47,13 @@
 
 from kallithea import BACKENDS
 from kallithea.lib import helpers as h
-from kallithea.lib.utils2 import safe_str, safe_unicode, get_server_url,\
+from kallithea.lib.utils2 import safe_str, safe_unicode, get_server_url, \
     _set_extras
-from kallithea.lib.auth import HasRepoPermissionAny, HasRepoGroupPermissionAny,\
-    HasUserGroupPermissionAny, HasPermissionAny, HasPermissionAll
+from kallithea.lib.auth import HasRepoPermissionAny, HasRepoGroupPermissionAny, \
+    HasUserGroupPermissionAny, HasPermissionAny, HasPermissionAny
 from kallithea.lib.utils import get_filesystem_repos, make_ui, \
     action_logger
-from kallithea.model import BaseModel
+from kallithea.model.base import BaseModel
 from kallithea.model.db import Repository, Ui, CacheInvalidation, \
     UserFollowing, UserLog, User, RepoGroup, PullRequest
 from kallithea.lib.hooks import log_push_action
@@ -77,92 +78,6 @@
         return "<%s('id:%s')>" % (self.__class__.__name__, self.repo_id)
 
 
-class CachedRepoList(object):
-    """
-    Cached repo list. Uses super-fast in-memory cache after initialization.
-    """
-
-    def __init__(self, db_repo_list, repos_path, order_by=None, perm_set=None):
-        self.db_repo_list = db_repo_list
-        self.repos_path = repos_path
-        self.order_by = order_by
-        self.reversed = (order_by or '').startswith('-')
-        if not perm_set:
-            perm_set = ['repository.read', 'repository.write',
-                        'repository.admin']
-        self.perm_set = perm_set
-
-    def __len__(self):
-        return len(self.db_repo_list)
-
-    def __repr__(self):
-        return '<%s (%s)>' % (self.__class__.__name__, self.__len__())
-
-    def __iter__(self):
-        # pre-propagated valid_cache_keys to save executing select statements
-        # for each repo
-        valid_cache_keys = CacheInvalidation.get_valid_cache_keys()
-
-        for dbr in self.db_repo_list:
-            scmr = dbr.scm_instance_cached(valid_cache_keys)
-            # check permission at this level
-            if not HasRepoPermissionAny(
-                *self.perm_set)(dbr.repo_name, 'get repo check'):
-                continue
-
-            try:
-                last_change = scmr.last_change
-                tip = h.get_changeset_safe(scmr, 'tip')
-            except Exception:
-                log.error(
-                    '%s this repository is present in database but it '
-                    'cannot be created as an scm instance, org_exc:%s'
-                    % (dbr.repo_name, traceback.format_exc())
-                )
-                continue
-
-            tmp_d = {}
-            tmp_d['name'] = dbr.repo_name
-            tmp_d['name_sort'] = tmp_d['name'].lower()
-            tmp_d['raw_name'] = tmp_d['name'].lower()
-            tmp_d['description'] = dbr.description
-            tmp_d['description_sort'] = tmp_d['description'].lower()
-            tmp_d['last_change'] = last_change
-            tmp_d['last_change_sort'] = time.mktime(last_change.timetuple())
-            tmp_d['tip'] = tip.raw_id
-            tmp_d['tip_sort'] = tip.revision
-            tmp_d['rev'] = tip.revision
-            tmp_d['contact'] = dbr.user.full_contact
-            tmp_d['contact_sort'] = tmp_d['contact']
-            tmp_d['owner_sort'] = tmp_d['contact']
-            tmp_d['repo_archives'] = list(scmr._get_archives())
-            tmp_d['last_msg'] = tip.message
-            tmp_d['author'] = tip.author
-            tmp_d['dbrepo'] = dbr.get_dict()
-            tmp_d['dbrepo_fork'] = dbr.fork.get_dict() if dbr.fork else {}
-            yield tmp_d
-
-
-class SimpleCachedRepoList(CachedRepoList):
-    """
-    Lighter version of CachedRepoList without the scm initialisation
-    """
-
-    def __iter__(self):
-        for dbr in self.db_repo_list:
-            # check permission at this level
-            if not HasRepoPermissionAny(
-                *self.perm_set)(dbr.repo_name, 'get repo check'):
-                continue
-
-            tmp_d = {
-                'name': dbr.repo_name,
-                'dbrepo': dbr.get_dict(),
-                'dbrepo_fork': dbr.fork.get_dict() if dbr.fork else {}
-            }
-            yield tmp_d
-
-
 class _PermCheckIterator(object):
     def __init__(self, obj_list, obj_attr, perm_set, perm_checker, extra_kwargs=None):
         """
@@ -276,7 +191,7 @@
         baseui = make_ui('db')
         repos = {}
 
-        for name, path in get_filesystem_repos(repos_path, recursive=True):
+        for name, path in get_filesystem_repos(repos_path):
             # name need to be decomposed and put back together using the /
             # since this is internal storage separator for kallithea
             name = Repository.normalize_repo_name(name)
@@ -299,53 +214,34 @@
         log.debug('found %s paths with repositories', len(repos))
         return repos
 
-    def get_repos(self, all_repos=None, sort_key=None, simple=False):
-        """
-        Get all repos from db and for each repo create its
-        backend instance and fill that backed with information from database
+    def get_repos(self, repos):
+        """Return the repos the user has access to"""
+        return RepoList(repos)
 
-        :param all_repos: list of repository names as strings
-            give specific repositories list, good for filtering
-
-        :param sort_key: initial sorting of repos
-        :param simple: use SimpleCachedList - one without the SCM info
+    def get_repo_groups(self, groups=None):
+        """Return the repo groups the user has access to
+        If no groups are specified, use top level groups.
         """
-        if all_repos is None:
-            all_repos = self.sa.query(Repository)\
-                        .filter(Repository.group_id == None)\
-                        .order_by(func.lower(Repository.repo_name)).all()
-        if simple:
-            repo_iter = SimpleCachedRepoList(all_repos,
-                                             repos_path=self.repos_path,
-                                             order_by=sort_key)
-        else:
-            repo_iter = CachedRepoList(all_repos,
-                                       repos_path=self.repos_path,
-                                       order_by=sort_key)
+        if groups is None:
+            groups = RepoGroup.query() \
+                .filter(RepoGroup.parent_group_id == None).all()
+        return RepoGroupList(groups)
 
-        return repo_iter
-
-    def get_repo_groups(self, all_groups=None):
-        if all_groups is None:
-            all_groups = RepoGroup.query()\
-                .filter(RepoGroup.group_parent_id == None).all()
-        return [x for x in RepoGroupList(all_groups)]
-
-    def mark_for_invalidation(self, repo_name, delete=False):
+    def mark_for_invalidation(self, repo_name):
         """
         Mark caches of this repo invalid in the database.
 
         :param repo_name: the repo for which caches should be marked invalid
         """
-        CacheInvalidation.set_invalidate(repo_name, delete=delete)
+        CacheInvalidation.set_invalidate(repo_name)
         repo = Repository.get_by_repo_name(repo_name)
         if repo is not None:
             repo.update_changeset_cache()
 
     def toggle_following_repo(self, follow_repo_id, user_id):
 
-        f = self.sa.query(UserFollowing)\
-            .filter(UserFollowing.follows_repo_id == follow_repo_id)\
+        f = self.sa.query(UserFollowing) \
+            .filter(UserFollowing.follows_repository_id == follow_repo_id) \
             .filter(UserFollowing.user_id == user_id).scalar()
 
         if f is not None:
@@ -362,7 +258,7 @@
         try:
             f = UserFollowing()
             f.user_id = user_id
-            f.follows_repo_id = follow_repo_id
+            f.follows_repository_id = follow_repo_id
             self.sa.add(f)
 
             action_logger(UserTemp(user_id),
@@ -373,8 +269,8 @@
             raise
 
     def toggle_following_user(self, follow_user_id, user_id):
-        f = self.sa.query(UserFollowing)\
-            .filter(UserFollowing.follows_user_id == follow_user_id)\
+        f = self.sa.query(UserFollowing) \
+            .filter(UserFollowing.follows_user_id == follow_user_id) \
             .filter(UserFollowing.user_id == user_id).scalar()
 
         if f is not None:
@@ -395,11 +291,11 @@
             raise
 
     def is_following_repo(self, repo_name, user_id, cache=False):
-        r = self.sa.query(Repository)\
+        r = self.sa.query(Repository) \
             .filter(Repository.repo_name == repo_name).scalar()
 
-        f = self.sa.query(UserFollowing)\
-            .filter(UserFollowing.follows_repository == r)\
+        f = self.sa.query(UserFollowing) \
+            .filter(UserFollowing.follows_repository == r) \
             .filter(UserFollowing.user_id == user_id).scalar()
 
         return f is not None
@@ -407,8 +303,8 @@
     def is_following_user(self, username, user_id, cache=False):
         u = User.get_by_username(username)
 
-        f = self.sa.query(UserFollowing)\
-            .filter(UserFollowing.follows_user == u)\
+        f = self.sa.query(UserFollowing) \
+            .filter(UserFollowing.follows_user == u) \
             .filter(UserFollowing.user_id == user_id).scalar()
 
         return f is not None
@@ -416,18 +312,18 @@
     def get_followers(self, repo):
         repo = self._get_repo(repo)
 
-        return self.sa.query(UserFollowing)\
+        return self.sa.query(UserFollowing) \
                 .filter(UserFollowing.follows_repository == repo).count()
 
     def get_forks(self, repo):
         repo = self._get_repo(repo)
-        return self.sa.query(Repository)\
+        return self.sa.query(Repository) \
                 .filter(Repository.fork == repo).count()
 
     def get_pull_requests(self, repo):
         repo = self._get_repo(repo)
-        return self.sa.query(PullRequest)\
-                .filter(PullRequest.other_repo == repo)\
+        return self.sa.query(PullRequest) \
+                .filter(PullRequest.other_repo == repo) \
                 .filter(PullRequest.status != PullRequest.STATUS_CLOSED).count()
 
     def mark_as_fork(self, repo, fork, user):
@@ -575,7 +471,7 @@
         if f_path.startswith('/') or f_path.startswith('.') or '../' in f_path:
             raise NonRelativePathError('%s is not an relative path' % f_path)
         if f_path:
-            f_path = os.path.normpath(f_path)
+            f_path = posixpath.normpath(f_path)
         return f_path
 
     def get_nodes(self, repo_name, revision, root_path='/', flat=True):
@@ -628,8 +524,8 @@
 
         processed_nodes = []
         for f_path in nodes:
+            content = nodes[f_path]['content']
             f_path = self._sanitize_path(f_path)
-            content = nodes[f_path]['content']
             f_path = safe_str(f_path)
             # decoding here will force that we have proper encoded values
             # in any other case this will throw exceptions and deny commit
@@ -842,21 +738,23 @@
         :param force_create: Create even if same name hook exists
         """
 
-        loc = jn(repo.path, 'hooks')
+        loc = os.path.join(repo.path, 'hooks')
         if not repo.bare:
-            loc = jn(repo.path, '.git', 'hooks')
+            loc = os.path.join(repo.path, '.git', 'hooks')
         if not os.path.isdir(loc):
             os.makedirs(loc)
 
-        tmpl_post = pkg_resources.resource_string(
-            'kallithea', jn('config', 'post_receive_tmpl.py')
+        tmpl_post = "#!/usr/bin/env %s\n" % sys.executable or 'python2'
+        tmpl_post += pkg_resources.resource_string(
+            'kallithea', os.path.join('config', 'post_receive_tmpl.py')
         )
-        tmpl_pre = pkg_resources.resource_string(
-            'kallithea', jn('config', 'pre_receive_tmpl.py')
+        tmpl_pre = "#!/usr/bin/env %s\n" % sys.executable or 'python2'
+        tmpl_pre += pkg_resources.resource_string(
+            'kallithea', os.path.join('config', 'pre_receive_tmpl.py')
         )
 
         for h_type, tmpl in [('pre', tmpl_pre), ('post', tmpl_post)]:
-            _hook_file = jn(loc, '%s-receive' % h_type)
+            _hook_file = os.path.join(loc, '%s-receive' % h_type)
             has_hook = False
             log.debug('Installing git hook in repo %s', repo)
             if os.path.exists(_hook_file):
@@ -896,7 +794,7 @@
     Top level is -1.
     """
     groups = RepoGroup.query().all()
-    if HasPermissionAll('hg.admin')('available repo groups'):
+    if HasPermissionAny('hg.admin')('available repo groups'):
         groups.append(None)
     else:
         groups = list(RepoGroupList(groups, perm_set=repo_group_perms))
--- a/kallithea/model/user.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/user.py	Fri Nov 18 01:11:13 2016 +0100
@@ -37,10 +37,9 @@
 
 from sqlalchemy.exc import DatabaseError
 
-from kallithea import EXTERN_TYPE_INTERNAL
-from kallithea.lib.utils2 import safe_unicode, generate_api_key, get_current_authuser
+from kallithea.lib.utils2 import safe_str, generate_api_key, get_current_authuser
 from kallithea.lib.caching_query import FromCache
-from kallithea.model import BaseModel
+from kallithea.model.base import BaseModel
 from kallithea.model.db import User, UserToPerm, Notification, \
     UserEmailMap, UserIpMap
 from kallithea.lib.exceptions import DefaultUserException, \
@@ -54,8 +53,6 @@
 class UserModel(BaseModel):
     password_reset_token_lifetime = 86400 # 24 hours
 
-    cls = User
-
     def get(self, user_id, cache=False):
         user = self.sa.query(User)
         if cache:
@@ -95,13 +92,14 @@
             setattr(new_user, k, v)
 
         new_user.api_key = generate_api_key()
-        self.sa.add(new_user)
+        Session().add(new_user)
+        Session().flush() # make database assign new_user.user_id
 
         log_create_user(new_user.get_dict(), cur_user)
         return new_user
 
-    def create_or_update(self, username, password, email, firstname='',
-                         lastname='', active=True, admin=False,
+    def create_or_update(self, username, password, email, firstname=u'',
+                         lastname=u'', active=True, admin=False,
                          extern_type=None, extern_name=None, cur_user=None):
         """
         Creates a new instance if not found, or updates current one
@@ -148,9 +146,9 @@
             new_user.admin = admin
             new_user.email = email
             new_user.active = active
-            new_user.extern_name = safe_unicode(extern_name) \
+            new_user.extern_name = safe_str(extern_name) \
                 if extern_name else None
-            new_user.extern_type = safe_unicode(extern_type) \
+            new_user.extern_type = safe_str(extern_type) \
                 if extern_type else None
             new_user.name = firstname
             new_user.lastname = lastname
@@ -165,12 +163,15 @@
                 reason = 'new password' if edit else 'new user'
                 log.debug('Updating password reason=>%s', reason)
                 new_user.password = get_crypt_password(password) \
-                    if password else None
+                    if password else ''
 
-            self.sa.add(new_user)
+            if user is None:
+                Session().add(new_user)
+                Session().flush() # make database assign new_user.user_id
 
             if not edit:
                 log_create_user(new_user.get_dict(), cur_user)
+
             return new_user
         except (DatabaseError,):
             log.error(traceback.format_exc())
@@ -181,13 +182,10 @@
         import kallithea.lib.helpers as h
 
         form_data['admin'] = False
-        form_data['extern_name'] = EXTERN_TYPE_INTERNAL
-        form_data['extern_type'] = EXTERN_TYPE_INTERNAL
+        form_data['extern_type'] = User.DEFAULT_AUTH_TYPE
+        form_data['extern_name'] = ''
         new_user = self.create(form_data)
 
-        self.sa.add(new_user)
-        self.sa.flush()
-
         # notification to admins
         subject = _('New user registration')
         body = (
@@ -200,15 +198,17 @@
         edit_url = h.canonical_url('edit_user', id=new_user.user_id)
         email_kwargs = {
             'registered_user_url': edit_url,
-            'new_username': new_user.username}
+            'new_username': new_user.username,
+            'new_email': new_user.email,
+            'new_full_name': new_user.full_name}
         NotificationModel().create(created_by=new_user, subject=subject,
                                    body=body, recipients=None,
                                    type_=Notification.TYPE_REGISTRATION,
                                    email_kwargs=email_kwargs)
 
-    def update(self, user_id, form_data, skip_attrs=[]):
+    def update(self, user_id, form_data, skip_attrs=None):
         from kallithea.lib.auth import get_crypt_password
-
+        skip_attrs = skip_attrs or []
         user = self.get(user_id, cache=False)
         if user.username == User.DEFAULT_USER:
             raise DefaultUserException(
@@ -278,6 +278,11 @@
         from kallithea.lib.hooks import log_delete_user
         log_delete_user(user.get_dict(), cur_user)
 
+    def can_change_password(self, user):
+        from kallithea.lib import auth_modules
+        managed_fields = auth_modules.get_managed_fields(user)
+        return 'password' not in managed_fields
+
     def get_reset_password_token(self, user, timestamp, session_id):
         """
         The token is a 40-digit hexstring, calculated as a HMAC-SHA1.
@@ -324,7 +329,7 @@
         allowing users to copy-paste or manually enter the token from the
         email.
         """
-        from kallithea.lib.celerylib import tasks, run_task
+        from kallithea.lib.celerylib import tasks
         from kallithea.model.notification import EmailNotificationModel
         import kallithea.lib.helpers as h
 
@@ -332,18 +337,21 @@
         user = User.get_by_email(user_email)
         timestamp = int(time.time())
         if user is not None:
-            log.debug('password reset user %s found', user)
-            token = self.get_reset_password_token(user,
-                                                  timestamp,
-                                                  h.authentication_token())
-            # URL must be fully qualified; but since the token is locked to
-            # the current browser session, we must provide a URL with the
-            # current scheme and hostname, rather than the canonical_url.
-            link = h.url('reset_password_confirmation', qualified=True,
-                         email=user_email,
-                         timestamp=timestamp,
-                         token=token)
-
+            if self.can_change_password(user):
+                log.debug('password reset user %s found', user)
+                token = self.get_reset_password_token(user,
+                                                      timestamp,
+                                                      h.authentication_token())
+                # URL must be fully qualified; but since the token is locked to
+                # the current browser session, we must provide a URL with the
+                # current scheme and hostname, rather than the canonical_url.
+                link = h.url('reset_password_confirmation', qualified=True,
+                             email=user_email,
+                             timestamp=timestamp,
+                             token=token)
+            else:
+                log.debug('password reset user %s found but was managed', user)
+                token = link = None
             reg_type = EmailNotificationModel.TYPE_PASSWORD_RESET
             body = EmailNotificationModel().get_email_tmpl(
                 reg_type, 'txt',
@@ -356,8 +364,7 @@
                 reset_token=token,
                 reset_url=link)
             log.debug('sending email')
-            run_task(tasks.send_email, [user_email],
-                     _("Password reset link"), body, html_body)
+            tasks.send_email([user_email], _("Password reset link"), body, html_body)
             log.info('send new password mail to %s', user_email)
         else:
             log.debug("password reset email %s not found", user_email)
@@ -367,7 +374,7 @@
                      timestamp=timestamp)
 
     def verify_reset_password_token(self, email, timestamp, token):
-        from kallithea.lib.celerylib import tasks, run_task
+        from kallithea.lib.celerylib import tasks
         from kallithea.lib import auth
         import kallithea.lib.helpers as h
         user = User.get_by_email(email)
@@ -393,18 +400,19 @@
         return expected_token == token
 
     def reset_password(self, user_email, new_passwd):
-        from kallithea.lib.celerylib import tasks, run_task
+        from kallithea.lib.celerylib import tasks
         from kallithea.lib import auth
         user = User.get_by_email(user_email)
         if user is not None:
+            if not self.can_change_password(user):
+                raise Exception('trying to change password for external user')
             user.password = auth.get_crypt_password(new_passwd)
-            Session().add(user)
             Session().commit()
             log.info('change password for %s', user_email)
         if new_passwd is None:
             raise Exception('unable to set new password')
 
-        run_task(tasks.send_email, [user_email],
+        tasks.send_email([user_email],
                  _('Password reset notification'),
                  _('The password to your account %s has been changed using password reset form.') % (user.username,))
         log.info('send password reset mail to %s', user_email)
@@ -415,7 +423,7 @@
         perm = self._get_perm(perm)
         user = self._get_user(user)
 
-        return UserToPerm.query().filter(UserToPerm.user == user)\
+        return UserToPerm.query().filter(UserToPerm.user == user) \
             .filter(UserToPerm.permission == perm).scalar() is not None
 
     def grant_perm(self, user, perm):
@@ -428,9 +436,9 @@
         user = self._get_user(user)
         perm = self._get_perm(perm)
         # if this permission is already granted skip it
-        _perm = UserToPerm.query()\
-            .filter(UserToPerm.user == user)\
-            .filter(UserToPerm.permission == perm)\
+        _perm = UserToPerm.query() \
+            .filter(UserToPerm.user == user) \
+            .filter(UserToPerm.permission == perm) \
             .scalar()
         if _perm:
             return
--- a/kallithea/model/user_group.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/user_group.py	Fri Nov 18 01:11:13 2016 +0100
@@ -27,11 +27,11 @@
 import logging
 import traceback
 
-from kallithea.model import BaseModel
-from kallithea.model.db import UserGroupMember, UserGroup,\
-    UserGroupRepoToPerm, Permission, UserGroupToPerm, User, UserUserGroupToPerm,\
+from kallithea.model.base import BaseModel
+from kallithea.model.db import UserGroupMember, UserGroup, \
+    UserGroupRepoToPerm, Permission, UserGroupToPerm, User, UserUserGroupToPerm, \
     UserGroupUserGroupToPerm
-from kallithea.lib.exceptions import UserGroupsAssignedException,\
+from kallithea.lib.exceptions import UserGroupsAssignedException, \
     RepoGroupAssignmentError
 
 log = logging.getLogger(__name__)
@@ -39,10 +39,8 @@
 
 class UserGroupModel(BaseModel):
 
-    cls = UserGroup
-
     def _get_user_group(self, user_group):
-        return self._get_instance(UserGroup, user_group,
+        return UserGroup.guess_instance(user_group,
                                   callback=UserGroup.get_by_group_name)
 
     def _create_default_perms(self, user_group):
@@ -109,7 +107,7 @@
     def create(self, name, description, owner, active=True, group_data=None):
         try:
             new_user_group = UserGroup()
-            new_user_group.user = self._get_user(owner)
+            new_user_group.owner = self._get_user(owner)
             new_user_group.users_group_name = name
             new_user_group.user_group_description = description
             new_user_group.users_group_active = active
@@ -134,18 +132,19 @@
 
             for k, v in form_data.items():
                 if k == 'users_group_members':
-                    user_group.members = []
-                    self.sa.flush()
                     members_list = []
                     if v:
                         v = [v] if isinstance(v, basestring) else v
                         for u_id in set(v):
                             member = UserGroupMember(user_group.users_group_id, u_id)
                             members_list.append(member)
-                    setattr(user_group, 'members', members_list)
+                            self.sa.add(member)
+                    user_group.members = members_list
                 setattr(user_group, k, v)
 
-            self.sa.add(user_group)
+            # Flush to make db assign users_group_member_id to newly
+            # created UserGroupMembers.
+            self.sa.flush()
         except Exception:
             log.error(traceback.format_exc())
             raise
@@ -162,7 +161,7 @@
         user_group = self._get_user_group(user_group)
         try:
             # check if this group is not assigned to repo
-            assigned_groups = UserGroupRepoToPerm.query()\
+            assigned_groups = UserGroupRepoToPerm.query() \
                 .filter(UserGroupRepoToPerm.users_group == user_group).all()
             assigned_groups = [x.repository.repo_name for x in assigned_groups]
 
@@ -204,7 +203,7 @@
 
         user_group_member = None
         for m in user_group.members:
-            if m.user.user_id == user.user_id:
+            if m.user_id == user.user_id:
                 # Found this user's membership row
                 user_group_member = m
                 break
@@ -224,8 +223,8 @@
         user_group = self._get_user_group(user_group)
         perm = self._get_perm(perm)
 
-        return UserGroupToPerm.query()\
-            .filter(UserGroupToPerm.users_group == user_group)\
+        return UserGroupToPerm.query() \
+            .filter(UserGroupToPerm.users_group == user_group) \
             .filter(UserGroupToPerm.permission == perm).scalar() is not None
 
     def grant_perm(self, user_group, perm):
@@ -233,9 +232,9 @@
         perm = self._get_perm(perm)
 
         # if this permission is already granted skip it
-        _perm = UserGroupToPerm.query()\
-            .filter(UserGroupToPerm.users_group == user_group)\
-            .filter(UserGroupToPerm.permission == perm)\
+        _perm = UserGroupToPerm.query() \
+            .filter(UserGroupToPerm.users_group == user_group) \
+            .filter(UserGroupToPerm.permission == perm) \
             .scalar()
         if _perm:
             return
@@ -250,8 +249,8 @@
         user_group = self._get_user_group(user_group)
         perm = self._get_perm(perm)
 
-        obj = UserGroupToPerm.query()\
-            .filter(UserGroupToPerm.users_group == user_group)\
+        obj = UserGroupToPerm.query() \
+            .filter(UserGroupToPerm.users_group == user_group) \
             .filter(UserGroupToPerm.permission == perm).scalar()
         if obj is not None:
             self.sa.delete(obj)
@@ -272,9 +271,9 @@
         permission = self._get_perm(perm)
 
         # check if we have that permission already
-        obj = self.sa.query(UserUserGroupToPerm)\
-            .filter(UserUserGroupToPerm.user == user)\
-            .filter(UserUserGroupToPerm.user_group == user_group)\
+        obj = self.sa.query(UserUserGroupToPerm) \
+            .filter(UserUserGroupToPerm.user == user) \
+            .filter(UserUserGroupToPerm.user_group == user_group) \
             .scalar()
         if obj is None:
             # create new !
@@ -298,9 +297,9 @@
         user_group = self._get_user_group(user_group)
         user = self._get_user(user)
 
-        obj = self.sa.query(UserUserGroupToPerm)\
-            .filter(UserUserGroupToPerm.user == user)\
-            .filter(UserUserGroupToPerm.user_group == user_group)\
+        obj = self.sa.query(UserUserGroupToPerm) \
+            .filter(UserUserGroupToPerm.user == user) \
+            .filter(UserUserGroupToPerm.user_group == user_group) \
             .scalar()
         if obj is not None:
             self.sa.delete(obj)
@@ -323,9 +322,9 @@
                                            'assigned to itself' % target_user_group)
 
         # check if we have that permission already
-        obj = self.sa.query(UserGroupUserGroupToPerm)\
-            .filter(UserGroupUserGroupToPerm.target_user_group == target_user_group)\
-            .filter(UserGroupUserGroupToPerm.user_group == user_group)\
+        obj = self.sa.query(UserGroupUserGroupToPerm) \
+            .filter(UserGroupUserGroupToPerm.target_user_group == target_user_group) \
+            .filter(UserGroupUserGroupToPerm.user_group == user_group) \
             .scalar()
         if obj is None:
             # create new !
@@ -347,9 +346,9 @@
         target_user_group = self._get_user_group(target_user_group)
         user_group = self._get_user_group(user_group)
 
-        obj = self.sa.query(UserGroupUserGroupToPerm)\
-            .filter(UserGroupUserGroupToPerm.target_user_group == target_user_group)\
-            .filter(UserGroupUserGroupToPerm.user_group == user_group)\
+        obj = self.sa.query(UserGroupUserGroupToPerm) \
+            .filter(UserGroupUserGroupToPerm.target_user_group == target_user_group) \
+            .filter(UserGroupUserGroupToPerm.user_group == user_group) \
             .scalar()
         if obj is not None:
             self.sa.delete(obj)
@@ -375,7 +374,7 @@
         for gr in set(groups):
             existing_group = UserGroup.get_by_group_name(gr)
             if not existing_group:
-                desc = 'Automatically created from plugin:%s' % extern_type
+                desc = u'Automatically created from plugin:%s' % extern_type
                 # we use first admin account to set the owner of the group
                 existing_group = UserGroupModel().create(gr, desc, owner,
                                         group_data={'extern_type': extern_type})
--- a/kallithea/model/validators.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/model/validators.py	Fri Nov 18 01:11:13 2016 +0100
@@ -89,7 +89,8 @@
     return _UniqueListFromString
 
 
-def ValidUsername(edit=False, old_data={}):
+def ValidUsername(edit=False, old_data=None):
+    old_data = old_data or {}
     class _validator(formencode.validators.FancyValidator):
         messages = {
             'username_exists': _('Username "%(username)s" already exists'),
@@ -135,7 +136,7 @@
 
         def validate_python(self, value, state):
             try:
-                User.query().filter(User.active == True)\
+                User.query().filter(User.active == True) \
                     .filter(User.username == value).one()
             except sqlalchemy.exc.InvalidRequestError: # NoResultFound/MultipleResultsFound
                 msg = M(self, 'invalid_username', state, username=value)
@@ -146,7 +147,8 @@
     return _validator
 
 
-def ValidUserGroup(edit=False, old_data={}):
+def ValidUserGroup(edit=False, old_data=None):
+    old_data = old_data or {}
     class _validator(formencode.validators.FancyValidator):
         messages = {
             'invalid_group': _('Invalid user group name'),
@@ -187,10 +189,12 @@
     return _validator
 
 
-def ValidRepoGroup(edit=False, old_data={}):
+def ValidRepoGroup(edit=False, old_data=None):
+    old_data = old_data or {}
+
     class _validator(formencode.validators.FancyValidator):
         messages = {
-            'group_parent_id': _('Cannot assign this group as parent'),
+            'parent_group_id': _('Cannot assign this group as parent'),
             'group_exists': _('Group "%(group_name)s" already exists'),
             'repo_exists':
                 _('Repository with name "%(group_name)s" already exists')
@@ -199,20 +203,20 @@
         def validate_python(self, value, state):
             # TODO WRITE VALIDATIONS
             group_name = value.get('group_name')
-            group_parent_id = value.get('group_parent_id')
+            parent_group_id = value.get('parent_group_id')
 
             # slugify repo group just in case :)
             slug = repo_name_slug(group_name)
 
             # check for parent of self
             parent_of_self = lambda: (
-                old_data['group_id'] == group_parent_id
-                if group_parent_id else False
+                old_data['group_id'] == parent_group_id
+                if parent_group_id else False
             )
             if edit and parent_of_self():
-                msg = M(self, 'group_parent_id', state)
+                msg = M(self, 'parent_group_id', state)
                 raise formencode.Invalid(msg, value, state,
-                    error_dict=dict(group_parent_id=msg)
+                    error_dict=dict(parent_group_id=msg)
                 )
 
             old_gname = None
@@ -222,9 +226,9 @@
             if old_gname != group_name or not edit:
 
                 # check group
-                gr = RepoGroup.query()\
-                      .filter(RepoGroup.group_name == slug)\
-                      .filter(RepoGroup.group_parent_id == group_parent_id)\
+                gr = RepoGroup.query() \
+                      .filter(RepoGroup.group_name == slug) \
+                      .filter(RepoGroup.parent_group_id == parent_group_id) \
                       .scalar()
 
                 if gr is not None:
@@ -234,8 +238,8 @@
                     )
 
                 # check for same repo
-                repo = Repository.query()\
-                      .filter(Repository.repo_name == slug)\
+                repo = Repository.query() \
+                      .filter(Repository.repo_name == slug) \
                       .scalar()
 
                 if repo is not None:
@@ -309,7 +313,7 @@
             # authenticate returns unused dict but has called
             # plugin._authenticate which has create_or_update'ed the username user in db
             if auth_modules.authenticate(username, password) is None:
-                user = User.get_by_username(username)
+                user = User.get_by_username_or_email(username)
                 if user and not user.active:
                     log.warning('user %s is disabled', username)
                     msg = M(self, 'invalid_auth', state)
@@ -338,7 +342,9 @@
     return _validator
 
 
-def ValidRepoName(edit=False, old_data={}):
+def ValidRepoName(edit=False, old_data=None):
+    old_data = old_data or {}
+
     class _validator(formencode.validators.FancyValidator):
         messages = {
             'invalid_repo_name':
@@ -373,7 +379,6 @@
             return value
 
         def validate_python(self, value, state):
-
             repo_name = value.get('repo_name')
             repo_name_full = value.get('repo_name_full')
             group_path = value.get('group_path')
@@ -483,7 +488,9 @@
     return _validator
 
 
-def ValidForkType(old_data={}):
+def ValidForkType(old_data=None):
+    old_data = old_data or {}
+
     class _validator(formencode.validators.FancyValidator):
         messages = {
             'invalid_fork_type': _('Fork has to be the same type as parent')
@@ -577,7 +584,7 @@
             if forbidden_in_root or forbidden:
                 msg = M(self, 'permission_denied', state)
                 raise formencode.Invalid(msg, value, state,
-                    error_dict=dict(group_parent_id=msg)
+                    error_dict=dict(parent_group_id=msg)
                 )
 
     return _validator
@@ -644,12 +651,12 @@
             for k, v, t in perms_new:
                 try:
                     if t is 'user':
-                        self.user_db = User.query()\
-                            .filter(User.active == True)\
+                        self.user_db = User.query() \
+                            .filter(User.active == True) \
                             .filter(User.username == k).one()
                     if t is 'users_group':
-                        self.user_db = UserGroup.query()\
-                            .filter(UserGroup.users_group_active == True)\
+                        self.user_db = UserGroup.query() \
+                            .filter(UserGroup.users_group_active == True) \
                             .filter(UserGroup.users_group_name == k).one()
 
                 except Exception:
@@ -699,7 +706,9 @@
     return _validator
 
 
-def UniqSystemEmail(old_data={}):
+def UniqSystemEmail(old_data=None):
+    old_data = old_data or {}
+
     class _validator(formencode.validators.FancyValidator):
         messages = {
             'email_taken': _('This email address is already in use')
@@ -710,7 +719,7 @@
 
         def validate_python(self, value, state):
             if (old_data.get('email') or '').lower() != value:
-                user = User.get_by_email(value, case_insensitive=True)
+                user = User.get_by_email(value)
                 if user is not None:
                     msg = M(self, 'email_taken', state)
                     raise formencode.Invalid(msg, value, state,
@@ -729,7 +738,7 @@
             return value.lower()
 
         def validate_python(self, value, state):
-            user = User.get_by_email(value, case_insensitive=True)
+            user = User.get_by_email(value)
             if user is None:
                 msg = M(self, 'non_existing_email', state, email=value)
                 raise formencode.Invalid(msg, value, state,
--- a/kallithea/public/css/bootstrap.css	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/public/css/bootstrap.css	Fri Nov 18 01:11:13 2016 +0100
@@ -1,15 +1,17 @@
 /*!
- * Bootstrap v3.0.0
- *
- * Copyright 2013 Twitter, Inc
- * Licensed under the Apache License v2.0
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Designed and built with all the love in the world by @mdo and @fat.
+ * Bootstrap v3.3.7 (http://getbootstrap.com)
+ * Copyright 2011-2016 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  */
-
-/*! normalize.css v2.1.0 | MIT License | git.io/normalize */
-
+/*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */
+html {
+  font-family: sans-serif;
+  -webkit-text-size-adjust: 100%;
+      -ms-text-size-adjust: 100%;
+}
+body {
+  margin: 0;
+}
 article,
 aside,
 details,
@@ -19,95 +21,55 @@
 header,
 hgroup,
 main,
+menu,
 nav,
 section,
 summary {
   display: block;
 }
-
 audio,
 canvas,
+progress,
 video {
   display: inline-block;
-}
-
+  vertical-align: baseline;
+}
 audio:not([controls]) {
   display: none;
   height: 0;
 }
-
-[hidden] {
+[hidden],
+template {
   display: none;
 }
-
-html {
-  font-family: sans-serif;
-  -webkit-text-size-adjust: 100%;
-      -ms-text-size-adjust: 100%;
-}
-
-body {
-  margin: 0;
-}
-
-a:focus {
-  outline: thin dotted;
-}
-
+a {
+  background-color: transparent;
+}
 a:active,
 a:hover {
   outline: 0;
 }
-
-h1 {
-  margin: 0.67em 0;
-  font-size: 2em;
-}
-
 abbr[title] {
   border-bottom: 1px dotted;
 }
-
 b,
 strong {
   font-weight: bold;
 }
-
 dfn {
   font-style: italic;
 }
-
-hr {
-  height: 0;
-  -moz-box-sizing: content-box;
-       box-sizing: content-box;
-}
-
+h1 {
+  margin: .67em 0;
+  font-size: 2em;
+}
 mark {
   color: #000;
   background: #ff0;
 }
-
-code,
-kbd,
-pre,
-samp {
-  font-family: monospace, serif;
-  font-size: 1em;
-}
-
-pre {
-  white-space: pre-wrap;
-}
-
-q {
-  quotes: "\201C" "\201D" "\2018" "\2019";
-}
-
 small {
   font-size: 80%;
 }
-
 sub,
 sup {
   position: relative;
@@ -115,110 +77,126 @@
   line-height: 0;
   vertical-align: baseline;
 }
-
 sup {
-  top: -0.5em;
-}
-
+  top: -.5em;
+}
 sub {
-  bottom: -0.25em;
-}
-
+  bottom: -.25em;
+}
 img {
   border: 0;
 }
-
 svg:not(:root) {
   overflow: hidden;
 }
-
 figure {
-  margin: 0;
-}
-
-fieldset {
-  padding: 0.35em 0.625em 0.75em;
-  margin: 0 2px;
-  border: 1px solid #c0c0c0;
-}
-
-legend {
-  padding: 0;
-  border: 0;
-}
-
+  margin: 1em 40px;
+}
+hr {
+  height: 0;
+  -webkit-box-sizing: content-box;
+     -moz-box-sizing: content-box;
+          box-sizing: content-box;
+}
+pre {
+  overflow: auto;
+}
+code,
+kbd,
+pre,
+samp {
+  font-family: monospace, monospace;
+  font-size: 1em;
+}
 button,
 input,
+optgroup,
 select,
 textarea {
   margin: 0;
-  font-family: inherit;
-  font-size: 100%;
-}
-
-button,
-input {
-  line-height: normal;
-}
-
+  font: inherit;
+  color: inherit;
+}
+button {
+  overflow: visible;
+}
 button,
 select {
   text-transform: none;
 }
-
 button,
 html input[type="button"],
 input[type="reset"],
 input[type="submit"] {
+  -webkit-appearance: button;
   cursor: pointer;
-  -webkit-appearance: button;
-}
-
+}
 button[disabled],
 html input[disabled] {
   cursor: default;
 }
-
+button::-moz-focus-inner,
+input::-moz-focus-inner {
+  padding: 0;
+  border: 0;
+}
+input {
+  line-height: normal;
+}
 input[type="checkbox"],
 input[type="radio"] {
+  -webkit-box-sizing: border-box;
+     -moz-box-sizing: border-box;
+          box-sizing: border-box;
   padding: 0;
-  box-sizing: border-box;
-}
-
+}
+input[type="number"]::-webkit-inner-spin-button,
+input[type="number"]::-webkit-outer-spin-button {
+  height: auto;
+}
 input[type="search"] {
   -webkit-box-sizing: content-box;
      -moz-box-sizing: content-box;
           box-sizing: content-box;
   -webkit-appearance: textfield;
 }
-
 input[type="search"]::-webkit-search-cancel-button,
 input[type="search"]::-webkit-search-decoration {
   -webkit-appearance: none;
 }
-
-button::-moz-focus-inner,
-input::-moz-focus-inner {
+fieldset {
+  padding: .35em .625em .75em;
+  margin: 0 2px;
+  border: 1px solid #c0c0c0;
+}
+legend {
   padding: 0;
   border: 0;
 }
-
 textarea {
   overflow: auto;
-  vertical-align: top;
-}
-
+}
+optgroup {
+  font-weight: bold;
+}
 table {
+  border-spacing: 0;
   border-collapse: collapse;
-  border-spacing: 0;
-}
-
+}
+td,
+th {
+  padding: 0;
+}
+/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */
 @media print {
-  * {
+  *,
+  *:before,
+  *:after {
     color: #000 !important;
     text-shadow: none !important;
     background: transparent !important;
-    box-shadow: none !important;
+    -webkit-box-shadow: none !important;
+            box-shadow: none !important;
   }
   a,
   a:visited {
@@ -230,14 +208,14 @@
   abbr[title]:after {
     content: " (" attr(title) ")";
   }
-  .ir a:after,
-  a[href^="javascript:"]:after,
-  a[href^="#"]:after {
+  a[href^="#"]:after,
+  a[href^="javascript:"]:after {
     content: "";
   }
   pre,
   blockquote {
     border: 1px solid #999;
+
     page-break-inside: avoid;
   }
   thead {
@@ -250,9 +228,6 @@
   img {
     max-width: 100% !important;
   }
-  @page  {
-    margin: 2cm .5cm;
-  }
   p,
   h2,
   h3 {
@@ -266,10 +241,6 @@
   .navbar {
     display: none;
   }
-  .table td,
-  .table th {
-    background-color: #fff !important;
-  }
   .btn > .caret,
   .dropup > .btn > .caret {
     border-top-color: #000 !important;
@@ -280,33 +251,843 @@
   .table {
     border-collapse: collapse !important;
   }
+  .table td,
+  .table th {
+    background-color: #fff !important;
+  }
   .table-bordered th,
   .table-bordered td {
     border: 1px solid #ddd !important;
   }
 }
+@font-face {
+  font-family: 'Glyphicons Halflings';
 
-*,
+  src: url('../fonts/glyphicons-halflings-regular.eot');
+  src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
+}
+.glyphicon {
+  position: relative;
+  top: 1px;
+  display: inline-block;
+  font-family: 'Glyphicons Halflings';
+  font-style: normal;
+  font-weight: normal;
+  line-height: 1;
+
+  -webkit-font-smoothing: antialiased;
+  -moz-osx-font-smoothing: grayscale;
+}
+.glyphicon-asterisk:before {
+  content: "\002a";
+}
+.glyphicon-plus:before {
+  content: "\002b";
+}
+.glyphicon-euro:before,
+.glyphicon-eur:before {
+  content: "\20ac";
+}
+.glyphicon-minus:before {
+  content: "\2212";
+}
+.glyphicon-cloud:before {
+  content: "\2601";
+}
+.glyphicon-envelope:before {
+  content: "\2709";
+}
+.glyphicon-pencil:before {
+  content: "\270f";
+}
+.glyphicon-glass:before {
+  content: "\e001";
+}
+.glyphicon-music:before {
+  content: "\e002";
+}
+.glyphicon-search:before {
+  content: "\e003";
+}
+.glyphicon-heart:before {
+  content: "\e005";
+}
+.glyphicon-star:before {
+  content: "\e006";
+}
+.glyphicon-star-empty:before {
+  content: "\e007";
+}
+.glyphicon-user:before {
+  content: "\e008";
+}
+.glyphicon-film:before {
+  content: "\e009";
+}
+.glyphicon-th-large:before {
+  content: "\e010";
+}
+.glyphicon-th:before {
+  content: "\e011";
+}
+.glyphicon-th-list:before {
+  content: "\e012";
+}
+.glyphicon-ok:before {
+  content: "\e013";
+}
+.glyphicon-remove:before {
+  content: "\e014";
+}
+.glyphicon-zoom-in:before {
+  content: "\e015";
+}
+.glyphicon-zoom-out:before {
+  content: "\e016";
+}
+.glyphicon-off:before {
+  content: "\e017";
+}
+.glyphicon-signal:before {
+  content: "\e018";
+}
+.glyphicon-cog:before {
+  content: "\e019";
+}
+.glyphicon-trash:before {
+  content: "\e020";
+}
+.glyphicon-home:before {
+  content: "\e021";
+}
+.glyphicon-file:before {
+  content: "\e022";
+}
+.glyphicon-time:before {
+  content: "\e023";
+}
+.glyphicon-road:before {
+  content: "\e024";
+}
+.glyphicon-download-alt:before {
+  content: "\e025";
+}
+.glyphicon-download:before {
+  content: "\e026";
+}
+.glyphicon-upload:before {
+  content: "\e027";
+}
+.glyphicon-inbox:before {
+  content: "\e028";
+}
+.glyphicon-play-circle:before {
+  content: "\e029";
+}
+.glyphicon-repeat:before {
+  content: "\e030";
+}
+.glyphicon-refresh:before {
+  content: "\e031";
+}
+.glyphicon-list-alt:before {
+  content: "\e032";
+}
+.glyphicon-lock:before {
+  content: "\e033";
+}
+.glyphicon-flag:before {
+  content: "\e034";
+}
+.glyphicon-headphones:before {
+  content: "\e035";
+}
+.glyphicon-volume-off:before {
+  content: "\e036";
+}
+.glyphicon-volume-down:before {
+  content: "\e037";
+}
+.glyphicon-volume-up:before {
+  content: "\e038";
+}
+.glyphicon-qrcode:before {
+  content: "\e039";
+}
+.glyphicon-barcode:before {
+  content: "\e040";
+}
+.glyphicon-tag:before {
+  content: "\e041";
+}
+.glyphicon-tags:before {
+  content: "\e042";
+}
+.glyphicon-book:before {
+  content: "\e043";
+}
+.glyphicon-bookmark:before {
+  content: "\e044";
+}
+.glyphicon-print:before {
+  content: "\e045";
+}
+.glyphicon-camera:before {
+  content: "\e046";
+}
+.glyphicon-font:before {
+  content: "\e047";
+}
+.glyphicon-bold:before {
+  content: "\e048";
+}
+.glyphicon-italic:before {
+  content: "\e049";
+}
+.glyphicon-text-height:before {
+  content: "\e050";
+}
+.glyphicon-text-width:before {
+  content: "\e051";
+}
+.glyphicon-align-left:before {
+  content: "\e052";
+}
+.glyphicon-align-center:before {
+  content: "\e053";
+}
+.glyphicon-align-right:before {
+  content: "\e054";
+}
+.glyphicon-align-justify:before {
+  content: "\e055";
+}
+.glyphicon-list:before {
+  content: "\e056";
+}
+.glyphicon-indent-left:before {
+  content: "\e057";
+}
+.glyphicon-indent-right:before {
+  content: "\e058";
+}
+.glyphicon-facetime-video:before {
+  content: "\e059";
+}
+.glyphicon-picture:before {
+  content: "\e060";
+}
+.glyphicon-map-marker:before {
+  content: "\e062";
+}
+.glyphicon-adjust:before {
+  content: "\e063";
+}
+.glyphicon-tint:before {
+  content: "\e064";
+}
+.glyphicon-edit:before {
+  content: "\e065";
+}
+.glyphicon-share:before {
+  content: "\e066";
+}
+.glyphicon-check:before {
+  content: "\e067";
+}
+.glyphicon-move:before {
+  content: "\e068";
+}
+.glyphicon-step-backward:before {
+  content: "\e069";
+}
+.glyphicon-fast-backward:before {
+  content: "\e070";
+}
+.glyphicon-backward:before {
+  content: "\e071";
+}
+.glyphicon-play:before {
+  content: "\e072";
+}
+.glyphicon-pause:before {
+  content: "\e073";
+}
+.glyphicon-stop:before {
+  content: "\e074";
+}
+.glyphicon-forward:before {
+  content: "\e075";
+}
+.glyphicon-fast-forward:before {
+  content: "\e076";
+}
+.glyphicon-step-forward:before {
+  content: "\e077";
+}
+.glyphicon-eject:before {
+  content: "\e078";
+}
+.glyphicon-chevron-left:before {
+  content: "\e079";
+}
+.glyphicon-chevron-right:before {
+  content: "\e080";
+}
+.glyphicon-plus-sign:before {
+  content: "\e081";
+}
+.glyphicon-minus-sign:before {
+  content: "\e082";
+}
+.glyphicon-remove-sign:before {
+  content: "\e083";
+}
+.glyphicon-ok-sign:before {
+  content: "\e084";
+}
+.glyphicon-question-sign:before {
+  content: "\e085";
+}
+.glyphicon-info-sign:before {
+  content: "\e086";
+}
+.glyphicon-screenshot:before {
+  content: "\e087";
+}
+.glyphicon-remove-circle:before {
+  content: "\e088";
+}
+.glyphicon-ok-circle:before {
+  content: "\e089";
+}
+.glyphicon-ban-circle:before {
+  content: "\e090";
+}
+.glyphicon-arrow-left:before {
+  content: "\e091";
+}
+.glyphicon-arrow-right:before {
+  content: "\e092";
+}
+.glyphicon-arrow-up:before {
+  content: "\e093";
+}
+.glyphicon-arrow-down:before {
+  content: "\e094";
+}
+.glyphicon-share-alt:before {
+  content: "\e095";
+}
+.glyphicon-resize-full:before {
+  content: "\e096";
+}
+.glyphicon-resize-small:before {
+  content: "\e097";
+}
+.glyphicon-exclamation-sign:before {
+  content: "\e101";
+}
+.glyphicon-gift:before {
+  content: "\e102";
+}
+.glyphicon-leaf:before {
+  content: "\e103";
+}
+.glyphicon-fire:before {
+  content: "\e104";
+}
+.glyphicon-eye-open:before {
+  content: "\e105";
+}
+.glyphicon-eye-close:before {
+  content: "\e106";
+}
+.glyphicon-warning-sign:before {
+  content: "\e107";
+}
+.glyphicon-plane:before {
+  content: "\e108";
+}
+.glyphicon-calendar:before {
+  content: "\e109";
+}
+.glyphicon-random:before {
+  content: "\e110";
+}
+.glyphicon-comment:before {
+  content: "\e111";
+}
+.glyphicon-magnet:before {
+  content: "\e112";
+}
+.glyphicon-chevron-up:before {
+  content: "\e113";
+}
+.glyphicon-chevron-down:before {
+  content: "\e114";
+}
+.glyphicon-retweet:before {
+  content: "\e115";
+}
+.glyphicon-shopping-cart:before {
+  content: "\e116";
+}
+.glyphicon-folder-close:before {
+  content: "\e117";
+}
+.glyphicon-folder-open:before {
+  content: "\e118";
+}
+.glyphicon-resize-vertical:before {
+  content: "\e119";
+}
+.glyphicon-resize-horizontal:before {
+  content: "\e120";
+}
+.glyphicon-hdd:before {
+  content: "\e121";
+}
+.glyphicon-bullhorn:before {
+  content: "\e122";
+}
+.glyphicon-bell:before {
+  content: "\e123";
+}
+.glyphicon-certificate:before {
+  content: "\e124";
+}
+.glyphicon-thumbs-up:before {
+  content: "\e125";
+}
+.glyphicon-thumbs-down:before {
+  content: "\e126";
+}
+.glyphicon-hand-right:before {
+  content: "\e127";
+}
+.glyphicon-hand-left:before {
+  content: "\e128";
+}
+.glyphicon-hand-up:before {
+  content: "\e129";
+}
+.glyphicon-hand-down:before {
+  content: "\e130";
+}
+.glyphicon-circle-arrow-right:before {
+  content: "\e131";
+}
+.glyphicon-circle-arrow-left:before {
+  content: "\e132";
+}
+.glyphicon-circle-arrow-up:before {
+  content: "\e133";
+}
+.glyphicon-circle-arrow-down:before {
+  content: "\e134";
+}
+.glyphicon-globe:before {
+  content: "\e135";
+}
+.glyphicon-wrench:before {
+  content: "\e136";
+}
+.glyphicon-tasks:before {
+  content: "\e137";
+}
+.glyphicon-filter:before {
+  content: "\e138";
+}
+.glyphicon-briefcase:before {
+  content: "\e139";
+}
+.glyphicon-fullscreen:before {
+  content: "\e140";
+}
+.glyphicon-dashboard:before {
+  content: "\e141";
+}
+.glyphicon-paperclip:before {
+  content: "\e142";
+}
+.glyphicon-heart-empty:before {
+  content: "\e143";
+}
+.glyphicon-link:before {
+  content: "\e144";
+}
+.glyphicon-phone:before {
+  content: "\e145";
+}
+.glyphicon-pushpin:before {
+  content: "\e146";
+}
+.glyphicon-usd:before {
+  content: "\e148";
+}
+.glyphicon-gbp:before {
+  content: "\e149";
+}
+.glyphicon-sort:before {
+  content: "\e150";
+}
+.glyphicon-sort-by-alphabet:before {
+  content: "\e151";
+}
+.glyphicon-sort-by-alphabet-alt:before {
+  content: "\e152";
+}
+.glyphicon-sort-by-order:before {
+  content: "\e153";
+}
+.glyphicon-sort-by-order-alt:before {
+  content: "\e154";
+}
+.glyphicon-sort-by-attributes:before {
+  content: "\e155";
+}
+.glyphicon-sort-by-attributes-alt:before {
+  content: "\e156";
+}
+.glyphicon-unchecked:before {
+  content: "\e157";
+}
+.glyphicon-expand:before {
+  content: "\e158";
+}
+.glyphicon-collapse-down:before {
+  content: "\e159";
+}
+.glyphicon-collapse-up:before {
+  content: "\e160";
+}
+.glyphicon-log-in:before {
+  content: "\e161";
+}
+.glyphicon-flash:before {
+  content: "\e162";
+}
+.glyphicon-log-out:before {
+  content: "\e163";
+}
+.glyphicon-new-window:before {
+  content: "\e164";
+}
+.glyphicon-record:before {
+  content: "\e165";
+}
+.glyphicon-save:before {
+  content: "\e166";
+}
+.glyphicon-open:before {
+  content: "\e167";
+}
+.glyphicon-saved:before {
+  content: "\e168";
+}
+.glyphicon-import:before {
+  content: "\e169";
+}
+.glyphicon-export:before {
+  content: "\e170";
+}
+.glyphicon-send:before {
+  content: "\e171";
+}
+.glyphicon-floppy-disk:before {
+  content: "\e172";
+}
+.glyphicon-floppy-saved:before {
+  content: "\e173";
+}
+.glyphicon-floppy-remove:before {
+  content: "\e174";
+}
+.glyphicon-floppy-save:before {
+  content: "\e175";
+}
+.glyphicon-floppy-open:before {
+  content: "\e176";
+}
+.glyphicon-credit-card:before {
+  content: "\e177";
+}
+.glyphicon-transfer:before {
+  content: "\e178";
+}
+.glyphicon-cutlery:before {
+  content: "\e179";
+}
+.glyphicon-header:before {
+  content: "\e180";
+}
+.glyphicon-compressed:before {
+  content: "\e181";
+}
+.glyphicon-earphone:before {
+  content: "\e182";
+}
+.glyphicon-phone-alt:before {
+  content: "\e183";
+}
+.glyphicon-tower:before {
+  content: "\e184";
+}
+.glyphicon-stats:before {
+  content: "\e185";
+}
+.glyphicon-sd-video:before {
+  content: "\e186";
+}
+.glyphicon-hd-video:before {
+  content: "\e187";
+}
+.glyphicon-subtitles:before {
+  content: "\e188";
+}
+.glyphicon-sound-stereo:before {
+  content: "\e189";
+}
+.glyphicon-sound-dolby:before {
+  content: "\e190";
+}
+.glyphicon-sound-5-1:before {
+  content: "\e191";
+}
+.glyphicon-sound-6-1:before {
+  content: "\e192";
+}
+.glyphicon-sound-7-1:before {
+  content: "\e193";
+}
+.glyphicon-copyright-mark:before {
+  content: "\e194";
+}
+.glyphicon-registration-mark:before {
+  content: "\e195";
+}
+.glyphicon-cloud-download:before {
+  content: "\e197";
+}
+.glyphicon-cloud-upload:before {
+  content: "\e198";
+}
+.glyphicon-tree-conifer:before {
+  content: "\e199";
+}
+.glyphicon-tree-deciduous:before {
+  content: "\e200";
+}
+.glyphicon-cd:before {
+  content: "\e201";
+}
+.glyphicon-save-file:before {
+  content: "\e202";
+}
+.glyphicon-open-file:before {
+  content: "\e203";
+}
+.glyphicon-level-up:before {
+  content: "\e204";
+}
+.glyphicon-copy:before {
+  content: "\e205";
+}
+.glyphicon-paste:before {
+  content: "\e206";
+}
+.glyphicon-alert:before {
+  content: "\e209";
+}
+.glyphicon-equalizer:before {
+  content: "\e210";
+}
+.glyphicon-king:before {
+  content: "\e211";
+}
+.glyphicon-queen:before {
+  content: "\e212";
+}
+.glyphicon-pawn:before {
+  content: "\e213";
+}
+.glyphicon-bishop:before {
+  content: "\e214";
+}
+.glyphicon-knight:before {
+  content: "\e215";
+}
+.glyphicon-baby-formula:before {
+  content: "\e216";
+}
+.glyphicon-tent:before {
+  content: "\26fa";
+}
+.glyphicon-blackboard:before {
+  content: "\e218";
+}
+.glyphicon-bed:before {
+  content: "\e219";
+}
+.glyphicon-apple:before {
+  content: "\f8ff";
+}
+.glyphicon-erase:before {
+  content: "\e221";
+}
+.glyphicon-hourglass:before {
+  content: "\231b";
+}
+.glyphicon-lamp:before {
+  content: "\e223";
+}
+.glyphicon-duplicate:before {
+  content: "\e224";
+}
+.glyphicon-piggy-bank:before {
+  content: "\e225";
+}
+.glyphicon-scissors:before {
+  content: "\e226";
+}
+.glyphicon-bitcoin:before {
+  content: "\e227";
+}
+.glyphicon-btc:before {
+  content: "\e227";
+}
+.glyphicon-xbt:before {
+  content: "\e227";
+}
+.glyphicon-yen:before {
+  content: "\00a5";
+}
+.glyphicon-jpy:before {
+  content: "\00a5";
+}
+.glyphicon-ruble:before {
+  content: "\20bd";
+}
+.glyphicon-rub:before {
+  content: "\20bd";
+}
+.glyphicon-scale:before {
+  content: "\e230";
+}
+.glyphicon-ice-lolly:before {
+  content: "\e231";
+}
+.glyphicon-ice-lolly-tasted:before {
+  content: "\e232";
+}
+.glyphicon-education:before {
+  content: "\e233";
+}
+.glyphicon-option-horizontal:before {
+  content: "\e234";
+}
+.glyphicon-option-vertical:before {
+  content: "\e235";
+}
+.glyphicon-menu-hamburger:before {
+  content: "\e236";
+}
+.glyphicon-modal-window:before {
+  content: "\e237";
+}
+.glyphicon-oil:before {
+  content: "\e238";
+}
+.glyphicon-grain:before {
+  content: "\e239";
+}
+.glyphicon-sunglasses:before {
+  content: "\e240";
+}
+.glyphicon-text-size:before {
+  content: "\e241";
+}
+.glyphicon-text-color:before {
+  content: "\e242";
+}
+.glyphicon-text-background:before {
+  content: "\e243";
+}
+.glyphicon-object-align-top:before {
+  content: "\e244";
+}
+.glyphicon-object-align-bottom:before {
+  content: "\e245";
+}
+.glyphicon-object-align-horizontal:before {
+  content: "\e246";
+}
+.glyphicon-object-align-left:before {
+  content: "\e247";
+}
+.glyphicon-object-align-vertical:before {
+  content: "\e248";
+}
+.glyphicon-object-align-right:before {
+  content: "\e249";
+}
+.glyphicon-triangle-right:before {
+  content: "\e250";
+}
+.glyphicon-triangle-left:before {
+  content: "\e251";
+}
+.glyphicon-triangle-bottom:before {
+  content: "\e252";
+}
+.glyphicon-triangle-top:before {
+  content: "\e253";
+}
+.glyphicon-console:before {
+  content: "\e254";
+}
+.glyphicon-superscript:before {
+  content: "\e255";
+}
+.glyphicon-subscript:before {
+  content: "\e256";
+}
+.glyphicon-menu-left:before {
+  content: "\e257";
+}
+.glyphicon-menu-right:before {
+  content: "\e258";
+}
+.glyphicon-menu-down:before {
+  content: "\e259";
+}
+.glyphicon-menu-up:before {
+  content: "\e260";
+}
+* {
+  -webkit-box-sizing: border-box;
+     -moz-box-sizing: border-box;
+          box-sizing: border-box;
+}
 *:before,
 *:after {
   -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
           box-sizing: border-box;
 }
+html {
+  font-size: 10px;
 
-html {
-  font-size: 62.5%;
   -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
 }
-
 body {
   font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
   font-size: 14px;
-  line-height: 1.428571429;
-  color: #333333;
-  background-color: #ffffff;
-}
-
+  line-height: 1.42857143;
+  color: #333;
+  background-color: #fff;
+}
 input,
 button,
 select,
@@ -315,69 +1096,59 @@
   font-size: inherit;
   line-height: inherit;
 }
-
-button,
-input,
-select[multiple],
-textarea {
-  background-image: none;
-}
-
 a {
-  color: #428bca;
+  color: #337ab7;
   text-decoration: none;
 }
-
 a:hover,
 a:focus {
-  color: #2a6496;
+  color: #23527c;
   text-decoration: underline;
 }
-
 a:focus {
-  outline: thin dotted #333;
   outline: 5px auto -webkit-focus-ring-color;
   outline-offset: -2px;
 }
-
+figure {
+  margin: 0;
+}
 img {
   vertical-align: middle;
 }
-
-.img-responsive {
+.img-responsive,
+.thumbnail > img,
+.thumbnail a > img,
+.carousel-inner > .item > img,
+.carousel-inner > .item > a > img {
   display: block;
+  max-width: 100%;
   height: auto;
-  max-width: 100%;
-}
-
+}
 .img-rounded {
   border-radius: 6px;
 }
-
 .img-thumbnail {
   display: inline-block;
+  max-width: 100%;
   height: auto;
-  max-width: 100%;
   padding: 4px;
-  line-height: 1.428571429;
-  background-color: #ffffff;
-  border: 1px solid #dddddd;
+  line-height: 1.42857143;
+  background-color: #fff;
+  border: 1px solid #ddd;
   border-radius: 4px;
-  -webkit-transition: all 0.2s ease-in-out;
-          transition: all 0.2s ease-in-out;
-}
-
+  -webkit-transition: all .2s ease-in-out;
+       -o-transition: all .2s ease-in-out;
+          transition: all .2s ease-in-out;
+}
 .img-circle {
   border-radius: 50%;
 }
-
 hr {
   margin-top: 20px;
   margin-bottom: 20px;
   border: 0;
-  border-top: 1px solid #eeeeee;
-}
-
+  border-top: 1px solid #eee;
+}
 .sr-only {
   position: absolute;
   width: 1px;
@@ -385,71 +1156,21 @@
   padding: 0;
   margin: -1px;
   overflow: hidden;
-  clip: rect(0 0 0 0);
+  clip: rect(0, 0, 0, 0);
   border: 0;
 }
-
-p {
-  margin: 0 0 10px;
-}
-
-.lead {
-  margin-bottom: 20px;
-  font-size: 16.099999999999998px;
-  font-weight: 200;
-  line-height: 1.4;
-}
-
-@media (min-width: 768px) {
-  .lead {
-    font-size: 21px;
-  }
-}
-
-small {
-  font-size: 85%;
-}
-
-cite {
-  font-style: normal;
-}
-
-.text-muted {
-  color: #999999;
-}
-
-.text-primary {
-  color: #428bca;
-}
-
-.text-warning {
-  color: #c09853;
-}
-
-.text-danger {
-  color: #b94a48;
-}
-
-.text-success {
-  color: #468847;
-}
-
-.text-info {
-  color: #3a87ad;
-}
-
-.text-left {
-  text-align: left;
-}
-
-.text-right {
-  text-align: right;
-}
-
-.text-center {
-  text-align: center;
-}
-
+.sr-only-focusable:active,
+.sr-only-focusable:focus {
+  position: static;
+  width: auto;
+  height: auto;
+  margin: 0;
+  overflow: visible;
+  clip: auto;
+}
+[role="button"] {
+  cursor: pointer;
+}
 h1,
 h2,
 h3,
@@ -462,11 +1183,11 @@
 .h4,
 .h5,
 .h6 {
-  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+  font-family: inherit;
   font-weight: 500;
   line-height: 1.1;
-}
-
+  color: inherit;
+}
 h1 small,
 h2 small,
 h3 small,
@@ -478,125 +1199,258 @@
 .h3 small,
 .h4 small,
 .h5 small,
-.h6 small {
+.h6 small,
+h1 .small,
+h2 .small,
+h3 .small,
+h4 .small,
+h5 .small,
+h6 .small,
+.h1 .small,
+.h2 .small,
+.h3 .small,
+.h4 .small,
+.h5 .small,
+.h6 .small {
   font-weight: normal;
   line-height: 1;
-  color: #999999;
-}
-
+  color: #777;
+}
 h1,
+.h1,
 h2,
-h3 {
+.h2,
+h3,
+.h3 {
   margin-top: 20px;
   margin-bottom: 10px;
 }
-
+h1 small,
+.h1 small,
+h2 small,
+.h2 small,
+h3 small,
+.h3 small,
+h1 .small,
+.h1 .small,
+h2 .small,
+.h2 .small,
+h3 .small,
+.h3 .small {
+  font-size: 65%;
+}
 h4,
+.h4,
 h5,
-h6 {
+.h5,
+h6,
+.h6 {
   margin-top: 10px;
   margin-bottom: 10px;
 }
-
+h4 small,
+.h4 small,
+h5 small,
+.h5 small,
+h6 small,
+.h6 small,
+h4 .small,
+.h4 .small,
+h5 .small,
+.h5 .small,
+h6 .small,
+.h6 .small {
+  font-size: 75%;
+}
 h1,
 .h1 {
   font-size: 36px;
 }
-
 h2,
 .h2 {
   font-size: 30px;
 }
-
 h3,
 .h3 {
   font-size: 24px;
 }
-
 h4,
 .h4 {
   font-size: 18px;
 }
-
 h5,
 .h5 {
   font-size: 14px;
 }
-
 h6,
 .h6 {
   font-size: 12px;
 }
-
-h1 small,
-.h1 small {
-  font-size: 24px;
-}
-
-h2 small,
-.h2 small {
-  font-size: 18px;
-}
-
-h3 small,
-.h3 small,
-h4 small,
-.h4 small {
-  font-size: 14px;
-}
-
+p {
+  margin: 0 0 10px;
+}
+.lead {
+  margin-bottom: 20px;
+  font-size: 16px;
+  font-weight: 300;
+  line-height: 1.4;
+}
+@media (min-width: 768px) {
+  .lead {
+    font-size: 21px;
+  }
+}
+small,
+.small {
+  font-size: 85%;
+}
+mark,
+.mark {
+  padding: .2em;
+  background-color: #fcf8e3;
+}
+.text-left {
+  text-align: left;
+}
+.text-right {
+  text-align: right;
+}
+.text-center {
+  text-align: center;
+}
+.text-justify {
+  text-align: justify;
+}
+.text-nowrap {
+  white-space: nowrap;
+}
+.text-lowercase {
+  text-transform: lowercase;
+}
+.text-uppercase {
+  text-transform: uppercase;
+}
+.text-capitalize {
+  text-transform: capitalize;
+}
+.text-muted {
+  color: #777;
+}
+.text-primary {
+  color: #337ab7;
+}
+a.text-primary:hover,
+a.text-primary:focus {
+  color: #286090;
+}
+.text-success {
+  color: #3c763d;
+}
+a.text-success:hover,
+a.text-success:focus {
+  color: #2b542c;
+}
+.text-info {
+  color: #31708f;
+}
+a.text-info:hover,
+a.text-info:focus {
+  color: #245269;
+}
+.text-warning {
+  color: #8a6d3b;
+}
+a.text-warning:hover,
+a.text-warning:focus {
+  color: #66512c;
+}
+.text-danger {
+  color: #a94442;
+}
+a.text-danger:hover,
+a.text-danger:focus {
+  color: #843534;
+}
+.bg-primary {
+  color: #fff;
+  background-color: #337ab7;
+}
+a.bg-primary:hover,
+a.bg-primary:focus {
+  background-color: #286090;
+}
+.bg-success {
+  background-color: #dff0d8;
+}
+a.bg-success:hover,
+a.bg-success:focus {
+  background-color: #c1e2b3;
+}
+.bg-info {
+  background-color: #d9edf7;
+}
+a.bg-info:hover,
+a.bg-info:focus {
+  background-color: #afd9ee;
+}
+.bg-warning {
+  background-color: #fcf8e3;
+}
+a.bg-warning:hover,
+a.bg-warning:focus {
+  background-color: #f7ecb5;
+}
+.bg-danger {
+  background-color: #f2dede;
+}
+a.bg-danger:hover,
+a.bg-danger:focus {
+  background-color: #e4b9b9;
+}
 .page-header {
   padding-bottom: 9px;
   margin: 40px 0 20px;
-  border-bottom: 1px solid #eeeeee;
-}
-
+  border-bottom: 1px solid #eee;
+}
 ul,
 ol {
   margin-top: 0;
   margin-bottom: 10px;
 }
-
 ul ul,
 ol ul,
 ul ol,
 ol ol {
   margin-bottom: 0;
 }
-
 .list-unstyled {
   padding-left: 0;
   list-style: none;
 }
-
 .list-inline {
   padding-left: 0;
+  margin-left: -5px;
   list-style: none;
 }
-
 .list-inline > li {
   display: inline-block;
   padding-right: 5px;
   padding-left: 5px;
 }
-
 dl {
+  margin-top: 0;
   margin-bottom: 20px;
 }
-
 dt,
 dd {
-  line-height: 1.428571429;
-}
-
+  line-height: 1.42857143;
+}
 dt {
   font-weight: bold;
 }
-
 dd {
   margin-left: 0;
 }
-
 @media (min-width: 768px) {
   .dl-horizontal dt {
     float: left;
@@ -610,885 +1464,876 @@
   .dl-horizontal dd {
     margin-left: 180px;
   }
-  .dl-horizontal dd:before,
-  .dl-horizontal dd:after {
-    display: table;
-    content: " ";
-  }
-  .dl-horizontal dd:after {
-    clear: both;
-  }
-  .dl-horizontal dd:before,
-  .dl-horizontal dd:after {
-    display: table;
-    content: " ";
-  }
-  .dl-horizontal dd:after {
-    clear: both;
-  }
-}
-
+}
 abbr[title],
 abbr[data-original-title] {
   cursor: help;
-  border-bottom: 1px dotted #999999;
-}
-
-abbr.initialism {
+  border-bottom: 1px dotted #777;
+}
+.initialism {
   font-size: 90%;
   text-transform: uppercase;
 }
-
 blockquote {
   padding: 10px 20px;
   margin: 0 0 20px;
-  border-left: 5px solid #eeeeee;
-}
-
-blockquote p {
   font-size: 17.5px;
-  font-weight: 300;
-  line-height: 1.25;
-}
-
-blockquote p:last-child {
+  border-left: 5px solid #eee;
+}
+blockquote p:last-child,
+blockquote ul:last-child,
+blockquote ol:last-child {
   margin-bottom: 0;
 }
-
-blockquote small {
+blockquote footer,
+blockquote small,
+blockquote .small {
   display: block;
-  line-height: 1.428571429;
-  color: #999999;
-}
-
-blockquote small:before {
+  font-size: 80%;
+  line-height: 1.42857143;
+  color: #777;
+}
+blockquote footer:before,
+blockquote small:before,
+blockquote .small:before {
   content: '\2014 \00A0';
 }
-
+.blockquote-reverse,
 blockquote.pull-right {
   padding-right: 15px;
   padding-left: 0;
-  border-right: 5px solid #eeeeee;
+  text-align: right;
+  border-right: 5px solid #eee;
   border-left: 0;
 }
-
-blockquote.pull-right p,
-blockquote.pull-right small {
-  text-align: right;
-}
-
-blockquote.pull-right small:before {
+.blockquote-reverse footer:before,
+blockquote.pull-right footer:before,
+.blockquote-reverse small:before,
+blockquote.pull-right small:before,
+.blockquote-reverse .small:before,
+blockquote.pull-right .small:before {
   content: '';
 }
-
-blockquote.pull-right small:after {
+.blockquote-reverse footer:after,
+blockquote.pull-right footer:after,
+.blockquote-reverse small:after,
+blockquote.pull-right small:after,
+.blockquote-reverse .small:after,
+blockquote.pull-right .small:after {
   content: '\00A0 \2014';
 }
-
-q:before,
-q:after,
-blockquote:before,
-blockquote:after {
-  content: "";
-}
-
 address {
-  display: block;
   margin-bottom: 20px;
   font-style: normal;
-  line-height: 1.428571429;
-}
-
+  line-height: 1.42857143;
+}
 code,
-pre {
-  font-family: Monaco, Menlo, Consolas, "Courier New", monospace;
-}
-
+kbd,
+pre,
+samp {
+  font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
+}
 code {
   padding: 2px 4px;
   font-size: 90%;
   color: #c7254e;
-  white-space: nowrap;
   background-color: #f9f2f4;
   border-radius: 4px;
 }
-
+kbd {
+  padding: 2px 4px;
+  font-size: 90%;
+  color: #fff;
+  background-color: #333;
+  border-radius: 3px;
+  -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
+          box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
+}
+kbd kbd {
+  padding: 0;
+  font-size: 100%;
+  font-weight: bold;
+  -webkit-box-shadow: none;
+          box-shadow: none;
+}
 pre {
   display: block;
   padding: 9.5px;
   margin: 0 0 10px;
   font-size: 13px;
-  line-height: 1.428571429;
-  color: #333333;
+  line-height: 1.42857143;
+  color: #333;
   word-break: break-all;
   word-wrap: break-word;
   background-color: #f5f5f5;
-  border: 1px solid #cccccc;
+  border: 1px solid #ccc;
   border-radius: 4px;
 }
-
-pre.prettyprint {
-  margin-bottom: 20px;
-}
-
 pre code {
   padding: 0;
   font-size: inherit;
   color: inherit;
   white-space: pre-wrap;
   background-color: transparent;
-  border: 0;
-}
-
+  border-radius: 0;
+}
 .pre-scrollable {
   max-height: 340px;
   overflow-y: scroll;
 }
-
 .container {
   padding-right: 15px;
   padding-left: 15px;
   margin-right: auto;
   margin-left: auto;
 }
-
-.container:before,
-.container:after {
-  display: table;
-  content: " ";
-}
-
-.container:after {
-  clear: both;
-}
-
-.container:before,
-.container:after {
-  display: table;
-  content: " ";
-}
-
-.container:after {
-  clear: both;
-}
-
+@media (min-width: 768px) {
+  .container {
+    width: 750px;
+  }
+}
+@media (min-width: 992px) {
+  .container {
+    width: 970px;
+  }
+}
+@media (min-width: 1200px) {
+  .container {
+    width: 1170px;
+  }
+}
+.container-fluid {
+  padding-right: 15px;
+  padding-left: 15px;
+  margin-right: auto;
+  margin-left: auto;
+}
 .row {
   margin-right: -15px;
   margin-left: -15px;
 }
-
-.row:before,
-.row:after {
-  display: table;
-  content: " ";
-}
-
-.row:after {
-  clear: both;
-}
-
-.row:before,
-.row:after {
-  display: table;
-  content: " ";
-}
-
-.row:after {
-  clear: both;
-}
-
-.col-xs-1,
-.col-xs-2,
-.col-xs-3,
-.col-xs-4,
-.col-xs-5,
-.col-xs-6,
-.col-xs-7,
-.col-xs-8,
-.col-xs-9,
-.col-xs-10,
-.col-xs-11,
-.col-xs-12,
-.col-sm-1,
-.col-sm-2,
-.col-sm-3,
-.col-sm-4,
-.col-sm-5,
-.col-sm-6,
-.col-sm-7,
-.col-sm-8,
-.col-sm-9,
-.col-sm-10,
-.col-sm-11,
-.col-sm-12,
-.col-md-1,
-.col-md-2,
-.col-md-3,
-.col-md-4,
-.col-md-5,
-.col-md-6,
-.col-md-7,
-.col-md-8,
-.col-md-9,
-.col-md-10,
-.col-md-11,
-.col-md-12,
-.col-lg-1,
-.col-lg-2,
-.col-lg-3,
-.col-lg-4,
-.col-lg-5,
-.col-lg-6,
-.col-lg-7,
-.col-lg-8,
-.col-lg-9,
-.col-lg-10,
-.col-lg-11,
-.col-lg-12 {
+.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
   position: relative;
   min-height: 1px;
   padding-right: 15px;
   padding-left: 15px;
 }
-
-.col-xs-1,
-.col-xs-2,
-.col-xs-3,
-.col-xs-4,
-.col-xs-5,
-.col-xs-6,
-.col-xs-7,
-.col-xs-8,
-.col-xs-9,
-.col-xs-10,
-.col-xs-11 {
+.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12 {
   float: left;
 }
-
-.col-xs-1 {
-  width: 8.333333333333332%;
-}
-
-.col-xs-2 {
-  width: 16.666666666666664%;
-}
-
-.col-xs-3 {
-  width: 25%;
-}
-
-.col-xs-4 {
-  width: 33.33333333333333%;
-}
-
-.col-xs-5 {
-  width: 41.66666666666667%;
-}
-
+.col-xs-12 {
+  width: 100%;
+}
+.col-xs-11 {
+  width: 91.66666667%;
+}
+.col-xs-10 {
+  width: 83.33333333%;
+}
+.col-xs-9 {
+  width: 75%;
+}
+.col-xs-8 {
+  width: 66.66666667%;
+}
+.col-xs-7 {
+  width: 58.33333333%;
+}
 .col-xs-6 {
   width: 50%;
 }
-
-.col-xs-7 {
-  width: 58.333333333333336%;
-}
-
-.col-xs-8 {
-  width: 66.66666666666666%;
-}
-
-.col-xs-9 {
-  width: 75%;
-}
-
-.col-xs-10 {
-  width: 83.33333333333334%;
-}
-
-.col-xs-11 {
-  width: 91.66666666666666%;
-}
-
-.col-xs-12 {
-  width: 100%;
-}
-
+.col-xs-5 {
+  width: 41.66666667%;
+}
+.col-xs-4 {
+  width: 33.33333333%;
+}
+.col-xs-3 {
+  width: 25%;
+}
+.col-xs-2 {
+  width: 16.66666667%;
+}
+.col-xs-1 {
+  width: 8.33333333%;
+}
+.col-xs-pull-12 {
+  right: 100%;
+}
+.col-xs-pull-11 {
+  right: 91.66666667%;
+}
+.col-xs-pull-10 {
+  right: 83.33333333%;
+}
+.col-xs-pull-9 {
+  right: 75%;
+}
+.col-xs-pull-8 {
+  right: 66.66666667%;
+}
+.col-xs-pull-7 {
+  right: 58.33333333%;
+}
+.col-xs-pull-6 {
+  right: 50%;
+}
+.col-xs-pull-5 {
+  right: 41.66666667%;
+}
+.col-xs-pull-4 {
+  right: 33.33333333%;
+}
+.col-xs-pull-3 {
+  right: 25%;
+}
+.col-xs-pull-2 {
+  right: 16.66666667%;
+}
+.col-xs-pull-1 {
+  right: 8.33333333%;
+}
+.col-xs-pull-0 {
+  right: auto;
+}
+.col-xs-push-12 {
+  left: 100%;
+}
+.col-xs-push-11 {
+  left: 91.66666667%;
+}
+.col-xs-push-10 {
+  left: 83.33333333%;
+}
+.col-xs-push-9 {
+  left: 75%;
+}
+.col-xs-push-8 {
+  left: 66.66666667%;
+}
+.col-xs-push-7 {
+  left: 58.33333333%;
+}
+.col-xs-push-6 {
+  left: 50%;
+}
+.col-xs-push-5 {
+  left: 41.66666667%;
+}
+.col-xs-push-4 {
+  left: 33.33333333%;
+}
+.col-xs-push-3 {
+  left: 25%;
+}
+.col-xs-push-2 {
+  left: 16.66666667%;
+}
+.col-xs-push-1 {
+  left: 8.33333333%;
+}
+.col-xs-push-0 {
+  left: auto;
+}
+.col-xs-offset-12 {
+  margin-left: 100%;
+}
+.col-xs-offset-11 {
+  margin-left: 91.66666667%;
+}
+.col-xs-offset-10 {
+  margin-left: 83.33333333%;
+}
+.col-xs-offset-9 {
+  margin-left: 75%;
+}
+.col-xs-offset-8 {
+  margin-left: 66.66666667%;
+}
+.col-xs-offset-7 {
+  margin-left: 58.33333333%;
+}
+.col-xs-offset-6 {
+  margin-left: 50%;
+}
+.col-xs-offset-5 {
+  margin-left: 41.66666667%;
+}
+.col-xs-offset-4 {
+  margin-left: 33.33333333%;
+}
+.col-xs-offset-3 {
+  margin-left: 25%;
+}
+.col-xs-offset-2 {
+  margin-left: 16.66666667%;
+}
+.col-xs-offset-1 {
+  margin-left: 8.33333333%;
+}
+.col-xs-offset-0 {
+  margin-left: 0;
+}
 @media (min-width: 768px) {
-  .container {
-    max-width: 750px;
-  }
-  .col-sm-1,
-  .col-sm-2,
-  .col-sm-3,
-  .col-sm-4,
-  .col-sm-5,
-  .col-sm-6,
-  .col-sm-7,
-  .col-sm-8,
-  .col-sm-9,
-  .col-sm-10,
+  .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 {
+    float: left;
+  }
+  .col-sm-12 {
+    width: 100%;
+  }
   .col-sm-11 {
-    float: left;
-  }
-  .col-sm-1 {
-    width: 8.333333333333332%;
-  }
-  .col-sm-2 {
-    width: 16.666666666666664%;
+    width: 91.66666667%;
+  }
+  .col-sm-10 {
+    width: 83.33333333%;
+  }
+  .col-sm-9 {
+    width: 75%;
+  }
+  .col-sm-8 {
+    width: 66.66666667%;
+  }
+  .col-sm-7 {
+    width: 58.33333333%;
+  }
+  .col-sm-6 {
+    width: 50%;
+  }
+  .col-sm-5 {
+    width: 41.66666667%;
+  }
+  .col-sm-4 {
+    width: 33.33333333%;
   }
   .col-sm-3 {
     width: 25%;
   }
-  .col-sm-4 {
-    width: 33.33333333333333%;
-  }
-  .col-sm-5 {
-    width: 41.66666666666667%;
-  }
-  .col-sm-6 {
-    width: 50%;
-  }
-  .col-sm-7 {
-    width: 58.333333333333336%;
-  }
-  .col-sm-8 {
-    width: 66.66666666666666%;
-  }
-  .col-sm-9 {
-    width: 75%;
-  }
-  .col-sm-10 {
-    width: 83.33333333333334%;
-  }
-  .col-sm-11 {
-    width: 91.66666666666666%;
-  }
-  .col-sm-12 {
-    width: 100%;
-  }
-  .col-sm-push-1 {
-    left: 8.333333333333332%;
-  }
-  .col-sm-push-2 {
-    left: 16.666666666666664%;
-  }
-  .col-sm-push-3 {
-    left: 25%;
-  }
-  .col-sm-push-4 {
-    left: 33.33333333333333%;
-  }
-  .col-sm-push-5 {
-    left: 41.66666666666667%;
-  }
-  .col-sm-push-6 {
-    left: 50%;
-  }
-  .col-sm-push-7 {
-    left: 58.333333333333336%;
-  }
-  .col-sm-push-8 {
-    left: 66.66666666666666%;
+  .col-sm-2 {
+    width: 16.66666667%;
+  }
+  .col-sm-1 {
+    width: 8.33333333%;
+  }
+  .col-sm-pull-12 {
+    right: 100%;
+  }
+  .col-sm-pull-11 {
+    right: 91.66666667%;
+  }
+  .col-sm-pull-10 {
+    right: 83.33333333%;
+  }
+  .col-sm-pull-9 {
+    right: 75%;
+  }
+  .col-sm-pull-8 {
+    right: 66.66666667%;
+  }
+  .col-sm-pull-7 {
+    right: 58.33333333%;
+  }
+  .col-sm-pull-6 {
+    right: 50%;
+  }
+  .col-sm-pull-5 {
+    right: 41.66666667%;
+  }
+  .col-sm-pull-4 {
+    right: 33.33333333%;
+  }
+  .col-sm-pull-3 {
+    right: 25%;
+  }
+  .col-sm-pull-2 {
+    right: 16.66666667%;
+  }
+  .col-sm-pull-1 {
+    right: 8.33333333%;
+  }
+  .col-sm-pull-0 {
+    right: auto;
+  }
+  .col-sm-push-12 {
+    left: 100%;
+  }
+  .col-sm-push-11 {
+    left: 91.66666667%;
+  }
+  .col-sm-push-10 {
+    left: 83.33333333%;
   }
   .col-sm-push-9 {
     left: 75%;
   }
-  .col-sm-push-10 {
-    left: 83.33333333333334%;
-  }
-  .col-sm-push-11 {
-    left: 91.66666666666666%;
-  }
-  .col-sm-pull-1 {
-    right: 8.333333333333332%;
-  }
-  .col-sm-pull-2 {
-    right: 16.666666666666664%;
-  }
-  .col-sm-pull-3 {
-    right: 25%;
-  }
-  .col-sm-pull-4 {
-    right: 33.33333333333333%;
-  }
-  .col-sm-pull-5 {
-    right: 41.66666666666667%;
-  }
-  .col-sm-pull-6 {
-    right: 50%;
-  }
-  .col-sm-pull-7 {
-    right: 58.333333333333336%;
-  }
-  .col-sm-pull-8 {
-    right: 66.66666666666666%;
-  }
-  .col-sm-pull-9 {
-    right: 75%;
-  }
-  .col-sm-pull-10 {
-    right: 83.33333333333334%;
-  }
-  .col-sm-pull-11 {
-    right: 91.66666666666666%;
-  }
-  .col-sm-offset-1 {
-    margin-left: 8.333333333333332%;
-  }
-  .col-sm-offset-2 {
-    margin-left: 16.666666666666664%;
-  }
-  .col-sm-offset-3 {
-    margin-left: 25%;
-  }
-  .col-sm-offset-4 {
-    margin-left: 33.33333333333333%;
-  }
-  .col-sm-offset-5 {
-    margin-left: 41.66666666666667%;
-  }
-  .col-sm-offset-6 {
-    margin-left: 50%;
-  }
-  .col-sm-offset-7 {
-    margin-left: 58.333333333333336%;
-  }
-  .col-sm-offset-8 {
-    margin-left: 66.66666666666666%;
+  .col-sm-push-8 {
+    left: 66.66666667%;
+  }
+  .col-sm-push-7 {
+    left: 58.33333333%;
+  }
+  .col-sm-push-6 {
+    left: 50%;
+  }
+  .col-sm-push-5 {
+    left: 41.66666667%;
+  }
+  .col-sm-push-4 {
+    left: 33.33333333%;
+  }
+  .col-sm-push-3 {
+    left: 25%;
+  }
+  .col-sm-push-2 {
+    left: 16.66666667%;
+  }
+  .col-sm-push-1 {
+    left: 8.33333333%;
+  }
+  .col-sm-push-0 {
+    left: auto;
+  }
+  .col-sm-offset-12 {
+    margin-left: 100%;
+  }
+  .col-sm-offset-11 {
+    margin-left: 91.66666667%;
+  }
+  .col-sm-offset-10 {
+    margin-left: 83.33333333%;
   }
   .col-sm-offset-9 {
     margin-left: 75%;
   }
-  .col-sm-offset-10 {
-    margin-left: 83.33333333333334%;
-  }
-  .col-sm-offset-11 {
-    margin-left: 91.66666666666666%;
-  }
-}
-
+  .col-sm-offset-8 {
+    margin-left: 66.66666667%;
+  }
+  .col-sm-offset-7 {
+    margin-left: 58.33333333%;
+  }
+  .col-sm-offset-6 {
+    margin-left: 50%;
+  }
+  .col-sm-offset-5 {
+    margin-left: 41.66666667%;
+  }
+  .col-sm-offset-4 {
+    margin-left: 33.33333333%;
+  }
+  .col-sm-offset-3 {
+    margin-left: 25%;
+  }
+  .col-sm-offset-2 {
+    margin-left: 16.66666667%;
+  }
+  .col-sm-offset-1 {
+    margin-left: 8.33333333%;
+  }
+  .col-sm-offset-0 {
+    margin-left: 0;
+  }
+}
 @media (min-width: 992px) {
-  .container {
-    max-width: 970px;
-  }
-  .col-md-1,
-  .col-md-2,
-  .col-md-3,
-  .col-md-4,
-  .col-md-5,
-  .col-md-6,
-  .col-md-7,
-  .col-md-8,
-  .col-md-9,
-  .col-md-10,
-  .col-md-11 {
+  .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {
     float: left;
   }
-  .col-md-1 {
-    width: 8.333333333333332%;
-  }
-  .col-md-2 {
-    width: 16.666666666666664%;
-  }
-  .col-md-3 {
-    width: 25%;
-  }
-  .col-md-4 {
-    width: 33.33333333333333%;
-  }
-  .col-md-5 {
-    width: 41.66666666666667%;
+  .col-md-12 {
+    width: 100%;
+  }
+  .col-md-11 {
+    width: 91.66666667%;
+  }
+  .col-md-10 {
+    width: 83.33333333%;
+  }
+  .col-md-9 {
+    width: 75%;
+  }
+  .col-md-8 {
+    width: 66.66666667%;
+  }
+  .col-md-7 {
+    width: 58.33333333%;
   }
   .col-md-6 {
     width: 50%;
   }
-  .col-md-7 {
-    width: 58.333333333333336%;
-  }
-  .col-md-8 {
-    width: 66.66666666666666%;
-  }
-  .col-md-9 {
-    width: 75%;
-  }
-  .col-md-10 {
-    width: 83.33333333333334%;
-  }
-  .col-md-11 {
-    width: 91.66666666666666%;
-  }
-  .col-md-12 {
-    width: 100%;
-  }
-  .col-md-push-0 {
-    left: auto;
-  }
-  .col-md-push-1 {
-    left: 8.333333333333332%;
-  }
-  .col-md-push-2 {
-    left: 16.666666666666664%;
-  }
-  .col-md-push-3 {
-    left: 25%;
-  }
-  .col-md-push-4 {
-    left: 33.33333333333333%;
-  }
-  .col-md-push-5 {
-    left: 41.66666666666667%;
-  }
-  .col-md-push-6 {
-    left: 50%;
-  }
-  .col-md-push-7 {
-    left: 58.333333333333336%;
-  }
-  .col-md-push-8 {
-    left: 66.66666666666666%;
+  .col-md-5 {
+    width: 41.66666667%;
+  }
+  .col-md-4 {
+    width: 33.33333333%;
+  }
+  .col-md-3 {
+    width: 25%;
+  }
+  .col-md-2 {
+    width: 16.66666667%;
+  }
+  .col-md-1 {
+    width: 8.33333333%;
+  }
+  .col-md-pull-12 {
+    right: 100%;
+  }
+  .col-md-pull-11 {
+    right: 91.66666667%;
+  }
+  .col-md-pull-10 {
+    right: 83.33333333%;
+  }
+  .col-md-pull-9 {
+    right: 75%;
+  }
+  .col-md-pull-8 {
+    right: 66.66666667%;
+  }
+  .col-md-pull-7 {
+    right: 58.33333333%;
+  }
+  .col-md-pull-6 {
+    right: 50%;
+  }
+  .col-md-pull-5 {
+    right: 41.66666667%;
+  }
+  .col-md-pull-4 {
+    right: 33.33333333%;
+  }
+  .col-md-pull-3 {
+    right: 25%;
+  }
+  .col-md-pull-2 {
+    right: 16.66666667%;
+  }
+  .col-md-pull-1 {
+    right: 8.33333333%;
+  }
+  .col-md-pull-0 {
+    right: auto;
+  }
+  .col-md-push-12 {
+    left: 100%;
+  }
+  .col-md-push-11 {
+    left: 91.66666667%;
+  }
+  .col-md-push-10 {
+    left: 83.33333333%;
   }
   .col-md-push-9 {
     left: 75%;
   }
-  .col-md-push-10 {
-    left: 83.33333333333334%;
-  }
-  .col-md-push-11 {
-    left: 91.66666666666666%;
-  }
-  .col-md-pull-0 {
-    right: auto;
-  }
-  .col-md-pull-1 {
-    right: 8.333333333333332%;
-  }
-  .col-md-pull-2 {
-    right: 16.666666666666664%;
-  }
-  .col-md-pull-3 {
-    right: 25%;
-  }
-  .col-md-pull-4 {
-    right: 33.33333333333333%;
-  }
-  .col-md-pull-5 {
-    right: 41.66666666666667%;
-  }
-  .col-md-pull-6 {
-    right: 50%;
-  }
-  .col-md-pull-7 {
-    right: 58.333333333333336%;
-  }
-  .col-md-pull-8 {
-    right: 66.66666666666666%;
-  }
-  .col-md-pull-9 {
-    right: 75%;
-  }
-  .col-md-pull-10 {
-    right: 83.33333333333334%;
-  }
-  .col-md-pull-11 {
-    right: 91.66666666666666%;
-  }
-  .col-md-offset-0 {
-    margin-left: 0;
-  }
-  .col-md-offset-1 {
-    margin-left: 8.333333333333332%;
-  }
-  .col-md-offset-2 {
-    margin-left: 16.666666666666664%;
-  }
-  .col-md-offset-3 {
-    margin-left: 25%;
-  }
-  .col-md-offset-4 {
-    margin-left: 33.33333333333333%;
-  }
-  .col-md-offset-5 {
-    margin-left: 41.66666666666667%;
-  }
-  .col-md-offset-6 {
-    margin-left: 50%;
-  }
-  .col-md-offset-7 {
-    margin-left: 58.333333333333336%;
-  }
-  .col-md-offset-8 {
-    margin-left: 66.66666666666666%;
+  .col-md-push-8 {
+    left: 66.66666667%;
+  }
+  .col-md-push-7 {
+    left: 58.33333333%;
+  }
+  .col-md-push-6 {
+    left: 50%;
+  }
+  .col-md-push-5 {
+    left: 41.66666667%;
+  }
+  .col-md-push-4 {
+    left: 33.33333333%;
+  }
+  .col-md-push-3 {
+    left: 25%;
+  }
+  .col-md-push-2 {
+    left: 16.66666667%;
+  }
+  .col-md-push-1 {
+    left: 8.33333333%;
+  }
+  .col-md-push-0 {
+    left: auto;
+  }
+  .col-md-offset-12 {
+    margin-left: 100%;
+  }
+  .col-md-offset-11 {
+    margin-left: 91.66666667%;
+  }
+  .col-md-offset-10 {
+    margin-left: 83.33333333%;
   }
   .col-md-offset-9 {
     margin-left: 75%;
   }
-  .col-md-offset-10 {
-    margin-left: 83.33333333333334%;
-  }
-  .col-md-offset-11 {
-    margin-left: 91.66666666666666%;
-  }
-}
-
+  .col-md-offset-8 {
+    margin-left: 66.66666667%;
+  }
+  .col-md-offset-7 {
+    margin-left: 58.33333333%;
+  }
+  .col-md-offset-6 {
+    margin-left: 50%;
+  }
+  .col-md-offset-5 {
+    margin-left: 41.66666667%;
+  }
+  .col-md-offset-4 {
+    margin-left: 33.33333333%;
+  }
+  .col-md-offset-3 {
+    margin-left: 25%;
+  }
+  .col-md-offset-2 {
+    margin-left: 16.66666667%;
+  }
+  .col-md-offset-1 {
+    margin-left: 8.33333333%;
+  }
+  .col-md-offset-0 {
+    margin-left: 0;
+  }
+}
 @media (min-width: 1200px) {
-  .container {
-    max-width: 1170px;
-  }
-  .col-lg-1,
-  .col-lg-2,
-  .col-lg-3,
-  .col-lg-4,
-  .col-lg-5,
-  .col-lg-6,
-  .col-lg-7,
-  .col-lg-8,
-  .col-lg-9,
-  .col-lg-10,
+  .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 {
+    float: left;
+  }
+  .col-lg-12 {
+    width: 100%;
+  }
   .col-lg-11 {
-    float: left;
-  }
-  .col-lg-1 {
-    width: 8.333333333333332%;
-  }
-  .col-lg-2 {
-    width: 16.666666666666664%;
+    width: 91.66666667%;
+  }
+  .col-lg-10 {
+    width: 83.33333333%;
+  }
+  .col-lg-9 {
+    width: 75%;
+  }
+  .col-lg-8 {
+    width: 66.66666667%;
+  }
+  .col-lg-7 {
+    width: 58.33333333%;
+  }
+  .col-lg-6 {
+    width: 50%;
+  }
+  .col-lg-5 {
+    width: 41.66666667%;
+  }
+  .col-lg-4 {
+    width: 33.33333333%;
   }
   .col-lg-3 {
     width: 25%;
   }
-  .col-lg-4 {
-    width: 33.33333333333333%;
-  }
-  .col-lg-5 {
-    width: 41.66666666666667%;
-  }
-  .col-lg-6 {
-    width: 50%;
-  }
-  .col-lg-7 {
-    width: 58.333333333333336%;
-  }
-  .col-lg-8 {
-    width: 66.66666666666666%;
-  }
-  .col-lg-9 {
-    width: 75%;
-  }
-  .col-lg-10 {
-    width: 83.33333333333334%;
-  }
-  .col-lg-11 {
-    width: 91.66666666666666%;
-  }
-  .col-lg-12 {
-    width: 100%;
-  }
-  .col-lg-push-0 {
-    left: auto;
-  }
-  .col-lg-push-1 {
-    left: 8.333333333333332%;
-  }
-  .col-lg-push-2 {
-    left: 16.666666666666664%;
+  .col-lg-2 {
+    width: 16.66666667%;
+  }
+  .col-lg-1 {
+    width: 8.33333333%;
+  }
+  .col-lg-pull-12 {
+    right: 100%;
+  }
+  .col-lg-pull-11 {
+    right: 91.66666667%;
+  }
+  .col-lg-pull-10 {
+    right: 83.33333333%;
+  }
+  .col-lg-pull-9 {
+    right: 75%;
+  }
+  .col-lg-pull-8 {
+    right: 66.66666667%;
+  }
+  .col-lg-pull-7 {
+    right: 58.33333333%;
+  }
+  .col-lg-pull-6 {
+    right: 50%;
+  }
+  .col-lg-pull-5 {
+    right: 41.66666667%;
+  }
+  .col-lg-pull-4 {
+    right: 33.33333333%;
+  }
+  .col-lg-pull-3 {
+    right: 25%;
+  }
+  .col-lg-pull-2 {
+    right: 16.66666667%;
+  }
+  .col-lg-pull-1 {
+    right: 8.33333333%;
+  }
+  .col-lg-pull-0 {
+    right: auto;
+  }
+  .col-lg-push-12 {
+    left: 100%;
+  }
+  .col-lg-push-11 {
+    left: 91.66666667%;
+  }
+  .col-lg-push-10 {
+    left: 83.33333333%;
+  }
+  .col-lg-push-9 {
+    left: 75%;
+  }
+  .col-lg-push-8 {
+    left: 66.66666667%;
+  }
+  .col-lg-push-7 {
+    left: 58.33333333%;
+  }
+  .col-lg-push-6 {
+    left: 50%;
+  }
+  .col-lg-push-5 {
+    left: 41.66666667%;
+  }
+  .col-lg-push-4 {
+    left: 33.33333333%;
   }
   .col-lg-push-3 {
     left: 25%;
   }
-  .col-lg-push-4 {
-    left: 33.33333333333333%;
-  }
-  .col-lg-push-5 {
-    left: 41.66666666666667%;
-  }
-  .col-lg-push-6 {
-    left: 50%;
-  }
-  .col-lg-push-7 {
-    left: 58.333333333333336%;
-  }
-  .col-lg-push-8 {
-    left: 66.66666666666666%;
-  }
-  .col-lg-push-9 {
-    left: 75%;
-  }
-  .col-lg-push-10 {
-    left: 83.33333333333334%;
-  }
-  .col-lg-push-11 {
-    left: 91.66666666666666%;
-  }
-  .col-lg-pull-0 {
-    right: auto;
-  }
-  .col-lg-pull-1 {
-    right: 8.333333333333332%;
-  }
-  .col-lg-pull-2 {
-    right: 16.666666666666664%;
-  }
-  .col-lg-pull-3 {
-    right: 25%;
-  }
-  .col-lg-pull-4 {
-    right: 33.33333333333333%;
-  }
-  .col-lg-pull-5 {
-    right: 41.66666666666667%;
-  }
-  .col-lg-pull-6 {
-    right: 50%;
-  }
-  .col-lg-pull-7 {
-    right: 58.333333333333336%;
-  }
-  .col-lg-pull-8 {
-    right: 66.66666666666666%;
-  }
-  .col-lg-pull-9 {
-    right: 75%;
-  }
-  .col-lg-pull-10 {
-    right: 83.33333333333334%;
-  }
-  .col-lg-pull-11 {
-    right: 91.66666666666666%;
-  }
-  .col-lg-offset-0 {
-    margin-left: 0;
-  }
-  .col-lg-offset-1 {
-    margin-left: 8.333333333333332%;
-  }
-  .col-lg-offset-2 {
-    margin-left: 16.666666666666664%;
-  }
-  .col-lg-offset-3 {
-    margin-left: 25%;
-  }
-  .col-lg-offset-4 {
-    margin-left: 33.33333333333333%;
-  }
-  .col-lg-offset-5 {
-    margin-left: 41.66666666666667%;
+  .col-lg-push-2 {
+    left: 16.66666667%;
+  }
+  .col-lg-push-1 {
+    left: 8.33333333%;
+  }
+  .col-lg-push-0 {
+    left: auto;
+  }
+  .col-lg-offset-12 {
+    margin-left: 100%;
+  }
+  .col-lg-offset-11 {
+    margin-left: 91.66666667%;
+  }
+  .col-lg-offset-10 {
+    margin-left: 83.33333333%;
+  }
+  .col-lg-offset-9 {
+    margin-left: 75%;
+  }
+  .col-lg-offset-8 {
+    margin-left: 66.66666667%;
+  }
+  .col-lg-offset-7 {
+    margin-left: 58.33333333%;
   }
   .col-lg-offset-6 {
     margin-left: 50%;
   }
-  .col-lg-offset-7 {
-    margin-left: 58.333333333333336%;
-  }
-  .col-lg-offset-8 {
-    margin-left: 66.66666666666666%;
-  }
-  .col-lg-offset-9 {
-    margin-left: 75%;
-  }
-  .col-lg-offset-10 {
-    margin-left: 83.33333333333334%;
-  }
-  .col-lg-offset-11 {
-    margin-left: 91.66666666666666%;
-  }
-}
-
+  .col-lg-offset-5 {
+    margin-left: 41.66666667%;
+  }
+  .col-lg-offset-4 {
+    margin-left: 33.33333333%;
+  }
+  .col-lg-offset-3 {
+    margin-left: 25%;
+  }
+  .col-lg-offset-2 {
+    margin-left: 16.66666667%;
+  }
+  .col-lg-offset-1 {
+    margin-left: 8.33333333%;
+  }
+  .col-lg-offset-0 {
+    margin-left: 0;
+  }
+}
 table {
-  max-width: 100%;
   background-color: transparent;
 }
-
+caption {
+  padding-top: 8px;
+  padding-bottom: 8px;
+  color: #777;
+  text-align: left;
+}
 th {
   text-align: left;
 }
-
 .table {
   width: 100%;
+  max-width: 100%;
   margin-bottom: 20px;
 }
-
-.table thead > tr > th,
-.table tbody > tr > th,
-.table tfoot > tr > th,
-.table thead > tr > td,
-.table tbody > tr > td,
-.table tfoot > tr > td {
+.table > thead > tr > th,
+.table > tbody > tr > th,
+.table > tfoot > tr > th,
+.table > thead > tr > td,
+.table > tbody > tr > td,
+.table > tfoot > tr > td {
   padding: 8px;
-  line-height: 1.428571429;
+  line-height: 1.42857143;
   vertical-align: top;
-  border-top: 1px solid #dddddd;
-}
-
-.table thead > tr > th {
+  border-top: 1px solid #ddd;
+}
+.table > thead > tr > th {
   vertical-align: bottom;
-  border-bottom: 2px solid #dddddd;
-}
-
-.table caption + thead tr:first-child th,
-.table colgroup + thead tr:first-child th,
-.table thead:first-child tr:first-child th,
-.table caption + thead tr:first-child td,
-.table colgroup + thead tr:first-child td,
-.table thead:first-child tr:first-child td {
+  border-bottom: 2px solid #ddd;
+}
+.table > caption + thead > tr:first-child > th,
+.table > colgroup + thead > tr:first-child > th,
+.table > thead:first-child > tr:first-child > th,
+.table > caption + thead > tr:first-child > td,
+.table > colgroup + thead > tr:first-child > td,
+.table > thead:first-child > tr:first-child > td {
   border-top: 0;
 }
-
-.table tbody + tbody {
-  border-top: 2px solid #dddddd;
-}
-
+.table > tbody + tbody {
+  border-top: 2px solid #ddd;
+}
 .table .table {
-  background-color: #ffffff;
-}
-
-.table-condensed thead > tr > th,
-.table-condensed tbody > tr > th,
-.table-condensed tfoot > tr > th,
-.table-condensed thead > tr > td,
-.table-condensed tbody > tr > td,
-.table-condensed tfoot > tr > td {
+  background-color: #fff;
+}
+.table-condensed > thead > tr > th,
+.table-condensed > tbody > tr > th,
+.table-condensed > tfoot > tr > th,
+.table-condensed > thead > tr > td,
+.table-condensed > tbody > tr > td,
+.table-condensed > tfoot > tr > td {
   padding: 5px;
 }
-
 .table-bordered {
-  border: 1px solid #dddddd;
-}
-
+  border: 1px solid #ddd;
+}
 .table-bordered > thead > tr > th,
 .table-bordered > tbody > tr > th,
 .table-bordered > tfoot > tr > th,
 .table-bordered > thead > tr > td,
 .table-bordered > tbody > tr > td,
 .table-bordered > tfoot > tr > td {
-  border: 1px solid #dddddd;
-}
-
+  border: 1px solid #ddd;
+}
 .table-bordered > thead > tr > th,
 .table-bordered > thead > tr > td {
   border-bottom-width: 2px;
 }
-
-.table-striped > tbody > tr:nth-child(odd) > td,
-.table-striped > tbody > tr:nth-child(odd) > th {
+.table-striped > tbody > tr:nth-of-type(odd) {
   background-color: #f9f9f9;
 }
-
-.table-hover > tbody > tr:hover > td,
-.table-hover > tbody > tr:hover > th {
+.table-hover > tbody > tr:hover {
   background-color: #f5f5f5;
 }
-
 table col[class*="col-"] {
+  position: static;
   display: table-column;
   float: none;
 }
-
 table td[class*="col-"],
 table th[class*="col-"] {
+  position: static;
   display: table-cell;
   float: none;
 }
-
 .table > thead > tr > td.active,
 .table > tbody > tr > td.active,
 .table > tfoot > tr > td.active,
@@ -1503,7 +2348,13 @@
 .table > tfoot > tr.active > th {
   background-color: #f5f5f5;
 }
-
+.table-hover > tbody > tr > td.active:hover,
+.table-hover > tbody > tr > th.active:hover,
+.table-hover > tbody > tr.active:hover > td,
+.table-hover > tbody > tr:hover > .active,
+.table-hover > tbody > tr.active:hover > th {
+  background-color: #e8e8e8;
+}
 .table > thead > tr > td.success,
 .table > tbody > tr > td.success,
 .table > tfoot > tr > td.success,
@@ -1517,16 +2368,56 @@
 .table > tbody > tr.success > th,
 .table > tfoot > tr.success > th {
   background-color: #dff0d8;
-  border-color: #d6e9c6;
-}
-
+}
 .table-hover > tbody > tr > td.success:hover,
 .table-hover > tbody > tr > th.success:hover,
-.table-hover > tbody > tr.success:hover > td {
+.table-hover > tbody > tr.success:hover > td,
+.table-hover > tbody > tr:hover > .success,
+.table-hover > tbody > tr.success:hover > th {
   background-color: #d0e9c6;
-  border-color: #c9e2b3;
-}
-
+}
+.table > thead > tr > td.info,
+.table > tbody > tr > td.info,
+.table > tfoot > tr > td.info,
+.table > thead > tr > th.info,
+.table > tbody > tr > th.info,
+.table > tfoot > tr > th.info,
+.table > thead > tr.info > td,
+.table > tbody > tr.info > td,
+.table > tfoot > tr.info > td,
+.table > thead > tr.info > th,
+.table > tbody > tr.info > th,
+.table > tfoot > tr.info > th {
+  background-color: #d9edf7;
+}
+.table-hover > tbody > tr > td.info:hover,
+.table-hover > tbody > tr > th.info:hover,
+.table-hover > tbody > tr.info:hover > td,
+.table-hover > tbody > tr:hover > .info,
+.table-hover > tbody > tr.info:hover > th {
+  background-color: #c4e3f3;
+}
+.table > thead > tr > td.warning,
+.table > tbody > tr > td.warning,
+.table > tfoot > tr > td.warning,
+.table > thead > tr > th.warning,
+.table > tbody > tr > th.warning,
+.table > tfoot > tr > th.warning,
+.table > thead > tr.warning > td,
+.table > tbody > tr.warning > td,
+.table > tfoot > tr.warning > td,
+.table > thead > tr.warning > th,
+.table > tbody > tr.warning > th,
+.table > tfoot > tr.warning > th {
+  background-color: #fcf8e3;
+}
+.table-hover > tbody > tr > td.warning:hover,
+.table-hover > tbody > tr > th.warning:hover,
+.table-hover > tbody > tr.warning:hover > td,
+.table-hover > tbody > tr:hover > .warning,
+.table-hover > tbody > tr.warning:hover > th {
+  background-color: #faf2cc;
+}
 .table > thead > tr > td.danger,
 .table > tbody > tr > td.danger,
 .table > tfoot > tr > td.danger,
@@ -1540,50 +2431,28 @@
 .table > tbody > tr.danger > th,
 .table > tfoot > tr.danger > th {
   background-color: #f2dede;
-  border-color: #eed3d7;
-}
-
+}
 .table-hover > tbody > tr > td.danger:hover,
 .table-hover > tbody > tr > th.danger:hover,
-.table-hover > tbody > tr.danger:hover > td {
+.table-hover > tbody > tr.danger:hover > td,
+.table-hover > tbody > tr:hover > .danger,
+.table-hover > tbody > tr.danger:hover > th {
   background-color: #ebcccc;
-  border-color: #e6c1c7;
-}
-
-.table > thead > tr > td.warning,
-.table > tbody > tr > td.warning,
-.table > tfoot > tr > td.warning,
-.table > thead > tr > th.warning,
-.table > tbody > tr > th.warning,
-.table > tfoot > tr > th.warning,
-.table > thead > tr.warning > td,
-.table > tbody > tr.warning > td,
-.table > tfoot > tr.warning > td,
-.table > thead > tr.warning > th,
-.table > tbody > tr.warning > th,
-.table > tfoot > tr.warning > th {
-  background-color: #fcf8e3;
-  border-color: #fbeed5;
-}
-
-.table-hover > tbody > tr > td.warning:hover,
-.table-hover > tbody > tr > th.warning:hover,
-.table-hover > tbody > tr.warning:hover > td {
-  background-color: #faf2cc;
-  border-color: #f8e5be;
-}
-
-@media (max-width: 768px) {
+}
+.table-responsive {
+  min-height: .01%;
+  overflow-x: auto;
+}
+@media screen and (max-width: 767px) {
   .table-responsive {
     width: 100%;
     margin-bottom: 15px;
-    overflow-x: scroll;
     overflow-y: hidden;
-    border: 1px solid #dddddd;
+    -ms-overflow-style: -ms-autohiding-scrollbar;
+    border: 1px solid #ddd;
   }
   .table-responsive > .table {
     margin-bottom: 0;
-    background-color: #fff;
   }
   .table-responsive > .table > thead > tr > th,
   .table-responsive > .table > tbody > tr > th,
@@ -1612,22 +2481,19 @@
   .table-responsive > .table-bordered > tfoot > tr > td:last-child {
     border-right: 0;
   }
-  .table-responsive > .table-bordered > thead > tr:last-child > th,
   .table-responsive > .table-bordered > tbody > tr:last-child > th,
   .table-responsive > .table-bordered > tfoot > tr:last-child > th,
-  .table-responsive > .table-bordered > thead > tr:last-child > td,
   .table-responsive > .table-bordered > tbody > tr:last-child > td,
   .table-responsive > .table-bordered > tfoot > tr:last-child > td {
     border-bottom: 0;
   }
 }
-
 fieldset {
+  min-width: 0;
   padding: 0;
   margin: 0;
   border: 0;
 }
-
 legend {
   display: block;
   width: 100%;
@@ -1635,149 +2501,166 @@
   margin-bottom: 20px;
   font-size: 21px;
   line-height: inherit;
-  color: #333333;
+  color: #333;
   border: 0;
   border-bottom: 1px solid #e5e5e5;
 }
-
 label {
   display: inline-block;
+  max-width: 100%;
   margin-bottom: 5px;
   font-weight: bold;
 }
-
 input[type="search"] {
   -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
           box-sizing: border-box;
 }
-
 input[type="radio"],
 input[type="checkbox"] {
   margin: 4px 0 0;
   margin-top: 1px \9;
-  /* IE8-9 */
-
   line-height: normal;
 }
-
 input[type="file"] {
   display: block;
 }
-
+input[type="range"] {
+  display: block;
+  width: 100%;
+}
 select[multiple],
 select[size] {
   height: auto;
 }
-
-select optgroup {
-  font-family: inherit;
-  font-size: inherit;
-  font-style: inherit;
-}
-
 input[type="file"]:focus,
 input[type="radio"]:focus,
 input[type="checkbox"]:focus {
-  outline: thin dotted #333;
   outline: 5px auto -webkit-focus-ring-color;
   outline-offset: -2px;
 }
-
-input[type="number"]::-webkit-outer-spin-button,
-input[type="number"]::-webkit-inner-spin-button {
-  height: auto;
-}
-
-.form-control:-moz-placeholder {
-  color: #999999;
-}
-
-.form-control::-moz-placeholder {
-  color: #999999;
-}
-
-.form-control:-ms-input-placeholder {
-  color: #999999;
-}
-
-.form-control::-webkit-input-placeholder {
-  color: #999999;
-}
-
+output {
+  display: block;
+  padding-top: 7px;
+  font-size: 14px;
+  line-height: 1.42857143;
+  color: #555;
+}
 .form-control {
   display: block;
   width: 100%;
   height: 34px;
   padding: 6px 12px;
   font-size: 14px;
-  line-height: 1.428571429;
-  color: #555555;
-  vertical-align: middle;
-  background-color: #ffffff;
-  border: 1px solid #cccccc;
+  line-height: 1.42857143;
+  color: #555;
+  background-color: #fff;
+  background-image: none;
+  border: 1px solid #ccc;
   border-radius: 4px;
-  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-  -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
-          transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
-}
-
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+  -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
+       -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
+          transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
+}
 .form-control:focus {
   border-color: #66afe9;
   outline: 0;
-  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
-          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
-}
-
+  -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
+          box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
+}
+.form-control::-moz-placeholder {
+  color: #999;
+  opacity: 1;
+}
+.form-control:-ms-input-placeholder {
+  color: #999;
+}
+.form-control::-webkit-input-placeholder {
+  color: #999;
+}
+.form-control::-ms-expand {
+  background-color: transparent;
+  border: 0;
+}
 .form-control[disabled],
 .form-control[readonly],
 fieldset[disabled] .form-control {
+  background-color: #eee;
+  opacity: 1;
+}
+.form-control[disabled],
+fieldset[disabled] .form-control {
   cursor: not-allowed;
-  background-color: #eeeeee;
-}
-
+}
 textarea.form-control {
   height: auto;
 }
-
+input[type="search"] {
+  -webkit-appearance: none;
+}
+@media screen and (-webkit-min-device-pixel-ratio: 0) {
+  input[type="date"].form-control,
+  input[type="time"].form-control,
+  input[type="datetime-local"].form-control,
+  input[type="month"].form-control {
+    line-height: 34px;
+  }
+  input[type="date"].input-sm,
+  input[type="time"].input-sm,
+  input[type="datetime-local"].input-sm,
+  input[type="month"].input-sm,
+  .input-group-sm input[type="date"],
+  .input-group-sm input[type="time"],
+  .input-group-sm input[type="datetime-local"],
+  .input-group-sm input[type="month"] {
+    line-height: 30px;
+  }
+  input[type="date"].input-lg,
+  input[type="time"].input-lg,
+  input[type="datetime-local"].input-lg,
+  input[type="month"].input-lg,
+  .input-group-lg input[type="date"],
+  .input-group-lg input[type="time"],
+  .input-group-lg input[type="datetime-local"],
+  .input-group-lg input[type="month"] {
+    line-height: 46px;
+  }
+}
 .form-group {
   margin-bottom: 15px;
 }
-
 .radio,
 .checkbox {
+  position: relative;
   display: block;
+  margin-top: 10px;
+  margin-bottom: 10px;
+}
+.radio label,
+.checkbox label {
   min-height: 20px;
   padding-left: 20px;
-  margin-top: 10px;
-  margin-bottom: 10px;
-  vertical-align: middle;
-}
-
-.radio label,
-.checkbox label {
-  display: inline;
   margin-bottom: 0;
   font-weight: normal;
   cursor: pointer;
 }
-
 .radio input[type="radio"],
 .radio-inline input[type="radio"],
 .checkbox input[type="checkbox"],
 .checkbox-inline input[type="checkbox"] {
-  float: left;
+  position: absolute;
+  margin-top: 4px \9;
   margin-left: -20px;
 }
-
 .radio + .radio,
 .checkbox + .checkbox {
   margin-top: -5px;
 }
-
 .radio-inline,
 .checkbox-inline {
+  position: relative;
   display: inline-block;
   padding-left: 20px;
   margin-bottom: 0;
@@ -1785,28 +2668,42 @@
   vertical-align: middle;
   cursor: pointer;
 }
-
 .radio-inline + .radio-inline,
 .checkbox-inline + .checkbox-inline {
   margin-top: 0;
   margin-left: 10px;
 }
-
 input[type="radio"][disabled],
 input[type="checkbox"][disabled],
-.radio[disabled],
-.radio-inline[disabled],
-.checkbox[disabled],
-.checkbox-inline[disabled],
+input[type="radio"].disabled,
+input[type="checkbox"].disabled,
 fieldset[disabled] input[type="radio"],
-fieldset[disabled] input[type="checkbox"],
-fieldset[disabled] .radio,
+fieldset[disabled] input[type="checkbox"] {
+  cursor: not-allowed;
+}
+.radio-inline.disabled,
+.checkbox-inline.disabled,
 fieldset[disabled] .radio-inline,
-fieldset[disabled] .checkbox,
 fieldset[disabled] .checkbox-inline {
   cursor: not-allowed;
 }
-
+.radio.disabled label,
+.checkbox.disabled label,
+fieldset[disabled] .radio label,
+fieldset[disabled] .checkbox label {
+  cursor: not-allowed;
+}
+.form-control-static {
+  min-height: 34px;
+  padding-top: 7px;
+  padding-bottom: 7px;
+  margin-bottom: 0;
+}
+.form-control-static.input-lg,
+.form-control-static.input-sm {
+  padding-right: 0;
+  padding-left: 0;
+}
 .input-sm {
   height: 30px;
   padding: 5px 10px;
@@ -1814,114 +2711,207 @@
   line-height: 1.5;
   border-radius: 3px;
 }
-
 select.input-sm {
   height: 30px;
   line-height: 30px;
 }
-
-textarea.input-sm {
+textarea.input-sm,
+select[multiple].input-sm {
+  height: auto;
+}
+.form-group-sm .form-control {
+  height: 30px;
+  padding: 5px 10px;
+  font-size: 12px;
+  line-height: 1.5;
+  border-radius: 3px;
+}
+.form-group-sm select.form-control {
+  height: 30px;
+  line-height: 30px;
+}
+.form-group-sm textarea.form-control,
+.form-group-sm select[multiple].form-control {
   height: auto;
 }
-
+.form-group-sm .form-control-static {
+  height: 30px;
+  min-height: 32px;
+  padding: 6px 10px;
+  font-size: 12px;
+  line-height: 1.5;
+}
 .input-lg {
-  height: 45px;
+  height: 46px;
+  padding: 10px 16px;
+  font-size: 18px;
+  line-height: 1.3333333;
+  border-radius: 6px;
+}
+select.input-lg {
+  height: 46px;
+  line-height: 46px;
+}
+textarea.input-lg,
+select[multiple].input-lg {
+  height: auto;
+}
+.form-group-lg .form-control {
+  height: 46px;
   padding: 10px 16px;
   font-size: 18px;
-  line-height: 1.33;
+  line-height: 1.3333333;
   border-radius: 6px;
 }
-
-select.input-lg {
-  height: 45px;
-  line-height: 45px;
-}
-
-textarea.input-lg {
+.form-group-lg select.form-control {
+  height: 46px;
+  line-height: 46px;
+}
+.form-group-lg textarea.form-control,
+.form-group-lg select[multiple].form-control {
   height: auto;
 }
-
+.form-group-lg .form-control-static {
+  height: 46px;
+  min-height: 38px;
+  padding: 11px 16px;
+  font-size: 18px;
+  line-height: 1.3333333;
+}
+.has-feedback {
+  position: relative;
+}
+.has-feedback .form-control {
+  padding-right: 42.5px;
+}
+.form-control-feedback {
+  position: absolute;
+  top: 0;
+  right: 0;
+  z-index: 2;
+  display: block;
+  width: 34px;
+  height: 34px;
+  line-height: 34px;
+  text-align: center;
+  pointer-events: none;
+}
+.input-lg + .form-control-feedback,
+.input-group-lg + .form-control-feedback,
+.form-group-lg .form-control + .form-control-feedback {
+  width: 46px;
+  height: 46px;
+  line-height: 46px;
+}
+.input-sm + .form-control-feedback,
+.input-group-sm + .form-control-feedback,
+.form-group-sm .form-control + .form-control-feedback {
+  width: 30px;
+  height: 30px;
+  line-height: 30px;
+}
+.has-success .help-block,
+.has-success .control-label,
+.has-success .radio,
+.has-success .checkbox,
+.has-success .radio-inline,
+.has-success .checkbox-inline,
+.has-success.radio label,
+.has-success.checkbox label,
+.has-success.radio-inline label,
+.has-success.checkbox-inline label {
+  color: #3c763d;
+}
+.has-success .form-control {
+  border-color: #3c763d;
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+}
+.has-success .form-control:focus {
+  border-color: #2b542c;
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
+}
+.has-success .input-group-addon {
+  color: #3c763d;
+  background-color: #dff0d8;
+  border-color: #3c763d;
+}
+.has-success .form-control-feedback {
+  color: #3c763d;
+}
 .has-warning .help-block,
-.has-warning .control-label {
-  color: #c09853;
-}
-
+.has-warning .control-label,
+.has-warning .radio,
+.has-warning .checkbox,
+.has-warning .radio-inline,
+.has-warning .checkbox-inline,
+.has-warning.radio label,
+.has-warning.checkbox label,
+.has-warning.radio-inline label,
+.has-warning.checkbox-inline label {
+  color: #8a6d3b;
+}
 .has-warning .form-control {
-  border-color: #c09853;
-  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-}
-
+  border-color: #8a6d3b;
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+}
 .has-warning .form-control:focus {
-  border-color: #a47e3c;
-  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e;
-          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e;
-}
-
+  border-color: #66512c;
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
+}
 .has-warning .input-group-addon {
-  color: #c09853;
+  color: #8a6d3b;
   background-color: #fcf8e3;
-  border-color: #c09853;
-}
-
+  border-color: #8a6d3b;
+}
+.has-warning .form-control-feedback {
+  color: #8a6d3b;
+}
 .has-error .help-block,
-.has-error .control-label {
-  color: #b94a48;
-}
-
+.has-error .control-label,
+.has-error .radio,
+.has-error .checkbox,
+.has-error .radio-inline,
+.has-error .checkbox-inline,
+.has-error.radio label,
+.has-error.checkbox label,
+.has-error.radio-inline label,
+.has-error.checkbox-inline label {
+  color: #a94442;
+}
 .has-error .form-control {
-  border-color: #b94a48;
-  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-}
-
+  border-color: #a94442;
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+}
 .has-error .form-control:focus {
-  border-color: #953b39;
-  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392;
-          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392;
-}
-
+  border-color: #843534;
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
+}
 .has-error .input-group-addon {
-  color: #b94a48;
+  color: #a94442;
   background-color: #f2dede;
-  border-color: #b94a48;
-}
-
-.has-success .help-block,
-.has-success .control-label {
-  color: #468847;
-}
-
-.has-success .form-control {
-  border-color: #468847;
-  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-}
-
-.has-success .form-control:focus {
-  border-color: #356635;
-  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b;
-          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b;
-}
-
-.has-success .input-group-addon {
-  color: #468847;
-  background-color: #dff0d8;
-  border-color: #468847;
-}
-
-.form-control-static {
-  padding-top: 7px;
-  margin-bottom: 0;
-}
-
+  border-color: #a94442;
+}
+.has-error .form-control-feedback {
+  color: #a94442;
+}
+.has-feedback label ~ .form-control-feedback {
+  top: 25px;
+}
+.has-feedback label.sr-only ~ .form-control-feedback {
+  top: 0;
+}
 .help-block {
   display: block;
   margin-top: 5px;
   margin-bottom: 10px;
   color: #737373;
 }
-
 @media (min-width: 768px) {
   .form-inline .form-group {
     display: inline-block;
@@ -1930,22 +2920,48 @@
   }
   .form-inline .form-control {
     display: inline-block;
+    width: auto;
+    vertical-align: middle;
+  }
+  .form-inline .form-control-static {
+    display: inline-block;
+  }
+  .form-inline .input-group {
+    display: inline-table;
+    vertical-align: middle;
+  }
+  .form-inline .input-group .input-group-addon,
+  .form-inline .input-group .input-group-btn,
+  .form-inline .input-group .form-control {
+    width: auto;
+  }
+  .form-inline .input-group > .form-control {
+    width: 100%;
+  }
+  .form-inline .control-label {
+    margin-bottom: 0;
+    vertical-align: middle;
   }
   .form-inline .radio,
   .form-inline .checkbox {
     display: inline-block;
-    padding-left: 0;
     margin-top: 0;
     margin-bottom: 0;
+    vertical-align: middle;
+  }
+  .form-inline .radio label,
+  .form-inline .checkbox label {
+    padding-left: 0;
   }
   .form-inline .radio input[type="radio"],
   .form-inline .checkbox input[type="checkbox"] {
-    float: none;
+    position: relative;
     margin-left: 0;
   }
-}
-
-.form-horizontal .control-label,
+  .form-inline .has-feedback .form-control-feedback {
+    top: 0;
+  }
+}
 .form-horizontal .radio,
 .form-horizontal .checkbox,
 .form-horizontal .radio-inline,
@@ -1954,1273 +2970,553 @@
   margin-top: 0;
   margin-bottom: 0;
 }
-
+.form-horizontal .radio,
+.form-horizontal .checkbox {
+  min-height: 27px;
+}
 .form-horizontal .form-group {
   margin-right: -15px;
   margin-left: -15px;
 }
-
-.form-horizontal .form-group:before,
-.form-horizontal .form-group:after {
-  display: table;
-  content: " ";
-}
-
-.form-horizontal .form-group:after {
-  clear: both;
-}
-
-.form-horizontal .form-group:before,
-.form-horizontal .form-group:after {
-  display: table;
-  content: " ";
-}
-
-.form-horizontal .form-group:after {
-  clear: both;
-}
-
 @media (min-width: 768px) {
   .form-horizontal .control-label {
+    padding-top: 7px;
+    margin-bottom: 0;
     text-align: right;
   }
 }
-
+.form-horizontal .has-feedback .form-control-feedback {
+  right: 15px;
+}
+@media (min-width: 768px) {
+  .form-horizontal .form-group-lg .control-label {
+    padding-top: 11px;
+    font-size: 18px;
+  }
+}
+@media (min-width: 768px) {
+  .form-horizontal .form-group-sm .control-label {
+    padding-top: 6px;
+    font-size: 12px;
+  }
+}
 .btn {
   display: inline-block;
   padding: 6px 12px;
   margin-bottom: 0;
   font-size: 14px;
   font-weight: normal;
-  line-height: 1.428571429;
+  line-height: 1.42857143;
   text-align: center;
   white-space: nowrap;
   vertical-align: middle;
+  -ms-touch-action: manipulation;
+      touch-action: manipulation;
   cursor: pointer;
-  border: 1px solid transparent;
-  border-radius: 4px;
   -webkit-user-select: none;
      -moz-user-select: none;
       -ms-user-select: none;
-       -o-user-select: none;
           user-select: none;
-}
-
-.btn:focus {
-  outline: thin dotted #333;
+  background-image: none;
+  border: 1px solid transparent;
+  border-radius: 4px;
+}
+.btn:focus,
+.btn:active:focus,
+.btn.active:focus,
+.btn.focus,
+.btn:active.focus,
+.btn.active.focus {
   outline: 5px auto -webkit-focus-ring-color;
   outline-offset: -2px;
 }
-
 .btn:hover,
-.btn:focus {
-  color: #333333;
+.btn:focus,
+.btn.focus {
+  color: #333;
   text-decoration: none;
 }
-
 .btn:active,
 .btn.active {
   background-image: none;
   outline: 0;
-  -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
-          box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
-}
-
+  -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
+          box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
+}
 .btn.disabled,
 .btn[disabled],
 fieldset[disabled] .btn {
-  pointer-events: none;
   cursor: not-allowed;
-  opacity: 0.65;
   filter: alpha(opacity=65);
   -webkit-box-shadow: none;
           box-shadow: none;
-}
-
+  opacity: .65;
+}
+a.btn.disabled,
+fieldset[disabled] a.btn {
+  pointer-events: none;
+}
 .btn-default {
-  color: #333333;
-  background-color: #ffffff;
-  border-color: #cccccc;
-}
-
-.btn-default:hover,
+  color: #333;
+  background-color: #fff;
+  border-color: #ccc;
+}
 .btn-default:focus,
+.btn-default.focus {
+  color: #333;
+  background-color: #e6e6e6;
+  border-color: #8c8c8c;
+}
+.btn-default:hover {
+  color: #333;
+  background-color: #e6e6e6;
+  border-color: #adadad;
+}
 .btn-default:active,
 .btn-default.active,
-.open .dropdown-toggle.btn-default {
-  color: #333333;
-  background-color: #ebebeb;
+.open > .dropdown-toggle.btn-default {
+  color: #333;
+  background-color: #e6e6e6;
   border-color: #adadad;
 }
-
+.btn-default:active:hover,
+.btn-default.active:hover,
+.open > .dropdown-toggle.btn-default:hover,
+.btn-default:active:focus,
+.btn-default.active:focus,
+.open > .dropdown-toggle.btn-default:focus,
+.btn-default:active.focus,
+.btn-default.active.focus,
+.open > .dropdown-toggle.btn-default.focus {
+  color: #333;
+  background-color: #d4d4d4;
+  border-color: #8c8c8c;
+}
 .btn-default:active,
 .btn-default.active,
-.open .dropdown-toggle.btn-default {
+.open > .dropdown-toggle.btn-default {
   background-image: none;
 }
-
-.btn-default.disabled,
-.btn-default[disabled],
-fieldset[disabled] .btn-default,
 .btn-default.disabled:hover,
 .btn-default[disabled]:hover,
 fieldset[disabled] .btn-default:hover,
 .btn-default.disabled:focus,
 .btn-default[disabled]:focus,
 fieldset[disabled] .btn-default:focus,
-.btn-default.disabled:active,
-.btn-default[disabled]:active,
-fieldset[disabled] .btn-default:active,
-.btn-default.disabled.active,
-.btn-default[disabled].active,
-fieldset[disabled] .btn-default.active {
-  background-color: #ffffff;
-  border-color: #cccccc;
-}
-
+.btn-default.disabled.focus,
+.btn-default[disabled].focus,
+fieldset[disabled] .btn-default.focus {
+  background-color: #fff;
+  border-color: #ccc;
+}
+.btn-default .badge {
+  color: #fff;
+  background-color: #333;
+}
 .btn-primary {
-  color: #ffffff;
-  background-color: #428bca;
-  border-color: #357ebd;
-}
-
-.btn-primary:hover,
+  color: #fff;
+  background-color: #337ab7;
+  border-color: #2e6da4;
+}
 .btn-primary:focus,
+.btn-primary.focus {
+  color: #fff;
+  background-color: #286090;
+  border-color: #122b40;
+}
+.btn-primary:hover {
+  color: #fff;
+  background-color: #286090;
+  border-color: #204d74;
+}
 .btn-primary:active,
 .btn-primary.active,
-.open .dropdown-toggle.btn-primary {
-  color: #ffffff;
-  background-color: #3276b1;
-  border-color: #285e8e;
-}
-
+.open > .dropdown-toggle.btn-primary {
+  color: #fff;
+  background-color: #286090;
+  border-color: #204d74;
+}
+.btn-primary:active:hover,
+.btn-primary.active:hover,
+.open > .dropdown-toggle.btn-primary:hover,
+.btn-primary:active:focus,
+.btn-primary.active:focus,
+.open > .dropdown-toggle.btn-primary:focus,
+.btn-primary:active.focus,
+.btn-primary.active.focus,
+.open > .dropdown-toggle.btn-primary.focus {
+  color: #fff;
+  background-color: #204d74;
+  border-color: #122b40;
+}
 .btn-primary:active,
 .btn-primary.active,
-.open .dropdown-toggle.btn-primary {
+.open > .dropdown-toggle.btn-primary {
   background-image: none;
 }
-
-.btn-primary.disabled,
-.btn-primary[disabled],
-fieldset[disabled] .btn-primary,
 .btn-primary.disabled:hover,
 .btn-primary[disabled]:hover,
 fieldset[disabled] .btn-primary:hover,
 .btn-primary.disabled:focus,
 .btn-primary[disabled]:focus,
 fieldset[disabled] .btn-primary:focus,
-.btn-primary.disabled:active,
-.btn-primary[disabled]:active,
-fieldset[disabled] .btn-primary:active,
-.btn-primary.disabled.active,
-.btn-primary[disabled].active,
-fieldset[disabled] .btn-primary.active {
-  background-color: #428bca;
-  border-color: #357ebd;
-}
-
-.btn-warning {
-  color: #ffffff;
-  background-color: #f0ad4e;
-  border-color: #eea236;
-}
-
-.btn-warning:hover,
-.btn-warning:focus,
-.btn-warning:active,
-.btn-warning.active,
-.open .dropdown-toggle.btn-warning {
-  color: #ffffff;
-  background-color: #ed9c28;
-  border-color: #d58512;
-}
-
-.btn-warning:active,
-.btn-warning.active,
-.open .dropdown-toggle.btn-warning {
-  background-image: none;
-}
-
-.btn-warning.disabled,
-.btn-warning[disabled],
-fieldset[disabled] .btn-warning,
-.btn-warning.disabled:hover,
-.btn-warning[disabled]:hover,
-fieldset[disabled] .btn-warning:hover,
-.btn-warning.disabled:focus,
-.btn-warning[disabled]:focus,
-fieldset[disabled] .btn-warning:focus,
-.btn-warning.disabled:active,
-.btn-warning[disabled]:active,
-fieldset[disabled] .btn-warning:active,
-.btn-warning.disabled.active,
-.btn-warning[disabled].active,
-fieldset[disabled] .btn-warning.active {
-  background-color: #f0ad4e;
-  border-color: #eea236;
-}
-
-.btn-danger {
-  color: #ffffff;
-  background-color: #d9534f;
-  border-color: #d43f3a;
-}
-
-.btn-danger:hover,
-.btn-danger:focus,
-.btn-danger:active,
-.btn-danger.active,
-.open .dropdown-toggle.btn-danger {
-  color: #ffffff;
-  background-color: #d2322d;
-  border-color: #ac2925;
-}
-
-.btn-danger:active,
-.btn-danger.active,
-.open .dropdown-toggle.btn-danger {
-  background-image: none;
-}
-
-.btn-danger.disabled,
-.btn-danger[disabled],
-fieldset[disabled] .btn-danger,
-.btn-danger.disabled:hover,
-.btn-danger[disabled]:hover,
-fieldset[disabled] .btn-danger:hover,
-.btn-danger.disabled:focus,
-.btn-danger[disabled]:focus,
-fieldset[disabled] .btn-danger:focus,
-.btn-danger.disabled:active,
-.btn-danger[disabled]:active,
-fieldset[disabled] .btn-danger:active,
-.btn-danger.disabled.active,
-.btn-danger[disabled].active,
-fieldset[disabled] .btn-danger.active {
-  background-color: #d9534f;
-  border-color: #d43f3a;
-}
-
+.btn-primary.disabled.focus,
+.btn-primary[disabled].focus,
+fieldset[disabled] .btn-primary.focus {
+  background-color: #337ab7;
+  border-color: #2e6da4;
+}
+.btn-primary .badge {
+  color: #337ab7;
+  background-color: #fff;
+}
 .btn-success {
-  color: #ffffff;
+  color: #fff;
   background-color: #5cb85c;
   border-color: #4cae4c;
 }
-
-.btn-success:hover,
 .btn-success:focus,
+.btn-success.focus {
+  color: #fff;
+  background-color: #449d44;
+  border-color: #255625;
+}
+.btn-success:hover {
+  color: #fff;
+  background-color: #449d44;
+  border-color: #398439;
+}
 .btn-success:active,
 .btn-success.active,
-.open .dropdown-toggle.btn-success {
-  color: #ffffff;
-  background-color: #47a447;
+.open > .dropdown-toggle.btn-success {
+  color: #fff;
+  background-color: #449d44;
   border-color: #398439;
 }
-
+.btn-success:active:hover,
+.btn-success.active:hover,
+.open > .dropdown-toggle.btn-success:hover,
+.btn-success:active:focus,
+.btn-success.active:focus,
+.open > .dropdown-toggle.btn-success:focus,
+.btn-success:active.focus,
+.btn-success.active.focus,
+.open > .dropdown-toggle.btn-success.focus {
+  color: #fff;
+  background-color: #398439;
+  border-color: #255625;
+}
 .btn-success:active,
 .btn-success.active,
-.open .dropdown-toggle.btn-success {
+.open > .dropdown-toggle.btn-success {
   background-image: none;
 }
-
-.btn-success.disabled,
-.btn-success[disabled],
-fieldset[disabled] .btn-success,
 .btn-success.disabled:hover,
 .btn-success[disabled]:hover,
 fieldset[disabled] .btn-success:hover,
 .btn-success.disabled:focus,
 .btn-success[disabled]:focus,
 fieldset[disabled] .btn-success:focus,
-.btn-success.disabled:active,
-.btn-success[disabled]:active,
-fieldset[disabled] .btn-success:active,
-.btn-success.disabled.active,
-.btn-success[disabled].active,
-fieldset[disabled] .btn-success.active {
+.btn-success.disabled.focus,
+.btn-success[disabled].focus,
+fieldset[disabled] .btn-success.focus {
   background-color: #5cb85c;
   border-color: #4cae4c;
 }
-
+.btn-success .badge {
+  color: #5cb85c;
+  background-color: #fff;
+}
 .btn-info {
-  color: #ffffff;
+  color: #fff;
   background-color: #5bc0de;
   border-color: #46b8da;
 }
-
-.btn-info:hover,
 .btn-info:focus,
+.btn-info.focus {
+  color: #fff;
+  background-color: #31b0d5;
+  border-color: #1b6d85;
+}
+.btn-info:hover {
+  color: #fff;
+  background-color: #31b0d5;
+  border-color: #269abc;
+}
 .btn-info:active,
 .btn-info.active,
-.open .dropdown-toggle.btn-info {
-  color: #ffffff;
-  background-color: #39b3d7;
+.open > .dropdown-toggle.btn-info {
+  color: #fff;
+  background-color: #31b0d5;
   border-color: #269abc;
 }
-
+.btn-info:active:hover,
+.btn-info.active:hover,
+.open > .dropdown-toggle.btn-info:hover,
+.btn-info:active:focus,
+.btn-info.active:focus,
+.open > .dropdown-toggle.btn-info:focus,
+.btn-info:active.focus,
+.btn-info.active.focus,
+.open > .dropdown-toggle.btn-info.focus {
+  color: #fff;
+  background-color: #269abc;
+  border-color: #1b6d85;
+}
 .btn-info:active,
 .btn-info.active,
-.open .dropdown-toggle.btn-info {
+.open > .dropdown-toggle.btn-info {
   background-image: none;
 }
-
-.btn-info.disabled,
-.btn-info[disabled],
-fieldset[disabled] .btn-info,
 .btn-info.disabled:hover,
 .btn-info[disabled]:hover,
 fieldset[disabled] .btn-info:hover,
 .btn-info.disabled:focus,
 .btn-info[disabled]:focus,
 fieldset[disabled] .btn-info:focus,
-.btn-info.disabled:active,
-.btn-info[disabled]:active,
-fieldset[disabled] .btn-info:active,
-.btn-info.disabled.active,
-.btn-info[disabled].active,
-fieldset[disabled] .btn-info.active {
+.btn-info.disabled.focus,
+.btn-info[disabled].focus,
+fieldset[disabled] .btn-info.focus {
   background-color: #5bc0de;
   border-color: #46b8da;
 }
-
+.btn-info .badge {
+  color: #5bc0de;
+  background-color: #fff;
+}
+.btn-warning {
+  color: #fff;
+  background-color: #f0ad4e;
+  border-color: #eea236;
+}
+.btn-warning:focus,
+.btn-warning.focus {
+  color: #fff;
+  background-color: #ec971f;
+  border-color: #985f0d;
+}
+.btn-warning:hover {
+  color: #fff;
+  background-color: #ec971f;
+  border-color: #d58512;
+}
+.btn-warning:active,
+.btn-warning.active,
+.open > .dropdown-toggle.btn-warning {
+  color: #fff;
+  background-color: #ec971f;
+  border-color: #d58512;
+}
+.btn-warning:active:hover,
+.btn-warning.active:hover,
+.open > .dropdown-toggle.btn-warning:hover,
+.btn-warning:active:focus,
+.btn-warning.active:focus,
+.open > .dropdown-toggle.btn-warning:focus,
+.btn-warning:active.focus,
+.btn-warning.active.focus,
+.open > .dropdown-toggle.btn-warning.focus {
+  color: #fff;
+  background-color: #d58512;
+  border-color: #985f0d;
+}
+.btn-warning:active,
+.btn-warning.active,
+.open > .dropdown-toggle.btn-warning {
+  background-image: none;
+}
+.btn-warning.disabled:hover,
+.btn-warning[disabled]:hover,
+fieldset[disabled] .btn-warning:hover,
+.btn-warning.disabled:focus,
+.btn-warning[disabled]:focus,
+fieldset[disabled] .btn-warning:focus,
+.btn-warning.disabled.focus,
+.btn-warning[disabled].focus,
+fieldset[disabled] .btn-warning.focus {
+  background-color: #f0ad4e;
+  border-color: #eea236;
+}
+.btn-warning .badge {
+  color: #f0ad4e;
+  background-color: #fff;
+}
+.btn-danger {
+  color: #fff;
+  background-color: #d9534f;
+  border-color: #d43f3a;
+}
+.btn-danger:focus,
+.btn-danger.focus {
+  color: #fff;
+  background-color: #c9302c;
+  border-color: #761c19;
+}
+.btn-danger:hover {
+  color: #fff;
+  background-color: #c9302c;
+  border-color: #ac2925;
+}
+.btn-danger:active,
+.btn-danger.active,
+.open > .dropdown-toggle.btn-danger {
+  color: #fff;
+  background-color: #c9302c;
+  border-color: #ac2925;
+}
+.btn-danger:active:hover,
+.btn-danger.active:hover,
+.open > .dropdown-toggle.btn-danger:hover,
+.btn-danger:active:focus,
+.btn-danger.active:focus,
+.open > .dropdown-toggle.btn-danger:focus,
+.btn-danger:active.focus,
+.btn-danger.active.focus,
+.open > .dropdown-toggle.btn-danger.focus {
+  color: #fff;
+  background-color: #ac2925;
+  border-color: #761c19;
+}
+.btn-danger:active,
+.btn-danger.active,
+.open > .dropdown-toggle.btn-danger {
+  background-image: none;
+}
+.btn-danger.disabled:hover,
+.btn-danger[disabled]:hover,
+fieldset[disabled] .btn-danger:hover,
+.btn-danger.disabled:focus,
+.btn-danger[disabled]:focus,
+fieldset[disabled] .btn-danger:focus,
+.btn-danger.disabled.focus,
+.btn-danger[disabled].focus,
+fieldset[disabled] .btn-danger.focus {
+  background-color: #d9534f;
+  border-color: #d43f3a;
+}
+.btn-danger .badge {
+  color: #d9534f;
+  background-color: #fff;
+}
 .btn-link {
   font-weight: normal;
-  color: #428bca;
-  cursor: pointer;
+  color: #337ab7;
   border-radius: 0;
 }
-
 .btn-link,
 .btn-link:active,
+.btn-link.active,
 .btn-link[disabled],
 fieldset[disabled] .btn-link {
   background-color: transparent;
   -webkit-box-shadow: none;
           box-shadow: none;
 }
-
 .btn-link,
 .btn-link:hover,
 .btn-link:focus,
 .btn-link:active {
   border-color: transparent;
 }
-
 .btn-link:hover,
 .btn-link:focus {
-  color: #2a6496;
+  color: #23527c;
   text-decoration: underline;
   background-color: transparent;
 }
-
 .btn-link[disabled]:hover,
 fieldset[disabled] .btn-link:hover,
 .btn-link[disabled]:focus,
 fieldset[disabled] .btn-link:focus {
-  color: #999999;
+  color: #777;
   text-decoration: none;
 }
-
-.btn-lg {
+.btn-lg,
+.btn-group-lg > .btn {
   padding: 10px 16px;
   font-size: 18px;
-  line-height: 1.33;
+  line-height: 1.3333333;
   border-radius: 6px;
 }
-
 .btn-sm,
-.btn-xs {
+.btn-group-sm > .btn {
   padding: 5px 10px;
   font-size: 12px;
   line-height: 1.5;
   border-radius: 3px;
 }
-
-.btn-xs {
+.btn-xs,
+.btn-group-xs > .btn {
   padding: 1px 5px;
-}
-
+  font-size: 12px;
+  line-height: 1.5;
+  border-radius: 3px;
+}
 .btn-block {
   display: block;
   width: 100%;
-  padding-right: 0;
-  padding-left: 0;
-}
-
+}
 .btn-block + .btn-block {
   margin-top: 5px;
 }
-
 input[type="submit"].btn-block,
 input[type="reset"].btn-block,
 input[type="button"].btn-block {
   width: 100%;
 }
-
 .fade {
   opacity: 0;
-  -webkit-transition: opacity 0.15s linear;
-          transition: opacity 0.15s linear;
-}
-
+  -webkit-transition: opacity .15s linear;
+       -o-transition: opacity .15s linear;
+          transition: opacity .15s linear;
+}
 .fade.in {
   opacity: 1;
 }
-
 .collapse {
   display: none;
 }
-
 .collapse.in {
   display: block;
 }
-
+tr.collapse.in {
+  display: table-row;
+}
+tbody.collapse.in {
+  display: table-row-group;
+}
 .collapsing {
   position: relative;
   height: 0;
   overflow: hidden;
-  -webkit-transition: height 0.35s ease;
-          transition: height 0.35s ease;
-}
-
-@font-face {
-  font-family: 'Glyphicons Halflings';
-  src: url('../fonts/glyphicons-halflings-regular.eot');
-  src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
-}
-
-.glyphicon {
-  position: relative;
-  top: 1px;
-  display: inline-block;
-  font-family: 'Glyphicons Halflings';
-  -webkit-font-smoothing: antialiased;
-  font-style: normal;
-  font-weight: normal;
-  line-height: 1;
-}
-
-.glyphicon-asterisk:before {
-  content: "\2a";
-}
-
-.glyphicon-plus:before {
-  content: "\2b";
-}
-
-.glyphicon-euro:before {
-  content: "\20ac";
-}
-
-.glyphicon-minus:before {
-  content: "\2212";
-}
-
-.glyphicon-cloud:before {
-  content: "\2601";
-}
-
-.glyphicon-envelope:before {
-  content: "\2709";
-}
-
-.glyphicon-pencil:before {
-  content: "\270f";
-}
-
-.glyphicon-glass:before {
-  content: "\e001";
-}
-
-.glyphicon-music:before {
-  content: "\e002";
-}
-
-.glyphicon-search:before {
-  content: "\e003";
-}
-
-.glyphicon-heart:before {
-  content: "\e005";
-}
-
-.glyphicon-star:before {
-  content: "\e006";
-}
-
-.glyphicon-star-empty:before {
-  content: "\e007";
-}
-
-.glyphicon-user:before {
-  content: "\e008";
-}
-
-.glyphicon-film:before {
-  content: "\e009";
-}
-
-.glyphicon-th-large:before {
-  content: "\e010";
-}
-
-.glyphicon-th:before {
-  content: "\e011";
-}
-
-.glyphicon-th-list:before {
-  content: "\e012";
-}
-
-.glyphicon-ok:before {
-  content: "\e013";
-}
-
-.glyphicon-remove:before {
-  content: "\e014";
-}
-
-.glyphicon-zoom-in:before {
-  content: "\e015";
-}
-
-.glyphicon-zoom-out:before {
-  content: "\e016";
-}
-
-.glyphicon-off:before {
-  content: "\e017";
-}
-
-.glyphicon-signal:before {
-  content: "\e018";
-}
-
-.glyphicon-cog:before {
-  content: "\e019";
-}
-
-.glyphicon-trash:before {
-  content: "\e020";
-}
-
-.glyphicon-home:before {
-  content: "\e021";
-}
-
-.glyphicon-file:before {
-  content: "\e022";
-}
-
-.glyphicon-time:before {
-  content: "\e023";
-}
-
-.glyphicon-road:before {
-  content: "\e024";
-}
-
-.glyphicon-download-alt:before {
-  content: "\e025";
-}
-
-.glyphicon-download:before {
-  content: "\e026";
-}
-
-.glyphicon-upload:before {
-  content: "\e027";
-}
-
-.glyphicon-inbox:before {
-  content: "\e028";
-}
-
-.glyphicon-play-circle:before {
-  content: "\e029";
-}
-
-.glyphicon-repeat:before {
-  content: "\e030";
-}
-
-.glyphicon-arrows-cw:before {
-  content: "\e031";
-}
-
-.glyphicon-list-alt:before {
-  content: "\e032";
-}
-
-.glyphicon-flag:before {
-  content: "\e034";
-}
-
-.glyphicon-headphones:before {
-  content: "\e035";
-}
-
-.glyphicon-volume-off:before {
-  content: "\e036";
-}
-
-.glyphicon-volume-down:before {
-  content: "\e037";
-}
-
-.glyphicon-volume-up:before {
-  content: "\e038";
-}
-
-.glyphicon-qrcode:before {
-  content: "\e039";
-}
-
-.glyphicon-barcode:before {
-  content: "\e040";
-}
-
-.glyphicon-tag:before {
-  content: "\e041";
-}
-
-.glyphicon-tags:before {
-  content: "\e042";
-}
-
-.glyphicon-book:before {
-  content: "\e043";
-}
-
-.glyphicon-print:before {
-  content: "\e045";
-}
-
-.glyphicon-font:before {
-  content: "\e047";
-}
-
-.glyphicon-bold:before {
-  content: "\e048";
-}
-
-.glyphicon-italic:before {
-  content: "\e049";
-}
-
-.glyphicon-text-height:before {
-  content: "\e050";
-}
-
-.glyphicon-text-width:before {
-  content: "\e051";
-}
-
-.glyphicon-align-left:before {
-  content: "\e052";
-}
-
-.glyphicon-align-center:before {
-  content: "\e053";
-}
-
-.glyphicon-align-right:before {
-  content: "\e054";
-}
-
-.glyphicon-align-justify:before {
-  content: "\e055";
-}
-
-.glyphicon-list:before {
-  content: "\e056";
-}
-
-.glyphicon-indent-left:before {
-  content: "\e057";
-}
-
-.glyphicon-indent-right:before {
-  content: "\e058";
-}
-
-.glyphicon-facetime-video:before {
-  content: "\e059";
-}
-
-.glyphicon-picture:before {
-  content: "\e060";
-}
-
-.glyphicon-map-marker:before {
-  content: "\e062";
-}
-
-.glyphicon-adjust:before {
-  content: "\e063";
-}
-
-.glyphicon-tint:before {
-  content: "\e064";
-}
-
-.glyphicon-edit:before {
-  content: "\e065";
-}
-
-.glyphicon-share:before {
-  content: "\e066";
-}
-
-.glyphicon-check:before {
-  content: "\e067";
-}
-
-.glyphicon-move:before {
-  content: "\e068";
-}
-
-.glyphicon-step-backward:before {
-  content: "\e069";
-}
-
-.glyphicon-fast-backward:before {
-  content: "\e070";
-}
-
-.glyphicon-backward:before {
-  content: "\e071";
-}
-
-.glyphicon-play:before {
-  content: "\e072";
-}
-
-.glyphicon-pause:before {
-  content: "\e073";
-}
-
-.glyphicon-stop:before {
-  content: "\e074";
-}
-
-.glyphicon-forward:before {
-  content: "\e075";
-}
-
-.glyphicon-fast-forward:before {
-  content: "\e076";
-}
-
-.glyphicon-step-forward:before {
-  content: "\e077";
-}
-
-.glyphicon-eject:before {
-  content: "\e078";
-}
-
-.glyphicon-chevron-left:before {
-  content: "\e079";
-}
-
-.glyphicon-chevron-right:before {
-  content: "\e080";
-}
-
-.glyphicon-plus-sign:before {
-  content: "\e081";
-}
-
-.glyphicon-minus-sign:before {
-  content: "\e082";
-}
-
-.glyphicon-remove-sign:before {
-  content: "\e083";
-}
-
-.glyphicon-ok-sign:before {
-  content: "\e084";
-}
-
-.glyphicon-question-sign:before {
-  content: "\e085";
-}
-
-.glyphicon-info-sign:before {
-  content: "\e086";
-}
-
-.glyphicon-screenshot:before {
-  content: "\e087";
-}
-
-.glyphicon-remove-circle:before {
-  content: "\e088";
-}
-
-.glyphicon-ok-circle:before {
-  content: "\e089";
-}
-
-.glyphicon-ban-circle:before {
-  content: "\e090";
-}
-
-.glyphicon-arrow-left:before {
-  content: "\e091";
-}
-
-.glyphicon-arrow-right:before {
-  content: "\e092";
-}
-
-.glyphicon-arrow-up:before {
-  content: "\e093";
-}
-
-.glyphicon-arrow-down:before {
-  content: "\e094";
-}
-
-.glyphicon-share-alt:before {
-  content: "\e095";
-}
-
-.glyphicon-resize-full:before {
-  content: "\e096";
-}
-
-.glyphicon-resize-small:before {
-  content: "\e097";
-}
-
-.glyphicon-exclamation-sign:before {
-  content: "\e101";
-}
-
-.glyphicon-gift:before {
-  content: "\e102";
-}
-
-.glyphicon-leaf:before {
-  content: "\e103";
-}
-
-.glyphicon-eye-open:before {
-  content: "\e105";
-}
-
-.glyphicon-eye-close:before {
-  content: "\e106";
-}
-
-.glyphicon-warning-sign:before {
-  content: "\e107";
-}
-
-.glyphicon-plane:before {
-  content: "\e108";
-}
-
-.glyphicon-random:before {
-  content: "\e110";
-}
-
-.glyphicon-comment:before {
-  content: "\e111";
-}
-
-.glyphicon-magnet:before {
-  content: "\e112";
-}
-
-.glyphicon-chevron-up:before {
-  content: "\e113";
-}
-
-.glyphicon-chevron-down:before {
-  content: "\e114";
-}
-
-.glyphicon-retweet:before {
-  content: "\e115";
-}
-
-.glyphicon-shopping-cart:before {
-  content: "\e116";
-}
-
-.glyphicon-folder-close:before {
-  content: "\e117";
-}
-
-.glyphicon-folder-open:before {
-  content: "\e118";
-}
-
-.glyphicon-resize-vertical:before {
-  content: "\e119";
-}
-
-.glyphicon-resize-horizontal:before {
-  content: "\e120";
-}
-
-.glyphicon-hdd:before {
-  content: "\e121";
-}
-
-.glyphicon-bullhorn:before {
-  content: "\e122";
-}
-
-.glyphicon-certificate:before {
-  content: "\e124";
-}
-
-.glyphicon-thumbs-up:before {
-  content: "\e125";
-}
-
-.glyphicon-thumbs-down:before {
-  content: "\e126";
-}
-
-.glyphicon-hand-right:before {
-  content: "\e127";
-}
-
-.glyphicon-hand-left:before {
-  content: "\e128";
-}
-
-.glyphicon-hand-up:before {
-  content: "\e129";
-}
-
-.glyphicon-hand-down:before {
-  content: "\e130";
-}
-
-.glyphicon-circle-arrow-right:before {
-  content: "\e131";
-}
-
-.glyphicon-circle-arrow-left:before {
-  content: "\e132";
-}
-
-.glyphicon-circle-arrow-up:before {
-  content: "\e133";
-}
-
-.glyphicon-circle-arrow-down:before {
-  content: "\e134";
-}
-
-.glyphicon-globe:before {
-  content: "\e135";
-}
-
-.glyphicon-tasks:before {
-  content: "\e137";
-}
-
-.glyphicon-filter:before {
-  content: "\e138";
-}
-
-.glyphicon-fullscreen:before {
-  content: "\e140";
-}
-
-.glyphicon-dashboard:before {
-  content: "\e141";
-}
-
-.glyphicon-heart-empty:before {
-  content: "\e143";
-}
-
-.glyphicon-link:before {
-  content: "\e144";
-}
-
-.glyphicon-phone:before {
-  content: "\e145";
-}
-
-.glyphicon-usd:before {
-  content: "\e148";
-}
-
-.glyphicon-gbp:before {
-  content: "\e149";
-}
-
-.glyphicon-sort:before {
-  content: "\e150";
-}
-
-.glyphicon-sort-by-alphabet:before {
-  content: "\e151";
-}
-
-.glyphicon-sort-by-alphabet-alt:before {
-  content: "\e152";
-}
-
-.glyphicon-sort-by-order:before {
-  content: "\e153";
-}
-
-.glyphicon-sort-by-order-alt:before {
-  content: "\e154";
-}
-
-.glyphicon-sort-by-attributes:before {
-  content: "\e155";
-}
-
-.glyphicon-sort-by-attributes-alt:before {
-  content: "\e156";
-}
-
-.glyphicon-unchecked:before {
-  content: "\e157";
-}
-
-.glyphicon-expand:before {
-  content: "\e158";
-}
-
-.glyphicon-collapse-down:before {
-  content: "\e159";
-}
-
-.glyphicon-collapse-up:before {
-  content: "\e160";
-}
-
-.glyphicon-log-in:before {
-  content: "\e161";
-}
-
-.glyphicon-flash:before {
-  content: "\e162";
-}
-
-.glyphicon-log-out:before {
-  content: "\e163";
-}
-
-.glyphicon-new-window:before {
-  content: "\e164";
-}
-
-.glyphicon-record:before {
-  content: "\e165";
-}
-
-.glyphicon-save:before {
-  content: "\e166";
-}
-
-.glyphicon-open:before {
-  content: "\e167";
-}
-
-.glyphicon-saved:before {
-  content: "\e168";
-}
-
-.glyphicon-import:before {
-  content: "\e169";
-}
-
-.glyphicon-export:before {
-  content: "\e170";
-}
-
-.glyphicon-send:before {
-  content: "\e171";
-}
-
-.glyphicon-floppy-disk:before {
-  content: "\e172";
-}
-
-.glyphicon-floppy-saved:before {
-  content: "\e173";
-}
-
-.glyphicon-floppy-remove:before {
-  content: "\e174";
-}
-
-.glyphicon-floppy-save:before {
-  content: "\e175";
-}
-
-.glyphicon-floppy-open:before {
-  content: "\e176";
-}
-
-.glyphicon-credit-card:before {
-  content: "\e177";
-}
-
-.glyphicon-transfer:before {
-  content: "\e178";
-}
-
-.glyphicon-cutlery:before {
-  content: "\e179";
-}
-
-.glyphicon-header:before {
-  content: "\e180";
-}
-
-.glyphicon-compressed:before {
-  content: "\e181";
-}
-
-.glyphicon-earphone:before {
-  content: "\e182";
-}
-
-.glyphicon-phone-alt:before {
-  content: "\e183";
-}
-
-.glyphicon-tower:before {
-  content: "\e184";
-}
-
-.glyphicon-stats:before {
-  content: "\e185";
-}
-
-.glyphicon-sd-video:before {
-  content: "\e186";
-}
-
-.glyphicon-hd-video:before {
-  content: "\e187";
-}
-
-.glyphicon-subtitles:before {
-  content: "\e188";
-}
-
-.glyphicon-sound-stereo:before {
-  content: "\e189";
-}
-
-.glyphicon-sound-dolby:before {
-  content: "\e190";
-}
-
-.glyphicon-sound-5-1:before {
-  content: "\e191";
-}
-
-.glyphicon-sound-6-1:before {
-  content: "\e192";
-}
-
-.glyphicon-sound-7-1:before {
-  content: "\e193";
-}
-
-.glyphicon-copyright-mark:before {
-  content: "\e194";
-}
-
-.glyphicon-registration-mark:before {
-  content: "\e195";
-}
-
-.glyphicon-cloud-download:before {
-  content: "\e197";
-}
-
-.glyphicon-cloud-upload:before {
-  content: "\e198";
-}
-
-.glyphicon-tree-conifer:before {
-  content: "\e199";
-}
-
-.glyphicon-tree-deciduous:before {
-  content: "\e200";
-}
-
-.glyphicon-briefcase:before {
-  content: "\1f4bc";
-}
-
-.glyphicon-calendar:before {
-  content: "\1f4c5";
-}
-
-.glyphicon-pushpin:before {
-  content: "\1f4cc";
-}
-
-.glyphicon-paperclip:before {
-  content: "\1f4ce";
-}
-
-.glyphicon-camera:before {
-  content: "\1f4f7";
-}
-
-.glyphicon-lock:before {
-  content: "\1f512";
-}
-
-.glyphicon-bell:before {
-  content: "\1f514";
-}
-
-.glyphicon-bookmark:before {
-  content: "\1f516";
-}
-
-.glyphicon-fire:before {
-  content: "\1f525";
-}
-
-.glyphicon-wrench:before {
-  content: "\1f527";
-}
-
+  -webkit-transition-timing-function: ease;
+       -o-transition-timing-function: ease;
+          transition-timing-function: ease;
+  -webkit-transition-duration: .35s;
+       -o-transition-duration: .35s;
+          transition-duration: .35s;
+  -webkit-transition-property: height, visibility;
+       -o-transition-property: height, visibility;
+          transition-property: height, visibility;
+}
 .caret {
   display: inline-block;
   width: 0;
   height: 0;
   margin-left: 2px;
   vertical-align: middle;
-  border-top: 4px solid #000000;
+  border-top: 4px dashed;
+  border-top: 4px solid \9;
   border-right: 4px solid transparent;
-  border-bottom: 0 dotted;
   border-left: 4px solid transparent;
-  content: "";
-}
-
+}
+.dropup,
 .dropdown {
   position: relative;
 }
-
 .dropdown-toggle:focus {
   outline: 0;
 }
-
 .dropdown-menu {
   position: absolute;
   top: 100%;
@@ -3232,85 +3528,85 @@
   padding: 5px 0;
   margin: 2px 0 0;
   font-size: 14px;
+  text-align: left;
   list-style: none;
-  background-color: #ffffff;
-  border: 1px solid #cccccc;
-  border: 1px solid rgba(0, 0, 0, 0.15);
+  background-color: #fff;
+  -webkit-background-clip: padding-box;
+          background-clip: padding-box;
+  border: 1px solid #ccc;
+  border: 1px solid rgba(0, 0, 0, .15);
   border-radius: 4px;
-  -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
-          box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
-  background-clip: padding-box;
-}
-
+  -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
+          box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
+}
 .dropdown-menu.pull-right {
   right: 0;
   left: auto;
 }
-
 .dropdown-menu .divider {
   height: 1px;
   margin: 9px 0;
   overflow: hidden;
   background-color: #e5e5e5;
 }
-
 .dropdown-menu > li > a {
   display: block;
   padding: 3px 20px;
   clear: both;
   font-weight: normal;
-  line-height: 1.428571429;
-  color: #333333;
+  line-height: 1.42857143;
+  color: #333;
   white-space: nowrap;
 }
-
 .dropdown-menu > li > a:hover,
 .dropdown-menu > li > a:focus {
-  color: #ffffff;
+  color: #262626;
   text-decoration: none;
-  background-color: #428bca;
-}
-
+  background-color: #f5f5f5;
+}
 .dropdown-menu > .active > a,
 .dropdown-menu > .active > a:hover,
 .dropdown-menu > .active > a:focus {
-  color: #ffffff;
+  color: #fff;
   text-decoration: none;
-  background-color: #428bca;
+  background-color: #337ab7;
   outline: 0;
 }
-
 .dropdown-menu > .disabled > a,
 .dropdown-menu > .disabled > a:hover,
 .dropdown-menu > .disabled > a:focus {
-  color: #999999;
-}
-
+  color: #777;
+}
 .dropdown-menu > .disabled > a:hover,
 .dropdown-menu > .disabled > a:focus {
   text-decoration: none;
   cursor: not-allowed;
   background-color: transparent;
   background-image: none;
-  filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
-}
-
+  filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
+}
 .open > .dropdown-menu {
   display: block;
 }
-
 .open > a {
   outline: 0;
 }
-
+.dropdown-menu-right {
+  right: 0;
+  left: auto;
+}
+.dropdown-menu-left {
+  right: auto;
+  left: 0;
+}
 .dropdown-header {
   display: block;
   padding: 3px 20px;
   font-size: 12px;
-  line-height: 1.428571429;
-  color: #999999;
-}
-
+  line-height: 1.42857143;
+  color: #777;
+  white-space: nowrap;
+}
 .dropdown-backdrop {
   position: fixed;
   top: 0;
@@ -3319,70 +3615,44 @@
   left: 0;
   z-index: 990;
 }
-
 .pull-right > .dropdown-menu {
   right: 0;
   left: auto;
 }
-
 .dropup .caret,
 .navbar-fixed-bottom .dropdown .caret {
-  border-top: 0 dotted;
-  border-bottom: 4px solid #000000;
   content: "";
-}
-
+  border-top: 0;
+  border-bottom: 4px dashed;
+  border-bottom: 4px solid \9;
+}
 .dropup .dropdown-menu,
 .navbar-fixed-bottom .dropdown .dropdown-menu {
   top: auto;
   bottom: 100%;
-  margin-bottom: 1px;
-}
-
+  margin-bottom: 2px;
+}
 @media (min-width: 768px) {
   .navbar-right .dropdown-menu {
     right: 0;
     left: auto;
   }
-}
-
-.btn-default .caret {
-  border-top-color: #333333;
-}
-
-.btn-primary .caret,
-.btn-success .caret,
-.btn-warning .caret,
-.btn-danger .caret,
-.btn-info .caret {
-  border-top-color: #fff;
-}
-
-.dropup .btn-default .caret {
-  border-bottom-color: #333333;
-}
-
-.dropup .btn-primary .caret,
-.dropup .btn-success .caret,
-.dropup .btn-warning .caret,
-.dropup .btn-danger .caret,
-.dropup .btn-info .caret {
-  border-bottom-color: #fff;
-}
-
+  .navbar-right .dropdown-menu-left {
+    right: auto;
+    left: 0;
+  }
+}
 .btn-group,
 .btn-group-vertical {
   position: relative;
   display: inline-block;
   vertical-align: middle;
 }
-
 .btn-group > .btn,
 .btn-group-vertical > .btn {
   position: relative;
   float: left;
 }
-
 .btn-group > .btn:hover,
 .btn-group-vertical > .btn:hover,
 .btn-group > .btn:focus,
@@ -3393,175 +3663,96 @@
 .btn-group-vertical > .btn.active {
   z-index: 2;
 }
-
-.btn-group > .btn:focus,
-.btn-group-vertical > .btn:focus {
-  outline: none;
-}
-
 .btn-group .btn + .btn,
 .btn-group .btn + .btn-group,
 .btn-group .btn-group + .btn,
 .btn-group .btn-group + .btn-group {
   margin-left: -1px;
 }
-
-.btn-toolbar:before,
-.btn-toolbar:after {
-  display: table;
-  content: " ";
-}
-
-.btn-toolbar:after {
-  clear: both;
-}
-
-.btn-toolbar:before,
-.btn-toolbar:after {
-  display: table;
-  content: " ";
-}
-
-.btn-toolbar:after {
-  clear: both;
-}
-
-.btn-toolbar .btn-group {
+.btn-toolbar {
+  margin-left: -5px;
+}
+.btn-toolbar .btn,
+.btn-toolbar .btn-group,
+.btn-toolbar .input-group {
   float: left;
 }
-
-.btn-toolbar > .btn + .btn,
-.btn-toolbar > .btn-group + .btn,
-.btn-toolbar > .btn + .btn-group,
-.btn-toolbar > .btn-group + .btn-group {
+.btn-toolbar > .btn,
+.btn-toolbar > .btn-group,
+.btn-toolbar > .input-group {
   margin-left: 5px;
 }
-
 .btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {
   border-radius: 0;
 }
-
 .btn-group > .btn:first-child {
   margin-left: 0;
 }
-
 .btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) {
   border-top-right-radius: 0;
   border-bottom-right-radius: 0;
 }
-
 .btn-group > .btn:last-child:not(:first-child),
 .btn-group > .dropdown-toggle:not(:first-child) {
+  border-top-left-radius: 0;
   border-bottom-left-radius: 0;
-  border-top-left-radius: 0;
-}
-
+}
 .btn-group > .btn-group {
   float: left;
 }
-
 .btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {
   border-radius: 0;
 }
-
-.btn-group > .btn-group:first-child > .btn:last-child,
-.btn-group > .btn-group:first-child > .dropdown-toggle {
+.btn-group > .btn-group:first-child:not(:last-child) > .btn:last-child,
+.btn-group > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
   border-top-right-radius: 0;
   border-bottom-right-radius: 0;
 }
-
-.btn-group > .btn-group:last-child > .btn:first-child {
+.btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child {
+  border-top-left-radius: 0;
   border-bottom-left-radius: 0;
-  border-top-left-radius: 0;
-}
-
+}
 .btn-group .dropdown-toggle:active,
 .btn-group.open .dropdown-toggle {
   outline: 0;
 }
-
-.btn-group-xs > .btn {
-  padding: 5px 10px;
-  padding: 1px 5px;
-  font-size: 12px;
-  line-height: 1.5;
-  border-radius: 3px;
-}
-
-.btn-group-sm > .btn {
-  padding: 5px 10px;
-  font-size: 12px;
-  line-height: 1.5;
-  border-radius: 3px;
-}
-
-.btn-group-lg > .btn {
-  padding: 10px 16px;
-  font-size: 18px;
-  line-height: 1.33;
-  border-radius: 6px;
-}
-
 .btn-group > .btn + .dropdown-toggle {
   padding-right: 8px;
   padding-left: 8px;
 }
-
 .btn-group > .btn-lg + .dropdown-toggle {
   padding-right: 12px;
   padding-left: 12px;
 }
-
 .btn-group.open .dropdown-toggle {
-  -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
-          box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
-}
-
+  -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
+          box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
+}
+.btn-group.open .dropdown-toggle.btn-link {
+  -webkit-box-shadow: none;
+          box-shadow: none;
+}
 .btn .caret {
   margin-left: 0;
 }
-
 .btn-lg .caret {
   border-width: 5px 5px 0;
   border-bottom-width: 0;
 }
-
 .dropup .btn-lg .caret {
   border-width: 0 5px 5px;
 }
-
 .btn-group-vertical > .btn,
-.btn-group-vertical > .btn-group {
+.btn-group-vertical > .btn-group,
+.btn-group-vertical > .btn-group > .btn {
   display: block;
   float: none;
   width: 100%;
   max-width: 100%;
 }
-
-.btn-group-vertical > .btn-group:before,
-.btn-group-vertical > .btn-group:after {
-  display: table;
-  content: " ";
-}
-
-.btn-group-vertical > .btn-group:after {
-  clear: both;
-}
-
-.btn-group-vertical > .btn-group:before,
-.btn-group-vertical > .btn-group:after {
-  display: table;
-  content: " ";
-}
-
-.btn-group-vertical > .btn-group:after {
-  clear: both;
-}
-
 .btn-group-vertical > .btn-group > .btn {
   float: none;
 }
-
 .btn-group-vertical > .btn + .btn,
 .btn-group-vertical > .btn + .btn-group,
 .btn-group-vertical > .btn-group + .btn,
@@ -3569,96 +3760,102 @@
   margin-top: -1px;
   margin-left: 0;
 }
-
 .btn-group-vertical > .btn:not(:first-child):not(:last-child) {
   border-radius: 0;
 }
-
 .btn-group-vertical > .btn:first-child:not(:last-child) {
+  border-top-left-radius: 4px;
   border-top-right-radius: 4px;
   border-bottom-right-radius: 0;
   border-bottom-left-radius: 0;
 }
-
 .btn-group-vertical > .btn:last-child:not(:first-child) {
+  border-top-left-radius: 0;
   border-top-right-radius: 0;
+  border-bottom-right-radius: 4px;
   border-bottom-left-radius: 4px;
-  border-top-left-radius: 0;
-}
-
+}
 .btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {
   border-radius: 0;
 }
-
-.btn-group-vertical > .btn-group:first-child > .btn:last-child,
-.btn-group-vertical > .btn-group:first-child > .dropdown-toggle {
+.btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child,
+.btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
   border-bottom-right-radius: 0;
   border-bottom-left-radius: 0;
 }
-
-.btn-group-vertical > .btn-group:last-child > .btn:first-child {
+.btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child {
+  border-top-left-radius: 0;
   border-top-right-radius: 0;
-  border-top-left-radius: 0;
-}
-
+}
 .btn-group-justified {
   display: table;
   width: 100%;
+  table-layout: fixed;
   border-collapse: separate;
-  table-layout: fixed;
-}
-
-.btn-group-justified .btn {
+}
+.btn-group-justified > .btn,
+.btn-group-justified > .btn-group {
   display: table-cell;
   float: none;
   width: 1%;
 }
-
-[data-toggle="buttons"] > .btn > input[type="radio"],
-[data-toggle="buttons"] > .btn > input[type="checkbox"] {
-  display: none;
-}
-
+.btn-group-justified > .btn-group .btn {
+  width: 100%;
+}
+.btn-group-justified > .btn-group .dropdown-menu {
+  left: auto;
+}
+[data-toggle="buttons"] > .btn input[type="radio"],
+[data-toggle="buttons"] > .btn-group > .btn input[type="radio"],
+[data-toggle="buttons"] > .btn input[type="checkbox"],
+[data-toggle="buttons"] > .btn-group > .btn input[type="checkbox"] {
+  position: absolute;
+  clip: rect(0, 0, 0, 0);
+  pointer-events: none;
+}
 .input-group {
   position: relative;
   display: table;
   border-collapse: separate;
 }
-
-.input-group.col {
+.input-group[class*="col-"] {
   float: none;
   padding-right: 0;
   padding-left: 0;
 }
-
 .input-group .form-control {
+  position: relative;
+  z-index: 2;
+  float: left;
   width: 100%;
   margin-bottom: 0;
 }
-
+.input-group .form-control:focus {
+  z-index: 3;
+}
 .input-group-lg > .form-control,
 .input-group-lg > .input-group-addon,
 .input-group-lg > .input-group-btn > .btn {
-  height: 45px;
+  height: 46px;
   padding: 10px 16px;
   font-size: 18px;
-  line-height: 1.33;
+  line-height: 1.3333333;
   border-radius: 6px;
 }
-
 select.input-group-lg > .form-control,
 select.input-group-lg > .input-group-addon,
 select.input-group-lg > .input-group-btn > .btn {
-  height: 45px;
-  line-height: 45px;
-}
-
+  height: 46px;
+  line-height: 46px;
+}
 textarea.input-group-lg > .form-control,
 textarea.input-group-lg > .input-group-addon,
-textarea.input-group-lg > .input-group-btn > .btn {
+textarea.input-group-lg > .input-group-btn > .btn,
+select[multiple].input-group-lg > .form-control,
+select[multiple].input-group-lg > .input-group-addon,
+select[multiple].input-group-lg > .input-group-btn > .btn {
   height: auto;
 }
-
 .input-group-sm > .form-control,
 .input-group-sm > .input-group-addon,
 .input-group-sm > .input-group-btn > .btn {
@@ -3668,448 +3865,338 @@
   line-height: 1.5;
   border-radius: 3px;
 }
-
 select.input-group-sm > .form-control,
 select.input-group-sm > .input-group-addon,
 select.input-group-sm > .input-group-btn > .btn {
   height: 30px;
   line-height: 30px;
 }
-
 textarea.input-group-sm > .form-control,
 textarea.input-group-sm > .input-group-addon,
-textarea.input-group-sm > .input-group-btn > .btn {
+textarea.input-group-sm > .input-group-btn > .btn,
+select[multiple].input-group-sm > .form-control,
+select[multiple].input-group-sm > .input-group-addon,
+select[multiple].input-group-sm > .input-group-btn > .btn {
   height: auto;
 }
-
 .input-group-addon,
 .input-group-btn,
 .input-group .form-control {
   display: table-cell;
 }
-
 .input-group-addon:not(:first-child):not(:last-child),
 .input-group-btn:not(:first-child):not(:last-child),
 .input-group .form-control:not(:first-child):not(:last-child) {
   border-radius: 0;
 }
-
 .input-group-addon,
 .input-group-btn {
   width: 1%;
   white-space: nowrap;
   vertical-align: middle;
 }
-
 .input-group-addon {
   padding: 6px 12px;
   font-size: 14px;
   font-weight: normal;
   line-height: 1;
+  color: #555;
   text-align: center;
-  background-color: #eeeeee;
-  border: 1px solid #cccccc;
+  background-color: #eee;
+  border: 1px solid #ccc;
   border-radius: 4px;
 }
-
 .input-group-addon.input-sm {
   padding: 5px 10px;
   font-size: 12px;
   border-radius: 3px;
 }
-
 .input-group-addon.input-lg {
   padding: 10px 16px;
   font-size: 18px;
   border-radius: 6px;
 }
-
 .input-group-addon input[type="radio"],
 .input-group-addon input[type="checkbox"] {
   margin-top: 0;
 }
-
 .input-group .form-control:first-child,
 .input-group-addon:first-child,
 .input-group-btn:first-child > .btn,
+.input-group-btn:first-child > .btn-group > .btn,
 .input-group-btn:first-child > .dropdown-toggle,
-.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle) {
+.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle),
+.input-group-btn:last-child > .btn-group:not(:last-child) > .btn {
   border-top-right-radius: 0;
   border-bottom-right-radius: 0;
 }
-
 .input-group-addon:first-child {
   border-right: 0;
 }
-
 .input-group .form-control:last-child,
 .input-group-addon:last-child,
 .input-group-btn:last-child > .btn,
+.input-group-btn:last-child > .btn-group > .btn,
 .input-group-btn:last-child > .dropdown-toggle,
-.input-group-btn:first-child > .btn:not(:first-child) {
+.input-group-btn:first-child > .btn:not(:first-child),
+.input-group-btn:first-child > .btn-group:not(:first-child) > .btn {
+  border-top-left-radius: 0;
   border-bottom-left-radius: 0;
-  border-top-left-radius: 0;
-}
-
+}
 .input-group-addon:last-child {
   border-left: 0;
 }
-
 .input-group-btn {
   position: relative;
+  font-size: 0;
   white-space: nowrap;
 }
-
 .input-group-btn > .btn {
   position: relative;
 }
-
 .input-group-btn > .btn + .btn {
-  margin-left: -4px;
-}
-
+  margin-left: -1px;
+}
 .input-group-btn > .btn:hover,
+.input-group-btn > .btn:focus,
 .input-group-btn > .btn:active {
   z-index: 2;
 }
-
+.input-group-btn:first-child > .btn,
+.input-group-btn:first-child > .btn-group {
+  margin-right: -1px;
+}
+.input-group-btn:last-child > .btn,
+.input-group-btn:last-child > .btn-group {
+  z-index: 2;
+  margin-left: -1px;
+}
 .nav {
   padding-left: 0;
   margin-bottom: 0;
   list-style: none;
 }
-
-.nav:before,
-.nav:after {
-  display: table;
-  content: " ";
-}
-
-.nav:after {
-  clear: both;
-}
-
-.nav:before,
-.nav:after {
-  display: table;
-  content: " ";
-}
-
-.nav:after {
-  clear: both;
-}
-
 .nav > li {
   position: relative;
   display: block;
 }
-
 .nav > li > a {
   position: relative;
   display: block;
   padding: 10px 15px;
 }
-
 .nav > li > a:hover,
 .nav > li > a:focus {
   text-decoration: none;
-  background-color: #eeeeee;
-}
-
+  background-color: #eee;
+}
 .nav > li.disabled > a {
-  color: #999999;
-}
-
+  color: #777;
+}
 .nav > li.disabled > a:hover,
 .nav > li.disabled > a:focus {
-  color: #999999;
+  color: #777;
   text-decoration: none;
   cursor: not-allowed;
   background-color: transparent;
 }
-
 .nav .open > a,
 .nav .open > a:hover,
 .nav .open > a:focus {
-  background-color: #eeeeee;
-  border-color: #428bca;
-}
-
+  background-color: #eee;
+  border-color: #337ab7;
+}
 .nav .nav-divider {
   height: 1px;
   margin: 9px 0;
   overflow: hidden;
   background-color: #e5e5e5;
 }
-
 .nav > li > a > img {
   max-width: none;
 }
-
 .nav-tabs {
-  border-bottom: 1px solid #dddddd;
-}
-
+  border-bottom: 1px solid #ddd;
+}
 .nav-tabs > li {
   float: left;
   margin-bottom: -1px;
 }
-
 .nav-tabs > li > a {
   margin-right: 2px;
-  line-height: 1.428571429;
+  line-height: 1.42857143;
   border: 1px solid transparent;
   border-radius: 4px 4px 0 0;
 }
-
 .nav-tabs > li > a:hover {
-  border-color: #eeeeee #eeeeee #dddddd;
-}
-
+  border-color: #eee #eee #ddd;
+}
 .nav-tabs > li.active > a,
 .nav-tabs > li.active > a:hover,
 .nav-tabs > li.active > a:focus {
-  color: #555555;
+  color: #555;
   cursor: default;
-  background-color: #ffffff;
-  border: 1px solid #dddddd;
+  background-color: #fff;
+  border: 1px solid #ddd;
   border-bottom-color: transparent;
 }
-
 .nav-tabs.nav-justified {
   width: 100%;
   border-bottom: 0;
 }
-
 .nav-tabs.nav-justified > li {
   float: none;
 }
-
 .nav-tabs.nav-justified > li > a {
+  margin-bottom: 5px;
   text-align: center;
 }
-
+.nav-tabs.nav-justified > .dropdown .dropdown-menu {
+  top: auto;
+  left: auto;
+}
 @media (min-width: 768px) {
   .nav-tabs.nav-justified > li {
     display: table-cell;
     width: 1%;
   }
-}
-
+  .nav-tabs.nav-justified > li > a {
+    margin-bottom: 0;
+  }
+}
 .nav-tabs.nav-justified > li > a {
   margin-right: 0;
-  border-bottom: 1px solid #dddddd;
-}
-
-.nav-tabs.nav-justified > .active > a {
-  border-bottom-color: #ffffff;
-}
-
+  border-radius: 4px;
+}
+.nav-tabs.nav-justified > .active > a,
+.nav-tabs.nav-justified > .active > a:hover,
+.nav-tabs.nav-justified > .active > a:focus {
+  border: 1px solid #ddd;
+}
+@media (min-width: 768px) {
+  .nav-tabs.nav-justified > li > a {
+    border-bottom: 1px solid #ddd;
+    border-radius: 4px 4px 0 0;
+  }
+  .nav-tabs.nav-justified > .active > a,
+  .nav-tabs.nav-justified > .active > a:hover,
+  .nav-tabs.nav-justified > .active > a:focus {
+    border-bottom-color: #fff;
+  }
+}
 .nav-pills > li {
   float: left;
 }
-
 .nav-pills > li > a {
-  border-radius: 5px;
-}
-
+  border-radius: 4px;
+}
 .nav-pills > li + li {
   margin-left: 2px;
 }
-
 .nav-pills > li.active > a,
 .nav-pills > li.active > a:hover,
 .nav-pills > li.active > a:focus {
-  color: #ffffff;
-  background-color: #428bca;
-}
-
+  color: #fff;
+  background-color: #337ab7;
+}
 .nav-stacked > li {
   float: none;
 }
-
 .nav-stacked > li + li {
   margin-top: 2px;
   margin-left: 0;
 }
-
 .nav-justified {
   width: 100%;
 }
-
 .nav-justified > li {
   float: none;
 }
-
 .nav-justified > li > a {
+  margin-bottom: 5px;
   text-align: center;
 }
-
+.nav-justified > .dropdown .dropdown-menu {
+  top: auto;
+  left: auto;
+}
 @media (min-width: 768px) {
   .nav-justified > li {
     display: table-cell;
     width: 1%;
   }
-}
-
+  .nav-justified > li > a {
+    margin-bottom: 0;
+  }
+}
 .nav-tabs-justified {
   border-bottom: 0;
 }
-
 .nav-tabs-justified > li > a {
   margin-right: 0;
-  border-bottom: 1px solid #dddddd;
-}
-
-.nav-tabs-justified > .active > a {
-  border-bottom-color: #ffffff;
-}
-
-.tabbable:before,
-.tabbable:after {
-  display: table;
-  content: " ";
-}
-
-.tabbable:after {
-  clear: both;
-}
-
-.tabbable:before,
-.tabbable:after {
-  display: table;
-  content: " ";
-}
-
-.tabbable:after {
-  clear: both;
-}
-
-.tab-content > .tab-pane,
-.pill-content > .pill-pane {
+  border-radius: 4px;
+}
+.nav-tabs-justified > .active > a,
+.nav-tabs-justified > .active > a:hover,
+.nav-tabs-justified > .active > a:focus {
+  border: 1px solid #ddd;
+}
+@media (min-width: 768px) {
+  .nav-tabs-justified > li > a {
+    border-bottom: 1px solid #ddd;
+    border-radius: 4px 4px 0 0;
+  }
+  .nav-tabs-justified > .active > a,
+  .nav-tabs-justified > .active > a:hover,
+  .nav-tabs-justified > .active > a:focus {
+    border-bottom-color: #fff;
+  }
+}
+.tab-content > .tab-pane {
   display: none;
 }
-
-.tab-content > .active,
-.pill-content > .active {
+.tab-content > .active {
   display: block;
 }
-
-.nav .caret {
-  border-top-color: #428bca;
-  border-bottom-color: #428bca;
-}
-
-.nav a:hover .caret {
-  border-top-color: #2a6496;
-  border-bottom-color: #2a6496;
-}
-
 .nav-tabs .dropdown-menu {
   margin-top: -1px;
+  border-top-left-radius: 0;
   border-top-right-radius: 0;
-  border-top-left-radius: 0;
-}
-
+}
 .navbar {
   position: relative;
-  z-index: 1000;
   min-height: 50px;
   margin-bottom: 20px;
   border: 1px solid transparent;
 }
-
-.navbar:before,
-.navbar:after {
-  display: table;
-  content: " ";
-}
-
-.navbar:after {
-  clear: both;
-}
-
-.navbar:before,
-.navbar:after {
-  display: table;
-  content: " ";
-}
-
-.navbar:after {
-  clear: both;
-}
-
 @media (min-width: 768px) {
   .navbar {
     border-radius: 4px;
   }
 }
-
-.navbar-header:before,
-.navbar-header:after {
-  display: table;
-  content: " ";
-}
-
-.navbar-header:after {
-  clear: both;
-}
-
-.navbar-header:before,
-.navbar-header:after {
-  display: table;
-  content: " ";
-}
-
-.navbar-header:after {
-  clear: both;
-}
-
 @media (min-width: 768px) {
   .navbar-header {
     float: left;
   }
 }
-
 .navbar-collapse {
-  max-height: 340px;
   padding-right: 15px;
   padding-left: 15px;
   overflow-x: visible;
+  -webkit-overflow-scrolling: touch;
   border-top: 1px solid transparent;
-  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
-  -webkit-overflow-scrolling: touch;
-}
-
-.navbar-collapse:before,
-.navbar-collapse:after {
-  display: table;
-  content: " ";
-}
-
-.navbar-collapse:after {
-  clear: both;
-}
-
-.navbar-collapse:before,
-.navbar-collapse:after {
-  display: table;
-  content: " ";
-}
-
-.navbar-collapse:after {
-  clear: both;
-}
-
+  -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
+          box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
+}
 .navbar-collapse.in {
   overflow-y: auto;
 }
-
 @media (min-width: 768px) {
   .navbar-collapse {
     width: auto;
     border-top: 0;
-    box-shadow: none;
+    -webkit-box-shadow: none;
+            box-shadow: none;
   }
   .navbar-collapse.collapse {
     display: block !important;
@@ -4120,84 +4207,90 @@
   .navbar-collapse.in {
     overflow-y: visible;
   }
-  .navbar-collapse .navbar-nav.navbar-left:first-child {
-    margin-left: -15px;
-  }
-  .navbar-collapse .navbar-nav.navbar-right:last-child {
-    margin-right: -15px;
-  }
-  .navbar-collapse .navbar-text:last-child {
-    margin-right: 0;
-  }
-}
-
+  .navbar-fixed-top .navbar-collapse,
+  .navbar-static-top .navbar-collapse,
+  .navbar-fixed-bottom .navbar-collapse {
+    padding-right: 0;
+    padding-left: 0;
+  }
+}
+.navbar-fixed-top .navbar-collapse,
+.navbar-fixed-bottom .navbar-collapse {
+  max-height: 340px;
+}
+@media (max-device-width: 480px) and (orientation: landscape) {
+  .navbar-fixed-top .navbar-collapse,
+  .navbar-fixed-bottom .navbar-collapse {
+    max-height: 200px;
+  }
+}
 .container > .navbar-header,
-.container > .navbar-collapse {
+.container-fluid > .navbar-header,
+.container > .navbar-collapse,
+.container-fluid > .navbar-collapse {
   margin-right: -15px;
   margin-left: -15px;
 }
-
 @media (min-width: 768px) {
   .container > .navbar-header,
-  .container > .navbar-collapse {
+  .container-fluid > .navbar-header,
+  .container > .navbar-collapse,
+  .container-fluid > .navbar-collapse {
     margin-right: 0;
     margin-left: 0;
   }
 }
-
 .navbar-static-top {
+  z-index: 1000;
   border-width: 0 0 1px;
 }
-
 @media (min-width: 768px) {
   .navbar-static-top {
     border-radius: 0;
   }
 }
-
 .navbar-fixed-top,
 .navbar-fixed-bottom {
   position: fixed;
   right: 0;
   left: 0;
-  border-width: 0 0 1px;
-}
-
+  z-index: 1030;
+}
 @media (min-width: 768px) {
   .navbar-fixed-top,
   .navbar-fixed-bottom {
     border-radius: 0;
   }
 }
-
 .navbar-fixed-top {
   top: 0;
-  z-index: 1030;
-}
-
+  border-width: 0 0 1px;
+}
 .navbar-fixed-bottom {
   bottom: 0;
   margin-bottom: 0;
-}
-
+  border-width: 1px 0 0;
+}
 .navbar-brand {
   float: left;
+  height: 50px;
   padding: 15px 15px;
   font-size: 18px;
   line-height: 20px;
 }
-
 .navbar-brand:hover,
 .navbar-brand:focus {
   text-decoration: none;
 }
-
+.navbar-brand > img {
+  display: block;
+}
 @media (min-width: 768px) {
-  .navbar > .container .navbar-brand {
+  .navbar > .container .navbar-brand,
+  .navbar > .container-fluid .navbar-brand {
     margin-left: -15px;
   }
 }
-
 .navbar-toggle {
   position: relative;
   float: right;
@@ -4206,37 +4299,35 @@
   margin-right: 15px;
   margin-bottom: 8px;
   background-color: transparent;
+  background-image: none;
   border: 1px solid transparent;
   border-radius: 4px;
 }
-
+.navbar-toggle:focus {
+  outline: 0;
+}
 .navbar-toggle .icon-bar {
   display: block;
   width: 22px;
   height: 2px;
   border-radius: 1px;
 }
-
 .navbar-toggle .icon-bar + .icon-bar {
   margin-top: 4px;
 }
-
 @media (min-width: 768px) {
   .navbar-toggle {
     display: none;
   }
 }
-
 .navbar-nav {
   margin: 7.5px -15px;
 }
-
 .navbar-nav > li > a {
   padding-top: 10px;
   padding-bottom: 10px;
   line-height: 20px;
 }
-
 @media (max-width: 767px) {
   .navbar-nav .open .dropdown-menu {
     position: static;
@@ -4245,7 +4336,8 @@
     margin-top: 0;
     background-color: transparent;
     border: 0;
-    box-shadow: none;
+    -webkit-box-shadow: none;
+            box-shadow: none;
   }
   .navbar-nav .open .dropdown-menu > li > a,
   .navbar-nav .open .dropdown-menu .dropdown-header {
@@ -4259,7 +4351,6 @@
     background-image: none;
   }
 }
-
 @media (min-width: 768px) {
   .navbar-nav {
     float: left;
@@ -4273,16 +4364,6 @@
     padding-bottom: 15px;
   }
 }
-
-@media (min-width: 768px) {
-  .navbar-left {
-    float: left !important;
-  }
-  .navbar-right {
-    float: right !important;
-  }
-}
-
 .navbar-form {
   padding: 10px 15px;
   margin-top: 8px;
@@ -4291,10 +4372,9 @@
   margin-left: -15px;
   border-top: 1px solid transparent;
   border-bottom: 1px solid transparent;
-  -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);
-          box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);
-}
-
+  -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
+          box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
+}
 @media (min-width: 768px) {
   .navbar-form .form-group {
     display: inline-block;
@@ -4303,27 +4383,56 @@
   }
   .navbar-form .form-control {
     display: inline-block;
+    width: auto;
+    vertical-align: middle;
+  }
+  .navbar-form .form-control-static {
+    display: inline-block;
+  }
+  .navbar-form .input-group {
+    display: inline-table;
+    vertical-align: middle;
+  }
+  .navbar-form .input-group .input-group-addon,
+  .navbar-form .input-group .input-group-btn,
+  .navbar-form .input-group .form-control {
+    width: auto;
+  }
+  .navbar-form .input-group > .form-control {
+    width: 100%;
+  }
+  .navbar-form .control-label {
+    margin-bottom: 0;
+    vertical-align: middle;
   }
   .navbar-form .radio,
   .navbar-form .checkbox {
     display: inline-block;
-    padding-left: 0;
     margin-top: 0;
     margin-bottom: 0;
+    vertical-align: middle;
+  }
+  .navbar-form .radio label,
+  .navbar-form .checkbox label {
+    padding-left: 0;
   }
   .navbar-form .radio input[type="radio"],
   .navbar-form .checkbox input[type="checkbox"] {
-    float: none;
+    position: relative;
     margin-left: 0;
   }
-}
-
+  .navbar-form .has-feedback .form-control-feedback {
+    top: 0;
+  }
+}
 @media (max-width: 767px) {
   .navbar-form .form-group {
     margin-bottom: 5px;
   }
-}
-
+  .navbar-form .form-group:last-child {
+    margin-bottom: 0;
+  }
+}
 @media (min-width: 768px) {
   .navbar-form {
     width: auto;
@@ -4336,278 +4445,251 @@
             box-shadow: none;
   }
 }
-
 .navbar-nav > li > .dropdown-menu {
   margin-top: 0;
+  border-top-left-radius: 0;
   border-top-right-radius: 0;
-  border-top-left-radius: 0;
-}
-
+}
 .navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {
+  margin-bottom: 0;
+  border-top-left-radius: 4px;
+  border-top-right-radius: 4px;
   border-bottom-right-radius: 0;
   border-bottom-left-radius: 0;
 }
-
-.navbar-nav.pull-right > li > .dropdown-menu,
-.navbar-nav > li > .dropdown-menu.pull-right {
-  right: 0;
-  left: auto;
-}
-
 .navbar-btn {
   margin-top: 8px;
   margin-bottom: 8px;
 }
-
+.navbar-btn.btn-sm {
+  margin-top: 10px;
+  margin-bottom: 10px;
+}
+.navbar-btn.btn-xs {
+  margin-top: 14px;
+  margin-bottom: 14px;
+}
 .navbar-text {
-  float: left;
   margin-top: 15px;
   margin-bottom: 15px;
 }
-
 @media (min-width: 768px) {
   .navbar-text {
+    float: left;
     margin-right: 15px;
     margin-left: 15px;
   }
 }
-
+@media (min-width: 768px) {
+  .navbar-left {
+    float: left !important;
+  }
+  .navbar-right {
+    float: right !important;
+    margin-right: -15px;
+  }
+  .navbar-right ~ .navbar-right {
+    margin-right: 0;
+  }
+}
 .navbar-default {
   background-color: #f8f8f8;
   border-color: #e7e7e7;
 }
-
 .navbar-default .navbar-brand {
-  color: #777777;
-}
-
+  color: #777;
+}
 .navbar-default .navbar-brand:hover,
 .navbar-default .navbar-brand:focus {
   color: #5e5e5e;
   background-color: transparent;
 }
-
 .navbar-default .navbar-text {
-  color: #777777;
-}
-
+  color: #777;
+}
 .navbar-default .navbar-nav > li > a {
-  color: #777777;
-}
-
+  color: #777;
+}
 .navbar-default .navbar-nav > li > a:hover,
 .navbar-default .navbar-nav > li > a:focus {
-  color: #333333;
+  color: #333;
   background-color: transparent;
 }
-
 .navbar-default .navbar-nav > .active > a,
 .navbar-default .navbar-nav > .active > a:hover,
 .navbar-default .navbar-nav > .active > a:focus {
-  color: #555555;
+  color: #555;
   background-color: #e7e7e7;
 }
-
 .navbar-default .navbar-nav > .disabled > a,
 .navbar-default .navbar-nav > .disabled > a:hover,
 .navbar-default .navbar-nav > .disabled > a:focus {
-  color: #cccccc;
+  color: #ccc;
   background-color: transparent;
 }
-
 .navbar-default .navbar-toggle {
-  border-color: #dddddd;
-}
-
+  border-color: #ddd;
+}
 .navbar-default .navbar-toggle:hover,
 .navbar-default .navbar-toggle:focus {
-  background-color: #dddddd;
-}
-
+  background-color: #ddd;
+}
 .navbar-default .navbar-toggle .icon-bar {
-  background-color: #cccccc;
-}
-
+  background-color: #888;
+}
 .navbar-default .navbar-collapse,
 .navbar-default .navbar-form {
-  border-color: #e6e6e6;
-}
-
-.navbar-default .navbar-nav > .dropdown > a:hover .caret,
-.navbar-default .navbar-nav > .dropdown > a:focus .caret {
-  border-top-color: #333333;
-  border-bottom-color: #333333;
-}
-
+  border-color: #e7e7e7;
+}
 .navbar-default .navbar-nav > .open > a,
 .navbar-default .navbar-nav > .open > a:hover,
 .navbar-default .navbar-nav > .open > a:focus {
-  color: #555555;
+  color: #555;
   background-color: #e7e7e7;
 }
-
-.navbar-default .navbar-nav > .open > a .caret,
-.navbar-default .navbar-nav > .open > a:hover .caret,
-.navbar-default .navbar-nav > .open > a:focus .caret {
-  border-top-color: #555555;
-  border-bottom-color: #555555;
-}
-
-.navbar-default .navbar-nav > .dropdown > a .caret {
-  border-top-color: #777777;
-  border-bottom-color: #777777;
-}
-
 @media (max-width: 767px) {
   .navbar-default .navbar-nav .open .dropdown-menu > li > a {
-    color: #777777;
+    color: #777;
   }
   .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
   .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
-    color: #333333;
+    color: #333;
     background-color: transparent;
   }
   .navbar-default .navbar-nav .open .dropdown-menu > .active > a,
   .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
   .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
-    color: #555555;
+    color: #555;
     background-color: #e7e7e7;
   }
   .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,
   .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,
   .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {
-    color: #cccccc;
+    color: #ccc;
     background-color: transparent;
   }
 }
-
 .navbar-default .navbar-link {
-  color: #777777;
-}
-
+  color: #777;
+}
 .navbar-default .navbar-link:hover {
-  color: #333333;
-}
-
+  color: #333;
+}
+.navbar-default .btn-link {
+  color: #777;
+}
+.navbar-default .btn-link:hover,
+.navbar-default .btn-link:focus {
+  color: #333;
+}
+.navbar-default .btn-link[disabled]:hover,
+fieldset[disabled] .navbar-default .btn-link:hover,
+.navbar-default .btn-link[disabled]:focus,
+fieldset[disabled] .navbar-default .btn-link:focus {
+  color: #ccc;
+}
 .navbar-inverse {
-  background-color: #222222;
+  background-color: #222;
   border-color: #080808;
 }
-
 .navbar-inverse .navbar-brand {
-  color: #999999;
-}
-
+  color: #9d9d9d;
+}
 .navbar-inverse .navbar-brand:hover,
 .navbar-inverse .navbar-brand:focus {
-  color: #ffffff;
+  color: #fff;
   background-color: transparent;
 }
-
 .navbar-inverse .navbar-text {
-  color: #999999;
-}
-
+  color: #9d9d9d;
+}
 .navbar-inverse .navbar-nav > li > a {
-  color: #999999;
-}
-
+  color: #9d9d9d;
+}
 .navbar-inverse .navbar-nav > li > a:hover,
 .navbar-inverse .navbar-nav > li > a:focus {
-  color: #ffffff;
+  color: #fff;
   background-color: transparent;
 }
-
 .navbar-inverse .navbar-nav > .active > a,
 .navbar-inverse .navbar-nav > .active > a:hover,
 .navbar-inverse .navbar-nav > .active > a:focus {
-  color: #ffffff;
+  color: #fff;
   background-color: #080808;
 }
-
 .navbar-inverse .navbar-nav > .disabled > a,
 .navbar-inverse .navbar-nav > .disabled > a:hover,
 .navbar-inverse .navbar-nav > .disabled > a:focus {
-  color: #444444;
+  color: #444;
   background-color: transparent;
 }
-
 .navbar-inverse .navbar-toggle {
-  border-color: #333333;
-}
-
+  border-color: #333;
+}
 .navbar-inverse .navbar-toggle:hover,
 .navbar-inverse .navbar-toggle:focus {
-  background-color: #333333;
-}
-
+  background-color: #333;
+}
 .navbar-inverse .navbar-toggle .icon-bar {
-  background-color: #ffffff;
-}
-
+  background-color: #fff;
+}
 .navbar-inverse .navbar-collapse,
 .navbar-inverse .navbar-form {
   border-color: #101010;
 }
-
 .navbar-inverse .navbar-nav > .open > a,
 .navbar-inverse .navbar-nav > .open > a:hover,
 .navbar-inverse .navbar-nav > .open > a:focus {
-  color: #ffffff;
+  color: #fff;
   background-color: #080808;
 }
-
-.navbar-inverse .navbar-nav > .dropdown > a:hover .caret {
-  border-top-color: #ffffff;
-  border-bottom-color: #ffffff;
-}
-
-.navbar-inverse .navbar-nav > .dropdown > a .caret {
-  border-top-color: #999999;
-  border-bottom-color: #999999;
-}
-
-.navbar-inverse .navbar-nav > .open > a .caret,
-.navbar-inverse .navbar-nav > .open > a:hover .caret,
-.navbar-inverse .navbar-nav > .open > a:focus .caret {
-  border-top-color: #ffffff;
-  border-bottom-color: #ffffff;
-}
-
 @media (max-width: 767px) {
   .navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {
     border-color: #080808;
   }
+  .navbar-inverse .navbar-nav .open .dropdown-menu .divider {
+    background-color: #080808;
+  }
   .navbar-inverse .navbar-nav .open .dropdown-menu > li > a {
-    color: #999999;
+    color: #9d9d9d;
   }
   .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover,
   .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus {
-    color: #ffffff;
+    color: #fff;
     background-color: transparent;
   }
   .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a,
   .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover,
   .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus {
-    color: #ffffff;
+    color: #fff;
     background-color: #080808;
   }
   .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a,
   .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover,
   .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus {
-    color: #444444;
+    color: #444;
     background-color: transparent;
   }
 }
-
 .navbar-inverse .navbar-link {
-  color: #999999;
-}
-
+  color: #9d9d9d;
+}
 .navbar-inverse .navbar-link:hover {
-  color: #ffffff;
-}
-
+  color: #fff;
+}
+.navbar-inverse .btn-link {
+  color: #9d9d9d;
+}
+.navbar-inverse .btn-link:hover,
+.navbar-inverse .btn-link:focus {
+  color: #fff;
+}
+.navbar-inverse .btn-link[disabled]:hover,
+fieldset[disabled] .navbar-inverse .btn-link:hover,
+.navbar-inverse .btn-link[disabled]:focus,
+fieldset[disabled] .navbar-inverse .btn-link:focus {
+  color: #444;
+}
 .breadcrumb {
   padding: 8px 15px;
   margin-bottom: 20px;
@@ -4615,266 +4697,218 @@
   background-color: #f5f5f5;
   border-radius: 4px;
 }
-
 .breadcrumb > li {
   display: inline-block;
 }
-
 .breadcrumb > li + li:before {
   padding: 0 5px;
-  color: #cccccc;
+  color: #ccc;
   content: "/\00a0";
 }
-
 .breadcrumb > .active {
-  color: #999999;
-}
-
+  color: #777;
+}
 .pagination {
   display: inline-block;
   padding-left: 0;
   margin: 20px 0;
   border-radius: 4px;
 }
-
 .pagination > li {
   display: inline;
 }
-
 .pagination > li > a,
 .pagination > li > span {
   position: relative;
   float: left;
   padding: 6px 12px;
   margin-left: -1px;
-  line-height: 1.428571429;
+  line-height: 1.42857143;
+  color: #337ab7;
   text-decoration: none;
-  background-color: #ffffff;
-  border: 1px solid #dddddd;
-}
-
+  background-color: #fff;
+  border: 1px solid #ddd;
+}
 .pagination > li:first-child > a,
 .pagination > li:first-child > span {
   margin-left: 0;
+  border-top-left-radius: 4px;
   border-bottom-left-radius: 4px;
-  border-top-left-radius: 4px;
-}
-
+}
 .pagination > li:last-child > a,
 .pagination > li:last-child > span {
   border-top-right-radius: 4px;
   border-bottom-right-radius: 4px;
 }
-
 .pagination > li > a:hover,
 .pagination > li > span:hover,
 .pagination > li > a:focus,
 .pagination > li > span:focus {
-  background-color: #eeeeee;
-}
-
+  z-index: 2;
+  color: #23527c;
+  background-color: #eee;
+  border-color: #ddd;
+}
 .pagination > .active > a,
 .pagination > .active > span,
 .pagination > .active > a:hover,
 .pagination > .active > span:hover,
 .pagination > .active > a:focus,
 .pagination > .active > span:focus {
-  z-index: 2;
-  color: #ffffff;
+  z-index: 3;
+  color: #fff;
   cursor: default;
-  background-color: #428bca;
-  border-color: #428bca;
-}
-
+  background-color: #337ab7;
+  border-color: #337ab7;
+}
 .pagination > .disabled > span,
+.pagination > .disabled > span:hover,
+.pagination > .disabled > span:focus,
 .pagination > .disabled > a,
 .pagination > .disabled > a:hover,
 .pagination > .disabled > a:focus {
-  color: #999999;
+  color: #777;
   cursor: not-allowed;
-  background-color: #ffffff;
-  border-color: #dddddd;
-}
-
+  background-color: #fff;
+  border-color: #ddd;
+}
 .pagination-lg > li > a,
 .pagination-lg > li > span {
   padding: 10px 16px;
   font-size: 18px;
-}
-
+  line-height: 1.3333333;
+}
 .pagination-lg > li:first-child > a,
 .pagination-lg > li:first-child > span {
+  border-top-left-radius: 6px;
   border-bottom-left-radius: 6px;
-  border-top-left-radius: 6px;
-}
-
+}
 .pagination-lg > li:last-child > a,
 .pagination-lg > li:last-child > span {
   border-top-right-radius: 6px;
   border-bottom-right-radius: 6px;
 }
-
 .pagination-sm > li > a,
 .pagination-sm > li > span {
   padding: 5px 10px;
   font-size: 12px;
-}
-
+  line-height: 1.5;
+}
 .pagination-sm > li:first-child > a,
 .pagination-sm > li:first-child > span {
+  border-top-left-radius: 3px;
   border-bottom-left-radius: 3px;
-  border-top-left-radius: 3px;
-}
-
+}
 .pagination-sm > li:last-child > a,
 .pagination-sm > li:last-child > span {
   border-top-right-radius: 3px;
   border-bottom-right-radius: 3px;
 }
-
 .pager {
   padding-left: 0;
   margin: 20px 0;
   text-align: center;
   list-style: none;
 }
-
-.pager:before,
-.pager:after {
-  display: table;
-  content: " ";
-}
-
-.pager:after {
-  clear: both;
-}
-
-.pager:before,
-.pager:after {
-  display: table;
-  content: " ";
-}
-
-.pager:after {
-  clear: both;
-}
-
 .pager li {
   display: inline;
 }
-
 .pager li > a,
 .pager li > span {
   display: inline-block;
   padding: 5px 14px;
-  background-color: #ffffff;
-  border: 1px solid #dddddd;
+  background-color: #fff;
+  border: 1px solid #ddd;
   border-radius: 15px;
 }
-
 .pager li > a:hover,
 .pager li > a:focus {
   text-decoration: none;
-  background-color: #eeeeee;
-}
-
+  background-color: #eee;
+}
 .pager .next > a,
 .pager .next > span {
   float: right;
 }
-
 .pager .previous > a,
 .pager .previous > span {
   float: left;
 }
-
 .pager .disabled > a,
 .pager .disabled > a:hover,
 .pager .disabled > a:focus,
 .pager .disabled > span {
-  color: #999999;
+  color: #777;
   cursor: not-allowed;
-  background-color: #ffffff;
-}
-
+  background-color: #fff;
+}
 .label {
   display: inline;
   padding: .2em .6em .3em;
   font-size: 75%;
   font-weight: bold;
   line-height: 1;
-  color: #ffffff;
+  color: #fff;
   text-align: center;
   white-space: nowrap;
   vertical-align: baseline;
   border-radius: .25em;
 }
-
-.label[href]:hover,
-.label[href]:focus {
-  color: #ffffff;
+a.label:hover,
+a.label:focus {
+  color: #fff;
   text-decoration: none;
   cursor: pointer;
 }
-
 .label:empty {
   display: none;
 }
-
+.btn .label {
+  position: relative;
+  top: -1px;
+}
 .label-default {
-  background-color: #999999;
-}
-
+  background-color: #777;
+}
 .label-default[href]:hover,
 .label-default[href]:focus {
-  background-color: #808080;
-}
-
+  background-color: #5e5e5e;
+}
 .label-primary {
-  background-color: #428bca;
-}
-
+  background-color: #337ab7;
+}
 .label-primary[href]:hover,
 .label-primary[href]:focus {
-  background-color: #3071a9;
-}
-
+  background-color: #286090;
+}
 .label-success {
   background-color: #5cb85c;
 }
-
 .label-success[href]:hover,
 .label-success[href]:focus {
   background-color: #449d44;
 }
-
 .label-info {
   background-color: #5bc0de;
 }
-
 .label-info[href]:hover,
 .label-info[href]:focus {
   background-color: #31b0d5;
 }
-
 .label-warning {
   background-color: #f0ad4e;
 }
-
 .label-warning[href]:hover,
 .label-warning[href]:focus {
   background-color: #ec971f;
 }
-
 .label-danger {
   background-color: #d9534f;
 }
-
 .label-danger[href]:hover,
 .label-danger[href]:focus {
   background-color: #c9302c;
 }
-
 .badge {
   display: inline-block;
   min-width: 10px;
@@ -4882,204 +4916,189 @@
   font-size: 12px;
   font-weight: bold;
   line-height: 1;
-  color: #ffffff;
+  color: #fff;
   text-align: center;
   white-space: nowrap;
-  vertical-align: baseline;
-  background-color: #999999;
+  vertical-align: middle;
+  background-color: #777;
   border-radius: 10px;
 }
-
 .badge:empty {
   display: none;
 }
-
-a.badge:hover,
-a.badge:focus {
-  color: #ffffff;
-  text-decoration: none;
-  cursor: pointer;
-}
-
 .btn .badge {
   position: relative;
   top: -1px;
 }
-
-a.list-group-item.active > .badge,
+.btn-xs .badge,
+.btn-group-xs > .btn .badge {
+  top: 0;
+  padding: 1px 5px;
+}
+a.badge:hover,
+a.badge:focus {
+  color: #fff;
+  text-decoration: none;
+  cursor: pointer;
+}
+.list-group-item.active > .badge,
 .nav-pills > .active > a > .badge {
-  color: #428bca;
-  background-color: #ffffff;
-}
-
+  color: #337ab7;
+  background-color: #fff;
+}
+.list-group-item > .badge {
+  float: right;
+}
+.list-group-item > .badge + .badge {
+  margin-right: 5px;
+}
 .nav-pills > li > a > .badge {
   margin-left: 3px;
 }
-
 .jumbotron {
-  padding: 30px;
+  padding-top: 30px;
+  padding-bottom: 30px;
   margin-bottom: 30px;
+  color: inherit;
+  background-color: #eee;
+}
+.jumbotron h1,
+.jumbotron .h1 {
+  color: inherit;
+}
+.jumbotron p {
+  margin-bottom: 15px;
   font-size: 21px;
   font-weight: 200;
-  line-height: 2.1428571435;
-  color: inherit;
-  background-color: #eeeeee;
-}
-
-.jumbotron h1 {
-  line-height: 1;
-  color: inherit;
-}
-
-.jumbotron p {
-  line-height: 1.4;
-}
-
-.container .jumbotron {
+}
+.jumbotron > hr {
+  border-top-color: #d5d5d5;
+}
+.container .jumbotron,
+.container-fluid .jumbotron {
+  padding-right: 15px;
+  padding-left: 15px;
   border-radius: 6px;
 }
-
+.jumbotron .container {
+  max-width: 100%;
+}
 @media screen and (min-width: 768px) {
   .jumbotron {
     padding-top: 48px;
     padding-bottom: 48px;
   }
-  .container .jumbotron {
+  .container .jumbotron,
+  .container-fluid .jumbotron {
     padding-right: 60px;
     padding-left: 60px;
   }
-  .jumbotron h1 {
+  .jumbotron h1,
+  .jumbotron .h1 {
     font-size: 63px;
   }
 }
-
 .thumbnail {
-  display: inline-block;
   display: block;
-  height: auto;
-  max-width: 100%;
   padding: 4px;
-  line-height: 1.428571429;
-  background-color: #ffffff;
-  border: 1px solid #dddddd;
+  margin-bottom: 20px;
+  line-height: 1.42857143;
+  background-color: #fff;
+  border: 1px solid #ddd;
   border-radius: 4px;
-  -webkit-transition: all 0.2s ease-in-out;
-          transition: all 0.2s ease-in-out;
-}
-
-.thumbnail > img {
-  display: block;
-  height: auto;
-  max-width: 100%;
-}
-
-a.thumbnail:hover,
-a.thumbnail:focus {
-  border-color: #428bca;
-}
-
-.thumbnail > img {
+  -webkit-transition: border .2s ease-in-out;
+       -o-transition: border .2s ease-in-out;
+          transition: border .2s ease-in-out;
+}
+.thumbnail > img,
+.thumbnail a > img {
   margin-right: auto;
   margin-left: auto;
 }
-
+a.thumbnail:hover,
+a.thumbnail:focus,
+a.thumbnail.active {
+  border-color: #337ab7;
+}
 .thumbnail .caption {
   padding: 9px;
-  color: #333333;
-}
-
+  color: #333;
+}
 .alert {
   padding: 15px;
   margin-bottom: 20px;
   border: 1px solid transparent;
   border-radius: 4px;
 }
-
 .alert h4 {
   margin-top: 0;
   color: inherit;
 }
-
 .alert .alert-link {
   font-weight: bold;
 }
-
 .alert > p,
 .alert > ul {
   margin-bottom: 0;
 }
-
 .alert > p + p {
   margin-top: 5px;
 }
-
-.alert-dismissable {
+.alert-dismissable,
+.alert-dismissible {
   padding-right: 35px;
 }
-
-.alert-dismissable .close {
+.alert-dismissable .close,
+.alert-dismissible .close {
   position: relative;
   top: -2px;
   right: -21px;
   color: inherit;
 }
-
 .alert-success {
-  color: #468847;
+  color: #3c763d;
   background-color: #dff0d8;
   border-color: #d6e9c6;
 }
-
 .alert-success hr {
   border-top-color: #c9e2b3;
 }
-
 .alert-success .alert-link {
-  color: #356635;
-}
-
+  color: #2b542c;
+}
 .alert-info {
-  color: #3a87ad;
+  color: #31708f;
   background-color: #d9edf7;
   border-color: #bce8f1;
 }
-
 .alert-info hr {
   border-top-color: #a6e1ec;
 }
-
 .alert-info .alert-link {
-  color: #2d6987;
-}
-
+  color: #245269;
+}
 .alert-warning {
-  color: #c09853;
+  color: #8a6d3b;
   background-color: #fcf8e3;
-  border-color: #fbeed5;
-}
-
+  border-color: #faebcc;
+}
 .alert-warning hr {
-  border-top-color: #f8e5be;
-}
-
+  border-top-color: #f7e1b5;
+}
 .alert-warning .alert-link {
-  color: #a47e3c;
-}
-
+  color: #66512c;
+}
 .alert-danger {
-  color: #b94a48;
+  color: #a94442;
   background-color: #f2dede;
-  border-color: #eed3d7;
-}
-
+  border-color: #ebccd1;
+}
 .alert-danger hr {
-  border-top-color: #e6c1c7;
-}
-
+  border-top-color: #e4b9c0;
+}
 .alert-danger .alert-link {
-  color: #953b39;
-}
-
+  color: #843534;
+}
 @-webkit-keyframes progress-bar-stripes {
   from {
     background-position: 40px 0;
@@ -5088,8 +5107,7 @@
     background-position: 0 0;
   }
 }
-
-@-moz-keyframes progress-bar-stripes {
+@-o-keyframes progress-bar-stripes {
   from {
     background-position: 40px 0;
   }
@@ -5097,16 +5115,6 @@
     background-position: 0 0;
   }
 }
-
-@-o-keyframes progress-bar-stripes {
-  from {
-    background-position: 0 0;
-  }
-  to {
-    background-position: 40px 0;
-  }
-}
-
 @keyframes progress-bar-stripes {
   from {
     background-position: 40px 0;
@@ -5115,426 +5123,699 @@
     background-position: 0 0;
   }
 }
-
 .progress {
   height: 20px;
   margin-bottom: 20px;
   overflow: hidden;
   background-color: #f5f5f5;
   border-radius: 4px;
-  -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
-          box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
-}
-
+  -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
+          box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
+}
 .progress-bar {
   float: left;
   width: 0;
   height: 100%;
   font-size: 12px;
-  color: #ffffff;
+  line-height: 20px;
+  color: #fff;
   text-align: center;
-  background-color: #428bca;
-  -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);
-          box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);
-  -webkit-transition: width 0.6s ease;
-          transition: width 0.6s ease;
-}
-
-.progress-striped .progress-bar {
-  background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));
-  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-  background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-  background-size: 40px 40px;
-}
-
-.progress.active .progress-bar {
+  background-color: #337ab7;
+  -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
+          box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
+  -webkit-transition: width .6s ease;
+       -o-transition: width .6s ease;
+          transition: width .6s ease;
+}
+.progress-striped .progress-bar,
+.progress-bar-striped {
+  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+  background-image:      -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+  background-image:         linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+  -webkit-background-size: 40px 40px;
+          background-size: 40px 40px;
+}
+.progress.active .progress-bar,
+.progress-bar.active {
   -webkit-animation: progress-bar-stripes 2s linear infinite;
-     -moz-animation: progress-bar-stripes 2s linear infinite;
-      -ms-animation: progress-bar-stripes 2s linear infinite;
        -o-animation: progress-bar-stripes 2s linear infinite;
           animation: progress-bar-stripes 2s linear infinite;
 }
-
 .progress-bar-success {
   background-color: #5cb85c;
 }
-
 .progress-striped .progress-bar-success {
-  background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));
-  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-  background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-}
-
+  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+  background-image:      -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+  background-image:         linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+}
 .progress-bar-info {
   background-color: #5bc0de;
 }
-
 .progress-striped .progress-bar-info {
-  background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));
-  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-  background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-}
-
+  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+  background-image:      -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+  background-image:         linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+}
 .progress-bar-warning {
   background-color: #f0ad4e;
 }
-
 .progress-striped .progress-bar-warning {
-  background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));
-  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-  background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-}
-
+  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+  background-image:      -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+  background-image:         linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+}
 .progress-bar-danger {
   background-color: #d9534f;
 }
-
 .progress-striped .progress-bar-danger {
-  background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));
-  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-  background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-}
-
+  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+  background-image:      -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+  background-image:         linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+}
+.media {
+  margin-top: 15px;
+}
+.media:first-child {
+  margin-top: 0;
+}
 .media,
 .media-body {
   overflow: hidden;
   zoom: 1;
 }
-
-.media,
-.media .media {
-  margin-top: 15px;
-}
-
-.media:first-child {
-  margin-top: 0;
-}
-
+.media-body {
+  width: 10000px;
+}
 .media-object {
   display: block;
 }
-
-.media-heading {
-  margin: 0 0 5px;
-}
-
+.media-object.img-thumbnail {
+  max-width: none;
+}
+.media-right,
+.media > .pull-right {
+  padding-left: 10px;
+}
+.media-left,
 .media > .pull-left {
-  margin-right: 10px;
-}
-
-.media > .pull-right {
-  margin-left: 10px;
-}
-
+  padding-right: 10px;
+}
+.media-left,
+.media-right,
+.media-body {
+  display: table-cell;
+  vertical-align: top;
+}
+.media-middle {
+  vertical-align: middle;
+}
+.media-bottom {
+  vertical-align: bottom;
+}
+.media-heading {
+  margin-top: 0;
+  margin-bottom: 5px;
+}
 .media-list {
   padding-left: 0;
   list-style: none;
 }
-
 .list-group {
   padding-left: 0;
   margin-bottom: 20px;
 }
-
 .list-group-item {
   position: relative;
   display: block;
   padding: 10px 15px;
   margin-bottom: -1px;
-  background-color: #ffffff;
-  border: 1px solid #dddddd;
-}
-
+  background-color: #fff;
+  border: 1px solid #ddd;
+}
 .list-group-item:first-child {
+  border-top-left-radius: 4px;
   border-top-right-radius: 4px;
-  border-top-left-radius: 4px;
-}
-
+}
 .list-group-item:last-child {
   margin-bottom: 0;
   border-bottom-right-radius: 4px;
   border-bottom-left-radius: 4px;
 }
-
-.list-group-item > .badge {
-  float: right;
-}
-
-.list-group-item > .badge + .badge {
-  margin-right: 5px;
-}
-
-a.list-group-item {
-  color: #555555;
-}
-
-a.list-group-item .list-group-item-heading {
-  color: #333333;
-}
-
+a.list-group-item,
+button.list-group-item {
+  color: #555;
+}
+a.list-group-item .list-group-item-heading,
+button.list-group-item .list-group-item-heading {
+  color: #333;
+}
 a.list-group-item:hover,
-a.list-group-item:focus {
+button.list-group-item:hover,
+a.list-group-item:focus,
+button.list-group-item:focus {
+  color: #555;
   text-decoration: none;
   background-color: #f5f5f5;
 }
-
+button.list-group-item {
+  width: 100%;
+  text-align: left;
+}
+.list-group-item.disabled,
+.list-group-item.disabled:hover,
+.list-group-item.disabled:focus {
+  color: #777;
+  cursor: not-allowed;
+  background-color: #eee;
+}
+.list-group-item.disabled .list-group-item-heading,
+.list-group-item.disabled:hover .list-group-item-heading,
+.list-group-item.disabled:focus .list-group-item-heading {
+  color: inherit;
+}
+.list-group-item.disabled .list-group-item-text,
+.list-group-item.disabled:hover .list-group-item-text,
+.list-group-item.disabled:focus .list-group-item-text {
+  color: #777;
+}
 .list-group-item.active,
 .list-group-item.active:hover,
 .list-group-item.active:focus {
   z-index: 2;
-  color: #ffffff;
-  background-color: #428bca;
-  border-color: #428bca;
-}
-
+  color: #fff;
+  background-color: #337ab7;
+  border-color: #337ab7;
+}
 .list-group-item.active .list-group-item-heading,
 .list-group-item.active:hover .list-group-item-heading,
-.list-group-item.active:focus .list-group-item-heading {
+.list-group-item.active:focus .list-group-item-heading,
+.list-group-item.active .list-group-item-heading > small,
+.list-group-item.active:hover .list-group-item-heading > small,
+.list-group-item.active:focus .list-group-item-heading > small,
+.list-group-item.active .list-group-item-heading > .small,
+.list-group-item.active:hover .list-group-item-heading > .small,
+.list-group-item.active:focus .list-group-item-heading > .small {
   color: inherit;
 }
-
 .list-group-item.active .list-group-item-text,
 .list-group-item.active:hover .list-group-item-text,
 .list-group-item.active:focus .list-group-item-text {
-  color: #e1edf7;
-}
-
+  color: #c7ddef;
+}
+.list-group-item-success {
+  color: #3c763d;
+  background-color: #dff0d8;
+}
+a.list-group-item-success,
+button.list-group-item-success {
+  color: #3c763d;
+}
+a.list-group-item-success .list-group-item-heading,
+button.list-group-item-success .list-group-item-heading {
+  color: inherit;
+}
+a.list-group-item-success:hover,
+button.list-group-item-success:hover,
+a.list-group-item-success:focus,
+button.list-group-item-success:focus {
+  color: #3c763d;
+  background-color: #d0e9c6;
+}
+a.list-group-item-success.active,
+button.list-group-item-success.active,
+a.list-group-item-success.active:hover,
+button.list-group-item-success.active:hover,
+a.list-group-item-success.active:focus,
+button.list-group-item-success.active:focus {
+  color: #fff;
+  background-color: #3c763d;
+  border-color: #3c763d;
+}
+.list-group-item-info {
+  color: #31708f;
+  background-color: #d9edf7;
+}
+a.list-group-item-info,
+button.list-group-item-info {
+  color: #31708f;
+}
+a.list-group-item-info .list-group-item-heading,
+button.list-group-item-info .list-group-item-heading {
+  color: inherit;
+}
+a.list-group-item-info:hover,
+button.list-group-item-info:hover,
+a.list-group-item-info:focus,
+button.list-group-item-info:focus {
+  color: #31708f;
+  background-color: #c4e3f3;
+}
+a.list-group-item-info.active,
+button.list-group-item-info.active,
+a.list-group-item-info.active:hover,
+button.list-group-item-info.active:hover,
+a.list-group-item-info.active:focus,
+button.list-group-item-info.active:focus {
+  color: #fff;
+  background-color: #31708f;
+  border-color: #31708f;
+}
+.list-group-item-warning {
+  color: #8a6d3b;
+  background-color: #fcf8e3;
+}
+a.list-group-item-warning,
+button.list-group-item-warning {
+  color: #8a6d3b;
+}
+a.list-group-item-warning .list-group-item-heading,
+button.list-group-item-warning .list-group-item-heading {
+  color: inherit;
+}
+a.list-group-item-warning:hover,
+button.list-group-item-warning:hover,
+a.list-group-item-warning:focus,
+button.list-group-item-warning:focus {
+  color: #8a6d3b;
+  background-color: #faf2cc;
+}
+a.list-group-item-warning.active,
+button.list-group-item-warning.active,
+a.list-group-item-warning.active:hover,
+button.list-group-item-warning.active:hover,
+a.list-group-item-warning.active:focus,
+button.list-group-item-warning.active:focus {
+  color: #fff;
+  background-color: #8a6d3b;
+  border-color: #8a6d3b;
+}
+.list-group-item-danger {
+  color: #a94442;
+  background-color: #f2dede;
+}
+a.list-group-item-danger,
+button.list-group-item-danger {
+  color: #a94442;
+}
+a.list-group-item-danger .list-group-item-heading,
+button.list-group-item-danger .list-group-item-heading {
+  color: inherit;
+}
+a.list-group-item-danger:hover,
+button.list-group-item-danger:hover,
+a.list-group-item-danger:focus,
+button.list-group-item-danger:focus {
+  color: #a94442;
+  background-color: #ebcccc;
+}
+a.list-group-item-danger.active,
+button.list-group-item-danger.active,
+a.list-group-item-danger.active:hover,
+button.list-group-item-danger.active:hover,
+a.list-group-item-danger.active:focus,
+button.list-group-item-danger.active:focus {
+  color: #fff;
+  background-color: #a94442;
+  border-color: #a94442;
+}
 .list-group-item-heading {
   margin-top: 0;
   margin-bottom: 5px;
 }
-
 .list-group-item-text {
   margin-bottom: 0;
   line-height: 1.3;
 }
-
 .panel {
   margin-bottom: 20px;
-  background-color: #ffffff;
+  background-color: #fff;
   border: 1px solid transparent;
   border-radius: 4px;
-  -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
-          box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
-}
-
+  -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
+          box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
+}
 .panel-body {
   padding: 15px;
 }
-
-.panel-body:before,
-.panel-body:after {
-  display: table;
-  content: " ";
-}
-
-.panel-body:after {
-  clear: both;
-}
-
-.panel-body:before,
-.panel-body:after {
-  display: table;
-  content: " ";
-}
-
-.panel-body:after {
-  clear: both;
-}
-
-.panel > .list-group {
-  margin-bottom: 0;
-}
-
-.panel > .list-group .list-group-item {
-  border-width: 1px 0;
-}
-
-.panel > .list-group .list-group-item:first-child {
-  border-top-right-radius: 0;
-  border-top-left-radius: 0;
-}
-
-.panel > .list-group .list-group-item:last-child {
-  border-bottom: 0;
-}
-
-.panel-heading + .list-group .list-group-item:first-child {
-  border-top-width: 0;
-}
-
-.panel > .table {
-  margin-bottom: 0;
-}
-
-.panel > .panel-body + .table {
-  border-top: 1px solid #dddddd;
-}
-
 .panel-heading {
   padding: 10px 15px;
   border-bottom: 1px solid transparent;
+  border-top-left-radius: 3px;
   border-top-right-radius: 3px;
-  border-top-left-radius: 3px;
-}
-
+}
+.panel-heading > .dropdown .dropdown-toggle {
+  color: inherit;
+}
 .panel-title {
   margin-top: 0;
   margin-bottom: 0;
   font-size: 16px;
-}
-
-.panel-title > a {
   color: inherit;
 }
-
+.panel-title > a,
+.panel-title > small,
+.panel-title > .small,
+.panel-title > small > a,
+.panel-title > .small > a {
+  color: inherit;
+}
 .panel-footer {
   padding: 10px 15px;
   background-color: #f5f5f5;
-  border-top: 1px solid #dddddd;
+  border-top: 1px solid #ddd;
+  border-bottom-right-radius: 3px;
+  border-bottom-left-radius: 3px;
+}
+.panel > .list-group,
+.panel > .panel-collapse > .list-group {
+  margin-bottom: 0;
+}
+.panel > .list-group .list-group-item,
+.panel > .panel-collapse > .list-group .list-group-item {
+  border-width: 1px 0;
+  border-radius: 0;
+}
+.panel > .list-group:first-child .list-group-item:first-child,
+.panel > .panel-collapse > .list-group:first-child .list-group-item:first-child {
+  border-top: 0;
+  border-top-left-radius: 3px;
+  border-top-right-radius: 3px;
+}
+.panel > .list-group:last-child .list-group-item:last-child,
+.panel > .panel-collapse > .list-group:last-child .list-group-item:last-child {
+  border-bottom: 0;
+  border-bottom-right-radius: 3px;
+  border-bottom-left-radius: 3px;
+}
+.panel > .panel-heading + .panel-collapse > .list-group .list-group-item:first-child {
+  border-top-left-radius: 0;
+  border-top-right-radius: 0;
+}
+.panel-heading + .list-group .list-group-item:first-child {
+  border-top-width: 0;
+}
+.list-group + .panel-footer {
+  border-top-width: 0;
+}
+.panel > .table,
+.panel > .table-responsive > .table,
+.panel > .panel-collapse > .table {
+  margin-bottom: 0;
+}
+.panel > .table caption,
+.panel > .table-responsive > .table caption,
+.panel > .panel-collapse > .table caption {
+  padding-right: 15px;
+  padding-left: 15px;
+}
+.panel > .table:first-child,
+.panel > .table-responsive:first-child > .table:first-child {
+  border-top-left-radius: 3px;
+  border-top-right-radius: 3px;
+}
+.panel > .table:first-child > thead:first-child > tr:first-child,
+.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child,
+.panel > .table:first-child > tbody:first-child > tr:first-child,
+.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child {
+  border-top-left-radius: 3px;
+  border-top-right-radius: 3px;
+}
+.panel > .table:first-child > thead:first-child > tr:first-child td:first-child,
+.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child,
+.panel > .table:first-child > tbody:first-child > tr:first-child td:first-child,
+.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:first-child,
+.panel > .table:first-child > thead:first-child > tr:first-child th:first-child,
+.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child,
+.panel > .table:first-child > tbody:first-child > tr:first-child th:first-child,
+.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child {
+  border-top-left-radius: 3px;
+}
+.panel > .table:first-child > thead:first-child > tr:first-child td:last-child,
+.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child,
+.panel > .table:first-child > tbody:first-child > tr:first-child td:last-child,
+.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:last-child,
+.panel > .table:first-child > thead:first-child > tr:first-child th:last-child,
+.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child,
+.panel > .table:first-child > tbody:first-child > tr:first-child th:last-child,
+.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child {
+  border-top-right-radius: 3px;
+}
+.panel > .table:last-child,
+.panel > .table-responsive:last-child > .table:last-child {
+  border-bottom-right-radius: 3px;
+  border-bottom-left-radius: 3px;
+}
+.panel > .table:last-child > tbody:last-child > tr:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child,
+.panel > .table:last-child > tfoot:last-child > tr:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child {
   border-bottom-right-radius: 3px;
   border-bottom-left-radius: 3px;
 }
-
+.panel > .table:last-child > tbody:last-child > tr:last-child td:first-child,
+.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child,
+.panel > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
+.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
+.panel > .table:last-child > tbody:last-child > tr:last-child th:first-child,
+.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child,
+.panel > .table:last-child > tfoot:last-child > tr:last-child th:first-child,
+.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child {
+  border-bottom-left-radius: 3px;
+}
+.panel > .table:last-child > tbody:last-child > tr:last-child td:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child,
+.panel > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
+.panel > .table:last-child > tbody:last-child > tr:last-child th:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child,
+.panel > .table:last-child > tfoot:last-child > tr:last-child th:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child {
+  border-bottom-right-radius: 3px;
+}
+.panel > .panel-body + .table,
+.panel > .panel-body + .table-responsive,
+.panel > .table + .panel-body,
+.panel > .table-responsive + .panel-body {
+  border-top: 1px solid #ddd;
+}
+.panel > .table > tbody:first-child > tr:first-child th,
+.panel > .table > tbody:first-child > tr:first-child td {
+  border-top: 0;
+}
+.panel > .table-bordered,
+.panel > .table-responsive > .table-bordered {
+  border: 0;
+}
+.panel > .table-bordered > thead > tr > th:first-child,
+.panel > .table-responsive > .table-bordered > thead > tr > th:first-child,
+.panel > .table-bordered > tbody > tr > th:first-child,
+.panel > .table-responsive > .table-bordered > tbody > tr > th:first-child,
+.panel > .table-bordered > tfoot > tr > th:first-child,
+.panel > .table-responsive > .table-bordered > tfoot > tr > th:first-child,
+.panel > .table-bordered > thead > tr > td:first-child,
+.panel > .table-responsive > .table-bordered > thead > tr > td:first-child,
+.panel > .table-bordered > tbody > tr > td:first-child,
+.panel > .table-responsive > .table-bordered > tbody > tr > td:first-child,
+.panel > .table-bordered > tfoot > tr > td:first-child,
+.panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child {
+  border-left: 0;
+}
+.panel > .table-bordered > thead > tr > th:last-child,
+.panel > .table-responsive > .table-bordered > thead > tr > th:last-child,
+.panel > .table-bordered > tbody > tr > th:last-child,
+.panel > .table-responsive > .table-bordered > tbody > tr > th:last-child,
+.panel > .table-bordered > tfoot > tr > th:last-child,
+.panel > .table-responsive > .table-bordered > tfoot > tr > th:last-child,
+.panel > .table-bordered > thead > tr > td:last-child,
+.panel > .table-responsive > .table-bordered > thead > tr > td:last-child,
+.panel > .table-bordered > tbody > tr > td:last-child,
+.panel > .table-responsive > .table-bordered > tbody > tr > td:last-child,
+.panel > .table-bordered > tfoot > tr > td:last-child,
+.panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child {
+  border-right: 0;
+}
+.panel > .table-bordered > thead > tr:first-child > td,
+.panel > .table-responsive > .table-bordered > thead > tr:first-child > td,
+.panel > .table-bordered > tbody > tr:first-child > td,
+.panel > .table-responsive > .table-bordered > tbody > tr:first-child > td,
+.panel > .table-bordered > thead > tr:first-child > th,
+.panel > .table-responsive > .table-bordered > thead > tr:first-child > th,
+.panel > .table-bordered > tbody > tr:first-child > th,
+.panel > .table-responsive > .table-bordered > tbody > tr:first-child > th {
+  border-bottom: 0;
+}
+.panel > .table-bordered > tbody > tr:last-child > td,
+.panel > .table-responsive > .table-bordered > tbody > tr:last-child > td,
+.panel > .table-bordered > tfoot > tr:last-child > td,
+.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > td,
+.panel > .table-bordered > tbody > tr:last-child > th,
+.panel > .table-responsive > .table-bordered > tbody > tr:last-child > th,
+.panel > .table-bordered > tfoot > tr:last-child > th,
+.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th {
+  border-bottom: 0;
+}
+.panel > .table-responsive {
+  margin-bottom: 0;
+  border: 0;
+}
+.panel-group {
+  margin-bottom: 20px;
+}
 .panel-group .panel {
   margin-bottom: 0;
-  overflow: hidden;
   border-radius: 4px;
 }
-
 .panel-group .panel + .panel {
   margin-top: 5px;
 }
-
 .panel-group .panel-heading {
   border-bottom: 0;
 }
-
-.panel-group .panel-heading + .panel-collapse .panel-body {
-  border-top: 1px solid #dddddd;
-}
-
+.panel-group .panel-heading + .panel-collapse > .panel-body,
+.panel-group .panel-heading + .panel-collapse > .list-group {
+  border-top: 1px solid #ddd;
+}
 .panel-group .panel-footer {
   border-top: 0;
 }
-
 .panel-group .panel-footer + .panel-collapse .panel-body {
-  border-bottom: 1px solid #dddddd;
-}
-
+  border-bottom: 1px solid #ddd;
+}
 .panel-default {
-  border-color: #dddddd;
-}
-
+  border-color: #ddd;
+}
 .panel-default > .panel-heading {
-  color: #333333;
+  color: #333;
   background-color: #f5f5f5;
-  border-color: #dddddd;
-}
-
-.panel-default > .panel-heading + .panel-collapse .panel-body {
-  border-top-color: #dddddd;
-}
-
-.panel-default > .panel-footer + .panel-collapse .panel-body {
-  border-bottom-color: #dddddd;
-}
-
+  border-color: #ddd;
+}
+.panel-default > .panel-heading + .panel-collapse > .panel-body {
+  border-top-color: #ddd;
+}
+.panel-default > .panel-heading .badge {
+  color: #f5f5f5;
+  background-color: #333;
+}
+.panel-default > .panel-footer + .panel-collapse > .panel-body {
+  border-bottom-color: #ddd;
+}
 .panel-primary {
-  border-color: #428bca;
-}
-
+  border-color: #337ab7;
+}
 .panel-primary > .panel-heading {
-  color: #ffffff;
-  background-color: #428bca;
-  border-color: #428bca;
-}
-
-.panel-primary > .panel-heading + .panel-collapse .panel-body {
-  border-top-color: #428bca;
-}
-
-.panel-primary > .panel-footer + .panel-collapse .panel-body {
-  border-bottom-color: #428bca;
-}
-
+  color: #fff;
+  background-color: #337ab7;
+  border-color: #337ab7;
+}
+.panel-primary > .panel-heading + .panel-collapse > .panel-body {
+  border-top-color: #337ab7;
+}
+.panel-primary > .panel-heading .badge {
+  color: #337ab7;
+  background-color: #fff;
+}
+.panel-primary > .panel-footer + .panel-collapse > .panel-body {
+  border-bottom-color: #337ab7;
+}
 .panel-success {
   border-color: #d6e9c6;
 }
-
 .panel-success > .panel-heading {
-  color: #468847;
+  color: #3c763d;
   background-color: #dff0d8;
   border-color: #d6e9c6;
 }
-
-.panel-success > .panel-heading + .panel-collapse .panel-body {
+.panel-success > .panel-heading + .panel-collapse > .panel-body {
   border-top-color: #d6e9c6;
 }
-
-.panel-success > .panel-footer + .panel-collapse .panel-body {
+.panel-success > .panel-heading .badge {
+  color: #dff0d8;
+  background-color: #3c763d;
+}
+.panel-success > .panel-footer + .panel-collapse > .panel-body {
   border-bottom-color: #d6e9c6;
 }
-
-.panel-warning {
-  border-color: #fbeed5;
-}
-
-.panel-warning > .panel-heading {
-  color: #c09853;
-  background-color: #fcf8e3;
-  border-color: #fbeed5;
-}
-
-.panel-warning > .panel-heading + .panel-collapse .panel-body {
-  border-top-color: #fbeed5;
-}
-
-.panel-warning > .panel-footer + .panel-collapse .panel-body {
-  border-bottom-color: #fbeed5;
-}
-
-.panel-danger {
-  border-color: #eed3d7;
-}
-
-.panel-danger > .panel-heading {
-  color: #b94a48;
-  background-color: #f2dede;
-  border-color: #eed3d7;
-}
-
-.panel-danger > .panel-heading + .panel-collapse .panel-body {
-  border-top-color: #eed3d7;
-}
-
-.panel-danger > .panel-footer + .panel-collapse .panel-body {
-  border-bottom-color: #eed3d7;
-}
-
 .panel-info {
   border-color: #bce8f1;
 }
-
 .panel-info > .panel-heading {
-  color: #3a87ad;
+  color: #31708f;
   background-color: #d9edf7;
   border-color: #bce8f1;
 }
-
-.panel-info > .panel-heading + .panel-collapse .panel-body {
+.panel-info > .panel-heading + .panel-collapse > .panel-body {
   border-top-color: #bce8f1;
 }
-
-.panel-info > .panel-footer + .panel-collapse .panel-body {
+.panel-info > .panel-heading .badge {
+  color: #d9edf7;
+  background-color: #31708f;
+}
+.panel-info > .panel-footer + .panel-collapse > .panel-body {
   border-bottom-color: #bce8f1;
 }
-
+.panel-warning {
+  border-color: #faebcc;
+}
+.panel-warning > .panel-heading {
+  color: #8a6d3b;
+  background-color: #fcf8e3;
+  border-color: #faebcc;
+}
+.panel-warning > .panel-heading + .panel-collapse > .panel-body {
+  border-top-color: #faebcc;
+}
+.panel-warning > .panel-heading .badge {
+  color: #fcf8e3;
+  background-color: #8a6d3b;
+}
+.panel-warning > .panel-footer + .panel-collapse > .panel-body {
+  border-bottom-color: #faebcc;
+}
+.panel-danger {
+  border-color: #ebccd1;
+}
+.panel-danger > .panel-heading {
+  color: #a94442;
+  background-color: #f2dede;
+  border-color: #ebccd1;
+}
+.panel-danger > .panel-heading + .panel-collapse > .panel-body {
+  border-top-color: #ebccd1;
+}
+.panel-danger > .panel-heading .badge {
+  color: #f2dede;
+  background-color: #a94442;
+}
+.panel-danger > .panel-footer + .panel-collapse > .panel-body {
+  border-bottom-color: #ebccd1;
+}
+.embed-responsive {
+  position: relative;
+  display: block;
+  height: 0;
+  padding: 0;
+  overflow: hidden;
+}
+.embed-responsive .embed-responsive-item,
+.embed-responsive iframe,
+.embed-responsive embed,
+.embed-responsive object,
+.embed-responsive video {
+  position: absolute;
+  top: 0;
+  bottom: 0;
+  left: 0;
+  width: 100%;
+  height: 100%;
+  border: 0;
+}
+.embed-responsive-16by9 {
+  padding-bottom: 56.25%;
+}
+.embed-responsive-4by3 {
+  padding-bottom: 75%;
+}
 .well {
   min-height: 20px;
   padding: 19px;
@@ -5542,251 +5823,221 @@
   background-color: #f5f5f5;
   border: 1px solid #e3e3e3;
   border-radius: 4px;
-  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
-          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
-}
-
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
+}
 .well blockquote {
   border-color: #ddd;
-  border-color: rgba(0, 0, 0, 0.15);
-}
-
+  border-color: rgba(0, 0, 0, .15);
+}
 .well-lg {
   padding: 24px;
   border-radius: 6px;
 }
-
 .well-sm {
   padding: 9px;
   border-radius: 3px;
 }
-
 .close {
   float: right;
   font-size: 21px;
   font-weight: bold;
   line-height: 1;
-  color: #000000;
-  text-shadow: 0 1px 0 #ffffff;
-  opacity: 0.2;
+  color: #000;
+  text-shadow: 0 1px 0 #fff;
   filter: alpha(opacity=20);
-}
-
+  opacity: .2;
+}
 .close:hover,
 .close:focus {
-  color: #000000;
+  color: #000;
   text-decoration: none;
   cursor: pointer;
-  opacity: 0.5;
   filter: alpha(opacity=50);
-}
-
+  opacity: .5;
+}
 button.close {
+  -webkit-appearance: none;
   padding: 0;
   cursor: pointer;
   background: transparent;
   border: 0;
-  -webkit-appearance: none;
-}
-
+}
 .modal-open {
   overflow: hidden;
 }
-
-body.modal-open,
-.modal-open .navbar-fixed-top,
-.modal-open .navbar-fixed-bottom {
-  margin-right: 15px;
-}
-
 .modal {
   position: fixed;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
-  z-index: 1040;
+  z-index: 1050;
   display: none;
-  overflow: auto;
-  overflow-y: scroll;
-}
-
+  overflow: hidden;
+  -webkit-overflow-scrolling: touch;
+  outline: 0;
+}
 .modal.fade .modal-dialog {
+  -webkit-transition: -webkit-transform .3s ease-out;
+       -o-transition:      -o-transform .3s ease-out;
+          transition:         transform .3s ease-out;
   -webkit-transform: translate(0, -25%);
       -ms-transform: translate(0, -25%);
+       -o-transform: translate(0, -25%);
           transform: translate(0, -25%);
-  -webkit-transition: -webkit-transform 0.3s ease-out;
-     -moz-transition: -moz-transform 0.3s ease-out;
-       -o-transition: -o-transform 0.3s ease-out;
-          transition: transform 0.3s ease-out;
-}
-
+}
 .modal.in .modal-dialog {
   -webkit-transform: translate(0, 0);
       -ms-transform: translate(0, 0);
+       -o-transform: translate(0, 0);
           transform: translate(0, 0);
 }
-
+.modal-open .modal {
+  overflow-x: hidden;
+  overflow-y: auto;
+}
 .modal-dialog {
-  z-index: 1050;
+  position: relative;
   width: auto;
-  padding: 10px;
-  margin-right: auto;
-  margin-left: auto;
-}
-
+  margin: 10px;
+}
 .modal-content {
   position: relative;
-  background-color: #ffffff;
-  border: 1px solid #999999;
-  border: 1px solid rgba(0, 0, 0, 0.2);
+  background-color: #fff;
+  -webkit-background-clip: padding-box;
+          background-clip: padding-box;
+  border: 1px solid #999;
+  border: 1px solid rgba(0, 0, 0, .2);
   border-radius: 6px;
-  outline: none;
-  -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
-          box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
-  background-clip: padding-box;
-}
-
+  outline: 0;
+  -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
+          box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
+}
 .modal-backdrop {
   position: fixed;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
-  z-index: 1030;
-  background-color: #000000;
-}
-
+  z-index: 1040;
+  background-color: #000;
+}
 .modal-backdrop.fade {
-  opacity: 0;
   filter: alpha(opacity=0);
-}
-
+  opacity: 0;
+}
 .modal-backdrop.in {
-  opacity: 0.5;
   filter: alpha(opacity=50);
-}
-
+  opacity: .5;
+}
 .modal-header {
-  min-height: 16.428571429px;
   padding: 15px;
   border-bottom: 1px solid #e5e5e5;
 }
-
 .modal-header .close {
   margin-top: -2px;
 }
-
 .modal-title {
   margin: 0;
-  line-height: 1.428571429;
-}
-
+  line-height: 1.42857143;
+}
 .modal-body {
   position: relative;
-  padding: 20px;
-}
-
+  padding: 15px;
+}
 .modal-footer {
-  padding: 19px 20px 20px;
-  margin-top: 15px;
+  padding: 15px;
   text-align: right;
   border-top: 1px solid #e5e5e5;
 }
-
-.modal-footer:before,
-.modal-footer:after {
-  display: table;
-  content: " ";
-}
-
-.modal-footer:after {
-  clear: both;
-}
-
-.modal-footer:before,
-.modal-footer:after {
-  display: table;
-  content: " ";
-}
-
-.modal-footer:after {
-  clear: both;
-}
-
 .modal-footer .btn + .btn {
   margin-bottom: 0;
   margin-left: 5px;
 }
-
 .modal-footer .btn-group .btn + .btn {
   margin-left: -1px;
 }
-
 .modal-footer .btn-block + .btn-block {
   margin-left: 0;
 }
-
-@media screen and (min-width: 768px) {
+.modal-scrollbar-measure {
+  position: absolute;
+  top: -9999px;
+  width: 50px;
+  height: 50px;
+  overflow: scroll;
+}
+@media (min-width: 768px) {
   .modal-dialog {
-    right: auto;
-    left: 50%;
     width: 600px;
-    padding-top: 30px;
-    padding-bottom: 30px;
+    margin: 30px auto;
   }
   .modal-content {
-    -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
-            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
-  }
-}
-
+    -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
+            box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
+  }
+  .modal-sm {
+    width: 300px;
+  }
+}
+@media (min-width: 992px) {
+  .modal-lg {
+    width: 900px;
+  }
+}
 .tooltip {
   position: absolute;
-  z-index: 1030;
+  z-index: 1070;
   display: block;
+  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
   font-size: 12px;
-  line-height: 1.4;
-  opacity: 0;
+  font-style: normal;
+  font-weight: normal;
+  line-height: 1.42857143;
+  text-align: left;
+  text-align: start;
+  text-decoration: none;
+  text-shadow: none;
+  text-transform: none;
+  letter-spacing: normal;
+  word-break: normal;
+  word-spacing: normal;
+  word-wrap: normal;
+  white-space: normal;
   filter: alpha(opacity=0);
-  visibility: visible;
-}
+  opacity: 0;
 
+  line-break: auto;
+}
 .tooltip.in {
-  opacity: 0.9;
   filter: alpha(opacity=90);
-}
-
+  opacity: .9;
+}
 .tooltip.top {
   padding: 5px 0;
   margin-top: -3px;
 }
-
 .tooltip.right {
   padding: 0 5px;
   margin-left: 3px;
 }
-
 .tooltip.bottom {
   padding: 5px 0;
   margin-top: 3px;
 }
-
 .tooltip.left {
   padding: 0 5px;
   margin-left: -3px;
 }
-
 .tooltip-inner {
   max-width: 200px;
   padding: 3px 8px;
-  color: #ffffff;
+  color: #fff;
   text-align: center;
-  text-decoration: none;
-  background-color: #000000;
+  background-color: #000;
   border-radius: 4px;
 }
-
 .tooltip-arrow {
   position: absolute;
   width: 0;
@@ -5794,119 +6045,121 @@
   border-color: transparent;
   border-style: solid;
 }
-
 .tooltip.top .tooltip-arrow {
   bottom: 0;
   left: 50%;
   margin-left: -5px;
-  border-top-color: #000000;
   border-width: 5px 5px 0;
-}
-
+  border-top-color: #000;
+}
 .tooltip.top-left .tooltip-arrow {
+  right: 5px;
+  bottom: 0;
+  margin-bottom: -5px;
+  border-width: 5px 5px 0;
+  border-top-color: #000;
+}
+.tooltip.top-right .tooltip-arrow {
   bottom: 0;
   left: 5px;
-  border-top-color: #000000;
+  margin-bottom: -5px;
   border-width: 5px 5px 0;
-}
-
-.tooltip.top-right .tooltip-arrow {
-  right: 5px;
-  bottom: 0;
-  border-top-color: #000000;
-  border-width: 5px 5px 0;
-}
-
+  border-top-color: #000;
+}
 .tooltip.right .tooltip-arrow {
   top: 50%;
   left: 0;
   margin-top: -5px;
-  border-right-color: #000000;
   border-width: 5px 5px 5px 0;
-}
-
+  border-right-color: #000;
+}
 .tooltip.left .tooltip-arrow {
   top: 50%;
   right: 0;
   margin-top: -5px;
-  border-left-color: #000000;
   border-width: 5px 0 5px 5px;
-}
-
+  border-left-color: #000;
+}
 .tooltip.bottom .tooltip-arrow {
   top: 0;
   left: 50%;
   margin-left: -5px;
-  border-bottom-color: #000000;
   border-width: 0 5px 5px;
-}
-
+  border-bottom-color: #000;
+}
 .tooltip.bottom-left .tooltip-arrow {
   top: 0;
+  right: 5px;
+  margin-top: -5px;
+  border-width: 0 5px 5px;
+  border-bottom-color: #000;
+}
+.tooltip.bottom-right .tooltip-arrow {
+  top: 0;
   left: 5px;
-  border-bottom-color: #000000;
+  margin-top: -5px;
   border-width: 0 5px 5px;
-}
-
-.tooltip.bottom-right .tooltip-arrow {
-  top: 0;
-  right: 5px;
-  border-bottom-color: #000000;
-  border-width: 0 5px 5px;
-}
-
+  border-bottom-color: #000;
+}
 .popover {
   position: absolute;
   top: 0;
   left: 0;
-  z-index: 1010;
+  z-index: 1060;
   display: none;
   max-width: 276px;
   padding: 1px;
+  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+  font-size: 14px;
+  font-style: normal;
+  font-weight: normal;
+  line-height: 1.42857143;
   text-align: left;
+  text-align: start;
+  text-decoration: none;
+  text-shadow: none;
+  text-transform: none;
+  letter-spacing: normal;
+  word-break: normal;
+  word-spacing: normal;
+  word-wrap: normal;
   white-space: normal;
-  background-color: #ffffff;
-  border: 1px solid #cccccc;
-  border: 1px solid rgba(0, 0, 0, 0.2);
+  background-color: #fff;
+  -webkit-background-clip: padding-box;
+          background-clip: padding-box;
+  border: 1px solid #ccc;
+  border: 1px solid rgba(0, 0, 0, .2);
   border-radius: 6px;
-  -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-          box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-  background-clip: padding-box;
-}
+  -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
+          box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
 
+  line-break: auto;
+}
 .popover.top {
   margin-top: -10px;
 }
-
 .popover.right {
   margin-left: 10px;
 }
-
 .popover.bottom {
   margin-top: 10px;
 }
-
 .popover.left {
   margin-left: -10px;
 }
-
 .popover-title {
   padding: 8px 14px;
   margin: 0;
   font-size: 14px;
-  font-weight: normal;
-  line-height: 18px;
   background-color: #f7f7f7;
   border-bottom: 1px solid #ebebeb;
   border-radius: 5px 5px 0 0;
 }
-
 .popover-content {
   padding: 9px 14px;
 }
-
-.popover .arrow,
-.popover .arrow:after {
+.popover > .arrow,
+.popover > .arrow:after {
   position: absolute;
   display: block;
   width: 0;
@@ -5914,147 +6167,153 @@
   border-color: transparent;
   border-style: solid;
 }
-
-.popover .arrow {
+.popover > .arrow {
   border-width: 11px;
 }
-
-.popover .arrow:after {
-  border-width: 10px;
+.popover > .arrow:after {
   content: "";
-}
-
-.popover.top .arrow {
+  border-width: 10px;
+}
+.popover.top > .arrow {
   bottom: -11px;
   left: 50%;
   margin-left: -11px;
-  border-top-color: #999999;
-  border-top-color: rgba(0, 0, 0, 0.25);
+  border-top-color: #999;
+  border-top-color: rgba(0, 0, 0, .25);
   border-bottom-width: 0;
 }
-
-.popover.top .arrow:after {
+.popover.top > .arrow:after {
   bottom: 1px;
   margin-left: -10px;
-  border-top-color: #ffffff;
+  content: " ";
+  border-top-color: #fff;
   border-bottom-width: 0;
-  content: " ";
-}
-
-.popover.right .arrow {
+}
+.popover.right > .arrow {
   top: 50%;
   left: -11px;
   margin-top: -11px;
-  border-right-color: #999999;
-  border-right-color: rgba(0, 0, 0, 0.25);
+  border-right-color: #999;
+  border-right-color: rgba(0, 0, 0, .25);
   border-left-width: 0;
 }
-
-.popover.right .arrow:after {
+.popover.right > .arrow:after {
   bottom: -10px;
   left: 1px;
-  border-right-color: #ffffff;
+  content: " ";
+  border-right-color: #fff;
   border-left-width: 0;
-  content: " ";
-}
-
-.popover.bottom .arrow {
+}
+.popover.bottom > .arrow {
   top: -11px;
   left: 50%;
   margin-left: -11px;
-  border-bottom-color: #999999;
-  border-bottom-color: rgba(0, 0, 0, 0.25);
   border-top-width: 0;
-}
-
-.popover.bottom .arrow:after {
+  border-bottom-color: #999;
+  border-bottom-color: rgba(0, 0, 0, .25);
+}
+.popover.bottom > .arrow:after {
   top: 1px;
   margin-left: -10px;
-  border-bottom-color: #ffffff;
+  content: " ";
   border-top-width: 0;
-  content: " ";
-}
-
-.popover.left .arrow {
+  border-bottom-color: #fff;
+}
+.popover.left > .arrow {
   top: 50%;
   right: -11px;
   margin-top: -11px;
-  border-left-color: #999999;
-  border-left-color: rgba(0, 0, 0, 0.25);
   border-right-width: 0;
-}
-
-.popover.left .arrow:after {
+  border-left-color: #999;
+  border-left-color: rgba(0, 0, 0, .25);
+}
+.popover.left > .arrow:after {
   right: 1px;
   bottom: -10px;
-  border-left-color: #ffffff;
+  content: " ";
   border-right-width: 0;
-  content: " ";
-}
-
+  border-left-color: #fff;
+}
 .carousel {
   position: relative;
 }
-
 .carousel-inner {
   position: relative;
   width: 100%;
   overflow: hidden;
 }
-
 .carousel-inner > .item {
   position: relative;
   display: none;
-  -webkit-transition: 0.6s ease-in-out left;
-          transition: 0.6s ease-in-out left;
-}
-
+  -webkit-transition: .6s ease-in-out left;
+       -o-transition: .6s ease-in-out left;
+          transition: .6s ease-in-out left;
+}
 .carousel-inner > .item > img,
 .carousel-inner > .item > a > img {
-  display: block;
-  height: auto;
-  max-width: 100%;
   line-height: 1;
 }
+@media all and (transform-3d), (-webkit-transform-3d) {
+  .carousel-inner > .item {
+    -webkit-transition: -webkit-transform .6s ease-in-out;
+         -o-transition:      -o-transform .6s ease-in-out;
+            transition:         transform .6s ease-in-out;
 
+    -webkit-backface-visibility: hidden;
+            backface-visibility: hidden;
+    -webkit-perspective: 1000px;
+            perspective: 1000px;
+  }
+  .carousel-inner > .item.next,
+  .carousel-inner > .item.active.right {
+    left: 0;
+    -webkit-transform: translate3d(100%, 0, 0);
+            transform: translate3d(100%, 0, 0);
+  }
+  .carousel-inner > .item.prev,
+  .carousel-inner > .item.active.left {
+    left: 0;
+    -webkit-transform: translate3d(-100%, 0, 0);
+            transform: translate3d(-100%, 0, 0);
+  }
+  .carousel-inner > .item.next.left,
+  .carousel-inner > .item.prev.right,
+  .carousel-inner > .item.active {
+    left: 0;
+    -webkit-transform: translate3d(0, 0, 0);
+            transform: translate3d(0, 0, 0);
+  }
+}
 .carousel-inner > .active,
 .carousel-inner > .next,
 .carousel-inner > .prev {
   display: block;
 }
-
 .carousel-inner > .active {
   left: 0;
 }
-
 .carousel-inner > .next,
 .carousel-inner > .prev {
   position: absolute;
   top: 0;
   width: 100%;
 }
-
 .carousel-inner > .next {
   left: 100%;
 }
-
 .carousel-inner > .prev {
   left: -100%;
 }
-
 .carousel-inner > .next.left,
 .carousel-inner > .prev.right {
   left: 0;
 }
-
 .carousel-inner > .active.left {
   left: -100%;
 }
-
 .carousel-inner > .active.right {
   left: 100%;
 }
-
 .carousel-control {
   position: absolute;
   top: 0;
@@ -6062,69 +6321,72 @@
   left: 0;
   width: 15%;
   font-size: 20px;
-  color: #ffffff;
+  color: #fff;
   text-align: center;
-  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
-  opacity: 0.5;
+  text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
+  background-color: rgba(0, 0, 0, 0);
   filter: alpha(opacity=50);
-}
-
+  opacity: .5;
+}
 .carousel-control.left {
-  background-image: -webkit-gradient(linear, 0 top, 100% top, from(rgba(0, 0, 0, 0.5)), to(rgba(0, 0, 0, 0.0001)));
-  background-image: -webkit-linear-gradient(left, color-stop(rgba(0, 0, 0, 0.5) 0), color-stop(rgba(0, 0, 0, 0.0001) 100%));
-  background-image: -moz-linear-gradient(left, rgba(0, 0, 0, 0.5) 0, rgba(0, 0, 0, 0.0001) 100%);
-  background-image: linear-gradient(to right, rgba(0, 0, 0, 0.5) 0, rgba(0, 0, 0, 0.0001) 100%);
+  background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
+  background-image:      -o-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
+  background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .5)), to(rgba(0, 0, 0, .0001)));
+  background-image:         linear-gradient(to right, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
   background-repeat: repeat-x;
-  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
-}
-
+}
 .carousel-control.right {
   right: 0;
   left: auto;
-  background-image: -webkit-gradient(linear, 0 top, 100% top, from(rgba(0, 0, 0, 0.0001)), to(rgba(0, 0, 0, 0.5)));
-  background-image: -webkit-linear-gradient(left, color-stop(rgba(0, 0, 0, 0.0001) 0), color-stop(rgba(0, 0, 0, 0.5) 100%));
-  background-image: -moz-linear-gradient(left, rgba(0, 0, 0, 0.0001) 0, rgba(0, 0, 0, 0.5) 100%);
-  background-image: linear-gradient(to right, rgba(0, 0, 0, 0.0001) 0, rgba(0, 0, 0, 0.5) 100%);
+  background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
+  background-image:      -o-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
+  background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .0001)), to(rgba(0, 0, 0, .5)));
+  background-image:         linear-gradient(to right, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
   background-repeat: repeat-x;
-  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
-}
-
+}
 .carousel-control:hover,
 .carousel-control:focus {
-  color: #ffffff;
+  color: #fff;
   text-decoration: none;
-  opacity: 0.9;
   filter: alpha(opacity=90);
-}
-
+  outline: 0;
+  opacity: .9;
+}
 .carousel-control .icon-prev,
 .carousel-control .icon-next,
 .carousel-control .glyphicon-chevron-left,
 .carousel-control .glyphicon-chevron-right {
   position: absolute;
   top: 50%;
-  left: 50%;
   z-index: 5;
   display: inline-block;
-}
-
+  margin-top: -10px;
+}
+.carousel-control .icon-prev,
+.carousel-control .glyphicon-chevron-left {
+  left: 50%;
+  margin-left: -10px;
+}
+.carousel-control .icon-next,
+.carousel-control .glyphicon-chevron-right {
+  right: 50%;
+  margin-right: -10px;
+}
 .carousel-control .icon-prev,
 .carousel-control .icon-next {
   width: 20px;
   height: 20px;
-  margin-top: -10px;
-  margin-left: -10px;
   font-family: serif;
-}
-
+  line-height: 1;
+}
 .carousel-control .icon-prev:before {
   content: '\2039';
 }
-
 .carousel-control .icon-next:before {
   content: '\203a';
 }
-
 .carousel-indicators {
   position: absolute;
   bottom: 10px;
@@ -6136,7 +6398,6 @@
   text-align: center;
   list-style: none;
 }
-
 .carousel-indicators li {
   display: inline-block;
   width: 10px;
@@ -6144,17 +6405,17 @@
   margin: 1px;
   text-indent: -999px;
   cursor: pointer;
-  border: 1px solid #ffffff;
+  background-color: #000 \9;
+  background-color: rgba(0, 0, 0, 0);
+  border: 1px solid #fff;
   border-radius: 10px;
 }
-
 .carousel-indicators .active {
   width: 12px;
   height: 12px;
   margin: 0;
-  background-color: #ffffff;
-}
-
+  background-color: #fff;
+}
 .carousel-caption {
   position: absolute;
   right: 15%;
@@ -6163,24 +6424,31 @@
   z-index: 10;
   padding-top: 20px;
   padding-bottom: 20px;
-  color: #ffffff;
+  color: #fff;
   text-align: center;
-  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
-}
-
+  text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
+}
 .carousel-caption .btn {
   text-shadow: none;
 }
-
 @media screen and (min-width: 768px) {
+  .carousel-control .glyphicon-chevron-left,
+  .carousel-control .glyphicon-chevron-right,
   .carousel-control .icon-prev,
   .carousel-control .icon-next {
     width: 30px;
     height: 30px;
-    margin-top: -15px;
-    margin-left: -15px;
+    margin-top: -10px;
     font-size: 30px;
   }
+  .carousel-control .glyphicon-chevron-left,
+  .carousel-control .icon-prev {
+    margin-left: -10px;
+  }
+  .carousel-control .glyphicon-chevron-right,
+  .carousel-control .icon-next {
+    margin-right: -10px;
+  }
   .carousel-caption {
     right: 20%;
     left: 20%;
@@ -6190,37 +6458,79 @@
     bottom: 20px;
   }
 }
-
 .clearfix:before,
-.clearfix:after {
+.clearfix:after,
+.dl-horizontal dd:before,
+.dl-horizontal dd:after,
+.container:before,
+.container:after,
+.container-fluid:before,
+.container-fluid:after,
+.row:before,
+.row:after,
+.form-horizontal .form-group:before,
+.form-horizontal .form-group:after,
+.btn-toolbar:before,
+.btn-toolbar:after,
+.btn-group-vertical > .btn-group:before,
+.btn-group-vertical > .btn-group:after,
+.nav:before,
+.nav:after,
+.navbar:before,
+.navbar:after,
+.navbar-header:before,
+.navbar-header:after,
+.navbar-collapse:before,
+.navbar-collapse:after,
+.pager:before,
+.pager:after,
+.panel-body:before,
+.panel-body:after,
+.modal-header:before,
+.modal-header:after,
+.modal-footer:before,
+.modal-footer:after {
   display: table;
   content: " ";
 }
-
-.clearfix:after {
+.clearfix:after,
+.dl-horizontal dd:after,
+.container:after,
+.container-fluid:after,
+.row:after,
+.form-horizontal .form-group:after,
+.btn-toolbar:after,
+.btn-group-vertical > .btn-group:after,
+.nav:after,
+.navbar:after,
+.navbar-header:after,
+.navbar-collapse:after,
+.pager:after,
+.panel-body:after,
+.modal-header:after,
+.modal-footer:after {
   clear: both;
 }
-
+.center-block {
+  display: block;
+  margin-right: auto;
+  margin-left: auto;
+}
 .pull-right {
   float: right !important;
 }
-
 .pull-left {
   float: left !important;
 }
-
 .hide {
   display: none !important;
 }
-
 .show {
   display: block !important;
 }
-
 .invisible {
   visibility: hidden;
 }
-
 .text-hide {
   font: 0/0 a;
   color: transparent;
@@ -6228,43 +6538,42 @@
   background-color: transparent;
   border: 0;
 }
-
-.affix {
-  position: fixed;
-}
-
-@-ms-viewport {
-  width: device-width;
-}
-
-@media screen and (max-width: 400px) {
-  @-ms-viewport {
-    width: 320px;
-  }
-}
-
 .hidden {
   display: none !important;
-  visibility: hidden !important;
-}
-
-.visible-xs {
+}
+.affix {
+  position: fixed;
+}
+@-ms-viewport {
+  width: device-width;
+}
+.visible-xs,
+.visible-sm,
+.visible-md,
+.visible-lg {
   display: none !important;
 }
-
-tr.visible-xs {
+.visible-xs-block,
+.visible-xs-inline,
+.visible-xs-inline-block,
+.visible-sm-block,
+.visible-sm-inline,
+.visible-sm-inline-block,
+.visible-md-block,
+.visible-md-inline,
+.visible-md-inline-block,
+.visible-lg-block,
+.visible-lg-inline,
+.visible-lg-inline-block {
   display: none !important;
 }
-
-th.visible-xs,
-td.visible-xs {
-  display: none !important;
-}
-
 @media (max-width: 767px) {
   .visible-xs {
     display: block !important;
   }
+  table.visible-xs {
+    display: table !important;
+  }
   tr.visible-xs {
     display: table-row !important;
   }
@@ -6273,76 +6582,28 @@
     display: table-cell !important;
   }
 }
-
-@media (min-width: 768px) and (max-width: 991px) {
-  .visible-xs.visible-sm {
-    display: block !important;
-  }
-  tr.visible-xs.visible-sm {
-    display: table-row !important;
-  }
-  th.visible-xs.visible-sm,
-  td.visible-xs.visible-sm {
-    display: table-cell !important;
-  }
-}
-
-@media (min-width: 992px) and (max-width: 1199px) {
-  .visible-xs.visible-md {
-    display: block !important;
-  }
-  tr.visible-xs.visible-md {
-    display: table-row !important;
-  }
-  th.visible-xs.visible-md,
-  td.visible-xs.visible-md {
-    display: table-cell !important;
-  }
-}
-
-@media (min-width: 1200px) {
-  .visible-xs.visible-lg {
+@media (max-width: 767px) {
+  .visible-xs-block {
     display: block !important;
   }
-  tr.visible-xs.visible-lg {
-    display: table-row !important;
-  }
-  th.visible-xs.visible-lg,
-  td.visible-xs.visible-lg {
-    display: table-cell !important;
-  }
-}
-
-.visible-sm {
-  display: none !important;
-}
-
-tr.visible-sm {
-  display: none !important;
-}
-
-th.visible-sm,
-td.visible-sm {
-  display: none !important;
-}
-
+}
 @media (max-width: 767px) {
-  .visible-sm.visible-xs {
-    display: block !important;
-  }
-  tr.visible-sm.visible-xs {
-    display: table-row !important;
-  }
-  th.visible-sm.visible-xs,
-  td.visible-sm.visible-xs {
-    display: table-cell !important;
-  }
-}
-
+  .visible-xs-inline {
+    display: inline !important;
+  }
+}
+@media (max-width: 767px) {
+  .visible-xs-inline-block {
+    display: inline-block !important;
+  }
+}
 @media (min-width: 768px) and (max-width: 991px) {
   .visible-sm {
     display: block !important;
   }
+  table.visible-sm {
+    display: table !important;
+  }
   tr.visible-sm {
     display: table-row !important;
   }
@@ -6351,76 +6612,28 @@
     display: table-cell !important;
   }
 }
-
-@media (min-width: 992px) and (max-width: 1199px) {
-  .visible-sm.visible-md {
-    display: block !important;
-  }
-  tr.visible-sm.visible-md {
-    display: table-row !important;
-  }
-  th.visible-sm.visible-md,
-  td.visible-sm.visible-md {
-    display: table-cell !important;
-  }
-}
-
-@media (min-width: 1200px) {
-  .visible-sm.visible-lg {
+@media (min-width: 768px) and (max-width: 991px) {
+  .visible-sm-block {
     display: block !important;
   }
-  tr.visible-sm.visible-lg {
-    display: table-row !important;
-  }
-  th.visible-sm.visible-lg,
-  td.visible-sm.visible-lg {
-    display: table-cell !important;
-  }
-}
-
-.visible-md {
-  display: none !important;
-}
-
-tr.visible-md {
-  display: none !important;
-}
-
-th.visible-md,
-td.visible-md {
-  display: none !important;
-}
-
-@media (max-width: 767px) {
-  .visible-md.visible-xs {
-    display: block !important;
-  }
-  tr.visible-md.visible-xs {
-    display: table-row !important;
-  }
-  th.visible-md.visible-xs,
-  td.visible-md.visible-xs {
-    display: table-cell !important;
-  }
-}
-
+}
 @media (min-width: 768px) and (max-width: 991px) {
-  .visible-md.visible-sm {
-    display: block !important;
-  }
-  tr.visible-md.visible-sm {
-    display: table-row !important;
-  }
-  th.visible-md.visible-sm,
-  td.visible-md.visible-sm {
-    display: table-cell !important;
-  }
-}
-
+  .visible-sm-inline {
+    display: inline !important;
+  }
+}
+@media (min-width: 768px) and (max-width: 991px) {
+  .visible-sm-inline-block {
+    display: inline-block !important;
+  }
+}
 @media (min-width: 992px) and (max-width: 1199px) {
   .visible-md {
     display: block !important;
   }
+  table.visible-md {
+    display: table !important;
+  }
   tr.visible-md {
     display: table-row !important;
   }
@@ -6429,76 +6642,28 @@
     display: table-cell !important;
   }
 }
-
-@media (min-width: 1200px) {
-  .visible-md.visible-lg {
-    display: block !important;
-  }
-  tr.visible-md.visible-lg {
-    display: table-row !important;
-  }
-  th.visible-md.visible-lg,
-  td.visible-md.visible-lg {
-    display: table-cell !important;
-  }
-}
-
-.visible-lg {
-  display: none !important;
-}
-
-tr.visible-lg {
-  display: none !important;
-}
-
-th.visible-lg,
-td.visible-lg {
-  display: none !important;
-}
-
-@media (max-width: 767px) {
-  .visible-lg.visible-xs {
+@media (min-width: 992px) and (max-width: 1199px) {
+  .visible-md-block {
     display: block !important;
   }
-  tr.visible-lg.visible-xs {
-    display: table-row !important;
-  }
-  th.visible-lg.visible-xs,
-  td.visible-lg.visible-xs {
-    display: table-cell !important;
-  }
-}
-
-@media (min-width: 768px) and (max-width: 991px) {
-  .visible-lg.visible-sm {
-    display: block !important;
-  }
-  tr.visible-lg.visible-sm {
-    display: table-row !important;
-  }
-  th.visible-lg.visible-sm,
-  td.visible-lg.visible-sm {
-    display: table-cell !important;
-  }
-}
-
+}
 @media (min-width: 992px) and (max-width: 1199px) {
-  .visible-lg.visible-md {
-    display: block !important;
-  }
-  tr.visible-lg.visible-md {
-    display: table-row !important;
-  }
-  th.visible-lg.visible-md,
-  td.visible-lg.visible-md {
-    display: table-cell !important;
-  }
-}
-
+  .visible-md-inline {
+    display: inline !important;
+  }
+}
+@media (min-width: 992px) and (max-width: 1199px) {
+  .visible-md-inline-block {
+    display: inline-block !important;
+  }
+}
 @media (min-width: 1200px) {
   .visible-lg {
     display: block !important;
   }
+  table.visible-lg {
+    display: table !important;
+  }
   tr.visible-lg {
     display: table-row !important;
   }
@@ -6507,284 +6672,51 @@
     display: table-cell !important;
   }
 }
-
-.hidden-xs {
-  display: block !important;
-}
-
-tr.hidden-xs {
-  display: table-row !important;
-}
-
-th.hidden-xs,
-td.hidden-xs {
-  display: table-cell !important;
-}
-
+@media (min-width: 1200px) {
+  .visible-lg-block {
+    display: block !important;
+  }
+}
+@media (min-width: 1200px) {
+  .visible-lg-inline {
+    display: inline !important;
+  }
+}
+@media (min-width: 1200px) {
+  .visible-lg-inline-block {
+    display: inline-block !important;
+  }
+}
 @media (max-width: 767px) {
   .hidden-xs {
     display: none !important;
   }
-  tr.hidden-xs {
-    display: none !important;
-  }
-  th.hidden-xs,
-  td.hidden-xs {
-    display: none !important;
-  }
-}
-
-@media (min-width: 768px) and (max-width: 991px) {
-  .hidden-xs.hidden-sm {
-    display: none !important;
-  }
-  tr.hidden-xs.hidden-sm {
-    display: none !important;
-  }
-  th.hidden-xs.hidden-sm,
-  td.hidden-xs.hidden-sm {
-    display: none !important;
-  }
-}
-
-@media (min-width: 992px) and (max-width: 1199px) {
-  .hidden-xs.hidden-md {
-    display: none !important;
-  }
-  tr.hidden-xs.hidden-md {
-    display: none !important;
-  }
-  th.hidden-xs.hidden-md,
-  td.hidden-xs.hidden-md {
-    display: none !important;
-  }
-}
-
-@media (min-width: 1200px) {
-  .hidden-xs.hidden-lg {
-    display: none !important;
-  }
-  tr.hidden-xs.hidden-lg {
-    display: none !important;
-  }
-  th.hidden-xs.hidden-lg,
-  td.hidden-xs.hidden-lg {
-    display: none !important;
-  }
-}
-
-.hidden-sm {
-  display: block !important;
-}
-
-tr.hidden-sm {
-  display: table-row !important;
-}
-
-th.hidden-sm,
-td.hidden-sm {
-  display: table-cell !important;
-}
-
-@media (max-width: 767px) {
-  .hidden-sm.hidden-xs {
-    display: none !important;
-  }
-  tr.hidden-sm.hidden-xs {
-    display: none !important;
-  }
-  th.hidden-sm.hidden-xs,
-  td.hidden-sm.hidden-xs {
-    display: none !important;
-  }
-}
-
+}
 @media (min-width: 768px) and (max-width: 991px) {
   .hidden-sm {
     display: none !important;
   }
-  tr.hidden-sm {
-    display: none !important;
-  }
-  th.hidden-sm,
-  td.hidden-sm {
-    display: none !important;
-  }
-}
-
-@media (min-width: 992px) and (max-width: 1199px) {
-  .hidden-sm.hidden-md {
-    display: none !important;
-  }
-  tr.hidden-sm.hidden-md {
-    display: none !important;
-  }
-  th.hidden-sm.hidden-md,
-  td.hidden-sm.hidden-md {
-    display: none !important;
-  }
-}
-
-@media (min-width: 1200px) {
-  .hidden-sm.hidden-lg {
-    display: none !important;
-  }
-  tr.hidden-sm.hidden-lg {
-    display: none !important;
-  }
-  th.hidden-sm.hidden-lg,
-  td.hidden-sm.hidden-lg {
-    display: none !important;
-  }
-}
-
-.hidden-md {
-  display: block !important;
-}
-
-tr.hidden-md {
-  display: table-row !important;
-}
-
-th.hidden-md,
-td.hidden-md {
-  display: table-cell !important;
-}
-
-@media (max-width: 767px) {
-  .hidden-md.hidden-xs {
-    display: none !important;
-  }
-  tr.hidden-md.hidden-xs {
-    display: none !important;
-  }
-  th.hidden-md.hidden-xs,
-  td.hidden-md.hidden-xs {
-    display: none !important;
-  }
-}
-
-@media (min-width: 768px) and (max-width: 991px) {
-  .hidden-md.hidden-sm {
-    display: none !important;
-  }
-  tr.hidden-md.hidden-sm {
-    display: none !important;
-  }
-  th.hidden-md.hidden-sm,
-  td.hidden-md.hidden-sm {
-    display: none !important;
-  }
-}
-
+}
 @media (min-width: 992px) and (max-width: 1199px) {
   .hidden-md {
     display: none !important;
   }
-  tr.hidden-md {
-    display: none !important;
-  }
-  th.hidden-md,
-  td.hidden-md {
-    display: none !important;
-  }
-}
-
-@media (min-width: 1200px) {
-  .hidden-md.hidden-lg {
-    display: none !important;
-  }
-  tr.hidden-md.hidden-lg {
-    display: none !important;
-  }
-  th.hidden-md.hidden-lg,
-  td.hidden-md.hidden-lg {
-    display: none !important;
-  }
-}
-
-.hidden-lg {
-  display: block !important;
-}
-
-tr.hidden-lg {
-  display: table-row !important;
-}
-
-th.hidden-lg,
-td.hidden-lg {
-  display: table-cell !important;
-}
-
-@media (max-width: 767px) {
-  .hidden-lg.hidden-xs {
-    display: none !important;
-  }
-  tr.hidden-lg.hidden-xs {
-    display: none !important;
-  }
-  th.hidden-lg.hidden-xs,
-  td.hidden-lg.hidden-xs {
-    display: none !important;
-  }
-}
-
-@media (min-width: 768px) and (max-width: 991px) {
-  .hidden-lg.hidden-sm {
-    display: none !important;
-  }
-  tr.hidden-lg.hidden-sm {
-    display: none !important;
-  }
-  th.hidden-lg.hidden-sm,
-  td.hidden-lg.hidden-sm {
-    display: none !important;
-  }
-}
-
-@media (min-width: 992px) and (max-width: 1199px) {
-  .hidden-lg.hidden-md {
-    display: none !important;
-  }
-  tr.hidden-lg.hidden-md {
-    display: none !important;
-  }
-  th.hidden-lg.hidden-md,
-  td.hidden-lg.hidden-md {
-    display: none !important;
-  }
-}
-
+}
 @media (min-width: 1200px) {
   .hidden-lg {
     display: none !important;
   }
-  tr.hidden-lg {
-    display: none !important;
-  }
-  th.hidden-lg,
-  td.hidden-lg {
-    display: none !important;
-  }
-}
-
+}
 .visible-print {
   display: none !important;
 }
-
-tr.visible-print {
-  display: none !important;
-}
-
-th.visible-print,
-td.visible-print {
-  display: none !important;
-}
-
 @media print {
   .visible-print {
     display: block !important;
   }
+  table.visible-print {
+    display: table !important;
+  }
   tr.visible-print {
     display: table-row !important;
   }
@@ -6792,14 +6724,34 @@
   td.visible-print {
     display: table-cell !important;
   }
+}
+.visible-print-block {
+  display: none !important;
+}
+@media print {
+  .visible-print-block {
+    display: block !important;
+  }
+}
+.visible-print-inline {
+  display: none !important;
+}
+@media print {
+  .visible-print-inline {
+    display: inline !important;
+  }
+}
+.visible-print-inline-block {
+  display: none !important;
+}
+@media print {
+  .visible-print-inline-block {
+    display: inline-block !important;
+  }
+}
+@media print {
   .hidden-print {
     display: none !important;
   }
-  tr.hidden-print {
-    display: none !important;
-  }
-  th.hidden-print,
-  td.hidden-print {
-    display: none !important;
-  }
-}
+}
+/*# sourceMappingURL=bootstrap.css.map */
--- a/kallithea/public/css/contextbar.css	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/public/css/contextbar.css	Fri Nov 18 01:11:13 2016 +0100
@@ -71,6 +71,10 @@
     vertical-align: text-bottom;
 }
 
+#content #context-bar li span {
+    margin: 0;
+}
+
 ul.horizontal-list {
     display: block;
 }
@@ -88,11 +92,6 @@
     z-index: 999;
 }
 
-#header #header-inner #quick li:hover > ul,
-ul.horizontal-list li:hover > ul {
-    display: block;
-}
-
 #header #header-inner #quick li ul li,
 ul.horizontal-list ul li {
     position: relative;
@@ -140,7 +139,6 @@
 #context-actions a,
 #context-pages a {
     background-repeat: no-repeat;
-    background-position: 10px 50%;
     padding-left: 30px;
 }
 
@@ -179,12 +177,14 @@
     padding: 11px 10px 12px 30px;
 }
 
+ul.dropdown-menu li a:focus,
 #header #header-inner #quick li:hover,
 #revision-changer:hover,
 #context-pages li:hover,
 #context-actions li:hover,
 #content #context-actions li:hover,
 #header #header-inner #quick li.current,
+#header #header-inner #quick li a.menu_link:focus,
 #context-pages li.current {
     background: #6388ad; /* Old browsers */
     background: linear-gradient(to bottom, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0.1) 100%); /* W3C */
@@ -245,7 +245,7 @@
 
 #header #header-inner #quick a,
 #context-pages a,
-#context-pages .admin_menu a {
+#context-pages .dropdown-menu a {
     display: block;
     padding: 0px 10px 1px 10px;
     line-height: 35px;
@@ -253,7 +253,7 @@
 
 #header #header-inner #quick a.thin,
 #context-pages a.thin,
-#context-pages .admin_menu a.thin {
+#context-pages .dropdown-menu a.thin {
     line-height: 28px !important;
 }
 
@@ -264,17 +264,7 @@
 #header #header-inner #quick a {
     overflow: hidden;
 }
-#quick a.childs:after,
-#revision-changer:before,
-#context-pages a.childs:after,
-#context-pages a.dropdown:after {
-    font-family: 'kallithea';
-    content: ' \23f7';
-}
-#context-pages a.childs {
-    padding-right: 30px;
-}
-#context-pages a.childs:after {
+#context-pages a.dropdown-toggle:after {
     position: absolute;
     float: right;
     padding-left: 5px;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/public/css/jquery.dataTables.css	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,453 @@
+/*
+ * Table styles
+ */
+table.dataTable {
+  width: 100%;
+  margin: 0 auto;
+  clear: both;
+  border-collapse: separate;
+  border-spacing: 0;
+  /*
+   * Header and footer styles
+   */
+  /*
+   * Body styles
+   */
+}
+table.dataTable thead th,
+table.dataTable tfoot th {
+  font-weight: bold;
+}
+table.dataTable thead th,
+table.dataTable thead td {
+  padding: 10px 18px;
+  border-bottom: 1px solid #111;
+}
+table.dataTable thead th:active,
+table.dataTable thead td:active {
+  outline: none;
+}
+table.dataTable tfoot th,
+table.dataTable tfoot td {
+  padding: 10px 18px 6px 18px;
+  border-top: 1px solid #111;
+}
+table.dataTable thead .sorting,
+table.dataTable thead .sorting_asc,
+table.dataTable thead .sorting_desc {
+  cursor: pointer;
+  *cursor: hand;
+}
+table.dataTable thead .sorting,
+table.dataTable thead .sorting_asc,
+table.dataTable thead .sorting_desc,
+table.dataTable thead .sorting_asc_disabled,
+table.dataTable thead .sorting_desc_disabled {
+  background-repeat: no-repeat;
+  background-position: center right;
+}
+table.dataTable thead .sorting {
+  background-image: url("../images/sort_both.png");
+}
+table.dataTable thead .sorting_asc {
+  background-image: url("../images/sort_asc.png");
+}
+table.dataTable thead .sorting_desc {
+  background-image: url("../images/sort_desc.png");
+}
+table.dataTable thead .sorting_asc_disabled {
+  background-image: url("../images/sort_asc_disabled.png");
+}
+table.dataTable thead .sorting_desc_disabled {
+  background-image: url("../images/sort_desc_disabled.png");
+}
+table.dataTable tbody tr {
+  background-color: #ffffff;
+}
+table.dataTable tbody tr.selected {
+  background-color: #B0BED9;
+}
+table.dataTable tbody th,
+table.dataTable tbody td {
+  padding: 8px 10px;
+}
+table.dataTable.row-border tbody th, table.dataTable.row-border tbody td, table.dataTable.display tbody th, table.dataTable.display tbody td {
+  border-top: 1px solid #ddd;
+}
+table.dataTable.row-border tbody tr:first-child th,
+table.dataTable.row-border tbody tr:first-child td, table.dataTable.display tbody tr:first-child th,
+table.dataTable.display tbody tr:first-child td {
+  border-top: none;
+}
+table.dataTable.cell-border tbody th, table.dataTable.cell-border tbody td {
+  border-top: 1px solid #ddd;
+  border-right: 1px solid #ddd;
+}
+table.dataTable.cell-border tbody tr th:first-child,
+table.dataTable.cell-border tbody tr td:first-child {
+  border-left: 1px solid #ddd;
+}
+table.dataTable.cell-border tbody tr:first-child th,
+table.dataTable.cell-border tbody tr:first-child td {
+  border-top: none;
+}
+table.dataTable.stripe tbody tr.odd, table.dataTable.display tbody tr.odd {
+  background-color: #f9f9f9;
+}
+table.dataTable.stripe tbody tr.odd.selected, table.dataTable.display tbody tr.odd.selected {
+  background-color: #acbad4;
+}
+table.dataTable.hover tbody tr:hover, table.dataTable.display tbody tr:hover {
+  background-color: #f6f6f6;
+}
+table.dataTable.hover tbody tr:hover.selected, table.dataTable.display tbody tr:hover.selected {
+  background-color: #aab7d1;
+}
+table.dataTable.order-column tbody tr > .sorting_1,
+table.dataTable.order-column tbody tr > .sorting_2,
+table.dataTable.order-column tbody tr > .sorting_3, table.dataTable.display tbody tr > .sorting_1,
+table.dataTable.display tbody tr > .sorting_2,
+table.dataTable.display tbody tr > .sorting_3 {
+  background-color: #fafafa;
+}
+table.dataTable.order-column tbody tr.selected > .sorting_1,
+table.dataTable.order-column tbody tr.selected > .sorting_2,
+table.dataTable.order-column tbody tr.selected > .sorting_3, table.dataTable.display tbody tr.selected > .sorting_1,
+table.dataTable.display tbody tr.selected > .sorting_2,
+table.dataTable.display tbody tr.selected > .sorting_3 {
+  background-color: #acbad5;
+}
+table.dataTable.display tbody tr.odd > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd > .sorting_1 {
+  background-color: #f1f1f1;
+}
+table.dataTable.display tbody tr.odd > .sorting_2, table.dataTable.order-column.stripe tbody tr.odd > .sorting_2 {
+  background-color: #f3f3f3;
+}
+table.dataTable.display tbody tr.odd > .sorting_3, table.dataTable.order-column.stripe tbody tr.odd > .sorting_3 {
+  background-color: whitesmoke;
+}
+table.dataTable.display tbody tr.odd.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_1 {
+  background-color: #a6b4cd;
+}
+table.dataTable.display tbody tr.odd.selected > .sorting_2, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_2 {
+  background-color: #a8b5cf;
+}
+table.dataTable.display tbody tr.odd.selected > .sorting_3, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_3 {
+  background-color: #a9b7d1;
+}
+table.dataTable.display tbody tr.even > .sorting_1, table.dataTable.order-column.stripe tbody tr.even > .sorting_1 {
+  background-color: #fafafa;
+}
+table.dataTable.display tbody tr.even > .sorting_2, table.dataTable.order-column.stripe tbody tr.even > .sorting_2 {
+  background-color: #fcfcfc;
+}
+table.dataTable.display tbody tr.even > .sorting_3, table.dataTable.order-column.stripe tbody tr.even > .sorting_3 {
+  background-color: #fefefe;
+}
+table.dataTable.display tbody tr.even.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_1 {
+  background-color: #acbad5;
+}
+table.dataTable.display tbody tr.even.selected > .sorting_2, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_2 {
+  background-color: #aebcd6;
+}
+table.dataTable.display tbody tr.even.selected > .sorting_3, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_3 {
+  background-color: #afbdd8;
+}
+table.dataTable.display tbody tr:hover > .sorting_1, table.dataTable.order-column.hover tbody tr:hover > .sorting_1 {
+  background-color: #eaeaea;
+}
+table.dataTable.display tbody tr:hover > .sorting_2, table.dataTable.order-column.hover tbody tr:hover > .sorting_2 {
+  background-color: #ececec;
+}
+table.dataTable.display tbody tr:hover > .sorting_3, table.dataTable.order-column.hover tbody tr:hover > .sorting_3 {
+  background-color: #efefef;
+}
+table.dataTable.display tbody tr:hover.selected > .sorting_1, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_1 {
+  background-color: #a2aec7;
+}
+table.dataTable.display tbody tr:hover.selected > .sorting_2, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_2 {
+  background-color: #a3b0c9;
+}
+table.dataTable.display tbody tr:hover.selected > .sorting_3, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_3 {
+  background-color: #a5b2cb;
+}
+table.dataTable.no-footer {
+  border-bottom: 1px solid #111;
+}
+table.dataTable.nowrap th, table.dataTable.nowrap td {
+  white-space: nowrap;
+}
+table.dataTable.compact thead th,
+table.dataTable.compact thead td {
+  padding: 4px 17px 4px 4px;
+}
+table.dataTable.compact tfoot th,
+table.dataTable.compact tfoot td {
+  padding: 4px;
+}
+table.dataTable.compact tbody th,
+table.dataTable.compact tbody td {
+  padding: 4px;
+}
+table.dataTable th.dt-left,
+table.dataTable td.dt-left {
+  text-align: left;
+}
+table.dataTable th.dt-center,
+table.dataTable td.dt-center,
+table.dataTable td.dataTables_empty {
+  text-align: center;
+}
+table.dataTable th.dt-right,
+table.dataTable td.dt-right {
+  text-align: right;
+}
+table.dataTable th.dt-justify,
+table.dataTable td.dt-justify {
+  text-align: justify;
+}
+table.dataTable th.dt-nowrap,
+table.dataTable td.dt-nowrap {
+  white-space: nowrap;
+}
+table.dataTable thead th.dt-head-left,
+table.dataTable thead td.dt-head-left,
+table.dataTable tfoot th.dt-head-left,
+table.dataTable tfoot td.dt-head-left {
+  text-align: left;
+}
+table.dataTable thead th.dt-head-center,
+table.dataTable thead td.dt-head-center,
+table.dataTable tfoot th.dt-head-center,
+table.dataTable tfoot td.dt-head-center {
+  text-align: center;
+}
+table.dataTable thead th.dt-head-right,
+table.dataTable thead td.dt-head-right,
+table.dataTable tfoot th.dt-head-right,
+table.dataTable tfoot td.dt-head-right {
+  text-align: right;
+}
+table.dataTable thead th.dt-head-justify,
+table.dataTable thead td.dt-head-justify,
+table.dataTable tfoot th.dt-head-justify,
+table.dataTable tfoot td.dt-head-justify {
+  text-align: justify;
+}
+table.dataTable thead th.dt-head-nowrap,
+table.dataTable thead td.dt-head-nowrap,
+table.dataTable tfoot th.dt-head-nowrap,
+table.dataTable tfoot td.dt-head-nowrap {
+  white-space: nowrap;
+}
+table.dataTable tbody th.dt-body-left,
+table.dataTable tbody td.dt-body-left {
+  text-align: left;
+}
+table.dataTable tbody th.dt-body-center,
+table.dataTable tbody td.dt-body-center {
+  text-align: center;
+}
+table.dataTable tbody th.dt-body-right,
+table.dataTable tbody td.dt-body-right {
+  text-align: right;
+}
+table.dataTable tbody th.dt-body-justify,
+table.dataTable tbody td.dt-body-justify {
+  text-align: justify;
+}
+table.dataTable tbody th.dt-body-nowrap,
+table.dataTable tbody td.dt-body-nowrap {
+  white-space: nowrap;
+}
+
+table.dataTable,
+table.dataTable th,
+table.dataTable td {
+  -webkit-box-sizing: content-box;
+  -moz-box-sizing: content-box;
+  box-sizing: content-box;
+}
+
+/*
+ * Control feature layout
+ */
+.dataTables_wrapper {
+  position: relative;
+  clear: both;
+  *zoom: 1;
+  zoom: 1;
+}
+.dataTables_wrapper .dataTables_length {
+  float: left;
+}
+.dataTables_wrapper .dataTables_filter {
+  float: right;
+  text-align: right;
+}
+.dataTables_wrapper .dataTables_filter input {
+  margin-left: 0.5em;
+}
+.dataTables_wrapper .dataTables_info {
+  clear: both;
+  float: left;
+  padding-top: 0.755em;
+}
+.dataTables_wrapper .dataTables_paginate {
+  float: right;
+  text-align: right;
+  padding-top: 0.25em;
+}
+.dataTables_wrapper .dataTables_paginate .paginate_button {
+  box-sizing: border-box;
+  display: inline-block;
+  min-width: 1.5em;
+  padding: 0.5em 1em;
+  margin-left: 2px;
+  text-align: center;
+  text-decoration: none !important;
+  cursor: pointer;
+  *cursor: hand;
+  color: #333 !important;
+  border: 1px solid transparent;
+  border-radius: 2px;
+}
+.dataTables_wrapper .dataTables_paginate .paginate_button.current, .dataTables_wrapper .dataTables_paginate .paginate_button.current:hover {
+  color: #333 !important;
+  border: 1px solid #979797;
+  background-color: white;
+  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, white), color-stop(100%, #dcdcdc));
+  /* Chrome,Safari4+ */
+  background: -webkit-linear-gradient(top, white 0%, #dcdcdc 100%);
+  /* Chrome10+,Safari5.1+ */
+  background: -moz-linear-gradient(top, white 0%, #dcdcdc 100%);
+  /* FF3.6+ */
+  background: -ms-linear-gradient(top, white 0%, #dcdcdc 100%);
+  /* IE10+ */
+  background: -o-linear-gradient(top, white 0%, #dcdcdc 100%);
+  /* Opera 11.10+ */
+  background: linear-gradient(to bottom, white 0%, #dcdcdc 100%);
+  /* W3C */
+}
+.dataTables_wrapper .dataTables_paginate .paginate_button.disabled, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:hover, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:active {
+  cursor: default;
+  color: #666 !important;
+  border: 1px solid transparent;
+  background: transparent;
+  box-shadow: none;
+}
+.dataTables_wrapper .dataTables_paginate .paginate_button:hover {
+  color: white !important;
+  border: 1px solid #111;
+  background-color: #585858;
+  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #585858), color-stop(100%, #111));
+  /* Chrome,Safari4+ */
+  background: -webkit-linear-gradient(top, #585858 0%, #111 100%);
+  /* Chrome10+,Safari5.1+ */
+  background: -moz-linear-gradient(top, #585858 0%, #111 100%);
+  /* FF3.6+ */
+  background: -ms-linear-gradient(top, #585858 0%, #111 100%);
+  /* IE10+ */
+  background: -o-linear-gradient(top, #585858 0%, #111 100%);
+  /* Opera 11.10+ */
+  background: linear-gradient(to bottom, #585858 0%, #111 100%);
+  /* W3C */
+}
+.dataTables_wrapper .dataTables_paginate .paginate_button:active {
+  outline: none;
+  background-color: #2b2b2b;
+  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #2b2b2b), color-stop(100%, #0c0c0c));
+  /* Chrome,Safari4+ */
+  background: -webkit-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
+  /* Chrome10+,Safari5.1+ */
+  background: -moz-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
+  /* FF3.6+ */
+  background: -ms-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
+  /* IE10+ */
+  background: -o-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
+  /* Opera 11.10+ */
+  background: linear-gradient(to bottom, #2b2b2b 0%, #0c0c0c 100%);
+  /* W3C */
+  box-shadow: inset 0 0 3px #111;
+}
+.dataTables_wrapper .dataTables_paginate .ellipsis {
+  padding: 0 1em;
+}
+.dataTables_wrapper .dataTables_processing {
+  position: absolute;
+  top: 50%;
+  left: 50%;
+  width: 100%;
+  height: 40px;
+  margin-left: -50%;
+  margin-top: -25px;
+  padding-top: 20px;
+  text-align: center;
+  font-size: 1.2em;
+  background-color: white;
+  background: -webkit-gradient(linear, left top, right top, color-stop(0%, rgba(255, 255, 255, 0)), color-stop(25%, rgba(255, 255, 255, 0.9)), color-stop(75%, rgba(255, 255, 255, 0.9)), color-stop(100%, rgba(255, 255, 255, 0)));
+  background: -webkit-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+  background: -moz-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+  background: -ms-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+  background: -o-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+  background: linear-gradient(to right, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+}
+.dataTables_wrapper .dataTables_length,
+.dataTables_wrapper .dataTables_filter,
+.dataTables_wrapper .dataTables_info,
+.dataTables_wrapper .dataTables_processing,
+.dataTables_wrapper .dataTables_paginate {
+  color: #333;
+}
+.dataTables_wrapper .dataTables_scroll {
+  clear: both;
+}
+.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody {
+  *margin-top: -1px;
+  -webkit-overflow-scrolling: touch;
+}
+.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody th, .dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody td {
+  vertical-align: middle;
+}
+.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody th > div.dataTables_sizing,
+.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody td > div.dataTables_sizing {
+  height: 0;
+  overflow: hidden;
+  margin: 0 !important;
+  padding: 0 !important;
+}
+.dataTables_wrapper.no-footer .dataTables_scrollBody {
+  border-bottom: 1px solid #111;
+}
+.dataTables_wrapper.no-footer div.dataTables_scrollHead table,
+.dataTables_wrapper.no-footer div.dataTables_scrollBody table {
+  border-bottom: none;
+}
+.dataTables_wrapper:after {
+  visibility: hidden;
+  display: block;
+  content: "";
+  clear: both;
+  height: 0;
+}
+
+@media screen and (max-width: 767px) {
+  .dataTables_wrapper .dataTables_info,
+  .dataTables_wrapper .dataTables_paginate {
+    float: none;
+    text-align: center;
+  }
+  .dataTables_wrapper .dataTables_paginate {
+    margin-top: 0.5em;
+  }
+}
+@media screen and (max-width: 640px) {
+  .dataTables_wrapper .dataTables_length,
+  .dataTables_wrapper .dataTables_filter {
+    float: none;
+    text-align: center;
+  }
+  .dataTables_wrapper .dataTables_filter {
+    margin-top: 0.5em;
+  }
+}
--- a/kallithea/public/css/style.css	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/public/css/style.css	Fri Nov 18 01:11:13 2016 +0100
@@ -160,11 +160,21 @@
 .code pre,
 div.readme .readme_box pre,
 div.rst-block pre,
+div.formatted-fixed,
+#changeset_content div.message,
 .CodeMirror .CodeMirror-code pre {
     font-size: 12px;
     font-family: Lucida Console, Consolas, Monaco, Inconsolata, Liberation Mono, monospace;
 }
 
+div.formatted-fixed {
+    white-space: pre-wrap;
+}
+
+.changeset_hash {
+    font-family: Lucida Console, Consolas, Monaco, Inconsolata, Liberation Mono, monospace;
+}
+
 .top-left-rounded-corner {
     border-top-left-radius: 8px;
 }
@@ -208,6 +218,21 @@
     color: #B9B9B9;
 }
 
+.inline-comments-general.show-general-status .hidden.general-only {
+    display: block !important;
+}
+
+/* Bootstrap compatible */
+.show {
+    display: block !important;
+}
+.hidden {
+    display: none !important;
+}
+.invisible {
+    visibility: hidden;
+}
+
 .truncate {
        white-space: nowrap;
        overflow: hidden;
@@ -411,12 +436,12 @@
     padding: 10px 12px 8px;
 }
 
-#header #header-inner #quick li span.icon {
+#header #header-inner #quick li .icon {
     border-left: none;
     padding-left: 10px;
 }
 
-#header #header-inner #quick li span.icon_short {
+#header #header-inner #quick li .icon_short {
     top: 0;
     left: 0;
     border-left: none;
@@ -424,8 +449,8 @@
     padding: 8px 6px 4px;
 }
 
-#header #header-inner #quick li span.icon img,
-#header #header-inner #quick li span.icon_short img {
+#header #header-inner #quick li .icon img,
+#header #header-inner #quick li .icon_short img {
     vertical-align: middle;
     margin-bottom: 2px;
 }
@@ -463,69 +488,6 @@
     text-decoration: none;
 }
 
-td.quick_repo_menu:before {
-    font-family: "kallithea";
-    content: "\23f5";           /* triangle-right */
-    margin-left: 3px;
-    padding-right: 3px;
-}
-
-td.quick_repo_menu {
-    cursor: pointer;
-    width: 8px;
-    border: 1px solid transparent;
-}
-
-td.quick_repo_menu.active:before {
-    font-family: "kallithea";
-    content: "\23f7";           /* triangle-down */
-    margin-left: 1px;
-    padding-right: 1px;
-}
-
-td.quick_repo_menu.active {
-    border: 1px solid #577632;
-    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
-    cursor: pointer;
-}
-
-td.quick_repo_menu .menu_items {
-    margin-top: 5px;
-    margin-left: -6px;
-    width: 150px;
-    position: absolute;
-    background-color: #FFF;
-    background: none repeat scroll 0 0 #FFFFFF;
-    border-color: #577632 #666666 #666666;
-    border-right: 1px solid #666666;
-    border-style: solid;
-    border-width: 1px;
-    box-shadow: 2px 8px 4px rgba(0, 0, 0, 0.2);
-    border-top-style: none;
-}
-
-td.quick_repo_menu .menu_items li {
-    padding: 0 !important;
-}
-
-td.quick_repo_menu .menu_items a {
-    display: block;
-    padding: 4px 12px 4px 8px;
-}
-
-td.quick_repo_menu .menu_items a:hover {
-    background-color: #EEE;
-    text-decoration: none;
-}
-
-td.quick_repo_menu .menu_items .icon img {
-    margin-bottom: -2px;
-}
-
-td.quick_repo_menu .menu_items.hidden {
-    display: none;
-}
-
 .dt_repo {
     white-space: nowrap;
     color: #577632;
@@ -551,219 +513,6 @@
     text-decoration: underline;
 }
 
-.yui-dt-first th {
-    text-align: left;
-}
-
-/*
-    Copyright (c) 2011, Yahoo! Inc. All rights reserved.
-    Code licensed under the BSD License:
-    http://developer.yahoo.com/yui/license.html
-    version: 2.9.0
-*/
-.yui-skin-sam .yui-dt-mask {
-    position: absolute;
-    z-index: 9500;
-}
-.yui-dt-tmp {
-    position: absolute;
-    left: -9000px;
-}
-.yui-dt-scrollable .yui-dt-bd { overflow: auto }
-.yui-dt-scrollable .yui-dt-hd {
-    overflow: hidden;
-    position: relative;
-}
-.yui-dt-scrollable .yui-dt-bd thead tr,
-.yui-dt-scrollable .yui-dt-bd thead th {
-    position: absolute;
-    left: -1500px;
-}
-.yui-skin-sam thead .yui-dt-sortable { cursor: pointer }
-.yui-skin-sam thead .yui-dt-draggable { cursor: move }
-.yui-dt-coltarget {
-    position: absolute;
-    z-index: 999;
-}
-.yui-dt-hd { zoom: 1 }
-th.yui-dt-resizeable .yui-dt-resizerliner { position: relative }
-.yui-dt-resizer {
-    position: absolute;
-    right: 0;
-    bottom: 0;
-    height: 100%;
-    cursor: e-resize;
-    cursor: col-resize;
-    background-color: #CCC;
-    opacity: 0;
-}
-.yui-dt-resizerproxy {
-    visibility: hidden;
-    position: absolute;
-    z-index: 9000;
-    background-color: #CCC;
-    opacity: 0;
-}
-th.yui-dt-hidden .yui-dt-liner,
-td.yui-dt-hidden .yui-dt-liner,
-th.yui-dt-hidden .yui-dt-resizer { display: none }
-.yui-dt-editor,
-.yui-dt-editor-shim {
-    position: absolute;
-    z-index: 9000;
-}
-.yui-skin-sam .yui-dt table {
-    margin: 0;
-    padding: 0;
-    font-family: arial;
-    font-size: inherit;
-    border-collapse: separate;
-    border-spacing: 0;
-    border: 1px solid #7f7f7f;
-}
-.yui-skin-sam .yui-dt thead { border-spacing: 0 }
-.yui-skin-sam .yui-dt caption {
-    color: #000;
-    font-size: 85%;
-    font-weight: normal;
-    font-style: italic;
-    line-height: 1;
-    padding: 1em 0;
-    text-align: center;
-}
-.yui-skin-sam .yui-dt th,
-.yui-skin-sam .yui-dt th a {
-    font-weight: normal;
-    text-decoration: none;
-    color: #000;
-    vertical-align: bottom;
-}
-.yui-skin-sam .yui-dt th {
-    margin: 0;
-    padding: 0;
-    border: 0;
-    border-right: 1px solid #cbcbcb;
-}
-.yui-skin-sam .yui-dt tr.yui-dt-first td { border-top: 1px solid #7f7f7f }
-.yui-skin-sam .yui-dt th .yui-dt-liner { white-space: nowrap }
-.yui-skin-sam .yui-dt-liner {
-    margin: 0;
-    padding: 0;
-}
-.yui-skin-sam .yui-dt-coltarget {
-    width: 5px;
-    background-color: red;
-}
-.yui-skin-sam .yui-dt td {
-    margin: 0;
-    padding: 0;
-    border: 0;
-    border-right: 1px solid #cbcbcb;
-    text-align: left;
-}
-.yui-skin-sam .yui-dt-list td { border-right: 0 }
-.yui-skin-sam .yui-dt-resizer { width: 6px }
-.yui-skin-sam .yui-dt-mask {
-    background-color: #000;
-    opacity: .25;
-}
-.yui-skin-sam .yui-dt-message { background-color: #FFF }
-.yui-skin-sam .yui-dt-scrollable table { border: 0 }
-.yui-skin-sam .yui-dt-scrollable .yui-dt-hd {
-    border-left: 1px solid #7f7f7f;
-    border-top: 1px solid #7f7f7f;
-    border-right: 1px solid #7f7f7f;
-}
-.yui-skin-sam .yui-dt-scrollable .yui-dt-bd {
-    border-left: 1px solid #7f7f7f;
-    border-bottom: 1px solid #7f7f7f;
-    border-right: 1px solid #7f7f7f;
-    background-color: #FFF;
-}
-.yui-skin-sam .yui-dt-scrollable .yui-dt-data tr.yui-dt-last td { border-bottom: 1px solid #7f7f7f }
-.yui-skin-sam th.yui-dt-asc,
-.yui-skin-sam th.yui-dt-sortable .yui-dt-label { margin-right: 10px }
-
-.yui-skin-sam th.yui-dt-asc .yui-dt-liner:after {
-    font-family: "kallithea";
-    content: "\23f6";           /* triangle-up */
-}
-
-.yui-skin-sam th.yui-dt-desc .yui-dt-liner:after {
-    font-family: "kallithea";
-    content: "\23f7";           /* triangle-down */
-}
-
-tbody .yui-dt-editable { cursor: pointer }
-.yui-dt-editor {
-    text-align: left;
-    background-color: #f2f2f2;
-    border: 1px solid #808080;
-    padding: 6px;
-}
-.yui-dt-editor label {
-    padding-left: 4px;
-    padding-right: 6px;
-}
-.yui-dt-editor .yui-dt-button {
-    padding-top: 6px;
-    text-align: right;
-}
-.yui-skin-sam th.yui-dt-highlighted,
-.yui-skin-sam th.yui-dt-highlighted a { background-color: #b2d2ff }
-.yui-skin-sam tr.yui-dt-highlighted,
-.yui-skin-sam tr.yui-dt-highlighted td.yui-dt-asc,
-.yui-skin-sam tr.yui-dt-highlighted td.yui-dt-desc {
-    cursor: pointer;
-    background-color: #b2d2ff;
-}
-.yui-skin-sam .yui-dt-list th.yui-dt-highlighted,
-.yui-skin-sam .yui-dt-list th.yui-dt-highlighted a { background-color: #b2d2ff }
-.yui-skin-sam .yui-dt-list tr.yui-dt-highlighted,
-.yui-skin-sam .yui-dt-list tr.yui-dt-highlighted td.yui-dt-asc,
-.yui-skin-sam .yui-dt-list tr.yui-dt-highlighted td.yui-dt-desc {
-    cursor: pointer;
-    background-color: #b2d2ff;
-}
-.yui-skin-sam th.yui-dt-selected,
-.yui-skin-sam th.yui-dt-selected a { background-color: #446cd7 }
-.yui-skin-sam tr.yui-dt-selected td,
-.yui-skin-sam tr.yui-dt-selected td.yui-dt-asc,
-.yui-skin-sam tr.yui-dt-selected td.yui-dt-desc {
-    background-color: #426fd9;
-    color: #FFF;
-}
-.yui-skin-sam .yui-dt-list th.yui-dt-selected,
-.yui-skin-sam .yui-dt-list th.yui-dt-selected a { background-color: #446cd7 }
-.yui-skin-sam .yui-dt-list tr.yui-dt-selected td,
-.yui-skin-sam .yui-dt-list tr.yui-dt-selected td.yui-dt-asc,
-.yui-skin-sam .yui-dt-list tr.yui-dt-selected td.yui-dt-desc {
-    background-color: #426fd9;
-    color: #FFF;
-}
-.yui-skin-sam .yui-dt-paginator {
-    display: block;
-    margin: 6px 0;
-    white-space: nowrap;
-}
-.yui-skin-sam .yui-dt-paginator .yui-dt-first,
-.yui-skin-sam .yui-dt-paginator .yui-dt-last,
-.yui-skin-sam .yui-dt-paginator .yui-dt-selected { padding: 2px 6px }
-.yui-skin-sam .yui-dt-paginator a.yui-dt-first,
-.yui-skin-sam .yui-dt-paginator a.yui-dt-last { text-decoration: none }
-.yui-skin-sam .yui-dt-paginator .yui-dt-previous,
-.yui-skin-sam .yui-dt-paginator .yui-dt-next { display: none }
-.yui-skin-sam a.yui-dt-page {
-    border: 1px solid #cbcbcb;
-    padding: 2px 6px;
-    text-decoration: none;
-    background-color: #fff;
-}
-.yui-skin-sam .yui-dt-selected {
-    border: 1px solid #fff;
-    background-color: #fff;
-}
-
 #content #left {
     left: 0;
     width: 280px;
@@ -774,7 +523,7 @@
     margin: 0 60px 10px 290px;
 }
 
-#content div.box {
+#content div.panel {
     clear: both;
     background: #fff;
     margin: 0 0 10px;
@@ -783,21 +532,7 @@
     box-shadow: 0 2px 2px rgba(0, 0, 0, 0.6);
 }
 
-#content div.box-left {
-    width: 49%;
-    clear: none;
-    float: left;
-    margin: 0 0 10px;
-}
-
-#content div.box-right {
-    width: 49%;
-    clear: none;
-    float: right;
-    margin: 0 0 10px;
-}
-
-#content div.box div.title {
+#content div.panel div.panel-heading {
     clear: both;
     overflow: hidden;
     background-color: #577632;
@@ -808,7 +543,7 @@
     border-radius: 4px 4px 0 0;
 }
 
-#content div.box div.title h5 {
+#content div.panel div.panel-heading h5 {
     float: left;
     border: none;
     color: #fff;
@@ -816,22 +551,22 @@
     padding: 11px 0 11px 10px;
 }
 
-#content div.box div.title .link-white {
+#content div.panel div.panel-heading .link-white {
     color: #FFFFFF;
 }
 
-#content div.box div.title .link-white.current {
+#content div.panel div.panel-heading .link-white.current {
     color: #BFE3FF;
 }
 
-#content div.box div.title ul.links li {
+#content div.panel div.panel-heading ul.links li {
     list-style: none;
     float: left;
     margin: 0;
     padding: 0;
 }
 
-#content div.box div.title ul.links li a {
+#content div.panel div.panel-heading ul.links li a {
     font-size: 13px;
     font-weight: 700;
     height: 1%;
@@ -839,43 +574,43 @@
     text-decoration: none;
 }
 
-#content div.box div.title ul.links.nav-tabs li a {
+#content div.panel div.panel-heading ul.links.nav-tabs li a {
     float: left;
     color: #fff;
     margin: 0;
     padding: 11px 10px 11px 10px;
 }
 
-#content div.box div.title ul.links.icon-only-links li a {
+#content div.panel div.panel-heading ul.links.icon-only-links li a {
     float: left;
     color: #fff;
     margin: 0;
     padding: 11px 10px 11px 10px;
 }
 
-#content div.box h1,
-#content div.box h2,
-#content div.box h3,
-#content div.box h4,
-#content div.box h5,
-#content div.box h6,
-#content div.box div.h1,
-#content div.box div.h2,
-#content div.box div.h3,
-#content div.box div.h4,
-#content div.box div.h5,
-#content div.box div.h6 {
+#content div.panel h1,
+#content div.panel h2,
+#content div.panel h3,
+#content div.panel h4,
+#content div.panel h5,
+#content div.panel h6,
+#content div.panel div.h1,
+#content div.panel div.h2,
+#content div.panel div.h3,
+#content div.panel div.h4,
+#content div.panel div.h5,
+#content div.panel div.h6 {
     clear: both;
     overflow: hidden;
     margin: 8px 20px 3px;
     padding-bottom: 2px;
 }
 
-#content div.box div.normal-indent {
+#content div.panel div.normal-indent {
     margin: 0 20px 10px 20px;
 }
 
-#content div.box p {
+#content div.panel p {
     color: #5f5f5f;
     font-size: 12px;
     line-height: 150%;
@@ -883,7 +618,7 @@
     padding: 0;
 }
 
-#content div.box blockquote {
+#content div.panel blockquote {
     border-left: 4px solid #DDD;
     color: #5f5f5f;
     font-size: 11px;
@@ -892,67 +627,70 @@
     padding: 0 0 0 14px;
 }
 
-#content div.box blockquote p {
+#content div.panel blockquote p {
     margin: 10px 0;
     padding: 0;
 }
 
-#content div.box dl {
+#content div.panel dl {
     margin: 10px 0px;
 }
 
-#content div.box dt {
+#content div.panel dt {
     font-size: 12px;
     margin: 0;
 }
 
-#content div.box dd {
+#content div.panel dd {
     font-size: 12px;
     margin: 0;
     padding: 8px 0 8px 15px;
 }
 
-#content div.box li {
+#content div.panel li {
     font-size: 12px;
     padding: 4px 0;
 }
 
-#content div.box ul.disc,
-#content div.box ul.circle {
+#content div.panel ul.disc,
+#content div.panel ul.circle {
     margin: 10px 24px 10px 38px;
 }
 
-#content div.box ul.square {
+#content div.panel ul.square {
     margin: 10px 24px 10px 40px;
 }
 
-#content div.box img.left {
+#content div.panel img.left {
     border: none;
     float: left;
     margin: 10px 10px 10px 0;
 }
 
-#content div.box img.right {
+#content div.panel img.right {
     border: none;
     float: right;
     margin: 10px 0 10px 10px;
 }
 
-#content div.box div.messages {
+#content div.panel div.messages {
     clear: both;
     overflow: hidden;
     margin: 0 20px;
     padding: 0;
 }
 
-#content div.box div.message {
-    clear: both;
+#content div.panel div.message {
+    float: left;
     overflow: hidden;
     margin: 0;
     padding: 5px 0;
     white-space: pre-wrap;
 }
-#content div.box div.expand {
+#content div.panel #changeset_content div.message {
+    padding: 15px 0;
+}
+#content div.panel div.expand {
     width: 110%;
     height: 14px;
     font-size: 10px;
@@ -963,52 +701,52 @@
     display: none;
     overflow: hidden;
 }
-#content div.box div.expand .expandtext {
+#content div.panel div.expand .expandtext {
     background-color: #ffffff;
     padding: 2px;
     border-radius: 2px;
 }
 
-#content div.box div.message a {
+#content div.panel div.message a {
     font-weight: 400 !important;
 }
 
-#content div.box div.message div.image {
+#content div.panel div.message div.image {
     float: left;
     margin: 9px 0 0 5px;
     padding: 6px;
 }
 
-#content div.box div.message div.image img {
+#content div.panel div.message div.image img {
     vertical-align: middle;
     margin: 0;
 }
 
-#content div.box div.message div.text {
+#content div.panel div.message div.text {
     float: left;
     margin: 0;
     padding: 9px 6px;
 }
 
-#content div.box div.message div.text h1,
-#content div.box div.message div.text h2,
-#content div.box div.message div.text h3,
-#content div.box div.message div.text h4,
-#content div.box div.message div.text h5,
-#content div.box div.message div.text h6 {
+#content div.panel div.message div.text h1,
+#content div.panel div.message div.text h2,
+#content div.panel div.message div.text h3,
+#content div.panel div.message div.text h4,
+#content div.panel div.message div.text h5,
+#content div.panel div.message div.text h6 {
     border: none;
     margin: 0;
     padding: 0;
 }
 
-#content div.box div.message div.text span {
+#content div.panel div.message div.text span {
     height: 1%;
     display: block;
     margin: 0;
     padding: 5px 0 0;
 }
 
-#content div.box div.message-error {
+#content div.panel div.message-error {
     height: 1%;
     clear: both;
     overflow: hidden;
@@ -1017,11 +755,11 @@
     color: #860006;
 }
 
-#content div.box div.message-error h6 {
+#content div.panel div.message-error h6 {
     color: #860006;
 }
 
-#content div.box div.message-warning {
+#content div.panel div.message-warning {
     height: 1%;
     clear: both;
     overflow: hidden;
@@ -1030,11 +768,11 @@
     color: #5f5200;
 }
 
-#content div.box div.message-warning h6 {
+#content div.panel div.message-warning h6 {
     color: #5f5200;
 }
 
-#content div.box div.message-notice {
+#content div.panel div.message-notice {
     height: 1%;
     clear: both;
     overflow: hidden;
@@ -1043,11 +781,11 @@
     color: #003863;
 }
 
-#content div.box div.message-notice h6 {
+#content div.panel div.message-notice h6 {
     color: #003863;
 }
 
-#content div.box div.message-success {
+#content div.panel div.message-success {
     height: 1%;
     clear: both;
     overflow: hidden;
@@ -1056,11 +794,12 @@
     color: #4e6100;
 }
 
-#content div.box div.message-success h6 {
+#content div.panel div.message-success h6 {
     color: #4e6100;
 }
 
-#content div.box div.form div.fields div.field {
+#content div.panel div.form div.fields div.field,
+#content div.panel div.form div.form-horizontal div.form-group {
     height: 1%;
     min-height: 12px;
     border-bottom: 1px solid #DDD;
@@ -1069,15 +808,18 @@
     padding: 10px 0;
 }
 
-#content div.box div.form div.fields div.field-first {
+#content div.panel div.form div.fields div.field-first,
+#content div.panel div.form div.form-horizontal div.form-group-first {
     padding: 0 0 10px;
 }
 
-#content div.box div.form div.fields div.field-noborder {
+#content div.panel div.form div.fields div.field-noborder,
+#content div.panel div.form div.form-horizontal div.form-group-noborder {
     border-bottom: 0 !important;
 }
 
-#content div.box div.form div.fields div.field span.error-message {
+#content div.panel div.form div.fields div.field span.error-message,
+#content div.panel div.form div.form-horizontal div.form-group span.error-message {
     height: 1%;
     display: inline-block;
     color: red;
@@ -1085,7 +827,8 @@
     padding: 0;
 }
 
-#content div.box div.form div.fields div.field span.success {
+#content div.panel div.form div.fields div.field span.success,
+#content div.panel div.form div.form-horizontal div.form-group span.success {
     height: 1%;
     display: block;
     color: #316309;
@@ -1093,84 +836,49 @@
     padding: 0;
 }
 
-#content div.box div.form div.fields div.field div.label {
-    left: 70px;
-    width: 155px;
-    position: absolute;
+#content div.panel div.form div.fields div.field > p,
+#content div.panel div.form div.form-horizontal div.form-group > label {
     margin: 0;
-    padding: 5px 0 0 0px;
-}
-
-#content div.box div.form div.fields div.field div.label-summary {
-    left: 30px;
+}
+
+#content div.panel div.form div.fields div.field > label,
+#content div.panel div.form div.form-horizontal div.form-group > label {
     width: 155px;
     position: absolute;
     margin: 0;
     padding: 0px 0 0 0px;
 }
 
-#content div.box-left div.form div.fields div.field div.label,
-#content div.box-right div.form div.fields div.field div.label,
-#content div.box-left div.form div.fields div.field div.label,
-#content div.box-left div.form div.fields div.field div.label-summary,
-#content div.box-right div.form div.fields div.field div.label-summary,
-#content div.box-left div.form div.fields div.field div.label-summary {
-    clear: both;
-    overflow: hidden;
-    left: 0;
-    width: auto;
-    position: relative;
-    margin: 0;
-    padding: 0 0 8px;
-}
-
-#content div.box div.form div.fields div.field div.label-select {
-    padding: 5px 0 0 5px;
-}
-
-#content div.box-left div.form div.fields div.field div.label-select,
-#content div.box-right div.form div.fields div.field div.label-select {
-    padding: 0 0 8px;
-}
-
-#content div.box-left div.form div.fields div.field div.label-textarea,
-#content div.box-right div.form div.fields div.field div.label-textarea {
-    padding: 0 0 8px !important;
-}
-
-#content div.box div.form div.fields div.field div.label label,
-div.label label {
+#content div.panel div.form div.fields div.field > label,
+#content div.panel div.form div.form-horizontal div.form-group > label {
     color: #393939;
     font-weight: 700;
 }
-#content div.box div.form div.fields div.field div.label label,
-div.label-summary label {
-    color: #393939;
-    font-weight: 700;
-}
-#content div.box div.form div.fields div.field div.input {
+
+#content div.panel div.form div.fields div.field div.input,
+#content div.panel div.form div.form-horizontal div.form-group div.input {
     margin: 0 0 0 200px;
 }
 
-#content div.box div.form div.fields div.field div.input.summary {
+#content div.panel div.form div.fields div.field div.input.summary,
+#content div.panel div.form div.form-horizontal div.form-group div.input.summary {
     margin: 0 0 0 110px;
 }
-#content div.box div.form div.fields div.field div.input.summary-short {
+#content div.panel div.form div.fields div.field div.input.summary-short,
+#content div.panel div.form div.form-horizontal div.form-group div.input.summary-short {
     margin: 0 0 0 110px;
 }
-#content div.box div.form div.fields div.field div.file {
-    margin: 0 0 0 200px;
-}
-#content div.box div.form div.fields div.field div.editor {
+#content div.panel div.form div.fields div.field div.file,
+#content div.panel div.form div.form-horizontal div.form-group div.file {
     margin: 0 0 0 200px;
 }
-
-#content div.box-left div.form div.fields div.field div.input,
-#content div.box-right div.form div.fields div.field div.input {
-    margin: 0 0 0 0px;
-}
-
-#content div.box div.form div.fields div.field div.input input,
+#content div.panel div.form div.fields div.field div.editor,
+#content div.panel div.form div.form-horizontal div.form-group div.editor {
+    margin: 0 0 0 200px;
+}
+
+#content div.panel div.form div.fields div.field div.input input,
+#content div.panel div.form div.form-horizontal div.form-group div.input input,
 .reviewer_ac input {
     background: #FFF;
     border-top: 1px solid #b3b3b3;
@@ -1183,14 +891,17 @@
     padding: 7px 7px 6px;
 }
 
-#content div.box div.form div.fields div.field div.input input#clone_url,
-#content div.box div.form div.fields div.field div.input input#clone_url_id
+#content div.panel div.form div.fields div.field div.input input#clone_url,
+#content div.panel div.form div.form-horizontal div.form-group div.input input#clone_url,
+#content div.panel div.form div.fields div.field div.input input#clone_url_id
+#content div.panel div.form div.form-horizontal div.form-group div.input input#clone_url_id
 {
     font-size: 14px;
     padding: 0 2px;
 }
 
-#content div.box div.form div.fields div.field div.file input {
+#content div.panel div.form div.fields div.field div.file input,
+#content div.panel div.form div.form-horizontal div.form-group div.file input {
     background: none repeat scroll 0 0 #FFFFFF;
     border-color: #B3B3B3 #EAEAEA #EAEAEA #B3B3B3;
     border-style: solid;
@@ -1206,23 +917,28 @@
     background-color: #F5F5F5 !important;
 }
 
-#content div.box div.form div.fields div.field div.input input.small {
+#content div.panel div.form div.fields div.field div.input input.small,
+#content div.panel div.form div.form-horizontal div.form-group div.input input.small {
     width: 30%;
 }
 
-#content div.box div.form div.fields div.field div.input input.medium {
+#content div.panel div.form div.fields div.field div.input input.medium,
+#content div.panel div.form div.form-horizontal div.form-group div.input input.medium {
     width: 55%;
 }
 
-#content div.box div.form div.fields div.field div.input input.large {
+#content div.panel div.form div.fields div.field div.input input.large,
+#content div.panel div.form div.form-horizontal div.form-group div.input input.large {
     width: 85%;
 }
 
-#content div.box div.form div.fields div.field div.input input.date {
+#content div.panel div.form div.fields div.field div.input input.date,
+#content div.panel div.form div.form-horizontal div.form-group div.input input.date {
     width: 177px;
 }
 
-#content div.box div.form div.fields div.field div.input input.button {
+#content div.panel div.form div.fields div.field div.input input.button,
+#content div.panel div.form div.form-horizontal div.form-group div.input input.button {
     background: #D4D0C8;
     border-top: 1px solid #FFF;
     border-left: 1px solid #FFF;
@@ -1233,7 +949,8 @@
     padding: 4px 8px;
 }
 
-#content div.box div.form div.fields div.field div.textarea {
+#content div.panel div.form div.fields div.field div.textarea,
+#content div.panel div.form div.form-horizontal div.form-group div.textarea {
     border-top: 1px solid #b3b3b3;
     border-left: 1px solid #b3b3b3;
     border-right: 1px solid #eaeaea;
@@ -1242,12 +959,14 @@
     padding: 7px 7px 6px;
 }
 
-#content div.box div.form div.fields div.field div.textarea-editor {
+#content div.panel div.form div.fields div.field div.textarea-editor,
+#content div.panel div.form div.form-horizontal div.form-group div.textarea-editor {
     border: 1px solid #ddd;
     padding: 0;
 }
 
-#content div.box div.form div.fields div.field div.textarea textarea {
+#content div.panel div.form div.fields div.field div.textarea textarea,
+#content div.panel div.form div.form-horizontal div.form-group div.textarea textarea {
     width: 100%;
     height: 220px;
     overflow-y: auto;
@@ -1260,42 +979,45 @@
     padding: 0;
 }
 
-#content div.box-left div.form div.fields div.field div.textarea textarea,
-#content div.box-right div.form div.fields div.field div.textarea textarea {
-    width: 100%;
-    height: 100px;
-}
-
-#content div.box div.form div.fields div.field div.textarea table {
+#content div.panel div.form div.fields div.field div.textarea table,
+#content div.panel div.form div.form-horizontal div.form-group div.textarea table {
     width: 100%;
     border: none;
     margin: 0;
     padding: 0;
 }
 
-#content div.box div.form div.fields div.field div.textarea table td {
+#content div.panel div.form div.fields div.field div.textarea table td,
+#content div.panel div.form div.form-horizontal div.form-group div.textarea table td {
     background: #DDD;
     border: none;
     padding: 0;
 }
 
-#content div.box div.form div.fields div.field div.textarea table td table {
+#content div.panel div.form div.fields div.field div.textarea table td table,
+#content div.panel div.form div.form-horizontal div.form-group div.textarea table td table {
     width: auto;
     border: none;
     margin: 0;
     padding: 0;
 }
 
-#content div.box div.form div.fields div.field div.textarea table td table td {
+#content div.panel div.form div.fields div.field div.textarea table td table td,
+#content div.panel div.form div.form-horizontal div.form-group div.textarea table td table td {
     font-size: 11px;
     padding: 5px 5px 5px 0;
 }
 
-#content div.box div.form div.fields div.field input[type=text]:focus,
-#content div.box div.form div.fields div.field input[type=password]:focus,
-#content div.box div.form div.fields div.field input[type=file]:focus,
-#content div.box div.form div.fields div.field textarea:focus,
-#content div.box div.form div.fields div.field select:focus,
+#content div.panel div.form div.fields div.field input[type=text]:focus,
+#content div.panel div.form div.form-horizontal div.form-group input[type=text]:focus,
+#content div.panel div.form div.fields div.field input[type=password]:focus,
+#content div.panel div.form div.form-horizontal div.form-group input[type=password]:focus,
+#content div.panel div.form div.fields div.field input[type=file]:focus,
+#content div.panel div.form div.form-horizontal div.form-group input[type=file]:focus,
+#content div.panel div.form div.fields div.field textarea:focus,
+#content div.panel div.form div.form-horizontal div.form-group textarea:focus,
+#content div.panel div.form div.fields div.field select:focus,
+#content div.panel div.form div.form-horizontal div.form-group select:focus,
 .reviewer_ac input:focus {
     background: #f6f6f6;
     border-color: #666;
@@ -1305,15 +1027,16 @@
     padding: 10px
 }
 
-div.form div.fields div.field div.button {
+div.form div.fields div.field div.button,
+div.form div.form-horizontal div.form-group div.button {
     margin: 0;
     padding: 0 0 0 8px;
 }
-#content div.box table.noborder {
+#content div.panel table.noborder {
     border: 1px solid transparent;
 }
 
-#content div.box table {
+#content div.panel table {
     width: 100%;
     border-collapse: separate;
     margin: 0;
@@ -1322,63 +1045,63 @@
     border-radius: 4px;
 }
 
-#content div.box table th {
+#content div.panel table th {
     background: #eee;
     border-bottom: 1px solid #ddd;
     padding: 5px 0px 5px 5px;
     text-align: left;
 }
 
-#content div.box table th.left {
+#content div.panel table th.left {
     text-align: left;
 }
 
-#content div.box table th.right {
+#content div.panel table th.right {
     text-align: right;
 }
 
-#content div.box table th.center {
+#content div.panel table th.center {
     text-align: center;
 }
 
-#content div.box table th.selected {
+#content div.panel table th.selected {
     vertical-align: middle;
     padding: 0;
 }
 
-#content div.box table td {
+#content div.panel table td {
     background: #fff;
     border-bottom: 1px solid #cdcdcd;
     vertical-align: middle;
     padding: 5px;
 }
 
-#content div.box table td.compact {
+#content div.panel table td.compact {
     padding: 0;
 }
 
-#content div.box table tr.selected td {
+#content div.panel table tr.selected td {
     background: #FFC;
 }
 
-#content div.box table td.selected {
+#content div.panel table td.selected {
     width: 3%;
     text-align: center;
     vertical-align: middle;
     padding: 0;
 }
 
-#content div.box table td.action {
+#content div.panel table td.action {
     width: 45%;
     text-align: left;
 }
 
-#content div.box table td.date {
+#content div.panel table td.date {
     width: 33%;
     text-align: center;
 }
 
-#content div.box div.action {
+#content div.panel div.action {
     float: right;
     background: #FFF;
     text-align: right;
@@ -1386,85 +1109,17 @@
     padding: 0;
 }
 
-#content div.box div.action select {
+#content div.panel div.action select {
     font-size: 11px;
     margin: 0;
 }
 
-#content div.box div.action .ui-selectmenu {
-    margin: 0;
-    padding: 0;
-}
-
-#content div.box div.pagination {
-    height: 1%;
-    clear: both;
-    overflow: hidden;
-    margin: 10px 0 0;
-    padding: 0;
-}
-
-#content div.box div.pagination ul.pager {
-    float: right;
-    text-align: right;
+#content div.panel div.action .ui-selectmenu {
     margin: 0;
     padding: 0;
 }
 
-#content div.box div.pagination ul.pager li {
-    height: 1%;
-    float: left;
-    list-style: none;
-    background: #ebebeb url("../images/pager.png") repeat-x;
-    border-top: 1px solid #dedede;
-    border-left: 1px solid #cfcfcf;
-    border-right: 1px solid #c4c4c4;
-    border-bottom: 1px solid #c4c4c4;
-    color: #4A4A4A;
-    font-weight: 700;
-    margin: 0 0 0 4px;
-    padding: 0;
-}
-
-#content div.box div.pagination ul.pager li.separator {
-    padding: 6px;
-}
-
-#content div.box div.pagination ul.pager li.current {
-    background: #b4b4b4 url("../images/pager_selected.png") repeat-x;
-    border-top: 1px solid #ccc;
-    border-left: 1px solid #bebebe;
-    border-right: 1px solid #b1b1b1;
-    border-bottom: 1px solid #afafaf;
-    color: #515151;
-    padding: 6px;
-}
-
-#content div.box div.pagination ul.pager li a {
-    height: 1%;
-    display: block;
-    float: left;
-    color: #515151;
-    text-decoration: none;
-    margin: 0;
-    padding: 6px;
-}
-
-#content div.box div.pagination ul.pager li a:hover,
-#content div.box div.pagination ul.pager li a:active {
-    background: #b4b4b4 url("../images/pager_selected.png") repeat-x;
-    border-top: 1px solid #ccc;
-    border-left: 1px solid #bebebe;
-    border-right: 1px solid #b1b1b1;
-    border-bottom: 1px solid #afafaf;
-    margin: -1px;
-}
-
-#content div.box div.pagination-right {
-    float: right;
-}
-
-#content div.box div.pagination-wh {
+#content div.panel ul.pagination {
     height: 1%;
     overflow: hidden;
     text-align: right;
@@ -1472,21 +1127,20 @@
     padding: 0;
 }
 
-#content div.box div.pagination-wh > :first-child {
+#content div.panel ul.pagination > li {
+    display: inline;
+}
+
+#content div.panel ul.pagination > :first-child {
     border-radius: 4px 0px 0px 4px;
 }
 
-#content div.box div.pagination-wh > :last-child {
+#content div.panel ul.pagination > :last-child {
     border-radius: 0px 4px 4px 0px;
     border-right: 1px solid #cfcfcf;
 }
 
-#content div.box div.pagination-wh a,
-#content div.box div.pagination-wh span.pager_dotdot,
-#content div.box div.pagination-wh span.yui-pg-previous,
-#content div.box div.pagination-wh span.yui-pg-last,
-#content div.box div.pagination-wh span.yui-pg-next,
-#content div.box div.pagination-wh span.yui-pg-first {
+#content div.panel ul.pagination > li {
     height: 1%;
     float: left;
     background: #ebebeb url("../images/pager.png") repeat-x;
@@ -1498,20 +1152,16 @@
     padding: 6px;
 }
 
-#content div.box div.pagination-wh span.pager_curpage {
-    height: 1%;
-    float: left;
+#content div.panel ul.pagination > li.active {
     background: #b4b4b4 url("../images/pager_selected.png") repeat-x;
     border-top: 1px solid #ccc;
     border-left: 1px solid #bebebe;
     border-bottom: 1px solid #afafaf;
     color: #515151;
-    font-weight: 700;
-    padding: 6px;
-}
-
-#content div.box div.pagination-wh a:hover,
-#content div.box div.pagination-wh a:active {
+}
+
+#content div.panel ul.pagination > a:hover,
+#content div.panel ul.pagination > a:active {
     background: #b4b4b4 url("../images/pager_selected.png") repeat-x;
     border-top: 1px solid #ccc;
     border-left: 1px solid #bebebe;
@@ -1519,7 +1169,12 @@
     text-decoration: none;
 }
 
-#content div.box div.traffic div.legend {
+#content div.panel ul.pagination > li a {
+    color: inherit;
+    text-decoration: inherit;
+}
+
+#content div.panel div.traffic div.legend {
     clear: both;
     overflow: hidden;
     border-bottom: 1px solid #ddd;
@@ -1527,14 +1182,14 @@
     padding: 0 0 10px;
 }
 
-#content div.box div.traffic div.legend h6 {
+#content div.panel div.traffic div.legend h6 {
     float: left;
     border: none;
     margin: 0;
     padding: 0;
 }
 
-#content div.box div.traffic div.legend li {
+#content div.panel div.traffic div.legend li {
     list-style: none;
     float: left;
     font-size: 11px;
@@ -1542,29 +1197,29 @@
     padding: 0 8px 0 4px;
 }
 
-#content div.box div.traffic div.legend li.visits {
+#content div.panel div.traffic div.legend li.visits {
     border-left: 12px solid #edc240;
 }
 
-#content div.box div.traffic div.legend li.pageviews {
+#content div.panel div.traffic div.legend li.pageviews {
     border-left: 12px solid #afd8f8;
 }
 
-#content div.box div.traffic table {
+#content div.panel div.traffic table {
     width: auto;
 }
 
-#content div.box div.traffic table td {
+#content div.panel div.traffic table td {
     background: transparent;
     border: none;
     padding: 2px 3px 3px;
 }
 
-#content div.box div.traffic table td.legendLabel {
+#content div.panel div.traffic table td.legendLabel {
     padding: 0 3px 2px;
 }
 
-#content div.box #summary {
+#content div.panel #summary {
     margin-right: 200px;
     min-height: 240px;
 }
@@ -1617,11 +1272,8 @@
     text-decoration: none;
 }
 
-#summary-menu-stats a span {
-    background-color: #DEDEDE;
-    color: #888 !important;
-    border-radius: 4px;
-    padding: 2px 4px;
+#summary-menu-stats .badge {
+    padding: 2px 4px !important;
     font-size: 10px;
 }
 
@@ -1633,17 +1285,17 @@
     border-radius: 5px;
 }
 
-#content div.box #summary p {
+#content div.panel #summary p {
     margin-bottom: -5px;
     width: 600px;
     white-space: pre-wrap;
 }
 
-#content div.box #summary p:last-child {
+#content div.panel #summary p:last-child {
     margin-bottom: 9px;
 }
 
-#content div.box #summary p:first-of-type {
+#content div.panel #summary p:first-of-type {
     margin-top: 9px;
 }
 
@@ -1741,7 +1393,7 @@
     color: #FFF;
 }
 
-#login div.title {
+#login div.panel-heading {
     clear: both;
     overflow: hidden;
     position: relative;
@@ -1911,21 +1563,25 @@
 #quick_login .links .logout {
 }
 
-#quick_login div.form div.fields {
+#quick_login div.form div.fields,
+#quick_login div.form div.form-horizontal {
     padding-top: 2px;
     padding-left: 10px;
 }
 
-#quick_login div.form div.fields div.field {
+#quick_login div.form div.fields div.field,
+#quick_login div.form div.form-horizontal div.form-group {
     padding: 5px;
 }
 
-#quick_login div.form div.fields div.field div.label label {
+#quick_login div.form div.fields div.field > label,
+#quick_login div.form div.form-horizontal div.form-group > label {
     color: #fff;
     padding-bottom: 3px;
 }
 
-#quick_login div.form div.fields div.field div.input input {
+#quick_login div.form div.fields div.field div.input input,
+#quick_login div.form div.form-horizontal div.form-group div.input input {
     width: 236px;
     background: #FFF;
     border-top: 1px solid #b3b3b3;
@@ -1938,7 +1594,8 @@
     padding: 5px 7px 4px;
 }
 
-#quick_login div.form div.fields div.buttons {
+#quick_login div.form div.fields div.buttons,
+#quick_login div.form div.form-horizontal div.buttons {
     clear: both;
     overflow: hidden;
     text-align: right;
@@ -1977,7 +1634,7 @@
     background-color: inherit !important;
 }
 
-#register div.title {
+#register div.panel-heading {
     clear: both;
     overflow: hidden;
     position: relative;
@@ -1996,7 +1653,8 @@
     padding: 20px;
 }
 
-#register div.form div.fields div.field div.label {
+#register div.form div.fields div.field > label,
+#register div.form div.form-horizontal div.form-group > label {
     width: 135px;
     float: left;
     text-align: right;
@@ -2004,7 +1662,8 @@
     padding: 5px 0 0 5px;
 }
 
-#register div.form div.fields div.field div.input input {
+#register div.form div.fields div.field div.input input,
+#register div.form div.form-horizontal div.form-group div.input input {
     width: 300px;
     background: #FFF;
     border-top: 1px solid #b3b3b3;
@@ -2017,7 +1676,8 @@
     padding: 7px 7px 6px;
 }
 
-#register div.form div.fields div.buttons {
+#register div.form div.fields div.buttons,
+#register div.form div.form-horizontal div.buttons {
     clear: both;
     overflow: hidden;
     border-top: 1px solid #DDD;
@@ -2186,10 +1846,6 @@
     text-align: right;
 }
 
-.changeset_hash {
-    color: #000000;
-}
-
 #changeset_content {
     border-left: 1px solid #CCC;
     border-right: 1px solid #CCC;
@@ -2340,6 +1996,7 @@
 
 #graph_nodes {
     position: absolute;
+    width: 100px;
 }
 
 #graph_content,
@@ -2375,9 +2032,12 @@
     border-color: #cdcdcd;
 }
 
+#updaterevs-table tr.mergerow,
+#graph_content_pr tr.mergerow,
+#shortlog_data tr.mergerow,
 #graph_content #changesets tr.out-of-range,
 #graph_content #changesets tr.mergerow {
-    opacity: 0.5;
+    opacity: 0.6;
 }
 
 #graph_content #changesets td {
@@ -2592,7 +2252,7 @@
     color: #81ba51;
 }
 .changeset-status-rejected {
-    color: #cc392e;
+    color: #d06060;
 }
 .changeset-status-under_review {
     color: #ffc71e;
@@ -2664,10 +2324,15 @@
 .right .logtags {
     line-height: 2.2em;
 }
-.repotag, .branchtag, .logtags .tagtag, .logtags .booktag {
+.phasetag, .bumpedtag, .divergenttag, .extincttag, .unstabletag, .repotag, .branchtag, .logtags .tagtag, .logtags .booktag {
     margin: 0px 2px;
 }
 
+.phasetag,
+.bumpedtag,
+.divergenttag,
+.extincttag,
+.unstabletag,
 .repotag,
 .branchtag,
 .tagtag,
@@ -2682,6 +2347,11 @@
     line-height: 1.5em;
 }
 
+#graph_content .phasetag,
+#graph_content .bumpedtag,
+#graph_content .divergenttag,
+#graph_content .extincttag,
+#graph_content .unstabletag,
 #graph_content .branchtag,
 #graph_content .tagtag,
 #graph_content .booktag {
@@ -2689,13 +2359,24 @@
     margin-right: 0.5em;
 }
 
+.phasetag,
+.bumpedtag,
+.divergenttag,
+.extincttag,
+.unstabletag,
 .repotag,
 .branchtag,
 .tagtag,
 .booktag {
     float: left;
-}
-
+    display: inline-block;
+}
+
+.right .logtags .phasetag,
+.right .logtags .bumpedtag,
+.right .logtags .divergenttag,
+.right .logtags .extincttag,
+.right .logtags .unstabletag,
 .right .logtags .branchtag,
 .right .logtags .tagtag,
 .right .logtags .booktag,
@@ -2736,6 +2417,20 @@
     color: #62cffc;
 }
 
+.bumpedtag,
+.divergenttag,
+.extincttag,
+.unstabletag {
+    background-color: #f00;
+    border-color: #600;
+    color: #fff;
+}
+
+.phasetag {
+    border-color: #1F14CE;
+    color: #1F14CE;
+}
+
 .logtags .branchtag a:hover,
 .logtags .branchtag a,
 .branchtag a,
@@ -2900,9 +2595,29 @@
 
 }
 .diffblock .diff-actions {
-    padding: 2px 0px 0px 2px;
     float: left;
 }
+.diffblock .diff-actions span.no-file,
+.diffblock .diff-actions span.arrow {
+    opacity: 0.5;
+}
+.diffblock .diff-actions span.arrow {
+    margin: 0 -3px;
+}
+.diffblock .diff-actions a i {
+    margin: 0 2px;
+}
+.diffblock.twoway {
+    overflow: visible;
+}
+.diffblock.twoway .diff-actions {
+    padding-top: 0;
+}
+.diffblock.twoway .diff-actions label input {
+    margin: -5px 5px 0 10px;
+    position: relative;
+    top: 3px;
+}
 .diffblock .diff-menu ul li {
     padding: 0px 0px 0px 0px !important;
 }
@@ -2932,14 +2647,14 @@
     padding-right: .3em;
 }
 
-.box .search {
+.panel .search {
     clear: both;
     overflow: hidden;
     margin: 0;
     padding: 0 20px 10px;
 }
 
-.box .search div.search_path {
+.panel .search div.search_path {
     background: none repeat scroll 0 0 #EEE;
     border: 1px solid #CCC;
     color: blue;
@@ -2947,12 +2662,12 @@
     padding: 10px 0;
 }
 
-.box .search div.search_path div.link {
+.panel .search div.search_path div.link {
     font-weight: 700;
     margin-left: 25px;
 }
 
-.box .search div.search_path div.link a {
+.panel .search div.search_path div.link a {
     color: #577632;
     cursor: pointer;
     text-decoration: none;
@@ -3131,17 +2846,6 @@
     padding-bottom: 5px;
 }
 
-.action_button {
-    border: 0;
-    display: inline;
-}
-
-.action_button:hover {
-    border: 0;
-    text-decoration: underline;
-    cursor: pointer;
-}
-
 #switch_repos {
     position: absolute;
     height: 25px;
@@ -3305,14 +3009,15 @@
     padding: 55px 10px 14px 10px !important;
 }
 
-#content div.box div.title div.search {
+#content div.panel div.panel-heading div.search {
     border-left: 1px solid #576622;
 }
 
-#content div.box div.title div.search div.input input {
+#content div.panel div.panel-heading div.search div.input input {
     border: 1px solid #576622;
 }
 
+.label,
 .btn {
     color: #515151;
     background-color: #DADADA;
@@ -3326,9 +3031,15 @@
     outline: none;
     margin: 0px 3px 3px 0px;
     border-radius: 4px 4px 4px 4px !important;
-    cursor: pointer !important;
     padding: 3px 3px 3px 3px;
     display: inline-block;
+    white-space: nowrap;
+}
+.btn {
+    cursor: pointer !important;
+}
+.label {
+    cursor: default !important;
 }
 
 ul.nav-stacked {
@@ -3367,18 +3078,13 @@
     color: #999;
 }
 
-.btn.btn-danger.disabled {
-    color: #eee;
-    background-color: #c77;
-    border-color: #b66
-}
-
-.btn.btn-small {
-    padding: 2px 6px;
-}
-
-.btn.btn-mini {
-    padding: 0px 4px;
+.label,
+.btn.btn-sm {
+    padding: 3px 8px;
+}
+
+.btn.btn-xs {
+    padding: 1px 5px;
 }
 
 .btn:focus {
@@ -3399,7 +3105,8 @@
     box-shadow: none !important;
 }
 
-.btn.red {
+.label.label-danger,
+.btn.btn-danger {
     color: #fff;
     background-color: #c43c35;
     background-repeat: repeat-x;
@@ -3408,8 +3115,8 @@
     border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
 }
 
-
-.btn.blue {
+.label.label-primary,
+.btn.btn-primary {
     color: #fff;
     background-color: #339bb9;
     background-repeat: repeat-x;
@@ -3418,7 +3125,8 @@
     border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
 }
 
-.btn.green {
+.label.label-success,
+.btn.btn-success {
     color: #fff;
     background-color: #57a957;
     background-repeat: repeat-x;
@@ -3427,7 +3135,8 @@
     border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
 }
 
-.btn.yellow {
+.label.label-warning,
+.btn.btn-warning {
     color: #fff;
     background-color: #faa732;
     background-repeat: repeat-x;
@@ -3440,21 +3149,49 @@
     color: #aaa;
 }
 
-.btn.blue.hidden {
-    display: none;
-}
-
 .btn.active {
     font-weight: bold;
 }
 
+.alert {
+    padding: 15px;
+    margin: 20px 0;
+    border: 1px solid transparent;
+    border-radius: 4px;
+}
+
+.alert-success {
+    color: #3c763d;
+    background-color: #dff0d8;
+    border-color: #d6e9c6;
+}
+
+.alert-info {
+    color: #31708f;
+    background-color: #d9edf7;
+    border-color: #bce8f1;
+}
+
+.alert-warning {
+    color: #8a6d3b;
+    background-color: #fcf8e3;
+    border-color: #faebcc;
+}
+
+.alert-danger {
+    color: #a94442;
+    background-color: #f2dede;
+    border-color: #ebccd1;
+}
+
 ins, div.options a:hover {
     text-decoration: none;
 }
 
 img,
 #header #header-inner #quick li a:hover span.normal,
-#content div.box div.form div.fields div.field div.textarea table td table td a,
+#content div.panel div.form div.fields div.field div.textarea table td table td a,
+#content div.panel div.form div.form-horizontal div.form-group div.textarea table td table td a,
 #clone_url,
 #clone_url_id
 {
@@ -3466,9 +3203,9 @@
 }
 
 #header ul#logged-user,
-#content div.box div.title ul.links,
-#content div.box div.message div.dismiss,
-#content div.box div.traffic div.legend ul {
+#content div.panel div.panel-heading ul.links,
+#content div.panel div.message div.dismiss,
+#content div.panel div.traffic div.legend ul {
     float: right;
     margin: 0;
     padding: 0;
@@ -3476,31 +3213,29 @@
 
 #header #header-inner #home,
 #header #header-inner #logo,
-#content div.box ul.left,
-#content div.box ol.left,
+#content div.panel ul.left,
+#content div.panel ol.left,
 div#commit_history,
 div#legend_data, div#legend_container, div#legend_choices {
     float: left;
 }
 
 #header #header-inner #quick li #quick_login,
-#header #header-inner #quick li:hover ul ul,
-#header #header-inner #quick li:hover ul ul ul,
-#header #header-inner #quick li:hover ul ul ul ul,
 #content #left #menu ul.closed,
 #content #left #menu li ul.collapsed,
 .yui-tt-shadow {
     display: none;
 }
 
-#header #header-inner #quick li:hover #quick_login,
-#header #header-inner #quick li:hover ul,
-#header #header-inner #quick li li:hover ul,
-#header #header-inner #quick li li li:hover ul,
-#header #header-inner #quick li li li li:hover ul,
+.dropdown.open .dropdown-menu,
 #content #left #menu ul.opened,
 #content #left #menu li ul.expanded {
-    display: block;
+    display: block !important;
+}
+
+.caret:after {
+    font-family: 'kallithea';
+    content: ' \23f7';           /* triangle-down */
 }
 
 .repo-switcher .select2-choice {
@@ -3522,11 +3257,6 @@
     display: none !important;
 }
 
-.repo-switcher .select2-chosen:after {
-    font-family: 'kallithea';
-    content: ' \23f7';
-}
-
 .repo-switcher-dropdown.select2-drop.select2-drop-active {
     box-shadow: none;
     color: #fff;
@@ -3542,47 +3272,41 @@
     height: 450px;
 }
 
-#content div.box ol.lower-roman,
-#content div.box ol.upper-roman,
-#content div.box ol.lower-alpha,
-#content div.box ol.upper-alpha,
-#content div.box ol.decimal {
+#content div.panel ol.lower-roman,
+#content div.panel ol.upper-roman,
+#content div.panel ol.lower-alpha,
+#content div.panel ol.upper-alpha,
+#content div.panel ol.decimal {
     margin: 10px 24px 10px 44px;
 }
 
-#content div.box div.form,
-#content div.box div.table,
-#content div.box div.traffic {
+#content div.panel div.form,
+#content div.panel div.table,
+#content div.panel div.traffic {
     position: relative;
     clear: both;
     margin: 0;
     padding: 0 20px 10px;
 }
 
-#content div.box div.form div.fields,
+#content div.panel div.form div.fields,
+#content div.panel div.form div.form-horizontal,
 #login div.form-horizontal,
 #login div.form-horizontal div.form-group,
 #register div.form,
-#register div.form div.fields {
+#register div.form div.fields,
+#register div.form div.form-horizontal {
     clear: both;
     overflow: hidden;
     margin: 0;
     padding: 0;
 }
 
-#content div.box div.form div.fields div.field div.label span,
-#login div.form div.form-horizontal div.form-group div.label span,
-#register div.form div.fields div.field div.label span {
-    height: 1%;
-    display: block;
-    color: #363636;
-    margin: 0;
-    padding: 2px 0 0;
-}
-
-#content div.box div.form div.fields div.field div.input input.error,
+#content div.panel div.form div.fields div.field div.input input.error,
+#content div.panel div.form div.form-horizontal div.form-group div.input input.error,
 #login div.form div.form-horizontal div.form-group div.input input.error,
-#register div.form div.fields div.field div.input input.error {
+#register div.form div.fields div.field div.input input.error,
+#register div.form div.form-horizontal div.form-group div.input input.error {
     background: #FBE3E4;
     border-top: 1px solid #e1b2b3;
     border-left: 1px solid #e1b2b3;
@@ -3590,9 +3314,11 @@
     border-bottom: 1px solid #FBC2C4;
 }
 
-#content div.box div.form div.fields div.field div.input input.success,
+#content div.panel div.form div.fields div.field div.input input.success,
+#content div.panel div.form div.form-horizontal div.form-group div.input input.success,
 #login div.form div.form-horizontal div.form-group div.input input.success,
-#register div.form div.fields div.field div.input input.success {
+#register div.form div.fields div.field div.input input.success,
+#register div.form div.form-horizontal div.form-group div.input input.success {
     background: #E6EFC2;
     border-top: 1px solid #cebb98;
     border-left: 1px solid #cebb98;
@@ -3600,59 +3326,60 @@
     border-bottom: 1px solid #c6d880;
 }
 
-#content div.box-left div.form div.fields div.field div.textarea,
-#content div.box-right div.form div.fields div.field div.textarea,
-#content div.box div.form div.fields div.field div.select select,
-#content div.box table th.selected input,
-#content div.box table td.selected input {
+#content div.panel div.form div.fields div.field div.select select,
+#content div.panel div.form div.form-horizontal div.form-group div.select select,
+#content div.panel table th.selected input,
+#content div.panel table td.selected input {
     margin: 0;
 }
 
-#content div.box-left div.form div.fields div.field div.select,
-#content div.box-left div.form div.fields div.field div.checkboxes,
-#content div.box-left div.form div.fields div.field div.radios,
-#content div.box-right div.form div.fields div.field div.select,
-#content div.box-right div.form div.fields div.field div.checkboxes,
-#content div.box-right div.form div.fields div.field div.radios {
-    margin: 0 0 0 0px !important;
-    padding: 0;
-}
-
-#content div.box div.form div.fields div.field div.select,
-#content div.box div.form div.fields div.field div.checkboxes,
-#content div.box div.form div.fields div.field div.radios {
+#content div.panel div.form div.fields div.field div.select,
+#content div.panel div.form div.form-horizontal div.form-group div.select,
+#content div.panel div.form div.fields div.field div.checkboxes,
+#content div.panel div.form div.form-horizontal div.form-group div.checkboxes,
+#content div.panel div.form div.fields div.field div.radios,
+#content div.panel div.form div.form-horizontal div.form-group div.radios {
     margin: 0 0 0 200px;
     padding: 0;
 }
 
-#content div.box div.form div.fields div.field div.select a:hover,
-#content div.box div.form div.fields div.field div.select a.ui-selectmenu:hover,
-#content div.box div.action a:hover {
+#content div.panel div.form div.fields div.field div.select a:hover,
+#content div.panel div.form div.form-horizontal div.form-group div.select a:hover,
+#content div.panel div.form div.fields div.field div.select a.ui-selectmenu:hover,
+#content div.panel div.form div.form-horizontal div.form-group div.select a.ui-selectmenu:hover,
+#content div.panel div.action a:hover {
     color: #000;
     text-decoration: none;
 }
 
-#content div.box div.form div.fields div.field div.select a.ui-selectmenu-focus,
-#content div.box div.action a.ui-selectmenu-focus {
+#content div.panel div.form div.fields div.field div.select a.ui-selectmenu-focus,
+#content div.panel div.form div.form-horizontal div.form-group div.select a.ui-selectmenu-focus,
+#content div.panel div.action a.ui-selectmenu-focus {
     border: 1px solid #666;
 }
 
-#content div.box div.form div.fields div.field div.checkboxes div.checkbox,
-#content div.box div.form div.fields div.field div.radios div.radio {
+#content div.panel div.form div.fields div.field div.checkboxes div.checkbox,
+#content div.panel div.form div.form-horizontal div.form-group div.checkboxes div.checkbox,
+#content div.panel div.form div.fields div.field div.radios div.radio,
+#content div.panel div.form div.form-horizontal div.form-group div.radios div.radio {
     clear: both;
     overflow: hidden;
     margin: 0;
     padding: 8px 0 2px;
 }
 
-#content div.box div.form div.fields div.field div.checkboxes div.checkbox input,
-#content div.box div.form div.fields div.field div.radios div.radio input {
+#content div.panel div.form div.fields div.field div.checkboxes div.checkbox input,
+#content div.panel div.form div.form-horizontal div.form-group div.checkboxes div.checkbox input,
+#content div.panel div.form div.fields div.field div.radios div.radio input,
+#content div.panel div.form div.form-horizontal div.form-group div.radios div.radio input {
     float: left;
     margin: 0;
 }
 
-#content div.box div.form div.fields div.field div.checkboxes div.checkbox label,
-#content div.box div.form div.fields div.field div.radios div.radio label {
+#content div.panel div.form div.fields div.field div.checkboxes div.checkbox label,
+#content div.panel div.form div.form-horizontal div.form-group div.checkboxes div.checkbox label,
+#content div.panel div.form div.fields div.field div.radios div.radio label,
+#content div.panel div.form div.form-horizontal div.form-group div.radios div.radio label {
     height: 1%;
     display: block;
     float: left;
@@ -3660,76 +3387,47 @@
 }
 
 div.form div.fields div.field div.button input,
-#content div.box div.form div.fields div.buttons input
+div.form div.form-horizontal div.form-group div.button input,
+#content div.panel div.form div.fields div.buttons input
+#content div.panel div.form div.form-horizontal div.buttons input
 div.form div.fields div.buttons input,
-#content div.box div.action div.button input {
+div.form div.form-horizontal div.buttons input,
+#content div.panel div.action div.button input {
     font-size: 11px;
     font-weight: 700;
     margin: 0;
 }
 
 div.form div.fields div.field div.highlight,
-#content div.box div.form div.fields div.buttons div.highlight {
+div.form div.form-horizontal div.form-group div.highlight,
+#content div.panel div.form div.fields div.buttons div.highlight,
+#content div.panel div.form div.form-horizontal div.buttons div.highlight {
     display: inline;
 }
 
-#content div.box div.form div.fields div.buttons,
-div.form div.fields div.buttons {
+#content div.panel div.form div.fields div.buttons,
+#content div.panel div.form div.form-horizontal div.buttons,
+div.form div.fields div.buttons,
+div.form div.form-horizontal div.buttons {
     margin: 10px 0 0 200px;
     padding: 0;
 }
 
-#content div.box-left div.form div.fields div.buttons,
-#content div.box-right div.form div.fields div.buttons,
-div.box-left div.form div.fields div.buttons,
-div.box-right div.form div.fields div.buttons {
-    margin: 10px 0 0;
-}
-
-#content div.box table td.user,
-#content div.box table td.address {
+#content div.panel table td.user,
+#content div.panel table td.address {
     width: 10%;
     text-align: center;
 }
 
-#content div.box div.action div.button,
+#content div.panel div.action div.button,
 #login div.form div.form-horizontal div.form-group div.input div.link,
-#register div.form div.fields div.field div.input div.link {
+#register div.form div.fields div.field div.input div.link,
+#register div.form div.form-horizontal div.form-group div.input div.link {
     text-align: right;
     margin: 6px 0 0;
     padding: 0;
 }
 
-#content div.box div.pagination div.results,
-#content div.box div.pagination-wh div.results {
-    text-align: left;
-    float: left;
-    margin: 0;
-    padding: 0;
-}
-
-#content div.box div.pagination div.results span,
-#content div.box div.pagination-wh div.results span {
-    height: 1%;
-    display: block;
-    float: left;
-    background: #ebebeb url("../images/pager.png") repeat-x;
-    border-top: 1px solid #dedede;
-    border-left: 1px solid #cfcfcf;
-    border-right: 1px solid #c4c4c4;
-    border-bottom: 1px solid #c4c4c4;
-    color: #4A4A4A;
-    font-weight: 700;
-    margin: 0;
-    padding: 6px 8px;
-}
-
-#content div.box div.pagination ul.pager li.disabled,
-#content div.box div.pagination-wh a.disabled {
-    color: #B4B4B4;
-    padding: 6px;
-}
-
 #login, #register {
     width: 520px;
     margin: 10% auto 0;
@@ -3755,15 +3453,16 @@
     padding: 0;
 }
 
-#login div.title h5,
-#register div.title h5 {
+#login div.panel-heading h5,
+#register div.panel-heading h5 {
     color: #fff;
     margin: 10px;
     padding: 0;
 }
 
 #login div.form div.form-horizontal div.form-group,
-#register div.form div.fields div.field {
+#register div.form div.fields div.field,
+#register div.form div.form-horizontal div.form-group {
     clear: both;
     overflow: hidden;
     margin: 0;
@@ -3771,7 +3470,8 @@
 }
 
 #login div.form div.form-horizontal div.form-group span.error-message,
-#register div.form div.fields div.field span.error-message {
+#register div.form div.fields div.field span.error-message,
+#register div.form div.form-horizontal div.form-group span.error-message {
     height: 1%;
     display: block;
     color: red;
@@ -3781,13 +3481,15 @@
 }
 
 #login div.form div.form-horizontal div.form-group label,
-#register div.form div.fields div.field div.label label {
+#register div.form div.fields div.field > label,
+#register div.form div.form-horizontal div.form-group > label {
     color: #000;
     font-weight: 700;
 }
 
 #login div.form div.form-horizontal div.form-group div,
-#register div.form div.fields div.field div.input {
+#register div.form div.fields div.field div.input,
+#register div.form div.form-horizontal div.form-group div.input {
     float: left;
     margin: 0;
     padding: 0;
@@ -3798,19 +3500,22 @@
 }
 
 #login div.form div.form-horizontal div.form-group div.checkbox,
-#register div.form div.fields div.field div.checkbox {
+#register div.form div.fields div.field div.checkbox,
+#register div.form div.form-horizontal div.form-group div.checkbox {
     margin: 0 0 0 184px;
     padding: 0;
 }
 
 #login div.form div.form-horizontal div.form-group div.checkbox label,
-#register div.form div.fields div.field div.checkbox label {
+#register div.form div.fields div.field div.checkbox label,
+#register div.form div.form-horizontal div.form-group div.checkbox label {
     color: #565656;
     font-weight: 700;
 }
 
 #login div.form div.buttons input,
-#register div.form div.fields div.buttons input {
+#register div.form div.fields div.buttons input,
+#register div.form div.form-horizontal div.buttons input {
     color: #000;
     font-size: 1em;
     font-weight: 700;
@@ -3850,17 +3555,6 @@
     padding-left: 3px;
 }
 
-
-.group_members_wrap {
-    min-height: 85px;
-    padding-left: 20px;
-}
-
-.group_members .group_member {
-    height: 30px;
-    padding: 0px 0px 0px 0px;
-}
-
 .reviewer_status {
     float: left;
 }
@@ -4131,14 +3825,11 @@
 
 .comments .comment .text {
     background-color: #FAFAFA;
-}
-.comment .text div.rst-block p {
-    margin: 0.5em 0px !important;
+    margin: 6px;
 }
 
 .comments-number {
-    margin: 5px;
-    padding: 0px 0px 10px 0px;
+    padding: 0px 20px 10px;
     font-weight: bold;
     color: #666;
     font-size: 16px;
@@ -4190,19 +3881,6 @@
     padding: 5px 5px 5px 5px;
     color: #666;
 }
-.comment-form .comment-help .preview-btn,
-.comment-form .comment-help .edit-btn {
-    float: right;
-    margin: -6px 0px 0px 0px;
-}
-
-.comment-form .preview-box.unloaded,
-.comment-inline-form .preview-box.unloaded {
-    height: 50px;
-    text-align: center;
-    padding: 20px;
-    background-color: #fafafa;
-}
 
 .comment-form .comment-button {
     padding-top: 5px;
@@ -4219,7 +3897,6 @@
     margin: -1px 0px 0px 0px;
 }
 
-
 .show-inline-comments {
     position: relative;
     top: 1px
@@ -4279,12 +3956,6 @@
     color: #666;
 }
 
-.comment-inline-form .comment-help .preview-btn,
-.comment-inline-form .comment-help .edit-btn {
-    float: right;
-    margin: -6px 0px 0px 0px;
-}
-
 .comment-inline-form .comment-button {
     padding-top: 5px;
 }
@@ -4294,13 +3965,6 @@
     padding: 0 20px;
 }
 
-.inline-comments div.rst-block {
-    clear: both;
-    overflow: hidden;
-    margin: 0;
-    padding: 0 20px 0px;
-}
-
 .inline-comments .comment .comment-wrapp {
     max-width: 978px;
     border: 1px solid #ddd;
@@ -4338,6 +4002,7 @@
 
 .inline-comments .comment .text {
     background-color: #FAFAFA;
+    margin: 6px;
 }
 
 .inline-comments .comments-number {
@@ -4346,21 +4011,13 @@
     color: #666;
     font-size: 16px;
 }
-.inline-comments-button .add-comment {
-    margin: 2px 0px 8px 5px !important
-}
 
 input.status_change_radio {
     margin: 2px 0 5px 15px;
     vertical-align: middle;
 }
 
-.notification-paginator {
-    padding: 0px 0px 4px 16px;
-}
-
-#context-pages .pull-request span,
-.menu_link_notifications {
+.badge {
     padding: 4px 4px !important;
     text-align: center;
     color: #888 !important;
@@ -4368,16 +4025,6 @@
     border-radius: 4px !important;
 }
 
-#context-pages .forks span,
-.menu_link_notifications {
-    padding: 4px 4px !important;
-    text-align: center;
-    color: #888 !important;
-    background-color: #DEDEDE !important;
-    border-radius: 4px !important;
-}
-
-
 .notification-header {
     padding-top: 6px;
 }
@@ -4497,7 +4144,7 @@
 }
 
 #perms .perm_tag {
-    padding: 1px 3px 1px 3px;
+    padding: 3px 3px 1px 3px;
     font-size: 10px;
     font-weight: bold;
     text-transform: uppercase;
@@ -4552,9 +4199,17 @@
 
 }
 
-.diff-container.hidden {
-    display: none;
-    overflow: hidden;
+.compare-revision-selector {
+    font-weight: bold;
+    font-size: 14px;
+}
+.compare-revision-selector > div {
+    display: inline-block;
+    margin-left: 8px;
+    vertical-align: middle;
+}
+.compare-revision-selector .btn {
+    margin-bottom: 0;
 }
 
 
@@ -4572,6 +4227,7 @@
 div.diffblock.margined {
     margin: 0px 20px 0px 20px;
 }
+.compare-revision-selector,
 div.diffblock .code-header {
     border-bottom: 1px solid #CCCCCC;
     background: #EEEEEE;
@@ -4722,6 +4378,10 @@
     width: 100%;
 }
 
+table.code-difftable .line:hover .lineno a {
+    color: #333 !important;
+}
+
 table.code-difftable .lineno-inline {
     background: none repeat scroll 0 0 #FFF !important;
     padding-left: 2px;
@@ -4873,3 +4533,59 @@
 .icon-only-links i {
     color: white;
 }
+
+
+body table.dataTable thead .sorting {
+  background-image: none;
+}
+body table.dataTable thead .sorting_asc {
+  background-image: none;
+}
+body table.dataTable thead .sorting_desc {
+  background-image: none;
+}
+body table.dataTable thead .sorting_asc_disabled {
+  background-image: none;
+}
+body table.dataTable thead .sorting_desc_disabled {
+  background-image: none;
+}
+
+body table.dataTable thead .sorting_asc::after {
+  font-family: "kallithea";
+  content: "\23f6";
+}
+body table.dataTable thead .sorting_desc::after {
+  font-family: "kallithea";
+  content: "\23f7";
+}
+
+.dataTables_wrapper .dataTables_left {
+  float: left !important;
+}
+
+.dataTables_wrapper .dataTables_right {
+  float: right;
+}
+
+.dataTables_wrapper .dataTables_right > div {
+  padding-left: 30px;
+}
+
+.dataTables_wrapper .dataTables_info {
+  clear: none;
+  padding-top: 1em;
+}
+
+.dataTables_wrapper .dataTables_paginate {
+  padding-top: 0;
+}
+
+.dataTables_wrapper .dataTables_paginate > a.paginate_button {
+  padding-top: 1em;
+  border: 0 !important;
+}
+
+.text-muted {
+    color: #777777;
+}
--- a/kallithea/public/js/base.js	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/public/js/base.js	Fri Nov 18 01:11:13 2016 +0100
@@ -311,12 +311,6 @@
 })();
 
 
-/**
- * GLOBAL YUI Shortcuts
- */
-var YUD = YAHOO.util.Dom;
-var YUE = YAHOO.util.Event;
-
 /* Invoke all functions in callbacks */
 var _run_callbacks = function(callbacks){
     if (callbacks !== undefined){
@@ -377,15 +371,16 @@
         ;
 };
 
-var ajaxGET = function(url,success) {
+var ajaxGET = function(url, success, failure) {
+    if(failure === undefined) {
+        failure = function(jqXHR, textStatus, errorThrown) {
+                if (textStatus != "abort")
+                    alert("Ajax GET error: " + textStatus);
+            };
+    }
     return $.ajax({url: url, headers: {'X-PARTIAL-XHR': '1'}, cache: false})
         .done(success)
-        .fail(function(jqXHR, textStatus, errorThrown) {
-                if (textStatus == "abort")
-                    return;
-                alert("Ajax GET error: " + textStatus);
-        })
-        ;
+        .fail(failure);
 };
 
 var ajaxPOST = function(url, postData, success, failure) {
@@ -456,8 +451,8 @@
     }
 }
 
-var toggleFollowingRepo = function(target, follows_repo_id){
-    var args = 'follows_repo_id=' + follows_repo_id;
+var toggleFollowingRepo = function(target, follows_repository_id){
+    var args = 'follows_repository_id=' + follows_repository_id;
     args += '&amp;_authentication_token=' + _authentication_token;
     $.post(TOGGLE_FOLLOW_URL, args, function(data){
             _onSuccessFollow(target);
@@ -504,7 +499,7 @@
     $tipBox.css('position', 'absolute');
     $tipBox.css('max-width', '600px');
 
-    _activate_tooltip($('.tooltip'));
+    _activate_tooltip($('[data-toggle="tooltip"]'));
 };
 
 var _show_tooltip = function(e, tipText, safe){
@@ -621,9 +616,13 @@
         var line_no = $anchorcomment.data('line_no');
         if ($comment_div[0]) {
             $comment_div.append($anchorcomment.children());
-            _comment_div_append_add($comment_div, f_path, line_no);
+            if (f_path && line_no) {
+                _comment_div_append_add($comment_div, f_path, line_no);
+            } else {
+                _comment_div_append_form($comment_div, f_path, line_no);
+            }
         } else {
-           $anchorcomment.before("Comment to {0} line {1} which is outside the diff context:".format(f_path || '?', line_no || '?'));
+            $anchorcomment.before("Comment to {0} line {1} which is outside the diff context:".format(f_path || '?', line_no || '?'));
         }
     });
     linkInlineComments($('.firstlink'), $('.comment:first-child'));
@@ -652,20 +651,19 @@
     return $comments_box;
 }
 
-// set $comment_div state - showing or not showing form and Add button
-function comment_div_state($comment_div, f_path, line_no, show_form) {
+// Set $comment_div state - showing or not showing form and Add button.
+// An Add button is shown on non-empty forms when no form is shown.
+// The form is controlled by show_form - if undefined, form is only shown for general comments.
+function comment_div_state($comment_div, f_path, line_no, show_form_opt) {
+    var show_form = show_form_opt !== undefined ? show_form_opt : !f_path && !line_no;
     var $forms = $comment_div.children('.comment-inline-form');
     var $buttonrow = $comment_div.children('.add-button-row');
     var $comments = $comment_div.children('.comment');
+    $forms.remove();
+    $buttonrow.remove();
     if (show_form) {
-        if (!$forms.length) {
-            _comment_div_append_form($comment_div, f_path, line_no);
-        }
-    } else {
-        $forms.remove();
-    }
-    $buttonrow.remove();
-    if ($comments.length && !show_form) {
+        _comment_div_append_form($comment_div, f_path, line_no);
+    } else if ($comments.length) {
         _comment_div_append_add($comment_div, f_path, line_no);
     }
 }
@@ -673,7 +671,7 @@
 // append an Add button to $comment_div and hook it up to show form
 function _comment_div_append_add($comment_div, f_path, line_no) {
     var addlabel = TRANSLATION_MAP['Add Another Comment'];
-    var $add = $('<div class="add-button-row"><span class="btn btn-mini add-button">{0}</span></div>'.format(addlabel));
+    var $add = $('<div class="add-button-row"><span class="btn btn-default btn-xs add-button">{0}</span></div>'.format(addlabel));
     $comment_div.append($add);
     $add.children('.add-button').click(function(e) {
         comment_div_state($comment_div, f_path, line_no, true);
@@ -682,78 +680,87 @@
 
 // append a comment form to $comment_div
 function _comment_div_append_form($comment_div, f_path, line_no) {
-    var $form_div = $($('#comment-inline-form-template').html().format(f_path, line_no))
+    var $form_div = $('#comment-inline-form-template').children()
+        .clone()
         .addClass('comment-inline-form');
     $comment_div.append($form_div);
     var $form = $comment_div.find("form");
+    var $textarea = $form.find('textarea');
+    var $mentions_container = $form.find('div.mentions-container');
 
     $form.submit(function(e) {
         e.preventDefault();
 
-        var text = $('#text_'+line_no).val();
-        if (!text){
-            return;
+        var text = $textarea.val();
+        var review_status = $form.find('input:radio[name=changeset_status]:checked').val();
+        var pr_close = $form.find('input:checkbox[name=save_close]:checked').length ? 'on' : '';
+        var pr_delete = $form.find('input:checkbox[name=save_delete]:checked').length ? 'delete' : '';
+
+        if (!text && !review_status && !pr_close && !pr_delete) {
+            alert("Please provide a comment");
+            return false;
+        }
+
+        if (pr_delete) {
+            if (text || review_status || pr_close) {
+                alert('Cannot delete pull request while making other changes');
+                return false;
+            }
+            if (!confirm('Confirm to delete this pull request')) {
+                return false;
+            }
+            var comments = $('.comment').size();
+            if (comments > 0 &&
+                !confirm('Confirm again to delete this pull request with {0} comments'.format(comments))) {
+                return false;
+            }
         }
 
         $form.find('.submitting-overlay').show();
 
-        var success = function(json_data) {
-            $comment_div.append(json_data['rendered_text']);
-            comment_div_state($comment_div, f_path, line_no, false);
-            linkInlineComments($('.firstlink'), $('.comment:first-child'));
-        };
         var postData = {
             'text': text,
             'f_path': f_path,
-            'line': line_no
+            'line': line_no,
+            'changeset_status': review_status,
+            'save_close': pr_close,
+            'save_delete': pr_delete
+        };
+        var success = function(json_data) {
+            if (pr_delete) {
+                location = json_data['location'];
+            } else {
+                $comment_div.append(json_data['rendered_text']);
+                comment_div_state($comment_div, f_path, line_no);
+                linkInlineComments($('.firstlink'), $('.comment:first-child'));
+                if ((review_status || pr_close) && !f_path && !line_no) {
+                    // Page changed a lot - reload it after closing the submitted form
+                    comment_div_state($comment_div, f_path, line_no, false);
+                    location.reload(true);
+                }
+            }
         };
         ajaxPOST(AJAX_COMMENT_URL, postData, success);
     });
 
-    $('#preview-btn_'+line_no).click(function(e){
-        var text = $('#text_'+line_no).val();
-        if(!text){
-            return
-        }
-        $('#preview-box_'+line_no).addClass('unloaded');
-        $('#preview-box_'+line_no).html(_TM['Loading ...']);
-        $('#edit-container_'+line_no).hide();
-        $('#edit-btn_'+line_no).show();
-        $('#preview-container_'+line_no).show();
-        $('#preview-btn_'+line_no).hide();
-
-        var url = pyroutes.url('changeset_comment_preview', {'repo_name': REPO_NAME});
-        var post_data = {'text': text};
-        ajaxPOST(url, post_data, function(html) {
-            $('#preview-box_'+line_no).html(html);
-            $('#preview-box_'+line_no).removeClass('unloaded');
-        })
-    })
-    $('#edit-btn_'+line_no).click(function(e) {
-        $('#edit-container_'+line_no).show();
-        $('#edit-btn_'+line_no).hide();
-        $('#preview-container_'+line_no).hide();
-        $('#preview-btn_'+line_no).show();
-    })
-
     // create event for hide button
     $form.find('.hide-inline-form').click(function(e) {
-        comment_div_state($comment_div, f_path, line_no, false);
+        comment_div_state($comment_div, f_path, line_no);
     });
 
-    setTimeout(function() {
-        // callbacks
-        tooltip_activate();
-        MentionsAutoComplete($('#text_'+line_no), $('#mentions_container_'+line_no),
-                             _USERS_AC_DATA);
-        $('#text_'+line_no).focus();
-    }, 10);
+    tooltip_activate();
+    if ($textarea.length > 0) {
+        MentionsAutoComplete($textarea, $mentions_container, _USERS_AC_DATA);
+    }
+    if (f_path) {
+        $textarea.focus();
+    }
 }
 
 
 function deleteComment(comment_id) {
     var url = AJAX_COMMENT_DELETE_URL.replace('__COMMENT_ID__', comment_id);
-    var postData = {'_method': 'delete'};
+    var postData = {};
     var success = function(o) {
         $('#comment-'+comment_id).remove();
         // Ignore that this might leave a stray Add button (or have a pending form with another comment) ...
@@ -913,14 +920,14 @@
             $('#editor_container').show();
             $('#upload_file_container').hide();
             $('#filename_container').show();
-            $('#set_mode_header').show();
+            $('#mimetype_header').show();
         });
 
     $('#upload_file_enable').click(function(){
             $('#editor_container').hide();
             $('#upload_file_container').show();
             $('#filename_container').hide();
-            $('#set_mode_header').hide();
+            $('#mimetype_header').hide();
         });
 
     return myCodeMirror
@@ -995,7 +1002,7 @@
     var failure = function(o){
             alert("deleteNotification failure");
         };
-    var postData = {'_method': 'delete'};
+    var postData = {};
     var sUrl = url.replace('__NOTIFICATION_ID__',notification_id);
     ajaxPOST(sUrl, postData, success, failure);
 };
@@ -1010,7 +1017,7 @@
     var failure = function(o){
             alert("readNotification failure");
         };
-    var postData = {'_method': 'put'};
+    var postData = {};
     var sUrl = url.replace('__NOTIFICATION_ID__',notification_id);
     ajaxPOST(sUrl, postData, success, failure);
 };
@@ -1065,18 +1072,23 @@
         + "</span>" + full.substring(matchindex + snippet.length);
 };
 
-var gravatar = function(link, size, cssclass) {
-    var elem = '<img alt="" class="{2}" style="width: {0}px; height: {0}px" src="{1}"/>'.format(size, link, cssclass);
-    if (!link) {
-        elem = '<i class="icon-user {1}" style="font-size: {0}px;"></i>'.format(size, cssclass);
+// Return html snippet for showing the provided gravatar url
+var gravatar = function(gravatar_lnk, size, cssclass) {
+    if (!gravatar_lnk) {
+        return '';
     }
-    return elem;
+    if (gravatar_lnk == 'default') {
+        return '<i class="icon-user {1}" style="font-size: {0}px;"></i>'.format(size, cssclass);
+    }
+    return '<img alt="" class="{2}" style="width: {0}px; height: {0}px" src="{1}"/>'.format(size, gravatar_lnk, cssclass);
 }
 
-var autocompleteGravatar = function(res, link, size, group) {
-    var elem = gravatar(link, size, "perm-gravatar-ac");
+var autocompleteGravatar = function(res, gravatar_lnk, size, group) {
+    var elem;
     if (group !== undefined) {
         elem = '<i class="perm-gravatar-ac icon-users"></i>';
+    } else {
+        elem = gravatar(gravatar_lnk, size, "perm-gravatar-ac");
     }
     return '<div class="ac-container-wrap">{0}{1}</div>'.format(elem, res);
 }
@@ -1300,17 +1312,19 @@
     // If you change something here it should be reflected in the template too.
     var element = (
         '     <li id="reviewer_{2}">\n'+
-        '       <div class="reviewers_member">\n'+
-        '           <div class="reviewer_status tooltip" title="not_reviewed">\n'+
+        '       <span class="reviewers_member">\n'+
+        '         <span class="reviewer_status" data-toggle="tooltip" title="not_reviewed">\n'+
         '             <i class="icon-circle changeset-status-not_reviewed"></i>\n'+
-        '           </div>\n'+
-        '         <div class="reviewer_gravatar gravatar">{0}</div>\n'+
-        '         <div style="float:left;">{1}</div>\n'+
+        '         </span>\n'+
+        (gravatarelm ?
+        '         {0}\n' :
+        '')+
+        '         <span>{1}</span>\n'+
         '         <input type="hidden" value="{2}" name="review_members" />\n'+
-        '         <div class="reviewer_member_remove action_button" onclick="removeReviewMember({2})">\n'+
+        '         <a href="#" class="reviewer_member_remove" onclick="removeReviewMember({2})">\n'+
         '             <i class="icon-minus-circled"></i>\n'+
-        '         </div> (add not saved)\n'+
-        '       </div>\n'+
+        '         </a> (add not saved)\n'+
+        '       </span>\n'+
         '     </li>\n'
         ).format(gravatarelm, displayname, id);
     // check if we don't have this ID already in
@@ -1355,66 +1369,6 @@
     }
 }
 
-/**
- * Activate .quick_repo_menu
- */
-var quick_repo_menu = function(){
-    $(".quick_repo_menu").mouseenter(function(e) {
-            var $menu = $(e.currentTarget).children().first().children().first();
-            if($menu.hasClass('hidden')){
-                $menu.removeClass('hidden').addClass('active');
-                $(e.currentTarget).removeClass('hidden').addClass('active');
-            }
-        });
-    $(".quick_repo_menu").mouseleave(function(e) {
-            var $menu = $(e.currentTarget).children().first().children().first();
-            if($menu.hasClass('active')){
-                $menu.removeClass('active').addClass('hidden');
-                $(e.currentTarget).removeClass('active').addClass('hidden');
-            }
-        });
-};
-
-
-/**
- * TABLE SORTING
- */
-
-var revisionSort = function(a, b, desc, field) {
-    var a_ = parseInt(a.getData('last_rev_raw') || 0);
-    var b_ = parseInt(b.getData('last_rev_raw') || 0);
-
-    return YAHOO.util.Sort.compare(a_, b_, desc);
-};
-
-var ageSort = function(a, b, desc, field) {
-    // data is like: <span class="tooltip" date="2014-06-04 18:18:55.325474" title="Wed, 04 Jun 2014 18:18:55">1 day and 23 hours ago</span>
-    var a_ = $(a.getData(field)).attr('date');
-    var b_ = $(b.getData(field)).attr('date');
-
-    return YAHOO.util.Sort.compare(a_, b_, desc);
-};
-
-var lastLoginSort = function(a, b, desc, field) {
-    var a_ = parseFloat(a.getData('last_login_raw') || 0);
-    var b_ = parseFloat(b.getData('last_login_raw') || 0);
-
-    return YAHOO.util.Sort.compare(a_, b_, desc);
-};
-
-var nameSort = function(a, b, desc, field) {
-    var a_ = a.getData('raw_name') || 0;
-    var b_ = b.getData('raw_name') || 0;
-
-    return YAHOO.util.Sort.compare(a_, b_, desc);
-};
-
-var dateSort = function(a, b, desc, field) {
-    var a_ = parseFloat(a.getData('raw_date') || 0);
-    var b_ = parseFloat(b.getData('raw_date') || 0);
-
-    return YAHOO.util.Sort.compare(a_, b_, desc);
-};
 
 var addPermAction = function(_html, users_list, groups_list){
     var $last_node = $('.last_new_member').last(); // empty tr between last and add
@@ -1431,9 +1385,7 @@
     var failure = function (o) {
             alert(_TM['Failed to revoke permission'] + ": " + o.status);
         };
-    var query_params = {
-        '_method': 'delete'
-    }
+    var query_params = {};
     // put extra data into POST
     if (extra_data !== undefined && (typeof extra_data === 'object')){
         for(var k in extra_data){
@@ -1484,362 +1436,6 @@
         });
 }
 
-// custom paginator
-var YUI_paginator = function(links_per_page, containers){
-
-    (function () {
-
-        var Paginator = YAHOO.widget.Paginator,
-            l         = YAHOO.lang,
-            setId     = YAHOO.util.Dom.generateId;
-
-        Paginator.ui.MyFirstPageLink = function (p) {
-            this.paginator = p;
-
-            p.subscribe('recordOffsetChange',this.update,this,true);
-            p.subscribe('rowsPerPageChange',this.update,this,true);
-            p.subscribe('totalRecordsChange',this.update,this,true);
-            p.subscribe('destroy',this.destroy,this,true);
-
-            // TODO: make this work
-            p.subscribe('firstPageLinkLabelChange',this.update,this,true);
-            p.subscribe('firstPageLinkClassChange',this.update,this,true);
-        };
-
-        Paginator.ui.MyFirstPageLink.init = function (p) {
-            p.setAttributeConfig('firstPageLinkLabel', {
-                value : 1,
-                validator : l.isString
-            });
-            p.setAttributeConfig('firstPageLinkClass', {
-                value : 'yui-pg-first',
-                validator : l.isString
-            });
-            p.setAttributeConfig('firstPageLinkTitle', {
-                value : 'First Page',
-                validator : l.isString
-            });
-        };
-
-        // Instance members and methods
-        Paginator.ui.MyFirstPageLink.prototype = {
-            current   : null,
-            leftmost_page: null,
-            rightmost_page: null,
-            link      : null,
-            span      : null,
-            dotdot    : null,
-            getPos    : function(cur_page, max_page, items){
-                var edge = parseInt(items / 2) + 1;
-                if (cur_page <= edge){
-                    var radius = Math.max(parseInt(items / 2), items - cur_page);
-                }
-                else if ((max_page - cur_page) < edge) {
-                    var radius = (items - 1) - (max_page - cur_page);
-                }
-                else{
-                    var radius = parseInt(items / 2);
-                }
-
-                var left = Math.max(1, (cur_page - (radius)));
-                var right = Math.min(max_page, cur_page + (radius));
-                return [left, cur_page, right]
-            },
-            render : function (id_base) {
-                var p      = this.paginator,
-                    c      = p.get('firstPageLinkClass'),
-                    label  = p.get('firstPageLinkLabel'),
-                    title  = p.get('firstPageLinkTitle');
-
-                this.link     = document.createElement('a');
-                this.span     = document.createElement('span');
-                $(this.span).hide();
-
-                var _pos = this.getPos(p.getCurrentPage(), p.getTotalPages(), 5);
-                this.leftmost_page = _pos[0];
-                this.rightmost_page = _pos[2];
-
-                setId(this.link, id_base + '-first-link');
-                this.link.href      = '#';
-                this.link.className = c;
-                this.link.innerHTML = label;
-                this.link.title     = title;
-                YUE.on(this.link,'click',this.onClick,this,true);
-
-                setId(this.span, id_base + '-first-span');
-                this.span.className = c;
-                this.span.innerHTML = label;
-
-                this.current = p.getCurrentPage() > 1 ? this.link : this.span;
-                return this.current;
-            },
-            update : function (e) {
-                var p      = this.paginator;
-                var _pos   = this.getPos(p.getCurrentPage(), p.getTotalPages(), 5);
-                this.leftmost_page = _pos[0];
-                this.rightmost_page = _pos[2];
-
-                if (e && e.prevValue === e.newValue) {
-                    return;
-                }
-
-                var par = this.current ? this.current.parentNode : null;
-                if (this.leftmost_page > 1) {
-                    if (par && this.current === this.span) {
-                        par.replaceChild(this.link,this.current);
-                        this.current = this.link;
-                    }
-                } else {
-                    if (par && this.current === this.link) {
-                        par.replaceChild(this.span,this.current);
-                        this.current = this.span;
-                    }
-                }
-            },
-            destroy : function () {
-                YUE.purgeElement(this.link);
-                this.current.parentNode.removeChild(this.current);
-                this.link = this.span = null;
-            },
-            onClick : function (e) {
-                YUE.stopEvent(e);
-                this.paginator.setPage(1);
-            }
-        };
-
-        })();
-
-    (function () {
-
-        var Paginator = YAHOO.widget.Paginator,
-            l         = YAHOO.lang,
-            setId     = YAHOO.util.Dom.generateId;
-
-        Paginator.ui.MyLastPageLink = function (p) {
-            this.paginator = p;
-
-            p.subscribe('recordOffsetChange',this.update,this,true);
-            p.subscribe('rowsPerPageChange',this.update,this,true);
-            p.subscribe('totalRecordsChange',this.update,this,true);
-            p.subscribe('destroy',this.destroy,this,true);
-
-            // TODO: make this work
-            p.subscribe('lastPageLinkLabelChange',this.update,this,true);
-            p.subscribe('lastPageLinkClassChange', this.update,this,true);
-        };
-
-        Paginator.ui.MyLastPageLink.init = function (p) {
-            p.setAttributeConfig('lastPageLinkLabel', {
-                value : -1,
-                validator : l.isString
-            });
-            p.setAttributeConfig('lastPageLinkClass', {
-                value : 'yui-pg-last',
-                validator : l.isString
-            });
-            p.setAttributeConfig('lastPageLinkTitle', {
-                value : 'Last Page',
-                validator : l.isString
-            });
-
-        };
-
-        Paginator.ui.MyLastPageLink.prototype = {
-
-            current   : null,
-            leftmost_page: null,
-            rightmost_page: null,
-            link      : null,
-            span      : null,
-            dotdot    : null,
-            na        : null,
-            getPos    : function(cur_page, max_page, items){
-                var edge = parseInt(items / 2) + 1;
-                if (cur_page <= edge){
-                    var radius = Math.max(parseInt(items / 2), items - cur_page);
-                }
-                else if ((max_page - cur_page) < edge) {
-                    var radius = (items - 1) - (max_page - cur_page);
-                }
-                else{
-                    var radius = parseInt(items / 2);
-                }
-
-                var left = Math.max(1, (cur_page - (radius)));
-                var right = Math.min(max_page, cur_page + (radius));
-                return [left, cur_page, right]
-            },
-            render : function (id_base) {
-                var p      = this.paginator,
-                    c      = p.get('lastPageLinkClass'),
-                    label  = p.get('lastPageLinkLabel'),
-                    last   = p.getTotalPages(),
-                    title  = p.get('lastPageLinkTitle');
-
-                var _pos = this.getPos(p.getCurrentPage(), p.getTotalPages(), 5);
-                this.leftmost_page = _pos[0];
-                this.rightmost_page = _pos[2];
-
-                this.link = document.createElement('a');
-                this.span = document.createElement('span');
-                $(this.span).hide();
-
-                this.na   = this.span.cloneNode(false);
-
-                setId(this.link, id_base + '-last-link');
-                this.link.href      = '#';
-                this.link.className = c;
-                this.link.innerHTML = label;
-                this.link.title     = title;
-                YUE.on(this.link,'click',this.onClick,this,true);
-
-                setId(this.span, id_base + '-last-span');
-                this.span.className = c;
-                this.span.innerHTML = label;
-
-                setId(this.na, id_base + '-last-na');
-
-                if (this.rightmost_page < p.getTotalPages()){
-                    this.current = this.link;
-                }
-                else{
-                    this.current = this.span;
-                }
-
-                this.current.innerHTML = p.getTotalPages();
-                return this.current;
-            },
-
-            update : function (e) {
-                var p      = this.paginator;
-
-                var _pos = this.getPos(p.getCurrentPage(), p.getTotalPages(), 5);
-                this.leftmost_page = _pos[0];
-                this.rightmost_page = _pos[2];
-
-                if (e && e.prevValue === e.newValue) {
-                    return;
-                }
-
-                var par   = this.current ? this.current.parentNode : null,
-                    after = this.link;
-                if (par) {
-
-                    // only show the last page if the rightmost one is
-                    // lower, so we don't have doubled entries at the end
-                    if (!(this.rightmost_page < p.getTotalPages())){
-                        after = this.span
-                    }
-
-                    if (this.current !== after) {
-                        par.replaceChild(after,this.current);
-                        this.current = after;
-                    }
-                }
-                this.current.innerHTML = this.paginator.getTotalPages();
-
-            },
-            destroy : function () {
-                YUE.purgeElement(this.link);
-                this.current.parentNode.removeChild(this.current);
-                this.link = this.span = null;
-            },
-            onClick : function (e) {
-                YUE.stopEvent(e);
-                this.paginator.setPage(this.paginator.getTotalPages());
-            }
-        };
-
-        })();
-
-    var pagi = new YAHOO.widget.Paginator({
-        rowsPerPage: links_per_page,
-        alwaysVisible: false,
-        template : "{PreviousPageLink} {MyFirstPageLink} {PageLinks} {MyLastPageLink} {NextPageLink}",
-        pageLinks: 5,
-        containerClass: 'pagination-wh',
-        currentPageClass: 'pager_curpage',
-        pageLinkClass: 'pager_link',
-        nextPageLinkLabel: '&gt;',
-        previousPageLinkLabel: '&lt;',
-        containers:containers
-    });
-
-    return pagi
-}
-
-var YUI_datatable = function(data, fields, columns, countnode, sortkey, rows){
-    var myDataSource = new YAHOO.util.DataSource(data);
-    myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
-    myDataSource.responseSchema = {
-        resultsList: "records",
-        fields: fields
-        };
-    myDataSource.doBeforeCallback = function(req, raw, res, cb) {
-        // This is the filter function
-        var data     = res.results || [],
-            filtered = [],
-            i, l;
-
-        if (req) {
-            req = req.toLowerCase();
-            for (i = 0; i<data.length; i++) {
-                var pos = data[i].raw_name.toLowerCase().indexOf(req);
-                if (pos != -1) {
-                    filtered.push(data[i]);
-                }
-            }
-            res.results = filtered;
-        }
-        $(countnode).html(res.results.length);
-        return res;
-    }
-
-    var myDataTable = new YAHOO.widget.DataTable("datatable_list_wrap", columns, myDataSource, {
-        sortedBy: {key:sortkey, dir:"asc"},
-        paginator: YUI_paginator(rows !== undefined && rows ? rows : 25, ['user-paginator']),
-        MSG_SORTASC: _TM['MSG_SORTASC'],
-        MSG_SORTDESC: _TM['MSG_SORTDESC'],
-        MSG_EMPTY: _TM['MSG_EMPTY'],
-        MSG_ERROR: _TM['MSG_ERROR'],
-        MSG_LOADING: _TM['MSG_LOADING']
-        });
-    myDataTable.subscribe('postRenderEvent',function(oArgs) {
-        tooltip_activate();
-        quick_repo_menu();
-        });
-
-    var filterTimeout = null;
-    var $q_filter = $('#q_filter');
-
-    var updateFilter = function () {
-        // Reset timeout
-        filterTimeout = null;
-
-        // Reset sort
-        var state = myDataTable.getState();
-        state.sortedBy = {key:sortkey, dir:YAHOO.widget.DataTable.CLASS_ASC};
-
-        // Get filtered data
-        myDataSource.sendRequest($q_filter.val(), {
-            success : myDataTable.onDataReturnInitializeTable,
-            failure : myDataTable.onDataReturnInitializeTable,
-            scope   : myDataTable,
-            argument: state});
-        };
-
-    $q_filter.click(function(){
-            if(!$q_filter.hasClass('loaded')){
-                //TODO: load here full list later to do search within groups
-                $q_filter.addClass('loaded');
-            }
-        });
-
-    $q_filter.keyup(function (e) {
-            clearTimeout(filterTimeout);
-            filterTimeout = setTimeout(updateFilter, 600);
-        });
-}
 
 /**
  Branch Sorting callback for select2, modifying the filtered result so prefix
@@ -1858,9 +1454,40 @@
                 return -1;
             }
 
+            // Put early (especially prefix) matches before later matches
+            var aPos = a.text.toLowerCase().indexOf(query.term.toLowerCase()),
+                bPos = b.text.toLowerCase().indexOf(query.term.toLowerCase());
+            if (aPos < bPos) {
+                return -1;
+            }
+            if (bPos < aPos) {
+                return 1;
+            }
+
+            // Default sorting
+            if (a.text > b.text) {
+                return 1;
+            }
+            if (a.text < b.text) {
+                return -1;
+            }
+            return 0;
+        });
+    }
+    return results;
+};
+
+var prefixFirstSort = function(results, container, query) {
+    if (query.term) {
+        return results.sort(function (a, b) {
+            // if parent node, no sorting
+            if (a.children != undefined || b.children != undefined) {
+                return 0;
+            }
+
             // Put prefix matches before matches in the line
-            var aPos = a.text.indexOf(query.term),
-                bPos = b.text.indexOf(query.term);
+            var aPos = a.text.toLowerCase().indexOf(query.term.toLowerCase()),
+                bPos = b.text.toLowerCase().indexOf(query.term.toLowerCase());
             if (aPos === 0 && bPos !== 0) {
                 return -1;
             }
@@ -1881,19 +1508,12 @@
     return results;
 };
 
-// global hooks after DOM is loaded
+/* Helper for jQuery DataTables */
 
-$(document).ready(function(){
-    $('.diff-collapse-button').click(function(e) {
-        var $button = $(e.currentTarget);
-        var $target = $('#' + $button.attr('target'));
-        if($target.hasClass('hidden')){
-            $target.removeClass('hidden');
-            $button.html("&uarr; {0} &uarr;".format(_TM['Collapse Diff']));
-        }
-        else if(!$target.hasClass('hidden')){
-            $target.addClass('hidden');
-            $button.html("&darr; {0} &darr;".format(_TM['Expand Diff']));
-        }
-    });
-});
+var updateRowCountCallback = function updateRowCountCallback($elem, onlyDisplayed) {
+    return function drawCallback() {
+        var info = this.api().page.info(),
+            count = onlyDisplayed === true ? info.recordsDisplay : info.recordsTotal;
+        $elem.html(count);
+    }
+};
--- a/kallithea/public/js/bootstrap.js	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/public/js/bootstrap.js	Fri Nov 18 01:11:13 2016 +0100
@@ -1,31 +1,32 @@
-/**
-* bootstrap.js v3.0.0 by @fat and @mdo
-* Copyright 2013 Twitter Inc.
-* http://www.apache.org/licenses/LICENSE-2.0
-*/
-if (!jQuery) { throw new Error("Bootstrap requires jQuery") }
+/*!
+ * Bootstrap v3.3.7 (http://getbootstrap.com)
+ * Copyright 2011-2016 Twitter, Inc.
+ * Licensed under the MIT license
+ */
+
+if (typeof jQuery === 'undefined') {
+  throw new Error('Bootstrap\'s JavaScript requires jQuery')
+}
+
++function ($) {
+  'use strict';
+  var version = $.fn.jquery.split(' ')[0].split('.')
+  if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 3)) {
+    throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4')
+  }
+}(jQuery);
 
 /* ========================================================================
- * Bootstrap: transition.js v3.0.0
- * http://twbs.github.com/bootstrap/javascript.html#transitions
+ * Bootstrap: transition.js v3.3.7
+ * http://getbootstrap.com/javascript/#transitions
  * ========================================================================
- * Copyright 2013 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Copyright 2011-2016 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  * ======================================================================== */
 
 
-+function ($) { "use strict";
++function ($) {
+  'use strict';
 
   // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
   // ============================================================
@@ -34,10 +35,10 @@
     var el = document.createElement('bootstrap')
 
     var transEndEventNames = {
-      'WebkitTransition' : 'webkitTransitionEnd'
-    , 'MozTransition'    : 'transitionend'
-    , 'OTransition'      : 'oTransitionEnd otransitionend'
-    , 'transition'       : 'transitionend'
+      WebkitTransition : 'webkitTransitionEnd',
+      MozTransition    : 'transitionend',
+      OTransition      : 'oTransitionEnd otransitionend',
+      transition       : 'transitionend'
     }
 
     for (var name in transEndEventNames) {
@@ -45,12 +46,15 @@
         return { end: transEndEventNames[name] }
       }
     }
+
+    return false // explicit for ie8 (  ._.)
   }
 
   // http://blog.alexmaccaw.com/css-transitions
   $.fn.emulateTransitionEnd = function (duration) {
-    var called = false, $el = this
-    $(this).one($.support.transition.end, function () { called = true })
+    var called = false
+    var $el = this
+    $(this).one('bsTransitionEnd', function () { called = true })
     var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
     setTimeout(callback, duration)
     return this
@@ -58,31 +62,31 @@
 
   $(function () {
     $.support.transition = transitionEnd()
+
+    if (!$.support.transition) return
+
+    $.event.special.bsTransitionEnd = {
+      bindType: $.support.transition.end,
+      delegateType: $.support.transition.end,
+      handle: function (e) {
+        if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
+      }
+    }
   })
 
-}(window.jQuery);
+}(jQuery);
 
 /* ========================================================================
- * Bootstrap: alert.js v3.0.0
- * http://twbs.github.com/bootstrap/javascript.html#alerts
+ * Bootstrap: alert.js v3.3.7
+ * http://getbootstrap.com/javascript/#alerts
  * ========================================================================
- * Copyright 2013 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Copyright 2011-2016 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  * ======================================================================== */
 
 
-+function ($) { "use strict";
++function ($) {
+  'use strict';
 
   // ALERT CLASS DEFINITION
   // ======================
@@ -92,6 +96,10 @@
     $(el).on('click', dismiss, this.close)
   }
 
+  Alert.VERSION = '3.3.7'
+
+  Alert.TRANSITION_DURATION = 150
+
   Alert.prototype.close = function (e) {
     var $this    = $(this)
     var selector = $this.attr('data-target')
@@ -101,12 +109,12 @@
       selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
     }
 
-    var $parent = $(selector)
+    var $parent = $(selector === '#' ? [] : selector)
 
     if (e) e.preventDefault()
 
     if (!$parent.length) {
-      $parent = $this.hasClass('alert') ? $this : $this.parent()
+      $parent = $this.closest('.alert')
     }
 
     $parent.trigger(e = $.Event('close.bs.alert'))
@@ -116,13 +124,14 @@
     $parent.removeClass('in')
 
     function removeElement() {
-      $parent.trigger('closed.bs.alert').remove()
+      // detach from parent, fire event then clean up data
+      $parent.detach().trigger('closed.bs.alert').remove()
     }
 
     $.support.transition && $parent.hasClass('fade') ?
       $parent
-        .one($.support.transition.end, removeElement)
-        .emulateTransitionEnd(150) :
+        .one('bsTransitionEnd', removeElement)
+        .emulateTransitionEnd(Alert.TRANSITION_DURATION) :
       removeElement()
   }
 
@@ -130,9 +139,7 @@
   // ALERT PLUGIN DEFINITION
   // =======================
 
-  var old = $.fn.alert
-
-  $.fn.alert = function (option) {
+  function Plugin(option) {
     return this.each(function () {
       var $this = $(this)
       var data  = $this.data('bs.alert')
@@ -142,6 +149,9 @@
     })
   }
 
+  var old = $.fn.alert
+
+  $.fn.alert             = Plugin
   $.fn.alert.Constructor = Alert
 
 
@@ -159,38 +169,31 @@
 
   $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
 
-}(window.jQuery);
+}(jQuery);
 
 /* ========================================================================
- * Bootstrap: button.js v3.0.0
- * http://twbs.github.com/bootstrap/javascript.html#buttons
+ * Bootstrap: button.js v3.3.7
+ * http://getbootstrap.com/javascript/#buttons
  * ========================================================================
- * Copyright 2013 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Copyright 2011-2016 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  * ======================================================================== */
 
 
-+function ($) { "use strict";
++function ($) {
+  'use strict';
 
   // BUTTON PUBLIC CLASS DEFINITION
   // ==============================
 
   var Button = function (element, options) {
-    this.$element = $(element)
-    this.options  = $.extend({}, Button.DEFAULTS, options)
+    this.$element  = $(element)
+    this.options   = $.extend({}, Button.DEFAULTS, options)
+    this.isLoading = false
   }
 
+  Button.VERSION  = '3.3.7'
+
   Button.DEFAULTS = {
     loadingText: 'loading...'
   }
@@ -201,40 +204,51 @@
     var val  = $el.is('input') ? 'val' : 'html'
     var data = $el.data()
 
-    state = state + 'Text'
-
-    if (!data.resetText) $el.data('resetText', $el[val]())
-
-    $el[val](data[state] || this.options[state])
+    state += 'Text'
+
+    if (data.resetText == null) $el.data('resetText', $el[val]())
 
     // push to event loop to allow forms to submit
-    setTimeout(function () {
-      state == 'loadingText' ?
-        $el.addClass(d).attr(d, d) :
-        $el.removeClass(d).removeAttr(d);
-    }, 0)
+    setTimeout($.proxy(function () {
+      $el[val](data[state] == null ? this.options[state] : data[state])
+
+      if (state == 'loadingText') {
+        this.isLoading = true
+        $el.addClass(d).attr(d, d).prop(d, true)
+      } else if (this.isLoading) {
+        this.isLoading = false
+        $el.removeClass(d).removeAttr(d).prop(d, false)
+      }
+    }, this), 0)
   }
 
   Button.prototype.toggle = function () {
+    var changed = true
     var $parent = this.$element.closest('[data-toggle="buttons"]')
 
     if ($parent.length) {
       var $input = this.$element.find('input')
-        .prop('checked', !this.$element.hasClass('active'))
-        .trigger('change')
-      if ($input.prop('type') === 'radio') $parent.find('.active').removeClass('active')
+      if ($input.prop('type') == 'radio') {
+        if ($input.prop('checked')) changed = false
+        $parent.find('.active').removeClass('active')
+        this.$element.addClass('active')
+      } else if ($input.prop('type') == 'checkbox') {
+        if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
+        this.$element.toggleClass('active')
+      }
+      $input.prop('checked', this.$element.hasClass('active'))
+      if (changed) $input.trigger('change')
+    } else {
+      this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
+      this.$element.toggleClass('active')
     }
-
-    this.$element.toggleClass('active')
   }
 
 
   // BUTTON PLUGIN DEFINITION
   // ========================
 
-  var old = $.fn.button
-
-  $.fn.button = function (option) {
+  function Plugin(option) {
     return this.each(function () {
       var $this   = $(this)
       var data    = $this.data('bs.button')
@@ -247,6 +261,9 @@
     })
   }
 
+  var old = $.fn.button
+
+  $.fn.button             = Plugin
   $.fn.button.Constructor = Button
 
 
@@ -262,36 +279,35 @@
   // BUTTON DATA-API
   // ===============
 
-  $(document).on('click.bs.button.data-api', '[data-toggle^=button]', function (e) {
-    var $btn = $(e.target)
-    if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
-    $btn.button('toggle')
-    e.preventDefault()
-  })
-
-}(window.jQuery);
+  $(document)
+    .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
+      var $btn = $(e.target).closest('.btn')
+      Plugin.call($btn, 'toggle')
+      if (!($(e.target).is('input[type="radio"], input[type="checkbox"]'))) {
+        // Prevent double click on radios, and the double selections (so cancellation) on checkboxes
+        e.preventDefault()
+        // The target component still receive the focus
+        if ($btn.is('input,button')) $btn.trigger('focus')
+        else $btn.find('input:visible,button:visible').first().trigger('focus')
+      }
+    })
+    .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
+      $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
+    })
+
+}(jQuery);
 
 /* ========================================================================
- * Bootstrap: carousel.js v3.0.0
- * http://twbs.github.com/bootstrap/javascript.html#carousel
+ * Bootstrap: carousel.js v3.3.7
+ * http://getbootstrap.com/javascript/#carousel
  * ========================================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Copyright 2011-2016 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  * ======================================================================== */
 
 
-+function ($) { "use strict";
++function ($) {
+  'use strict';
 
   // CAROUSEL CLASS DEFINITION
   // =========================
@@ -300,24 +316,42 @@
     this.$element    = $(element)
     this.$indicators = this.$element.find('.carousel-indicators')
     this.options     = options
-    this.paused      =
-    this.sliding     =
-    this.interval    =
-    this.$active     =
+    this.paused      = null
+    this.sliding     = null
+    this.interval    = null
+    this.$active     = null
     this.$items      = null
 
-    this.options.pause == 'hover' && this.$element
-      .on('mouseenter', $.proxy(this.pause, this))
-      .on('mouseleave', $.proxy(this.cycle, this))
+    this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))
+
+    this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
+      .on('mouseenter.bs.carousel', $.proxy(this.pause, this))
+      .on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
   }
 
+  Carousel.VERSION  = '3.3.7'
+
+  Carousel.TRANSITION_DURATION = 600
+
   Carousel.DEFAULTS = {
-    interval: 5000
-  , pause: 'hover'
-  , wrap: true
+    interval: 5000,
+    pause: 'hover',
+    wrap: true,
+    keyboard: true
   }
 
-  Carousel.prototype.cycle =  function (e) {
+  Carousel.prototype.keydown = function (e) {
+    if (/input|textarea/i.test(e.target.tagName)) return
+    switch (e.which) {
+      case 37: this.prev(); break
+      case 39: this.next(); break
+      default: return
+    }
+
+    e.preventDefault()
+  }
+
+  Carousel.prototype.cycle = function (e) {
     e || (this.paused = false)
 
     this.interval && clearInterval(this.interval)
@@ -329,29 +363,37 @@
     return this
   }
 
-  Carousel.prototype.getActiveIndex = function () {
-    this.$active = this.$element.find('.item.active')
-    this.$items  = this.$active.parent().children()
-
-    return this.$items.index(this.$active)
+  Carousel.prototype.getItemIndex = function (item) {
+    this.$items = item.parent().children('.item')
+    return this.$items.index(item || this.$active)
+  }
+
+  Carousel.prototype.getItemForDirection = function (direction, active) {
+    var activeIndex = this.getItemIndex(active)
+    var willWrap = (direction == 'prev' && activeIndex === 0)
+                || (direction == 'next' && activeIndex == (this.$items.length - 1))
+    if (willWrap && !this.options.wrap) return active
+    var delta = direction == 'prev' ? -1 : 1
+    var itemIndex = (activeIndex + delta) % this.$items.length
+    return this.$items.eq(itemIndex)
   }
 
   Carousel.prototype.to = function (pos) {
     var that        = this
-    var activeIndex = this.getActiveIndex()
+    var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
 
     if (pos > (this.$items.length - 1) || pos < 0) return
 
-    if (this.sliding)       return this.$element.one('slid', function () { that.to(pos) })
+    if (this.sliding)       return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
     if (activeIndex == pos) return this.pause().cycle()
 
-    return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos]))
+    return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
   }
 
   Carousel.prototype.pause = function (e) {
     e || (this.paused = true)
 
-    if (this.$element.find('.next, .prev').length && $.support.transition.end) {
+    if (this.$element.find('.next, .prev').length && $.support.transition) {
       this.$element.trigger($.support.transition.end)
       this.cycle(true)
     }
@@ -373,55 +415,52 @@
 
   Carousel.prototype.slide = function (type, next) {
     var $active   = this.$element.find('.item.active')
-    var $next     = next || $active[type]()
+    var $next     = next || this.getItemForDirection(type, $active)
     var isCycling = this.interval
     var direction = type == 'next' ? 'left' : 'right'
-    var fallback  = type == 'next' ? 'first' : 'last'
     var that      = this
 
-    if (!$next.length) {
-      if (!this.options.wrap) return
-      $next = this.$element.find('.item')[fallback]()
-    }
+    if ($next.hasClass('active')) return (this.sliding = false)
+
+    var relatedTarget = $next[0]
+    var slideEvent = $.Event('slide.bs.carousel', {
+      relatedTarget: relatedTarget,
+      direction: direction
+    })
+    this.$element.trigger(slideEvent)
+    if (slideEvent.isDefaultPrevented()) return
 
     this.sliding = true
 
     isCycling && this.pause()
 
-    var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction })
-
-    if ($next.hasClass('active')) return
-
     if (this.$indicators.length) {
       this.$indicators.find('.active').removeClass('active')
-      this.$element.one('slid', function () {
-        var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()])
-        $nextIndicator && $nextIndicator.addClass('active')
-      })
+      var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
+      $nextIndicator && $nextIndicator.addClass('active')
     }
 
+    var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
     if ($.support.transition && this.$element.hasClass('slide')) {
-      this.$element.trigger(e)
-      if (e.isDefaultPrevented()) return
       $next.addClass(type)
       $next[0].offsetWidth // force reflow
       $active.addClass(direction)
       $next.addClass(direction)
       $active
-        .one($.support.transition.end, function () {
+        .one('bsTransitionEnd', function () {
           $next.removeClass([type, direction].join(' ')).addClass('active')
           $active.removeClass(['active', direction].join(' '))
           that.sliding = false
-          setTimeout(function () { that.$element.trigger('slid') }, 0)
+          setTimeout(function () {
+            that.$element.trigger(slidEvent)
+          }, 0)
         })
-        .emulateTransitionEnd(600)
+        .emulateTransitionEnd(Carousel.TRANSITION_DURATION)
     } else {
-      this.$element.trigger(e)
-      if (e.isDefaultPrevented()) return
       $active.removeClass('active')
       $next.addClass('active')
       this.sliding = false
-      this.$element.trigger('slid')
+      this.$element.trigger(slidEvent)
     }
 
     isCycling && this.cycle()
@@ -433,9 +472,7 @@
   // CAROUSEL PLUGIN DEFINITION
   // ==========================
 
-  var old = $.fn.carousel
-
-  $.fn.carousel = function (option) {
+  function Plugin(option) {
     return this.each(function () {
       var $this   = $(this)
       var data    = $this.data('bs.carousel')
@@ -449,6 +486,9 @@
     })
   }
 
+  var old = $.fn.carousel
+
+  $.fn.carousel             = Plugin
   $.fn.carousel.Constructor = Carousel
 
 
@@ -464,52 +504,49 @@
   // CAROUSEL DATA-API
   // =================
 
-  $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
-    var $this   = $(this), href
-    var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
+  var clickHandler = function (e) {
+    var href
+    var $this   = $(this)
+    var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
+    if (!$target.hasClass('carousel')) return
     var options = $.extend({}, $target.data(), $this.data())
     var slideIndex = $this.attr('data-slide-to')
     if (slideIndex) options.interval = false
 
-    $target.carousel(options)
-
-    if (slideIndex = $this.attr('data-slide-to')) {
+    Plugin.call($target, options)
+
+    if (slideIndex) {
       $target.data('bs.carousel').to(slideIndex)
     }
 
     e.preventDefault()
-  })
+  }
+
+  $(document)
+    .on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
+    .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)
 
   $(window).on('load', function () {
     $('[data-ride="carousel"]').each(function () {
       var $carousel = $(this)
-      $carousel.carousel($carousel.data())
+      Plugin.call($carousel, $carousel.data())
     })
   })
 
-}(window.jQuery);
+}(jQuery);
 
 /* ========================================================================
- * Bootstrap: collapse.js v3.0.0
- * http://twbs.github.com/bootstrap/javascript.html#collapse
+ * Bootstrap: collapse.js v3.3.7
+ * http://getbootstrap.com/javascript/#collapse
  * ========================================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Copyright 2011-2016 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  * ======================================================================== */
 
-
-+function ($) { "use strict";
+/* jshint latedef: false */
+
++function ($) {
+  'use strict';
 
   // COLLAPSE PUBLIC CLASS DEFINITION
   // ================================
@@ -517,12 +554,23 @@
   var Collapse = function (element, options) {
     this.$element      = $(element)
     this.options       = $.extend({}, Collapse.DEFAULTS, options)
+    this.$trigger      = $('[data-toggle="collapse"][href="#' + element.id + '"],' +
+                           '[data-toggle="collapse"][data-target="#' + element.id + '"]')
     this.transitioning = null
 
-    if (this.options.parent) this.$parent = $(this.options.parent)
+    if (this.options.parent) {
+      this.$parent = this.getParent()
+    } else {
+      this.addAriaAndCollapsedClass(this.$element, this.$trigger)
+    }
+
     if (this.options.toggle) this.toggle()
   }
 
+  Collapse.VERSION  = '3.3.7'
+
+  Collapse.TRANSITION_DURATION = 350
+
   Collapse.DEFAULTS = {
     toggle: true
   }
@@ -535,35 +583,43 @@
   Collapse.prototype.show = function () {
     if (this.transitioning || this.$element.hasClass('in')) return
 
+    var activesData
+    var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')
+
+    if (actives && actives.length) {
+      activesData = actives.data('bs.collapse')
+      if (activesData && activesData.transitioning) return
+    }
+
     var startEvent = $.Event('show.bs.collapse')
     this.$element.trigger(startEvent)
     if (startEvent.isDefaultPrevented()) return
 
-    var actives = this.$parent && this.$parent.find('> .panel > .in')
-
     if (actives && actives.length) {
-      var hasData = actives.data('bs.collapse')
-      if (hasData && hasData.transitioning) return
-      actives.collapse('hide')
-      hasData || actives.data('bs.collapse', null)
+      Plugin.call(actives, 'hide')
+      activesData || actives.data('bs.collapse', null)
     }
 
     var dimension = this.dimension()
 
     this.$element
       .removeClass('collapse')
-      .addClass('collapsing')
-      [dimension](0)
+      .addClass('collapsing')[dimension](0)
+      .attr('aria-expanded', true)
+
+    this.$trigger
+      .removeClass('collapsed')
+      .attr('aria-expanded', true)
 
     this.transitioning = 1
 
     var complete = function () {
       this.$element
         .removeClass('collapsing')
-        .addClass('in')
-        [dimension]('auto')
+        .addClass('collapse in')[dimension]('')
       this.transitioning = 0
-      this.$element.trigger('shown.bs.collapse')
+      this.$element
+        .trigger('shown.bs.collapse')
     }
 
     if (!$.support.transition) return complete.call(this)
@@ -571,9 +627,8 @@
     var scrollSize = $.camelCase(['scroll', dimension].join('-'))
 
     this.$element
-      .one($.support.transition.end, $.proxy(complete, this))
-      .emulateTransitionEnd(350)
-      [dimension](this.$element[0][scrollSize])
+      .one('bsTransitionEnd', $.proxy(complete, this))
+      .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
   }
 
   Collapse.prototype.hide = function () {
@@ -585,54 +640,85 @@
 
     var dimension = this.dimension()
 
-    this.$element
-      [dimension](this.$element[dimension]())
-      [0].offsetHeight
+    this.$element[dimension](this.$element[dimension]())[0].offsetHeight
 
     this.$element
       .addClass('collapsing')
-      .removeClass('collapse')
-      .removeClass('in')
+      .removeClass('collapse in')
+      .attr('aria-expanded', false)
+
+    this.$trigger
+      .addClass('collapsed')
+      .attr('aria-expanded', false)
 
     this.transitioning = 1
 
     var complete = function () {
       this.transitioning = 0
       this.$element
-        .trigger('hidden.bs.collapse')
         .removeClass('collapsing')
         .addClass('collapse')
+        .trigger('hidden.bs.collapse')
     }
 
     if (!$.support.transition) return complete.call(this)
 
     this.$element
       [dimension](0)
-      .one($.support.transition.end, $.proxy(complete, this))
-      .emulateTransitionEnd(350)
+      .one('bsTransitionEnd', $.proxy(complete, this))
+      .emulateTransitionEnd(Collapse.TRANSITION_DURATION)
   }
 
   Collapse.prototype.toggle = function () {
     this[this.$element.hasClass('in') ? 'hide' : 'show']()
   }
 
+  Collapse.prototype.getParent = function () {
+    return $(this.options.parent)
+      .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
+      .each($.proxy(function (i, element) {
+        var $element = $(element)
+        this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
+      }, this))
+      .end()
+  }
+
+  Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) {
+    var isOpen = $element.hasClass('in')
+
+    $element.attr('aria-expanded', isOpen)
+    $trigger
+      .toggleClass('collapsed', !isOpen)
+      .attr('aria-expanded', isOpen)
+  }
+
+  function getTargetFromTrigger($trigger) {
+    var href
+    var target = $trigger.attr('data-target')
+      || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
+
+    return $(target)
+  }
+
 
   // COLLAPSE PLUGIN DEFINITION
   // ==========================
 
-  var old = $.fn.collapse
-
-  $.fn.collapse = function (option) {
+  function Plugin(option) {
     return this.each(function () {
       var $this   = $(this)
       var data    = $this.data('bs.collapse')
       var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
 
+      if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false
       if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
       if (typeof option == 'string') data[option]()
     })
   }
 
+  var old = $.fn.collapse
+
+  $.fn.collapse             = Plugin
   $.fn.collapse.Constructor = Collapse
 
 
@@ -648,56 +734,75 @@
   // COLLAPSE DATA-API
   // =================
 
-  $(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function (e) {
-    var $this   = $(this), href
-    var target  = $this.attr('data-target')
-        || e.preventDefault()
-        || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
-    var $target = $(target)
+  $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
+    var $this   = $(this)
+
+    if (!$this.attr('data-target')) e.preventDefault()
+
+    var $target = getTargetFromTrigger($this)
     var data    = $target.data('bs.collapse')
     var option  = data ? 'toggle' : $this.data()
-    var parent  = $this.attr('data-parent')
-    var $parent = parent && $(parent)
-
-    if (!data || !data.transitioning) {
-      if ($parent) $parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed')
-      $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
-    }
-
-    $target.collapse(option)
+
+    Plugin.call($target, option)
   })
 
-}(window.jQuery);
+}(jQuery);
 
 /* ========================================================================
- * Bootstrap: dropdown.js v3.0.0
- * http://twbs.github.com/bootstrap/javascript.html#dropdowns
+ * Bootstrap: dropdown.js v3.3.7
+ * http://getbootstrap.com/javascript/#dropdowns
  * ========================================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Copyright 2011-2016 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  * ======================================================================== */
 
 
-+function ($) { "use strict";
++function ($) {
+  'use strict';
 
   // DROPDOWN CLASS DEFINITION
   // =========================
 
   var backdrop = '.dropdown-backdrop'
-  var toggle   = '[data-toggle=dropdown]'
+  var toggle   = '[data-toggle="dropdown"]'
   var Dropdown = function (element) {
-    var $el = $(element).on('click.bs.dropdown', this.toggle)
+    $(element).on('click.bs.dropdown', this.toggle)
+  }
+
+  Dropdown.VERSION = '3.3.7'
+
+  function getParent($this) {
+    var selector = $this.attr('data-target')
+
+    if (!selector) {
+      selector = $this.attr('href')
+      selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
+    }
+
+    var $parent = selector && $(selector)
+
+    return $parent && $parent.length ? $parent : $this.parent()
+  }
+
+  function clearMenus(e) {
+    if (e && e.which === 3) return
+    $(backdrop).remove()
+    $(toggle).each(function () {
+      var $this         = $(this)
+      var $parent       = getParent($this)
+      var relatedTarget = { relatedTarget: this }
+
+      if (!$parent.hasClass('open')) return
+
+      if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
+
+      $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
+
+      if (e.isDefaultPrevented()) return
+
+      $this.attr('aria-expanded', 'false')
+      $parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget))
+    })
   }
 
   Dropdown.prototype.toggle = function (e) {
@@ -712,26 +817,32 @@
 
     if (!isActive) {
       if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
-        // if mobile we we use a backdrop because click events don't delegate
-        $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
+        // if mobile we use a backdrop because click events don't delegate
+        $(document.createElement('div'))
+          .addClass('dropdown-backdrop')
+          .insertAfter($(this))
+          .on('click', clearMenus)
       }
 
-      $parent.trigger(e = $.Event('show.bs.dropdown'))
+      var relatedTarget = { relatedTarget: this }
+      $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
 
       if (e.isDefaultPrevented()) return
 
+      $this
+        .trigger('focus')
+        .attr('aria-expanded', 'true')
+
       $parent
         .toggleClass('open')
-        .trigger('shown.bs.dropdown')
-
-      $this.focus()
+        .trigger($.Event('shown.bs.dropdown', relatedTarget))
     }
 
     return false
   }
 
   Dropdown.prototype.keydown = function (e) {
-    if (!/(38|40|27)/.test(e.keyCode)) return
+    if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
 
     var $this = $(this)
 
@@ -743,64 +854,42 @@
     var $parent  = getParent($this)
     var isActive = $parent.hasClass('open')
 
-    if (!isActive || (isActive && e.keyCode == 27)) {
-      if (e.which == 27) $parent.find(toggle).focus()
-      return $this.click()
+    if (!isActive && e.which != 27 || isActive && e.which == 27) {
+      if (e.which == 27) $parent.find(toggle).trigger('focus')
+      return $this.trigger('click')
     }
 
-    var $items = $('[role=menu] li:not(.divider):visible a', $parent)
+    var desc = ' li:not(.disabled):visible a'
+    var $items = $parent.find('.dropdown-menu' + desc)
 
     if (!$items.length) return
 
-    var index = $items.index($items.filter(':focus'))
-
-    if (e.keyCode == 38 && index > 0)                 index--                        // up
-    if (e.keyCode == 40 && index < $items.length - 1) index++                        // down
-    if (!~index)                                      index=0
-
-    $items.eq(index).focus()
-  }
-
-  function clearMenus() {
-    $(backdrop).remove()
-    $(toggle).each(function (e) {
-      var $parent = getParent($(this))
-      if (!$parent.hasClass('open')) return
-      $parent.trigger(e = $.Event('hide.bs.dropdown'))
-      if (e.isDefaultPrevented()) return
-      $parent.removeClass('open').trigger('hidden.bs.dropdown')
-    })
-  }
-
-  function getParent($this) {
-    var selector = $this.attr('data-target')
-
-    if (!selector) {
-      selector = $this.attr('href')
-      selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
-    }
-
-    var $parent = selector && $(selector)
-
-    return $parent && $parent.length ? $parent : $this.parent()
+    var index = $items.index(e.target)
+
+    if (e.which == 38 && index > 0)                 index--         // up
+    if (e.which == 40 && index < $items.length - 1) index++         // down
+    if (!~index)                                    index = 0
+
+    $items.eq(index).trigger('focus')
   }
 
 
   // DROPDOWN PLUGIN DEFINITION
   // ==========================
 
-  var old = $.fn.dropdown
-
-  $.fn.dropdown = function (option) {
+  function Plugin(option) {
     return this.each(function () {
       var $this = $(this)
-      var data  = $this.data('dropdown')
-
-      if (!data) $this.data('dropdown', (data = new Dropdown(this)))
+      var data  = $this.data('bs.dropdown')
+
+      if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
       if (typeof option == 'string') data[option].call($this)
     })
   }
 
+  var old = $.fn.dropdown
+
+  $.fn.dropdown             = Plugin
   $.fn.dropdown.Constructor = Dropdown
 
 
@@ -819,53 +908,60 @@
   $(document)
     .on('click.bs.dropdown.data-api', clearMenus)
     .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
-    .on('click.bs.dropdown.data-api'  , toggle, Dropdown.prototype.toggle)
-    .on('keydown.bs.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown)
-
-}(window.jQuery);
+    .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
+    .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
+    .on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)
+
+}(jQuery);
 
 /* ========================================================================
- * Bootstrap: modal.js v3.0.0
- * http://twbs.github.com/bootstrap/javascript.html#modals
+ * Bootstrap: modal.js v3.3.7
+ * http://getbootstrap.com/javascript/#modals
  * ========================================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Copyright 2011-2016 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  * ======================================================================== */
 
 
-+function ($) { "use strict";
++function ($) {
+  'use strict';
 
   // MODAL CLASS DEFINITION
   // ======================
 
   var Modal = function (element, options) {
-    this.options   = options
-    this.$element  = $(element)
-    this.$backdrop =
-    this.isShown   = null
-
-    if (this.options.remote) this.$element.load(this.options.remote)
+    this.options             = options
+    this.$body               = $(document.body)
+    this.$element            = $(element)
+    this.$dialog             = this.$element.find('.modal-dialog')
+    this.$backdrop           = null
+    this.isShown             = null
+    this.originalBodyPad     = null
+    this.scrollbarWidth      = 0
+    this.ignoreBackdropClick = false
+
+    if (this.options.remote) {
+      this.$element
+        .find('.modal-content')
+        .load(this.options.remote, $.proxy(function () {
+          this.$element.trigger('loaded.bs.modal')
+        }, this))
+    }
   }
 
+  Modal.VERSION  = '3.3.7'
+
+  Modal.TRANSITION_DURATION = 300
+  Modal.BACKDROP_TRANSITION_DURATION = 150
+
   Modal.DEFAULTS = {
-      backdrop: true
-    , keyboard: true
-    , show: true
+    backdrop: true,
+    keyboard: true,
+    show: true
   }
 
   Modal.prototype.toggle = function (_relatedTarget) {
-    return this[!this.isShown ? 'show' : 'hide'](_relatedTarget)
+    return this.isShown ? this.hide() : this.show(_relatedTarget)
   }
 
   Modal.prototype.show = function (_relatedTarget) {
@@ -878,38 +974,51 @@
 
     this.isShown = true
 
+    this.checkScrollbar()
+    this.setScrollbar()
+    this.$body.addClass('modal-open')
+
     this.escape()
-
-    this.$element.on('click.dismiss.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
+    this.resize()
+
+    this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
+
+    this.$dialog.on('mousedown.dismiss.bs.modal', function () {
+      that.$element.one('mouseup.dismiss.bs.modal', function (e) {
+        if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
+      })
+    })
 
     this.backdrop(function () {
       var transition = $.support.transition && that.$element.hasClass('fade')
 
       if (!that.$element.parent().length) {
-        that.$element.appendTo(document.body) // don't move modals dom position
+        that.$element.appendTo(that.$body) // don't move modals dom position
       }
 
-      that.$element.show()
+      that.$element
+        .show()
+        .scrollTop(0)
+
+      that.adjustDialog()
 
       if (transition) {
         that.$element[0].offsetWidth // force reflow
       }
 
-      that.$element
-        .addClass('in')
-        .attr('aria-hidden', false)
+      that.$element.addClass('in')
 
       that.enforceFocus()
 
       var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
 
       transition ?
-        that.$element.find('.modal-dialog') // wait for modal to slide in
-          .one($.support.transition.end, function () {
-            that.$element.focus().trigger(e)
+        that.$dialog // wait for modal to slide in
+          .one('bsTransitionEnd', function () {
+            that.$element.trigger('focus').trigger(e)
           })
-          .emulateTransitionEnd(300) :
-        that.$element.focus().trigger(e)
+          .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
+        that.$element.trigger('focus').trigger(e)
     })
   }
 
@@ -925,18 +1034,21 @@
     this.isShown = false
 
     this.escape()
+    this.resize()
 
     $(document).off('focusin.bs.modal')
 
     this.$element
       .removeClass('in')
-      .attr('aria-hidden', true)
-      .off('click.dismiss.modal')
+      .off('click.dismiss.bs.modal')
+      .off('mouseup.dismiss.bs.modal')
+
+    this.$dialog.off('mousedown.dismiss.bs.modal')
 
     $.support.transition && this.$element.hasClass('fade') ?
       this.$element
-        .one($.support.transition.end, $.proxy(this.hideModal, this))
-        .emulateTransitionEnd(300) :
+        .one('bsTransitionEnd', $.proxy(this.hideModal, this))
+        .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
       this.hideModal()
   }
 
@@ -944,19 +1056,29 @@
     $(document)
       .off('focusin.bs.modal') // guard against infinite focus loop
       .on('focusin.bs.modal', $.proxy(function (e) {
-        if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
-          this.$element.focus()
+        if (document !== e.target &&
+            this.$element[0] !== e.target &&
+            !this.$element.has(e.target).length) {
+          this.$element.trigger('focus')
         }
       }, this))
   }
 
   Modal.prototype.escape = function () {
     if (this.isShown && this.options.keyboard) {
-      this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) {
+      this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
         e.which == 27 && this.hide()
       }, this))
     } else if (!this.isShown) {
-      this.$element.off('keyup.dismiss.bs.modal')
+      this.$element.off('keydown.dismiss.bs.modal')
+    }
+  }
+
+  Modal.prototype.resize = function () {
+    if (this.isShown) {
+      $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
+    } else {
+      $(window).off('resize.bs.modal')
     }
   }
 
@@ -964,7 +1086,9 @@
     var that = this
     this.$element.hide()
     this.backdrop(function () {
-      that.removeBackdrop()
+      that.$body.removeClass('modal-open')
+      that.resetAdjustments()
+      that.resetScrollbar()
       that.$element.trigger('hidden.bs.modal')
     })
   }
@@ -975,20 +1099,25 @@
   }
 
   Modal.prototype.backdrop = function (callback) {
-    var that    = this
+    var that = this
     var animate = this.$element.hasClass('fade') ? 'fade' : ''
 
     if (this.isShown && this.options.backdrop) {
       var doAnimate = $.support.transition && animate
 
-      this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
-        .appendTo(document.body)
-
-      this.$element.on('click.dismiss.modal', $.proxy(function (e) {
+      this.$backdrop = $(document.createElement('div'))
+        .addClass('modal-backdrop ' + animate)
+        .appendTo(this.$body)
+
+      this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
+        if (this.ignoreBackdropClick) {
+          this.ignoreBackdropClick = false
+          return
+        }
         if (e.target !== e.currentTarget) return
         this.options.backdrop == 'static'
-          ? this.$element[0].focus.call(this.$element[0])
-          : this.hide.call(this)
+          ? this.$element[0].focus()
+          : this.hide()
       }, this))
 
       if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
@@ -999,31 +1128,84 @@
 
       doAnimate ?
         this.$backdrop
-          .one($.support.transition.end, callback)
-          .emulateTransitionEnd(150) :
+          .one('bsTransitionEnd', callback)
+          .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
         callback()
 
     } else if (!this.isShown && this.$backdrop) {
       this.$backdrop.removeClass('in')
 
-      $.support.transition && this.$element.hasClass('fade')?
+      var callbackRemove = function () {
+        that.removeBackdrop()
+        callback && callback()
+      }
+      $.support.transition && this.$element.hasClass('fade') ?
         this.$backdrop
-          .one($.support.transition.end, callback)
-          .emulateTransitionEnd(150) :
-        callback()
+          .one('bsTransitionEnd', callbackRemove)
+          .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
+        callbackRemove()
 
     } else if (callback) {
       callback()
     }
   }
 
+  // these following methods are used to handle overflowing modals
+
+  Modal.prototype.handleUpdate = function () {
+    this.adjustDialog()
+  }
+
+  Modal.prototype.adjustDialog = function () {
+    var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
+
+    this.$element.css({
+      paddingLeft:  !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
+      paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
+    })
+  }
+
+  Modal.prototype.resetAdjustments = function () {
+    this.$element.css({
+      paddingLeft: '',
+      paddingRight: ''
+    })
+  }
+
+  Modal.prototype.checkScrollbar = function () {
+    var fullWindowWidth = window.innerWidth
+    if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
+      var documentElementRect = document.documentElement.getBoundingClientRect()
+      fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
+    }
+    this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
+    this.scrollbarWidth = this.measureScrollbar()
+  }
+
+  Modal.prototype.setScrollbar = function () {
+    var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
+    this.originalBodyPad = document.body.style.paddingRight || ''
+    if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
+  }
+
+  Modal.prototype.resetScrollbar = function () {
+    this.$body.css('padding-right', this.originalBodyPad)
+  }
+
+  Modal.prototype.measureScrollbar = function () { // thx walsh
+    var scrollDiv = document.createElement('div')
+    scrollDiv.className = 'modal-scrollbar-measure'
+    this.$body.append(scrollDiv)
+    var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
+    this.$body[0].removeChild(scrollDiv)
+    return scrollbarWidth
+  }
+
 
   // MODAL PLUGIN DEFINITION
   // =======================
 
-  var old = $.fn.modal
-
-  $.fn.modal = function (option, _relatedTarget) {
+  function Plugin(option, _relatedTarget) {
     return this.each(function () {
       var $this   = $(this)
       var data    = $this.data('bs.modal')
@@ -1035,6 +1217,9 @@
     })
   }
 
+  var old = $.fn.modal
+
+  $.fn.modal             = Plugin
   $.fn.modal.Constructor = Modal
 
 
@@ -1053,78 +1238,81 @@
   $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
     var $this   = $(this)
     var href    = $this.attr('href')
-    var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
-    var option  = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
-
-    e.preventDefault()
-
-    $target
-      .modal(option, this)
-      .one('hide', function () {
-        $this.is(':visible') && $this.focus()
+    var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
+    var option  = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
+
+    if ($this.is('a')) e.preventDefault()
+
+    $target.one('show.bs.modal', function (showEvent) {
+      if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
+      $target.one('hidden.bs.modal', function () {
+        $this.is(':visible') && $this.trigger('focus')
       })
+    })
+    Plugin.call($target, option, this)
   })
 
-  $(document)
-    .on('show.bs.modal',  '.modal', function () { $(document.body).addClass('modal-open') })
-    .on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open') })
-
-}(window.jQuery);
+}(jQuery);
 
 /* ========================================================================
- * Bootstrap: tooltip.js v3.0.0
- * http://twbs.github.com/bootstrap/javascript.html#tooltip
+ * Bootstrap: tooltip.js v3.3.7
+ * http://getbootstrap.com/javascript/#tooltip
  * Inspired by the original jQuery.tipsy by Jason Frame
  * ========================================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Copyright 2011-2016 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  * ======================================================================== */
 
 
-+function ($) { "use strict";
++function ($) {
+  'use strict';
 
   // TOOLTIP PUBLIC CLASS DEFINITION
   // ===============================
 
   var Tooltip = function (element, options) {
-    this.type       =
-    this.options    =
-    this.enabled    =
-    this.timeout    =
-    this.hoverState =
+    this.type       = null
+    this.options    = null
+    this.enabled    = null
+    this.timeout    = null
+    this.hoverState = null
     this.$element   = null
+    this.inState    = null
 
     this.init('tooltip', element, options)
   }
 
+  Tooltip.VERSION  = '3.3.7'
+
+  Tooltip.TRANSITION_DURATION = 150
+
   Tooltip.DEFAULTS = {
-    animation: true
-  , placement: 'top'
-  , selector: false
-  , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
-  , trigger: 'hover focus'
-  , title: ''
-  , delay: 0
-  , html: false
-  , container: false
+    animation: true,
+    placement: 'top',
+    selector: false,
+    template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
+    trigger: 'hover focus',
+    title: '',
+    delay: 0,
+    html: false,
+    container: false,
+    viewport: {
+      selector: 'body',
+      padding: 0
+    }
   }
 
   Tooltip.prototype.init = function (type, element, options) {
-    this.enabled  = true
-    this.type     = type
-    this.$element = $(element)
-    this.options  = this.getOptions(options)
+    this.enabled   = true
+    this.type      = type
+    this.$element  = $(element)
+    this.options   = this.getOptions(options)
+    this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport))
+    this.inState   = { click: false, hover: false, focus: false }
+
+    if (this.$element[0] instanceof document.constructor && !this.options.selector) {
+      throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!')
+    }
 
     var triggers = this.options.trigger.split(' ')
 
@@ -1134,8 +1322,8 @@
       if (trigger == 'click') {
         this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
       } else if (trigger != 'manual') {
-        var eventIn  = trigger == 'hover' ? 'mouseenter' : 'focus'
-        var eventOut = trigger == 'hover' ? 'mouseleave' : 'blur'
+        var eventIn  = trigger == 'hover' ? 'mouseenter' : 'focusin'
+        var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
 
         this.$element.on(eventIn  + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
         this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
@@ -1156,8 +1344,8 @@
 
     if (options.delay && typeof options.delay == 'number') {
       options.delay = {
-        show: options.delay
-      , hide: options.delay
+        show: options.delay,
+        hide: options.delay
       }
     }
 
@@ -1177,7 +1365,21 @@
 
   Tooltip.prototype.enter = function (obj) {
     var self = obj instanceof this.constructor ?
-      obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
+      obj : $(obj.currentTarget).data('bs.' + this.type)
+
+    if (!self) {
+      self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
+      $(obj.currentTarget).data('bs.' + this.type, self)
+    }
+
+    if (obj instanceof $.Event) {
+      self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
+    }
+
+    if (self.tip().hasClass('in') || self.hoverState == 'in') {
+      self.hoverState = 'in'
+      return
+    }
 
     clearTimeout(self.timeout)
 
@@ -1190,9 +1392,28 @@
     }, self.options.delay.show)
   }
 
+  Tooltip.prototype.isInStateTrue = function () {
+    for (var key in this.inState) {
+      if (this.inState[key]) return true
+    }
+
+    return false
+  }
+
   Tooltip.prototype.leave = function (obj) {
     var self = obj instanceof this.constructor ?
-      obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
+      obj : $(obj.currentTarget).data('bs.' + this.type)
+
+    if (!self) {
+      self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
+      $(obj.currentTarget).data('bs.' + this.type, self)
+    }
+
+    if (obj instanceof $.Event) {
+      self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false
+    }
+
+    if (self.isInStateTrue()) return
 
     clearTimeout(self.timeout)
 
@@ -1206,16 +1427,22 @@
   }
 
   Tooltip.prototype.show = function () {
-    var e = $.Event('show.bs.'+ this.type)
+    var e = $.Event('show.bs.' + this.type)
 
     if (this.hasContent() && this.enabled) {
       this.$element.trigger(e)
 
-      if (e.isDefaultPrevented()) return
+      var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
+      if (e.isDefaultPrevented() || !inDom) return
+      var that = this
 
       var $tip = this.tip()
 
+      var tipId = this.getUID(this.type)
+
       this.setContent()
+      $tip.attr('id', tipId)
+      this.$element.attr('aria-describedby', tipId)
 
       if (this.options.animation) $tip.addClass('fade')
 
@@ -1231,26 +1458,23 @@
         .detach()
         .css({ top: 0, left: 0, display: 'block' })
         .addClass(placement)
+        .data('bs.' + this.type, this)
 
       this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
+      this.$element.trigger('inserted.bs.' + this.type)
 
       var pos          = this.getPosition()
       var actualWidth  = $tip[0].offsetWidth
       var actualHeight = $tip[0].offsetHeight
 
       if (autoPlace) {
-        var $parent = this.$element.parent()
-
         var orgPlacement = placement
-        var docScroll    = document.documentElement.scrollTop || document.body.scrollTop
-        var parentWidth  = this.options.container == 'body' ? window.innerWidth  : $parent.outerWidth()
-        var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight()
-        var parentLeft   = this.options.container == 'body' ? 0 : $parent.offset().left
-
-        placement = placement == 'bottom' && pos.top   + pos.height  + actualHeight - docScroll > parentHeight  ? 'top'    :
-                    placement == 'top'    && pos.top   - docScroll   - actualHeight < 0                         ? 'bottom' :
-                    placement == 'right'  && pos.right + actualWidth > parentWidth                              ? 'left'   :
-                    placement == 'left'   && pos.left  - actualWidth < parentLeft                               ? 'right'  :
+        var viewportDim = this.getPosition(this.$viewport)
+
+        placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top'    :
+                    placement == 'top'    && pos.top    - actualHeight < viewportDim.top    ? 'bottom' :
+                    placement == 'right'  && pos.right  + actualWidth  > viewportDim.width  ? 'left'   :
+                    placement == 'left'   && pos.left   - actualWidth  < viewportDim.left   ? 'right'  :
                     placement
 
         $tip
@@ -1261,12 +1485,24 @@
       var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
 
       this.applyPlacement(calculatedOffset, placement)
-      this.$element.trigger('shown.bs.' + this.type)
+
+      var complete = function () {
+        var prevHoverState = that.hoverState
+        that.$element.trigger('shown.bs.' + that.type)
+        that.hoverState = null
+
+        if (prevHoverState == 'out') that.leave(that)
+      }
+
+      $.support.transition && this.$tip.hasClass('fade') ?
+        $tip
+          .one('bsTransitionEnd', complete)
+          .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
+        complete()
     }
   }
 
-  Tooltip.prototype.applyPlacement = function(offset, placement) {
-    var replace
+  Tooltip.prototype.applyPlacement = function (offset, placement) {
     var $tip   = this.tip()
     var width  = $tip[0].offsetWidth
     var height = $tip[0].offsetHeight
@@ -1279,45 +1515,47 @@
     if (isNaN(marginTop))  marginTop  = 0
     if (isNaN(marginLeft)) marginLeft = 0
 
-    offset.top  = offset.top  + marginTop
-    offset.left = offset.left + marginLeft
-
-    $tip
-      .offset(offset)
-      .addClass('in')
+    offset.top  += marginTop
+    offset.left += marginLeft
+
+    // $.fn.offset doesn't round pixel values
+    // so we use setOffset directly with our own function B-0
+    $.offset.setOffset($tip[0], $.extend({
+      using: function (props) {
+        $tip.css({
+          top: Math.round(props.top),
+          left: Math.round(props.left)
+        })
+      }
+    }, offset), 0)
+
+    $tip.addClass('in')
 
     // check to see if placing tip in new offset caused the tip to resize itself
     var actualWidth  = $tip[0].offsetWidth
     var actualHeight = $tip[0].offsetHeight
 
     if (placement == 'top' && actualHeight != height) {
-      replace = true
       offset.top = offset.top + height - actualHeight
     }
 
-    if (/bottom|top/.test(placement)) {
-      var delta = 0
-
-      if (offset.left < 0) {
-        delta       = offset.left * -2
-        offset.left = 0
-
-        $tip.offset(offset)
-
-        actualWidth  = $tip[0].offsetWidth
-        actualHeight = $tip[0].offsetHeight
-      }
-
-      this.replaceArrow(delta - width + actualWidth, actualWidth, 'left')
-    } else {
-      this.replaceArrow(actualHeight - height, actualHeight, 'top')
-    }
-
-    if (replace) $tip.offset(offset)
+    var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
+
+    if (delta.left) offset.left += delta.left
+    else offset.top += delta.top
+
+    var isVertical          = /top|bottom/.test(placement)
+    var arrowDelta          = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
+    var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'
+
+    $tip.offset(offset)
+    this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
   }
 
-  Tooltip.prototype.replaceArrow = function(delta, dimension, position) {
-    this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + "%") : '')
+  Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) {
+    this.arrow()
+      .css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
+      .css(isVertical ? 'top' : 'left', '')
   }
 
   Tooltip.prototype.setContent = function () {
@@ -1328,13 +1566,19 @@
     $tip.removeClass('fade in top bottom left right')
   }
 
-  Tooltip.prototype.hide = function () {
+  Tooltip.prototype.hide = function (callback) {
     var that = this
-    var $tip = this.tip()
+    var $tip = $(this.$tip)
     var e    = $.Event('hide.bs.' + this.type)
 
     function complete() {
       if (that.hoverState != 'in') $tip.detach()
+      if (that.$element) { // TODO: Check whether guarding this code with this `if` is really necessary.
+        that.$element
+          .removeAttr('aria-describedby')
+          .trigger('hidden.bs.' + that.type)
+      }
+      callback && callback()
     }
 
     this.$element.trigger(e)
@@ -1343,20 +1587,20 @@
 
     $tip.removeClass('in')
 
-    $.support.transition && this.$tip.hasClass('fade') ?
+    $.support.transition && $tip.hasClass('fade') ?
       $tip
-        .one($.support.transition.end, complete)
-        .emulateTransitionEnd(150) :
+        .one('bsTransitionEnd', complete)
+        .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
       complete()
 
-    this.$element.trigger('hidden.bs.' + this.type)
+    this.hoverState = null
 
     return this
   }
 
   Tooltip.prototype.fixTitle = function () {
     var $e = this.$element
-    if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
+    if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') {
       $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
     }
   }
@@ -1365,19 +1609,61 @@
     return this.getTitle()
   }
 
-  Tooltip.prototype.getPosition = function () {
-    var el = this.$element[0]
-    return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
-      width: el.offsetWidth
-    , height: el.offsetHeight
-    }, this.$element.offset())
+  Tooltip.prototype.getPosition = function ($element) {
+    $element   = $element || this.$element
+
+    var el     = $element[0]
+    var isBody = el.tagName == 'BODY'
+
+    var elRect    = el.getBoundingClientRect()
+    if (elRect.width == null) {
+      // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
+      elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
+    }
+    var isSvg = window.SVGElement && el instanceof window.SVGElement
+    // Avoid using $.offset() on SVGs since it gives incorrect results in jQuery 3.
+    // See https://github.com/twbs/bootstrap/issues/20280
+    var elOffset  = isBody ? { top: 0, left: 0 } : (isSvg ? null : $element.offset())
+    var scroll    = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
+    var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null
+
+    return $.extend({}, elRect, scroll, outerDims, elOffset)
   }
 
   Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
-    return placement == 'bottom' ? { top: pos.top + pos.height,   left: pos.left + pos.width / 2 - actualWidth / 2  } :
-           placement == 'top'    ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2  } :
+    return placement == 'bottom' ? { top: pos.top + pos.height,   left: pos.left + pos.width / 2 - actualWidth / 2 } :
+           placement == 'top'    ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
            placement == 'left'   ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
-        /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width   }
+        /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
+
+  }
+
+  Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
+    var delta = { top: 0, left: 0 }
+    if (!this.$viewport) return delta
+
+    var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
+    var viewportDimensions = this.getPosition(this.$viewport)
+
+    if (/right|left/.test(placement)) {
+      var topEdgeOffset    = pos.top - viewportPadding - viewportDimensions.scroll
+      var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
+      if (topEdgeOffset < viewportDimensions.top) { // top overflow
+        delta.top = viewportDimensions.top - topEdgeOffset
+      } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
+        delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
+      }
+    } else {
+      var leftEdgeOffset  = pos.left - viewportPadding
+      var rightEdgeOffset = pos.left + viewportPadding + actualWidth
+      if (leftEdgeOffset < viewportDimensions.left) { // left overflow
+        delta.left = viewportDimensions.left - leftEdgeOffset
+      } else if (rightEdgeOffset > viewportDimensions.right) { // right overflow
+        delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
+      }
+    }
+
+    return delta
   }
 
   Tooltip.prototype.getTitle = function () {
@@ -1391,20 +1677,24 @@
     return title
   }
 
+  Tooltip.prototype.getUID = function (prefix) {
+    do prefix += ~~(Math.random() * 1000000)
+    while (document.getElementById(prefix))
+    return prefix
+  }
+
   Tooltip.prototype.tip = function () {
-    return this.$tip = this.$tip || $(this.options.template)
+    if (!this.$tip) {
+      this.$tip = $(this.options.template)
+      if (this.$tip.length != 1) {
+        throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!')
+      }
+    }
+    return this.$tip
   }
 
   Tooltip.prototype.arrow = function () {
-    return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')
-  }
-
-  Tooltip.prototype.validate = function () {
-    if (!this.$element[0].parentNode) {
-      this.hide()
-      this.$element = null
-      this.options  = null
-    }
+    return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
   }
 
   Tooltip.prototype.enable = function () {
@@ -1420,31 +1710,58 @@
   }
 
   Tooltip.prototype.toggle = function (e) {
-    var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this
-    self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
+    var self = this
+    if (e) {
+      self = $(e.currentTarget).data('bs.' + this.type)
+      if (!self) {
+        self = new this.constructor(e.currentTarget, this.getDelegateOptions())
+        $(e.currentTarget).data('bs.' + this.type, self)
+      }
+    }
+
+    if (e) {
+      self.inState.click = !self.inState.click
+      if (self.isInStateTrue()) self.enter(self)
+      else self.leave(self)
+    } else {
+      self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
+    }
   }
 
   Tooltip.prototype.destroy = function () {
-    this.hide().$element.off('.' + this.type).removeData('bs.' + this.type)
+    var that = this
+    clearTimeout(this.timeout)
+    this.hide(function () {
+      that.$element.off('.' + that.type).removeData('bs.' + that.type)
+      if (that.$tip) {
+        that.$tip.detach()
+      }
+      that.$tip = null
+      that.$arrow = null
+      that.$viewport = null
+      that.$element = null
+    })
   }
 
 
   // TOOLTIP PLUGIN DEFINITION
   // =========================
 
-  var old = $.fn.tooltip
-
-  $.fn.tooltip = function (option) {
+  function Plugin(option) {
     return this.each(function () {
       var $this   = $(this)
       var data    = $this.data('bs.tooltip')
       var options = typeof option == 'object' && option
 
+      if (!data && /destroy|hide/.test(option)) return
       if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
       if (typeof option == 'string') data[option]()
     })
   }
 
+  var old = $.fn.tooltip
+
+  $.fn.tooltip             = Plugin
   $.fn.tooltip.Constructor = Tooltip
 
 
@@ -1456,29 +1773,19 @@
     return this
   }
 
-}(window.jQuery);
+}(jQuery);
 
 /* ========================================================================
- * Bootstrap: popover.js v3.0.0
- * http://twbs.github.com/bootstrap/javascript.html#popovers
+ * Bootstrap: popover.js v3.3.7
+ * http://getbootstrap.com/javascript/#popovers
  * ========================================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Copyright 2011-2016 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  * ======================================================================== */
 
 
-+function ($) { "use strict";
++function ($) {
+  'use strict';
 
   // POPOVER PUBLIC CLASS DEFINITION
   // ===============================
@@ -1489,11 +1796,13 @@
 
   if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
 
-  Popover.DEFAULTS = $.extend({} , $.fn.tooltip.Constructor.DEFAULTS, {
-    placement: 'right'
-  , trigger: 'click'
-  , content: ''
-  , template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
+  Popover.VERSION  = '3.3.7'
+
+  Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
+    placement: 'right',
+    trigger: 'click',
+    content: '',
+    template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
   })
 
 
@@ -1514,7 +1823,9 @@
     var content = this.getContent()
 
     $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
-    $tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content)
+    $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
+      this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
+    ](content)
 
     $tip.removeClass('fade top bottom left right in')
 
@@ -1538,31 +1849,28 @@
   }
 
   Popover.prototype.arrow = function () {
-    return this.$arrow = this.$arrow || this.tip().find('.arrow')
-  }
-
-  Popover.prototype.tip = function () {
-    if (!this.$tip) this.$tip = $(this.options.template)
-    return this.$tip
+    return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
   }
 
 
   // POPOVER PLUGIN DEFINITION
   // =========================
 
-  var old = $.fn.popover
-
-  $.fn.popover = function (option) {
+  function Plugin(option) {
     return this.each(function () {
       var $this   = $(this)
       var data    = $this.data('bs.popover')
       var options = typeof option == 'object' && option
 
+      if (!data && /destroy|hide/.test(option)) return
       if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
       if (typeof option == 'string') data[option]()
     })
   }
 
+  var old = $.fn.popover
+
+  $.fn.popover             = Plugin
   $.fn.popover.Constructor = Popover
 
 
@@ -1574,133 +1882,144 @@
     return this
   }
 
-}(window.jQuery);
+}(jQuery);
 
 /* ========================================================================
- * Bootstrap: scrollspy.js v3.0.0
- * http://twbs.github.com/bootstrap/javascript.html#scrollspy
+ * Bootstrap: scrollspy.js v3.3.7
+ * http://getbootstrap.com/javascript/#scrollspy
  * ========================================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Copyright 2011-2016 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  * ======================================================================== */
 
 
-+function ($) { "use strict";
++function ($) {
+  'use strict';
 
   // SCROLLSPY CLASS DEFINITION
   // ==========================
 
   function ScrollSpy(element, options) {
-    var href
-    var process  = $.proxy(this.process, this)
-
-    this.$element       = $(element).is('body') ? $(window) : $(element)
-    this.$body          = $('body')
-    this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process)
+    this.$body          = $(document.body)
+    this.$scrollElement = $(element).is(document.body) ? $(window) : $(element)
     this.options        = $.extend({}, ScrollSpy.DEFAULTS, options)
-    this.selector       = (this.options.target
-      || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
-      || '') + ' .nav li > a'
-    this.offsets        = $([])
-    this.targets        = $([])
+    this.selector       = (this.options.target || '') + ' .nav li > a'
+    this.offsets        = []
+    this.targets        = []
     this.activeTarget   = null
-
+    this.scrollHeight   = 0
+
+    this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this))
     this.refresh()
     this.process()
   }
 
+  ScrollSpy.VERSION  = '3.3.7'
+
   ScrollSpy.DEFAULTS = {
     offset: 10
   }
 
+  ScrollSpy.prototype.getScrollHeight = function () {
+    return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
+  }
+
   ScrollSpy.prototype.refresh = function () {
-    var offsetMethod = this.$element[0] == window ? 'offset' : 'position'
-
-    this.offsets = $([])
-    this.targets = $([])
-
-    var self     = this
-    var $targets = this.$body
+    var that          = this
+    var offsetMethod  = 'offset'
+    var offsetBase    = 0
+
+    this.offsets      = []
+    this.targets      = []
+    this.scrollHeight = this.getScrollHeight()
+
+    if (!$.isWindow(this.$scrollElement[0])) {
+      offsetMethod = 'position'
+      offsetBase   = this.$scrollElement.scrollTop()
+    }
+
+    this.$body
       .find(this.selector)
       .map(function () {
         var $el   = $(this)
         var href  = $el.data('target') || $el.attr('href')
-        var $href = /^#\w/.test(href) && $(href)
+        var $href = /^#./.test(href) && $(href)
 
         return ($href
           && $href.length
-          && [[ $href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]]) || null
+          && $href.is(':visible')
+          && [[$href[offsetMethod]().top + offsetBase, href]]) || null
       })
       .sort(function (a, b) { return a[0] - b[0] })
       .each(function () {
-        self.offsets.push(this[0])
-        self.targets.push(this[1])
+        that.offsets.push(this[0])
+        that.targets.push(this[1])
       })
   }
 
   ScrollSpy.prototype.process = function () {
     var scrollTop    = this.$scrollElement.scrollTop() + this.options.offset
-    var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight
-    var maxScroll    = scrollHeight - this.$scrollElement.height()
+    var scrollHeight = this.getScrollHeight()
+    var maxScroll    = this.options.offset + scrollHeight - this.$scrollElement.height()
     var offsets      = this.offsets
     var targets      = this.targets
     var activeTarget = this.activeTarget
     var i
 
+    if (this.scrollHeight != scrollHeight) {
+      this.refresh()
+    }
+
     if (scrollTop >= maxScroll) {
-      return activeTarget != (i = targets.last()[0]) && this.activate(i)
+      return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
+    }
+
+    if (activeTarget && scrollTop < offsets[0]) {
+      this.activeTarget = null
+      return this.clear()
     }
 
     for (i = offsets.length; i--;) {
       activeTarget != targets[i]
         && scrollTop >= offsets[i]
-        && (!offsets[i + 1] || scrollTop <= offsets[i + 1])
-        && this.activate( targets[i] )
+        && (offsets[i + 1] === undefined || scrollTop < offsets[i + 1])
+        && this.activate(targets[i])
     }
   }
 
   ScrollSpy.prototype.activate = function (target) {
     this.activeTarget = target
 
-    $(this.selector)
-      .parents('.active')
-      .removeClass('active')
-
-    var selector = this.selector
-      + '[data-target="' + target + '"],'
-      + this.selector + '[href="' + target + '"]'
+    this.clear()
+
+    var selector = this.selector +
+      '[data-target="' + target + '"],' +
+      this.selector + '[href="' + target + '"]'
 
     var active = $(selector)
       .parents('li')
       .addClass('active')
 
-    if (active.parent('.dropdown-menu').length)  {
+    if (active.parent('.dropdown-menu').length) {
       active = active
         .closest('li.dropdown')
         .addClass('active')
     }
 
-    active.trigger('activate')
+    active.trigger('activate.bs.scrollspy')
+  }
+
+  ScrollSpy.prototype.clear = function () {
+    $(this.selector)
+      .parentsUntil(this.options.target, '.active')
+      .removeClass('active')
   }
 
 
   // SCROLLSPY PLUGIN DEFINITION
   // ===========================
 
-  var old = $.fn.scrollspy
-
-  $.fn.scrollspy = function (option) {
+  function Plugin(option) {
     return this.each(function () {
       var $this   = $(this)
       var data    = $this.data('bs.scrollspy')
@@ -1711,6 +2030,9 @@
     })
   }
 
+  var old = $.fn.scrollspy
+
+  $.fn.scrollspy             = Plugin
   $.fn.scrollspy.Constructor = ScrollSpy
 
 
@@ -1726,72 +2048,76 @@
   // SCROLLSPY DATA-API
   // ==================
 
-  $(window).on('load', function () {
+  $(window).on('load.bs.scrollspy.data-api', function () {
     $('[data-spy="scroll"]').each(function () {
       var $spy = $(this)
-      $spy.scrollspy($spy.data())
+      Plugin.call($spy, $spy.data())
     })
   })
 
-}(window.jQuery);
+}(jQuery);
 
 /* ========================================================================
- * Bootstrap: tab.js v3.0.0
- * http://twbs.github.com/bootstrap/javascript.html#tabs
+ * Bootstrap: tab.js v3.3.7
+ * http://getbootstrap.com/javascript/#tabs
  * ========================================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Copyright 2011-2016 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  * ======================================================================== */
 
 
-+function ($) { "use strict";
++function ($) {
+  'use strict';
 
   // TAB CLASS DEFINITION
   // ====================
 
   var Tab = function (element) {
+    // jscs:disable requireDollarBeforejQueryAssignment
     this.element = $(element)
+    // jscs:enable requireDollarBeforejQueryAssignment
   }
 
+  Tab.VERSION = '3.3.7'
+
+  Tab.TRANSITION_DURATION = 150
+
   Tab.prototype.show = function () {
     var $this    = this.element
     var $ul      = $this.closest('ul:not(.dropdown-menu)')
-    var selector = $this.attr('data-target')
+    var selector = $this.data('target')
 
     if (!selector) {
       selector = $this.attr('href')
-      selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
+      selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
     }
 
     if ($this.parent('li').hasClass('active')) return
 
-    var previous = $ul.find('.active:last a')[0]
-    var e        = $.Event('show.bs.tab', {
-      relatedTarget: previous
+    var $previous = $ul.find('.active:last a')
+    var hideEvent = $.Event('hide.bs.tab', {
+      relatedTarget: $this[0]
     })
-
-    $this.trigger(e)
-
-    if (e.isDefaultPrevented()) return
+    var showEvent = $.Event('show.bs.tab', {
+      relatedTarget: $previous[0]
+    })
+
+    $previous.trigger(hideEvent)
+    $this.trigger(showEvent)
+
+    if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
 
     var $target = $(selector)
 
-    this.activate($this.parent('li'), $ul)
+    this.activate($this.closest('li'), $ul)
     this.activate($target, $target.parent(), function () {
+      $previous.trigger({
+        type: 'hidden.bs.tab',
+        relatedTarget: $this[0]
+      })
       $this.trigger({
-        type: 'shown.bs.tab'
-      , relatedTarget: previous
+        type: 'shown.bs.tab',
+        relatedTarget: $previous[0]
       })
     })
   }
@@ -1800,15 +2126,21 @@
     var $active    = container.find('> .active')
     var transition = callback
       && $.support.transition
-      && $active.hasClass('fade')
+      && ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length)
 
     function next() {
       $active
         .removeClass('active')
         .find('> .dropdown-menu > .active')
-        .removeClass('active')
-
-      element.addClass('active')
+          .removeClass('active')
+        .end()
+        .find('[data-toggle="tab"]')
+          .attr('aria-expanded', false)
+
+      element
+        .addClass('active')
+        .find('[data-toggle="tab"]')
+          .attr('aria-expanded', true)
 
       if (transition) {
         element[0].offsetWidth // reflow for transition
@@ -1817,17 +2149,22 @@
         element.removeClass('fade')
       }
 
-      if (element.parent('.dropdown-menu')) {
-        element.closest('li.dropdown').addClass('active')
+      if (element.parent('.dropdown-menu').length) {
+        element
+          .closest('li.dropdown')
+            .addClass('active')
+          .end()
+          .find('[data-toggle="tab"]')
+            .attr('aria-expanded', true)
       }
 
       callback && callback()
     }
 
-    transition ?
+    $active.length && transition ?
       $active
-        .one($.support.transition.end, next)
-        .emulateTransitionEnd(150) :
+        .one('bsTransitionEnd', next)
+        .emulateTransitionEnd(Tab.TRANSITION_DURATION) :
       next()
 
     $active.removeClass('in')
@@ -1837,9 +2174,7 @@
   // TAB PLUGIN DEFINITION
   // =====================
 
-  var old = $.fn.tab
-
-  $.fn.tab = function ( option ) {
+  function Plugin(option) {
     return this.each(function () {
       var $this = $(this)
       var data  = $this.data('bs.tab')
@@ -1849,6 +2184,9 @@
     })
   }
 
+  var old = $.fn.tab
+
+  $.fn.tab             = Plugin
   $.fn.tab.Constructor = Tab
 
 
@@ -1864,55 +2202,84 @@
   // TAB DATA-API
   // ============
 
-  $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
+  var clickHandler = function (e) {
     e.preventDefault()
-    $(this).tab('show')
-  })
-
-}(window.jQuery);
+    Plugin.call($(this), 'show')
+  }
+
+  $(document)
+    .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
+    .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
+
+}(jQuery);
 
 /* ========================================================================
- * Bootstrap: affix.js v3.0.0
- * http://twbs.github.com/bootstrap/javascript.html#affix
+ * Bootstrap: affix.js v3.3.7
+ * http://getbootstrap.com/javascript/#affix
  * ========================================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Copyright 2011-2016 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  * ======================================================================== */
 
 
-+function ($) { "use strict";
++function ($) {
+  'use strict';
 
   // AFFIX CLASS DEFINITION
   // ======================
 
   var Affix = function (element, options) {
     this.options = $.extend({}, Affix.DEFAULTS, options)
-    this.$window = $(window)
+
+    this.$target = $(this.options.target)
       .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
       .on('click.bs.affix.data-api',  $.proxy(this.checkPositionWithEventLoop, this))
 
-    this.$element = $(element)
-    this.affixed  =
-    this.unpin    = null
+    this.$element     = $(element)
+    this.affixed      = null
+    this.unpin        = null
+    this.pinnedOffset = null
 
     this.checkPosition()
   }
 
-  Affix.RESET = 'affix affix-top affix-bottom'
+  Affix.VERSION  = '3.3.7'
+
+  Affix.RESET    = 'affix affix-top affix-bottom'
 
   Affix.DEFAULTS = {
-    offset: 0
+    offset: 0,
+    target: window
+  }
+
+  Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
+    var scrollTop    = this.$target.scrollTop()
+    var position     = this.$element.offset()
+    var targetHeight = this.$target.height()
+
+    if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
+
+    if (this.affixed == 'bottom') {
+      if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
+      return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
+    }
+
+    var initializing   = this.affixed == null
+    var colliderTop    = initializing ? scrollTop : position.top
+    var colliderHeight = initializing ? targetHeight : height
+
+    if (offsetTop != null && scrollTop <= offsetTop) return 'top'
+    if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
+
+    return false
+  }
+
+  Affix.prototype.getPinnedOffset = function () {
+    if (this.pinnedOffset) return this.pinnedOffset
+    this.$element.removeClass(Affix.RESET).addClass('affix')
+    var scrollTop = this.$target.scrollTop()
+    var position  = this.$element.offset()
+    return (this.pinnedOffset = position.top - scrollTop)
   }
 
   Affix.prototype.checkPositionWithEventLoop = function () {
@@ -1922,31 +2289,41 @@
   Affix.prototype.checkPosition = function () {
     if (!this.$element.is(':visible')) return
 
-    var scrollHeight = $(document).height()
-    var scrollTop    = this.$window.scrollTop()
-    var position     = this.$element.offset()
+    var height       = this.$element.height()
     var offset       = this.options.offset
     var offsetTop    = offset.top
     var offsetBottom = offset.bottom
+    var scrollHeight = Math.max($(document).height(), $(document.body).height())
 
     if (typeof offset != 'object')         offsetBottom = offsetTop = offset
-    if (typeof offsetTop == 'function')    offsetTop    = offset.top()
-    if (typeof offsetBottom == 'function') offsetBottom = offset.bottom()
-
-    var affix = this.unpin   != null && (scrollTop + this.unpin <= position.top) ? false :
-                offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' :
-                offsetTop    != null && (scrollTop <= offsetTop) ? 'top' : false
-
-    if (this.affixed === affix) return
-    if (this.unpin) this.$element.css('top', '')
-
-    this.affixed = affix
-    this.unpin   = affix == 'bottom' ? position.top - scrollTop : null
-
-    this.$element.removeClass(Affix.RESET).addClass('affix' + (affix ? '-' + affix : ''))
+    if (typeof offsetTop == 'function')    offsetTop    = offset.top(this.$element)
+    if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
+
+    var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
+
+    if (this.affixed != affix) {
+      if (this.unpin != null) this.$element.css('top', '')
+
+      var affixType = 'affix' + (affix ? '-' + affix : '')
+      var e         = $.Event(affixType + '.bs.affix')
+
+      this.$element.trigger(e)
+
+      if (e.isDefaultPrevented()) return
+
+      this.affixed = affix
+      this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
+
+      this.$element
+        .removeClass(Affix.RESET)
+        .addClass(affixType)
+        .trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
+    }
 
     if (affix == 'bottom') {
-      this.$element.offset({ top: document.body.offsetHeight - offsetBottom - this.$element.height() })
+      this.$element.offset({
+        top: scrollHeight - height - offsetBottom
+      })
     }
   }
 
@@ -1954,9 +2331,7 @@
   // AFFIX PLUGIN DEFINITION
   // =======================
 
-  var old = $.fn.affix
-
-  $.fn.affix = function (option) {
+  function Plugin(option) {
     return this.each(function () {
       var $this   = $(this)
       var data    = $this.data('bs.affix')
@@ -1967,6 +2342,9 @@
     })
   }
 
+  var old = $.fn.affix
+
+  $.fn.affix             = Plugin
   $.fn.affix.Constructor = Affix
 
 
@@ -1989,11 +2367,11 @@
 
       data.offset = data.offset || {}
 
-      if (data.offsetBottom) data.offset.bottom = data.offsetBottom
-      if (data.offsetTop)    data.offset.top    = data.offsetTop
-
-      $spy.affix(data)
+      if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
+      if (data.offsetTop    != null) data.offset.top    = data.offsetTop
+
+      Plugin.call($spy, data)
     })
   })
 
-}(window.jQuery);
+}(jQuery);
--- a/kallithea/public/js/graph.js	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/public/js/graph.js	Fri Nov 18 01:11:13 2016 +0100
@@ -28,11 +28,11 @@
 	// row_id_prefix is prefix that is applied to get row id's
 	this.canvas = document.getElementById(canvas_id);
 	var content = document.getElementById(content_id);
-	
+
 	if (!document.createElement("canvas").getContext)
 		this.canvas = window.G_vmlCanvasManager.initElement(this.canvas);
 	if (!this.canvas) { // canvas creation did for some reason fail - fail silently
-		this.render = function(data,canvasWidth) {};
+		this.render = function(data) {};
 		return;
 	}
 	this.ctx = this.canvas.getContext('2d');
@@ -62,8 +62,9 @@
 		this.ctx.fillStyle = s;
 	}
 
-	this.render = function(data,canvasWidth) {
+	this.render = function(data) {
 		var idx = 1;
+		var canvasWidth = $(this.canvas).parent().width();
 
 		this.canvas.setAttribute('width',canvasWidth);
 		this.canvas.setAttribute('height',content.clientHeight);
@@ -100,12 +101,16 @@
 			}
 			var next = document.getElementById(row_id_prefix+(idx+1));
 			var extra = 0;
-			
+
 			cur = data[i];
 			node = cur[0];
 			in_l = cur[1];
 			closing = cur[2];
 			obsolete_node = cur[3];
+			bumped_node = cur[4];
+			divergent_node = cur[5];
+			extinct_node = cur[6];
+			unstable_node = cur[7];
 
 			var rowY = row.offsetTop + row.offsetHeight/2;
 			var nextY = (next == null) ? rowY + row.offsetHeight/2 : next.offsetTop + next.offsetHeight/2;
@@ -116,7 +121,7 @@
 				end = line[1];
 				color = line[2];
 				obsolete_line = line[3];
-				
+
 				x = Math.floor(base_x - box_size * start);
 
 				// figure out if this is a dead-end;
@@ -157,7 +162,7 @@
 				{
 					this.setColor(color, 0.0, 0.65);
 				}
-				
+
 				this.ctx.lineWidth=this.line_width;
 				this.ctx.beginPath();
 				if (obsolete_line)
@@ -183,14 +188,17 @@
 				this.ctx.stroke();
 				this.ctx.setLineDash([]); // reset the dashed line, if any
 			}
-			
+
 			column = node[0];
 			color = node[1];
-			
+
 			x = Math.floor(base_x - box_size * column);
-		
+
 			this.setColor(color, 0.25, 0.75);
-
+			if(unstable_node)
+			{
+				this.ctx.fillStyle = 'rgb(255, 0, 0)';
+			}
 
 			r = this.dot_radius
 			if (obsolete_node)
@@ -216,7 +224,7 @@
 
 			idx++;
 		}
-				
+
 	}
 
 }
--- a/kallithea/public/js/jquery-1.11.1.min.js	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,4 +0,0 @@
-/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
-!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;
-if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")
-},cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m});
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/public/js/jquery.dataTables.min.js	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,166 @@
+/*!
+ DataTables 1.10.11
+ ©2008-2015 SpryMedia Ltd - datatables.net/license
+*/
+(function(h){"function"===typeof define&&define.amd?define(["jquery"],function(D){return h(D,window,document)}):"object"===typeof exports?module.exports=function(D,I){D||(D=window);I||(I="undefined"!==typeof window?require("jquery"):require("jquery")(D));return h(I,D,D.document)}:h(jQuery,window,document)})(function(h,D,I,k){function Y(a){var b,c,d={};h.each(a,function(e){if((b=e.match(/^([^A-Z]+?)([A-Z])/))&&-1!=="a aa ai ao as b fn i m o s ".indexOf(b[1]+" "))c=e.replace(b[0],b[2].toLowerCase()),
+d[c]=e,"o"===b[1]&&Y(a[e])});a._hungarianMap=d}function K(a,b,c){a._hungarianMap||Y(a);var d;h.each(b,function(e){d=a._hungarianMap[e];if(d!==k&&(c||b[d]===k))"o"===d.charAt(0)?(b[d]||(b[d]={}),h.extend(!0,b[d],b[e]),K(a[d],b[d],c)):b[d]=b[e]})}function Fa(a){var b=m.defaults.oLanguage,c=a.sZeroRecords;!a.sEmptyTable&&(c&&"No data available in table"===b.sEmptyTable)&&E(a,a,"sZeroRecords","sEmptyTable");!a.sLoadingRecords&&(c&&"Loading..."===b.sLoadingRecords)&&E(a,a,"sZeroRecords","sLoadingRecords");
+a.sInfoThousands&&(a.sThousands=a.sInfoThousands);(a=a.sDecimal)&&db(a)}function eb(a){A(a,"ordering","bSort");A(a,"orderMulti","bSortMulti");A(a,"orderClasses","bSortClasses");A(a,"orderCellsTop","bSortCellsTop");A(a,"order","aaSorting");A(a,"orderFixed","aaSortingFixed");A(a,"paging","bPaginate");A(a,"pagingType","sPaginationType");A(a,"pageLength","iDisplayLength");A(a,"searching","bFilter");"boolean"===typeof a.sScrollX&&(a.sScrollX=a.sScrollX?"100%":"");"boolean"===typeof a.scrollX&&(a.scrollX=
+a.scrollX?"100%":"");if(a=a.aoSearchCols)for(var b=0,c=a.length;b<c;b++)a[b]&&K(m.models.oSearch,a[b])}function fb(a){A(a,"orderable","bSortable");A(a,"orderData","aDataSort");A(a,"orderSequence","asSorting");A(a,"orderDataType","sortDataType");var b=a.aDataSort;b&&!h.isArray(b)&&(a.aDataSort=[b])}function gb(a){if(!m.__browser){var b={};m.__browser=b;var c=h("<div/>").css({position:"fixed",top:0,left:0,height:1,width:1,overflow:"hidden"}).append(h("<div/>").css({position:"absolute",top:1,left:1,
+width:100,overflow:"scroll"}).append(h("<div/>").css({width:"100%",height:10}))).appendTo("body"),d=c.children(),e=d.children();b.barWidth=d[0].offsetWidth-d[0].clientWidth;b.bScrollOversize=100===e[0].offsetWidth&&100!==d[0].clientWidth;b.bScrollbarLeft=1!==Math.round(e.offset().left);b.bBounding=c[0].getBoundingClientRect().width?!0:!1;c.remove()}h.extend(a.oBrowser,m.__browser);a.oScroll.iBarWidth=m.__browser.barWidth}function hb(a,b,c,d,e,f){var g,j=!1;c!==k&&(g=c,j=!0);for(;d!==e;)a.hasOwnProperty(d)&&
+(g=j?b(g,a[d],d,a):a[d],j=!0,d+=f);return g}function Ga(a,b){var c=m.defaults.column,d=a.aoColumns.length,c=h.extend({},m.models.oColumn,c,{nTh:b?b:I.createElement("th"),sTitle:c.sTitle?c.sTitle:b?b.innerHTML:"",aDataSort:c.aDataSort?c.aDataSort:[d],mData:c.mData?c.mData:d,idx:d});a.aoColumns.push(c);c=a.aoPreSearchCols;c[d]=h.extend({},m.models.oSearch,c[d]);ja(a,d,h(b).data())}function ja(a,b,c){var b=a.aoColumns[b],d=a.oClasses,e=h(b.nTh);if(!b.sWidthOrig){b.sWidthOrig=e.attr("width")||null;var f=
+(e.attr("style")||"").match(/width:\s*(\d+[pxem%]+)/);f&&(b.sWidthOrig=f[1])}c!==k&&null!==c&&(fb(c),K(m.defaults.column,c),c.mDataProp!==k&&!c.mData&&(c.mData=c.mDataProp),c.sType&&(b._sManualType=c.sType),c.className&&!c.sClass&&(c.sClass=c.className),h.extend(b,c),E(b,c,"sWidth","sWidthOrig"),c.iDataSort!==k&&(b.aDataSort=[c.iDataSort]),E(b,c,"aDataSort"));var g=b.mData,j=Q(g),i=b.mRender?Q(b.mRender):null,c=function(a){return"string"===typeof a&&-1!==a.indexOf("@")};b._bAttrSrc=h.isPlainObject(g)&&
+(c(g.sort)||c(g.type)||c(g.filter));b._setter=null;b.fnGetData=function(a,b,c){var d=j(a,b,k,c);return i&&b?i(d,b,a,c):d};b.fnSetData=function(a,b,c){return R(g)(a,b,c)};"number"!==typeof g&&(a._rowReadObject=!0);a.oFeatures.bSort||(b.bSortable=!1,e.addClass(d.sSortableNone));a=-1!==h.inArray("asc",b.asSorting);c=-1!==h.inArray("desc",b.asSorting);!b.bSortable||!a&&!c?(b.sSortingClass=d.sSortableNone,b.sSortingClassJUI=""):a&&!c?(b.sSortingClass=d.sSortableAsc,b.sSortingClassJUI=d.sSortJUIAscAllowed):
+!a&&c?(b.sSortingClass=d.sSortableDesc,b.sSortingClassJUI=d.sSortJUIDescAllowed):(b.sSortingClass=d.sSortable,b.sSortingClassJUI=d.sSortJUI)}function U(a){if(!1!==a.oFeatures.bAutoWidth){var b=a.aoColumns;Ha(a);for(var c=0,d=b.length;c<d;c++)b[c].nTh.style.width=b[c].sWidth}b=a.oScroll;(""!==b.sY||""!==b.sX)&&ka(a);u(a,null,"column-sizing",[a])}function Z(a,b){var c=la(a,"bVisible");return"number"===typeof c[b]?c[b]:null}function $(a,b){var c=la(a,"bVisible"),c=h.inArray(b,c);return-1!==c?c:null}
+function aa(a){return h(F(a.aoColumns,"nTh")).filter(":visible").length}function la(a,b){var c=[];h.map(a.aoColumns,function(a,e){a[b]&&c.push(e)});return c}function Ia(a){var b=a.aoColumns,c=a.aoData,d=m.ext.type.detect,e,f,g,j,i,h,l,q,t;e=0;for(f=b.length;e<f;e++)if(l=b[e],t=[],!l.sType&&l._sManualType)l.sType=l._sManualType;else if(!l.sType){g=0;for(j=d.length;g<j;g++){i=0;for(h=c.length;i<h;i++){t[i]===k&&(t[i]=B(a,i,e,"type"));q=d[g](t[i],a);if(!q&&g!==d.length-1)break;if("html"===q)break}if(q){l.sType=
+q;break}}l.sType||(l.sType="string")}}function ib(a,b,c,d){var e,f,g,j,i,n,l=a.aoColumns;if(b)for(e=b.length-1;0<=e;e--){n=b[e];var q=n.targets!==k?n.targets:n.aTargets;h.isArray(q)||(q=[q]);f=0;for(g=q.length;f<g;f++)if("number"===typeof q[f]&&0<=q[f]){for(;l.length<=q[f];)Ga(a);d(q[f],n)}else if("number"===typeof q[f]&&0>q[f])d(l.length+q[f],n);else if("string"===typeof q[f]){j=0;for(i=l.length;j<i;j++)("_all"==q[f]||h(l[j].nTh).hasClass(q[f]))&&d(j,n)}}if(c){e=0;for(a=c.length;e<a;e++)d(e,c[e])}}
+function N(a,b,c,d){var e=a.aoData.length,f=h.extend(!0,{},m.models.oRow,{src:c?"dom":"data",idx:e});f._aData=b;a.aoData.push(f);for(var g=a.aoColumns,j=0,i=g.length;j<i;j++)g[j].sType=null;a.aiDisplayMaster.push(e);b=a.rowIdFn(b);b!==k&&(a.aIds[b]=f);(c||!a.oFeatures.bDeferRender)&&Ja(a,e,c,d);return e}function ma(a,b){var c;b instanceof h||(b=h(b));return b.map(function(b,e){c=Ka(a,e);return N(a,c.data,e,c.cells)})}function B(a,b,c,d){var e=a.iDraw,f=a.aoColumns[c],g=a.aoData[b]._aData,j=f.sDefaultContent,
+i=f.fnGetData(g,d,{settings:a,row:b,col:c});if(i===k)return a.iDrawError!=e&&null===j&&(L(a,0,"Requested unknown parameter "+("function"==typeof f.mData?"{function}":"'"+f.mData+"'")+" for row "+b+", column "+c,4),a.iDrawError=e),j;if((i===g||null===i)&&null!==j&&d!==k)i=j;else if("function"===typeof i)return i.call(g);return null===i&&"display"==d?"":i}function jb(a,b,c,d){a.aoColumns[c].fnSetData(a.aoData[b]._aData,d,{settings:a,row:b,col:c})}function La(a){return h.map(a.match(/(\\.|[^\.])+/g)||
+[""],function(a){return a.replace(/\\./g,".")})}function Q(a){if(h.isPlainObject(a)){var b={};h.each(a,function(a,c){c&&(b[a]=Q(c))});return function(a,c,f,g){var j=b[c]||b._;return j!==k?j(a,c,f,g):a}}if(null===a)return function(a){return a};if("function"===typeof a)return function(b,c,f,g){return a(b,c,f,g)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("[")||-1!==a.indexOf("("))){var c=function(a,b,f){var g,j;if(""!==f){j=La(f);for(var i=0,n=j.length;i<n;i++){f=j[i].match(ba);g=
+j[i].match(V);if(f){j[i]=j[i].replace(ba,"");""!==j[i]&&(a=a[j[i]]);g=[];j.splice(0,i+1);j=j.join(".");if(h.isArray(a)){i=0;for(n=a.length;i<n;i++)g.push(c(a[i],b,j))}a=f[0].substring(1,f[0].length-1);a=""===a?g:g.join(a);break}else if(g){j[i]=j[i].replace(V,"");a=a[j[i]]();continue}if(null===a||a[j[i]]===k)return k;a=a[j[i]]}}return a};return function(b,e){return c(b,e,a)}}return function(b){return b[a]}}function R(a){if(h.isPlainObject(a))return R(a._);if(null===a)return function(){};if("function"===
+typeof a)return function(b,d,e){a(b,"set",d,e)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("[")||-1!==a.indexOf("("))){var b=function(a,d,e){var e=La(e),f;f=e[e.length-1];for(var g,j,i=0,n=e.length-1;i<n;i++){g=e[i].match(ba);j=e[i].match(V);if(g){e[i]=e[i].replace(ba,"");a[e[i]]=[];f=e.slice();f.splice(0,i+1);g=f.join(".");if(h.isArray(d)){j=0;for(n=d.length;j<n;j++)f={},b(f,d[j],g),a[e[i]].push(f)}else a[e[i]]=d;return}j&&(e[i]=e[i].replace(V,""),a=a[e[i]](d));if(null===a[e[i]]||
+a[e[i]]===k)a[e[i]]={};a=a[e[i]]}if(f.match(V))a[f.replace(V,"")](d);else a[f.replace(ba,"")]=d};return function(c,d){return b(c,d,a)}}return function(b,d){b[a]=d}}function Ma(a){return F(a.aoData,"_aData")}function na(a){a.aoData.length=0;a.aiDisplayMaster.length=0;a.aiDisplay.length=0;a.aIds={}}function oa(a,b,c){for(var d=-1,e=0,f=a.length;e<f;e++)a[e]==b?d=e:a[e]>b&&a[e]--; -1!=d&&c===k&&a.splice(d,1)}function ca(a,b,c,d){var e=a.aoData[b],f,g=function(c,d){for(;c.childNodes.length;)c.removeChild(c.firstChild);
+c.innerHTML=B(a,b,d,"display")};if("dom"===c||(!c||"auto"===c)&&"dom"===e.src)e._aData=Ka(a,e,d,d===k?k:e._aData).data;else{var j=e.anCells;if(j)if(d!==k)g(j[d],d);else{c=0;for(f=j.length;c<f;c++)g(j[c],c)}}e._aSortData=null;e._aFilterData=null;g=a.aoColumns;if(d!==k)g[d].sType=null;else{c=0;for(f=g.length;c<f;c++)g[c].sType=null;Na(a,e)}}function Ka(a,b,c,d){var e=[],f=b.firstChild,g,j,i=0,n,l=a.aoColumns,q=a._rowReadObject,d=d!==k?d:q?{}:[],t=function(a,b){if("string"===typeof a){var c=a.indexOf("@");
+-1!==c&&(c=a.substring(c+1),R(a)(d,b.getAttribute(c)))}},S=function(a){if(c===k||c===i)j=l[i],n=h.trim(a.innerHTML),j&&j._bAttrSrc?(R(j.mData._)(d,n),t(j.mData.sort,a),t(j.mData.type,a),t(j.mData.filter,a)):q?(j._setter||(j._setter=R(j.mData)),j._setter(d,n)):d[i]=n;i++};if(f)for(;f;){g=f.nodeName.toUpperCase();if("TD"==g||"TH"==g)S(f),e.push(f);f=f.nextSibling}else{e=b.anCells;f=0;for(g=e.length;f<g;f++)S(e[f])}if(b=b.firstChild?b:b.nTr)(b=b.getAttribute("id"))&&R(a.rowId)(d,b);return{data:d,cells:e}}
+function Ja(a,b,c,d){var e=a.aoData[b],f=e._aData,g=[],j,i,n,l,q;if(null===e.nTr){j=c||I.createElement("tr");e.nTr=j;e.anCells=g;j._DT_RowIndex=b;Na(a,e);l=0;for(q=a.aoColumns.length;l<q;l++){n=a.aoColumns[l];i=c?d[l]:I.createElement(n.sCellType);i._DT_CellIndex={row:b,column:l};g.push(i);if((!c||n.mRender||n.mData!==l)&&(!h.isPlainObject(n.mData)||n.mData._!==l+".display"))i.innerHTML=B(a,b,l,"display");n.sClass&&(i.className+=" "+n.sClass);n.bVisible&&!c?j.appendChild(i):!n.bVisible&&c&&i.parentNode.removeChild(i);
+n.fnCreatedCell&&n.fnCreatedCell.call(a.oInstance,i,B(a,b,l),f,b,l)}u(a,"aoRowCreatedCallback",null,[j,f,b])}e.nTr.setAttribute("role","row")}function Na(a,b){var c=b.nTr,d=b._aData;if(c){var e=a.rowIdFn(d);e&&(c.id=e);d.DT_RowClass&&(e=d.DT_RowClass.split(" "),b.__rowc=b.__rowc?pa(b.__rowc.concat(e)):e,h(c).removeClass(b.__rowc.join(" ")).addClass(d.DT_RowClass));d.DT_RowAttr&&h(c).attr(d.DT_RowAttr);d.DT_RowData&&h(c).data(d.DT_RowData)}}function kb(a){var b,c,d,e,f,g=a.nTHead,j=a.nTFoot,i=0===
+h("th, td",g).length,n=a.oClasses,l=a.aoColumns;i&&(e=h("<tr/>").appendTo(g));b=0;for(c=l.length;b<c;b++)f=l[b],d=h(f.nTh).addClass(f.sClass),i&&d.appendTo(e),a.oFeatures.bSort&&(d.addClass(f.sSortingClass),!1!==f.bSortable&&(d.attr("tabindex",a.iTabIndex).attr("aria-controls",a.sTableId),Oa(a,f.nTh,b))),f.sTitle!=d[0].innerHTML&&d.html(f.sTitle),Pa(a,"header")(a,d,f,n);i&&da(a.aoHeader,g);h(g).find(">tr").attr("role","row");h(g).find(">tr>th, >tr>td").addClass(n.sHeaderTH);h(j).find(">tr>th, >tr>td").addClass(n.sFooterTH);
+if(null!==j){a=a.aoFooter[0];b=0;for(c=a.length;b<c;b++)f=l[b],f.nTf=a[b].cell,f.sClass&&h(f.nTf).addClass(f.sClass)}}function ea(a,b,c){var d,e,f,g=[],j=[],i=a.aoColumns.length,n;if(b){c===k&&(c=!1);d=0;for(e=b.length;d<e;d++){g[d]=b[d].slice();g[d].nTr=b[d].nTr;for(f=i-1;0<=f;f--)!a.aoColumns[f].bVisible&&!c&&g[d].splice(f,1);j.push([])}d=0;for(e=g.length;d<e;d++){if(a=g[d].nTr)for(;f=a.firstChild;)a.removeChild(f);f=0;for(b=g[d].length;f<b;f++)if(n=i=1,j[d][f]===k){a.appendChild(g[d][f].cell);
+for(j[d][f]=1;g[d+i]!==k&&g[d][f].cell==g[d+i][f].cell;)j[d+i][f]=1,i++;for(;g[d][f+n]!==k&&g[d][f].cell==g[d][f+n].cell;){for(c=0;c<i;c++)j[d+c][f+n]=1;n++}h(g[d][f].cell).attr("rowspan",i).attr("colspan",n)}}}}function O(a){var b=u(a,"aoPreDrawCallback","preDraw",[a]);if(-1!==h.inArray(!1,b))C(a,!1);else{var b=[],c=0,d=a.asStripeClasses,e=d.length,f=a.oLanguage,g=a.iInitDisplayStart,j="ssp"==y(a),i=a.aiDisplay;a.bDrawing=!0;g!==k&&-1!==g&&(a._iDisplayStart=j?g:g>=a.fnRecordsDisplay()?0:g,a.iInitDisplayStart=
+-1);var g=a._iDisplayStart,n=a.fnDisplayEnd();if(a.bDeferLoading)a.bDeferLoading=!1,a.iDraw++,C(a,!1);else if(j){if(!a.bDestroying&&!lb(a))return}else a.iDraw++;if(0!==i.length){f=j?a.aoData.length:n;for(j=j?0:g;j<f;j++){var l=i[j],q=a.aoData[l];null===q.nTr&&Ja(a,l);l=q.nTr;if(0!==e){var t=d[c%e];q._sRowStripe!=t&&(h(l).removeClass(q._sRowStripe).addClass(t),q._sRowStripe=t)}u(a,"aoRowCallback",null,[l,q._aData,c,j]);b.push(l);c++}}else c=f.sZeroRecords,1==a.iDraw&&"ajax"==y(a)?c=f.sLoadingRecords:
+f.sEmptyTable&&0===a.fnRecordsTotal()&&(c=f.sEmptyTable),b[0]=h("<tr/>",{"class":e?d[0]:""}).append(h("<td />",{valign:"top",colSpan:aa(a),"class":a.oClasses.sRowEmpty}).html(c))[0];u(a,"aoHeaderCallback","header",[h(a.nTHead).children("tr")[0],Ma(a),g,n,i]);u(a,"aoFooterCallback","footer",[h(a.nTFoot).children("tr")[0],Ma(a),g,n,i]);d=h(a.nTBody);d.children().detach();d.append(h(b));u(a,"aoDrawCallback","draw",[a]);a.bSorted=!1;a.bFiltered=!1;a.bDrawing=!1}}function T(a,b){var c=a.oFeatures,d=c.bFilter;
+c.bSort&&mb(a);d?fa(a,a.oPreviousSearch):a.aiDisplay=a.aiDisplayMaster.slice();!0!==b&&(a._iDisplayStart=0);a._drawHold=b;O(a);a._drawHold=!1}function nb(a){var b=a.oClasses,c=h(a.nTable),c=h("<div/>").insertBefore(c),d=a.oFeatures,e=h("<div/>",{id:a.sTableId+"_wrapper","class":b.sWrapper+(a.nTFoot?"":" "+b.sNoFooter)});a.nHolding=c[0];a.nTableWrapper=e[0];a.nTableReinsertBefore=a.nTable.nextSibling;for(var f=a.sDom.split(""),g,j,i,n,l,q,t=0;t<f.length;t++){g=null;j=f[t];if("<"==j){i=h("<div/>")[0];
+n=f[t+1];if("'"==n||'"'==n){l="";for(q=2;f[t+q]!=n;)l+=f[t+q],q++;"H"==l?l=b.sJUIHeader:"F"==l&&(l=b.sJUIFooter);-1!=l.indexOf(".")?(n=l.split("."),i.id=n[0].substr(1,n[0].length-1),i.className=n[1]):"#"==l.charAt(0)?i.id=l.substr(1,l.length-1):i.className=l;t+=q}e.append(i);e=h(i)}else if(">"==j)e=e.parent();else if("l"==j&&d.bPaginate&&d.bLengthChange)g=ob(a);else if("f"==j&&d.bFilter)g=pb(a);else if("r"==j&&d.bProcessing)g=qb(a);else if("t"==j)g=rb(a);else if("i"==j&&d.bInfo)g=sb(a);else if("p"==
+j&&d.bPaginate)g=tb(a);else if(0!==m.ext.feature.length){i=m.ext.feature;q=0;for(n=i.length;q<n;q++)if(j==i[q].cFeature){g=i[q].fnInit(a);break}}g&&(i=a.aanFeatures,i[j]||(i[j]=[]),i[j].push(g),e.append(g))}c.replaceWith(e);a.nHolding=null}function da(a,b){var c=h(b).children("tr"),d,e,f,g,j,i,n,l,q,t;a.splice(0,a.length);f=0;for(i=c.length;f<i;f++)a.push([]);f=0;for(i=c.length;f<i;f++){d=c[f];for(e=d.firstChild;e;){if("TD"==e.nodeName.toUpperCase()||"TH"==e.nodeName.toUpperCase()){l=1*e.getAttribute("colspan");
+q=1*e.getAttribute("rowspan");l=!l||0===l||1===l?1:l;q=!q||0===q||1===q?1:q;g=0;for(j=a[f];j[g];)g++;n=g;t=1===l?!0:!1;for(j=0;j<l;j++)for(g=0;g<q;g++)a[f+g][n+j]={cell:e,unique:t},a[f+g].nTr=d}e=e.nextSibling}}}function qa(a,b,c){var d=[];c||(c=a.aoHeader,b&&(c=[],da(c,b)));for(var b=0,e=c.length;b<e;b++)for(var f=0,g=c[b].length;f<g;f++)if(c[b][f].unique&&(!d[f]||!a.bSortCellsTop))d[f]=c[b][f].cell;return d}function ra(a,b,c){u(a,"aoServerParams","serverParams",[b]);if(b&&h.isArray(b)){var d={},
+e=/(.*?)\[\]$/;h.each(b,function(a,b){var c=b.name.match(e);c?(c=c[0],d[c]||(d[c]=[]),d[c].push(b.value)):d[b.name]=b.value});b=d}var f,g=a.ajax,j=a.oInstance,i=function(b){u(a,null,"xhr",[a,b,a.jqXHR]);c(b)};if(h.isPlainObject(g)&&g.data){f=g.data;var n=h.isFunction(f)?f(b,a):f,b=h.isFunction(f)&&n?n:h.extend(!0,b,n);delete g.data}n={data:b,success:function(b){var c=b.error||b.sError;c&&L(a,0,c);a.json=b;i(b)},dataType:"json",cache:!1,type:a.sServerMethod,error:function(b,c){var d=u(a,null,"xhr",
+[a,null,a.jqXHR]);-1===h.inArray(!0,d)&&("parsererror"==c?L(a,0,"Invalid JSON response",1):4===b.readyState&&L(a,0,"Ajax error",7));C(a,!1)}};a.oAjaxData=b;u(a,null,"preXhr",[a,b]);a.fnServerData?a.fnServerData.call(j,a.sAjaxSource,h.map(b,function(a,b){return{name:b,value:a}}),i,a):a.sAjaxSource||"string"===typeof g?a.jqXHR=h.ajax(h.extend(n,{url:g||a.sAjaxSource})):h.isFunction(g)?a.jqXHR=g.call(j,b,i,a):(a.jqXHR=h.ajax(h.extend(n,g)),g.data=f)}function lb(a){return a.bAjaxDataGet?(a.iDraw++,C(a,
+!0),ra(a,ub(a),function(b){vb(a,b)}),!1):!0}function ub(a){var b=a.aoColumns,c=b.length,d=a.oFeatures,e=a.oPreviousSearch,f=a.aoPreSearchCols,g,j=[],i,n,l,q=W(a);g=a._iDisplayStart;i=!1!==d.bPaginate?a._iDisplayLength:-1;var k=function(a,b){j.push({name:a,value:b})};k("sEcho",a.iDraw);k("iColumns",c);k("sColumns",F(b,"sName").join(","));k("iDisplayStart",g);k("iDisplayLength",i);var S={draw:a.iDraw,columns:[],order:[],start:g,length:i,search:{value:e.sSearch,regex:e.bRegex}};for(g=0;g<c;g++)n=b[g],
+l=f[g],i="function"==typeof n.mData?"function":n.mData,S.columns.push({data:i,name:n.sName,searchable:n.bSearchable,orderable:n.bSortable,search:{value:l.sSearch,regex:l.bRegex}}),k("mDataProp_"+g,i),d.bFilter&&(k("sSearch_"+g,l.sSearch),k("bRegex_"+g,l.bRegex),k("bSearchable_"+g,n.bSearchable)),d.bSort&&k("bSortable_"+g,n.bSortable);d.bFilter&&(k("sSearch",e.sSearch),k("bRegex",e.bRegex));d.bSort&&(h.each(q,function(a,b){S.order.push({column:b.col,dir:b.dir});k("iSortCol_"+a,b.col);k("sSortDir_"+
+a,b.dir)}),k("iSortingCols",q.length));b=m.ext.legacy.ajax;return null===b?a.sAjaxSource?j:S:b?j:S}function vb(a,b){var c=sa(a,b),d=b.sEcho!==k?b.sEcho:b.draw,e=b.iTotalRecords!==k?b.iTotalRecords:b.recordsTotal,f=b.iTotalDisplayRecords!==k?b.iTotalDisplayRecords:b.recordsFiltered;if(d){if(1*d<a.iDraw)return;a.iDraw=1*d}na(a);a._iRecordsTotal=parseInt(e,10);a._iRecordsDisplay=parseInt(f,10);d=0;for(e=c.length;d<e;d++)N(a,c[d]);a.aiDisplay=a.aiDisplayMaster.slice();a.bAjaxDataGet=!1;O(a);a._bInitComplete||
+ta(a,b);a.bAjaxDataGet=!0;C(a,!1)}function sa(a,b){var c=h.isPlainObject(a.ajax)&&a.ajax.dataSrc!==k?a.ajax.dataSrc:a.sAjaxDataProp;return"data"===c?b.aaData||b[c]:""!==c?Q(c)(b):b}function pb(a){var b=a.oClasses,c=a.sTableId,d=a.oLanguage,e=a.oPreviousSearch,f=a.aanFeatures,g='<input type="search" class="'+b.sFilterInput+'"/>',j=d.sSearch,j=j.match(/_INPUT_/)?j.replace("_INPUT_",g):j+g,b=h("<div/>",{id:!f.f?c+"_filter":null,"class":b.sFilter}).append(h("<label/>").append(j)),f=function(){var b=!this.value?
+"":this.value;b!=e.sSearch&&(fa(a,{sSearch:b,bRegex:e.bRegex,bSmart:e.bSmart,bCaseInsensitive:e.bCaseInsensitive}),a._iDisplayStart=0,O(a))},g=null!==a.searchDelay?a.searchDelay:"ssp"===y(a)?400:0,i=h("input",b).val(e.sSearch).attr("placeholder",d.sSearchPlaceholder).bind("keyup.DT search.DT input.DT paste.DT cut.DT",g?ua(f,g):f).bind("keypress.DT",function(a){if(13==a.keyCode)return!1}).attr("aria-controls",c);h(a.nTable).on("search.dt.DT",function(b,c){if(a===c)try{i[0]!==I.activeElement&&i.val(e.sSearch)}catch(d){}});
+return b[0]}function fa(a,b,c){var d=a.oPreviousSearch,e=a.aoPreSearchCols,f=function(a){d.sSearch=a.sSearch;d.bRegex=a.bRegex;d.bSmart=a.bSmart;d.bCaseInsensitive=a.bCaseInsensitive};Ia(a);if("ssp"!=y(a)){wb(a,b.sSearch,c,b.bEscapeRegex!==k?!b.bEscapeRegex:b.bRegex,b.bSmart,b.bCaseInsensitive);f(b);for(b=0;b<e.length;b++)xb(a,e[b].sSearch,b,e[b].bEscapeRegex!==k?!e[b].bEscapeRegex:e[b].bRegex,e[b].bSmart,e[b].bCaseInsensitive);yb(a)}else f(b);a.bFiltered=!0;u(a,null,"search",[a])}function yb(a){for(var b=
+m.ext.search,c=a.aiDisplay,d,e,f=0,g=b.length;f<g;f++){for(var j=[],i=0,n=c.length;i<n;i++)e=c[i],d=a.aoData[e],b[f](a,d._aFilterData,e,d._aData,i)&&j.push(e);c.length=0;h.merge(c,j)}}function xb(a,b,c,d,e,f){if(""!==b)for(var g=a.aiDisplay,d=Qa(b,d,e,f),e=g.length-1;0<=e;e--)b=a.aoData[g[e]]._aFilterData[c],d.test(b)||g.splice(e,1)}function wb(a,b,c,d,e,f){var d=Qa(b,d,e,f),e=a.oPreviousSearch.sSearch,f=a.aiDisplayMaster,g;0!==m.ext.search.length&&(c=!0);g=zb(a);if(0>=b.length)a.aiDisplay=f.slice();
+else{if(g||c||e.length>b.length||0!==b.indexOf(e)||a.bSorted)a.aiDisplay=f.slice();b=a.aiDisplay;for(c=b.length-1;0<=c;c--)d.test(a.aoData[b[c]]._sFilterRow)||b.splice(c,1)}}function Qa(a,b,c,d){a=b?a:va(a);c&&(a="^(?=.*?"+h.map(a.match(/"[^"]+"|[^ ]+/g)||[""],function(a){if('"'===a.charAt(0))var b=a.match(/^"(.*)"$/),a=b?b[1]:a;return a.replace('"',"")}).join(")(?=.*?")+").*$");return RegExp(a,d?"i":"")}function va(a){return a.replace(Zb,"\\$1")}function zb(a){var b=a.aoColumns,c,d,e,f,g,j,i,h,l=
+m.ext.type.search;c=!1;d=0;for(f=a.aoData.length;d<f;d++)if(h=a.aoData[d],!h._aFilterData){j=[];e=0;for(g=b.length;e<g;e++)c=b[e],c.bSearchable?(i=B(a,d,e,"filter"),l[c.sType]&&(i=l[c.sType](i)),null===i&&(i=""),"string"!==typeof i&&i.toString&&(i=i.toString())):i="",i.indexOf&&-1!==i.indexOf("&")&&(wa.innerHTML=i,i=$b?wa.textContent:wa.innerText),i.replace&&(i=i.replace(/[\r\n]/g,"")),j.push(i);h._aFilterData=j;h._sFilterRow=j.join("  ");c=!0}return c}function Ab(a){return{search:a.sSearch,smart:a.bSmart,
+regex:a.bRegex,caseInsensitive:a.bCaseInsensitive}}function Bb(a){return{sSearch:a.search,bSmart:a.smart,bRegex:a.regex,bCaseInsensitive:a.caseInsensitive}}function sb(a){var b=a.sTableId,c=a.aanFeatures.i,d=h("<div/>",{"class":a.oClasses.sInfo,id:!c?b+"_info":null});c||(a.aoDrawCallback.push({fn:Cb,sName:"information"}),d.attr("role","status").attr("aria-live","polite"),h(a.nTable).attr("aria-describedby",b+"_info"));return d[0]}function Cb(a){var b=a.aanFeatures.i;if(0!==b.length){var c=a.oLanguage,
+d=a._iDisplayStart+1,e=a.fnDisplayEnd(),f=a.fnRecordsTotal(),g=a.fnRecordsDisplay(),j=g?c.sInfo:c.sInfoEmpty;g!==f&&(j+=" "+c.sInfoFiltered);j+=c.sInfoPostFix;j=Db(a,j);c=c.fnInfoCallback;null!==c&&(j=c.call(a.oInstance,a,d,e,f,g,j));h(b).html(j)}}function Db(a,b){var c=a.fnFormatNumber,d=a._iDisplayStart+1,e=a._iDisplayLength,f=a.fnRecordsDisplay(),g=-1===e;return b.replace(/_START_/g,c.call(a,d)).replace(/_END_/g,c.call(a,a.fnDisplayEnd())).replace(/_MAX_/g,c.call(a,a.fnRecordsTotal())).replace(/_TOTAL_/g,
+c.call(a,f)).replace(/_PAGE_/g,c.call(a,g?1:Math.ceil(d/e))).replace(/_PAGES_/g,c.call(a,g?1:Math.ceil(f/e)))}function ga(a){var b,c,d=a.iInitDisplayStart,e=a.aoColumns,f;c=a.oFeatures;var g=a.bDeferLoading;if(a.bInitialised){nb(a);kb(a);ea(a,a.aoHeader);ea(a,a.aoFooter);C(a,!0);c.bAutoWidth&&Ha(a);b=0;for(c=e.length;b<c;b++)f=e[b],f.sWidth&&(f.nTh.style.width=x(f.sWidth));u(a,null,"preInit",[a]);T(a);e=y(a);if("ssp"!=e||g)"ajax"==e?ra(a,[],function(c){var f=sa(a,c);for(b=0;b<f.length;b++)N(a,f[b]);
+a.iInitDisplayStart=d;T(a);C(a,!1);ta(a,c)},a):(C(a,!1),ta(a))}else setTimeout(function(){ga(a)},200)}function ta(a,b){a._bInitComplete=!0;(b||a.oInit.aaData)&&U(a);u(a,null,"plugin-init",[a,b]);u(a,"aoInitComplete","init",[a,b])}function Ra(a,b){var c=parseInt(b,10);a._iDisplayLength=c;Sa(a);u(a,null,"length",[a,c])}function ob(a){for(var b=a.oClasses,c=a.sTableId,d=a.aLengthMenu,e=h.isArray(d[0]),f=e?d[0]:d,d=e?d[1]:d,e=h("<select/>",{name:c+"_length","aria-controls":c,"class":b.sLengthSelect}),
+g=0,j=f.length;g<j;g++)e[0][g]=new Option(d[g],f[g]);var i=h("<div><label/></div>").addClass(b.sLength);a.aanFeatures.l||(i[0].id=c+"_length");i.children().append(a.oLanguage.sLengthMenu.replace("_MENU_",e[0].outerHTML));h("select",i).val(a._iDisplayLength).bind("change.DT",function(){Ra(a,h(this).val());O(a)});h(a.nTable).bind("length.dt.DT",function(b,c,d){a===c&&h("select",i).val(d)});return i[0]}function tb(a){var b=a.sPaginationType,c=m.ext.pager[b],d="function"===typeof c,e=function(a){O(a)},
+b=h("<div/>").addClass(a.oClasses.sPaging+b)[0],f=a.aanFeatures;d||c.fnInit(a,b,e);f.p||(b.id=a.sTableId+"_paginate",a.aoDrawCallback.push({fn:function(a){if(d){var b=a._iDisplayStart,i=a._iDisplayLength,h=a.fnRecordsDisplay(),l=-1===i,b=l?0:Math.ceil(b/i),i=l?1:Math.ceil(h/i),h=c(b,i),k,l=0;for(k=f.p.length;l<k;l++)Pa(a,"pageButton")(a,f.p[l],l,h,b,i)}else c.fnUpdate(a,e)},sName:"pagination"}));return b}function Ta(a,b,c){var d=a._iDisplayStart,e=a._iDisplayLength,f=a.fnRecordsDisplay();0===f||-1===
+e?d=0:"number"===typeof b?(d=b*e,d>f&&(d=0)):"first"==b?d=0:"previous"==b?(d=0<=e?d-e:0,0>d&&(d=0)):"next"==b?d+e<f&&(d+=e):"last"==b?d=Math.floor((f-1)/e)*e:L(a,0,"Unknown paging action: "+b,5);b=a._iDisplayStart!==d;a._iDisplayStart=d;b&&(u(a,null,"page",[a]),c&&O(a));return b}function qb(a){return h("<div/>",{id:!a.aanFeatures.r?a.sTableId+"_processing":null,"class":a.oClasses.sProcessing}).html(a.oLanguage.sProcessing).insertBefore(a.nTable)[0]}function C(a,b){a.oFeatures.bProcessing&&h(a.aanFeatures.r).css("display",
+b?"block":"none");u(a,null,"processing",[a,b])}function rb(a){var b=h(a.nTable);b.attr("role","grid");var c=a.oScroll;if(""===c.sX&&""===c.sY)return a.nTable;var d=c.sX,e=c.sY,f=a.oClasses,g=b.children("caption"),j=g.length?g[0]._captionSide:null,i=h(b[0].cloneNode(!1)),n=h(b[0].cloneNode(!1)),l=b.children("tfoot");l.length||(l=null);i=h("<div/>",{"class":f.sScrollWrapper}).append(h("<div/>",{"class":f.sScrollHead}).css({overflow:"hidden",position:"relative",border:0,width:d?!d?null:x(d):"100%"}).append(h("<div/>",
+{"class":f.sScrollHeadInner}).css({"box-sizing":"content-box",width:c.sXInner||"100%"}).append(i.removeAttr("id").css("margin-left",0).append("top"===j?g:null).append(b.children("thead"))))).append(h("<div/>",{"class":f.sScrollBody}).css({position:"relative",overflow:"auto",width:!d?null:x(d)}).append(b));l&&i.append(h("<div/>",{"class":f.sScrollFoot}).css({overflow:"hidden",border:0,width:d?!d?null:x(d):"100%"}).append(h("<div/>",{"class":f.sScrollFootInner}).append(n.removeAttr("id").css("margin-left",
+0).append("bottom"===j?g:null).append(b.children("tfoot")))));var b=i.children(),k=b[0],f=b[1],t=l?b[2]:null;if(d)h(f).on("scroll.DT",function(){var a=this.scrollLeft;k.scrollLeft=a;l&&(t.scrollLeft=a)});h(f).css(e&&c.bCollapse?"max-height":"height",e);a.nScrollHead=k;a.nScrollBody=f;a.nScrollFoot=t;a.aoDrawCallback.push({fn:ka,sName:"scrolling"});return i[0]}function ka(a){var b=a.oScroll,c=b.sX,d=b.sXInner,e=b.sY,b=b.iBarWidth,f=h(a.nScrollHead),g=f[0].style,j=f.children("div"),i=j[0].style,n=j.children("table"),
+j=a.nScrollBody,l=h(j),q=j.style,t=h(a.nScrollFoot).children("div"),m=t.children("table"),o=h(a.nTHead),G=h(a.nTable),p=G[0],r=p.style,u=a.nTFoot?h(a.nTFoot):null,Eb=a.oBrowser,Ua=Eb.bScrollOversize,s=F(a.aoColumns,"nTh"),P,v,w,y,z=[],A=[],B=[],C=[],D,E=function(a){a=a.style;a.paddingTop="0";a.paddingBottom="0";a.borderTopWidth="0";a.borderBottomWidth="0";a.height=0};v=j.scrollHeight>j.clientHeight;if(a.scrollBarVis!==v&&a.scrollBarVis!==k)a.scrollBarVis=v,U(a);else{a.scrollBarVis=v;G.children("thead, tfoot").remove();
+u&&(w=u.clone().prependTo(G),P=u.find("tr"),w=w.find("tr"));y=o.clone().prependTo(G);o=o.find("tr");v=y.find("tr");y.find("th, td").removeAttr("tabindex");c||(q.width="100%",f[0].style.width="100%");h.each(qa(a,y),function(b,c){D=Z(a,b);c.style.width=a.aoColumns[D].sWidth});u&&J(function(a){a.style.width=""},w);f=G.outerWidth();if(""===c){r.width="100%";if(Ua&&(G.find("tbody").height()>j.offsetHeight||"scroll"==l.css("overflow-y")))r.width=x(G.outerWidth()-b);f=G.outerWidth()}else""!==d&&(r.width=
+x(d),f=G.outerWidth());J(E,v);J(function(a){B.push(a.innerHTML);z.push(x(h(a).css("width")))},v);J(function(a,b){if(h.inArray(a,s)!==-1)a.style.width=z[b]},o);h(v).height(0);u&&(J(E,w),J(function(a){C.push(a.innerHTML);A.push(x(h(a).css("width")))},w),J(function(a,b){a.style.width=A[b]},P),h(w).height(0));J(function(a,b){a.innerHTML='<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+B[b]+"</div>";a.style.width=z[b]},v);u&&J(function(a,b){a.innerHTML='<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+
+C[b]+"</div>";a.style.width=A[b]},w);if(G.outerWidth()<f){P=j.scrollHeight>j.offsetHeight||"scroll"==l.css("overflow-y")?f+b:f;if(Ua&&(j.scrollHeight>j.offsetHeight||"scroll"==l.css("overflow-y")))r.width=x(P-b);(""===c||""!==d)&&L(a,1,"Possible column misalignment",6)}else P="100%";q.width=x(P);g.width=x(P);u&&(a.nScrollFoot.style.width=x(P));!e&&Ua&&(q.height=x(p.offsetHeight+b));c=G.outerWidth();n[0].style.width=x(c);i.width=x(c);d=G.height()>j.clientHeight||"scroll"==l.css("overflow-y");e="padding"+
+(Eb.bScrollbarLeft?"Left":"Right");i[e]=d?b+"px":"0px";u&&(m[0].style.width=x(c),t[0].style.width=x(c),t[0].style[e]=d?b+"px":"0px");G.children("colgroup").insertBefore(G.children("thead"));l.scroll();if((a.bSorted||a.bFiltered)&&!a._drawHold)j.scrollTop=0}}function J(a,b,c){for(var d=0,e=0,f=b.length,g,j;e<f;){g=b[e].firstChild;for(j=c?c[e].firstChild:null;g;)1===g.nodeType&&(c?a(g,j,d):a(g,d),d++),g=g.nextSibling,j=c?j.nextSibling:null;e++}}function Ha(a){var b=a.nTable,c=a.aoColumns,d=a.oScroll,
+e=d.sY,f=d.sX,g=d.sXInner,j=c.length,i=la(a,"bVisible"),n=h("th",a.nTHead),l=b.getAttribute("width"),k=b.parentNode,t=!1,m,o,p=a.oBrowser,d=p.bScrollOversize;(m=b.style.width)&&-1!==m.indexOf("%")&&(l=m);for(m=0;m<i.length;m++)o=c[i[m]],null!==o.sWidth&&(o.sWidth=Fb(o.sWidthOrig,k),t=!0);if(d||!t&&!f&&!e&&j==aa(a)&&j==n.length)for(m=0;m<j;m++)i=Z(a,m),null!==i&&(c[i].sWidth=x(n.eq(m).width()));else{j=h(b).clone().css("visibility","hidden").removeAttr("id");j.find("tbody tr").remove();var r=h("<tr/>").appendTo(j.find("tbody"));
+j.find("thead, tfoot").remove();j.append(h(a.nTHead).clone()).append(h(a.nTFoot).clone());j.find("tfoot th, tfoot td").css("width","");n=qa(a,j.find("thead")[0]);for(m=0;m<i.length;m++)o=c[i[m]],n[m].style.width=null!==o.sWidthOrig&&""!==o.sWidthOrig?x(o.sWidthOrig):"",o.sWidthOrig&&f&&h(n[m]).append(h("<div/>").css({width:o.sWidthOrig,margin:0,padding:0,border:0,height:1}));if(a.aoData.length)for(m=0;m<i.length;m++)t=i[m],o=c[t],h(Gb(a,t)).clone(!1).append(o.sContentPadding).appendTo(r);h("[name]",
+j).removeAttr("name");o=h("<div/>").css(f||e?{position:"absolute",top:0,left:0,height:1,right:0,overflow:"hidden"}:{}).append(j).appendTo(k);f&&g?j.width(g):f?(j.css("width","auto"),j.removeAttr("width"),j.width()<k.clientWidth&&l&&j.width(k.clientWidth)):e?j.width(k.clientWidth):l&&j.width(l);for(m=e=0;m<i.length;m++)k=h(n[m]),g=k.outerWidth()-k.width(),k=p.bBounding?Math.ceil(n[m].getBoundingClientRect().width):k.outerWidth(),e+=k,c[i[m]].sWidth=x(k-g);b.style.width=x(e);o.remove()}l&&(b.style.width=
+x(l));if((l||f)&&!a._reszEvt)b=function(){h(D).bind("resize.DT-"+a.sInstance,ua(function(){U(a)}))},d?setTimeout(b,1E3):b(),a._reszEvt=!0}function ua(a,b){var c=b!==k?b:200,d,e;return function(){var b=this,g=+new Date,j=arguments;d&&g<d+c?(clearTimeout(e),e=setTimeout(function(){d=k;a.apply(b,j)},c)):(d=g,a.apply(b,j))}}function Fb(a,b){if(!a)return 0;var c=h("<div/>").css("width",x(a)).appendTo(b||I.body),d=c[0].offsetWidth;c.remove();return d}function Gb(a,b){var c=Hb(a,b);if(0>c)return null;var d=
+a.aoData[c];return!d.nTr?h("<td/>").html(B(a,c,b,"display"))[0]:d.anCells[b]}function Hb(a,b){for(var c,d=-1,e=-1,f=0,g=a.aoData.length;f<g;f++)c=B(a,f,b,"display")+"",c=c.replace(ac,""),c=c.replace(/&nbsp;/g," "),c.length>d&&(d=c.length,e=f);return e}function x(a){return null===a?"0px":"number"==typeof a?0>a?"0px":a+"px":a.match(/\d$/)?a+"px":a}function W(a){var b,c,d=[],e=a.aoColumns,f,g,j,i;b=a.aaSortingFixed;c=h.isPlainObject(b);var n=[];f=function(a){a.length&&!h.isArray(a[0])?n.push(a):h.merge(n,
+a)};h.isArray(b)&&f(b);c&&b.pre&&f(b.pre);f(a.aaSorting);c&&b.post&&f(b.post);for(a=0;a<n.length;a++){i=n[a][0];f=e[i].aDataSort;b=0;for(c=f.length;b<c;b++)g=f[b],j=e[g].sType||"string",n[a]._idx===k&&(n[a]._idx=h.inArray(n[a][1],e[g].asSorting)),d.push({src:i,col:g,dir:n[a][1],index:n[a]._idx,type:j,formatter:m.ext.type.order[j+"-pre"]})}return d}function mb(a){var b,c,d=[],e=m.ext.type.order,f=a.aoData,g=0,j,i=a.aiDisplayMaster,h;Ia(a);h=W(a);b=0;for(c=h.length;b<c;b++)j=h[b],j.formatter&&g++,Ib(a,
+j.col);if("ssp"!=y(a)&&0!==h.length){b=0;for(c=i.length;b<c;b++)d[i[b]]=b;g===h.length?i.sort(function(a,b){var c,e,g,j,i=h.length,k=f[a]._aSortData,m=f[b]._aSortData;for(g=0;g<i;g++)if(j=h[g],c=k[j.col],e=m[j.col],c=c<e?-1:c>e?1:0,0!==c)return"asc"===j.dir?c:-c;c=d[a];e=d[b];return c<e?-1:c>e?1:0}):i.sort(function(a,b){var c,g,j,i,k=h.length,m=f[a]._aSortData,p=f[b]._aSortData;for(j=0;j<k;j++)if(i=h[j],c=m[i.col],g=p[i.col],i=e[i.type+"-"+i.dir]||e["string-"+i.dir],c=i(c,g),0!==c)return c;c=d[a];
+g=d[b];return c<g?-1:c>g?1:0})}a.bSorted=!0}function Jb(a){for(var b,c,d=a.aoColumns,e=W(a),a=a.oLanguage.oAria,f=0,g=d.length;f<g;f++){c=d[f];var j=c.asSorting;b=c.sTitle.replace(/<.*?>/g,"");var i=c.nTh;i.removeAttribute("aria-sort");c.bSortable&&(0<e.length&&e[0].col==f?(i.setAttribute("aria-sort","asc"==e[0].dir?"ascending":"descending"),c=j[e[0].index+1]||j[0]):c=j[0],b+="asc"===c?a.sSortAscending:a.sSortDescending);i.setAttribute("aria-label",b)}}function Va(a,b,c,d){var e=a.aaSorting,f=a.aoColumns[b].asSorting,
+g=function(a,b){var c=a._idx;c===k&&(c=h.inArray(a[1],f));return c+1<f.length?c+1:b?null:0};"number"===typeof e[0]&&(e=a.aaSorting=[e]);c&&a.oFeatures.bSortMulti?(c=h.inArray(b,F(e,"0")),-1!==c?(b=g(e[c],!0),null===b&&1===e.length&&(b=0),null===b?e.splice(c,1):(e[c][1]=f[b],e[c]._idx=b)):(e.push([b,f[0],0]),e[e.length-1]._idx=0)):e.length&&e[0][0]==b?(b=g(e[0]),e.length=1,e[0][1]=f[b],e[0]._idx=b):(e.length=0,e.push([b,f[0]]),e[0]._idx=0);T(a);"function"==typeof d&&d(a)}function Oa(a,b,c,d){var e=
+a.aoColumns[c];Wa(b,{},function(b){!1!==e.bSortable&&(a.oFeatures.bProcessing?(C(a,!0),setTimeout(function(){Va(a,c,b.shiftKey,d);"ssp"!==y(a)&&C(a,!1)},0)):Va(a,c,b.shiftKey,d))})}function xa(a){var b=a.aLastSort,c=a.oClasses.sSortColumn,d=W(a),e=a.oFeatures,f,g;if(e.bSort&&e.bSortClasses){e=0;for(f=b.length;e<f;e++)g=b[e].src,h(F(a.aoData,"anCells",g)).removeClass(c+(2>e?e+1:3));e=0;for(f=d.length;e<f;e++)g=d[e].src,h(F(a.aoData,"anCells",g)).addClass(c+(2>e?e+1:3))}a.aLastSort=d}function Ib(a,
+b){var c=a.aoColumns[b],d=m.ext.order[c.sSortDataType],e;d&&(e=d.call(a.oInstance,a,b,$(a,b)));for(var f,g=m.ext.type.order[c.sType+"-pre"],j=0,i=a.aoData.length;j<i;j++)if(c=a.aoData[j],c._aSortData||(c._aSortData=[]),!c._aSortData[b]||d)f=d?e[j]:B(a,j,b,"sort"),c._aSortData[b]=g?g(f):f}function ya(a){if(a.oFeatures.bStateSave&&!a.bDestroying){var b={time:+new Date,start:a._iDisplayStart,length:a._iDisplayLength,order:h.extend(!0,[],a.aaSorting),search:Ab(a.oPreviousSearch),columns:h.map(a.aoColumns,
+function(b,d){return{visible:b.bVisible,search:Ab(a.aoPreSearchCols[d])}})};u(a,"aoStateSaveParams","stateSaveParams",[a,b]);a.oSavedState=b;a.fnStateSaveCallback.call(a.oInstance,a,b)}}function Kb(a){var b,c,d=a.aoColumns;if(a.oFeatures.bStateSave){var e=a.fnStateLoadCallback.call(a.oInstance,a);if(e&&e.time&&(b=u(a,"aoStateLoadParams","stateLoadParams",[a,e]),-1===h.inArray(!1,b)&&(b=a.iStateDuration,!(0<b&&e.time<+new Date-1E3*b)&&d.length===e.columns.length))){a.oLoadedState=h.extend(!0,{},e);
+e.start!==k&&(a._iDisplayStart=e.start,a.iInitDisplayStart=e.start);e.length!==k&&(a._iDisplayLength=e.length);e.order!==k&&(a.aaSorting=[],h.each(e.order,function(b,c){a.aaSorting.push(c[0]>=d.length?[0,c[1]]:c)}));e.search!==k&&h.extend(a.oPreviousSearch,Bb(e.search));b=0;for(c=e.columns.length;b<c;b++){var f=e.columns[b];f.visible!==k&&(d[b].bVisible=f.visible);f.search!==k&&h.extend(a.aoPreSearchCols[b],Bb(f.search))}u(a,"aoStateLoaded","stateLoaded",[a,e])}}}function za(a){var b=m.settings,a=
+h.inArray(a,F(b,"nTable"));return-1!==a?b[a]:null}function L(a,b,c,d){c="DataTables warning: "+(a?"table id="+a.sTableId+" - ":"")+c;d&&(c+=". For more information about this error, please see http://datatables.net/tn/"+d);if(b)D.console&&console.log&&console.log(c);else if(b=m.ext,b=b.sErrMode||b.errMode,a&&u(a,null,"error",[a,d,c]),"alert"==b)alert(c);else{if("throw"==b)throw Error(c);"function"==typeof b&&b(a,d,c)}}function E(a,b,c,d){h.isArray(c)?h.each(c,function(c,d){h.isArray(d)?E(a,b,d[0],
+d[1]):E(a,b,d)}):(d===k&&(d=c),b[c]!==k&&(a[d]=b[c]))}function Lb(a,b,c){var d,e;for(e in b)b.hasOwnProperty(e)&&(d=b[e],h.isPlainObject(d)?(h.isPlainObject(a[e])||(a[e]={}),h.extend(!0,a[e],d)):a[e]=c&&"data"!==e&&"aaData"!==e&&h.isArray(d)?d.slice():d);return a}function Wa(a,b,c){h(a).bind("click.DT",b,function(b){a.blur();c(b)}).bind("keypress.DT",b,function(a){13===a.which&&(a.preventDefault(),c(a))}).bind("selectstart.DT",function(){return!1})}function z(a,b,c,d){c&&a[b].push({fn:c,sName:d})}
+function u(a,b,c,d){var e=[];b&&(e=h.map(a[b].slice().reverse(),function(b){return b.fn.apply(a.oInstance,d)}));null!==c&&(b=h.Event(c+".dt"),h(a.nTable).trigger(b,d),e.push(b.result));return e}function Sa(a){var b=a._iDisplayStart,c=a.fnDisplayEnd(),d=a._iDisplayLength;b>=c&&(b=c-d);b-=b%d;if(-1===d||0>b)b=0;a._iDisplayStart=b}function Pa(a,b){var c=a.renderer,d=m.ext.renderer[b];return h.isPlainObject(c)&&c[b]?d[c[b]]||d._:"string"===typeof c?d[c]||d._:d._}function y(a){return a.oFeatures.bServerSide?
+"ssp":a.ajax||a.sAjaxSource?"ajax":"dom"}function Aa(a,b){var c=[],c=Mb.numbers_length,d=Math.floor(c/2);b<=c?c=X(0,b):a<=d?(c=X(0,c-2),c.push("ellipsis"),c.push(b-1)):(a>=b-1-d?c=X(b-(c-2),b):(c=X(a-d+2,a+d-1),c.push("ellipsis"),c.push(b-1)),c.splice(0,0,"ellipsis"),c.splice(0,0,0));c.DT_el="span";return c}function db(a){h.each({num:function(b){return Ba(b,a)},"num-fmt":function(b){return Ba(b,a,Xa)},"html-num":function(b){return Ba(b,a,Ca)},"html-num-fmt":function(b){return Ba(b,a,Ca,Xa)}},function(b,
+c){v.type.order[b+a+"-pre"]=c;b.match(/^html\-/)&&(v.type.search[b+a]=v.type.search.html)})}function Nb(a){return function(){var b=[za(this[m.ext.iApiIndex])].concat(Array.prototype.slice.call(arguments));return m.ext.internal[a].apply(this,b)}}var m,v,r,p,s,Ya={},Ob=/[\r\n]/g,Ca=/<.*?>/g,bc=/^[\w\+\-]/,cc=/[\w\+\-]$/,Zb=RegExp("(\\/|\\.|\\*|\\+|\\?|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\\\|\\$|\\^|\\-)","g"),Xa=/[',$£€¥%\u2009\u202F\u20BD\u20a9\u20BArfk]/gi,M=function(a){return!a||!0===a||"-"===a?!0:!1},
+Pb=function(a){var b=parseInt(a,10);return!isNaN(b)&&isFinite(a)?b:null},Qb=function(a,b){Ya[b]||(Ya[b]=RegExp(va(b),"g"));return"string"===typeof a&&"."!==b?a.replace(/\./g,"").replace(Ya[b],"."):a},Za=function(a,b,c){var d="string"===typeof a;if(M(a))return!0;b&&d&&(a=Qb(a,b));c&&d&&(a=a.replace(Xa,""));return!isNaN(parseFloat(a))&&isFinite(a)},Rb=function(a,b,c){return M(a)?!0:!(M(a)||"string"===typeof a)?null:Za(a.replace(Ca,""),b,c)?!0:null},F=function(a,b,c){var d=[],e=0,f=a.length;if(c!==k)for(;e<
+f;e++)a[e]&&a[e][b]&&d.push(a[e][b][c]);else for(;e<f;e++)a[e]&&d.push(a[e][b]);return d},ha=function(a,b,c,d){var e=[],f=0,g=b.length;if(d!==k)for(;f<g;f++)a[b[f]][c]&&e.push(a[b[f]][c][d]);else for(;f<g;f++)e.push(a[b[f]][c]);return e},X=function(a,b){var c=[],d;b===k?(b=0,d=a):(d=b,b=a);for(var e=b;e<d;e++)c.push(e);return c},Sb=function(a){for(var b=[],c=0,d=a.length;c<d;c++)a[c]&&b.push(a[c]);return b},pa=function(a){var b=[],c,d,e=a.length,f,g=0;d=0;a:for(;d<e;d++){c=a[d];for(f=0;f<g;f++)if(b[f]===
+c)continue a;b.push(c);g++}return b},A=function(a,b,c){a[b]!==k&&(a[c]=a[b])},ba=/\[.*?\]$/,V=/\(\)$/,wa=h("<div>")[0],$b=wa.textContent!==k,ac=/<.*?>/g;m=function(a){this.$=function(a,b){return this.api(!0).$(a,b)};this._=function(a,b){return this.api(!0).rows(a,b).data()};this.api=function(a){return a?new r(za(this[v.iApiIndex])):new r(this)};this.fnAddData=function(a,b){var c=this.api(!0),d=h.isArray(a)&&(h.isArray(a[0])||h.isPlainObject(a[0]))?c.rows.add(a):c.row.add(a);(b===k||b)&&c.draw();return d.flatten().toArray()};
+this.fnAdjustColumnSizing=function(a){var b=this.api(!0).columns.adjust(),c=b.settings()[0],d=c.oScroll;a===k||a?b.draw(!1):(""!==d.sX||""!==d.sY)&&ka(c)};this.fnClearTable=function(a){var b=this.api(!0).clear();(a===k||a)&&b.draw()};this.fnClose=function(a){this.api(!0).row(a).child.hide()};this.fnDeleteRow=function(a,b,c){var d=this.api(!0),a=d.rows(a),e=a.settings()[0],h=e.aoData[a[0][0]];a.remove();b&&b.call(this,e,h);(c===k||c)&&d.draw();return h};this.fnDestroy=function(a){this.api(!0).destroy(a)};
+this.fnDraw=function(a){this.api(!0).draw(a)};this.fnFilter=function(a,b,c,d,e,h){e=this.api(!0);null===b||b===k?e.search(a,c,d,h):e.column(b).search(a,c,d,h);e.draw()};this.fnGetData=function(a,b){var c=this.api(!0);if(a!==k){var d=a.nodeName?a.nodeName.toLowerCase():"";return b!==k||"td"==d||"th"==d?c.cell(a,b).data():c.row(a).data()||null}return c.data().toArray()};this.fnGetNodes=function(a){var b=this.api(!0);return a!==k?b.row(a).node():b.rows().nodes().flatten().toArray()};this.fnGetPosition=
+function(a){var b=this.api(!0),c=a.nodeName.toUpperCase();return"TR"==c?b.row(a).index():"TD"==c||"TH"==c?(a=b.cell(a).index(),[a.row,a.columnVisible,a.column]):null};this.fnIsOpen=function(a){return this.api(!0).row(a).child.isShown()};this.fnOpen=function(a,b,c){return this.api(!0).row(a).child(b,c).show().child()[0]};this.fnPageChange=function(a,b){var c=this.api(!0).page(a);(b===k||b)&&c.draw(!1)};this.fnSetColumnVis=function(a,b,c){a=this.api(!0).column(a).visible(b);(c===k||c)&&a.columns.adjust().draw()};
+this.fnSettings=function(){return za(this[v.iApiIndex])};this.fnSort=function(a){this.api(!0).order(a).draw()};this.fnSortListener=function(a,b,c){this.api(!0).order.listener(a,b,c)};this.fnUpdate=function(a,b,c,d,e){var h=this.api(!0);c===k||null===c?h.row(b).data(a):h.cell(b,c).data(a);(e===k||e)&&h.columns.adjust();(d===k||d)&&h.draw();return 0};this.fnVersionCheck=v.fnVersionCheck;var b=this,c=a===k,d=this.length;c&&(a={});this.oApi=this.internal=v.internal;for(var e in m.ext.internal)e&&(this[e]=
+Nb(e));this.each(function(){var e={},e=1<d?Lb(e,a,!0):a,g=0,j,i=this.getAttribute("id"),n=!1,l=m.defaults,q=h(this);if("table"!=this.nodeName.toLowerCase())L(null,0,"Non-table node initialisation ("+this.nodeName+")",2);else{eb(l);fb(l.column);K(l,l,!0);K(l.column,l.column,!0);K(l,h.extend(e,q.data()));var t=m.settings,g=0;for(j=t.length;g<j;g++){var p=t[g];if(p.nTable==this||p.nTHead.parentNode==this||p.nTFoot&&p.nTFoot.parentNode==this){g=e.bRetrieve!==k?e.bRetrieve:l.bRetrieve;if(c||g)return p.oInstance;
+if(e.bDestroy!==k?e.bDestroy:l.bDestroy){p.oInstance.fnDestroy();break}else{L(p,0,"Cannot reinitialise DataTable",3);return}}if(p.sTableId==this.id){t.splice(g,1);break}}if(null===i||""===i)this.id=i="DataTables_Table_"+m.ext._unique++;var o=h.extend(!0,{},m.models.oSettings,{sDestroyWidth:q[0].style.width,sInstance:i,sTableId:i});o.nTable=this;o.oApi=b.internal;o.oInit=e;t.push(o);o.oInstance=1===b.length?b:q.dataTable();eb(e);e.oLanguage&&Fa(e.oLanguage);e.aLengthMenu&&!e.iDisplayLength&&(e.iDisplayLength=
+h.isArray(e.aLengthMenu[0])?e.aLengthMenu[0][0]:e.aLengthMenu[0]);e=Lb(h.extend(!0,{},l),e);E(o.oFeatures,e,"bPaginate bLengthChange bFilter bSort bSortMulti bInfo bProcessing bAutoWidth bSortClasses bServerSide bDeferRender".split(" "));E(o,e,["asStripeClasses","ajax","fnServerData","fnFormatNumber","sServerMethod","aaSorting","aaSortingFixed","aLengthMenu","sPaginationType","sAjaxSource","sAjaxDataProp","iStateDuration","sDom","bSortCellsTop","iTabIndex","fnStateLoadCallback","fnStateSaveCallback",
+"renderer","searchDelay","rowId",["iCookieDuration","iStateDuration"],["oSearch","oPreviousSearch"],["aoSearchCols","aoPreSearchCols"],["iDisplayLength","_iDisplayLength"],["bJQueryUI","bJUI"]]);E(o.oScroll,e,[["sScrollX","sX"],["sScrollXInner","sXInner"],["sScrollY","sY"],["bScrollCollapse","bCollapse"]]);E(o.oLanguage,e,"fnInfoCallback");z(o,"aoDrawCallback",e.fnDrawCallback,"user");z(o,"aoServerParams",e.fnServerParams,"user");z(o,"aoStateSaveParams",e.fnStateSaveParams,"user");z(o,"aoStateLoadParams",
+e.fnStateLoadParams,"user");z(o,"aoStateLoaded",e.fnStateLoaded,"user");z(o,"aoRowCallback",e.fnRowCallback,"user");z(o,"aoRowCreatedCallback",e.fnCreatedRow,"user");z(o,"aoHeaderCallback",e.fnHeaderCallback,"user");z(o,"aoFooterCallback",e.fnFooterCallback,"user");z(o,"aoInitComplete",e.fnInitComplete,"user");z(o,"aoPreDrawCallback",e.fnPreDrawCallback,"user");o.rowIdFn=Q(e.rowId);gb(o);i=o.oClasses;e.bJQueryUI?(h.extend(i,m.ext.oJUIClasses,e.oClasses),e.sDom===l.sDom&&"lfrtip"===l.sDom&&(o.sDom=
+'<"H"lfr>t<"F"ip>'),o.renderer)?h.isPlainObject(o.renderer)&&!o.renderer.header&&(o.renderer.header="jqueryui"):o.renderer="jqueryui":h.extend(i,m.ext.classes,e.oClasses);q.addClass(i.sTable);o.iInitDisplayStart===k&&(o.iInitDisplayStart=e.iDisplayStart,o._iDisplayStart=e.iDisplayStart);null!==e.iDeferLoading&&(o.bDeferLoading=!0,g=h.isArray(e.iDeferLoading),o._iRecordsDisplay=g?e.iDeferLoading[0]:e.iDeferLoading,o._iRecordsTotal=g?e.iDeferLoading[1]:e.iDeferLoading);var r=o.oLanguage;h.extend(!0,
+r,e.oLanguage);""!==r.sUrl&&(h.ajax({dataType:"json",url:r.sUrl,success:function(a){Fa(a);K(l.oLanguage,a);h.extend(true,r,a);ga(o)},error:function(){ga(o)}}),n=!0);null===e.asStripeClasses&&(o.asStripeClasses=[i.sStripeOdd,i.sStripeEven]);var g=o.asStripeClasses,v=q.children("tbody").find("tr").eq(0);-1!==h.inArray(!0,h.map(g,function(a){return v.hasClass(a)}))&&(h("tbody tr",this).removeClass(g.join(" ")),o.asDestroyStripes=g.slice());t=[];g=this.getElementsByTagName("thead");0!==g.length&&(da(o.aoHeader,
+g[0]),t=qa(o));if(null===e.aoColumns){p=[];g=0;for(j=t.length;g<j;g++)p.push(null)}else p=e.aoColumns;g=0;for(j=p.length;g<j;g++)Ga(o,t?t[g]:null);ib(o,e.aoColumnDefs,p,function(a,b){ja(o,a,b)});if(v.length){var s=function(a,b){return a.getAttribute("data-"+b)!==null?b:null};h(v[0]).children("th, td").each(function(a,b){var c=o.aoColumns[a];if(c.mData===a){var d=s(b,"sort")||s(b,"order"),e=s(b,"filter")||s(b,"search");if(d!==null||e!==null){c.mData={_:a+".display",sort:d!==null?a+".@data-"+d:k,type:d!==
+null?a+".@data-"+d:k,filter:e!==null?a+".@data-"+e:k};ja(o,a)}}})}var w=o.oFeatures;e.bStateSave&&(w.bStateSave=!0,Kb(o,e),z(o,"aoDrawCallback",ya,"state_save"));if(e.aaSorting===k){t=o.aaSorting;g=0;for(j=t.length;g<j;g++)t[g][1]=o.aoColumns[g].asSorting[0]}xa(o);w.bSort&&z(o,"aoDrawCallback",function(){if(o.bSorted){var a=W(o),b={};h.each(a,function(a,c){b[c.src]=c.dir});u(o,null,"order",[o,a,b]);Jb(o)}});z(o,"aoDrawCallback",function(){(o.bSorted||y(o)==="ssp"||w.bDeferRender)&&xa(o)},"sc");g=
+q.children("caption").each(function(){this._captionSide=q.css("caption-side")});j=q.children("thead");0===j.length&&(j=h("<thead/>").appendTo(this));o.nTHead=j[0];j=q.children("tbody");0===j.length&&(j=h("<tbody/>").appendTo(this));o.nTBody=j[0];j=q.children("tfoot");if(0===j.length&&0<g.length&&(""!==o.oScroll.sX||""!==o.oScroll.sY))j=h("<tfoot/>").appendTo(this);0===j.length||0===j.children().length?q.addClass(i.sNoFooter):0<j.length&&(o.nTFoot=j[0],da(o.aoFooter,o.nTFoot));if(e.aaData)for(g=0;g<
+e.aaData.length;g++)N(o,e.aaData[g]);else(o.bDeferLoading||"dom"==y(o))&&ma(o,h(o.nTBody).children("tr"));o.aiDisplay=o.aiDisplayMaster.slice();o.bInitialised=!0;!1===n&&ga(o)}});b=null;return this};var Tb=[],w=Array.prototype,dc=function(a){var b,c,d=m.settings,e=h.map(d,function(a){return a.nTable});if(a){if(a.nTable&&a.oApi)return[a];if(a.nodeName&&"table"===a.nodeName.toLowerCase())return b=h.inArray(a,e),-1!==b?[d[b]]:null;if(a&&"function"===typeof a.settings)return a.settings().toArray();"string"===
+typeof a?c=h(a):a instanceof h&&(c=a)}else return[];if(c)return c.map(function(){b=h.inArray(this,e);return-1!==b?d[b]:null}).toArray()};r=function(a,b){if(!(this instanceof r))return new r(a,b);var c=[],d=function(a){(a=dc(a))&&(c=c.concat(a))};if(h.isArray(a))for(var e=0,f=a.length;e<f;e++)d(a[e]);else d(a);this.context=pa(c);b&&h.merge(this,b);this.selector={rows:null,cols:null,opts:null};r.extend(this,this,Tb)};m.Api=r;h.extend(r.prototype,{any:function(){return 0!==this.count()},concat:w.concat,
+context:[],count:function(){return this.flatten().length},each:function(a){for(var b=0,c=this.length;b<c;b++)a.call(this,this[b],b,this);return this},eq:function(a){var b=this.context;return b.length>a?new r(b[a],this[a]):null},filter:function(a){var b=[];if(w.filter)b=w.filter.call(this,a,this);else for(var c=0,d=this.length;c<d;c++)a.call(this,this[c],c,this)&&b.push(this[c]);return new r(this.context,b)},flatten:function(){var a=[];return new r(this.context,a.concat.apply(a,this.toArray()))},join:w.join,
+indexOf:w.indexOf||function(a,b){for(var c=b||0,d=this.length;c<d;c++)if(this[c]===a)return c;return-1},iterator:function(a,b,c,d){var e=[],f,g,h,i,n,l=this.context,m,t,p=this.selector;"string"===typeof a&&(d=c,c=b,b=a,a=!1);g=0;for(h=l.length;g<h;g++){var o=new r(l[g]);if("table"===b)f=c.call(o,l[g],g),f!==k&&e.push(f);else if("columns"===b||"rows"===b)f=c.call(o,l[g],this[g],g),f!==k&&e.push(f);else if("column"===b||"column-rows"===b||"row"===b||"cell"===b){t=this[g];"column-rows"===b&&(m=Da(l[g],
+p.opts));i=0;for(n=t.length;i<n;i++)f=t[i],f="cell"===b?c.call(o,l[g],f.row,f.column,g,i):c.call(o,l[g],f,g,i,m),f!==k&&e.push(f)}}return e.length||d?(a=new r(l,a?e.concat.apply([],e):e),b=a.selector,b.rows=p.rows,b.cols=p.cols,b.opts=p.opts,a):this},lastIndexOf:w.lastIndexOf||function(a,b){return this.indexOf.apply(this.toArray.reverse(),arguments)},length:0,map:function(a){var b=[];if(w.map)b=w.map.call(this,a,this);else for(var c=0,d=this.length;c<d;c++)b.push(a.call(this,this[c],c));return new r(this.context,
+b)},pluck:function(a){return this.map(function(b){return b[a]})},pop:w.pop,push:w.push,reduce:w.reduce||function(a,b){return hb(this,a,b,0,this.length,1)},reduceRight:w.reduceRight||function(a,b){return hb(this,a,b,this.length-1,-1,-1)},reverse:w.reverse,selector:null,shift:w.shift,sort:w.sort,splice:w.splice,toArray:function(){return w.slice.call(this)},to$:function(){return h(this)},toJQuery:function(){return h(this)},unique:function(){return new r(this.context,pa(this))},unshift:w.unshift});r.extend=
+function(a,b,c){if(c.length&&b&&(b instanceof r||b.__dt_wrapper)){var d,e,f,g=function(a,b,c){return function(){var d=b.apply(a,arguments);r.extend(d,d,c.methodExt);return d}};d=0;for(e=c.length;d<e;d++)f=c[d],b[f.name]="function"===typeof f.val?g(a,f.val,f):h.isPlainObject(f.val)?{}:f.val,b[f.name].__dt_wrapper=!0,r.extend(a,b[f.name],f.propExt)}};r.register=p=function(a,b){if(h.isArray(a))for(var c=0,d=a.length;c<d;c++)r.register(a[c],b);else for(var e=a.split("."),f=Tb,g,j,c=0,d=e.length;c<d;c++){g=
+(j=-1!==e[c].indexOf("()"))?e[c].replace("()",""):e[c];var i;a:{i=0;for(var n=f.length;i<n;i++)if(f[i].name===g){i=f[i];break a}i=null}i||(i={name:g,val:{},methodExt:[],propExt:[]},f.push(i));c===d-1?i.val=b:f=j?i.methodExt:i.propExt}};r.registerPlural=s=function(a,b,c){r.register(a,c);r.register(b,function(){var a=c.apply(this,arguments);return a===this?this:a instanceof r?a.length?h.isArray(a[0])?new r(a.context,a[0]):a[0]:k:a})};p("tables()",function(a){var b;if(a){b=r;var c=this.context;if("number"===
+typeof a)a=[c[a]];else var d=h.map(c,function(a){return a.nTable}),a=h(d).filter(a).map(function(){var a=h.inArray(this,d);return c[a]}).toArray();b=new b(a)}else b=this;return b});p("table()",function(a){var a=this.tables(a),b=a.context;return b.length?new r(b[0]):a});s("tables().nodes()","table().node()",function(){return this.iterator("table",function(a){return a.nTable},1)});s("tables().body()","table().body()",function(){return this.iterator("table",function(a){return a.nTBody},1)});s("tables().header()",
+"table().header()",function(){return this.iterator("table",function(a){return a.nTHead},1)});s("tables().footer()","table().footer()",function(){return this.iterator("table",function(a){return a.nTFoot},1)});s("tables().containers()","table().container()",function(){return this.iterator("table",function(a){return a.nTableWrapper},1)});p("draw()",function(a){return this.iterator("table",function(b){"page"===a?O(b):("string"===typeof a&&(a="full-hold"===a?!1:!0),T(b,!1===a))})});p("page()",function(a){return a===
+k?this.page.info().page:this.iterator("table",function(b){Ta(b,a)})});p("page.info()",function(){if(0===this.context.length)return k;var a=this.context[0],b=a._iDisplayStart,c=a.oFeatures.bPaginate?a._iDisplayLength:-1,d=a.fnRecordsDisplay(),e=-1===c;return{page:e?0:Math.floor(b/c),pages:e?1:Math.ceil(d/c),start:b,end:a.fnDisplayEnd(),length:c,recordsTotal:a.fnRecordsTotal(),recordsDisplay:d,serverSide:"ssp"===y(a)}});p("page.len()",function(a){return a===k?0!==this.context.length?this.context[0]._iDisplayLength:
+k:this.iterator("table",function(b){Ra(b,a)})});var Ub=function(a,b,c){if(c){var d=new r(a);d.one("draw",function(){c(d.ajax.json())})}if("ssp"==y(a))T(a,b);else{C(a,!0);var e=a.jqXHR;e&&4!==e.readyState&&e.abort();ra(a,[],function(c){na(a);for(var c=sa(a,c),d=0,e=c.length;d<e;d++)N(a,c[d]);T(a,b);C(a,!1)})}};p("ajax.json()",function(){var a=this.context;if(0<a.length)return a[0].json});p("ajax.params()",function(){var a=this.context;if(0<a.length)return a[0].oAjaxData});p("ajax.reload()",function(a,
+b){return this.iterator("table",function(c){Ub(c,!1===b,a)})});p("ajax.url()",function(a){var b=this.context;if(a===k){if(0===b.length)return k;b=b[0];return b.ajax?h.isPlainObject(b.ajax)?b.ajax.url:b.ajax:b.sAjaxSource}return this.iterator("table",function(b){h.isPlainObject(b.ajax)?b.ajax.url=a:b.ajax=a})});p("ajax.url().load()",function(a,b){return this.iterator("table",function(c){Ub(c,!1===b,a)})});var $a=function(a,b,c,d,e){var f=[],g,j,i,n,l,m;i=typeof b;if(!b||"string"===i||"function"===
+i||b.length===k)b=[b];i=0;for(n=b.length;i<n;i++){j=b[i]&&b[i].split?b[i].split(","):[b[i]];l=0;for(m=j.length;l<m;l++)(g=c("string"===typeof j[l]?h.trim(j[l]):j[l]))&&g.length&&(f=f.concat(g))}a=v.selector[a];if(a.length){i=0;for(n=a.length;i<n;i++)f=a[i](d,e,f)}return pa(f)},ab=function(a){a||(a={});a.filter&&a.search===k&&(a.search=a.filter);return h.extend({search:"none",order:"current",page:"all"},a)},bb=function(a){for(var b=0,c=a.length;b<c;b++)if(0<a[b].length)return a[0]=a[b],a[0].length=
+1,a.length=1,a.context=[a.context[b]],a;a.length=0;return a},Da=function(a,b){var c,d,e,f=[],g=a.aiDisplay;c=a.aiDisplayMaster;var j=b.search;d=b.order;e=b.page;if("ssp"==y(a))return"removed"===j?[]:X(0,c.length);if("current"==e){c=a._iDisplayStart;for(d=a.fnDisplayEnd();c<d;c++)f.push(g[c])}else if("current"==d||"applied"==d)f="none"==j?c.slice():"applied"==j?g.slice():h.map(c,function(a){return-1===h.inArray(a,g)?a:null});else if("index"==d||"original"==d){c=0;for(d=a.aoData.length;c<d;c++)"none"==
+j?f.push(c):(e=h.inArray(c,g),(-1===e&&"removed"==j||0<=e&&"applied"==j)&&f.push(c))}return f};p("rows()",function(a,b){a===k?a="":h.isPlainObject(a)&&(b=a,a="");var b=ab(b),c=this.iterator("table",function(c){var e=b;return $a("row",a,function(a){var b=Pb(a);if(b!==null&&!e)return[b];var j=Da(c,e);if(b!==null&&h.inArray(b,j)!==-1)return[b];if(!a)return j;if(typeof a==="function")return h.map(j,function(b){var e=c.aoData[b];return a(b,e._aData,e.nTr)?b:null});b=Sb(ha(c.aoData,j,"nTr"));if(a.nodeName){if(a._DT_RowIndex!==
+k)return[a._DT_RowIndex];if(a._DT_CellIndex)return[a._DT_CellIndex.row];b=h(a).closest("*[data-dt-row]");return b.length?[b.data("dt-row")]:[]}if(typeof a==="string"&&a.charAt(0)==="#"){j=c.aIds[a.replace(/^#/,"")];if(j!==k)return[j.idx]}return h(b).filter(a).map(function(){return this._DT_RowIndex}).toArray()},c,e)},1);c.selector.rows=a;c.selector.opts=b;return c});p("rows().nodes()",function(){return this.iterator("row",function(a,b){return a.aoData[b].nTr||k},1)});p("rows().data()",function(){return this.iterator(!0,
+"rows",function(a,b){return ha(a.aoData,b,"_aData")},1)});s("rows().cache()","row().cache()",function(a){return this.iterator("row",function(b,c){var d=b.aoData[c];return"search"===a?d._aFilterData:d._aSortData},1)});s("rows().invalidate()","row().invalidate()",function(a){return this.iterator("row",function(b,c){ca(b,c,a)})});s("rows().indexes()","row().index()",function(){return this.iterator("row",function(a,b){return b},1)});s("rows().ids()","row().id()",function(a){for(var b=[],c=this.context,
+d=0,e=c.length;d<e;d++)for(var f=0,g=this[d].length;f<g;f++){var h=c[d].rowIdFn(c[d].aoData[this[d][f]]._aData);b.push((!0===a?"#":"")+h)}return new r(c,b)});s("rows().remove()","row().remove()",function(){var a=this;this.iterator("row",function(b,c,d){var e=b.aoData,f=e[c],g,h,i,n,l;e.splice(c,1);g=0;for(h=e.length;g<h;g++)if(i=e[g],l=i.anCells,null!==i.nTr&&(i.nTr._DT_RowIndex=g),null!==l){i=0;for(n=l.length;i<n;i++)l[i]._DT_CellIndex.row=g}oa(b.aiDisplayMaster,c);oa(b.aiDisplay,c);oa(a[d],c,!1);
+Sa(b);c=b.rowIdFn(f._aData);c!==k&&delete b.aIds[c]});this.iterator("table",function(a){for(var c=0,d=a.aoData.length;c<d;c++)a.aoData[c].idx=c});return this});p("rows.add()",function(a){var b=this.iterator("table",function(b){var c,f,g,h=[];f=0;for(g=a.length;f<g;f++)c=a[f],c.nodeName&&"TR"===c.nodeName.toUpperCase()?h.push(ma(b,c)[0]):h.push(N(b,c));return h},1),c=this.rows(-1);c.pop();h.merge(c,b);return c});p("row()",function(a,b){return bb(this.rows(a,b))});p("row().data()",function(a){var b=
+this.context;if(a===k)return b.length&&this.length?b[0].aoData[this[0]]._aData:k;b[0].aoData[this[0]]._aData=a;ca(b[0],this[0],"data");return this});p("row().node()",function(){var a=this.context;return a.length&&this.length?a[0].aoData[this[0]].nTr||null:null});p("row.add()",function(a){a instanceof h&&a.length&&(a=a[0]);var b=this.iterator("table",function(b){return a.nodeName&&"TR"===a.nodeName.toUpperCase()?ma(b,a)[0]:N(b,a)});return this.row(b[0])});var cb=function(a,b){var c=a.context;if(c.length&&
+(c=c[0].aoData[b!==k?b:a[0]])&&c._details)c._details.remove(),c._detailsShow=k,c._details=k},Vb=function(a,b){var c=a.context;if(c.length&&a.length){var d=c[0].aoData[a[0]];if(d._details){(d._detailsShow=b)?d._details.insertAfter(d.nTr):d._details.detach();var e=c[0],f=new r(e),g=e.aoData;f.off("draw.dt.DT_details column-visibility.dt.DT_details destroy.dt.DT_details");0<F(g,"_details").length&&(f.on("draw.dt.DT_details",function(a,b){e===b&&f.rows({page:"current"}).eq(0).each(function(a){a=g[a];
+a._detailsShow&&a._details.insertAfter(a.nTr)})}),f.on("column-visibility.dt.DT_details",function(a,b){if(e===b)for(var c,d=aa(b),f=0,h=g.length;f<h;f++)c=g[f],c._details&&c._details.children("td[colspan]").attr("colspan",d)}),f.on("destroy.dt.DT_details",function(a,b){if(e===b)for(var c=0,d=g.length;c<d;c++)g[c]._details&&cb(f,c)}))}}};p("row().child()",function(a,b){var c=this.context;if(a===k)return c.length&&this.length?c[0].aoData[this[0]]._details:k;if(!0===a)this.child.show();else if(!1===
+a)cb(this);else if(c.length&&this.length){var d=c[0],c=c[0].aoData[this[0]],e=[],f=function(a,b){if(h.isArray(a)||a instanceof h)for(var c=0,k=a.length;c<k;c++)f(a[c],b);else a.nodeName&&"tr"===a.nodeName.toLowerCase()?e.push(a):(c=h("<tr><td/></tr>").addClass(b),h("td",c).addClass(b).html(a)[0].colSpan=aa(d),e.push(c[0]))};f(a,b);c._details&&c._details.remove();c._details=h(e);c._detailsShow&&c._details.insertAfter(c.nTr)}return this});p(["row().child.show()","row().child().show()"],function(){Vb(this,
+!0);return this});p(["row().child.hide()","row().child().hide()"],function(){Vb(this,!1);return this});p(["row().child.remove()","row().child().remove()"],function(){cb(this);return this});p("row().child.isShown()",function(){var a=this.context;return a.length&&this.length?a[0].aoData[this[0]]._detailsShow||!1:!1});var ec=/^(.+):(name|visIdx|visible)$/,Wb=function(a,b,c,d,e){for(var c=[],d=0,f=e.length;d<f;d++)c.push(B(a,e[d],b));return c};p("columns()",function(a,b){a===k?a="":h.isPlainObject(a)&&
+(b=a,a="");var b=ab(b),c=this.iterator("table",function(c){var e=a,f=b,g=c.aoColumns,j=F(g,"sName"),i=F(g,"nTh");return $a("column",e,function(a){var b=Pb(a);if(a==="")return X(g.length);if(b!==null)return[b>=0?b:g.length+b];if(typeof a==="function"){var e=Da(c,f);return h.map(g,function(b,f){return a(f,Wb(c,f,0,0,e),i[f])?f:null})}var k=typeof a==="string"?a.match(ec):"";if(k)switch(k[2]){case "visIdx":case "visible":b=parseInt(k[1],10);if(b<0){var m=h.map(g,function(a,b){return a.bVisible?b:null});
+return[m[m.length+b]]}return[Z(c,b)];case "name":return h.map(j,function(a,b){return a===k[1]?b:null});default:return[]}if(a.nodeName&&a._DT_CellIndex)return[a._DT_CellIndex.column];b=h(i).filter(a).map(function(){return h.inArray(this,i)}).toArray();if(b.length||!a.nodeName)return b;b=h(a).closest("*[data-dt-column]");return b.length?[b.data("dt-column")]:[]},c,f)},1);c.selector.cols=a;c.selector.opts=b;return c});s("columns().header()","column().header()",function(){return this.iterator("column",
+function(a,b){return a.aoColumns[b].nTh},1)});s("columns().footer()","column().footer()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].nTf},1)});s("columns().data()","column().data()",function(){return this.iterator("column-rows",Wb,1)});s("columns().dataSrc()","column().dataSrc()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].mData},1)});s("columns().cache()","column().cache()",function(a){return this.iterator("column-rows",function(b,
+c,d,e,f){return ha(b.aoData,f,"search"===a?"_aFilterData":"_aSortData",c)},1)});s("columns().nodes()","column().nodes()",function(){return this.iterator("column-rows",function(a,b,c,d,e){return ha(a.aoData,e,"anCells",b)},1)});s("columns().visible()","column().visible()",function(a,b){return this.iterator("column",function(c,d){if(a===k)return c.aoColumns[d].bVisible;var e=c.aoColumns,f=e[d],g=c.aoData,j,i,n;if(a!==k&&f.bVisible!==a){if(a){var l=h.inArray(!0,F(e,"bVisible"),d+1);j=0;for(i=g.length;j<
+i;j++)n=g[j].nTr,e=g[j].anCells,n&&n.insertBefore(e[d],e[l]||null)}else h(F(c.aoData,"anCells",d)).detach();f.bVisible=a;ea(c,c.aoHeader);ea(c,c.aoFooter);(b===k||b)&&U(c);u(c,null,"column-visibility",[c,d,a,b]);ya(c)}})});s("columns().indexes()","column().index()",function(a){return this.iterator("column",function(b,c){return"visible"===a?$(b,c):c},1)});p("columns.adjust()",function(){return this.iterator("table",function(a){U(a)},1)});p("column.index()",function(a,b){if(0!==this.context.length){var c=
+this.context[0];if("fromVisible"===a||"toData"===a)return Z(c,b);if("fromData"===a||"toVisible"===a)return $(c,b)}});p("column()",function(a,b){return bb(this.columns(a,b))});p("cells()",function(a,b,c){h.isPlainObject(a)&&(a.row===k?(c=a,a=null):(c=b,b=null));h.isPlainObject(b)&&(c=b,b=null);if(null===b||b===k)return this.iterator("table",function(b){var d=a,e=ab(c),f=b.aoData,g=Da(b,e),j=Sb(ha(f,g,"anCells")),i=h([].concat.apply([],j)),l,n=b.aoColumns.length,m,p,r,u,v,s;return $a("cell",d,function(a){var c=
+typeof a==="function";if(a===null||a===k||c){m=[];p=0;for(r=g.length;p<r;p++){l=g[p];for(u=0;u<n;u++){v={row:l,column:u};if(c){s=f[l];a(v,B(b,l,u),s.anCells?s.anCells[u]:null)&&m.push(v)}else m.push(v)}}return m}if(h.isPlainObject(a))return[a];c=i.filter(a).map(function(a,b){return{row:b._DT_CellIndex.row,column:b._DT_CellIndex.column}}).toArray();if(c.length||!a.nodeName)return c;s=h(a).closest("*[data-dt-row]");return s.length?[{row:s.data("dt-row"),column:s.data("dt-column")}]:[]},b,e)});var d=
+this.columns(b,c),e=this.rows(a,c),f,g,j,i,n,l=this.iterator("table",function(a,b){f=[];g=0;for(j=e[b].length;g<j;g++){i=0;for(n=d[b].length;i<n;i++)f.push({row:e[b][g],column:d[b][i]})}return f},1);h.extend(l.selector,{cols:b,rows:a,opts:c});return l});s("cells().nodes()","cell().node()",function(){return this.iterator("cell",function(a,b,c){return(a=a.aoData[b])&&a.anCells?a.anCells[c]:k},1)});p("cells().data()",function(){return this.iterator("cell",function(a,b,c){return B(a,b,c)},1)});s("cells().cache()",
+"cell().cache()",function(a){a="search"===a?"_aFilterData":"_aSortData";return this.iterator("cell",function(b,c,d){return b.aoData[c][a][d]},1)});s("cells().render()","cell().render()",function(a){return this.iterator("cell",function(b,c,d){return B(b,c,d,a)},1)});s("cells().indexes()","cell().index()",function(){return this.iterator("cell",function(a,b,c){return{row:b,column:c,columnVisible:$(a,c)}},1)});s("cells().invalidate()","cell().invalidate()",function(a){return this.iterator("cell",function(b,
+c,d){ca(b,c,a,d)})});p("cell()",function(a,b,c){return bb(this.cells(a,b,c))});p("cell().data()",function(a){var b=this.context,c=this[0];if(a===k)return b.length&&c.length?B(b[0],c[0].row,c[0].column):k;jb(b[0],c[0].row,c[0].column,a);ca(b[0],c[0].row,"data",c[0].column);return this});p("order()",function(a,b){var c=this.context;if(a===k)return 0!==c.length?c[0].aaSorting:k;"number"===typeof a?a=[[a,b]]:h.isArray(a[0])||(a=Array.prototype.slice.call(arguments));return this.iterator("table",function(b){b.aaSorting=
+a.slice()})});p("order.listener()",function(a,b,c){return this.iterator("table",function(d){Oa(d,a,b,c)})});p("order.fixed()",function(a){if(!a){var b=this.context,b=b.length?b[0].aaSortingFixed:k;return h.isArray(b)?{pre:b}:b}return this.iterator("table",function(b){b.aaSortingFixed=h.extend(!0,{},a)})});p(["columns().order()","column().order()"],function(a){var b=this;return this.iterator("table",function(c,d){var e=[];h.each(b[d],function(b,c){e.push([c,a])});c.aaSorting=e})});p("search()",function(a,
+b,c,d){var e=this.context;return a===k?0!==e.length?e[0].oPreviousSearch.sSearch:k:this.iterator("table",function(e){e.oFeatures.bFilter&&fa(e,h.extend({},e.oPreviousSearch,{sSearch:a+"",bRegex:null===b?!1:b,bSmart:null===c?!0:c,bCaseInsensitive:null===d?!0:d}),1)})});s("columns().search()","column().search()",function(a,b,c,d){return this.iterator("column",function(e,f){var g=e.aoPreSearchCols;if(a===k)return g[f].sSearch;e.oFeatures.bFilter&&(h.extend(g[f],{sSearch:a+"",bRegex:null===b?!1:b,bSmart:null===
+c?!0:c,bCaseInsensitive:null===d?!0:d}),fa(e,e.oPreviousSearch,1))})});p("state()",function(){return this.context.length?this.context[0].oSavedState:null});p("state.clear()",function(){return this.iterator("table",function(a){a.fnStateSaveCallback.call(a.oInstance,a,{})})});p("state.loaded()",function(){return this.context.length?this.context[0].oLoadedState:null});p("state.save()",function(){return this.iterator("table",function(a){ya(a)})});m.versionCheck=m.fnVersionCheck=function(a){for(var b=
+m.version.split("."),a=a.split("."),c,d,e=0,f=a.length;e<f;e++)if(c=parseInt(b[e],10)||0,d=parseInt(a[e],10)||0,c!==d)return c>d;return!0};m.isDataTable=m.fnIsDataTable=function(a){var b=h(a).get(0),c=!1;h.each(m.settings,function(a,e){var f=e.nScrollHead?h("table",e.nScrollHead)[0]:null,g=e.nScrollFoot?h("table",e.nScrollFoot)[0]:null;if(e.nTable===b||f===b||g===b)c=!0});return c};m.tables=m.fnTables=function(a){var b=!1;h.isPlainObject(a)&&(b=a.api,a=a.visible);var c=h.map(m.settings,function(b){if(!a||
+a&&h(b.nTable).is(":visible"))return b.nTable});return b?new r(c):c};m.util={throttle:ua,escapeRegex:va};m.camelToHungarian=K;p("$()",function(a,b){var c=this.rows(b).nodes(),c=h(c);return h([].concat(c.filter(a).toArray(),c.find(a).toArray()))});h.each(["on","one","off"],function(a,b){p(b+"()",function(){var a=Array.prototype.slice.call(arguments);a[0].match(/\.dt\b/)||(a[0]+=".dt");var d=h(this.tables().nodes());d[b].apply(d,a);return this})});p("clear()",function(){return this.iterator("table",
+function(a){na(a)})});p("settings()",function(){return new r(this.context,this.context)});p("init()",function(){var a=this.context;return a.length?a[0].oInit:null});p("data()",function(){return this.iterator("table",function(a){return F(a.aoData,"_aData")}).flatten()});p("destroy()",function(a){a=a||!1;return this.iterator("table",function(b){var c=b.nTableWrapper.parentNode,d=b.oClasses,e=b.nTable,f=b.nTBody,g=b.nTHead,j=b.nTFoot,i=h(e),f=h(f),k=h(b.nTableWrapper),l=h.map(b.aoData,function(a){return a.nTr}),
+p;b.bDestroying=!0;u(b,"aoDestroyCallback","destroy",[b]);a||(new r(b)).columns().visible(!0);k.unbind(".DT").find(":not(tbody *)").unbind(".DT");h(D).unbind(".DT-"+b.sInstance);e!=g.parentNode&&(i.children("thead").detach(),i.append(g));j&&e!=j.parentNode&&(i.children("tfoot").detach(),i.append(j));b.aaSorting=[];b.aaSortingFixed=[];xa(b);h(l).removeClass(b.asStripeClasses.join(" "));h("th, td",g).removeClass(d.sSortable+" "+d.sSortableAsc+" "+d.sSortableDesc+" "+d.sSortableNone);b.bJUI&&(h("th span."+
+d.sSortIcon+", td span."+d.sSortIcon,g).detach(),h("th, td",g).each(function(){var a=h("div."+d.sSortJUIWrapper,this);h(this).append(a.contents());a.detach()}));f.children().detach();f.append(l);g=a?"remove":"detach";i[g]();k[g]();!a&&c&&(c.insertBefore(e,b.nTableReinsertBefore),i.css("width",b.sDestroyWidth).removeClass(d.sTable),(p=b.asDestroyStripes.length)&&f.children().each(function(a){h(this).addClass(b.asDestroyStripes[a%p])}));c=h.inArray(b,m.settings);-1!==c&&m.settings.splice(c,1)})});h.each(["column",
+"row","cell"],function(a,b){p(b+"s().every()",function(a){var d=this.selector.opts,e=this;return this.iterator(b,function(f,g,h,i,n){a.call(e[b](g,"cell"===b?h:d,"cell"===b?d:k),g,h,i,n)})})});p("i18n()",function(a,b,c){var d=this.context[0],a=Q(a)(d.oLanguage);a===k&&(a=b);c!==k&&h.isPlainObject(a)&&(a=a[c]!==k?a[c]:a._);return a.replace("%d",c)});m.version="1.10.11";m.settings=[];m.models={};m.models.oSearch={bCaseInsensitive:!0,sSearch:"",bRegex:!1,bSmart:!0};m.models.oRow={nTr:null,anCells:null,
+_aData:[],_aSortData:null,_aFilterData:null,_sFilterRow:null,_sRowStripe:"",src:null,idx:-1};m.models.oColumn={idx:null,aDataSort:null,asSorting:null,bSearchable:null,bSortable:null,bVisible:null,_sManualType:null,_bAttrSrc:!1,fnCreatedCell:null,fnGetData:null,fnSetData:null,mData:null,mRender:null,nTh:null,nTf:null,sClass:null,sContentPadding:null,sDefaultContent:null,sName:null,sSortDataType:"std",sSortingClass:null,sSortingClassJUI:null,sTitle:null,sType:null,sWidth:null,sWidthOrig:null};m.defaults=
+{aaData:null,aaSorting:[[0,"asc"]],aaSortingFixed:[],ajax:null,aLengthMenu:[10,25,50,100],aoColumns:null,aoColumnDefs:null,aoSearchCols:[],asStripeClasses:null,bAutoWidth:!0,bDeferRender:!1,bDestroy:!1,bFilter:!0,bInfo:!0,bJQueryUI:!1,bLengthChange:!0,bPaginate:!0,bProcessing:!1,bRetrieve:!1,bScrollCollapse:!1,bServerSide:!1,bSort:!0,bSortMulti:!0,bSortCellsTop:!1,bSortClasses:!0,bStateSave:!1,fnCreatedRow:null,fnDrawCallback:null,fnFooterCallback:null,fnFormatNumber:function(a){return a.toString().replace(/\B(?=(\d{3})+(?!\d))/g,
+this.oLanguage.sThousands)},fnHeaderCallback:null,fnInfoCallback:null,fnInitComplete:null,fnPreDrawCallback:null,fnRowCallback:null,fnServerData:null,fnServerParams:null,fnStateLoadCallback:function(a){try{return JSON.parse((-1===a.iStateDuration?sessionStorage:localStorage).getItem("DataTables_"+a.sInstance+"_"+location.pathname))}catch(b){}},fnStateLoadParams:null,fnStateLoaded:null,fnStateSaveCallback:function(a,b){try{(-1===a.iStateDuration?sessionStorage:localStorage).setItem("DataTables_"+a.sInstance+
+"_"+location.pathname,JSON.stringify(b))}catch(c){}},fnStateSaveParams:null,iStateDuration:7200,iDeferLoading:null,iDisplayLength:10,iDisplayStart:0,iTabIndex:0,oClasses:{},oLanguage:{oAria:{sSortAscending:": activate to sort column ascending",sSortDescending:": activate to sort column descending"},oPaginate:{sFirst:"First",sLast:"Last",sNext:"Next",sPrevious:"Previous"},sEmptyTable:"No data available in table",sInfo:"Showing _START_ to _END_ of _TOTAL_ entries",sInfoEmpty:"Showing 0 to 0 of 0 entries",
+sInfoFiltered:"(filtered from _MAX_ total entries)",sInfoPostFix:"",sDecimal:"",sThousands:",",sLengthMenu:"Show _MENU_ entries",sLoadingRecords:"Loading...",sProcessing:"Processing...",sSearch:"Search:",sSearchPlaceholder:"",sUrl:"",sZeroRecords:"No matching records found"},oSearch:h.extend({},m.models.oSearch),sAjaxDataProp:"data",sAjaxSource:null,sDom:"lfrtip",searchDelay:null,sPaginationType:"simple_numbers",sScrollX:"",sScrollXInner:"",sScrollY:"",sServerMethod:"GET",renderer:null,rowId:"DT_RowId"};
+Y(m.defaults);m.defaults.column={aDataSort:null,iDataSort:-1,asSorting:["asc","desc"],bSearchable:!0,bSortable:!0,bVisible:!0,fnCreatedCell:null,mData:null,mRender:null,sCellType:"td",sClass:"",sContentPadding:"",sDefaultContent:null,sName:"",sSortDataType:"std",sTitle:null,sType:null,sWidth:null};Y(m.defaults.column);m.models.oSettings={oFeatures:{bAutoWidth:null,bDeferRender:null,bFilter:null,bInfo:null,bLengthChange:null,bPaginate:null,bProcessing:null,bServerSide:null,bSort:null,bSortMulti:null,
+bSortClasses:null,bStateSave:null},oScroll:{bCollapse:null,iBarWidth:0,sX:null,sXInner:null,sY:null},oLanguage:{fnInfoCallback:null},oBrowser:{bScrollOversize:!1,bScrollbarLeft:!1,bBounding:!1,barWidth:0},ajax:null,aanFeatures:[],aoData:[],aiDisplay:[],aiDisplayMaster:[],aIds:{},aoColumns:[],aoHeader:[],aoFooter:[],oPreviousSearch:{},aoPreSearchCols:[],aaSorting:null,aaSortingFixed:[],asStripeClasses:null,asDestroyStripes:[],sDestroyWidth:0,aoRowCallback:[],aoHeaderCallback:[],aoFooterCallback:[],
+aoDrawCallback:[],aoRowCreatedCallback:[],aoPreDrawCallback:[],aoInitComplete:[],aoStateSaveParams:[],aoStateLoadParams:[],aoStateLoaded:[],sTableId:"",nTable:null,nTHead:null,nTFoot:null,nTBody:null,nTableWrapper:null,bDeferLoading:!1,bInitialised:!1,aoOpenRows:[],sDom:null,searchDelay:null,sPaginationType:"two_button",iStateDuration:0,aoStateSave:[],aoStateLoad:[],oSavedState:null,oLoadedState:null,sAjaxSource:null,sAjaxDataProp:null,bAjaxDataGet:!0,jqXHR:null,json:k,oAjaxData:k,fnServerData:null,
+aoServerParams:[],sServerMethod:null,fnFormatNumber:null,aLengthMenu:null,iDraw:0,bDrawing:!1,iDrawError:-1,_iDisplayLength:10,_iDisplayStart:0,_iRecordsTotal:0,_iRecordsDisplay:0,bJUI:null,oClasses:{},bFiltered:!1,bSorted:!1,bSortCellsTop:null,oInit:null,aoDestroyCallback:[],fnRecordsTotal:function(){return"ssp"==y(this)?1*this._iRecordsTotal:this.aiDisplayMaster.length},fnRecordsDisplay:function(){return"ssp"==y(this)?1*this._iRecordsDisplay:this.aiDisplay.length},fnDisplayEnd:function(){var a=
+this._iDisplayLength,b=this._iDisplayStart,c=b+a,d=this.aiDisplay.length,e=this.oFeatures,f=e.bPaginate;return e.bServerSide?!1===f||-1===a?b+d:Math.min(b+a,this._iRecordsDisplay):!f||c>d||-1===a?d:c},oInstance:null,sInstance:null,iTabIndex:0,nScrollHead:null,nScrollFoot:null,aLastSort:[],oPlugins:{},rowIdFn:null,rowId:null};m.ext=v={buttons:{},classes:{},builder:"-source-",errMode:"alert",feature:[],search:[],selector:{cell:[],column:[],row:[]},internal:{},legacy:{ajax:null},pager:{},renderer:{pageButton:{},
+header:{}},order:{},type:{detect:[],search:{},order:{}},_unique:0,fnVersionCheck:m.fnVersionCheck,iApiIndex:0,oJUIClasses:{},sVersion:m.version};h.extend(v,{afnFiltering:v.search,aTypes:v.type.detect,ofnSearch:v.type.search,oSort:v.type.order,afnSortData:v.order,aoFeatures:v.feature,oApi:v.internal,oStdClasses:v.classes,oPagination:v.pager});h.extend(m.ext.classes,{sTable:"dataTable",sNoFooter:"no-footer",sPageButton:"paginate_button",sPageButtonActive:"current",sPageButtonDisabled:"disabled",sStripeOdd:"odd",
+sStripeEven:"even",sRowEmpty:"dataTables_empty",sWrapper:"dataTables_wrapper",sFilter:"dataTables_filter",sInfo:"dataTables_info",sPaging:"dataTables_paginate paging_",sLength:"dataTables_length",sProcessing:"dataTables_processing",sSortAsc:"sorting_asc",sSortDesc:"sorting_desc",sSortable:"sorting",sSortableAsc:"sorting_asc_disabled",sSortableDesc:"sorting_desc_disabled",sSortableNone:"sorting_disabled",sSortColumn:"sorting_",sFilterInput:"",sLengthSelect:"",sScrollWrapper:"dataTables_scroll",sScrollHead:"dataTables_scrollHead",
+sScrollHeadInner:"dataTables_scrollHeadInner",sScrollBody:"dataTables_scrollBody",sScrollFoot:"dataTables_scrollFoot",sScrollFootInner:"dataTables_scrollFootInner",sHeaderTH:"",sFooterTH:"",sSortJUIAsc:"",sSortJUIDesc:"",sSortJUI:"",sSortJUIAscAllowed:"",sSortJUIDescAllowed:"",sSortJUIWrapper:"",sSortIcon:"",sJUIHeader:"",sJUIFooter:""});var Ea="",Ea="",H=Ea+"ui-state-default",ia=Ea+"css_right ui-icon ui-icon-",Xb=Ea+"fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix";h.extend(m.ext.oJUIClasses,
+m.ext.classes,{sPageButton:"fg-button ui-button "+H,sPageButtonActive:"ui-state-disabled",sPageButtonDisabled:"ui-state-disabled",sPaging:"dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi ui-buttonset-multi paging_",sSortAsc:H+" sorting_asc",sSortDesc:H+" sorting_desc",sSortable:H+" sorting",sSortableAsc:H+" sorting_asc_disabled",sSortableDesc:H+" sorting_desc_disabled",sSortableNone:H+" sorting_disabled",sSortJUIAsc:ia+"triangle-1-n",sSortJUIDesc:ia+"triangle-1-s",sSortJUI:ia+"carat-2-n-s",
+sSortJUIAscAllowed:ia+"carat-1-n",sSortJUIDescAllowed:ia+"carat-1-s",sSortJUIWrapper:"DataTables_sort_wrapper",sSortIcon:"DataTables_sort_icon",sScrollHead:"dataTables_scrollHead "+H,sScrollFoot:"dataTables_scrollFoot "+H,sHeaderTH:H,sFooterTH:H,sJUIHeader:Xb+" ui-corner-tl ui-corner-tr",sJUIFooter:Xb+" ui-corner-bl ui-corner-br"});var Mb=m.ext.pager;h.extend(Mb,{simple:function(){return["previous","next"]},full:function(){return["first","previous","next","last"]},numbers:function(a,b){return[Aa(a,
+b)]},simple_numbers:function(a,b){return["previous",Aa(a,b),"next"]},full_numbers:function(a,b){return["first","previous",Aa(a,b),"next","last"]},_numbers:Aa,numbers_length:7});h.extend(!0,m.ext.renderer,{pageButton:{_:function(a,b,c,d,e,f){var g=a.oClasses,j=a.oLanguage.oPaginate,i=a.oLanguage.oAria.paginate||{},k,l,m=0,p=function(b,d){var o,r,u,s,v=function(b){Ta(a,b.data.action,true)};o=0;for(r=d.length;o<r;o++){s=d[o];if(h.isArray(s)){u=h("<"+(s.DT_el||"div")+"/>").appendTo(b);p(u,s)}else{k=null;
+l="";switch(s){case "ellipsis":b.append('<span class="ellipsis">&#x2026;</span>');break;case "first":k=j.sFirst;l=s+(e>0?"":" "+g.sPageButtonDisabled);break;case "previous":k=j.sPrevious;l=s+(e>0?"":" "+g.sPageButtonDisabled);break;case "next":k=j.sNext;l=s+(e<f-1?"":" "+g.sPageButtonDisabled);break;case "last":k=j.sLast;l=s+(e<f-1?"":" "+g.sPageButtonDisabled);break;default:k=s+1;l=e===s?g.sPageButtonActive:""}if(k!==null){u=h("<a>",{"class":g.sPageButton+" "+l,"aria-controls":a.sTableId,"aria-label":i[s],
+"data-dt-idx":m,tabindex:a.iTabIndex,id:c===0&&typeof s==="string"?a.sTableId+"_"+s:null}).html(k).appendTo(b);Wa(u,{action:s},v);m++}}}},r;try{r=h(b).find(I.activeElement).data("dt-idx")}catch(o){}p(h(b).empty(),d);r&&h(b).find("[data-dt-idx="+r+"]").focus()}}});h.extend(m.ext.type.detect,[function(a,b){var c=b.oLanguage.sDecimal;return Za(a,c)?"num"+c:null},function(a){if(a&&!(a instanceof Date)&&(!bc.test(a)||!cc.test(a)))return null;var b=Date.parse(a);return null!==b&&!isNaN(b)||M(a)?"date":
+null},function(a,b){var c=b.oLanguage.sDecimal;return Za(a,c,!0)?"num-fmt"+c:null},function(a,b){var c=b.oLanguage.sDecimal;return Rb(a,c)?"html-num"+c:null},function(a,b){var c=b.oLanguage.sDecimal;return Rb(a,c,!0)?"html-num-fmt"+c:null},function(a){return M(a)||"string"===typeof a&&-1!==a.indexOf("<")?"html":null}]);h.extend(m.ext.type.search,{html:function(a){return M(a)?a:"string"===typeof a?a.replace(Ob," ").replace(Ca,""):""},string:function(a){return M(a)?a:"string"===typeof a?a.replace(Ob,
+" "):a}});var Ba=function(a,b,c,d){if(0!==a&&(!a||"-"===a))return-Infinity;b&&(a=Qb(a,b));a.replace&&(c&&(a=a.replace(c,"")),d&&(a=a.replace(d,"")));return 1*a};h.extend(v.type.order,{"date-pre":function(a){return Date.parse(a)||0},"html-pre":function(a){return M(a)?"":a.replace?a.replace(/<.*?>/g,"").toLowerCase():a+""},"string-pre":function(a){return M(a)?"":"string"===typeof a?a.toLowerCase():!a.toString?"":a.toString()},"string-asc":function(a,b){return a<b?-1:a>b?1:0},"string-desc":function(a,
+b){return a<b?1:a>b?-1:0}});db("");h.extend(!0,m.ext.renderer,{header:{_:function(a,b,c,d){h(a.nTable).on("order.dt.DT",function(e,f,g,h){if(a===f){e=c.idx;b.removeClass(c.sSortingClass+" "+d.sSortAsc+" "+d.sSortDesc).addClass(h[e]=="asc"?d.sSortAsc:h[e]=="desc"?d.sSortDesc:c.sSortingClass)}})},jqueryui:function(a,b,c,d){h("<div/>").addClass(d.sSortJUIWrapper).append(b.contents()).append(h("<span/>").addClass(d.sSortIcon+" "+c.sSortingClassJUI)).appendTo(b);h(a.nTable).on("order.dt.DT",function(e,
+f,g,h){if(a===f){e=c.idx;b.removeClass(d.sSortAsc+" "+d.sSortDesc).addClass(h[e]=="asc"?d.sSortAsc:h[e]=="desc"?d.sSortDesc:c.sSortingClass);b.find("span."+d.sSortIcon).removeClass(d.sSortJUIAsc+" "+d.sSortJUIDesc+" "+d.sSortJUI+" "+d.sSortJUIAscAllowed+" "+d.sSortJUIDescAllowed).addClass(h[e]=="asc"?d.sSortJUIAsc:h[e]=="desc"?d.sSortJUIDesc:c.sSortingClassJUI)}})}}});var Yb=function(a){return"string"===typeof a?a.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"):a};m.render={number:function(a,
+b,c,d,e){return{display:function(f){if("number"!==typeof f&&"string"!==typeof f)return f;var g=0>f?"-":"",h=parseFloat(f);if(isNaN(h))return Yb(f);f=Math.abs(h);h=parseInt(f,10);f=c?b+(f-h).toFixed(c).substring(2):"";return g+(d||"")+h.toString().replace(/\B(?=(\d{3})+(?!\d))/g,a)+f+(e||"")}}},text:function(){return{display:Yb}}};h.extend(m.ext.internal,{_fnExternApiFunc:Nb,_fnBuildAjax:ra,_fnAjaxUpdate:lb,_fnAjaxParameters:ub,_fnAjaxUpdateDraw:vb,_fnAjaxDataSrc:sa,_fnAddColumn:Ga,_fnColumnOptions:ja,
+_fnAdjustColumnSizing:U,_fnVisibleToColumnIndex:Z,_fnColumnIndexToVisible:$,_fnVisbleColumns:aa,_fnGetColumns:la,_fnColumnTypes:Ia,_fnApplyColumnDefs:ib,_fnHungarianMap:Y,_fnCamelToHungarian:K,_fnLanguageCompat:Fa,_fnBrowserDetect:gb,_fnAddData:N,_fnAddTr:ma,_fnNodeToDataIndex:function(a,b){return b._DT_RowIndex!==k?b._DT_RowIndex:null},_fnNodeToColumnIndex:function(a,b,c){return h.inArray(c,a.aoData[b].anCells)},_fnGetCellData:B,_fnSetCellData:jb,_fnSplitObjNotation:La,_fnGetObjectDataFn:Q,_fnSetObjectDataFn:R,
+_fnGetDataMaster:Ma,_fnClearTable:na,_fnDeleteIndex:oa,_fnInvalidate:ca,_fnGetRowElements:Ka,_fnCreateTr:Ja,_fnBuildHead:kb,_fnDrawHead:ea,_fnDraw:O,_fnReDraw:T,_fnAddOptionsHtml:nb,_fnDetectHeader:da,_fnGetUniqueThs:qa,_fnFeatureHtmlFilter:pb,_fnFilterComplete:fa,_fnFilterCustom:yb,_fnFilterColumn:xb,_fnFilter:wb,_fnFilterCreateSearch:Qa,_fnEscapeRegex:va,_fnFilterData:zb,_fnFeatureHtmlInfo:sb,_fnUpdateInfo:Cb,_fnInfoMacros:Db,_fnInitialise:ga,_fnInitComplete:ta,_fnLengthChange:Ra,_fnFeatureHtmlLength:ob,
+_fnFeatureHtmlPaginate:tb,_fnPageChange:Ta,_fnFeatureHtmlProcessing:qb,_fnProcessingDisplay:C,_fnFeatureHtmlTable:rb,_fnScrollDraw:ka,_fnApplyToChildren:J,_fnCalculateColumnWidths:Ha,_fnThrottle:ua,_fnConvertToWidth:Fb,_fnGetWidestNode:Gb,_fnGetMaxLenString:Hb,_fnStringToCss:x,_fnSortFlatten:W,_fnSort:mb,_fnSortAria:Jb,_fnSortListener:Va,_fnSortAttachListener:Oa,_fnSortingClasses:xa,_fnSortData:Ib,_fnSaveState:ya,_fnLoadState:Kb,_fnSettingsFromNode:za,_fnLog:L,_fnMap:E,_fnBindAction:Wa,_fnCallbackReg:z,
+_fnCallbackFire:u,_fnLengthOverflow:Sa,_fnRenderer:Pa,_fnDataSource:y,_fnRowAttributes:Na,_fnCalculateEnd:function(){}});h.fn.dataTable=m;m.$=h;h.fn.dataTableSettings=m.settings;h.fn.dataTableExt=m.ext;h.fn.DataTable=function(a){return h(this).dataTable(a).api()};h.each(m,function(a,b){h.fn.DataTable[a]=b});return h.fn.dataTable});
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/public/js/jquery.min.js	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,5 @@
+/*! jQuery v1.12.3 | (c) jQuery Foundation | jquery.org/license */
+!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=a.document,e=c.slice,f=c.concat,g=c.push,h=c.indexOf,i={},j=i.toString,k=i.hasOwnProperty,l={},m="1.12.3",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return e.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(!l.ownFirst)for(b in a)return k.call(a,b);for(b in a);return void 0===b||k.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(h)return h.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;d>g;g++)e=b(a[g],g,c),null!=e&&h.push(e);else for(g in a)e=b(a[g],g,c),null!=e&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=e.call(arguments,2),d=function(){return a.apply(b||this,c.concat(e.call(arguments)))},d.guid=a.guid=a.guid||n.guid++,d):void 0},now:function(){return+new Date},support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M+"|[*])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,aa=/'|\\/g,ba=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(ea){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fa(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+qa(r[h]);s=r.join(","),w=_.test(a)&&oa(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function ga(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ha(a){return a[u]=!0,a}function ia(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ka(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function la(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function na(a){return ha(function(b){return b=+b,ha(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function oa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=fa.support={},f=fa.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fa.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ia(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ia(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ia(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ia(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ia(function(a){var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ia(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ka(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ka(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},fa.matches=function(a,b){return fa(a,null,null,b)},fa.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fa(b,n,null,[a]).length>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fa.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fa.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fa.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fa.selectors={cacheLength:50,createPseudo:ha,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fa.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fa.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ba,ca).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fa.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(P," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fa.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ha(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ha(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ha(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ha(function(a){return function(b){return fa(a,b).length>0}}),contains:ha(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ha(function(a){return V.test(a||"")||fa.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:na(function(){return[0]}),last:na(function(a,b){return[b-1]}),eq:na(function(a,b,c){return[0>c?c+b:c]}),even:na(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:na(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:na(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:na(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=la(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=ma(b);function pa(){}pa.prototype=d.filters=d.pseudos,d.setFilters=new pa,g=fa.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=R.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fa.error(a):z(a,i).slice(0)};function qa(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function ra(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function sa(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ta(a,b,c){for(var d=0,e=b.length;e>d;d++)fa(a,b[d],c);return c}function ua(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function va(a,b,c,d,e,f){return d&&!d[u]&&(d=va(d)),e&&!e[u]&&(e=va(e,f)),ha(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ta(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ua(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ua(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ua(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ra(function(a){return a===b},h,!0),l=ra(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[ra(sa(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return va(i>1&&sa(m),i>1&&qa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(Q,"$1"),c,e>i&&wa(a.slice(i,e)),f>e&&wa(a=a.slice(e)),f>e&&qa(a))}m.push(c)}return sa(m)}function xa(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(i));u=ua(u)}H.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&fa.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ha(f):f}return h=fa.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xa(e,d)),f.selector=a}return f},i=fa.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ba,ca),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=W.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ba,ca),_.test(j[0].type)&&oa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qa(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||_.test(a)&&oa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ia(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ia(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ja("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ia(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ja("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ia(function(a){return null==a.getAttribute("disabled")})||ja(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fa}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.uniqueSort=n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},v=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},w=n.expr.match.needsContext,x=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,y=/^.[^:#\[\.,]*$/;function z(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(y.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>-1!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(z(this,a||[],!1))},not:function(a){return this.pushStack(z(this,a||[],!0))},is:function(a){return!!z(this,"string"==typeof a&&w.test(a)?n(a):a||[],!1).length}});var A,B=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=n.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||A,"string"==typeof a){if(e="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:B.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),x.test(e[1])&&n.isPlainObject(b))for(e in b)n.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}if(f=d.getElementById(e[2]),f&&f.parentNode){if(f.id!==e[2])return A.find(a);this.length=1,this[0]=f}return this.context=d,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof c.ready?c.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};C.prototype=n.fn,A=n(d);var D=/^(?:parents|prev(?:Until|All))/,E={children:!0,contents:!0,next:!0,prev:!0};n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=w.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.uniqueSort(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function F(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return u(a,"parentNode")},parentsUntil:function(a,b,c){return u(a,"parentNode",c)},next:function(a){return F(a,"nextSibling")},prev:function(a){return F(a,"previousSibling")},nextAll:function(a){return u(a,"nextSibling")},prevAll:function(a){return u(a,"previousSibling")},nextUntil:function(a,b,c){return u(a,"nextSibling",c)},prevUntil:function(a,b,c){return u(a,"previousSibling",c)},siblings:function(a){return v((a.parentNode||{}).firstChild,a)},children:function(a){return v(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(E[a]||(e=n.uniqueSort(e)),D.test(a)&&(e=e.reverse())),this.pushStack(e)}});var G=/\S+/g;function H(a){var b={};return n.each(a.match(G)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?H(a):n.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){n.each(b,function(b,c){n.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==n.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return n.each(arguments,function(a,b){var c;while((c=n.inArray(b,f,c))>-1)f.splice(c,1),h>=c&&h--}),this},has:function(a){return a?n.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=!0,c||j.disable(),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().progress(c.notify).done(c.resolve).fail(c.reject):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=e.call(arguments),d=c.length,f=1!==d||a&&n.isFunction(a.promise)?d:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?e.call(arguments):d,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(d>1)for(i=new Array(d),j=new Array(d),k=new Array(d);d>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().progress(h(b,j,i)).done(h(b,k,c)).fail(g.reject):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(d,[n]),n.fn.triggerHandler&&(n(d).triggerHandler("ready"),n(d).off("ready"))))}});function J(){d.addEventListener?(d.removeEventListener("DOMContentLoaded",K),a.removeEventListener("load",K)):(d.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(d.addEventListener||"load"===a.event.type||"complete"===d.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll)a.setTimeout(n.ready);else if(d.addEventListener)d.addEventListener("DOMContentLoaded",K),a.addEventListener("load",K);else{d.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&d.documentElement}catch(e){}c&&c.doScroll&&!function f(){if(!n.isReady){try{c.doScroll("left")}catch(b){return a.setTimeout(f,50)}J(),n.ready()}}()}return I.promise(b)},n.ready.promise();var L;for(L in n(l))break;l.ownFirst="0"===L,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c,e;c=d.getElementsByTagName("body")[0],c&&c.style&&(b=d.createElement("div"),e=d.createElement("div"),e.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(e).appendChild(b),"undefined"!=typeof b.style.zoom&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",l.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(e))}),function(){var a=d.createElement("div");l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}a=null}();var M=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b},N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0;
+}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(M(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),"object"!=typeof b&&"function"!=typeof b||(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f}}function S(a,b,c){if(M(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=void 0)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}}),function(){var a;l.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,e;return c=d.getElementsByTagName("body")[0],c&&c.style?(b=d.createElement("div"),e=d.createElement("div"),e.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(e).appendChild(b),"undefined"!=typeof b.style.zoom&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(d.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(e),a):void 0}}();var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),V=["Top","Right","Bottom","Left"],W=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)};function X(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return n.css(a,b,"")},i=h(),j=c&&c[3]||(n.cssNumber[b]?"":"px"),k=(n.cssNumber[b]||"px"!==j&&+i)&&U.exec(n.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,n.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var Y=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)Y(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},Z=/^(?:checkbox|radio)$/i,$=/<([\w:-]+)/,_=/^$|\/(?:java|ecma)script/i,aa=/^\s+/,ba="abbr|article|aside|audio|bdi|canvas|data|datalist|details|dialog|figcaption|figure|footer|header|hgroup|main|mark|meter|nav|output|picture|progress|section|summary|template|time|video";function ca(a){var b=ba.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}!function(){var a=d.createElement("div"),b=d.createDocumentFragment(),c=d.createElement("input");a.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",l.leadingWhitespace=3===a.firstChild.nodeType,l.tbody=!a.getElementsByTagName("tbody").length,l.htmlSerialize=!!a.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==d.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,b.appendChild(c),l.appendChecked=c.checked,a.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!a.cloneNode(!0).lastChild.defaultValue,b.appendChild(a),c=d.createElement("input"),c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),a.appendChild(c),l.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!!a.addEventListener,a[n.expando]=1,l.attributes=!a.getAttribute(n.expando)}();var da={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]};da.optgroup=da.option,da.tbody=da.tfoot=da.colgroup=da.caption=da.thead,da.th=da.td;function ea(a,b){var c,d,e=0,f="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,ea(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function fa(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}var ga=/<|&#?\w+;/,ha=/<tbody/i;function ia(a){Z.test(a.type)&&(a.defaultChecked=a.checked)}function ja(a,b,c,d,e){for(var f,g,h,i,j,k,m,o=a.length,p=ca(b),q=[],r=0;o>r;r++)if(g=a[r],g||0===g)if("object"===n.type(g))n.merge(q,g.nodeType?[g]:g);else if(ga.test(g)){i=i||p.appendChild(b.createElement("div")),j=($.exec(g)||["",""])[1].toLowerCase(),m=da[j]||da._default,i.innerHTML=m[1]+n.htmlPrefilter(g)+m[2],f=m[0];while(f--)i=i.lastChild;if(!l.leadingWhitespace&&aa.test(g)&&q.push(b.createTextNode(aa.exec(g)[0])),!l.tbody){g="table"!==j||ha.test(g)?"<table>"!==m[1]||ha.test(g)?0:i:i.firstChild,f=g&&g.childNodes.length;while(f--)n.nodeName(k=g.childNodes[f],"tbody")&&!k.childNodes.length&&g.removeChild(k)}n.merge(q,i.childNodes),i.textContent="";while(i.firstChild)i.removeChild(i.firstChild);i=p.lastChild}else q.push(b.createTextNode(g));i&&p.removeChild(i),l.appendChecked||n.grep(ea(q,"input"),ia),r=0;while(g=q[r++])if(d&&n.inArray(g,d)>-1)e&&e.push(g);else if(h=n.contains(g.ownerDocument,g),i=ea(p.appendChild(g),"script"),h&&fa(i),c){f=0;while(g=i[f++])_.test(g.type||"")&&c.push(g)}return i=null,p}!function(){var b,c,e=d.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b]=c in a)||(e.setAttribute(c,"t"),l[b]=e.attributes[c].expando===!1);e=null}();var ka=/^(?:input|select|textarea)$/i,la=/^key/,ma=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,na=/^(?:focusinfocus|focusoutblur)$/,oa=/^([^.]*)(?:\.(.+)|)/;function pa(){return!0}function qa(){return!1}function ra(){try{return d.activeElement}catch(a){}}function sa(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)sa(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=qa;else if(!e)return a;return 1===f&&(g=e,e=function(a){return n().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=n.guid++)),a.each(function(){n.event.add(this,b,e,d,c)})}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return"undefined"==typeof n||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(G)||[""],h=b.length;while(h--)f=oa.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(G)||[""],j=b.length;while(j--)if(h=oa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,e,f){var g,h,i,j,l,m,o,p=[e||d],q=k.call(b,"type")?b.type:b,r=k.call(b,"namespace")?b.namespace.split("."):[];if(i=m=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!na.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),h=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=r.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:n.makeArray(c,[b]),l=n.event.special[q]||{},f||!l.trigger||l.trigger.apply(e,c)!==!1)){if(!f&&!l.noBubble&&!n.isWindow(e)){for(j=l.delegateType||q,na.test(j+q)||(i=i.parentNode);i;i=i.parentNode)p.push(i),m=i;m===(e.ownerDocument||d)&&p.push(m.defaultView||m.parentWindow||a)}o=0;while((i=p[o++])&&!b.isPropagationStopped())b.type=o>1?j:l.bindType||q,g=(n._data(i,"events")||{})[b.type]&&n._data(i,"handle"),g&&g.apply(i,c),g=h&&i[h],g&&g.apply&&M(i)&&(b.result=g.apply(i,c),b.result===!1&&b.preventDefault());if(b.type=q,!f&&!b.isDefaultPrevented()&&(!l._default||l._default.apply(p.pop(),c)===!1)&&M(e)&&h&&e[q]&&!n.isWindow(e)){m=e[h],m&&(e[h]=null),n.event.triggered=q;try{e[q]()}catch(s){}n.event.triggered=void 0,m&&(e[h]=m)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())a.rnamespace&&!a.rnamespace.test(g.namespace)||(a.handleObj=g,a.data=g.data,d=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>-1:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,e,f=a.type,g=a,h=this.fixHooks[f];h||(this.fixHooks[f]=h=ma.test(f)?this.mouseHooks:la.test(f)?this.keyHooks:{}),e=h.props?this.props.concat(h.props):this.props,a=new n.Event(g),b=e.length;while(b--)c=e[b],a[c]=g[c];return a.target||(a.target=g.srcElement||d),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,h.filter?h.filter(a,g):a},props:"altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,e,f,g=b.button,h=b.fromElement;return null==a.pageX&&null!=b.clientX&&(e=a.target.ownerDocument||d,f=e.documentElement,c=e.body,a.pageX=b.clientX+(f&&f.scrollLeft||c&&c.scrollLeft||0)-(f&&f.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(f&&f.scrollTop||c&&c.scrollTop||0)-(f&&f.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&h&&(a.relatedTarget=h===a.target?b.toElement:h),a.which||void 0===g||(a.which=1&g?1:2&g?3:4&g?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ra()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ra()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c){var d=n.extend(new n.Event,c,{type:a,isSimulated:!0});n.event.trigger(d,null,b),d.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=d.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)}:function(a,b,c){var d="on"+b;a.detachEvent&&("undefined"==typeof a[d]&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?pa:qa):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={constructor:n.Event,isDefaultPrevented:qa,isPropagationStopped:qa,isImmediatePropagationStopped:qa,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=pa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=pa,a&&!this.isSimulated&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=pa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||n.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submit||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?n.prop(b,"form"):void 0;c&&!n._data(c,"submit")&&(n.event.add(c,"submit._submit",function(a){a._submitBubble=!0}),n._data(c,"submit",!0))})},postDispatch:function(a){a._submitBubble&&(delete a._submitBubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.change||(n.event.special.change={setup:function(){return ka.test(this.nodeName)?("checkbox"!==this.type&&"radio"!==this.type||(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._justChanged=!0)}),n.event.add(this,"click._change",function(a){this._justChanged&&!a.isTrigger&&(this._justChanged=!1),n.event.simulate("change",this,a)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;ka.test(b.nodeName)&&!n._data(b,"change")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a)}),n._data(b,"change",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!ka.test(this.nodeName)}}),l.focusin||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a))};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d){return sa(this,a,b,c,d)},one:function(a,b,c,d){return sa(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=qa),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});var ta=/ jQuery\d+="(?:null|\d+)"/g,ua=new RegExp("<(?:"+ba+")[\\s/>]","i"),va=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,wa=/<script|<style|<link/i,xa=/checked\s*(?:[^=]|=\s*.checked.)/i,ya=/^true\/(.*)/,za=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Aa=ca(d),Ba=Aa.appendChild(d.createElement("div"));function Ca(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function Da(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function Ea(a){var b=ya.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Fa(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Ga(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(Da(b).text=a.text,Ea(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&Z.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}}function Ha(a,b,c,d){b=f.apply([],b);var e,g,h,i,j,k,m=0,o=a.length,p=o-1,q=b[0],r=n.isFunction(q);if(r||o>1&&"string"==typeof q&&!l.checkClone&&xa.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),Ha(f,b,c,d)});if(o&&(k=ja(b,a[0].ownerDocument,!1,a,d),e=k.firstChild,1===k.childNodes.length&&(k=e),e||d)){for(i=n.map(ea(k,"script"),Da),h=i.length;o>m;m++)g=k,m!==p&&(g=n.clone(g,!0,!0),h&&n.merge(i,ea(g,"script"))),c.call(a[m],g,m);if(h)for(j=i[i.length-1].ownerDocument,n.map(i,Ea),m=0;h>m;m++)g=i[m],_.test(g.type||"")&&!n._data(g,"globalEval")&&n.contains(j,g)&&(g.src?n._evalUrl&&n._evalUrl(g.src):n.globalEval((g.text||g.textContent||g.innerHTML||"").replace(za,"")));k=e=null}return a}function Ia(a,b,c){for(var d,e=b?n.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||n.cleanData(ea(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&fa(ea(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(va,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!ua.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(Ba.innerHTML=a.outerHTML,Ba.removeChild(f=Ba.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=ea(f),h=ea(a),g=0;null!=(e=h[g]);++g)d[g]&&Ga(e,d[g]);if(b)if(c)for(h=h||ea(a),d=d||ea(f),g=0;null!=(e=h[g]);g++)Fa(e,d[g]);else Fa(a,f);return d=ea(f,"script"),d.length>0&&fa(d,!i&&ea(a,"script")),d=h=e=null,f},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.attributes,m=n.event.special;null!=(d=a[h]);h++)if((b||M(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k||"undefined"==typeof d.removeAttribute?d[i]=void 0:d.removeAttribute(i),c.push(f))}}}),n.fn.extend({domManip:Ha,detach:function(a){return Ia(this,a,!0)},remove:function(a){return Ia(this,a)},text:function(a){return Y(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||d).createTextNode(a))},null,a,arguments.length)},append:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.appendChild(a)}})},prepend:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(ea(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return Y(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(ta,""):void 0;if("string"==typeof a&&!wa.test(a)&&(l.htmlSerialize||!ua.test(a))&&(l.leadingWhitespace||!aa.test(a))&&!da[($.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(ea(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return Ha(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData(ea(this)),c&&c.replaceChild(b,this))},a)}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],f=n(a),h=f.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(f[d])[b](c),g.apply(e,c.get());return this.pushStack(e)}});var Ja,Ka={HTML:"block",BODY:"block"};function La(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function Ma(a){var b=d,c=Ka[a];return c||(c=La(a,b),"none"!==c&&c||(Ja=(Ja||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ja[0].contentWindow||Ja[0].contentDocument).document,b.write(),b.close(),c=La(a,b),Ja.detach()),Ka[a]=c),c}var Na=/^margin/,Oa=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Pa=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e},Qa=d.documentElement;!function(){var b,c,e,f,g,h,i=d.createElement("div"),j=d.createElement("div");if(j.style){j.style.cssText="float:left;opacity:.5",l.opacity="0.5"===j.style.opacity,l.cssFloat=!!j.style.cssFloat,j.style.backgroundClip="content-box",j.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===j.style.backgroundClip,i=d.createElement("div"),i.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",j.innerHTML="",i.appendChild(j),l.boxSizing=""===j.style.boxSizing||""===j.style.MozBoxSizing||""===j.style.WebkitBoxSizing,n.extend(l,{reliableHiddenOffsets:function(){return null==b&&k(),f},boxSizingReliable:function(){return null==b&&k(),e},pixelMarginRight:function(){return null==b&&k(),c},pixelPosition:function(){return null==b&&k(),b},reliableMarginRight:function(){return null==b&&k(),g},reliableMarginLeft:function(){return null==b&&k(),h}});function k(){var k,l,m=d.documentElement;m.appendChild(i),j.style.cssText="-webkit-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",b=e=h=!1,c=g=!0,a.getComputedStyle&&(l=a.getComputedStyle(j),b="1%"!==(l||{}).top,h="2px"===(l||{}).marginLeft,e="4px"===(l||{width:"4px"}).width,j.style.marginRight="50%",c="4px"===(l||{marginRight:"4px"}).marginRight,k=j.appendChild(d.createElement("div")),k.style.cssText=j.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",k.style.marginRight=k.style.width="0",j.style.width="1px",g=!parseFloat((a.getComputedStyle(k)||{}).marginRight),j.removeChild(k)),j.style.display="none",f=0===j.getClientRects().length,f&&(j.style.display="",j.innerHTML="<table><tr><td></td><td>t</td></tr></table>",k=j.getElementsByTagName("td"),k[0].style.cssText="margin:0;border:0;padding:0;display:none",f=0===k[0].offsetHeight,f&&(k[0].style.display="",k[1].style.display="none",f=0===k[0].offsetHeight)),m.removeChild(i)}}}();var Ra,Sa,Ta=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ra=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)},Sa=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ra(a),g=c?c.getPropertyValue(b)||c[b]:void 0,""!==g&&void 0!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),c&&!l.pixelMarginRight()&&Oa.test(g)&&Na.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f),void 0===g?g:g+""}):Qa.currentStyle&&(Ra=function(a){return a.currentStyle},Sa=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ra(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Oa.test(g)&&!Ta.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Ua(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Va=/alpha\([^)]*\)/i,Wa=/opacity\s*=\s*([^)]*)/i,Xa=/^(none|table(?!-c[ea]).+)/,Ya=new RegExp("^("+T+")(.*)$","i"),Za={position:"absolute",visibility:"hidden",display:"block"},$a={letterSpacing:"0",fontWeight:"400"},_a=["Webkit","O","Moz","ms"],ab=d.createElement("div").style;function bb(a){if(a in ab)return a;var b=a.charAt(0).toUpperCase()+a.slice(1),c=_a.length;while(c--)if(a=_a[c]+b,a in ab)return a}function cb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&W(d)&&(f[g]=n._data(d,"olddisplay",Ma(d.nodeName)))):(e=W(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function db(a,b,c){var d=Ya.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function eb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+V[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+V[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+V[f]+"Width",!0,e))):(g+=n.css(a,"padding"+V[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+V[f]+"Width",!0,e)));return g}function fb(b,c,e){var f=!0,g="width"===c?b.offsetWidth:b.offsetHeight,h=Ra(b),i=l.boxSizing&&"border-box"===n.css(b,"boxSizing",!1,h);if(d.msFullscreenElement&&a.top!==a&&b.getClientRects().length&&(g=Math.round(100*b.getBoundingClientRect()[c])),0>=g||null==g){if(g=Sa(b,c,h),(0>g||null==g)&&(g=b.style[c]),Oa.test(g))return g;f=i&&(l.boxSizingReliable()||g===b.style[c]),g=parseFloat(g)||0}return g+eb(b,c,e||(i?"border":"content"),f,h)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Sa(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=bb(h)||h),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=U.exec(c))&&e[1]&&(c=X(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(n.cssNumber[h]?"":"px")),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=bb(h)||h),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Sa(a,b,d)),"normal"===f&&b in $a&&(f=$a[b]),""===c||c?(e=parseFloat(f),c===!0||isFinite(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?Xa.test(n.css(a,"display"))&&0===a.offsetWidth?Pa(a,Za,function(){return fb(a,b,d)}):fb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ra(a);return db(a,c,d?eb(a,b,d,l.boxSizing&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Wa.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Va,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Va.test(f)?f.replace(Va,e):f+" "+e)}}),n.cssHooks.marginRight=Ua(l.reliableMarginRight,function(a,b){return b?Pa(a,{display:"inline-block"},Sa,[a,"marginRight"]):void 0}),n.cssHooks.marginLeft=Ua(l.reliableMarginLeft,function(a,b){
+return b?(parseFloat(Sa(a,"marginLeft"))||(n.contains(a.ownerDocument,a)?a.getBoundingClientRect().left-Pa(a,{marginLeft:0},function(){return a.getBoundingClientRect().left}):0))+"px":void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+V[d]+b]=f[d]||f[d-2]||f[0];return e}},Na.test(a)||(n.cssHooks[a+b].set=db)}),n.fn.extend({css:function(a,b){return Y(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Ra(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return cb(this,!0)},hide:function(){return cb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){W(this)?n(this).show():n(this).hide()})}});function gb(a,b,c,d,e){return new gb.prototype.init(a,b,c,d,e)}n.Tween=gb,gb.prototype={constructor:gb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||n.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=gb.propHooks[this.prop];return a&&a.get?a.get(this):gb.propHooks._default.get(this)},run:function(a){var b,c=gb.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):gb.propHooks._default.set(this),this}},gb.prototype.init.prototype=gb.prototype,gb.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[n.cssProps[a.prop]]&&!n.cssHooks[a.prop]?a.elem[a.prop]=a.now:n.style(a.elem,a.prop,a.now+a.unit)}}},gb.propHooks.scrollTop=gb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},n.fx=gb.prototype.init,n.fx.step={};var hb,ib,jb=/^(?:toggle|show|hide)$/,kb=/queueHooks$/;function lb(){return a.setTimeout(function(){hb=void 0}),hb=n.now()}function mb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=V[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function nb(a,b,c){for(var d,e=(qb.tweeners[b]||[]).concat(qb.tweeners["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ob(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&W(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k="none"===j?n._data(a,"olddisplay")||Ma(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==Ma(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],jb.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(o))"inline"===("none"===j?Ma(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=nb(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function pb(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function qb(a,b,c){var d,e,f=0,g=qb.prefilters.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=hb||lb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{},easing:n.easing._default},c),originalProperties:b,originalOptions:c,startTime:hb||lb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for(pb(k,j.opts.specialEasing);g>f;f++)if(d=qb.prefilters[f].call(j,a,k,j.opts))return n.isFunction(d.stop)&&(n._queueHooks(j.elem,j.opts.queue).stop=n.proxy(d.stop,d)),d;return n.map(k,nb,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(qb,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return X(c.elem,a,U.exec(b),c),c}]},tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.match(G);for(var c,d=0,e=a.length;e>d;d++)c=a[d],qb.tweeners[c]=qb.tweeners[c]||[],qb.tweeners[c].unshift(b)},prefilters:[ob],prefilter:function(a,b){b?qb.prefilters.unshift(a):qb.prefilters.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,null!=d.queue&&d.queue!==!0||(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(W).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=qb(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&kb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(mb(b,!0),a,d,e)}}),n.each({slideDown:mb("show"),slideUp:mb("hide"),slideToggle:mb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(hb=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),hb=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ib||(ib=a.setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){a.clearInterval(ib),ib=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(b,c){return b=n.fx?n.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a,b=d.createElement("input"),c=d.createElement("div"),e=d.createElement("select"),f=e.appendChild(d.createElement("option"));c=d.createElement("div"),c.setAttribute("className","t"),c.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],b.setAttribute("type","checkbox"),c.appendChild(b),a=c.getElementsByTagName("a")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==c.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=f.selected,l.enctype=!!d.createElement("form").enctype,e.disabled=!0,l.optDisabled=!f.disabled,b=d.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value}();var rb=/\r/g,sb=/[\x20\t\r\n\f]+/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(rb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a)).replace(sb," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],(c.selected||i===e)&&(l.optDisabled?!c.disabled:null===c.getAttribute("disabled"))&&(!c.parentNode.disabled||!n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>-1)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>-1:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var tb,ub,vb=n.expr.attrHandle,wb=/^(?:checked|selected)$/i,xb=l.getSetAttribute,yb=l.input;n.fn.extend({attr:function(a,b){return Y(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),e=n.attrHooks[b]||(n.expr.match.bool.test(b)?ub:tb)),void 0!==c?null===c?void n.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=n.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(G);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?yb&&xb||!wb.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(xb?c:d)}}),ub={set:function(a,b,c){return b===!1?n.removeAttr(a,c):yb&&xb||!wb.test(c)?a.setAttribute(!xb&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=vb[b]||n.find.attr;yb&&xb||!wb.test(b)?vb[b]=function(a,b,d){var e,f;return d||(f=vb[b],vb[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,vb[b]=f),e}:vb[b]=function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),yb&&xb||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):tb&&tb.set(a,b,c)}}),xb||(tb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},vb.id=vb.name=vb.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:tb.set},n.attrHooks.contenteditable={set:function(a,b,c){tb.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var zb=/^(?:input|select|textarea|button|object)$/i,Ab=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return Y(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&n.isXMLDoc(a)||(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):zb.test(a.nodeName)||Ab.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var Bb=/[\t\r\n\f]/g;function Cb(a){return n.attr(a,"class")||""}n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,Cb(this)))});if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=Cb(c),d=1===c.nodeType&&(" "+e+" ").replace(Bb," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=n.trim(d),e!==h&&n.attr(c,"class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,Cb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=Cb(c),d=1===c.nodeType&&(" "+e+" ").replace(Bb," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=n.trim(d),e!==h&&n.attr(c,"class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):n.isFunction(a)?this.each(function(c){n(this).toggleClass(a.call(this,c,Cb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=n(this),f=a.match(G)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=Cb(this),b&&n._data(this,"__className__",b),n.attr(this,"class",b||a===!1?"":n._data(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+Cb(c)+" ").replace(Bb," ").indexOf(b)>-1)return!0;return!1}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Db=a.location,Eb=n.now(),Fb=/\?/,Gb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(Gb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new a.DOMParser,c=d.parseFromString(b,"text/xml")):(c=new a.ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var Hb=/#.*$/,Ib=/([?&])_=[^&]*/,Jb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Kb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Lb=/^(?:GET|HEAD)$/,Mb=/^\/\//,Nb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ob={},Pb={},Qb="*/".concat("*"),Rb=Db.href,Sb=Nb.exec(Rb.toLowerCase())||[];function Tb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(G)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Ub(a,b,c,d){var e={},f=a===Pb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Vb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Wb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Xb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Rb,type:"GET",isLocal:Kb.test(Sb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Qb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Vb(Vb(a,n.ajaxSettings),b):Vb(n.ajaxSettings,a)},ajaxPrefilter:Tb(Ob),ajaxTransport:Tb(Pb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var d,e,f,g,h,i,j,k,l=n.ajaxSetup({},c),m=l.context||l,o=l.context&&(m.nodeType||m.jquery)?n(m):n.event,p=n.Deferred(),q=n.Callbacks("once memory"),r=l.statusCode||{},s={},t={},u=0,v="canceled",w={readyState:0,getResponseHeader:function(a){var b;if(2===u){if(!k){k={};while(b=Jb.exec(g))k[b[1].toLowerCase()]=b[2]}b=k[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===u?g:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return u||(a=t[c]=t[c]||a,s[a]=b),this},overrideMimeType:function(a){return u||(l.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>u)for(b in a)r[b]=[r[b],a[b]];else w.always(a[w.status]);return this},abort:function(a){var b=a||v;return j&&j.abort(b),y(0,b),this}};if(p.promise(w).complete=q.add,w.success=w.done,w.error=w.fail,l.url=((b||l.url||Rb)+"").replace(Hb,"").replace(Mb,Sb[1]+"//"),l.type=c.method||c.type||l.method||l.type,l.dataTypes=n.trim(l.dataType||"*").toLowerCase().match(G)||[""],null==l.crossDomain&&(d=Nb.exec(l.url.toLowerCase()),l.crossDomain=!(!d||d[1]===Sb[1]&&d[2]===Sb[2]&&(d[3]||("http:"===d[1]?"80":"443"))===(Sb[3]||("http:"===Sb[1]?"80":"443")))),l.data&&l.processData&&"string"!=typeof l.data&&(l.data=n.param(l.data,l.traditional)),Ub(Ob,l,c,w),2===u)return w;i=n.event&&l.global,i&&0===n.active++&&n.event.trigger("ajaxStart"),l.type=l.type.toUpperCase(),l.hasContent=!Lb.test(l.type),f=l.url,l.hasContent||(l.data&&(f=l.url+=(Fb.test(f)?"&":"?")+l.data,delete l.data),l.cache===!1&&(l.url=Ib.test(f)?f.replace(Ib,"$1_="+Eb++):f+(Fb.test(f)?"&":"?")+"_="+Eb++)),l.ifModified&&(n.lastModified[f]&&w.setRequestHeader("If-Modified-Since",n.lastModified[f]),n.etag[f]&&w.setRequestHeader("If-None-Match",n.etag[f])),(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&w.setRequestHeader("Content-Type",l.contentType),w.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+("*"!==l.dataTypes[0]?", "+Qb+"; q=0.01":""):l.accepts["*"]);for(e in l.headers)w.setRequestHeader(e,l.headers[e]);if(l.beforeSend&&(l.beforeSend.call(m,w,l)===!1||2===u))return w.abort();v="abort";for(e in{success:1,error:1,complete:1})w[e](l[e]);if(j=Ub(Pb,l,c,w)){if(w.readyState=1,i&&o.trigger("ajaxSend",[w,l]),2===u)return w;l.async&&l.timeout>0&&(h=a.setTimeout(function(){w.abort("timeout")},l.timeout));try{u=1,j.send(s,y)}catch(x){if(!(2>u))throw x;y(-1,x)}}else y(-1,"No Transport");function y(b,c,d,e){var k,s,t,v,x,y=c;2!==u&&(u=2,h&&a.clearTimeout(h),j=void 0,g=e||"",w.readyState=b>0?4:0,k=b>=200&&300>b||304===b,d&&(v=Wb(l,w,d)),v=Xb(l,v,w,k),k?(l.ifModified&&(x=w.getResponseHeader("Last-Modified"),x&&(n.lastModified[f]=x),x=w.getResponseHeader("etag"),x&&(n.etag[f]=x)),204===b||"HEAD"===l.type?y="nocontent":304===b?y="notmodified":(y=v.state,s=v.data,t=v.error,k=!t)):(t=y,!b&&y||(y="error",0>b&&(b=0))),w.status=b,w.statusText=(c||y)+"",k?p.resolveWith(m,[s,y,w]):p.rejectWith(m,[w,y,t]),w.statusCode(r),r=void 0,i&&o.trigger(k?"ajaxSuccess":"ajaxError",[w,l,k?s:t]),q.fireWith(m,[w,y]),i&&(o.trigger("ajaxComplete",[w,l]),--n.active||n.event.trigger("ajaxStop")))}return w},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax(n.extend({url:a,type:b,dataType:e,data:c,success:d},n.isPlainObject(a)&&a))}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return n.isFunction(a)?this.each(function(b){n(this).wrapInner(a.call(this,b))}):this.each(function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}});function Yb(a){return a.style&&a.style.display||n.css(a,"display")}function Zb(a){while(a&&1===a.nodeType){if("none"===Yb(a)||"hidden"===a.type)return!0;a=a.parentNode}return!1}n.expr.filters.hidden=function(a){return l.reliableHiddenOffsets()?a.offsetWidth<=0&&a.offsetHeight<=0&&!a.getClientRects().length:Zb(a)},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var $b=/%20/g,_b=/\[\]$/,ac=/\r?\n/g,bc=/^(?:submit|button|image|reset|file)$/i,cc=/^(?:input|select|textarea|keygen)/i;function dc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||_b.test(a)?d(a,e):dc(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)dc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)dc(c,a[c],b,e);return d.join("&").replace($b,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&cc.test(this.nodeName)&&!bc.test(a)&&(this.checked||!Z.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(ac,"\r\n")}}):{name:b.name,value:c.replace(ac,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return this.isLocal?ic():d.documentMode>8?hc():/^(get|post|head|put|delete|options)$/i.test(this.type)&&hc()||ic()}:hc;var ec=0,fc={},gc=n.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in fc)fc[a](void 0,!0)}),l.cors=!!gc&&"withCredentials"in gc,gc=l.ajax=!!gc,gc&&n.ajaxTransport(function(b){if(!b.crossDomain||l.cors){var c;return{send:function(d,e){var f,g=b.xhr(),h=++ec;if(g.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(f in b.xhrFields)g[f]=b.xhrFields[f];b.mimeType&&g.overrideMimeType&&g.overrideMimeType(b.mimeType),b.crossDomain||d["X-Requested-With"]||(d["X-Requested-With"]="XMLHttpRequest");for(f in d)void 0!==d[f]&&g.setRequestHeader(f,d[f]+"");g.send(b.hasContent&&b.data||null),c=function(a,d){var f,i,j;if(c&&(d||4===g.readyState))if(delete fc[h],c=void 0,g.onreadystatechange=n.noop,d)4!==g.readyState&&g.abort();else{j={},f=g.status,"string"==typeof g.responseText&&(j.text=g.responseText);try{i=g.statusText}catch(k){i=""}f||!b.isLocal||b.crossDomain?1223===f&&(f=204):f=j.text?200:404}j&&e(f,i,j,g.getAllResponseHeaders())},b.async?4===g.readyState?a.setTimeout(c):g.onreadystatechange=fc[h]=c:c()},abort:function(){c&&c(void 0,!0)}}}});function hc(){try{return new a.XMLHttpRequest}catch(b){}}function ic(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=d.head||n("head")[0]||d.documentElement;return{send:function(e,f){b=d.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||f(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var jc=[],kc=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=jc.pop()||n.expando+"_"+Eb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(kc.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&kc.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(kc,"$1"+e):b.jsonp!==!1&&(b.url+=(Fb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?n(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,jc.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||d;var e=x.exec(a),f=!c&&[];return e?[b.createElement(e[1])]:(e=ja([a],b,f),f&&f.length&&n(f).remove(),n.merge([],e.childNodes))};var lc=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&lc)return lc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=n.trim(a.slice(h,a.length)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};function mc(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,n.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?("undefined"!=typeof e.getBoundingClientRect&&(d=e.getBoundingClientRect()),c=mc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Qa})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return Y(this,function(a,d,e){var f=mc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Ua(l.pixelPosition,function(a,c){return c?(c=Sa(a,b),Oa.test(c)?n(a).position()[b]+"px":c):void 0;
+})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return Y(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var nc=a.jQuery,oc=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=oc),b&&a.jQuery===n&&(a.jQuery=nc),n},b||(a.jQuery=a.$=n),n});
--- a/kallithea/public/js/mousetrap.js	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,931 +0,0 @@
-/*global define:false */
-/**
- * Copyright 2013 Craig Campbell
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * Mousetrap is a simple keyboard shortcut library for Javascript with
- * no external dependencies
- *
- * @version 1.4.5
- * @url craig.is/killing/mice
- */
-(function(window, document, undefined) {
-
-    /**
-     * mapping of special keycodes to their corresponding keys
-     *
-     * everything in this dictionary cannot use keypress events
-     * so it has to be here to map to the correct keycodes for
-     * keyup/keydown events
-     *
-     * @type {Object}
-     */
-    var _MAP = {
-            8: 'backspace',
-            9: 'tab',
-            13: 'enter',
-            16: 'shift',
-            17: 'ctrl',
-            18: 'alt',
-            20: 'capslock',
-            27: 'esc',
-            32: 'space',
-            33: 'pageup',
-            34: 'pagedown',
-            35: 'end',
-            36: 'home',
-            37: 'left',
-            38: 'up',
-            39: 'right',
-            40: 'down',
-            45: 'ins',
-            46: 'del',
-            91: 'meta',
-            93: 'meta',
-            224: 'meta'
-        },
-
-        /**
-         * mapping for special characters so they can support
-         *
-         * this dictionary is only used incase you want to bind a
-         * keyup or keydown event to one of these keys
-         *
-         * @type {Object}
-         */
-        _KEYCODE_MAP = {
-            106: '*',
-            107: '+',
-            109: '-',
-            110: '.',
-            111 : '/',
-            186: ';',
-            187: '=',
-            188: ',',
-            189: '-',
-            190: '.',
-            191: '/',
-            192: '`',
-            219: '[',
-            220: '\\',
-            221: ']',
-            222: '\''
-        },
-
-        /**
-         * this is a mapping of keys that require shift on a US keypad
-         * back to the non shift equivelents
-         *
-         * this is so you can use keyup events with these keys
-         *
-         * note that this will only work reliably on US keyboards
-         *
-         * @type {Object}
-         */
-        _SHIFT_MAP = {
-            '~': '`',
-            '!': '1',
-            '@': '2',
-            '#': '3',
-            '$': '4',
-            '%': '5',
-            '^': '6',
-            '&': '7',
-            '*': '8',
-            '(': '9',
-            ')': '0',
-            '_': '-',
-            '+': '=',
-            ':': ';',
-            '\"': '\'',
-            '<': ',',
-            '>': '.',
-            '?': '/',
-            '|': '\\'
-        },
-
-        /**
-         * this is a list of special strings you can use to map
-         * to modifier keys when you specify your keyboard shortcuts
-         *
-         * @type {Object}
-         */
-        _SPECIAL_ALIASES = {
-            'option': 'alt',
-            'command': 'meta',
-            'return': 'enter',
-            'escape': 'esc',
-            'mod': /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? 'meta' : 'ctrl'
-        },
-
-        /**
-         * variable to store the flipped version of _MAP from above
-         * needed to check if we should use keypress or not when no action
-         * is specified
-         *
-         * @type {Object|undefined}
-         */
-        _REVERSE_MAP,
-
-        /**
-         * a list of all the callbacks setup via Mousetrap.bind()
-         *
-         * @type {Object}
-         */
-        _callbacks = {},
-
-        /**
-         * direct map of string combinations to callbacks used for trigger()
-         *
-         * @type {Object}
-         */
-        _directMap = {},
-
-        /**
-         * keeps track of what level each sequence is at since multiple
-         * sequences can start out with the same sequence
-         *
-         * @type {Object}
-         */
-        _sequenceLevels = {},
-
-        /**
-         * variable to store the setTimeout call
-         *
-         * @type {null|number}
-         */
-        _resetTimer,
-
-        /**
-         * temporary state where we will ignore the next keyup
-         *
-         * @type {boolean|string}
-         */
-        _ignoreNextKeyup = false,
-
-        /**
-         * temporary state where we will ignore the next keypress
-         *
-         * @type {boolean}
-         */
-        _ignoreNextKeypress = false,
-
-        /**
-         * are we currently inside of a sequence?
-         * type of action ("keyup" or "keydown" or "keypress") or false
-         *
-         * @type {boolean|string}
-         */
-        _nextExpectedAction = false;
-
-    /**
-     * loop through the f keys, f1 to f19 and add them to the map
-     * programatically
-     */
-    for (var i = 1; i < 20; ++i) {
-        _MAP[111 + i] = 'f' + i;
-    }
-
-    /**
-     * loop through to map numbers on the numeric keypad
-     */
-    for (i = 0; i <= 9; ++i) {
-        _MAP[i + 96] = i;
-    }
-
-    /**
-     * cross browser add event method
-     *
-     * @param {Element|HTMLDocument} object
-     * @param {string} type
-     * @param {Function} callback
-     * @returns void
-     */
-    function _addEvent(object, type, callback) {
-        if (object.addEventListener) {
-            object.addEventListener(type, callback, false);
-            return;
-        }
-
-        object.attachEvent('on' + type, callback);
-    }
-
-    /**
-     * takes the event and returns the key character
-     *
-     * @param {Event} e
-     * @return {string}
-     */
-    function _characterFromEvent(e) {
-
-        // for keypress events we should return the character as is
-        if (e.type == 'keypress') {
-            var character = String.fromCharCode(e.which);
-
-            // if the shift key is not pressed then it is safe to assume
-            // that we want the character to be lowercase.  this means if
-            // you accidentally have caps lock on then your key bindings
-            // will continue to work
-            //
-            // the only side effect that might not be desired is if you
-            // bind something like 'A' cause you want to trigger an
-            // event when capital A is pressed caps lock will no longer
-            // trigger the event.  shift+a will though.
-            if (!e.shiftKey) {
-                character = character.toLowerCase();
-            }
-
-            return character;
-        }
-
-        // for non keypress events the special maps are needed
-        if (_MAP[e.which]) {
-            return _MAP[e.which];
-        }
-
-        if (_KEYCODE_MAP[e.which]) {
-            return _KEYCODE_MAP[e.which];
-        }
-
-        // if it is not in the special map
-
-        // with keydown and keyup events the character seems to always
-        // come in as an uppercase character whether you are pressing shift
-        // or not.  we should make sure it is always lowercase for comparisons
-        return String.fromCharCode(e.which).toLowerCase();
-    }
-
-    /**
-     * checks if two arrays are equal
-     *
-     * @param {Array} modifiers1
-     * @param {Array} modifiers2
-     * @returns {boolean}
-     */
-    function _modifiersMatch(modifiers1, modifiers2) {
-        return modifiers1.sort().join(',') === modifiers2.sort().join(',');
-    }
-
-    /**
-     * resets all sequence counters except for the ones passed in
-     *
-     * @param {Object} doNotReset
-     * @returns void
-     */
-    function _resetSequences(doNotReset) {
-        doNotReset = doNotReset || {};
-
-        var activeSequences = false,
-            key;
-
-        for (key in _sequenceLevels) {
-            if (doNotReset[key]) {
-                activeSequences = true;
-                continue;
-            }
-            _sequenceLevels[key] = 0;
-        }
-
-        if (!activeSequences) {
-            _nextExpectedAction = false;
-        }
-    }
-
-    /**
-     * finds all callbacks that match based on the keycode, modifiers,
-     * and action
-     *
-     * @param {string} character
-     * @param {Array} modifiers
-     * @param {Event|Object} e
-     * @param {string=} sequenceName - name of the sequence we are looking for
-     * @param {string=} combination
-     * @param {number=} level
-     * @returns {Array}
-     */
-    function _getMatches(character, modifiers, e, sequenceName, combination, level) {
-        var i,
-            callback,
-            matches = [],
-            action = e.type;
-
-        // if there are no events related to this keycode
-        if (!_callbacks[character]) {
-            return [];
-        }
-
-        // if a modifier key is coming up on its own we should allow it
-        if (action == 'keyup' && _isModifier(character)) {
-            modifiers = [character];
-        }
-
-        // loop through all callbacks for the key that was pressed
-        // and see if any of them match
-        for (i = 0; i < _callbacks[character].length; ++i) {
-            callback = _callbacks[character][i];
-
-            // if a sequence name is not specified, but this is a sequence at
-            // the wrong level then move onto the next match
-            if (!sequenceName && callback.seq && _sequenceLevels[callback.seq] != callback.level) {
-                continue;
-            }
-
-            // if the action we are looking for doesn't match the action we got
-            // then we should keep going
-            if (action != callback.action) {
-                continue;
-            }
-
-            // if this is a keypress event and the meta key and control key
-            // are not pressed that means that we need to only look at the
-            // character, otherwise check the modifiers as well
-            //
-            // chrome will not fire a keypress if meta or control is down
-            // safari will fire a keypress if meta or meta+shift is down
-            // firefox will fire a keypress if meta or control is down
-            if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) {
-
-                // when you bind a combination or sequence a second time it
-                // should overwrite the first one.  if a sequenceName or
-                // combination is specified in this call it does just that
-                //
-                // @todo make deleting its own method?
-                var deleteCombo = !sequenceName && callback.combo == combination;
-                var deleteSequence = sequenceName && callback.seq == sequenceName && callback.level == level;
-                if (deleteCombo || deleteSequence) {
-                    _callbacks[character].splice(i, 1);
-                }
-
-                matches.push(callback);
-            }
-        }
-
-        return matches;
-    }
-
-    /**
-     * takes a key event and figures out what the modifiers are
-     *
-     * @param {Event} e
-     * @returns {Array}
-     */
-    function _eventModifiers(e) {
-        var modifiers = [];
-
-        if (e.shiftKey) {
-            modifiers.push('shift');
-        }
-
-        if (e.altKey) {
-            modifiers.push('alt');
-        }
-
-        if (e.ctrlKey) {
-            modifiers.push('ctrl');
-        }
-
-        if (e.metaKey) {
-            modifiers.push('meta');
-        }
-
-        return modifiers;
-    }
-
-    /**
-     * actually calls the callback function
-     *
-     * if your callback function returns false this will use the jquery
-     * convention - prevent default and stop propogation on the event
-     *
-     * @param {Function} callback
-     * @param {Event} e
-     * @returns void
-     */
-    function _fireCallback(callback, e, combo) {
-
-        // if this event should not happen stop here
-        if (Mousetrap.stopCallback(e, e.target || e.srcElement, combo)) {
-            return;
-        }
-
-        if (callback(e, combo) === false) {
-            if (e.preventDefault) {
-                e.preventDefault();
-            }
-
-            if (e.stopPropagation) {
-                e.stopPropagation();
-            }
-
-            e.returnValue = false;
-            e.cancelBubble = true;
-        }
-    }
-
-    /**
-     * handles a character key event
-     *
-     * @param {string} character
-     * @param {Array} modifiers
-     * @param {Event} e
-     * @returns void
-     */
-    function _handleKey(character, modifiers, e) {
-        var callbacks = _getMatches(character, modifiers, e),
-            i,
-            doNotReset = {},
-            maxLevel = 0,
-            processedSequenceCallback = false;
-
-        // Calculate the maxLevel for sequences so we can only execute the longest callback sequence
-        for (i = 0; i < callbacks.length; ++i) {
-            if (callbacks[i].seq) {
-                maxLevel = Math.max(maxLevel, callbacks[i].level);
-            }
-        }
-
-        // loop through matching callbacks for this key event
-        for (i = 0; i < callbacks.length; ++i) {
-
-            // fire for all sequence callbacks
-            // this is because if for example you have multiple sequences
-            // bound such as "g i" and "g t" they both need to fire the
-            // callback for matching g cause otherwise you can only ever
-            // match the first one
-            if (callbacks[i].seq) {
-
-                // only fire callbacks for the maxLevel to prevent
-                // subsequences from also firing
-                //
-                // for example 'a option b' should not cause 'option b' to fire
-                // even though 'option b' is part of the other sequence
-                //
-                // any sequences that do not match here will be discarded
-                // below by the _resetSequences call
-                if (callbacks[i].level != maxLevel) {
-                    continue;
-                }
-
-                processedSequenceCallback = true;
-
-                // keep a list of which sequences were matches for later
-                doNotReset[callbacks[i].seq] = 1;
-                _fireCallback(callbacks[i].callback, e, callbacks[i].combo);
-                continue;
-            }
-
-            // if there were no sequence matches but we are still here
-            // that means this is a regular match so we should fire that
-            if (!processedSequenceCallback) {
-                _fireCallback(callbacks[i].callback, e, callbacks[i].combo);
-            }
-        }
-
-        // if the key you pressed matches the type of sequence without
-        // being a modifier (ie "keyup" or "keypress") then we should
-        // reset all sequences that were not matched by this event
-        //
-        // this is so, for example, if you have the sequence "h a t" and you
-        // type "h e a r t" it does not match.  in this case the "e" will
-        // cause the sequence to reset
-        //
-        // modifier keys are ignored because you can have a sequence
-        // that contains modifiers such as "enter ctrl+space" and in most
-        // cases the modifier key will be pressed before the next key
-        //
-        // also if you have a sequence such as "ctrl+b a" then pressing the
-        // "b" key will trigger a "keypress" and a "keydown"
-        //
-        // the "keydown" is expected when there is a modifier, but the
-        // "keypress" ends up matching the _nextExpectedAction since it occurs
-        // after and that causes the sequence to reset
-        //
-        // we ignore keypresses in a sequence that directly follow a keydown
-        // for the same character
-        var ignoreThisKeypress = e.type == 'keypress' && _ignoreNextKeypress;
-        if (e.type == _nextExpectedAction && !_isModifier(character) && !ignoreThisKeypress) {
-            _resetSequences(doNotReset);
-        }
-
-        _ignoreNextKeypress = processedSequenceCallback && e.type == 'keydown';
-    }
-
-    /**
-     * handles a keydown event
-     *
-     * @param {Event} e
-     * @returns void
-     */
-    function _handleKeyEvent(e) {
-
-        // normalize e.which for key events
-        // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
-        if (typeof e.which !== 'number') {
-            e.which = e.keyCode;
-        }
-
-        var character = _characterFromEvent(e);
-
-        // no character found then stop
-        if (!character) {
-            return;
-        }
-
-        // need to use === for the character check because the character can be 0
-        if (e.type == 'keyup' && _ignoreNextKeyup === character) {
-            _ignoreNextKeyup = false;
-            return;
-        }
-
-        Mousetrap.handleKey(character, _eventModifiers(e), e);
-    }
-
-    /**
-     * determines if the keycode specified is a modifier key or not
-     *
-     * @param {string} key
-     * @returns {boolean}
-     */
-    function _isModifier(key) {
-        return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
-    }
-
-    /**
-     * called to set a 1 second timeout on the specified sequence
-     *
-     * this is so after each key press in the sequence you have 1 second
-     * to press the next key before you have to start over
-     *
-     * @returns void
-     */
-    function _resetSequenceTimer() {
-        clearTimeout(_resetTimer);
-        _resetTimer = setTimeout(_resetSequences, 1000);
-    }
-
-    /**
-     * reverses the map lookup so that we can look for specific keys
-     * to see what can and can't use keypress
-     *
-     * @return {Object}
-     */
-    function _getReverseMap() {
-        if (!_REVERSE_MAP) {
-            _REVERSE_MAP = {};
-            for (var key in _MAP) {
-
-                // pull out the numeric keypad from here cause keypress should
-                // be able to detect the keys from the character
-                if (key > 95 && key < 112) {
-                    continue;
-                }
-
-                if (_MAP.hasOwnProperty(key)) {
-                    _REVERSE_MAP[_MAP[key]] = key;
-                }
-            }
-        }
-        return _REVERSE_MAP;
-    }
-
-    /**
-     * picks the best action based on the key combination
-     *
-     * @param {string} key - character for key
-     * @param {Array} modifiers
-     * @param {string=} action passed in
-     */
-    function _pickBestAction(key, modifiers, action) {
-
-        // if no action was picked in we should try to pick the one
-        // that we think would work best for this key
-        if (!action) {
-            action = _getReverseMap()[key] ? 'keydown' : 'keypress';
-        }
-
-        // modifier keys don't work as expected with keypress,
-        // switch to keydown
-        if (action == 'keypress' && modifiers.length) {
-            action = 'keydown';
-        }
-
-        return action;
-    }
-
-    /**
-     * binds a key sequence to an event
-     *
-     * @param {string} combo - combo specified in bind call
-     * @param {Array} keys
-     * @param {Function} callback
-     * @param {string=} action
-     * @returns void
-     */
-    function _bindSequence(combo, keys, callback, action) {
-
-        // start off by adding a sequence level record for this combination
-        // and setting the level to 0
-        _sequenceLevels[combo] = 0;
-
-        /**
-         * callback to increase the sequence level for this sequence and reset
-         * all other sequences that were active
-         *
-         * @param {string} nextAction
-         * @returns {Function}
-         */
-        function _increaseSequence(nextAction) {
-            return function() {
-                _nextExpectedAction = nextAction;
-                ++_sequenceLevels[combo];
-                _resetSequenceTimer();
-            };
-        }
-
-        /**
-         * wraps the specified callback inside of another function in order
-         * to reset all sequence counters as soon as this sequence is done
-         *
-         * @param {Event} e
-         * @returns void
-         */
-        function _callbackAndReset(e) {
-            _fireCallback(callback, e, combo);
-
-            // we should ignore the next key up if the action is key down
-            // or keypress.  this is so if you finish a sequence and
-            // release the key the final key will not trigger a keyup
-            if (action !== 'keyup') {
-                _ignoreNextKeyup = _characterFromEvent(e);
-            }
-
-            // weird race condition if a sequence ends with the key
-            // another sequence begins with
-            setTimeout(_resetSequences, 10);
-        }
-
-        // loop through keys one at a time and bind the appropriate callback
-        // function.  for any key leading up to the final one it should
-        // increase the sequence. after the final, it should reset all sequences
-        //
-        // if an action is specified in the original bind call then that will
-        // be used throughout.  otherwise we will pass the action that the
-        // next key in the sequence should match.  this allows a sequence
-        // to mix and match keypress and keydown events depending on which
-        // ones are better suited to the key provided
-        for (var i = 0; i < keys.length; ++i) {
-            var isFinal = i + 1 === keys.length;
-            var wrappedCallback = isFinal ? _callbackAndReset : _increaseSequence(action || _getKeyInfo(keys[i + 1]).action);
-            _bindSingle(keys[i], wrappedCallback, action, combo, i);
-        }
-    }
-
-    /**
-     * Converts from a string key combination to an array
-     *
-     * @param  {string} combination like "command+shift+l"
-     * @return {Array}
-     */
-    function _keysFromString(combination) {
-        if (combination === '+') {
-            return ['+'];
-        }
-
-        return combination.split('+');
-    }
-
-    /**
-     * Gets info for a specific key combination
-     *
-     * @param  {string} combination key combination ("command+s" or "a" or "*")
-     * @param  {string=} action
-     * @returns {Object}
-     */
-    function _getKeyInfo(combination, action) {
-        var keys,
-            key,
-            i,
-            modifiers = [];
-
-        // take the keys from this pattern and figure out what the actual
-        // pattern is all about
-        keys = _keysFromString(combination);
-
-        for (i = 0; i < keys.length; ++i) {
-            key = keys[i];
-
-            // normalize key names
-            if (_SPECIAL_ALIASES[key]) {
-                key = _SPECIAL_ALIASES[key];
-            }
-
-            // if this is not a keypress event then we should
-            // be smart about using shift keys
-            // this will only work for US keyboards however
-            if (action && action != 'keypress' && _SHIFT_MAP[key]) {
-                key = _SHIFT_MAP[key];
-                modifiers.push('shift');
-            }
-
-            // if this key is a modifier then add it to the list of modifiers
-            if (_isModifier(key)) {
-                modifiers.push(key);
-            }
-        }
-
-        // depending on what the key combination is
-        // we will try to pick the best event for it
-        action = _pickBestAction(key, modifiers, action);
-
-        return {
-            key: key,
-            modifiers: modifiers,
-            action: action
-        };
-    }
-
-    /**
-     * binds a single keyboard combination
-     *
-     * @param {string} combination
-     * @param {Function} callback
-     * @param {string=} action
-     * @param {string=} sequenceName - name of sequence if part of sequence
-     * @param {number=} level - what part of the sequence the command is
-     * @returns void
-     */
-    function _bindSingle(combination, callback, action, sequenceName, level) {
-
-        // store a direct mapped reference for use with Mousetrap.trigger
-        _directMap[combination + ':' + action] = callback;
-
-        // make sure multiple spaces in a row become a single space
-        combination = combination.replace(/\s+/g, ' ');
-
-        var sequence = combination.split(' '),
-            info;
-
-        // if this pattern is a sequence of keys then run through this method
-        // to reprocess each pattern one key at a time
-        if (sequence.length > 1) {
-            _bindSequence(combination, sequence, callback, action);
-            return;
-        }
-
-        info = _getKeyInfo(combination, action);
-
-        // make sure to initialize array if this is the first time
-        // a callback is added for this key
-        _callbacks[info.key] = _callbacks[info.key] || [];
-
-        // remove an existing match if there is one
-        _getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level);
-
-        // add this call back to the array
-        // if it is a sequence put it at the beginning
-        // if not put it at the end
-        //
-        // this is important because the way these are processed expects
-        // the sequence ones to come first
-        _callbacks[info.key][sequenceName ? 'unshift' : 'push']({
-            callback: callback,
-            modifiers: info.modifiers,
-            action: info.action,
-            seq: sequenceName,
-            level: level,
-            combo: combination
-        });
-    }
-
-    /**
-     * binds multiple combinations to the same callback
-     *
-     * @param {Array} combinations
-     * @param {Function} callback
-     * @param {string|undefined} action
-     * @returns void
-     */
-    function _bindMultiple(combinations, callback, action) {
-        for (var i = 0; i < combinations.length; ++i) {
-            _bindSingle(combinations[i], callback, action);
-        }
-    }
-
-    // start!
-    _addEvent(document, 'keypress', _handleKeyEvent);
-    _addEvent(document, 'keydown', _handleKeyEvent);
-    _addEvent(document, 'keyup', _handleKeyEvent);
-
-    var Mousetrap = {
-
-        /**
-         * binds an event to mousetrap
-         *
-         * can be a single key, a combination of keys separated with +,
-         * an array of keys, or a sequence of keys separated by spaces
-         *
-         * be sure to list the modifier keys first to make sure that the
-         * correct key ends up getting bound (the last key in the pattern)
-         *
-         * @param {string|Array} keys
-         * @param {Function} callback
-         * @param {string=} action - 'keypress', 'keydown', or 'keyup'
-         * @returns void
-         */
-        bind: function(keys, callback, action) {
-            keys = keys instanceof Array ? keys : [keys];
-            _bindMultiple(keys, callback, action);
-            return this;
-        },
-
-        /**
-         * unbinds an event to mousetrap
-         *
-         * the unbinding sets the callback function of the specified key combo
-         * to an empty function and deletes the corresponding key in the
-         * _directMap dict.
-         *
-         * TODO: actually remove this from the _callbacks dictionary instead
-         * of binding an empty function
-         *
-         * the keycombo+action has to be exactly the same as
-         * it was defined in the bind method
-         *
-         * @param {string|Array} keys
-         * @param {string} action
-         * @returns void
-         */
-        unbind: function(keys, action) {
-            return Mousetrap.bind(keys, function() {}, action);
-        },
-
-        /**
-         * triggers an event that has already been bound
-         *
-         * @param {string} keys
-         * @param {string=} action
-         * @returns void
-         */
-        trigger: function(keys, action) {
-            if (_directMap[keys + ':' + action]) {
-                _directMap[keys + ':' + action]({}, keys);
-            }
-            return this;
-        },
-
-        /**
-         * resets the library back to its initial state.  this is useful
-         * if you want to clear out the current keyboard shortcuts and bind
-         * new ones - for example if you switch to another page
-         *
-         * @returns void
-         */
-        reset: function() {
-            _callbacks = {};
-            _directMap = {};
-            return this;
-        },
-
-       /**
-        * should we stop this event before firing off callbacks
-        *
-        * @param {Event} e
-        * @param {Element} element
-        * @return {boolean}
-        */
-        stopCallback: function(e, element) {
-
-            // if the element has the class "mousetrap" then no need to stop
-            if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
-                return false;
-            }
-
-            // stop for input, select, and textarea
-            return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA' || element.isContentEditable;
-        },
-
-        /**
-         * exposes _handleKey publicly so it can be overwritten by extensions
-         */
-        handleKey: _handleKey
-    };
-
-    // expose mousetrap to the global object
-    window.Mousetrap = Mousetrap;
-
-    // expose mousetrap as an AMD module
-    if (typeof define === 'function' && define.amd) {
-        define(Mousetrap);
-    }
-}) (window, document);
--- a/kallithea/public/js/select2/select2.css	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/public/js/select2/select2.css	Fri Nov 18 01:11:13 2016 +0100
@@ -1,13 +1,10 @@
 /*
-Version: 3.5.0 Timestamp: Mon Jun 16 19:29:44 EDT 2014
+Version: 3.5.4 Timestamp: Sun Aug 30 13:30:32 EDT 2015
 */
 .select2-container {
     margin: 0;
     position: relative;
     display: inline-block;
-    /* inline-block for ie7 */
-    zoom: 1;
-    *display: inline;
     vertical-align: middle;
 }
 
@@ -180,10 +177,6 @@
     width: auto;
 }
 
-.select2-drop-auto-width .select2-search {
-    padding-top: 4px;
-}
-
 .select2-container .select2-choice .select2-arrow {
     display: inline-block;
     width: 18px;
@@ -230,8 +223,7 @@
     width: 100%;
     min-height: 26px;
     margin: 0;
-    padding-left: 4px;
-    padding-right: 4px;
+    padding: 4px 4px 0 4px;
 
     position: relative;
     z-index: 10000;
@@ -273,10 +265,6 @@
     background: url('select2.png') no-repeat -37px -22px, linear-gradient(to bottom, #fff 85%, #eee 99%) 0 0;
 }
 
-.select2-drop.select2-drop-above .select2-search input {
-    margin-top: 4px;
-}
-
 .select2-search input.select2-active {
     background: #fff url('select2-spinner.gif') no-repeat 100%;
     background: url('select2-spinner.gif') no-repeat 100%, -webkit-gradient(linear, left bottom, left top, color-stop(0.85, #fff), color-stop(0.99, #eee));
@@ -422,9 +410,9 @@
     color: #000;
 }
 
-
 .select2-results .select2-no-results,
 .select2-results .select2-searching,
+.select2-results .select2-ajax-error,
 .select2-results .select2-selection-limit {
     background: #f4f4f4;
     display: list-item;
@@ -454,6 +442,10 @@
     background: #f4f4f4 url('select2-spinner.gif') no-repeat 100%;
 }
 
+.select2-results .select2-ajax-error {
+    background: rgba(255, 50, 50, .2);
+}
+
 .select2-more-results {
     background: #f4f4f4;
     display: list-item;
@@ -582,7 +574,7 @@
     background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(20%, #f4f4f4), color-stop(50%, #f0f0f0), color-stop(52%, #e8e8e8), color-stop(100%, #eee));
     background-image: -webkit-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eee 100%);
     background-image: -moz-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eee 100%);
-    background-image: linear-gradient(to top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eee 100%);
+    background-image: linear-gradient(to bottom, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eee 100%);
 }
 html[dir="rtl"] .select2-container-multi .select2-choices .select2-search-choice
 {
--- a/kallithea/public/js/select2/select2.js	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/public/js/select2/select2.js	Fri Nov 18 01:11:13 2016 +0100
@@ -1,7 +1,7 @@
 /*
 Copyright 2012 Igor Vaynberg
 
-Version: 3.5.0 Timestamp: Mon Jun 16 19:29:44 EDT 2014
+Version: 3.5.4 Timestamp: Sun Aug 30 13:30:32 EDT 2015
 
 This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
 General Public License version 2 (the "GPL License"). You may choose either license to govern your
@@ -46,7 +46,7 @@
         return;
     }
 
-    var KEY, AbstractSelect2, SingleSelect2, MultiSelect2, nextUid, sizer,
+    var AbstractSelect2, SingleSelect2, MultiSelect2, nextUid, sizer,
         lastMousePosition={x:0,y:0}, $document, scrollBarDimensions,
 
     KEY = {
@@ -132,7 +132,7 @@
 
     function measureScrollbar () {
         var $template = $( MEASURE_SCROLLBAR_TEMPLATE );
-        $template.appendTo('body');
+        $template.appendTo(document.body);
 
         var dim = {
             width: $template.width() - $template[0].clientWidth,
@@ -160,16 +160,16 @@
     }
 
     /**
-     * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
+     * Splits the string into an array of values, transforming each value. An empty array is returned for nulls or empty
      * strings
      * @param string
      * @param separator
      */
-    function splitVal(string, separator) {
+    function splitVal(string, separator, transform) {
         var val, i, l;
         if (string === null || string.length < 1) return [];
         val = string.split(separator);
-        for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
+        for (i = 0, l = val.length; i < l; i = i + 1) val[i] = transform(val[i]);
         return val;
     }
 
@@ -311,7 +311,7 @@
                 whiteSpace: "nowrap"
             });
             sizer.attr("class","select2-sizer");
-            $("body").append(sizer);
+            $(document.body).append(sizer);
         }
         sizer.text(e.val());
         return sizer.width();
@@ -444,6 +444,16 @@
                         // added query as third paramter to keep backwards compatibility
                         var results = options.results(data, query.page, query);
                         query.callback(results);
+                    },
+                    error: function(jqXHR, textStatus, errorThrown){
+                        var results = {
+                            hasError: true,
+                            jqXHR: jqXHR,
+                            textStatus: textStatus,
+                            errorThrown: errorThrown
+                        };
+
+                        query.callback(results);
                     }
                 });
                 handler = transport.call(self, params);
@@ -689,12 +699,15 @@
 
             this.container = this.createContainer();
 
-            this.liveRegion = $("<span>", {
-                    role: "status",
-                    "aria-live": "polite"
-                })
-                .addClass("select2-hidden-accessible")
-                .appendTo(document.body);
+            this.liveRegion = $('.select2-hidden-accessible');
+            if (this.liveRegion.length == 0) {
+                this.liveRegion = $("<span>", {
+                        role: "status",
+                        "aria-live": "polite"
+                    })
+                    .addClass("select2-hidden-accessible")
+                    .appendTo(document.body);
+            }
 
             this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid());
             this.containerEventName= this.containerId
@@ -704,7 +717,7 @@
 
             this.container.attr("title", opts.element.attr("title"));
 
-            this.body = $("body");
+            this.body = $(document.body);
 
             syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
 
@@ -801,7 +814,7 @@
             // focusin can cause focus wars between modals and select2 since the dropdown is outside the modal.
             this.dropdown.on("click mouseup mousedown touchstart touchend focusin", function (e) { e.stopPropagation(); });
 
-            this.nextSearchTerm = undefined;
+            this.lastSearchTerm = undefined;
 
             if ($.isFunction(this.opts.initSelection)) {
                 // initialize selection based on the current value of the source element
@@ -836,13 +849,15 @@
 
         // abstract
         destroy: function () {
-            var element=this.opts.element, select2 = element.data("select2");
+            var element=this.opts.element, select2 = element.data("select2"), self = this;
 
             this.close();
 
-            if (element.length && element[0].detachEvent) {
+            if (element.length && element[0].detachEvent && self._sync) {
                 element.each(function () {
-                    this.detachEvent("onpropertychange", this._sync);
+                    if (self._sync) {
+                        this.detachEvent("onpropertychange", self._sync);
+                    }
                 });
             }
             if (this.propertyObserver) {
@@ -855,17 +870,21 @@
                 select2.container.remove();
                 select2.liveRegion.remove();
                 select2.dropdown.remove();
-                element
-                    .removeClass("select2-offscreen")
-                    .removeData("select2")
-                    .off(".select2")
-                    .prop("autofocus", this.autofocus || false);
-                if (this.elementTabIndex) {
-                    element.attr({tabindex: this.elementTabIndex});
+                element.removeData("select2")
+                    .off(".select2");
+                if (!element.is("input[type='hidden']")) {
+                    element
+                        .show()
+                        .prop("autofocus", this.autofocus || false);
+                    if (this.elementTabIndex) {
+                        element.attr({tabindex: this.elementTabIndex});
+                    } else {
+                        element.removeAttr("tabindex");
+                    }
+                    element.show();
                 } else {
-                    element.removeAttr("tabindex");
+                    element.css("display", "");
                 }
-                element.show();
             }
 
             cleanupJQueryElements.call(this,
@@ -917,6 +936,155 @@
                 });
             }
 
+            opts.debug = opts.debug || $.fn.select2.defaults.debug;
+
+            // Warnings for options renamed/removed in Select2 4.0.0
+            // Only when it's enabled through debug mode
+            if (opts.debug && console && console.warn) {
+                // id was removed
+                if (opts.id != null) {
+                    console.warn(
+                        'Select2: The `id` option has been removed in Select2 4.0.0, ' +
+                        'consider renaming your `id` property or mapping the property before your data makes it to Select2. ' +
+                        'You can read more at https://select2.github.io/announcements-4.0.html#changed-id'
+                    );
+                }
+
+                // text was removed
+                if (opts.text != null) {
+                    console.warn(
+                        'Select2: The `text` option has been removed in Select2 4.0.0, ' +
+                        'consider renaming your `text` property or mapping the property before your data makes it to Select2. ' +
+                        'You can read more at https://select2.github.io/announcements-4.0.html#changed-id'
+                    );
+                }
+
+                // sortResults was renamed to results
+                if (opts.sortResults != null) {
+                    console.warn(
+                        'Select2: the `sortResults` option has been renamed to `sorter` in Select2 4.0.0. '
+                    );
+                }
+
+                // selectOnBlur was renamed to selectOnClose
+                if (opts.selectOnBlur != null) {
+                    console.warn(
+                        'Select2: The `selectOnBlur` option has been renamed to `selectOnClose` in Select2 4.0.0.'
+                    );
+                }
+
+                // ajax.results was renamed to ajax.processResults
+                if (opts.ajax != null && opts.ajax.results != null) {
+                    console.warn(
+                        'Select2: The `ajax.results` option has been renamed to `ajax.processResults` in Select2 4.0.0.'
+                    );
+                }
+
+                // format* options were renamed to language.*
+                if (opts.formatNoResults != null) {
+                    console.warn(
+                        'Select2: The `formatNoResults` option has been renamed to `language.noResults` in Select2 4.0.0.'
+                    );
+                }
+                if (opts.formatSearching != null) {
+                    console.warn(
+                        'Select2: The `formatSearching` option has been renamed to `language.searching` in Select2 4.0.0.'
+                    );
+                }
+                if (opts.formatInputTooShort != null) {
+                    console.warn(
+                        'Select2: The `formatInputTooShort` option has been renamed to `language.inputTooShort` in Select2 4.0.0.'
+                    );
+                }
+                if (opts.formatInputTooLong != null) {
+                    console.warn(
+                        'Select2: The `formatInputTooLong` option has been renamed to `language.inputTooLong` in Select2 4.0.0.'
+                    );
+                }
+                if (opts.formatLoading != null) {
+                    console.warn(
+                        'Select2: The `formatLoading` option has been renamed to `language.loadingMore` in Select2 4.0.0.'
+                    );
+                }
+                if (opts.formatSelectionTooBig != null) {
+                    console.warn(
+                        'Select2: The `formatSelectionTooBig` option has been renamed to `language.maximumSelected` in Select2 4.0.0.'
+                    );
+                }
+
+                if (opts.element.data('select2Tags')) {
+                    console.warn(
+                        'Select2: The `data-select2-tags` attribute has been renamed to `data-tags` in Select2 4.0.0.'
+                    );
+                }
+            }
+
+            // Aliasing options renamed in Select2 4.0.0
+
+            // data-select2-tags -> data-tags
+            if (opts.element.data('tags') != null) {
+                var elemTags = opts.element.data('tags');
+
+                // data-tags should actually be a boolean
+                if (!$.isArray(elemTags)) {
+                    elemTags = [];
+                }
+
+                opts.element.data('select2Tags', elemTags);
+            }
+
+            // sortResults -> sorter
+            if (opts.sorter != null) {
+                opts.sortResults = opts.sorter;
+            }
+
+            // selectOnBlur -> selectOnClose
+            if (opts.selectOnClose != null) {
+                opts.selectOnBlur = opts.selectOnClose;
+            }
+
+            // ajax.results -> ajax.processResults
+            if (opts.ajax != null) {
+                if ($.isFunction(opts.ajax.processResults)) {
+                    opts.ajax.results = opts.ajax.processResults;
+                }
+            }
+
+            // Formatters/language options
+            if (opts.language != null) {
+                var lang = opts.language;
+
+                // formatNoMatches -> language.noMatches
+                if ($.isFunction(lang.noMatches)) {
+                    opts.formatNoMatches = lang.noMatches;
+                }
+
+                // formatSearching -> language.searching
+                if ($.isFunction(lang.searching)) {
+                    opts.formatSearching = lang.searching;
+                }
+
+                // formatInputTooShort -> language.inputTooShort
+                if ($.isFunction(lang.inputTooShort)) {
+                    opts.formatInputTooShort = lang.inputTooShort;
+                }
+
+                // formatInputTooLong -> language.inputTooLong
+                if ($.isFunction(lang.inputTooLong)) {
+                    opts.formatInputTooLong = lang.inputTooLong;
+                }
+
+                // formatLoading -> language.loadingMore
+                if ($.isFunction(lang.loadingMore)) {
+                    opts.formatLoading = lang.loadingMore;
+                }
+
+                // formatSelectionTooBig -> language.maximumSelected
+                if ($.isFunction(lang.maximumSelected)) {
+                    opts.formatSelectionTooBig = lang.maximumSelected;
+                }
+            }
+
             opts = $.extend({}, {
                 populateResults: function(container, results, query) {
                     var populate, id=this.opts.id, liveRegion=this.liveRegion;
@@ -929,7 +1097,13 @@
 
                         // collect the created nodes for bulk append
                         var nodes = [];
-                        for (i = 0, l = results.length; i < l; i = i + 1) {
+
+                        // Kallithea customization: maxResults
+                        l = results.length;
+                        if (query.term.length == 0 && l > opts.maxResults) {
+                            l = opts.maxResults;
+                        }
+                        for (i = 0; i < l; i = i + 1) {
 
                             result=results[i];
 
@@ -960,7 +1134,6 @@
 
 
                             if (compound) {
-
                                 innerContainer=$("<ul></ul>");
                                 innerContainer.addClass("select2-result-sub");
                                 populate(result.children, innerContainer, depth+1);
@@ -971,6 +1144,10 @@
                             nodes.push(node[0]);
                         }
 
+                        if (results.length >= opts.maxResults) {
+                            nodes.push($('<li class="select2-no-results"><div class="select2-result-label">Too many matches found</div></li>'));
+                        }
+
                         // bulk append the created nodes
                         container.append(nodes);
                         liveRegion.text(opts.formatMatches(results.length));
@@ -994,16 +1171,25 @@
 
             if (select) {
                 opts.query = this.bind(function (query) {
+                    // Kallithea customization: maxResults
                     var data = { results: [], more: false },
                         term = query.term,
-                        children, placeholderOption, process;
+                        children, placeholderOption, process,
+                        maxResults = opts.maxResults || -1,
+                        termLower = term.toLowerCase();
 
                     process=function(element, collection) {
                         var group;
                         if (element.is("option")) {
+                          if (collection.length < maxResults) {
                             if (query.matcher(term, element.text(), element)) {
                                 collection.push(self.optionToData(element));
                             }
+                          } else {
+                            if (element.text().toLowerCase().indexOf(termLower) == 0) {
+                                collection.push(self.optionToData(element));
+                            }
+                          }
                         } else if (element.is("optgroup")) {
                             group=self.optionToData(element);
                             element.children().each2(function(i, elm) { process(elm, group.children); });
@@ -1027,11 +1213,10 @@
 
                     query.callback(data);
                 });
-                // this is needed because inside val() we construct choices from options and there id is hardcoded
+                // this is needed because inside val() we construct choices from options and their id is hardcoded
                 opts.id=function(e) { return e.id; };
             } else {
                 if (!("query" in opts)) {
-
                     if ("ajax" in opts) {
                         ajaxUrl = opts.element.data("ajax-url");
                         if (ajaxUrl && ajaxUrl.length > 0) {
@@ -1048,7 +1233,7 @@
                         if (opts.initSelection === undefined) {
                             opts.initSelection = function (element, callback) {
                                 var data = [];
-                                $(splitVal(element.val(), opts.separator)).each(function () {
+                                $(splitVal(element.val(), opts.separator, opts.transformVal)).each(function () {
                                     var obj = { id: this, text: this },
                                         tags = opts.tags;
                                     if ($.isFunction(tags)) tags=tags();
@@ -1103,11 +1288,15 @@
                 if (readonly === undefined) readonly = false;
                 this.readonly(readonly);
 
-                syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
-                this.container.addClass(evaluate(this.opts.containerCssClass, this.opts.element));
-
-                syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
-                this.dropdown.addClass(evaluate(this.opts.dropdownCssClass, this.opts.element));
+                if (this.container) {
+                    syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
+                    this.container.addClass(evaluate(this.opts.containerCssClass, this.opts.element));
+                }
+
+                if (this.dropdown) {
+                    syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
+                    this.dropdown.addClass(evaluate(this.opts.dropdownCssClass, this.opts.element));
+                }
 
             });
 
@@ -1212,9 +1401,10 @@
         // abstract
         positionDropdown: function() {
             var $dropdown = this.dropdown,
-                offset = this.container.offset(),
-                height = this.container.outerHeight(false),
-                width = this.container.outerWidth(false),
+                container = this.container,
+                offset = container.offset(),
+                height = container.outerHeight(false),
+                width = container.outerWidth(false),
                 dropHeight = $dropdown.outerHeight(false),
                 $window = $(window),
                 windowWidth = $window.width(),
@@ -1226,7 +1416,12 @@
                 enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
                 enoughRoomAbove = (offset.top - dropHeight) >= $window.scrollTop(),
                 dropWidth = $dropdown.outerWidth(false),
-                enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight,
+                enoughRoomOnRight = function() {
+                    return dropLeft + dropWidth <= viewPortRight;
+                },
+                enoughRoomOnLeft = function() {
+                    return offset.left + viewPortRight + container.outerWidth(false)  > dropWidth;
+                },
                 aboveNow = $dropdown.hasClass("select2-drop-above"),
                 bodyOffset,
                 above,
@@ -1261,7 +1456,6 @@
                 dropTop = offset.top + height;
                 dropLeft = offset.left;
                 dropWidth = $dropdown.outerWidth(false);
-                enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
                 $dropdown.show();
 
                 // fix so the cursor does not move to the left within the search-textbox in IE
@@ -1276,7 +1470,6 @@
                 dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width);
                 dropWidth > width ? width = dropWidth : dropWidth = width;
                 dropHeight = $dropdown.outerHeight(false);
-                enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
             }
             else {
                 this.container.removeClass('select2-drop-auto-width');
@@ -1292,7 +1485,7 @@
                 dropLeft -= bodyOffset.left;
             }
 
-            if (!enoughRoomOnRight) {
+            if (!enoughRoomOnRight() && enoughRoomOnLeft()) {
                 dropLeft = offset.left + this.container.outerWidth(false) - dropWidth;
             }
 
@@ -1302,10 +1495,11 @@
             };
 
             if (above) {
+                this.container.addClass("select2-drop-above");
+                $dropdown.addClass("select2-drop-above");
+                dropHeight = $dropdown.outerHeight(false);
                 css.top = offset.top - dropHeight;
                 css.bottom = 'auto';
-                this.container.addClass("select2-drop-above");
-                $dropdown.addClass("select2-drop-above");
             }
             else {
                 css.top = dropTop;
@@ -1381,7 +1575,7 @@
 
             // create the dropdown mask if doesn't already exist
             mask = $("#select2-drop-mask");
-            if (mask.length == 0) {
+            if (mask.length === 0) {
                 mask = $(document.createElement("div"));
                 mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");
                 mask.hide();
@@ -1458,6 +1652,9 @@
 
             this.clearSearch();
             this.search.removeClass("select2-active");
+
+            // Remove the aria active descendant for highlighted element
+            this.search.removeAttr("aria-activedescendant");
             this.opts.element.trigger($.Event("select2-close"));
         },
 
@@ -1476,6 +1673,27 @@
 
         },
 
+        /**
+         * @return {Boolean} Whether or not search value was changed.
+         * @private
+         */
+        prefillNextSearchTerm: function () {
+            // initializes search's value with nextSearchTerm (if defined by user)
+            // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
+            if(this.search.val() !== "") {
+                return false;
+            }
+
+            var nextSearchTerm = this.opts.nextSearchTerm(this.data(), this.lastSearchTerm);
+            if(nextSearchTerm !== undefined){
+                this.search.val(nextSearchTerm);
+                this.search.select();
+                return true;
+            }
+
+            return false;
+        },
+
         //abstract
         getMaximumSelectionSize: function() {
             return evaluate(this.opts.maximumSelectionSize, this.opts.element);
@@ -1515,7 +1733,7 @@
                 }
             }
 
-            rb = results.offset().top + results.outerHeight(true);
+            rb = results.offset().top + results.outerHeight(false);
             if (hb > rb) {
                 results.scrollTop(results.scrollTop() + (hb - rb));
             }
@@ -1638,7 +1856,7 @@
                     self.postprocessResults(data, false, false);
 
                     if (data.more===true) {
-                        more.detach().appendTo(results).text(evaluate(self.opts.formatLoadMore, self.opts.element, page+1));
+                        more.detach().appendTo(results).html(self.opts.escapeMarkup(evaluate(self.opts.formatLoadMore, self.opts.element, page+1)));
                         window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
                     } else {
                         more.remove();
@@ -1691,7 +1909,7 @@
                     self.liveRegion.text(results.text());
                 }
                 else {
-                    self.liveRegion.text(self.opts.formatMatches(results.find('.select2-result-selectable').length));
+                    self.liveRegion.text(self.opts.formatMatches(results.find('.select2-result-selectable:not(".select2-selected")').length));
                 }
             }
 
@@ -1766,6 +1984,12 @@
                     return;
                 }
 
+                // handle ajax error
+                if(data.hasError !== undefined && checkFormatter(opts.formatAjaxError, "formatAjaxError")) {
+                    render("<li class='select2-ajax-error'>" + evaluate(opts.formatAjaxError, opts.element, data.jqXHR, data.textStatus, data.errorThrown) + "</li>");
+                    return;
+                }
+
                 // save context, if any
                 this.context = (data.context===undefined) ? null : data.context;
                 // create a default choice and prepend it to the list
@@ -1783,6 +2007,9 @@
 
                 if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
                     render("<li class='select2-no-results'>" + evaluate(opts.formatNoMatches, opts.element, search.val()) + "</li>");
+                    if(this.showSearch){
+                        this.showSearch(search.val());
+                    }
                     return;
                 }
 
@@ -1887,7 +2114,7 @@
                 } else if (this.opts.width === "copy" || this.opts.width === "resolve") {
                     // check if there is inline style on the element that contains width
                     style = this.opts.element.attr('style');
-                    if (style !== undefined) {
+                    if (typeof(style) === "string") {
                         attrs = style.split(';');
                         for (i = 0, l = attrs.length; i < l; i = i + 1) {
                             attr = attrs[i].replace(/\s/g, '');
@@ -1986,14 +2213,7 @@
                 }
             }
 
-            // initializes search's value with nextSearchTerm (if defined by user)
-            // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
-            if(this.search.val() === "") {
-                if(this.nextSearchTerm != undefined){
-                    this.search.val(this.nextSearchTerm);
-                    this.search.select();
-                }
-            }
+            this.prefillNextSearchTerm();
 
             this.focusser.prop("disabled", true).val("");
             this.updateResults(true);
@@ -2080,6 +2300,7 @@
             this.focusser.attr("id", "s2id_autogen"+idSuffix);
 
             elementLabel = $("label[for='" + this.opts.element.attr("id") + "']");
+            this.opts.element.on('focus.select2', this.bind(function () { this.focus(); }));
 
             this.focusser.prev()
                 .text(elementLabel.text())
@@ -2101,6 +2322,9 @@
             this.search.on("keydown", this.bind(function (e) {
                 if (!this.isInterfaceEnabled()) return;
 
+                // filter 229 keyCodes (input method editor is processing key input)
+                if (229 == e.keyCode) return;
+
                 if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
                     // prevent the page from scrolling
                     killEvent(e);
@@ -2132,7 +2356,7 @@
                 // without this the search field loses focus which is annoying
                 if (document.activeElement === this.body.get(0)) {
                     window.setTimeout(this.bind(function() {
-                        if (this.opened()) {
+                        if (this.opened() && this.results && this.results.length > 1) {
                             this.search.focus();
                         }
                     }), 0);
@@ -2181,11 +2405,17 @@
             }));
 
             selection.on("mousedown touchstart", "abbr", this.bind(function (e) {
-                if (!this.isInterfaceEnabled()) return;
+                if (!this.isInterfaceEnabled()) {
+                    return;
+                }
+
                 this.clear();
                 killEventImmediately(e);
                 this.close();
-                this.selection.focus();
+
+                if (this.selection) {
+                    this.selection.focus();
+                }
             }));
 
             selection.on("mousedown touchstart", this.bind(function (e) {
@@ -2234,7 +2464,7 @@
             }));
 
             this.initContainerWidth();
-            this.opts.element.addClass("select2-offscreen");
+            this.opts.element.hide();
             this.setPlaceholder();
 
         },
@@ -2278,7 +2508,7 @@
                         self.updateSelection(selected);
                         self.close();
                         self.setPlaceholder();
-                        self.nextSearchTerm = self.opts.nextSearchTerm(selected, self.search.val());
+                        self.lastSearchTerm = self.search.val();
                     }
                 });
             }
@@ -2415,7 +2645,7 @@
 
             this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data });
 
-            this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val());
+            this.lastSearchTerm = this.search.val();
             this.close();
 
             if ((!options || !options.noFocus) && this.opts.shouldFocusInput(this)) {
@@ -2469,9 +2699,23 @@
 
             if (arguments.length > 1) {
                 triggerChange = arguments[1];
+
+                if (this.opts.debug && console && console.warn) {
+                    console.warn(
+                        'Select2: The second option to `select2("val")` is not supported in Select2 4.0.0. ' +
+                        'The `change` event will always be triggered in 4.0.0.'
+                    );
+                }
             }
 
             if (this.select) {
+                if (this.opts.debug && console && console.warn) {
+                    console.warn(
+                        'Select2: Setting the value on a <select> using `select2("val")` is no longer supported in 4.0.0. ' +
+                        'You can use the `.val(newValue).trigger("change")` method provided by jQuery instead.'
+                    );
+                }
+
                 this.select
                     .val(val)
                     .find("option").filter(function() { return this.selected }).each2(function (i, elm) {
@@ -2520,6 +2764,13 @@
                 if (data == undefined) data = null;
                 return data;
             } else {
+                if (this.opts.debug && console && console.warn) {
+                    console.warn(
+                        'Select2: The `select2("data")` method can no longer set selected values in 4.0.0, ' +
+                        'consider using the `.val()` method instead.'
+                    );
+                }
+
                 if (arguments.length > 1) {
                     triggerChange = arguments[1];
                 }
@@ -2563,7 +2814,6 @@
                 self=this;
 
             // TODO validate placeholder is a string if specified
-
             if (opts.element.get(0).tagName.toLowerCase() === "select") {
                 // install the selection initializer
                 opts.initSelection = function (element, callback) {
@@ -2578,7 +2828,7 @@
             } else if ("data" in opts) {
                 // install default initSelection when applied to hidden input and data is local
                 opts.initSelection = opts.initSelection || function (element, callback) {
-                    var ids = splitVal(element.val(), opts.separator);
+                    var ids = splitVal(element.val(), opts.separator, opts.transformVal);
                     //search in data by array of ids, storing matching items in a list
                     var matches = [];
                     opts.query({
@@ -2655,8 +2905,7 @@
             this.selection = selection = this.container.find(selector);
 
             var _this = this;
-            this.selection.on("click", ".select2-search-choice:not(.select2-locked)", function (e) {
-                //killEvent(e);
+            this.selection.on("click", ".select2-container:not(.select2-container-disabled) .select2-search-choice:not(.select2-locked)", function (e) {
                 _this.search[0].focus();
                 _this.selectChoice($(this));
             });
@@ -2667,6 +2916,7 @@
             this.search.prev()
                 .text($("label[for='" + this.opts.element.attr("id") + "']").text())
                 .attr('for', this.search.attr('id'));
+            this.opts.element.on('focus.select2', this.bind(function () { this.focus(); }));
 
             this.search.on("input paste", this.bind(function() {
                 if (this.search.attr('placeholder') && this.search.val().length == 0) return;
@@ -2818,7 +3068,7 @@
             }));
 
             this.initContainerWidth();
-            this.opts.element.addClass("select2-offscreen");
+            this.opts.element.hide();
 
             // set the placeholder if necessary
             this.clearSearch();
@@ -2884,16 +3134,9 @@
 
             this.focusSearch();
 
-            // initializes search's value with nextSearchTerm (if defined by user)
-            // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
-            if(this.search.val() === "") {
-                if(this.nextSearchTerm != undefined){
-                    this.search.val(this.nextSearchTerm);
-                    this.search.select();
-                }
-            }
-
+            this.prefillNextSearchTerm();
             this.updateResults(true);
+
             if (this.opts.shouldFocusInput(this)) {
                 this.search.focus();
             }
@@ -2919,21 +3162,18 @@
 
         // multi
         updateSelection: function (data) {
-            var ids = [], filtered = [], self = this;
+            var ids = {}, filtered = [], self = this;
 
             // filter out duplicates
             $(data).each(function () {
-                if (indexOf(self.id(this), ids) < 0) {
-                    ids.push(self.id(this));
+                if (!(self.id(this) in ids)) {
+                    ids[self.id(this)] = 0;
                     filtered.push(this);
                 }
             });
-            data = filtered;
 
             this.selection.find(".select2-search-choice").remove();
-            $(data).each(function () {
-                self.addSelectedChoice(this);
-            });
+            this.addSelectedChoice(filtered);
             self.postprocessResults();
         },
 
@@ -2953,14 +3193,14 @@
         // multi
         onSelect: function (data, options) {
 
-            if (!this.triggerSelect(data)) { return; }
+            if (!this.triggerSelect(data) || data.text === "") { return; }
 
             this.addSelectedChoice(data);
 
             this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
 
             // keep track of the search's value before it gets cleared
-            this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val());
+            this.lastSearchTerm = this.search.val();
 
             this.clearSearch();
             this.updateResults();
@@ -2980,10 +3220,8 @@
                         this.updateResults(true);
                     } else {
                         // initializes search's value with nextSearchTerm and update search result
-                        if(this.nextSearchTerm != undefined){
-                            this.search.val(this.nextSearchTerm);
+                        if (this.prefillNextSearchTerm()) {
                             this.updateResults();
-                            this.search.select();
                         }
                     }
                     this.positionDropdown();
@@ -3009,6 +3247,14 @@
         },
 
         addSelectedChoice: function (data) {
+            var val = this.getVal(), self = this;
+            $(data).each(function () {
+                val.push(self.createChoice(this));
+            });
+            this.setVal(val);
+        },
+
+        createChoice: function (data) {
             var enableChoice = !data.locked,
                 enabledItem = $(
                     "<li class='select2-search-choice'>" +
@@ -3021,13 +3267,12 @@
                     "</li>");
             var choice = enableChoice ? enabledItem : disabledItem,
                 id = this.id(data),
-                val = this.getVal(),
                 formatted,
                 cssClass;
 
             formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup);
             if (formatted != undefined) {
-                choice.find("div").replaceWith("<div>"+formatted+"</div>");
+                choice.find("div").replaceWith($("<div></div>").html(formatted));
             }
             cssClass=this.opts.formatSelectionCssClass(data, choice.find("div"));
             if (cssClass != undefined) {
@@ -3055,8 +3300,7 @@
             choice.data("select2-data", data);
             choice.insertBefore(this.searchContainer);
 
-            val.push(id);
-            this.setVal(val);
+            return id;
         },
 
         // multi
@@ -3125,7 +3369,7 @@
                 }
             });
 
-            if (this.highlight() == -1 && noHighlightUpdate !== false){
+            if (this.highlight() == -1 && noHighlightUpdate !== false && this.opts.closeOnSelect === true){
                 self.highlight(0);
             }
 
@@ -3182,20 +3426,22 @@
                 return val === null ? [] : val;
             } else {
                 val = this.opts.element.val();
-                return splitVal(val, this.opts.separator);
+                return splitVal(val, this.opts.separator, this.opts.transformVal);
             }
         },
 
         // multi
         setVal: function (val) {
-            var unique;
             if (this.select) {
                 this.select.val(val);
             } else {
-                unique = [];
+                var unique = [], valMap = {};
                 // filter out duplicates
                 $(val).each(function () {
-                    if (indexOf(this, unique) < 0) unique.push(this);
+                    if (!(this in valMap)) {
+                        unique.push(this);
+                        valMap[this] = 0;
+                    }
                 });
                 this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
             }
@@ -3211,11 +3457,9 @@
                 for (var j = 0; j < old.length; j++) {
                     if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) {
                         current.splice(i, 1);
-                        if(i>0){
-                        	i--;
-                        }
+                        i--;
                         old.splice(j, 1);
-                        j--;
+                        break;
                     }
                 }
             }
@@ -3385,6 +3629,7 @@
 
     // plugin defaults, accessible to users
     $.fn.select2.defaults = {
+        debug: false,
         width: "copy",
         loadMorePadding: 0,
         closeOnSelect: true,
@@ -3395,29 +3640,36 @@
         dropdownCssClass: "",
         formatResult: function(result, container, query, escapeMarkup) {
             var markup=[];
-            markMatch(result.text, query.term, markup, escapeMarkup);
+            markMatch(this.text(result), query.term, markup, escapeMarkup);
             return markup.join("");
         },
+        transformVal: function(val) {
+            return $.trim(val);
+        },
         formatSelection: function (data, container, escapeMarkup) {
-            return data ? escapeMarkup(data.text) : undefined;
+            return data ? escapeMarkup(this.text(data)) : undefined;
         },
         sortResults: function (results, container, query) {
             return results;
         },
         formatResultCssClass: function(data) {return data.css;},
         formatSelectionCssClass: function(data, container) {return undefined;},
-        formatMatches: function (matches) { if (matches === 1) { return "One result is available, press enter to select it."; } return matches + " results are available, use up and down arrow keys to navigate."; },
-        formatNoMatches: function () { return "No matches found"; },
-        formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " or more character" + (n == 1? "" : "s"); },
-        formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1? "" : "s"); },
-        formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
-        formatLoadMore: function (pageNumber) { return "Loading more results…"; },
-        formatSearching: function () { return "Searching…"; },
         minimumResultsForSearch: 0,
         minimumInputLength: 0,
         maximumInputLength: null,
         maximumSelectionSize: 0,
         id: function (e) { return e == undefined ? null : e.id; },
+        text: function (e) {
+          if (e && this.data && this.data.text) {
+            if ($.isFunction(this.data.text)) {
+              return this.data.text(e);
+            } else {
+              return e[this.data.text];
+            }
+          } else {
+            return e.text;
+          }
+        },
         matcher: function(term, text) {
             return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0;
         },
@@ -3451,6 +3703,21 @@
         }
     };
 
+    $.fn.select2.locales = [];
+
+    $.fn.select2.locales['en'] = {
+         formatMatches: function (matches) { if (matches === 1) { return "One result is available, press enter to select it."; } return matches + " results are available, use up and down arrow keys to navigate."; },
+         formatNoMatches: function () { return "No matches found"; },
+         formatAjaxError: function (jqXHR, textStatus, errorThrown) { return "Loading failed"; },
+         formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " or more character" + (n == 1 ? "" : "s"); },
+         formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1 ? "" : "s"); },
+         formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
+         formatLoadMore: function (pageNumber) { return "Loading more results…"; },
+         formatSearching: function () { return "Searching…"; }
+    };
+
+    $.extend($.fn.select2.defaults, $.fn.select2.locales['en']);
+
     $.fn.select2.ajaxDefaults = {
         transport: $.ajax,
         params: {
--- a/kallithea/public/js/yui.2.9.js	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/public/js/yui.2.9.js	Fri Nov 18 01:11:13 2016 +0100
@@ -1,6 +1,6 @@
 if(typeof YAHOO=="undefined"||!YAHOO){var YAHOO={}}YAHOO.namespace=function(){var b=arguments,g=null,e,c,f;for(e=0;e<b.length;e=e+1){f=(""+b[e]).split(".");g=YAHOO;for(c=(f[0]=="YAHOO")?1:0;c<f.length;c=c+1){g[f[c]]=g[f[c]]||{};g=g[f[c]]}}return g};YAHOO.log=function(d,a,c){var b=YAHOO.widget.Logger;if(b&&b.log){return b.log(d,a,c)}else{return false}};YAHOO.register=function(a,f,e){var k=YAHOO.env.modules,c,j,h,g,d;if(!k[a]){k[a]={versions:[],builds:[]}}c=k[a];j=e.version;h=e.build;g=YAHOO.env.listeners;c.name=a;c.version=j;c.build=h;c.versions.push(j);c.builds.push(h);c.mainClass=f;for(d=0;d<g.length;d=d+1){g[d](c)}if(f){f.VERSION=j;f.BUILD=h}else{YAHOO.log("mainClass is undefined for module "+a,"warn")}};YAHOO.env=YAHOO.env||{modules:[],listeners:[]};YAHOO.env.getVersion=function(a){return YAHOO.env.modules[a]||null};YAHOO.env.parseUA=function(d){var e=function(i){var j=0;return parseFloat(i.replace(/\./g,function(){return(j++==1)?"":"."}))},h=navigator,g={ie:0,opera:0,gecko:0,webkit:0,chrome:0,mobile:null,air:0,ipad:0,iphone:0,ipod:0,ios:null,android:0,webos:0,caja:h&&h.cajaVersion,secure:false,os:null},c=d||(navigator&&navigator.userAgent),f=window&&window.location,b=f&&f.href,a;g.secure=b&&(b.toLowerCase().indexOf("https")===0);if(c){if((/windows|win32/i).test(c)){g.os="windows"}else{if((/macintosh/i).test(c)){g.os="macintosh"}else{if((/rhino/i).test(c)){g.os="rhino"}}}if((/KHTML/).test(c)){g.webkit=1}a=c.match(/AppleWebKit\/([^\s]*)/);if(a&&a[1]){g.webkit=e(a[1]);if(/ Mobile\//.test(c)){g.mobile="Apple";a=c.match(/OS ([^\s]*)/);if(a&&a[1]){a=e(a[1].replace("_","."))}g.ios=a;g.ipad=g.ipod=g.iphone=0;a=c.match(/iPad|iPod|iPhone/);if(a&&a[0]){g[a[0].toLowerCase()]=g.ios}}else{a=c.match(/NokiaN[^\/]*|Android \d\.\d|webOS\/\d\.\d/);if(a){g.mobile=a[0]}if(/webOS/.test(c)){g.mobile="WebOS";a=c.match(/webOS\/([^\s]*);/);if(a&&a[1]){g.webos=e(a[1])}}if(/ Android/.test(c)){g.mobile="Android";a=c.match(/Android ([^\s]*);/);if(a&&a[1]){g.android=e(a[1])}}}a=c.match(/Chrome\/([^\s]*)/);if(a&&a[1]){g.chrome=e(a[1])}else{a=c.match(/AdobeAIR\/([^\s]*)/);if(a){g.air=a[0]}}}if(!g.webkit){a=c.match(/Opera[\s\/]([^\s]*)/);if(a&&a[1]){g.opera=e(a[1]);a=c.match(/Version\/([^\s]*)/);if(a&&a[1]){g.opera=e(a[1])}a=c.match(/Opera Mini[^;]*/);if(a){g.mobile=a[0]}}else{a=c.match(/MSIE\s([^;]*)/);if(a&&a[1]){g.ie=e(a[1])}else{a=c.match(/Gecko\/([^\s]*)/);if(a){g.gecko=1;a=c.match(/rv:([^\s\)]*)/);if(a&&a[1]){g.gecko=e(a[1])}}}}}}return g};YAHOO.env.ua=YAHOO.env.parseUA();(function(){YAHOO.namespace("util","widget","example");if("undefined"!==typeof YAHOO_config){var b=YAHOO_config.listener,a=YAHOO.env.listeners,d=true,c;if(b){for(c=0;c<a.length;c++){if(a[c]==b){d=false;break}}if(d){a.push(b)}}}})();YAHOO.lang=YAHOO.lang||{};(function(){var f=YAHOO.lang,a=Object.prototype,c="[object Array]",h="[object Function]",i="[object Object]",b=[],g={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;","`":"&#x60;"},d=["toString","valueOf"],e={isArray:function(j){return a.toString.apply(j)===c},isBoolean:function(j){return typeof j==="boolean"},isFunction:function(j){return(typeof j==="function")||a.toString.apply(j)===h},isNull:function(j){return j===null},isNumber:function(j){return typeof j==="number"&&isFinite(j)},isObject:function(j){return(j&&(typeof j==="object"||f.isFunction(j)))||false},isString:function(j){return typeof j==="string"},isUndefined:function(j){return typeof j==="undefined"},_IEEnumFix:(YAHOO.env.ua.ie)?function(l,k){var j,n,m;for(j=0;j<d.length;j=j+1){n=d[j];m=k[n];if(f.isFunction(m)&&m!=a[n]){l[n]=m}}}:function(){},escapeHTML:function(j){return j.replace(/[&<>"'\/`]/g,function(k){return g[k]})},extend:function(m,n,l){if(!n||!m){throw new Error("extend failed, please check that all dependencies are included.")}var k=function(){},j;k.prototype=n.prototype;m.prototype=new k();m.prototype.constructor=m;m.superclass=n.prototype;if(n.prototype.constructor==a.constructor){n.prototype.constructor=n}if(l){for(j in l){if(f.hasOwnProperty(l,j)){m.prototype[j]=l[j]}}f._IEEnumFix(m.prototype,l)}},augmentObject:function(n,m){if(!m||!n){throw new Error("Absorb failed, verify dependencies.")}var j=arguments,l,o,k=j[2];if(k&&k!==true){for(l=2;l<j.length;l=l+1){n[j[l]]=m[j[l]]}}else{for(o in m){if(k||!(o in n)){n[o]=m[o]}}f._IEEnumFix(n,m)}return n},augmentProto:function(m,l){if(!l||!m){throw new Error("Augment failed, verify dependencies.")}var j=[m.prototype,l.prototype],k;for(k=2;k<arguments.length;k=k+1){j.push(arguments[k])}f.augmentObject.apply(this,j);return m},dump:function(j,p){var l,n,r=[],t="{...}",k="f(){...}",q=", ",m=" => ";if(!f.isObject(j)){return j+""}else{if(j instanceof Date||("nodeType" in j&&"tagName" in j)){return j}else{if(f.isFunction(j)){return k}}}p=(f.isNumber(p))?p:3;if(f.isArray(j)){r.push("[");for(l=0,n=j.length;l<n;l=l+1){if(f.isObject(j[l])){r.push((p>0)?f.dump(j[l],p-1):t)}else{r.push(j[l])}r.push(q)}if(r.length>1){r.pop()}r.push("]")}else{r.push("{");for(l in j){if(f.hasOwnProperty(j,l)){r.push(l+m);if(f.isObject(j[l])){r.push((p>0)?f.dump(j[l],p-1):t)}else{r.push(j[l])}r.push(q)}}if(r.length>1){r.pop()}r.push("}")}return r.join("")},substitute:function(x,y,E,l){var D,C,B,G,t,u,F=[],p,z=x.length,A="dump",r=" ",q="{",m="}",n,w;for(;;){D=x.lastIndexOf(q,z);if(D<0){break}C=x.indexOf(m,D);if(D+1>C){break}p=x.substring(D+1,C);G=p;u=null;B=G.indexOf(r);if(B>-1){u=G.substring(B+1);G=G.substring(0,B)}t=y[G];if(E){t=E(G,t,u)}if(f.isObject(t)){if(f.isArray(t)){t=f.dump(t,parseInt(u,10))}else{u=u||"";n=u.indexOf(A);if(n>-1){u=u.substring(4)}w=t.toString();if(w===i||n>-1){t=f.dump(t,parseInt(u,10))}else{t=w}}}else{if(!f.isString(t)&&!f.isNumber(t)){t="~-"+F.length+"-~";F[F.length]=p}}x=x.substring(0,D)+t+x.substring(C+1);if(l===false){z=D-1}}for(D=F.length-1;D>=0;D=D-1){x=x.replace(new RegExp("~-"+D+"-~"),"{"+F[D]+"}","g")}return x},trim:function(j){try{return j.replace(/^\s+|\s+$/g,"")}catch(k){return j}},merge:function(){var n={},k=arguments,j=k.length,m;for(m=0;m<j;m=m+1){f.augmentObject(n,k[m],true)}return n},later:function(t,k,u,n,p){t=t||0;k=k||{};var l=u,s=n,q,j;if(f.isString(u)){l=k[u]}if(!l){throw new TypeError("method undefined")}if(!f.isUndefined(n)&&!f.isArray(s)){s=[n]}q=function(){l.apply(k,s||b)};j=(p)?setInterval(q,t):setTimeout(q,t);return{interval:p,cancel:function(){if(this.interval){clearInterval(j)}else{clearTimeout(j)}}}},isValue:function(j){return(f.isObject(j)||f.isString(j)||f.isNumber(j)||f.isBoolean(j))}};f.hasOwnProperty=(a.hasOwnProperty)?function(j,k){return j&&j.hasOwnProperty&&j.hasOwnProperty(k)}:function(j,k){return !f.isUndefined(j[k])&&j.constructor.prototype[k]!==j[k]};e.augmentObject(f,e,true);YAHOO.util.Lang=f;f.augment=f.augmentProto;YAHOO.augment=f.augmentProto;YAHOO.extend=f.extend})();YAHOO.register("yahoo",YAHOO,{version:"2.9.0",build:"2800"});YAHOO.util.CustomEvent=function(d,c,b,a,e){this.type=d;this.scope=c||window;this.silent=b;this.fireOnce=e;this.fired=false;this.firedWith=null;this.signature=a||YAHOO.util.CustomEvent.LIST;this.subscribers=[];if(!this.silent){}var f="_YUICEOnSubscribe";if(d!==f){this.subscribeEvent=new YAHOO.util.CustomEvent(f,this,true)}this.lastError=null};YAHOO.util.CustomEvent.LIST=0;YAHOO.util.CustomEvent.FLAT=1;YAHOO.util.CustomEvent.prototype={subscribe:function(b,c,d){if(!b){throw new Error("Invalid callback for subscriber to '"+this.type+"'")}if(this.subscribeEvent){this.subscribeEvent.fire(b,c,d)}var a=new YAHOO.util.Subscriber(b,c,d);if(this.fireOnce&&this.fired){this.notify(a,this.firedWith)}else{this.subscribers.push(a)}},unsubscribe:function(d,f){if(!d){return this.unsubscribeAll()}var e=false;for(var b=0,a=this.subscribers.length;b<a;++b){var c=this.subscribers[b];if(c&&c.contains(d,f)){this._delete(b);e=true}}return e},fire:function(){this.lastError=null;var h=[],a=this.subscribers.length;var d=[].slice.call(arguments,0),c=true,f,b=false;if(this.fireOnce){if(this.fired){return true}else{this.firedWith=d}}this.fired=true;if(!a&&this.silent){return true}if(!this.silent){}var e=this.subscribers.slice();for(f=0;f<a;++f){var g=e[f];if(!g||!g.fn){b=true}else{c=this.notify(g,d);if(false===c){if(!this.silent){}break}}}return(c!==false)},notify:function(g,c){var b,i=null,f=g.getScope(this.scope),a=YAHOO.util.Event.throwErrors;if(!this.silent){}if(this.signature==YAHOO.util.CustomEvent.FLAT){if(c.length>0){i=c[0]}try{b=g.fn.call(f,i,g.obj)}catch(h){this.lastError=h;if(a){throw h}}}else{try{b=g.fn.call(f,this.type,c,g.obj)}catch(d){this.lastError=d;if(a){throw d}}}return b},unsubscribeAll:function(){var a=this.subscribers.length,b;for(b=a-1;b>-1;b--){this._delete(b)}this.subscribers=[];return a},_delete:function(a){var b=this.subscribers[a];if(b){delete b.fn;delete b.obj}this.subscribers.splice(a,1)},toString:function(){return"CustomEvent: '"+this.type+"', context: "+this.scope}};YAHOO.util.Subscriber=function(a,b,c){this.fn=a;this.obj=YAHOO.lang.isUndefined(b)?null:b;this.overrideContext=c};YAHOO.util.Subscriber.prototype.getScope=function(a){if(this.overrideContext){if(this.overrideContext===true){return this.obj}else{return this.overrideContext}}return a};YAHOO.util.Subscriber.prototype.contains=function(a,b){if(b){return(this.fn==a&&this.obj==b)}else{return(this.fn==a)}};YAHOO.util.Subscriber.prototype.toString=function(){return"Subscriber { obj: "+this.obj+", overrideContext: "+(this.overrideContext||"no")+" }"};if(!YAHOO.util.Event){YAHOO.util.Event=function(){var g=false,h=[],j=[],a=0,e=[],b=0,c={63232:38,63233:40,63234:37,63235:39,63276:33,63277:34,25:9},d=YAHOO.env.ua.ie,f="focusin",i="focusout";return{POLL_RETRYS:500,POLL_INTERVAL:40,EL:0,TYPE:1,FN:2,WFN:3,UNLOAD_OBJ:3,ADJ_SCOPE:4,OBJ:5,OVERRIDE:6,CAPTURE:7,lastError:null,isSafari:YAHOO.env.ua.webkit,webkit:YAHOO.env.ua.webkit,isIE:d,_interval:null,_dri:null,_specialTypes:{focusin:(d?"focusin":"focus"),focusout:(d?"focusout":"blur")},DOMReady:false,throwErrors:false,startInterval:function(){if(!this._interval){this._interval=YAHOO.lang.later(this.POLL_INTERVAL,this,this._tryPreloadAttach,null,true)}},onAvailable:function(q,m,o,p,n){var k=(YAHOO.lang.isString(q))?[q]:q;for(var l=0;l<k.length;l=l+1){e.push({id:k[l],fn:m,obj:o,overrideContext:p,checkReady:n})}a=this.POLL_RETRYS;this.startInterval()},onContentReady:function(n,k,l,m){this.onAvailable(n,k,l,m,true)},onDOMReady:function(){this.DOMReadyEvent.subscribe.apply(this.DOMReadyEvent,arguments)},_addListener:function(m,k,v,p,t,y){if(!v||!v.call){return false}if(this._isValidCollection(m)){var w=true;for(var q=0,s=m.length;q<s;++q){w=this.on(m[q],k,v,p,t)&&w}return w}else{if(YAHOO.lang.isString(m)){var o=this.getEl(m);if(o){m=o}else{this.onAvailable(m,function(){YAHOO.util.Event._addListener(m,k,v,p,t,y)});return true}}}if(!m){return false}if("unload"==k&&p!==this){j[j.length]=[m,k,v,p,t];return true}var l=m;if(t){if(t===true){l=p}else{l=t}}var n=function(z){return v.call(l,YAHOO.util.Event.getEvent(z,m),p)};var x=[m,k,v,n,l,p,t,y];var r=h.length;h[r]=x;try{this._simpleAdd(m,k,n,y)}catch(u){this.lastError=u;this.removeListener(m,k,v);return false}return true},_getType:function(k){return this._specialTypes[k]||k},addListener:function(m,p,l,n,o){var k=((p==f||p==i)&&!YAHOO.env.ua.ie)?true:false;return this._addListener(m,this._getType(p),l,n,o,k)},addFocusListener:function(l,k,m,n){return this.on(l,f,k,m,n)},removeFocusListener:function(l,k){return this.removeListener(l,f,k)},addBlurListener:function(l,k,m,n){return this.on(l,i,k,m,n)},removeBlurListener:function(l,k){return this.removeListener(l,i,k)},removeListener:function(l,k,r){var m,p,u;k=this._getType(k);if(typeof l=="string"){l=this.getEl(l)}else{if(this._isValidCollection(l)){var s=true;for(m=l.length-1;m>-1;m--){s=(this.removeListener(l[m],k,r)&&s)}return s}}if(!r||!r.call){return this.purgeElement(l,false,k)}if("unload"==k){for(m=j.length-1;m>-1;m--){u=j[m];if(u&&u[0]==l&&u[1]==k&&u[2]==r){j.splice(m,1);return true}}return false}var n=null;var o=arguments[3];if("undefined"===typeof o){o=this._getCacheIndex(h,l,k,r)}if(o>=0){n=h[o]}if(!l||!n){return false}var t=n[this.CAPTURE]===true?true:false;try{this._simpleRemove(l,k,n[this.WFN],t)}catch(q){this.lastError=q;return false}delete h[o][this.WFN];delete h[o][this.FN];h.splice(o,1);return true},getTarget:function(m,l){var k=m.target||m.srcElement;return this.resolveTextNode(k)},resolveTextNode:function(l){try{if(l&&3==l.nodeType){return l.parentNode}}catch(k){return null}return l},getPageX:function(l){var k=l.pageX;if(!k&&0!==k){k=l.clientX||0;if(this.isIE){k+=this._getScrollLeft()}}return k},getPageY:function(k){var l=k.pageY;if(!l&&0!==l){l=k.clientY||0;if(this.isIE){l+=this._getScrollTop()}}return l},getXY:function(k){return[this.getPageX(k),this.getPageY(k)]},getRelatedTarget:function(l){var k=l.relatedTarget;if(!k){if(l.type=="mouseout"){k=l.toElement}else{if(l.type=="mouseover"){k=l.fromElement}}}return this.resolveTextNode(k)},getTime:function(m){if(!m.time){var l=new Date().getTime();try{m.time=l}catch(k){this.lastError=k;return l}}return m.time},stopEvent:function(k){this.stopPropagation(k);this.preventDefault(k)},stopPropagation:function(k){if(k.stopPropagation){k.stopPropagation()}else{k.cancelBubble=true}},preventDefault:function(k){if(k.preventDefault){k.preventDefault()}else{k.returnValue=false}},getEvent:function(m,k){var l=m||window.event;if(!l){var n=this.getEvent.caller;while(n){l=n.arguments[0];if(l&&Event==l.constructor){break}n=n.caller}}return l},getCharCode:function(l){var k=l.keyCode||l.charCode||0;if(YAHOO.env.ua.webkit&&(k in c)){k=c[k]}return k},_getCacheIndex:function(n,q,r,p){for(var o=0,m=n.length;o<m;o=o+1){var k=n[o];if(k&&k[this.FN]==p&&k[this.EL]==q&&k[this.TYPE]==r){return o}}return -1},generateId:function(k){var l=k.id;if(!l){l="yuievtautoid-"+b;++b;k.id=l}return l},_isValidCollection:function(l){try{return(l&&typeof l!=="string"&&l.length&&!l.tagName&&!l.alert&&typeof l[0]!=="undefined")}catch(k){return false}},elCache:{},getEl:function(k){return(typeof k==="string")?document.getElementById(k):k},clearCache:function(){},DOMReadyEvent:new YAHOO.util.CustomEvent("DOMReady",YAHOO,0,0,1),_load:function(l){if(!g){g=true;var k=YAHOO.util.Event;k._ready();k._tryPreloadAttach()}},_ready:function(l){var k=YAHOO.util.Event;if(!k.DOMReady){k.DOMReady=true;k.DOMReadyEvent.fire();k._simpleRemove(document,"DOMContentLoaded",k._ready)}},_tryPreloadAttach:function(){if(e.length===0){a=0;if(this._interval){this._interval.cancel();this._interval=null}return}if(this.locked){return}if(this.isIE){if(!this.DOMReady){this.startInterval();return}}this.locked=true;var q=!g;if(!q){q=(a>0&&e.length>0)}var p=[];var r=function(t,u){var s=t;if(u.overrideContext){if(u.overrideContext===true){s=u.obj}else{s=u.overrideContext}}u.fn.call(s,u.obj)};var l,k,o,n,m=[];for(l=0,k=e.length;l<k;l=l+1){o=e[l];if(o){n=this.getEl(o.id);if(n){if(o.checkReady){if(g||n.nextSibling||!q){m.push(o);e[l]=null}}else{r(n,o);e[l]=null}}else{p.push(o)}}}for(l=0,k=m.length;l<k;l=l+1){o=m[l];r(this.getEl(o.id),o)}a--;if(q){for(l=e.length-1;l>-1;l--){o=e[l];if(!o||!o.id){e.splice(l,1)}}this.startInterval()}else{if(this._interval){this._interval.cancel();this._interval=null}}this.locked=false},purgeElement:function(p,q,s){var n=(YAHOO.lang.isString(p))?this.getEl(p):p;var r=this.getListeners(n,s),o,k;if(r){for(o=r.length-1;o>-1;o--){var m=r[o];this.removeListener(n,m.type,m.fn)}}if(q&&n&&n.childNodes){for(o=0,k=n.childNodes.length;o<k;++o){this.purgeElement(n.childNodes[o],q,s)}}},getListeners:function(n,k){var q=[],m;if(!k){m=[h,j]}else{if(k==="unload"){m=[j]}else{k=this._getType(k);m=[h]}}var s=(YAHOO.lang.isString(n))?this.getEl(n):n;for(var p=0;p<m.length;p=p+1){var u=m[p];if(u){for(var r=0,t=u.length;r<t;++r){var o=u[r];if(o&&o[this.EL]===s&&(!k||k===o[this.TYPE])){q.push({type:o[this.TYPE],fn:o[this.FN],obj:o[this.OBJ],adjust:o[this.OVERRIDE],scope:o[this.ADJ_SCOPE],index:r})}}}}return(q.length)?q:null},_unload:function(s){var m=YAHOO.util.Event,p,o,n,r,q,t=j.slice(),k;for(p=0,r=j.length;p<r;++p){n=t[p];if(n){try{k=window;if(n[m.ADJ_SCOPE]){if(n[m.ADJ_SCOPE]===true){k=n[m.UNLOAD_OBJ]}else{k=n[m.ADJ_SCOPE]}}n[m.FN].call(k,m.getEvent(s,n[m.EL]),n[m.UNLOAD_OBJ])}catch(w){}t[p]=null}}n=null;k=null;j=null;if(h){for(o=h.length-1;o>-1;o--){n=h[o];if(n){try{m.removeListener(n[m.EL],n[m.TYPE],n[m.FN],o)}catch(v){}}}n=null}try{m._simpleRemove(window,"unload",m._unload);m._simpleRemove(window,"load",m._load)}catch(u){}},_getScrollLeft:function(){return this._getScroll()[1]},_getScrollTop:function(){return this._getScroll()[0]},_getScroll:function(){var k=document.documentElement,l=document.body;if(k&&(k.scrollTop||k.scrollLeft)){return[k.scrollTop,k.scrollLeft]}else{if(l){return[l.scrollTop,l.scrollLeft]}else{return[0,0]}}},regCE:function(){},_simpleAdd:function(){if(window.addEventListener){return function(m,n,l,k){m.addEventListener(n,l,(k))}}else{if(window.attachEvent){return function(m,n,l,k){m.attachEvent("on"+n,l)}}else{return function(){}}}}(),_simpleRemove:function(){if(window.removeEventListener){return function(m,n,l,k){m.removeEventListener(n,l,(k))}}else{if(window.detachEvent){return function(l,m,k){l.detachEvent("on"+m,k)}}else{return function(){}}}}()}}();(function(){var a=YAHOO.util.Event;a.on=a.addListener;a.onFocus=a.addFocusListener;a.onBlur=a.addBlurListener;
 /*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller/Diego Perini */
-if(a.isIE){if(self!==self.top){document.onreadystatechange=function(){if(document.readyState=="complete"){document.onreadystatechange=null;a._ready()}}}else{YAHOO.util.Event.onDOMReady(YAHOO.util.Event._tryPreloadAttach,YAHOO.util.Event,true);var b=document.createElement("p");a._dri=setInterval(function(){try{b.doScroll("left");clearInterval(a._dri);a._dri=null;a._ready();b=null}catch(c){}},a.POLL_INTERVAL)}}else{if(a.webkit&&a.webkit<525){a._dri=setInterval(function(){var c=document.readyState;if("loaded"==c||"complete"==c){clearInterval(a._dri);a._dri=null;a._ready()}},a.POLL_INTERVAL)}else{a._simpleAdd(document,"DOMContentLoaded",a._ready)}}a._simpleAdd(window,"load",a._load);a._simpleAdd(window,"unload",a._unload);a._tryPreloadAttach()})()}YAHOO.util.EventProvider=function(){};YAHOO.util.EventProvider.prototype={__yui_events:null,__yui_subscribers:null,subscribe:function(a,c,f,e){this.__yui_events=this.__yui_events||{};var d=this.__yui_events[a];if(d){d.subscribe(c,f,e)}else{this.__yui_subscribers=this.__yui_subscribers||{};var b=this.__yui_subscribers;if(!b[a]){b[a]=[]}b[a].push({fn:c,obj:f,overrideContext:e})}},unsubscribe:function(c,e,g){this.__yui_events=this.__yui_events||{};var a=this.__yui_events;if(c){var f=a[c];if(f){return f.unsubscribe(e,g)}}else{var b=true;for(var d in a){if(YAHOO.lang.hasOwnProperty(a,d)){b=b&&a[d].unsubscribe(e,g)}}return b}return false},unsubscribeAll:function(a){return this.unsubscribe(a)},createEvent:function(b,g){this.__yui_events=this.__yui_events||{};var e=g||{},d=this.__yui_events,f;if(d[b]){}else{f=new YAHOO.util.CustomEvent(b,e.scope||this,e.silent,YAHOO.util.CustomEvent.FLAT,e.fireOnce);d[b]=f;if(e.onSubscribeCallback){f.subscribeEvent.subscribe(e.onSubscribeCallback)}this.__yui_subscribers=this.__yui_subscribers||{};var a=this.__yui_subscribers[b];if(a){for(var c=0;c<a.length;++c){f.subscribe(a[c].fn,a[c].obj,a[c].overrideContext)}}}return d[b]},fireEvent:function(b){this.__yui_events=this.__yui_events||{};var d=this.__yui_events[b];if(!d){return null}var a=[];for(var c=1;c<arguments.length;++c){a.push(arguments[c])}return d.fire.apply(d,a)},hasEvent:function(a){if(this.__yui_events){if(this.__yui_events[a]){return true}}return false}};(function(){var a=YAHOO.util.Event,c=YAHOO.lang;YAHOO.util.KeyListener=function(d,i,e,f){if(!d){}else{if(!i){}else{if(!e){}}}if(!f){f=YAHOO.util.KeyListener.KEYDOWN}var g=new YAHOO.util.CustomEvent("keyPressed");this.enabledEvent=new YAHOO.util.CustomEvent("enabled");this.disabledEvent=new YAHOO.util.CustomEvent("disabled");if(c.isString(d)){d=document.getElementById(d)}if(c.isFunction(e)){g.subscribe(e)}else{g.subscribe(e.fn,e.scope,e.correctScope)}function h(o,n){if(!i.shift){i.shift=false}if(!i.alt){i.alt=false}if(!i.ctrl){i.ctrl=false}if(o.shiftKey==i.shift&&o.altKey==i.alt&&o.ctrlKey==i.ctrl){var j,m=i.keys,l;if(YAHOO.lang.isArray(m)){for(var k=0;k<m.length;k++){j=m[k];l=a.getCharCode(o);if(j==l){g.fire(l,o);break}}}else{l=a.getCharCode(o);if(m==l){g.fire(l,o)}}}}this.enable=function(){if(!this.enabled){a.on(d,f,h);this.enabledEvent.fire(i)}this.enabled=true};this.disable=function(){if(this.enabled){a.removeListener(d,f,h);this.disabledEvent.fire(i)}this.enabled=false};this.toString=function(){return"KeyListener ["+i.keys+"] "+d.tagName+(d.id?"["+d.id+"]":"")}};var b=YAHOO.util.KeyListener;b.KEYDOWN="keydown";b.KEYUP="keyup";b.KEY={ALT:18,BACK_SPACE:8,CAPS_LOCK:20,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,META:224,NUM_LOCK:144,PAGE_DOWN:34,PAGE_UP:33,PAUSE:19,PRINTSCREEN:44,RIGHT:39,SCROLL_LOCK:145,SHIFT:16,SPACE:32,TAB:9,UP:38}})();YAHOO.register("event",YAHOO.util.Event,{version:"2.9.0",build:"2800"});(function(){YAHOO.env._id_counter=YAHOO.env._id_counter||0;var e=YAHOO.util,k=YAHOO.lang,L=YAHOO.env.ua,a=YAHOO.lang.trim,B={},F={},m=/^t(?:able|d|h)$/i,w=/color$/i,j=window.document,v=j.documentElement,C="ownerDocument",M="defaultView",U="documentElement",S="compatMode",z="offsetLeft",o="offsetTop",T="offsetParent",x="parentNode",K="nodeType",c="tagName",n="scrollLeft",H="scrollTop",p="getBoundingClientRect",V="getComputedStyle",y="currentStyle",l="CSS1Compat",A="BackCompat",E="class",f="className",i="",b=" ",R="(?:^|\\s)",J="(?= |$)",t="g",O="position",D="fixed",u="relative",I="left",N="top",Q="medium",P="borderLeftWidth",q="borderTopWidth",d=L.opera,h=L.webkit,g=L.gecko,s=L.ie;e.Dom={CUSTOM_ATTRIBUTES:(!v.hasAttribute)?{"for":"htmlFor","class":f}:{htmlFor:"for",className:E},DOT_ATTRIBUTES:{checked:true},get:function(ab){var ad,X,ac,aa,W,G,Z=null;if(ab){if(typeof ab=="string"||typeof ab=="number"){ad=ab+"";ab=j.getElementById(ab);G=(ab)?ab.attributes:null;if(ab&&G&&G.id&&G.id.value===ad){return ab}else{if(ab&&j.all){ab=null;X=j.all[ad];if(X&&X.length){for(aa=0,W=X.length;aa<W;++aa){if(X[aa].id===ad){return X[aa]}}}}}}else{if(e.Element&&ab instanceof e.Element){ab=ab.get("element")}else{if(!ab.nodeType&&"length" in ab){ac=[];for(aa=0,W=ab.length;aa<W;++aa){ac[ac.length]=e.Dom.get(ab[aa])}ab=ac}}}Z=ab}return Z},getComputedStyle:function(G,W){if(window[V]){return G[C][M][V](G,null)[W]}else{if(G[y]){return e.Dom.IE_ComputedStyle.get(G,W)}}},getStyle:function(G,W){return e.Dom.batch(G,e.Dom._getStyle,W)},_getStyle:function(){if(window[V]){return function(G,Z){Z=(Z==="float")?Z="cssFloat":e.Dom._toCamel(Z);var X=G.style[Z],W;if(!X){W=G[C][M][V](G,null);if(W){X=W[Z]}}return X}}else{if(v[y]){return function(G,Z){var X;switch(Z){case"opacity":X=100;try{X=G.filters["DXImageTransform.Microsoft.Alpha"].opacity}catch(aa){try{X=G.filters("alpha").opacity}catch(W){}}return X/100;case"float":Z="styleFloat";default:Z=e.Dom._toCamel(Z);X=G[y]?G[y][Z]:null;return(G.style[Z]||X)}}}}}(),setStyle:function(G,W,X){e.Dom.batch(G,e.Dom._setStyle,{prop:W,val:X})},_setStyle:function(){if(!window.getComputedStyle&&j.documentElement.currentStyle){return function(W,G){var X=e.Dom._toCamel(G.prop),Z=G.val;if(W){switch(X){case"opacity":if(Z===""||Z===null||Z===1){W.style.removeAttribute("filter")}else{if(k.isString(W.style.filter)){W.style.filter="alpha(opacity="+Z*100+")";if(!W[y]||!W[y].hasLayout){W.style.zoom=1}}}break;case"float":X="styleFloat";default:W.style[X]=Z}}else{}}}else{return function(W,G){var X=e.Dom._toCamel(G.prop),Z=G.val;if(W){if(X=="float"){X="cssFloat"}W.style[X]=Z}else{}}}}(),getXY:function(G){return e.Dom.batch(G,e.Dom._getXY)},_canPosition:function(G){return(e.Dom._getStyle(G,"display")!=="none"&&e.Dom._inDoc(G))},_getXY:function(W){var X,G,aa,ac,Z,ab,ad=Math.round,ae=false;if(e.Dom._canPosition(W)){aa=W[p]();ac=W[C];X=e.Dom.getDocumentScrollLeft(ac);G=e.Dom.getDocumentScrollTop(ac);ae=[aa[I],aa[N]];if(Z||ab){ae[0]-=ab;ae[1]-=Z}if((G||X)){ae[0]+=X;ae[1]+=G}ae[0]=ad(ae[0]);ae[1]=ad(ae[1])}else{}return ae},getX:function(G){var W=function(X){return e.Dom.getXY(X)[0]};return e.Dom.batch(G,W,e.Dom,true)},getY:function(G){var W=function(X){return e.Dom.getXY(X)[1]};return e.Dom.batch(G,W,e.Dom,true)},setXY:function(G,X,W){e.Dom.batch(G,e.Dom._setXY,{pos:X,noRetry:W})},_setXY:function(G,aa){var ab=e.Dom._getStyle(G,O),Z=e.Dom.setStyle,ae=aa.pos,W=aa.noRetry,ac=[parseInt(e.Dom.getComputedStyle(G,I),10),parseInt(e.Dom.getComputedStyle(G,N),10)],ad,X;ad=e.Dom._getXY(G);if(!ae||ad===false){return false}if(ab=="static"){ab=u;Z(G,O,ab)}if(isNaN(ac[0])){ac[0]=(ab==u)?0:G[z]}if(isNaN(ac[1])){ac[1]=(ab==u)?0:G[o]}if(ae[0]!==null){Z(G,I,ae[0]-ad[0]+ac[0]+"px")}if(ae[1]!==null){Z(G,N,ae[1]-ad[1]+ac[1]+"px")}if(!W){X=e.Dom._getXY(G);if((ae[0]!==null&&X[0]!=ae[0])||(ae[1]!==null&&X[1]!=ae[1])){e.Dom._setXY(G,{pos:ae,noRetry:true})}}},setX:function(W,G){e.Dom.setXY(W,[G,null])},setY:function(G,W){e.Dom.setXY(G,[null,W])},getRegion:function(G){var W=function(X){var Z=false;if(e.Dom._canPosition(X)){Z=e.Region.getRegion(X)}else{}return Z};return e.Dom.batch(G,W,e.Dom,true)},getClientWidth:function(){return e.Dom.getViewportWidth()},getClientHeight:function(){return e.Dom.getViewportHeight()},getElementsByClassName:function(ac,ag,ad,af,X,ae){ag=ag||"*";ad=(ad)?e.Dom.get(ad):null||j;if(!ad){return[]}var W=[],G=ad.getElementsByTagName(ag),aa=e.Dom.hasClass;for(var Z=0,ab=G.length;Z<ab;++Z){if(aa(G[Z],ac)){W[W.length]=G[Z]}}if(af){e.Dom.batch(W,af,X,ae)}return W},hasClass:function(W,G){return e.Dom.batch(W,e.Dom._hasClass,G)},_hasClass:function(X,W){var G=false,Z;if(X&&W){Z=e.Dom._getAttribute(X,f)||i;if(Z){Z=Z.replace(/\s+/g,b)}if(W.exec){G=W.test(Z)}else{G=W&&(b+Z+b).indexOf(b+W+b)>-1}}else{}return G},addClass:function(W,G){return e.Dom.batch(W,e.Dom._addClass,G)},_addClass:function(X,W){var G=false,Z;if(X&&W){Z=e.Dom._getAttribute(X,f)||i;if(!e.Dom._hasClass(X,W)){e.Dom.setAttribute(X,f,a(Z+b+W));G=true}}else{}return G},removeClass:function(W,G){return e.Dom.batch(W,e.Dom._removeClass,G)},_removeClass:function(Z,X){var W=false,ab,aa,G;if(Z&&X){ab=e.Dom._getAttribute(Z,f)||i;e.Dom.setAttribute(Z,f,ab.replace(e.Dom._getClassRegex(X),i));aa=e.Dom._getAttribute(Z,f);if(ab!==aa){e.Dom.setAttribute(Z,f,a(aa));W=true;if(e.Dom._getAttribute(Z,f)===""){G=(Z.hasAttribute&&Z.hasAttribute(E))?E:f;Z.removeAttribute(G)}}}else{}return W},replaceClass:function(X,W,G){return e.Dom.batch(X,e.Dom._replaceClass,{from:W,to:G})},_replaceClass:function(Z,X){var W,ac,ab,G=false,aa;if(Z&&X){ac=X.from;ab=X.to;if(!ab){G=false}else{if(!ac){G=e.Dom._addClass(Z,X.to)}else{if(ac!==ab){aa=e.Dom._getAttribute(Z,f)||i;W=(b+aa.replace(e.Dom._getClassRegex(ac),b+ab).replace(/\s+/g,b)).split(e.Dom._getClassRegex(ab));W.splice(1,0,b+ab);e.Dom.setAttribute(Z,f,a(W.join(i)));G=true}}}}else{}return G},generateId:function(G,X){X=X||"yui-gen";var W=function(Z){if(Z&&Z.id){return Z.id}var aa=X+YAHOO.env._id_counter++;if(Z){if(Z[C]&&Z[C].getElementById(aa)){return e.Dom.generateId(Z,aa+X)}Z.id=aa}return aa};return e.Dom.batch(G,W,e.Dom,true)||W.apply(e.Dom,arguments)},isAncestor:function(W,X){W=e.Dom.get(W);X=e.Dom.get(X);var G=false;if((W&&X)&&(W[K]&&X[K])){if(W.contains&&W!==X){G=W.contains(X)}else{if(W.compareDocumentPosition){G=!!(W.compareDocumentPosition(X)&16)}}}else{}return G},inDocument:function(G,W){return e.Dom._inDoc(e.Dom.get(G),W)},_inDoc:function(W,X){var G=false;if(W&&W[c]){X=X||W[C];G=e.Dom.isAncestor(X[U],W)}else{}return G},getElementsBy:function(W,ag,ac,ae,X,ad,af){ag=ag||"*";ac=(ac)?e.Dom.get(ac):null||j;var ab=(af)?null:[],G;if(ac){G=ac.getElementsByTagName(ag);for(var Z=0,aa=G.length;Z<aa;++Z){if(W(G[Z])){if(af){ab=G[Z];break}else{ab[ab.length]=G[Z]}}}if(ae){e.Dom.batch(ab,ae,X,ad)}}return ab},getElementBy:function(X,G,W){return e.Dom.getElementsBy(X,G,W,null,null,null,true)},batch:function(X,ac,ab,aa){var Z=[],W=(aa)?ab:null;X=(X&&(X[c]||X.item))?X:e.Dom.get(X);if(X&&ac){if(X[c]||X.length===undefined){return ac.call(W,X,ab)}for(var G=0;G<X.length;++G){Z[Z.length]=ac.call(W||X[G],X[G],ab)}}else{return false}return Z},getDocumentHeight:function(){var W=(j[S]!=l||h)?j.body.scrollHeight:v.scrollHeight,G=Math.max(W,e.Dom.getViewportHeight());return G},getDocumentWidth:function(){var W=(j[S]!=l||h)?j.body.scrollWidth:v.scrollWidth,G=Math.max(W,e.Dom.getViewportWidth());return G},getViewportHeight:function(){var G=self.innerHeight,W=j[S];if((W||s)&&!d){G=(W==l)?v.clientHeight:j.body.clientHeight}return G},getViewportWidth:function(){var G=self.innerWidth,W=j[S];if(W||s){G=(W==l)?v.clientWidth:j.body.clientWidth}return G},getAncestorBy:function(G,W){while((G=G[x])){if(e.Dom._testElement(G,W)){return G}}return null},getAncestorByClassName:function(W,G){W=e.Dom.get(W);if(!W){return null}var X=function(Z){return e.Dom.hasClass(Z,G)};return e.Dom.getAncestorBy(W,X)},getAncestorByTagName:function(W,G){W=e.Dom.get(W);if(!W){return null}var X=function(Z){return Z[c]&&Z[c].toUpperCase()==G.toUpperCase()};return e.Dom.getAncestorBy(W,X)},getPreviousSiblingBy:function(G,W){while(G){G=G.previousSibling;if(e.Dom._testElement(G,W)){return G}}return null},getPreviousSibling:function(G){G=e.Dom.get(G);if(!G){return null}return e.Dom.getPreviousSiblingBy(G)},getNextSiblingBy:function(G,W){while(G){G=G.nextSibling;if(e.Dom._testElement(G,W)){return G}}return null},getNextSibling:function(G){G=e.Dom.get(G);if(!G){return null}return e.Dom.getNextSiblingBy(G)},getFirstChildBy:function(G,X){var W=(e.Dom._testElement(G.firstChild,X))?G.firstChild:null;return W||e.Dom.getNextSiblingBy(G.firstChild,X)},getFirstChild:function(G,W){G=e.Dom.get(G);if(!G){return null}return e.Dom.getFirstChildBy(G)},getLastChildBy:function(G,X){if(!G){return null}var W=(e.Dom._testElement(G.lastChild,X))?G.lastChild:null;return W||e.Dom.getPreviousSiblingBy(G.lastChild,X)},getLastChild:function(G){G=e.Dom.get(G);return e.Dom.getLastChildBy(G)},getChildrenBy:function(W,Z){var X=e.Dom.getFirstChildBy(W,Z),G=X?[X]:[];e.Dom.getNextSiblingBy(X,function(aa){if(!Z||Z(aa)){G[G.length]=aa}return false});return G},getChildren:function(G){G=e.Dom.get(G);if(!G){}return e.Dom.getChildrenBy(G)},getDocumentScrollLeft:function(G){G=G||j;return Math.max(G[U].scrollLeft,G.body.scrollLeft)},getDocumentScrollTop:function(G){G=G||j;return Math.max(G[U].scrollTop,G.body.scrollTop)},insertBefore:function(W,G){W=e.Dom.get(W);G=e.Dom.get(G);if(!W||!G||!G[x]){return null}return G[x].insertBefore(W,G)},insertAfter:function(W,G){W=e.Dom.get(W);G=e.Dom.get(G);if(!W||!G||!G[x]){return null}if(G.nextSibling){return G[x].insertBefore(W,G.nextSibling)}else{return G[x].appendChild(W)}},getClientRegion:function(){var X=e.Dom.getDocumentScrollTop(),W=e.Dom.getDocumentScrollLeft(),Z=e.Dom.getViewportWidth()+W,G=e.Dom.getViewportHeight()+X;return new e.Region(X,Z,G,W)},setAttribute:function(W,G,X){e.Dom.batch(W,e.Dom._setAttribute,{attr:G,val:X})},_setAttribute:function(X,W){var G=e.Dom._toCamel(W.attr),Z=W.val;if(X&&X.setAttribute){if(e.Dom.DOT_ATTRIBUTES[G]&&X.tagName&&X.tagName!="BUTTON"){X[G]=Z}else{G=e.Dom.CUSTOM_ATTRIBUTES[G]||G;X.setAttribute(G,Z)}}else{}},getAttribute:function(W,G){return e.Dom.batch(W,e.Dom._getAttribute,G)},_getAttribute:function(W,G){var X;G=e.Dom.CUSTOM_ATTRIBUTES[G]||G;if(e.Dom.DOT_ATTRIBUTES[G]){X=W[G]}else{if(W&&"getAttribute" in W){if(/^(?:href|src)$/.test(G)){X=W.getAttribute(G,2)}else{X=W.getAttribute(G)}}else{}}return X},_toCamel:function(W){var X=B;function G(Z,aa){return aa.toUpperCase()}return X[W]||(X[W]=W.indexOf("-")===-1?W:W.replace(/-([a-z])/gi,G))},_getClassRegex:function(W){var G;if(W!==undefined){if(W.exec){G=W}else{G=F[W];if(!G){W=W.replace(e.Dom._patterns.CLASS_RE_TOKENS,"\\$1");W=W.replace(/\s+/g,b);G=F[W]=new RegExp(R+W+J,t)}}}return G},_patterns:{ROOT_TAG:/^body|html$/i,CLASS_RE_TOKENS:/([\.\(\)\^\$\*\+\?\|\[\]\{\}\\])/g},_testElement:function(G,W){return G&&G[K]==1&&(!W||W(G))},_calcBorders:function(X,Z){var W=parseInt(e.Dom[V](X,q),10)||0,G=parseInt(e.Dom[V](X,P),10)||0;if(g){if(m.test(X[c])){W=0;G=0}}Z[0]+=G;Z[1]+=W;return Z}};var r=e.Dom[V];if(L.opera){e.Dom[V]=function(W,G){var X=r(W,G);if(w.test(G)){X=e.Dom.Color.toRGB(X)}return X}}if(L.webkit){e.Dom[V]=function(W,G){var X=r(W,G);if(X==="rgba(0, 0, 0, 0)"){X="transparent"}return X}}if(L.ie&&L.ie>=8){e.Dom.DOT_ATTRIBUTES.type=true}})();YAHOO.util.Region=function(d,e,a,c){this.top=d;this.y=d;this[1]=d;this.right=e;this.bottom=a;this.left=c;this.x=c;this[0]=c;this.width=this.right-this.left;this.height=this.bottom-this.top};YAHOO.util.Region.prototype.contains=function(a){return(a.left>=this.left&&a.right<=this.right&&a.top>=this.top&&a.bottom<=this.bottom)};YAHOO.util.Region.prototype.getArea=function(){return((this.bottom-this.top)*(this.right-this.left))};YAHOO.util.Region.prototype.intersect=function(f){var d=Math.max(this.top,f.top),e=Math.min(this.right,f.right),a=Math.min(this.bottom,f.bottom),c=Math.max(this.left,f.left);if(a>=d&&e>=c){return new YAHOO.util.Region(d,e,a,c)}else{return null}};YAHOO.util.Region.prototype.union=function(f){var d=Math.min(this.top,f.top),e=Math.max(this.right,f.right),a=Math.max(this.bottom,f.bottom),c=Math.min(this.left,f.left);return new YAHOO.util.Region(d,e,a,c)};YAHOO.util.Region.prototype.toString=function(){return("Region {top: "+this.top+", right: "+this.right+", bottom: "+this.bottom+", left: "+this.left+", height: "+this.height+", width: "+this.width+"}")};YAHOO.util.Region.getRegion=function(e){var g=YAHOO.util.Dom.getXY(e),d=g[1],f=g[0]+e.offsetWidth,a=g[1]+e.offsetHeight,c=g[0];return new YAHOO.util.Region(d,f,a,c)};YAHOO.util.Point=function(a,b){if(YAHOO.lang.isArray(a)){b=a[1];a=a[0]}YAHOO.util.Point.superclass.constructor.call(this,b,a,b,a)};YAHOO.extend(YAHOO.util.Point,YAHOO.util.Region);(function(){var b=YAHOO.util,a="clientTop",f="clientLeft",j="parentNode",k="right",w="hasLayout",i="px",u="opacity",l="auto",d="borderLeftWidth",g="borderTopWidth",p="borderRightWidth",v="borderBottomWidth",s="visible",q="transparent",n="height",e="width",h="style",t="currentStyle",r=/^width|height$/,o=/^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i,m={get:function(x,z){var y="",A=x[t][z];if(z===u){y=b.Dom.getStyle(x,u)}else{if(!A||(A.indexOf&&A.indexOf(i)>-1)){y=A}else{if(b.Dom.IE_COMPUTED[z]){y=b.Dom.IE_COMPUTED[z](x,z)}else{if(o.test(A)){y=b.Dom.IE.ComputedStyle.getPixel(x,z)}else{y=A}}}}return y},getOffset:function(z,E){var B=z[t][E],x=E.charAt(0).toUpperCase()+E.substr(1),C="offset"+x,y="pixel"+x,A="",D;if(B==l){D=z[C];if(D===undefined){A=0}A=D;if(r.test(E)){z[h][E]=D;if(z[C]>D){A=D-(z[C]-D)}z[h][E]=l}}else{if(!z[h][y]&&!z[h][E]){z[h][E]=B}A=z[h][y]}return A+i},getBorderWidth:function(x,z){var y=null;if(!x[t][w]){x[h].zoom=1}switch(z){case g:y=x[a];break;case v:y=x.offsetHeight-x.clientHeight-x[a];break;case d:y=x[f];break;case p:y=x.offsetWidth-x.clientWidth-x[f];break}return y+i},getPixel:function(y,x){var A=null,B=y[t][k],z=y[t][x];y[h][k]=z;A=y[h].pixelRight;y[h][k]=B;return A+i},getMargin:function(y,x){var z;if(y[t][x]==l){z=0+i}else{z=b.Dom.IE.ComputedStyle.getPixel(y,x)}return z},getVisibility:function(y,x){var z;while((z=y[t])&&z[x]=="inherit"){y=y[j]}return(z)?z[x]:s},getColor:function(y,x){return b.Dom.Color.toRGB(y[t][x])||q},getBorderColor:function(y,x){var z=y[t],A=z[x]||z.color;return b.Dom.Color.toRGB(b.Dom.Color.toHex(A))}},c={};c.top=c.right=c.bottom=c.left=c[e]=c[n]=m.getOffset;c.color=m.getColor;c[g]=c[p]=c[v]=c[d]=m.getBorderWidth;c.marginTop=c.marginRight=c.marginBottom=c.marginLeft=m.getMargin;c.visibility=m.getVisibility;c.borderColor=c.borderTopColor=c.borderRightColor=c.borderBottomColor=c.borderLeftColor=m.getBorderColor;b.Dom.IE_COMPUTED=c;b.Dom.IE_ComputedStyle=m})();(function(){var c="toString",a=parseInt,b=RegExp,d=YAHOO.util;d.Dom.Color={KEYWORDS:{black:"000",silver:"c0c0c0",gray:"808080",white:"fff",maroon:"800000",red:"f00",purple:"800080",fuchsia:"f0f",green:"008000",lime:"0f0",olive:"808000",yellow:"ff0",navy:"000080",blue:"00f",teal:"008080",aqua:"0ff"},re_RGB:/^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i,re_hex:/^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i,re_hex3:/([0-9A-F])/gi,toRGB:function(e){if(!d.Dom.Color.re_RGB.test(e)){e=d.Dom.Color.toHex(e)}if(d.Dom.Color.re_hex.exec(e)){e="rgb("+[a(b.$1,16),a(b.$2,16),a(b.$3,16)].join(", ")+")"}return e},toHex:function(f){f=d.Dom.Color.KEYWORDS[f]||f;if(d.Dom.Color.re_RGB.exec(f)){f=[Number(b.$1).toString(16),Number(b.$2).toString(16),Number(b.$3).toString(16)];for(var e=0;e<f.length;e++){if(f[e].length<2){f[e]="0"+f[e]}}f=f.join("")}if(f.length<6){f=f.replace(d.Dom.Color.re_hex3,"$1$1")}if(f!=="transparent"&&f.indexOf("#")<0){f="#"+f}return f.toUpperCase()}}}());YAHOO.register("dom",YAHOO.util.Dom,{version:"2.9.0",build:"2800"});YAHOO.util.Connect={_msxml_progid:["Microsoft.XMLHTTP","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP"],_http_headers:{},_has_http_headers:false,_use_default_post_header:true,_default_post_header:"application/x-www-form-urlencoded; charset=UTF-8",_default_form_header:"application/x-www-form-urlencoded",_use_default_xhr_header:true,_default_xhr_header:"XMLHttpRequest",_has_default_headers:true,_isFormSubmit:false,_default_headers:{},_poll:{},_timeOut:{},_polling_interval:50,_transaction_id:0,startEvent:new YAHOO.util.CustomEvent("start"),completeEvent:new YAHOO.util.CustomEvent("complete"),successEvent:new YAHOO.util.CustomEvent("success"),failureEvent:new YAHOO.util.CustomEvent("failure"),abortEvent:new YAHOO.util.CustomEvent("abort"),_customEvents:{onStart:["startEvent","start"],onComplete:["completeEvent","complete"],onSuccess:["successEvent","success"],onFailure:["failureEvent","failure"],onUpload:["uploadEvent","upload"],onAbort:["abortEvent","abort"]},setProgId:function(a){this._msxml_progid.unshift(a)},setDefaultPostHeader:function(a){if(typeof a=="string"){this._default_post_header=a;this._use_default_post_header=true}else{if(typeof a=="boolean"){this._use_default_post_header=a}}},setDefaultXhrHeader:function(a){if(typeof a=="string"){this._default_xhr_header=a}else{this._use_default_xhr_header=a}},setPollingInterval:function(a){if(typeof a=="number"&&isFinite(a)){this._polling_interval=a}},createXhrObject:function(g){var d,a,b;try{a=new XMLHttpRequest();d={conn:a,tId:g,xhr:true}}catch(c){for(b=0;b<this._msxml_progid.length;++b){try{a=new ActiveXObject(this._msxml_progid[b]);d={conn:a,tId:g,xhr:true};break}catch(f){}}}finally{return d}},getConnectionObject:function(a){var c,d=this._transaction_id;try{if(!a){c=this.createXhrObject(d)}else{c={tId:d};if(a==="xdr"){c.conn=this._transport;c.xdr=true}else{if(a==="upload"){c.upload=true}}}if(c){this._transaction_id++}}catch(b){}return c},asyncRequest:function(h,d,g,a){var b=g&&g.argument?g.argument:null,e=this,f,c;if(this._isFileUpload){c="upload"}else{if(g&&g.xdr){c="xdr"}}f=this.getConnectionObject(c);if(!f){return null}else{if(g&&g.customevents){this.initCustomEvents(f,g)}if(this._isFormSubmit){if(this._isFileUpload){window.setTimeout(function(){e.uploadFile(f,g,d,a)},10);return f}if(h.toUpperCase()=="GET"){if(this._sFormData.length!==0){d+=((d.indexOf("?")==-1)?"?":"&")+this._sFormData}}else{if(h.toUpperCase()=="POST"){a=a?this._sFormData+"&"+a:this._sFormData}}}if(h.toUpperCase()=="GET"&&(g&&g.cache===false)){d+=((d.indexOf("?")==-1)?"?":"&")+"rnd="+new Date().valueOf().toString()}if(this._use_default_xhr_header){if(!this._default_headers["X-Requested-With"]){this.initHeader("X-Requested-With",this._default_xhr_header,true)}}if((h.toUpperCase()==="POST"&&this._use_default_post_header)&&this._isFormSubmit===false){this.initHeader("Content-Type",this._default_post_header)}if(f.xdr){this.xdr(f,h,d,g,a);return f}f.conn.open(h,d,true);if(this._has_default_headers||this._has_http_headers){this.setHeader(f)}this.handleReadyState(f,g);f.conn.send(a||"");if(this._isFormSubmit===true){this.resetFormState()}this.startEvent.fire(f,b);if(f.startEvent){f.startEvent.fire(f,b)}return f}},initCustomEvents:function(a,c){var b;for(b in c.customevents){if(this._customEvents[b][0]){a[this._customEvents[b][0]]=new YAHOO.util.CustomEvent(this._customEvents[b][1],(c.scope)?c.scope:null);a[this._customEvents[b][0]].subscribe(c.customevents[b])}}},handleReadyState:function(c,d){var b=this,a=(d&&d.argument)?d.argument:null;if(d&&d.timeout){this._timeOut[c.tId]=window.setTimeout(function(){b.abort(c,d,true)},d.timeout)}this._poll[c.tId]=window.setInterval(function(){if(c.conn&&c.conn.readyState===4){window.clearInterval(b._poll[c.tId]);delete b._poll[c.tId];if(d&&d.timeout){window.clearTimeout(b._timeOut[c.tId]);delete b._timeOut[c.tId]}b.completeEvent.fire(c,a);if(c.completeEvent){c.completeEvent.fire(c,a)}b.handleTransactionResponse(c,d)}},this._polling_interval)},handleTransactionResponse:function(b,j,d){var f,a,h=(j&&j.argument)?j.argument:null,c=(b.r&&b.r.statusText==="xdr:success")?true:false,i=(b.r&&b.r.statusText==="xdr:failure")?true:false,k=d;try{if((b.conn.status!==undefined&&b.conn.status!==0)||c){f=b.conn.status}else{if(i&&!k){f=0}else{f=13030}}}catch(g){f=13030}if((f>=200&&f<300)||f===1223||c){a=b.xdr?b.r:this.createResponseObject(b,h);if(j&&j.success){if(!j.scope){j.success(a)}else{j.success.apply(j.scope,[a])}}this.successEvent.fire(a);if(b.successEvent){b.successEvent.fire(a)}}else{switch(f){case 12002:case 12029:case 12030:case 12031:case 12152:case 13030:a=this.createExceptionObject(b.tId,h,(d?d:false));if(j&&j.failure){if(!j.scope){j.failure(a)}else{j.failure.apply(j.scope,[a])}}break;default:a=(b.xdr)?b.response:this.createResponseObject(b,h);if(j&&j.failure){if(!j.scope){j.failure(a)}else{j.failure.apply(j.scope,[a])}}}this.failureEvent.fire(a);if(b.failureEvent){b.failureEvent.fire(a)}}this.releaseObject(b);a=null},createResponseObject:function(a,h){var d={},k={},f,c,g,b;try{c=a.conn.getAllResponseHeaders();g=c.split("\n");for(f=0;f<g.length;f++){b=g[f].indexOf(":");if(b!=-1){k[g[f].substring(0,b)]=YAHOO.lang.trim(g[f].substring(b+2))}}}catch(j){}d.tId=a.tId;d.status=(a.conn.status==1223)?204:a.conn.status;d.statusText=(a.conn.status==1223)?"No Content":a.conn.statusText;d.getResponseHeader=k;d.getAllResponseHeaders=c;d.responseText=a.conn.responseText;d.responseXML=a.conn.responseXML;if(h){d.argument=h}return d},createExceptionObject:function(h,d,a){var f=0,g="communication failure",c=-1,b="transaction aborted",e={};e.tId=h;if(a){e.status=c;e.statusText=b}else{e.status=f;e.statusText=g}if(d){e.argument=d}return e},initHeader:function(a,d,c){var b=(c)?this._default_headers:this._http_headers;b[a]=d;if(c){this._has_default_headers=true}else{this._has_http_headers=true}},setHeader:function(a){var b;if(this._has_default_headers){for(b in this._default_headers){if(YAHOO.lang.hasOwnProperty(this._default_headers,b)){a.conn.setRequestHeader(b,this._default_headers[b])}}}if(this._has_http_headers){for(b in this._http_headers){if(YAHOO.lang.hasOwnProperty(this._http_headers,b)){a.conn.setRequestHeader(b,this._http_headers[b])}}this._http_headers={};this._has_http_headers=false}},resetDefaultHeaders:function(){this._default_headers={};this._has_default_headers=false},abort:function(e,g,a){var d,b=(g&&g.argument)?g.argument:null;e=e||{};if(e.conn){if(e.xhr){if(this.isCallInProgress(e)){e.conn.abort();window.clearInterval(this._poll[e.tId]);delete this._poll[e.tId];if(a){window.clearTimeout(this._timeOut[e.tId]);delete this._timeOut[e.tId]}d=true}}else{if(e.xdr){e.conn.abort(e.tId);d=true}}}else{if(e.upload){var c="yuiIO"+e.tId;var f=document.getElementById(c);if(f){YAHOO.util.Event.removeListener(f,"load");document.body.removeChild(f);if(a){window.clearTimeout(this._timeOut[e.tId]);delete this._timeOut[e.tId]}d=true}}else{d=false}}if(d===true){this.abortEvent.fire(e,b);if(e.abortEvent){e.abortEvent.fire(e,b)}this.handleTransactionResponse(e,g,true)}return d},isCallInProgress:function(a){a=a||{};if(a.xhr&&a.conn){return a.conn.readyState!==4&&a.conn.readyState!==0}else{if(a.xdr&&a.conn){return a.conn.isCallInProgress(a.tId)}else{if(a.upload===true){return document.getElementById("yuiIO"+a.tId)?true:false}else{return false}}}},releaseObject:function(a){if(a&&a.conn){a.conn=null;a=null}}};(function(){var g=YAHOO.util.Connect,h={};function d(i){var j='<object id="YUIConnectionSwf" type="application/x-shockwave-flash" data="'+i+'" width="0" height="0"><param name="movie" value="'+i+'"><param name="allowScriptAccess" value="always"></object>',k=document.createElement("div");document.body.appendChild(k);k.innerHTML=j}function b(l,i,j,n,k){h[parseInt(l.tId)]={o:l,c:n};if(k){n.method=i;n.data=k}l.conn.send(j,n,l.tId)}function e(i){d(i);g._transport=document.getElementById("YUIConnectionSwf")}function c(){g.xdrReadyEvent.fire()}function a(j,i){if(j){g.startEvent.fire(j,i.argument);if(j.startEvent){j.startEvent.fire(j,i.argument)}}}function f(j){var k=h[j.tId].o,i=h[j.tId].c;if(j.statusText==="xdr:start"){a(k,i);return}j.responseText=decodeURI(j.responseText);k.r=j;if(i.argument){k.r.argument=i.argument}this.handleTransactionResponse(k,i,j.statusText==="xdr:abort"?true:false);delete h[j.tId]}g.xdr=b;g.swf=d;g.transport=e;g.xdrReadyEvent=new YAHOO.util.CustomEvent("xdrReady");g.xdrReady=c;g.handleXdrResponse=f})();(function(){var e=YAHOO.util.Connect,g=YAHOO.util.Event,a=document.documentMode?document.documentMode:false;e._isFileUpload=false;e._formNode=null;e._sFormData=null;e._submitElementValue=null;e.uploadEvent=new YAHOO.util.CustomEvent("upload");e._hasSubmitListener=function(){if(g){g.addListener(document,"click",function(k){var j=g.getTarget(k),i=j.nodeName.toLowerCase();if((i==="input"||i==="button")&&(j.type&&j.type.toLowerCase()=="submit")){e._submitElementValue=encodeURIComponent(j.name)+"="+encodeURIComponent(j.value)}});return true}return false}();function h(w,r,m){var v,l,u,s,z,t=false,p=[],y=0,o,q,n,x,k;this.resetFormState();if(typeof w=="string"){v=(document.getElementById(w)||document.forms[w])}else{if(typeof w=="object"){v=w}else{return}}if(r){this.createFrame(m?m:null);this._isFormSubmit=true;this._isFileUpload=true;this._formNode=v;return}for(o=0,q=v.elements.length;o<q;++o){l=v.elements[o];z=l.disabled;u=l.name;if(!z&&u){u=encodeURIComponent(u)+"=";s=encodeURIComponent(l.value);switch(l.type){case"select-one":if(l.selectedIndex>-1){k=l.options[l.selectedIndex];p[y++]=u+encodeURIComponent((k.attributes.value&&k.attributes.value.specified)?k.value:k.text)}break;case"select-multiple":if(l.selectedIndex>-1){for(n=l.selectedIndex,x=l.options.length;n<x;++n){k=l.options[n];if(k.selected){p[y++]=u+encodeURIComponent((k.attributes.value&&k.attributes.value.specified)?k.value:k.text)}}}break;case"radio":case"checkbox":if(l.checked){p[y++]=u+s}break;case"file":case undefined:case"reset":case"button":break;case"submit":if(t===false){if(this._hasSubmitListener&&this._submitElementValue){p[y++]=this._submitElementValue}t=true}break;default:p[y++]=u+s}}}this._isFormSubmit=true;this._sFormData=p.join("&");this.initHeader("Content-Type",this._default_form_header);return this._sFormData}function d(){this._isFormSubmit=false;this._isFileUpload=false;this._formNode=null;this._sFormData=""}function c(i){var j="yuiIO"+this._transaction_id,l=(a===9)?true:false,k;if(YAHOO.env.ua.ie&&!l){k=document.createElement('<iframe id="'+j+'" name="'+j+'" />');if(typeof i=="boolean"){k.src="javascript:false"}}else{k=document.createElement("iframe");k.id=j;k.name=j}k.style.position="absolute";k.style.top="-1000px";k.style.left="-1000px";document.body.appendChild(k)}function f(j){var m=[],k=j.split("&"),l,n;for(l=0;l<k.length;l++){n=k[l].indexOf("=");if(n!=-1){m[l]=document.createElement("input");m[l].type="hidden";m[l].name=decodeURIComponent(k[l].substring(0,n));m[l].value=decodeURIComponent(k[l].substring(n+1));this._formNode.appendChild(m[l])}}return m}function b(m,y,n,l){var t="yuiIO"+m.tId,u="multipart/form-data",w=document.getElementById(t),p=(a>=8)?true:false,z=this,v=(y&&y.argument)?y.argument:null,x,s,k,r,j,q;j={action:this._formNode.getAttribute("action"),method:this._formNode.getAttribute("method"),target:this._formNode.getAttribute("target")};this._formNode.setAttribute("action",n);this._formNode.setAttribute("method","POST");this._formNode.setAttribute("target",t);if(YAHOO.env.ua.ie&&!p){this._formNode.setAttribute("encoding",u)}else{this._formNode.setAttribute("enctype",u)}if(l){x=this.appendPostData(l)}this._formNode.submit();this.startEvent.fire(m,v);if(m.startEvent){m.startEvent.fire(m,v)}if(y&&y.timeout){this._timeOut[m.tId]=window.setTimeout(function(){z.abort(m,y,true)},y.timeout)}if(x&&x.length>0){for(s=0;s<x.length;s++){this._formNode.removeChild(x[s])}}for(k in j){if(YAHOO.lang.hasOwnProperty(j,k)){if(j[k]){this._formNode.setAttribute(k,j[k])}else{this._formNode.removeAttribute(k)}}}this.resetFormState();q=function(){var i,A,B;if(y&&y.timeout){window.clearTimeout(z._timeOut[m.tId]);delete z._timeOut[m.tId]}z.completeEvent.fire(m,v);if(m.completeEvent){m.completeEvent.fire(m,v)}r={tId:m.tId,argument:v};try{i=w.contentWindow.document.getElementsByTagName("body")[0];A=w.contentWindow.document.getElementsByTagName("pre")[0];if(i){if(A){B=A.textContent?A.textContent:A.innerText}else{B=i.textContent?i.textContent:i.innerText}}r.responseText=B;r.responseXML=w.contentWindow.document.XMLDocument?w.contentWindow.document.XMLDocument:w.contentWindow.document}catch(o){}if(y&&y.upload){if(!y.scope){y.upload(r)}else{y.upload.apply(y.scope,[r])}}z.uploadEvent.fire(r);if(m.uploadEvent){m.uploadEvent.fire(r)}g.removeListener(w,"load",q);setTimeout(function(){document.body.removeChild(w);z.releaseObject(m)},100)};g.addListener(w,"load",q)}e.setForm=h;e.resetFormState=d;e.createFrame=c;e.appendPostData=f;e.uploadFile=b})();YAHOO.register("connection",YAHOO.util.Connect,{version:"2.9.0",build:"2800"});(function(){var b=YAHOO.util;var a=function(d,c,e,f){if(!d){}this.init(d,c,e,f)};a.NAME="Anim";a.prototype={toString:function(){var c=this.getEl()||{};var d=c.id||c.tagName;return(this.constructor.NAME+": "+d)},patterns:{noNegatives:/width|height|opacity|padding/i,offsetAttribute:/^((width|height)|(top|left))$/,defaultUnit:/width|height|top$|bottom$|left$|right$/i,offsetUnit:/\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i},doMethod:function(c,e,d){return this.method(this.currentFrame,e,d-e,this.totalFrames)},setAttribute:function(c,f,e){var d=this.getEl();if(this.patterns.noNegatives.test(c)){f=(f>0)?f:0}if(c in d&&!("style" in d&&c in d.style)){d[c]=f}else{b.Dom.setStyle(d,c,f+e)}},getAttribute:function(c){var e=this.getEl();var g=b.Dom.getStyle(e,c);if(g!=="auto"&&!this.patterns.offsetUnit.test(g)){return parseFloat(g)}var d=this.patterns.offsetAttribute.exec(c)||[];var h=!!(d[3]);var f=!!(d[2]);if("style" in e){if(f||(b.Dom.getStyle(e,"position")=="absolute"&&h)){g=e["offset"+d[0].charAt(0).toUpperCase()+d[0].substr(1)]}else{g=0}}else{if(c in e){g=e[c]}}return g},getDefaultUnit:function(c){if(this.patterns.defaultUnit.test(c)){return"px"}return""},setRuntimeAttribute:function(d){var j;var e;var f=this.attributes;this.runtimeAttributes[d]={};var h=function(i){return(typeof i!=="undefined")};if(!h(f[d]["to"])&&!h(f[d]["by"])){return false}j=(h(f[d]["from"]))?f[d]["from"]:this.getAttribute(d);if(h(f[d]["to"])){e=f[d]["to"]}else{if(h(f[d]["by"])){if(j.constructor==Array){e=[];for(var g=0,c=j.length;g<c;++g){e[g]=j[g]+f[d]["by"][g]*1}}else{e=j+f[d]["by"]*1}}}this.runtimeAttributes[d].start=j;this.runtimeAttributes[d].end=e;this.runtimeAttributes[d].unit=(h(f[d].unit))?f[d]["unit"]:this.getDefaultUnit(d);return true},init:function(f,c,h,i){var d=false;var e=null;var g=0;f=b.Dom.get(f);this.attributes=c||{};this.duration=!YAHOO.lang.isUndefined(h)?h:1;this.method=i||b.Easing.easeNone;this.useSeconds=true;this.currentFrame=0;this.totalFrames=b.AnimMgr.fps;this.setEl=function(j){f=b.Dom.get(j)};this.getEl=function(){return f};this.isAnimated=function(){return d};this.getStartTime=function(){return e};this.runtimeAttributes={};this.animate=function(){if(this.isAnimated()){return false}this.currentFrame=0;this.totalFrames=(this.useSeconds)?Math.ceil(b.AnimMgr.fps*this.duration):this.duration;if(this.duration===0&&this.useSeconds){this.totalFrames=1}b.AnimMgr.registerElement(this);return true};this.stop=function(j){if(!this.isAnimated()){return false}if(j){this.currentFrame=this.totalFrames;this._onTween.fire()}b.AnimMgr.stop(this)};this._handleStart=function(){this.onStart.fire();this.runtimeAttributes={};for(var j in this.attributes){if(this.attributes.hasOwnProperty(j)){this.setRuntimeAttribute(j)}}d=true;g=0;e=new Date()};this._handleTween=function(){var l={duration:new Date()-this.getStartTime(),currentFrame:this.currentFrame};l.toString=function(){return("duration: "+l.duration+", currentFrame: "+l.currentFrame)};this.onTween.fire(l);var k=this.runtimeAttributes;for(var j in k){if(k.hasOwnProperty(j)){this.setAttribute(j,this.doMethod(j,k[j].start,k[j].end),k[j].unit)}}this.afterTween.fire(l);g+=1};this._handleComplete=function(){var j=(new Date()-e)/1000;var k={duration:j,frames:g,fps:g/j};k.toString=function(){return("duration: "+k.duration+", frames: "+k.frames+", fps: "+k.fps)};d=false;g=0;this.onComplete.fire(k)};this._onStart=new b.CustomEvent("_start",this,true);this.onStart=new b.CustomEvent("start",this);this.onTween=new b.CustomEvent("tween",this);this.afterTween=new b.CustomEvent("afterTween",this);this._onTween=new b.CustomEvent("_tween",this,true);this.onComplete=new b.CustomEvent("complete",this);this._onComplete=new b.CustomEvent("_complete",this,true);this._onStart.subscribe(this._handleStart);this._onTween.subscribe(this._handleTween);this._onComplete.subscribe(this._handleComplete)}};b.Anim=a})();YAHOO.util.AnimMgr=new function(){var e=null;var c=[];var g=0;this.fps=1000;this.delay=20;this.registerElement=function(j){c[c.length]=j;g+=1;j._onStart.fire();this.start()};var f=[];var d=false;var h=function(){var j=f.shift();b.apply(YAHOO.util.AnimMgr,j);if(f.length){arguments.callee()}};var b=function(k,j){j=j||a(k);if(!k.isAnimated()||j===-1){return false}k._onComplete.fire();c.splice(j,1);g-=1;if(g<=0){this.stop()}return true};this.unRegister=function(){f.push(arguments);if(!d){d=true;h();d=false}};this.start=function(){if(e===null){e=setInterval(this.run,this.delay)}};this.stop=function(l){if(!l){clearInterval(e);for(var k=0,j=c.length;k<j;++k){this.unRegister(c[0],0)}c=[];e=null;g=0}else{this.unRegister(l)}};this.run=function(){for(var l=0,j=c.length;l<j;++l){var k=c[l];if(!k||!k.isAnimated()){continue}if(k.currentFrame<k.totalFrames||k.totalFrames===null){k.currentFrame+=1;if(k.useSeconds){i(k)}k._onTween.fire()}else{YAHOO.util.AnimMgr.stop(k,l)}}};var a=function(l){for(var k=0,j=c.length;k<j;++k){if(c[k]===l){return k}}return -1};var i=function(k){var n=k.totalFrames;var m=k.currentFrame;var l=(k.currentFrame*k.duration*1000/k.totalFrames);var j=(new Date()-k.getStartTime());var o=0;if(j<k.duration*1000){o=Math.round((j/l-1)*k.currentFrame)}else{o=n-(m+1)}if(o>0&&isFinite(o)){if(k.currentFrame+o>=n){o=n-(m+1)}k.currentFrame+=o}};this._queue=c;this._getIndex=a};YAHOO.util.Bezier=new function(){this.getPosition=function(e,d){var f=e.length;var c=[];for(var b=0;b<f;++b){c[b]=[e[b][0],e[b][1]]}for(var a=1;a<f;++a){for(b=0;b<f-a;++b){c[b][0]=(1-d)*c[b][0]+d*c[parseInt(b+1,10)][0];c[b][1]=(1-d)*c[b][1]+d*c[parseInt(b+1,10)][1]}}return[c[0][0],c[0][1]]}};(function(){var a=function(f,e,g,h){a.superclass.constructor.call(this,f,e,g,h)};a.NAME="ColorAnim";a.DEFAULT_BGCOLOR="#fff";var c=YAHOO.util;YAHOO.extend(a,c.Anim);var d=a.superclass;var b=a.prototype;b.patterns.color=/color$/i;b.patterns.rgb=/^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;b.patterns.hex=/^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;b.patterns.hex3=/^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;b.patterns.transparent=/^transparent|rgba\(0, 0, 0, 0\)$/;b.parseColor=function(e){if(e.length==3){return e}var f=this.patterns.hex.exec(e);if(f&&f.length==4){return[parseInt(f[1],16),parseInt(f[2],16),parseInt(f[3],16)]}f=this.patterns.rgb.exec(e);if(f&&f.length==4){return[parseInt(f[1],10),parseInt(f[2],10),parseInt(f[3],10)]}f=this.patterns.hex3.exec(e);if(f&&f.length==4){return[parseInt(f[1]+f[1],16),parseInt(f[2]+f[2],16),parseInt(f[3]+f[3],16)]}return null};b.getAttribute=function(e){var g=this.getEl();if(this.patterns.color.test(e)){var i=YAHOO.util.Dom.getStyle(g,e);var h=this;if(this.patterns.transparent.test(i)){var f=YAHOO.util.Dom.getAncestorBy(g,function(j){return !h.patterns.transparent.test(i)});if(f){i=c.Dom.getStyle(f,e)}else{i=a.DEFAULT_BGCOLOR}}}else{i=d.getAttribute.call(this,e)}return i};b.doMethod=function(f,k,g){var j;if(this.patterns.color.test(f)){j=[];for(var h=0,e=k.length;h<e;++h){j[h]=d.doMethod.call(this,f,k[h],g[h])}j="rgb("+Math.floor(j[0])+","+Math.floor(j[1])+","+Math.floor(j[2])+")"}else{j=d.doMethod.call(this,f,k,g)}return j};b.setRuntimeAttribute=function(f){d.setRuntimeAttribute.call(this,f);if(this.patterns.color.test(f)){var h=this.attributes;var k=this.parseColor(this.runtimeAttributes[f].start);var g=this.parseColor(this.runtimeAttributes[f].end);if(typeof h[f]["to"]==="undefined"&&typeof h[f]["by"]!=="undefined"){g=this.parseColor(h[f].by);for(var j=0,e=k.length;j<e;++j){g[j]=k[j]+g[j]}}this.runtimeAttributes[f].start=k;this.runtimeAttributes[f].end=g}};c.ColorAnim=a})();
+if(a.isIE){if(self!==self.top){document.onreadystatechange=function(){if(document.readyState=="complete"){document.onreadystatechange=null;a._ready()}}}else{YAHOO.util.Event.onDOMReady(YAHOO.util.Event._tryPreloadAttach,YAHOO.util.Event,true);var b=document.createElement("p");a._dri=setInterval(function(){try{b.doScroll("left");clearInterval(a._dri);a._dri=null;a._ready();b=null}catch(c){}},a.POLL_INTERVAL)}}else{if(a.webkit&&a.webkit<525){a._dri=setInterval(function(){var c=document.readyState;if("loaded"==c||"complete"==c){clearInterval(a._dri);a._dri=null;a._ready()}},a.POLL_INTERVAL)}else{a._simpleAdd(document,"DOMContentLoaded",a._ready)}}a._simpleAdd(window,"load",a._load);a._simpleAdd(window,"unload",a._unload);a._tryPreloadAttach()})()}YAHOO.util.EventProvider=function(){};YAHOO.util.EventProvider.prototype={__yui_events:null,__yui_subscribers:null,subscribe:function(a,c,f,e){this.__yui_events=this.__yui_events||{};var d=this.__yui_events[a];if(d){d.subscribe(c,f,e)}else{this.__yui_subscribers=this.__yui_subscribers||{};var b=this.__yui_subscribers;if(!b[a]){b[a]=[]}b[a].push({fn:c,obj:f,overrideContext:e})}},unsubscribe:function(c,e,g){this.__yui_events=this.__yui_events||{};var a=this.__yui_events;if(c){var f=a[c];if(f){return f.unsubscribe(e,g)}}else{var b=true;for(var d in a){if(YAHOO.lang.hasOwnProperty(a,d)){b=b&&a[d].unsubscribe(e,g)}}return b}return false},unsubscribeAll:function(a){return this.unsubscribe(a)},createEvent:function(b,g){this.__yui_events=this.__yui_events||{};var e=g||{},d=this.__yui_events,f;if(d[b]){}else{f=new YAHOO.util.CustomEvent(b,e.scope||this,e.silent,YAHOO.util.CustomEvent.FLAT,e.fireOnce);d[b]=f;if(e.onSubscribeCallback){f.subscribeEvent.subscribe(e.onSubscribeCallback)}this.__yui_subscribers=this.__yui_subscribers||{};var a=this.__yui_subscribers[b];if(a){for(var c=0;c<a.length;++c){f.subscribe(a[c].fn,a[c].obj,a[c].overrideContext)}}}return d[b]},fireEvent:function(b){this.__yui_events=this.__yui_events||{};var d=this.__yui_events[b];if(!d){return null}var a=[];for(var c=1;c<arguments.length;++c){a.push(arguments[c])}return d.fire.apply(d,a)},hasEvent:function(a){if(this.__yui_events){if(this.__yui_events[a]){return true}}return false}};(function(){var a=YAHOO.util.Event,c=YAHOO.lang;YAHOO.util.KeyListener=function(d,i,e,f){if(!d){}else{if(!i){}else{if(!e){}}}if(!f){f=YAHOO.util.KeyListener.KEYDOWN}var g=new YAHOO.util.CustomEvent("keyPressed");this.enabledEvent=new YAHOO.util.CustomEvent("enabled");this.disabledEvent=new YAHOO.util.CustomEvent("disabled");if(c.isString(d)){d=document.getElementById(d)}if(c.isFunction(e)){g.subscribe(e)}else{g.subscribe(e.fn,e.scope,e.correctScope)}function h(o,n){if(!i.shift){i.shift=false}if(!i.alt){i.alt=false}if(!i.ctrl){i.ctrl=false}if(o.shiftKey==i.shift&&o.altKey==i.alt&&o.ctrlKey==i.ctrl){var j,m=i.keys,l;if(YAHOO.lang.isArray(m)){for(var k=0;k<m.length;k++){j=m[k];l=a.getCharCode(o);if(j==l){g.fire(l,o);break}}}else{l=a.getCharCode(o);if(m==l){g.fire(l,o)}}}}this.enable=function(){if(!this.enabled){a.on(d,f,h);this.enabledEvent.fire(i)}this.enabled=true};this.disable=function(){if(this.enabled){a.removeListener(d,f,h);this.disabledEvent.fire(i)}this.enabled=false};this.toString=function(){return"KeyListener ["+i.keys+"] "+d.tagName+(d.id?"["+d.id+"]":"")}};var b=YAHOO.util.KeyListener;b.KEYDOWN="keydown";b.KEYUP="keyup";b.KEY={ALT:18,BACK_SPACE:8,CAPS_LOCK:20,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,META:224,NUM_LOCK:144,PAGE_DOWN:34,PAGE_UP:33,PAUSE:19,PRINTSCREEN:44,RIGHT:39,SCROLL_LOCK:145,SHIFT:16,SPACE:32,TAB:9,UP:38}})();YAHOO.register("event",YAHOO.util.Event,{version:"2.9.0",build:"2800"});(function(){YAHOO.env._id_counter=YAHOO.env._id_counter||0;var e=YAHOO.util,k=YAHOO.lang,L=YAHOO.env.ua,a=YAHOO.lang.trim,B={},F={},m=/^t(?:able|d|h)$/i,w=/color$/i,j=window.document,v=j.documentElement,C="ownerDocument",M="defaultView",U="documentElement",S="compatMode",z="offsetLeft",o="offsetTop",T="offsetParent",x="parentNode",K="nodeType",c="tagName",n="scrollLeft",H="scrollTop",p="getBoundingClientRect",V="getComputedStyle",y="currentStyle",l="CSS1Compat",A="BackCompat",E="class",f="className",i="",b=" ",R="(?:^|\\s)",J="(?= |$)",t="g",O="position",D="fixed",u="relative",I="left",N="top",Q="medium",P="borderLeftWidth",q="borderTopWidth",d=L.opera,h=L.webkit,g=L.gecko,s=L.ie;e.Dom={CUSTOM_ATTRIBUTES:(!v.hasAttribute)?{"for":"htmlFor","class":f}:{htmlFor:"for",className:E},DOT_ATTRIBUTES:{checked:true},get:function(aa){var ac,X,ab,Z,W,G,Y=null;if(aa){if(typeof aa=="string"||typeof aa=="number"){ac=aa+"";aa=j.getElementById(aa);G=(aa)?aa.attributes:null;if(aa&&G&&G.id&&G.id.value===ac){return aa}else{if(aa&&j.all){aa=null;X=j.all[ac];if(X&&X.length){for(Z=0,W=X.length;Z<W;++Z){if(X[Z].id===ac){return X[Z]}}}}}}else{if(e.Element&&aa instanceof e.Element){aa=aa.get("element")}else{if(!aa.nodeType&&"length" in aa){ab=[];for(Z=0,W=aa.length;Z<W;++Z){ab[ab.length]=e.Dom.get(aa[Z])}aa=ab}}}Y=aa}return Y},getComputedStyle:function(G,W){if(window[V]){return G[C][M][V](G,null)[W]}else{if(G[y]){return e.Dom.IE_ComputedStyle.get(G,W)}}},getStyle:function(G,W){return e.Dom.batch(G,e.Dom._getStyle,W)},_getStyle:function(){if(window[V]){return function(G,Y){Y=(Y==="float")?Y="cssFloat":e.Dom._toCamel(Y);var X=G.style[Y],W;if(!X){W=G[C][M][V](G,null);if(W){X=W[Y]}}return X}}else{if(v[y]){return function(G,Y){var X;switch(Y){case"opacity":X=100;try{X=G.filters["DXImageTransform.Microsoft.Alpha"].opacity}catch(Z){try{X=G.filters("alpha").opacity}catch(W){}}return X/100;case"float":Y="styleFloat";default:Y=e.Dom._toCamel(Y);X=G[y]?G[y][Y]:null;return(G.style[Y]||X)}}}}}(),setStyle:function(G,W,X){e.Dom.batch(G,e.Dom._setStyle,{prop:W,val:X})},_setStyle:function(){if(!window.getComputedStyle&&j.documentElement.currentStyle){return function(W,G){var X=e.Dom._toCamel(G.prop),Y=G.val;if(W){switch(X){case"opacity":if(Y===""||Y===null||Y===1){W.style.removeAttribute("filter")}else{if(k.isString(W.style.filter)){W.style.filter="alpha(opacity="+Y*100+")";if(!W[y]||!W[y].hasLayout){W.style.zoom=1}}}break;case"float":X="styleFloat";default:W.style[X]=Y}}else{}}}else{return function(W,G){var X=e.Dom._toCamel(G.prop),Y=G.val;if(W){if(X=="float"){X="cssFloat"}W.style[X]=Y}else{}}}}(),getXY:function(G){return e.Dom.batch(G,e.Dom._getXY)},_canPosition:function(G){return(e.Dom._getStyle(G,"display")!=="none"&&e.Dom._inDoc(G))},_getXY:function(W){var X,G,Z,ab,Y,aa,ac=Math.round,ad=false;if(e.Dom._canPosition(W)){Z=W[p]();ab=W[C];X=e.Dom.getDocumentScrollLeft(ab);G=e.Dom.getDocumentScrollTop(ab);ad=[Z[I],Z[N]];if(Y||aa){ad[0]-=aa;ad[1]-=Y}if((G||X)){ad[0]+=X;ad[1]+=G}ad[0]=ac(ad[0]);ad[1]=ac(ad[1])}else{}return ad},getX:function(G){var W=function(X){return e.Dom.getXY(X)[0]};return e.Dom.batch(G,W,e.Dom,true)},getY:function(G){var W=function(X){return e.Dom.getXY(X)[1]};return e.Dom.batch(G,W,e.Dom,true)},setXY:function(G,X,W){e.Dom.batch(G,e.Dom._setXY,{pos:X,noRetry:W})},_setXY:function(G,Z){var aa=e.Dom._getStyle(G,O),Y=e.Dom.setStyle,ad=Z.pos,W=Z.noRetry,ab=[parseInt(e.Dom.getComputedStyle(G,I),10),parseInt(e.Dom.getComputedStyle(G,N),10)],ac,X;ac=e.Dom._getXY(G);if(!ad||ac===false){return false}if(aa=="static"){aa=u;Y(G,O,aa)}if(isNaN(ab[0])){ab[0]=(aa==u)?0:G[z]}if(isNaN(ab[1])){ab[1]=(aa==u)?0:G[o]}if(ad[0]!==null){Y(G,I,ad[0]-ac[0]+ab[0]+"px")}if(ad[1]!==null){Y(G,N,ad[1]-ac[1]+ab[1]+"px")}if(!W){X=e.Dom._getXY(G);if((ad[0]!==null&&X[0]!=ad[0])||(ad[1]!==null&&X[1]!=ad[1])){e.Dom._setXY(G,{pos:ad,noRetry:true})}}},setX:function(W,G){e.Dom.setXY(W,[G,null])},setY:function(G,W){e.Dom.setXY(G,[null,W])},getRegion:function(G){var W=function(X){var Y=false;if(e.Dom._canPosition(X)){Y=e.Region.getRegion(X)}else{}return Y};return e.Dom.batch(G,W,e.Dom,true)},getClientWidth:function(){return e.Dom.getViewportWidth()},getClientHeight:function(){return e.Dom.getViewportHeight()},getElementsByClassName:function(ab,af,ac,ae,X,ad){af=af||"*";ac=(ac)?e.Dom.get(ac):null||j;if(!ac){return[]}var W=[],G=ac.getElementsByTagName(af),Z=e.Dom.hasClass;for(var Y=0,aa=G.length;Y<aa;++Y){if(Z(G[Y],ab)){W[W.length]=G[Y]}}if(ae){e.Dom.batch(W,ae,X,ad)}return W},hasClass:function(W,G){return e.Dom.batch(W,e.Dom._hasClass,G)},_hasClass:function(X,W){var G=false,Y;if(X&&W){Y=e.Dom._getAttribute(X,f)||i;if(Y){Y=Y.replace(/\s+/g,b)}if(W.exec){G=W.test(Y)}else{G=W&&(b+Y+b).indexOf(b+W+b)>-1}}else{}return G},addClass:function(W,G){return e.Dom.batch(W,e.Dom._addClass,G)},_addClass:function(X,W){var G=false,Y;if(X&&W){Y=e.Dom._getAttribute(X,f)||i;if(!e.Dom._hasClass(X,W)){e.Dom.setAttribute(X,f,a(Y+b+W));G=true}}else{}return G},removeClass:function(W,G){return e.Dom.batch(W,e.Dom._removeClass,G)},_removeClass:function(Y,X){var W=false,aa,Z,G;if(Y&&X){aa=e.Dom._getAttribute(Y,f)||i;e.Dom.setAttribute(Y,f,aa.replace(e.Dom._getClassRegex(X),i));Z=e.Dom._getAttribute(Y,f);if(aa!==Z){e.Dom.setAttribute(Y,f,a(Z));W=true;if(e.Dom._getAttribute(Y,f)===""){G=(Y.hasAttribute&&Y.hasAttribute(E))?E:f;Y.removeAttribute(G)}}}else{}return W},replaceClass:function(X,W,G){return e.Dom.batch(X,e.Dom._replaceClass,{from:W,to:G})},_replaceClass:function(Y,X){var W,ab,aa,G=false,Z;if(Y&&X){ab=X.from;aa=X.to;if(!aa){G=false}else{if(!ab){G=e.Dom._addClass(Y,X.to)}else{if(ab!==aa){Z=e.Dom._getAttribute(Y,f)||i;W=(b+Z.replace(e.Dom._getClassRegex(ab),b+aa).replace(/\s+/g,b)).split(e.Dom._getClassRegex(aa));W.splice(1,0,b+aa);e.Dom.setAttribute(Y,f,a(W.join(i)));G=true}}}}else{}return G},generateId:function(G,X){X=X||"yui-gen";var W=function(Y){if(Y&&Y.id){return Y.id}var Z=X+YAHOO.env._id_counter++;if(Y){if(Y[C]&&Y[C].getElementById(Z)){return e.Dom.generateId(Y,Z+X)}Y.id=Z}return Z};return e.Dom.batch(G,W,e.Dom,true)||W.apply(e.Dom,arguments)},isAncestor:function(W,X){W=e.Dom.get(W);X=e.Dom.get(X);var G=false;if((W&&X)&&(W[K]&&X[K])){if(W.contains&&W!==X){G=W.contains(X)}else{if(W.compareDocumentPosition){G=!!(W.compareDocumentPosition(X)&16)}}}else{}return G},inDocument:function(G,W){return e.Dom._inDoc(e.Dom.get(G),W)},_inDoc:function(W,X){var G=false;if(W&&W[c]){X=X||W[C];G=e.Dom.isAncestor(X[U],W)}else{}return G},getElementsBy:function(W,af,ab,ad,X,ac,ae){af=af||"*";ab=(ab)?e.Dom.get(ab):null||j;var aa=(ae)?null:[],G;if(ab){G=ab.getElementsByTagName(af);for(var Y=0,Z=G.length;Y<Z;++Y){if(W(G[Y])){if(ae){aa=G[Y];break}else{aa[aa.length]=G[Y]}}}if(ad){e.Dom.batch(aa,ad,X,ac)}}return aa},getElementBy:function(X,G,W){return e.Dom.getElementsBy(X,G,W,null,null,null,true)},batch:function(X,ab,aa,Z){var Y=[],W=(Z)?aa:null;X=(X&&(X[c]||X.item))?X:e.Dom.get(X);if(X&&ab){if(X[c]||X.length===undefined){return ab.call(W,X,aa)}for(var G=0;G<X.length;++G){Y[Y.length]=ab.call(W||X[G],X[G],aa)}}else{return false}return Y},getDocumentHeight:function(){var W=(j[S]!=l||h)?j.body.scrollHeight:v.scrollHeight,G=Math.max(W,e.Dom.getViewportHeight());return G},getDocumentWidth:function(){var W=(j[S]!=l||h)?j.body.scrollWidth:v.scrollWidth,G=Math.max(W,e.Dom.getViewportWidth());return G},getViewportHeight:function(){var G=self.innerHeight,W=j[S];if((W||s)&&!d){G=(W==l)?v.clientHeight:j.body.clientHeight}return G},getViewportWidth:function(){var G=self.innerWidth,W=j[S];if(W||s){G=(W==l)?v.clientWidth:j.body.clientWidth}return G},getAncestorBy:function(G,W){while((G=G[x])){if(e.Dom._testElement(G,W)){return G}}return null},getAncestorByClassName:function(W,G){W=e.Dom.get(W);if(!W){return null}var X=function(Y){return e.Dom.hasClass(Y,G)};return e.Dom.getAncestorBy(W,X)},getAncestorByTagName:function(W,G){W=e.Dom.get(W);if(!W){return null}var X=function(Y){return Y[c]&&Y[c].toUpperCase()==G.toUpperCase()};return e.Dom.getAncestorBy(W,X)},getPreviousSiblingBy:function(G,W){while(G){G=G.previousSibling;if(e.Dom._testElement(G,W)){return G}}return null},getPreviousSibling:function(G){G=e.Dom.get(G);if(!G){return null}return e.Dom.getPreviousSiblingBy(G)},getNextSiblingBy:function(G,W){while(G){G=G.nextSibling;if(e.Dom._testElement(G,W)){return G}}return null},getNextSibling:function(G){G=e.Dom.get(G);if(!G){return null}return e.Dom.getNextSiblingBy(G)},getFirstChildBy:function(G,X){var W=(e.Dom._testElement(G.firstChild,X))?G.firstChild:null;return W||e.Dom.getNextSiblingBy(G.firstChild,X)},getFirstChild:function(G,W){G=e.Dom.get(G);if(!G){return null}return e.Dom.getFirstChildBy(G)},getLastChildBy:function(G,X){if(!G){return null}var W=(e.Dom._testElement(G.lastChild,X))?G.lastChild:null;return W||e.Dom.getPreviousSiblingBy(G.lastChild,X)},getLastChild:function(G){G=e.Dom.get(G);return e.Dom.getLastChildBy(G)},getChildrenBy:function(W,Y){var X=e.Dom.getFirstChildBy(W,Y),G=X?[X]:[];e.Dom.getNextSiblingBy(X,function(Z){if(!Y||Y(Z)){G[G.length]=Z}return false});return G},getChildren:function(G){G=e.Dom.get(G);if(!G){}return e.Dom.getChildrenBy(G)},getDocumentScrollLeft:function(G){G=G||j;return Math.max(G[U].scrollLeft,G.body.scrollLeft)},getDocumentScrollTop:function(G){G=G||j;return Math.max(G[U].scrollTop,G.body.scrollTop)},insertBefore:function(W,G){W=e.Dom.get(W);G=e.Dom.get(G);if(!W||!G||!G[x]){return null}return G[x].insertBefore(W,G)},insertAfter:function(W,G){W=e.Dom.get(W);G=e.Dom.get(G);if(!W||!G||!G[x]){return null}if(G.nextSibling){return G[x].insertBefore(W,G.nextSibling)}else{return G[x].appendChild(W)}},getClientRegion:function(){var X=e.Dom.getDocumentScrollTop(),W=e.Dom.getDocumentScrollLeft(),Y=e.Dom.getViewportWidth()+W,G=e.Dom.getViewportHeight()+X;return new e.Region(X,Y,G,W)},setAttribute:function(W,G,X){e.Dom.batch(W,e.Dom._setAttribute,{attr:G,val:X})},_setAttribute:function(X,W){var G=e.Dom._toCamel(W.attr),Y=W.val;if(X&&X.setAttribute){if(e.Dom.DOT_ATTRIBUTES[G]&&X.tagName&&X.tagName!="BUTTON"){X[G]=Y}else{G=e.Dom.CUSTOM_ATTRIBUTES[G]||G;X.setAttribute(G,Y)}}else{}},getAttribute:function(W,G){return e.Dom.batch(W,e.Dom._getAttribute,G)},_getAttribute:function(W,G){var X;G=e.Dom.CUSTOM_ATTRIBUTES[G]||G;if(e.Dom.DOT_ATTRIBUTES[G]){X=W[G]}else{if(W&&"getAttribute" in W){if(/^(?:href|src)$/.test(G)){X=W.getAttribute(G,2)}else{X=W.getAttribute(G)}}else{}}return X},_toCamel:function(W){var X=B;function G(Y,Z){return Z.toUpperCase()}return X[W]||(X[W]=W.indexOf("-")===-1?W:W.replace(/-([a-z])/gi,G))},_getClassRegex:function(W){var G;if(W!==undefined){if(W.exec){G=W}else{G=F[W];if(!G){W=W.replace(e.Dom._patterns.CLASS_RE_TOKENS,"\\$1");W=W.replace(/\s+/g,b);G=F[W]=new RegExp(R+W+J,t)}}}return G},_patterns:{ROOT_TAG:/^body|html$/i,CLASS_RE_TOKENS:/([\.\(\)\^\$\*\+\?\|\[\]\{\}\\])/g},_testElement:function(G,W){return G&&G[K]==1&&(!W||W(G))},_calcBorders:function(X,Y){var W=parseInt(e.Dom[V](X,q),10)||0,G=parseInt(e.Dom[V](X,P),10)||0;if(g){if(m.test(X[c])){W=0;G=0}}Y[0]+=G;Y[1]+=W;return Y}};var r=e.Dom[V];if(L.opera){e.Dom[V]=function(W,G){var X=r(W,G);if(w.test(G)){X=e.Dom.Color.toRGB(X)}return X}}if(L.webkit){e.Dom[V]=function(W,G){var X=r(W,G);if(X==="rgba(0, 0, 0, 0)"){X="transparent"}return X}}if(L.ie&&L.ie>=8){e.Dom.DOT_ATTRIBUTES.type=true}})();YAHOO.util.Region=function(d,e,a,c){this.top=d;this.y=d;this[1]=d;this.right=e;this.bottom=a;this.left=c;this.x=c;this[0]=c;this.width=this.right-this.left;this.height=this.bottom-this.top};YAHOO.util.Region.prototype.contains=function(a){return(a.left>=this.left&&a.right<=this.right&&a.top>=this.top&&a.bottom<=this.bottom)};YAHOO.util.Region.prototype.getArea=function(){return((this.bottom-this.top)*(this.right-this.left))};YAHOO.util.Region.prototype.intersect=function(f){var d=Math.max(this.top,f.top),e=Math.min(this.right,f.right),a=Math.min(this.bottom,f.bottom),c=Math.max(this.left,f.left);if(a>=d&&e>=c){return new YAHOO.util.Region(d,e,a,c)}else{return null}};YAHOO.util.Region.prototype.union=function(f){var d=Math.min(this.top,f.top),e=Math.max(this.right,f.right),a=Math.max(this.bottom,f.bottom),c=Math.min(this.left,f.left);return new YAHOO.util.Region(d,e,a,c)};YAHOO.util.Region.prototype.toString=function(){return("Region {top: "+this.top+", right: "+this.right+", bottom: "+this.bottom+", left: "+this.left+", height: "+this.height+", width: "+this.width+"}")};YAHOO.util.Region.getRegion=function(e){var g=YAHOO.util.Dom.getXY(e),d=g[1],f=g[0]+e.offsetWidth,a=g[1]+e.offsetHeight,c=g[0];return new YAHOO.util.Region(d,f,a,c)};YAHOO.util.Point=function(a,b){if(YAHOO.lang.isArray(a)){b=a[1];a=a[0]}YAHOO.util.Point.superclass.constructor.call(this,b,a,b,a)};YAHOO.extend(YAHOO.util.Point,YAHOO.util.Region);(function(){var b=YAHOO.util,a="clientTop",f="clientLeft",j="parentNode",k="right",w="hasLayout",i="px",u="opacity",l="auto",d="borderLeftWidth",g="borderTopWidth",p="borderRightWidth",v="borderBottomWidth",s="visible",q="transparent",n="height",e="width",h="style",t="currentStyle",r=/^width|height$/,o=/^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i,m={get:function(x,z){var y="",A=x[t][z];if(z===u){y=b.Dom.getStyle(x,u)}else{if(!A||(A.indexOf&&A.indexOf(i)>-1)){y=A}else{if(b.Dom.IE_COMPUTED[z]){y=b.Dom.IE_COMPUTED[z](x,z)}else{if(o.test(A)){y=b.Dom.IE.ComputedStyle.getPixel(x,z)}else{y=A}}}}return y},getOffset:function(z,E){var B=z[t][E],x=E.charAt(0).toUpperCase()+E.substr(1),C="offset"+x,y="pixel"+x,A="",D;if(B==l){D=z[C];if(D===undefined){A=0}A=D;if(r.test(E)){z[h][E]=D;if(z[C]>D){A=D-(z[C]-D)}z[h][E]=l}}else{if(!z[h][y]&&!z[h][E]){z[h][E]=B}A=z[h][y]}return A+i},getBorderWidth:function(x,z){var y=null;if(!x[t][w]){x[h].zoom=1}switch(z){case g:y=x[a];break;case v:y=x.offsetHeight-x.clientHeight-x[a];break;case d:y=x[f];break;case p:y=x.offsetWidth-x.clientWidth-x[f];break}return y+i},getPixel:function(y,x){var A=null,B=y[t][k],z=y[t][x];y[h][k]=z;A=y[h].pixelRight;y[h][k]=B;return A+i},getMargin:function(y,x){var z;if(y[t][x]==l){z=0+i}else{z=b.Dom.IE.ComputedStyle.getPixel(y,x)}return z},getVisibility:function(y,x){var z;while((z=y[t])&&z[x]=="inherit"){y=y[j]}return(z)?z[x]:s},getColor:function(y,x){return b.Dom.Color.toRGB(y[t][x])||q},getBorderColor:function(y,x){var z=y[t],A=z[x]||z.color;return b.Dom.Color.toRGB(b.Dom.Color.toHex(A))}},c={};c.top=c.right=c.bottom=c.left=c[e]=c[n]=m.getOffset;c.color=m.getColor;c[g]=c[p]=c[v]=c[d]=m.getBorderWidth;c.marginTop=c.marginRight=c.marginBottom=c.marginLeft=m.getMargin;c.visibility=m.getVisibility;c.borderColor=c.borderTopColor=c.borderRightColor=c.borderBottomColor=c.borderLeftColor=m.getBorderColor;b.Dom.IE_COMPUTED=c;b.Dom.IE_ComputedStyle=m})();(function(){var c="toString",a=parseInt,b=RegExp,d=YAHOO.util;d.Dom.Color={KEYWORDS:{black:"000",silver:"c0c0c0",gray:"808080",white:"fff",maroon:"800000",red:"f00",purple:"800080",fuchsia:"f0f",green:"008000",lime:"0f0",olive:"808000",yellow:"ff0",navy:"000080",blue:"00f",teal:"008080",aqua:"0ff"},re_RGB:/^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i,re_hex:/^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i,re_hex3:/([0-9A-F])/gi,toRGB:function(e){if(!d.Dom.Color.re_RGB.test(e)){e=d.Dom.Color.toHex(e)}if(d.Dom.Color.re_hex.exec(e)){e="rgb("+[a(b.$1,16),a(b.$2,16),a(b.$3,16)].join(", ")+")"}return e},toHex:function(f){f=d.Dom.Color.KEYWORDS[f]||f;if(d.Dom.Color.re_RGB.exec(f)){f=[Number(b.$1).toString(16),Number(b.$2).toString(16),Number(b.$3).toString(16)];for(var e=0;e<f.length;e++){if(f[e].length<2){f[e]="0"+f[e]}}f=f.join("")}if(f.length<6){f=f.replace(d.Dom.Color.re_hex3,"$1$1")}if(f!=="transparent"&&f.indexOf("#")<0){f="#"+f}return f.toUpperCase()}}}());YAHOO.register("dom",YAHOO.util.Dom,{version:"2.9.0",build:"2800"});(function(){var b=YAHOO.util;var a=function(d,c,e,f){if(!d){}this.init(d,c,e,f)};a.NAME="Anim";a.prototype={toString:function(){var c=this.getEl()||{};var d=c.id||c.tagName;return(this.constructor.NAME+": "+d)},patterns:{noNegatives:/width|height|opacity|padding/i,offsetAttribute:/^((width|height)|(top|left))$/,defaultUnit:/width|height|top$|bottom$|left$|right$/i,offsetUnit:/\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i},doMethod:function(c,e,d){return this.method(this.currentFrame,e,d-e,this.totalFrames)},setAttribute:function(c,f,e){var d=this.getEl();if(this.patterns.noNegatives.test(c)){f=(f>0)?f:0}if(c in d&&!("style" in d&&c in d.style)){d[c]=f}else{b.Dom.setStyle(d,c,f+e)}},getAttribute:function(c){var e=this.getEl();var g=b.Dom.getStyle(e,c);if(g!=="auto"&&!this.patterns.offsetUnit.test(g)){return parseFloat(g)}var d=this.patterns.offsetAttribute.exec(c)||[];var h=!!(d[3]);var f=!!(d[2]);if("style" in e){if(f||(b.Dom.getStyle(e,"position")=="absolute"&&h)){g=e["offset"+d[0].charAt(0).toUpperCase()+d[0].substr(1)]}else{g=0}}else{if(c in e){g=e[c]}}return g},getDefaultUnit:function(c){if(this.patterns.defaultUnit.test(c)){return"px"}return""},setRuntimeAttribute:function(d){var j;var e;var f=this.attributes;this.runtimeAttributes[d]={};var h=function(i){return(typeof i!=="undefined")};if(!h(f[d]["to"])&&!h(f[d]["by"])){return false}j=(h(f[d]["from"]))?f[d]["from"]:this.getAttribute(d);if(h(f[d]["to"])){e=f[d]["to"]}else{if(h(f[d]["by"])){if(j.constructor==Array){e=[];for(var g=0,c=j.length;g<c;++g){e[g]=j[g]+f[d]["by"][g]*1}}else{e=j+f[d]["by"]*1}}}this.runtimeAttributes[d].start=j;this.runtimeAttributes[d].end=e;this.runtimeAttributes[d].unit=(h(f[d].unit))?f[d]["unit"]:this.getDefaultUnit(d);return true},init:function(f,c,h,i){var d=false;var e=null;var g=0;f=b.Dom.get(f);this.attributes=c||{};this.duration=!YAHOO.lang.isUndefined(h)?h:1;this.method=i||b.Easing.easeNone;this.useSeconds=true;this.currentFrame=0;this.totalFrames=b.AnimMgr.fps;this.setEl=function(j){f=b.Dom.get(j)};this.getEl=function(){return f};this.isAnimated=function(){return d};this.getStartTime=function(){return e};this.runtimeAttributes={};this.animate=function(){if(this.isAnimated()){return false}this.currentFrame=0;this.totalFrames=(this.useSeconds)?Math.ceil(b.AnimMgr.fps*this.duration):this.duration;if(this.duration===0&&this.useSeconds){this.totalFrames=1}b.AnimMgr.registerElement(this);return true};this.stop=function(j){if(!this.isAnimated()){return false}if(j){this.currentFrame=this.totalFrames;this._onTween.fire()}b.AnimMgr.stop(this)};this._handleStart=function(){this.onStart.fire();this.runtimeAttributes={};for(var j in this.attributes){if(this.attributes.hasOwnProperty(j)){this.setRuntimeAttribute(j)}}d=true;g=0;e=new Date()};this._handleTween=function(){var l={duration:new Date()-this.getStartTime(),currentFrame:this.currentFrame};l.toString=function(){return("duration: "+l.duration+", currentFrame: "+l.currentFrame)};this.onTween.fire(l);var k=this.runtimeAttributes;for(var j in k){if(k.hasOwnProperty(j)){this.setAttribute(j,this.doMethod(j,k[j].start,k[j].end),k[j].unit)}}this.afterTween.fire(l);g+=1};this._handleComplete=function(){var j=(new Date()-e)/1000;var k={duration:j,frames:g,fps:g/j};k.toString=function(){return("duration: "+k.duration+", frames: "+k.frames+", fps: "+k.fps)};d=false;g=0;this.onComplete.fire(k)};this._onStart=new b.CustomEvent("_start",this,true);this.onStart=new b.CustomEvent("start",this);this.onTween=new b.CustomEvent("tween",this);this.afterTween=new b.CustomEvent("afterTween",this);this._onTween=new b.CustomEvent("_tween",this,true);this.onComplete=new b.CustomEvent("complete",this);this._onComplete=new b.CustomEvent("_complete",this,true);this._onStart.subscribe(this._handleStart);this._onTween.subscribe(this._handleTween);this._onComplete.subscribe(this._handleComplete)}};b.Anim=a})();YAHOO.util.AnimMgr=new function(){var e=null;var c=[];var g=0;this.fps=1000;this.delay=20;this.registerElement=function(j){c[c.length]=j;g+=1;j._onStart.fire();this.start()};var f=[];var d=false;var h=function(){var j=f.shift();b.apply(YAHOO.util.AnimMgr,j);if(f.length){arguments.callee()}};var b=function(k,j){j=j||a(k);if(!k.isAnimated()||j===-1){return false}k._onComplete.fire();c.splice(j,1);g-=1;if(g<=0){this.stop()}return true};this.unRegister=function(){f.push(arguments);if(!d){d=true;h();d=false}};this.start=function(){if(e===null){e=setInterval(this.run,this.delay)}};this.stop=function(l){if(!l){clearInterval(e);for(var k=0,j=c.length;k<j;++k){this.unRegister(c[0],0)}c=[];e=null;g=0}else{this.unRegister(l)}};this.run=function(){for(var l=0,j=c.length;l<j;++l){var k=c[l];if(!k||!k.isAnimated()){continue}if(k.currentFrame<k.totalFrames||k.totalFrames===null){k.currentFrame+=1;if(k.useSeconds){i(k)}k._onTween.fire()}else{YAHOO.util.AnimMgr.stop(k,l)}}};var a=function(l){for(var k=0,j=c.length;k<j;++k){if(c[k]===l){return k}}return -1};var i=function(k){var n=k.totalFrames;var m=k.currentFrame;var l=(k.currentFrame*k.duration*1000/k.totalFrames);var j=(new Date()-k.getStartTime());var o=0;if(j<k.duration*1000){o=Math.round((j/l-1)*k.currentFrame)}else{o=n-(m+1)}if(o>0&&isFinite(o)){if(k.currentFrame+o>=n){o=n-(m+1)}k.currentFrame+=o}};this._queue=c;this._getIndex=a};YAHOO.util.Bezier=new function(){this.getPosition=function(e,d){var f=e.length;var c=[];for(var b=0;b<f;++b){c[b]=[e[b][0],e[b][1]]}for(var a=1;a<f;++a){for(b=0;b<f-a;++b){c[b][0]=(1-d)*c[b][0]+d*c[parseInt(b+1,10)][0];c[b][1]=(1-d)*c[b][1]+d*c[parseInt(b+1,10)][1]}}return[c[0][0],c[0][1]]}};(function(){var a=function(f,e,g,h){a.superclass.constructor.call(this,f,e,g,h)};a.NAME="ColorAnim";a.DEFAULT_BGCOLOR="#fff";var c=YAHOO.util;YAHOO.extend(a,c.Anim);var d=a.superclass;var b=a.prototype;b.patterns.color=/color$/i;b.patterns.rgb=/^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;b.patterns.hex=/^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;b.patterns.hex3=/^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;b.patterns.transparent=/^transparent|rgba\(0, 0, 0, 0\)$/;b.parseColor=function(e){if(e.length==3){return e}var f=this.patterns.hex.exec(e);if(f&&f.length==4){return[parseInt(f[1],16),parseInt(f[2],16),parseInt(f[3],16)]}f=this.patterns.rgb.exec(e);if(f&&f.length==4){return[parseInt(f[1],10),parseInt(f[2],10),parseInt(f[3],10)]}f=this.patterns.hex3.exec(e);if(f&&f.length==4){return[parseInt(f[1]+f[1],16),parseInt(f[2]+f[2],16),parseInt(f[3]+f[3],16)]}return null};b.getAttribute=function(e){var g=this.getEl();if(this.patterns.color.test(e)){var i=YAHOO.util.Dom.getStyle(g,e);var h=this;if(this.patterns.transparent.test(i)){var f=YAHOO.util.Dom.getAncestorBy(g,function(j){return !h.patterns.transparent.test(i)});if(f){i=c.Dom.getStyle(f,e)}else{i=a.DEFAULT_BGCOLOR}}}else{i=d.getAttribute.call(this,e)}return i};b.doMethod=function(f,k,g){var j;if(this.patterns.color.test(f)){j=[];for(var h=0,e=k.length;h<e;++h){j[h]=d.doMethod.call(this,f,k[h],g[h])}j="rgb("+Math.floor(j[0])+","+Math.floor(j[1])+","+Math.floor(j[2])+")"}else{j=d.doMethod.call(this,f,k,g)}return j};b.setRuntimeAttribute=function(f){d.setRuntimeAttribute.call(this,f);if(this.patterns.color.test(f)){var h=this.attributes;var k=this.parseColor(this.runtimeAttributes[f].start);var g=this.parseColor(this.runtimeAttributes[f].end);if(typeof h[f]["to"]==="undefined"&&typeof h[f]["by"]!=="undefined"){g=this.parseColor(h[f].by);for(var j=0,e=k.length;j<e;++j){g[j]=k[j]+g[j]}}this.runtimeAttributes[f].start=k;this.runtimeAttributes[f].end=g}};c.ColorAnim=a})();
 /*!
 TERMS OF USE - EASING EQUATIONS
 Open source under the BSD License.
@@ -14,4 +14,4 @@
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
-YAHOO.util.Easing={easeNone:function(e,a,g,f){return g*e/f+a},easeIn:function(e,a,g,f){return g*(e/=f)*e+a},easeOut:function(e,a,g,f){return -g*(e/=f)*(e-2)+a},easeBoth:function(e,a,g,f){if((e/=f/2)<1){return g/2*e*e+a}return -g/2*((--e)*(e-2)-1)+a},easeInStrong:function(e,a,g,f){return g*(e/=f)*e*e*e+a},easeOutStrong:function(e,a,g,f){return -g*((e=e/f-1)*e*e*e-1)+a},easeBothStrong:function(e,a,g,f){if((e/=f/2)<1){return g/2*e*e*e*e+a}return -g/2*((e-=2)*e*e*e-2)+a},elasticIn:function(g,e,k,j,f,i){if(g==0){return e}if((g/=j)==1){return e+k}if(!i){i=j*0.3}if(!f||f<Math.abs(k)){f=k;var h=i/4}else{var h=i/(2*Math.PI)*Math.asin(k/f)}return -(f*Math.pow(2,10*(g-=1))*Math.sin((g*j-h)*(2*Math.PI)/i))+e},elasticOut:function(g,e,k,j,f,i){if(g==0){return e}if((g/=j)==1){return e+k}if(!i){i=j*0.3}if(!f||f<Math.abs(k)){f=k;var h=i/4}else{var h=i/(2*Math.PI)*Math.asin(k/f)}return f*Math.pow(2,-10*g)*Math.sin((g*j-h)*(2*Math.PI)/i)+k+e},elasticBoth:function(g,e,k,j,f,i){if(g==0){return e}if((g/=j/2)==2){return e+k}if(!i){i=j*(0.3*1.5)}if(!f||f<Math.abs(k)){f=k;var h=i/4}else{var h=i/(2*Math.PI)*Math.asin(k/f)}if(g<1){return -0.5*(f*Math.pow(2,10*(g-=1))*Math.sin((g*j-h)*(2*Math.PI)/i))+e}return f*Math.pow(2,-10*(g-=1))*Math.sin((g*j-h)*(2*Math.PI)/i)*0.5+k+e},backIn:function(e,a,h,g,f){if(typeof f=="undefined"){f=1.70158}return h*(e/=g)*e*((f+1)*e-f)+a},backOut:function(e,a,h,g,f){if(typeof f=="undefined"){f=1.70158}return h*((e=e/g-1)*e*((f+1)*e+f)+1)+a},backBoth:function(e,a,h,g,f){if(typeof f=="undefined"){f=1.70158}if((e/=g/2)<1){return h/2*(e*e*(((f*=(1.525))+1)*e-f))+a}return h/2*((e-=2)*e*(((f*=(1.525))+1)*e+f)+2)+a},bounceIn:function(e,a,g,f){return g-YAHOO.util.Easing.bounceOut(f-e,0,g,f)+a},bounceOut:function(e,a,g,f){if((e/=f)<(1/2.75)){return g*(7.5625*e*e)+a}else{if(e<(2/2.75)){return g*(7.5625*(e-=(1.5/2.75))*e+0.75)+a}else{if(e<(2.5/2.75)){return g*(7.5625*(e-=(2.25/2.75))*e+0.9375)+a}}}return g*(7.5625*(e-=(2.625/2.75))*e+0.984375)+a},bounceBoth:function(e,a,g,f){if(e<f/2){return YAHOO.util.Easing.bounceIn(e*2,0,g,f)*0.5+a}return YAHOO.util.Easing.bounceOut(e*2-f,0,g,f)*0.5+g*0.5+a}};(function(){var a=function(h,g,i,j){if(h){a.superclass.constructor.call(this,h,g,i,j)}};a.NAME="Motion";var e=YAHOO.util;YAHOO.extend(a,e.ColorAnim);var f=a.superclass;var c=a.prototype;c.patterns.points=/^points$/i;c.setAttribute=function(g,i,h){if(this.patterns.points.test(g)){h=h||"px";f.setAttribute.call(this,"left",i[0],h);f.setAttribute.call(this,"top",i[1],h)}else{f.setAttribute.call(this,g,i,h)}};c.getAttribute=function(g){if(this.patterns.points.test(g)){var h=[f.getAttribute.call(this,"left"),f.getAttribute.call(this,"top")]}else{h=f.getAttribute.call(this,g)}return h};c.doMethod=function(g,k,h){var j=null;if(this.patterns.points.test(g)){var i=this.method(this.currentFrame,0,100,this.totalFrames)/100;j=e.Bezier.getPosition(this.runtimeAttributes[g],i)}else{j=f.doMethod.call(this,g,k,h)}return j};c.setRuntimeAttribute=function(q){if(this.patterns.points.test(q)){var h=this.getEl();var k=this.attributes;var g;var m=k.points["control"]||[];var j;var n,p;if(m.length>0&&!(m[0] instanceof Array)){m=[m]}else{var l=[];for(n=0,p=m.length;n<p;++n){l[n]=m[n]}m=l}if(e.Dom.getStyle(h,"position")=="static"){e.Dom.setStyle(h,"position","relative")}if(d(k.points["from"])){e.Dom.setXY(h,k.points["from"])}else{e.Dom.setXY(h,e.Dom.getXY(h))}g=this.getAttribute("points");if(d(k.points["to"])){j=b.call(this,k.points["to"],g);var o=e.Dom.getXY(this.getEl());for(n=0,p=m.length;n<p;++n){m[n]=b.call(this,m[n],g)}}else{if(d(k.points["by"])){j=[g[0]+k.points["by"][0],g[1]+k.points["by"][1]];for(n=0,p=m.length;n<p;++n){m[n]=[g[0]+m[n][0],g[1]+m[n][1]]}}}this.runtimeAttributes[q]=[g];if(m.length>0){this.runtimeAttributes[q]=this.runtimeAttributes[q].concat(m)}this.runtimeAttributes[q][this.runtimeAttributes[q].length]=j}else{f.setRuntimeAttribute.call(this,q)}};var b=function(g,i){var h=e.Dom.getXY(this.getEl());g=[g[0]-h[0]+i[0],g[1]-h[1]+i[1]];return g};var d=function(g){return(typeof g!=="undefined")};e.Motion=a})();(function(){var d=function(f,e,g,h){if(f){d.superclass.constructor.call(this,f,e,g,h)}};d.NAME="Scroll";var b=YAHOO.util;YAHOO.extend(d,b.ColorAnim);var c=d.superclass;var a=d.prototype;a.doMethod=function(e,h,f){var g=null;if(e=="scroll"){g=[this.method(this.currentFrame,h[0],f[0]-h[0],this.totalFrames),this.method(this.currentFrame,h[1],f[1]-h[1],this.totalFrames)]}else{g=c.doMethod.call(this,e,h,f)}return g};a.getAttribute=function(e){var g=null;var f=this.getEl();if(e=="scroll"){g=[f.scrollLeft,f.scrollTop]}else{g=c.getAttribute.call(this,e)}return g};a.setAttribute=function(e,h,g){var f=this.getEl();if(e=="scroll"){f.scrollLeft=h[0];f.scrollTop=h[1]}else{c.setAttribute.call(this,e,h,g)}};b.Scroll=d})();YAHOO.register("animation",YAHOO.util.Anim,{version:"2.9.0",build:"2800"});if(!YAHOO.util.DragDropMgr){YAHOO.util.DragDropMgr=function(){var a=YAHOO.util.Event,b=YAHOO.util.Dom;return{useShim:false,_shimActive:false,_shimState:false,_debugShim:false,_createShim:function(){var c=document.createElement("div");c.id="yui-ddm-shim";if(document.body.firstChild){document.body.insertBefore(c,document.body.firstChild)}else{document.body.appendChild(c)}c.style.display="none";c.style.backgroundColor="red";c.style.position="absolute";c.style.zIndex="99999";b.setStyle(c,"opacity","0");this._shim=c;a.on(c,"mouseup",this.handleMouseUp,this,true);a.on(c,"mousemove",this.handleMouseMove,this,true);a.on(window,"scroll",this._sizeShim,this,true)},_sizeShim:function(){if(this._shimActive){var c=this._shim;c.style.height=b.getDocumentHeight()+"px";c.style.width=b.getDocumentWidth()+"px";c.style.top="0";c.style.left="0"}},_activateShim:function(){if(this.useShim){if(!this._shim){this._createShim()}this._shimActive=true;var c=this._shim,d="0";if(this._debugShim){d=".5"}b.setStyle(c,"opacity",d);this._sizeShim();c.style.display="block"}},_deactivateShim:function(){this._shim.style.display="none";this._shimActive=false},_shim:null,ids:{},handleIds:{},dragCurrent:null,dragOvers:{},deltaX:0,deltaY:0,preventDefault:true,stopPropagation:true,initialized:false,locked:false,interactionInfo:null,init:function(){this.initialized=true},POINT:0,INTERSECT:1,STRICT_INTERSECT:2,mode:0,_execOnAll:function(e,d){for(var f in this.ids){for(var c in this.ids[f]){var g=this.ids[f][c];if(!this.isTypeOfDD(g)){continue}g[e].apply(g,d)}}},_onLoad:function(){this.init();a.on(document,"mouseup",this.handleMouseUp,this,true);a.on(document,"mousemove",this.handleMouseMove,this,true);a.on(window,"unload",this._onUnload,this,true);a.on(window,"resize",this._onResize,this,true)},_onResize:function(c){this._execOnAll("resetConstraints",[])},lock:function(){this.locked=true},unlock:function(){this.locked=false},isLocked:function(){return this.locked},locationCache:{},useCache:true,clickPixelThresh:3,clickTimeThresh:1000,dragThreshMet:false,clickTimeout:null,startX:0,startY:0,fromTimeout:false,regDragDrop:function(d,c){if(!this.initialized){this.init()}if(!this.ids[c]){this.ids[c]={}}this.ids[c][d.id]=d},removeDDFromGroup:function(e,c){if(!this.ids[c]){this.ids[c]={}}var d=this.ids[c];if(d&&d[e.id]){delete d[e.id]}},_remove:function(e){for(var d in e.groups){if(d){var c=this.ids[d];if(c&&c[e.id]){delete c[e.id]}}}delete this.handleIds[e.id]},regHandle:function(d,c){if(!this.handleIds[d]){this.handleIds[d]={}}this.handleIds[d][c]=c},isDragDrop:function(c){return(this.getDDById(c))?true:false},getRelated:function(h,d){var g=[];for(var f in h.groups){for(var e in this.ids[f]){var c=this.ids[f][e];if(!this.isTypeOfDD(c)){continue}if(!d||c.isTarget){g[g.length]=c}}}return g},isLegalTarget:function(g,f){var d=this.getRelated(g,true);for(var e=0,c=d.length;e<c;++e){if(d[e].id==f.id){return true}}return false},isTypeOfDD:function(c){return(c&&c.__ygDragDrop)},isHandle:function(d,c){return(this.handleIds[d]&&this.handleIds[d][c])},getDDById:function(d){for(var c in this.ids){if(this.ids[c][d]){return this.ids[c][d]}}return null},handleMouseDown:function(f,d){this.currentTarget=YAHOO.util.Event.getTarget(f);this.dragCurrent=d;var c=d.getEl();this.startX=YAHOO.util.Event.getPageX(f);this.startY=YAHOO.util.Event.getPageY(f);this.deltaX=this.startX-c.offsetLeft;this.deltaY=this.startY-c.offsetTop;this.dragThreshMet=false;this.clickTimeout=setTimeout(function(){var e=YAHOO.util.DDM;e.startDrag(e.startX,e.startY);e.fromTimeout=true},this.clickTimeThresh)},startDrag:function(c,e){if(this.dragCurrent&&this.dragCurrent.useShim){this._shimState=this.useShim;this.useShim=true}this._activateShim();clearTimeout(this.clickTimeout);var d=this.dragCurrent;if(d&&d.events.b4StartDrag){d.b4StartDrag(c,e);d.fireEvent("b4StartDragEvent",{x:c,y:e})}if(d&&d.events.startDrag){d.startDrag(c,e);d.fireEvent("startDragEvent",{x:c,y:e})}this.dragThreshMet=true},handleMouseUp:function(c){if(this.dragCurrent){clearTimeout(this.clickTimeout);if(this.dragThreshMet){if(this.fromTimeout){this.fromTimeout=false;this.handleMouseMove(c)}this.fromTimeout=false;this.fireEvents(c,true)}else{}this.stopDrag(c);this.stopEvent(c)}},stopEvent:function(c){if(this.stopPropagation){YAHOO.util.Event.stopPropagation(c)}if(this.preventDefault){YAHOO.util.Event.preventDefault(c)}},stopDrag:function(f,d){var c=this.dragCurrent;if(c&&!d){if(this.dragThreshMet){if(c.events.b4EndDrag){c.b4EndDrag(f);c.fireEvent("b4EndDragEvent",{e:f})}if(c.events.endDrag){c.endDrag(f);c.fireEvent("endDragEvent",{e:f})}}if(c.events.mouseUp){c.onMouseUp(f);c.fireEvent("mouseUpEvent",{e:f})}}if(this._shimActive){this._deactivateShim();if(this.dragCurrent&&this.dragCurrent.useShim){this.useShim=this._shimState;this._shimState=false}}this.dragCurrent=null;this.dragOvers={}},handleMouseMove:function(g){var c=this.dragCurrent;if(c){if(YAHOO.env.ua.ie&&(YAHOO.env.ua.ie<9)&&!g.button){this.stopEvent(g);return this.handleMouseUp(g)}else{if(g.clientX<0||g.clientY<0){}}if(!this.dragThreshMet){var f=Math.abs(this.startX-YAHOO.util.Event.getPageX(g));var d=Math.abs(this.startY-YAHOO.util.Event.getPageY(g));if(f>this.clickPixelThresh||d>this.clickPixelThresh){this.startDrag(this.startX,this.startY)}}if(this.dragThreshMet){if(c&&c.events.b4Drag){c.b4Drag(g);c.fireEvent("b4DragEvent",{e:g})}if(c&&c.events.drag){c.onDrag(g);c.fireEvent("dragEvent",{e:g})}if(c){this.fireEvents(g,false)}}this.stopEvent(g)}},fireEvents:function(A,o){var F=this.dragCurrent;if(!F||F.isLocked()||F.dragOnly){return}var q=YAHOO.util.Event.getPageX(A),p=YAHOO.util.Event.getPageY(A),s=new YAHOO.util.Point(q,p),m=F.getTargetCoord(s.x,s.y),g=F.getDragEl(),f=["out","over","drop","enter"],z=new YAHOO.util.Region(m.y,m.x+g.offsetWidth,m.y+g.offsetHeight,m.x),k=[],d={},n={},t=[],G={outEvts:[],overEvts:[],dropEvts:[],enterEvts:[]};for(var v in this.dragOvers){var H=this.dragOvers[v];if(!this.isTypeOfDD(H)){continue}if(!this.isOverTarget(s,H,this.mode,z)){G.outEvts.push(H)}k[v]=true;delete this.dragOvers[v]}for(var u in F.groups){if("string"!=typeof u){continue}for(v in this.ids[u]){var h=this.ids[u][v];if(!this.isTypeOfDD(h)){continue}if(h.isTarget&&!h.isLocked()&&h!=F){if(this.isOverTarget(s,h,this.mode,z)){d[u]=true;if(o){G.dropEvts.push(h)}else{if(!k[h.id]){G.enterEvts.push(h)}else{G.overEvts.push(h)}this.dragOvers[h.id]=h}}}}}this.interactionInfo={out:G.outEvts,enter:G.enterEvts,over:G.overEvts,drop:G.dropEvts,point:s,draggedRegion:z,sourceRegion:this.locationCache[F.id],validDrop:o};for(var c in d){t.push(c)}if(o&&!G.dropEvts.length){this.interactionInfo.validDrop=false;if(F.events.invalidDrop){F.onInvalidDrop(A);F.fireEvent("invalidDropEvent",{e:A})}}for(v=0;v<f.length;v++){var D=null;if(G[f[v]+"Evts"]){D=G[f[v]+"Evts"]}if(D&&D.length){var j=f[v].charAt(0).toUpperCase()+f[v].substr(1),C="onDrag"+j,l="b4Drag"+j,r="drag"+j+"Event",B="drag"+j;if(this.mode){if(F.events[l]){F[l](A,D,t);n[C]=F.fireEvent(l+"Event",{event:A,info:D,group:t})}if(F.events[B]&&(n[C]!==false)){F[C](A,D,t);F.fireEvent(r,{event:A,info:D,group:t})}}else{for(var E=0,w=D.length;E<w;++E){if(F.events[l]){F[l](A,D[E].id,t[0]);n[C]=F.fireEvent(l+"Event",{event:A,info:D[E].id,group:t[0]})}if(F.events[B]&&(n[C]!==false)){F[C](A,D[E].id,t[0]);F.fireEvent(r,{event:A,info:D[E].id,group:t[0]})}}}}}},getBestMatch:function(e){var g=null;var d=e.length;if(d==1){g=e[0]}else{for(var f=0;f<d;++f){var c=e[f];if(this.mode==this.INTERSECT&&c.cursorIsOver){g=c;break}else{if(!g||!g.overlap||(c.overlap&&g.overlap.getArea()<c.overlap.getArea())){g=c}}}}return g},refreshCache:function(d){var f=d||this.ids;for(var c in f){if("string"!=typeof c){continue}for(var e in this.ids[c]){var h=this.ids[c][e];if(this.isTypeOfDD(h)){var j=this.getLocation(h);if(j){this.locationCache[h.id]=j}else{delete this.locationCache[h.id]}}}}},verifyEl:function(d){try{if(d){var c=d.offsetParent;if(c){return true}}}catch(f){}return false},getLocation:function(i){if(!this.isTypeOfDD(i)){return null}var g=i.getEl(),m,f,d,o,n,p,c,k,h;try{m=YAHOO.util.Dom.getXY(g)}catch(j){}if(!m){return null}f=m[0];d=f+g.offsetWidth;o=m[1];n=o+g.offsetHeight;p=o-i.padding[0];c=d+i.padding[1];k=n+i.padding[2];h=f-i.padding[3];return new YAHOO.util.Region(p,c,k,h)},isOverTarget:function(k,c,e,f){var g=this.locationCache[c.id];if(!g||!this.useCache){g=this.getLocation(c);this.locationCache[c.id]=g}if(!g){return false}c.cursorIsOver=g.contains(k);var j=this.dragCurrent;if(!j||(!e&&!j.constrainX&&!j.constrainY)){return c.cursorIsOver}c.overlap=null;if(!f){var h=j.getTargetCoord(k.x,k.y);var d=j.getDragEl();f=new YAHOO.util.Region(h.y,h.x+d.offsetWidth,h.y+d.offsetHeight,h.x)}var i=f.intersect(g);if(i){c.overlap=i;return(e)?true:c.cursorIsOver}else{return false}},_onUnload:function(d,c){this.unregAll()},unregAll:function(){if(this.dragCurrent){this.stopDrag();this.dragCurrent=null}this._execOnAll("unreg",[]);this.ids={}},elementCache:{},getElWrapper:function(d){var c=this.elementCache[d];if(!c||!c.el){c=this.elementCache[d]=new this.ElementWrapper(YAHOO.util.Dom.get(d))}return c},getElement:function(c){return YAHOO.util.Dom.get(c)},getCss:function(d){var c=YAHOO.util.Dom.get(d);return(c)?c.style:null},ElementWrapper:function(c){this.el=c||null;this.id=this.el&&c.id;this.css=this.el&&c.style},getPosX:function(c){return YAHOO.util.Dom.getX(c)},getPosY:function(c){return YAHOO.util.Dom.getY(c)},swapNode:function(e,c){if(e.swapNode){e.swapNode(c)}else{var f=c.parentNode;var d=c.nextSibling;if(d==e){f.insertBefore(e,c)}else{if(c==e.nextSibling){f.insertBefore(c,e)}else{e.parentNode.replaceChild(c,e);f.insertBefore(e,d)}}}},getScroll:function(){var e,c,f=document.documentElement,d=document.body;if(f&&(f.scrollTop||f.scrollLeft)){e=f.scrollTop;c=f.scrollLeft}else{if(d){e=d.scrollTop;c=d.scrollLeft}else{}}return{top:e,left:c}},getStyle:function(d,c){return YAHOO.util.Dom.getStyle(d,c)},getScrollTop:function(){return this.getScroll().top},getScrollLeft:function(){return this.getScroll().left},moveToEl:function(c,e){var d=YAHOO.util.Dom.getXY(e);YAHOO.util.Dom.setXY(c,d)},getClientHeight:function(){return YAHOO.util.Dom.getViewportHeight()},getClientWidth:function(){return YAHOO.util.Dom.getViewportWidth()},numericSort:function(d,c){return(d-c)},_timeoutCount:0,_addListeners:function(){var c=YAHOO.util.DDM;if(YAHOO.util.Event&&document){c._onLoad()}else{if(c._timeoutCount>2000){}else{setTimeout(c._addListeners,10);if(document&&document.body){c._timeoutCount+=1}}}},handleWasClicked:function(c,e){if(this.isHandle(e,c.id)){return true}else{var d=c.parentNode;while(d){if(this.isHandle(e,d.id)){return true}else{d=d.parentNode}}}return false}}}();YAHOO.util.DDM=YAHOO.util.DragDropMgr;YAHOO.util.DDM._addListeners()}(function(){var a=YAHOO.util.Event;var b=YAHOO.util.Dom;YAHOO.util.DragDrop=function(e,c,d){if(e){this.init(e,c,d)}};YAHOO.util.DragDrop.prototype={events:null,on:function(){this.subscribe.apply(this,arguments)},id:null,config:null,dragElId:null,handleElId:null,invalidHandleTypes:null,invalidHandleIds:null,invalidHandleClasses:null,startPageX:0,startPageY:0,groups:null,locked:false,lock:function(){this.locked=true},unlock:function(){this.locked=false},isTarget:true,padding:null,dragOnly:false,useShim:false,_domRef:null,__ygDragDrop:true,constrainX:false,constrainY:false,minX:0,maxX:0,minY:0,maxY:0,deltaX:0,deltaY:0,maintainOffset:false,xTicks:null,yTicks:null,primaryButtonOnly:true,available:false,hasOuterHandles:false,cursorIsOver:false,overlap:null,b4StartDrag:function(c,d){},startDrag:function(c,d){},b4Drag:function(c){},onDrag:function(c){},onDragEnter:function(c,d){},b4DragOver:function(c){},onDragOver:function(c,d){},b4DragOut:function(c){},onDragOut:function(c,d){},b4DragDrop:function(c){},onDragDrop:function(c,d){},onInvalidDrop:function(c){},b4EndDrag:function(c){},endDrag:function(c){},b4MouseDown:function(c){},onMouseDown:function(c){},onMouseUp:function(c){},onAvailable:function(){},getEl:function(){if(!this._domRef){this._domRef=b.get(this.id)}return this._domRef},getDragEl:function(){return b.get(this.dragElId)},init:function(f,c,d){this.initTarget(f,c,d);a.on(this._domRef||this.id,"mousedown",this.handleMouseDown,this,true);for(var e in this.events){this.createEvent(e+"Event")}},initTarget:function(e,c,d){this.config=d||{};this.events={};this.DDM=YAHOO.util.DDM;this.groups={};if(typeof e!=="string"){this._domRef=e;e=b.generateId(e)}this.id=e;this.addToGroup((c)?c:"default");this.handleElId=e;a.onAvailable(e,this.handleOnAvailable,this,true);this.setDragElId(e);this.invalidHandleTypes={A:"A"};this.invalidHandleIds={};this.invalidHandleClasses=[];this.applyConfig()},applyConfig:function(){this.events={mouseDown:true,b4MouseDown:true,mouseUp:true,b4StartDrag:true,startDrag:true,b4EndDrag:true,endDrag:true,drag:true,b4Drag:true,invalidDrop:true,b4DragOut:true,dragOut:true,dragEnter:true,b4DragOver:true,dragOver:true,b4DragDrop:true,dragDrop:true};if(this.config.events){for(var c in this.config.events){if(this.config.events[c]===false){this.events[c]=false}}}this.padding=this.config.padding||[0,0,0,0];this.isTarget=(this.config.isTarget!==false);this.maintainOffset=(this.config.maintainOffset);this.primaryButtonOnly=(this.config.primaryButtonOnly!==false);this.dragOnly=((this.config.dragOnly===true)?true:false);this.useShim=((this.config.useShim===true)?true:false)},handleOnAvailable:function(){this.available=true;this.resetConstraints();this.onAvailable()},setPadding:function(e,c,f,d){if(!c&&0!==c){this.padding=[e,e,e,e]}else{if(!f&&0!==f){this.padding=[e,c,e,c]}else{this.padding=[e,c,f,d]}}},setInitPosition:function(f,e){var g=this.getEl();if(!this.DDM.verifyEl(g)){if(g&&g.style&&(g.style.display=="none")){}else{}return}var d=f||0;var c=e||0;var h=b.getXY(g);this.initPageX=h[0]-d;this.initPageY=h[1]-c;this.lastPageX=h[0];this.lastPageY=h[1];this.setStartPosition(h)},setStartPosition:function(d){var c=d||b.getXY(this.getEl());this.deltaSetXY=null;this.startPageX=c[0];this.startPageY=c[1]},addToGroup:function(c){this.groups[c]=true;this.DDM.regDragDrop(this,c)},removeFromGroup:function(c){if(this.groups[c]){delete this.groups[c]}this.DDM.removeDDFromGroup(this,c)},setDragElId:function(c){this.dragElId=c},setHandleElId:function(c){if(typeof c!=="string"){c=b.generateId(c)}this.handleElId=c;this.DDM.regHandle(this.id,c)},setOuterHandleElId:function(c){if(typeof c!=="string"){c=b.generateId(c)}a.on(c,"mousedown",this.handleMouseDown,this,true);this.setHandleElId(c);this.hasOuterHandles=true},unreg:function(){a.removeListener(this.id,"mousedown",this.handleMouseDown);this._domRef=null;this.DDM._remove(this)},isLocked:function(){return(this.DDM.isLocked()||this.locked)},handleMouseDown:function(k,j){var d=k.which||k.button;if(this.primaryButtonOnly&&d>1){return}if(this.isLocked()){return}var c=this.b4MouseDown(k),g=true;if(this.events.b4MouseDown){g=this.fireEvent("b4MouseDownEvent",k)}var f=this.onMouseDown(k),i=true;if(this.events.mouseDown){if(f===false){i=false}else{i=this.fireEvent("mouseDownEvent",k)}}if((c===false)||(f===false)||(g===false)||(i===false)){return}this.DDM.refreshCache(this.groups);var h=new YAHOO.util.Point(a.getPageX(k),a.getPageY(k));if(!this.hasOuterHandles&&!this.DDM.isOverTarget(h,this)){}else{if(this.clickValidator(k)){this.setStartPosition();this.DDM.handleMouseDown(k,this);this.DDM.stopEvent(k)}else{}}},clickValidator:function(d){var c=YAHOO.util.Event.getTarget(d);return(this.isValidHandleChild(c)&&(this.id==this.handleElId||this.DDM.handleWasClicked(c,this.id)))},getTargetCoord:function(e,d){var c=e-this.deltaX;var f=d-this.deltaY;if(this.constrainX){if(c<this.minX){c=this.minX}if(c>this.maxX){c=this.maxX}}if(this.constrainY){if(f<this.minY){f=this.minY}if(f>this.maxY){f=this.maxY}}c=this.getTick(c,this.xTicks);f=this.getTick(f,this.yTicks);return{x:c,y:f}},addInvalidHandleType:function(c){var d=c.toUpperCase();this.invalidHandleTypes[d]=d},addInvalidHandleId:function(c){if(typeof c!=="string"){c=b.generateId(c)}this.invalidHandleIds[c]=c},addInvalidHandleClass:function(c){this.invalidHandleClasses.push(c)},removeInvalidHandleType:function(c){var d=c.toUpperCase();delete this.invalidHandleTypes[d]},removeInvalidHandleId:function(c){if(typeof c!=="string"){c=b.generateId(c)}delete this.invalidHandleIds[c]},removeInvalidHandleClass:function(d){for(var e=0,c=this.invalidHandleClasses.length;e<c;++e){if(this.invalidHandleClasses[e]==d){delete this.invalidHandleClasses[e]}}},isValidHandleChild:function(g){var f=true;var j;try{j=g.nodeName.toUpperCase()}catch(h){j=g.nodeName}f=f&&!this.invalidHandleTypes[j];f=f&&!this.invalidHandleIds[g.id];for(var d=0,c=this.invalidHandleClasses.length;f&&d<c;++d){f=!b.hasClass(g,this.invalidHandleClasses[d])}return f},setXTicks:function(f,c){this.xTicks=[];this.xTickSize=c;var e={};for(var d=this.initPageX;d>=this.minX;d=d-c){if(!e[d]){this.xTicks[this.xTicks.length]=d;e[d]=true}}for(d=this.initPageX;d<=this.maxX;d=d+c){if(!e[d]){this.xTicks[this.xTicks.length]=d;e[d]=true}}this.xTicks.sort(this.DDM.numericSort)},setYTicks:function(f,c){this.yTicks=[];this.yTickSize=c;var e={};for(var d=this.initPageY;d>=this.minY;d=d-c){if(!e[d]){this.yTicks[this.yTicks.length]=d;e[d]=true}}for(d=this.initPageY;d<=this.maxY;d=d+c){if(!e[d]){this.yTicks[this.yTicks.length]=d;e[d]=true}}this.yTicks.sort(this.DDM.numericSort)},setXConstraint:function(e,d,c){this.leftConstraint=parseInt(e,10);this.rightConstraint=parseInt(d,10);this.minX=this.initPageX-this.leftConstraint;this.maxX=this.initPageX+this.rightConstraint;if(c){this.setXTicks(this.initPageX,c)}this.constrainX=true},clearConstraints:function(){this.constrainX=false;this.constrainY=false;this.clearTicks()},clearTicks:function(){this.xTicks=null;this.yTicks=null;this.xTickSize=0;this.yTickSize=0},setYConstraint:function(c,e,d){this.topConstraint=parseInt(c,10);this.bottomConstraint=parseInt(e,10);this.minY=this.initPageY-this.topConstraint;this.maxY=this.initPageY+this.bottomConstraint;if(d){this.setYTicks(this.initPageY,d)}this.constrainY=true},resetConstraints:function(){if(this.initPageX||this.initPageX===0){var d=(this.maintainOffset)?this.lastPageX-this.initPageX:0;var c=(this.maintainOffset)?this.lastPageY-this.initPageY:0;this.setInitPosition(d,c)}else{this.setInitPosition()}if(this.constrainX){this.setXConstraint(this.leftConstraint,this.rightConstraint,this.xTickSize)}if(this.constrainY){this.setYConstraint(this.topConstraint,this.bottomConstraint,this.yTickSize)}},getTick:function(j,f){if(!f){return j}else{if(f[0]>=j){return f[0]}else{for(var d=0,c=f.length;d<c;++d){var e=d+1;if(f[e]&&f[e]>=j){var h=j-f[d];var g=f[e]-j;return(g>h)?f[d]:f[e]}}return f[f.length-1]}}},toString:function(){return("DragDrop "+this.id)}};YAHOO.augment(YAHOO.util.DragDrop,YAHOO.util.EventProvider)})();YAHOO.util.DD=function(c,a,b){if(c){this.init(c,a,b)}};YAHOO.extend(YAHOO.util.DD,YAHOO.util.DragDrop,{scroll:true,autoOffset:function(c,b){var a=c-this.startPageX;var d=b-this.startPageY;this.setDelta(a,d)},setDelta:function(b,a){this.deltaX=b;this.deltaY=a},setDragElPos:function(c,b){var a=this.getDragEl();this.alignElWithMouse(a,c,b)},alignElWithMouse:function(c,g,f){var e=this.getTargetCoord(g,f);if(!this.deltaSetXY){var h=[e.x,e.y];YAHOO.util.Dom.setXY(c,h);var d=parseInt(YAHOO.util.Dom.getStyle(c,"left"),10);var b=parseInt(YAHOO.util.Dom.getStyle(c,"top"),10);this.deltaSetXY=[d-e.x,b-e.y]}else{YAHOO.util.Dom.setStyle(c,"left",(e.x+this.deltaSetXY[0])+"px");YAHOO.util.Dom.setStyle(c,"top",(e.y+this.deltaSetXY[1])+"px")}this.cachePosition(e.x,e.y);var a=this;setTimeout(function(){a.autoScroll.call(a,e.x,e.y,c.offsetHeight,c.offsetWidth)},0)},cachePosition:function(b,a){if(b){this.lastPageX=b;this.lastPageY=a}else{var c=YAHOO.util.Dom.getXY(this.getEl());this.lastPageX=c[0];this.lastPageY=c[1]}},autoScroll:function(k,j,e,l){if(this.scroll){var m=this.DDM.getClientHeight();var b=this.DDM.getClientWidth();var o=this.DDM.getScrollTop();var d=this.DDM.getScrollLeft();var i=e+j;var n=l+k;var g=(m+o-j-this.deltaY);var f=(b+d-k-this.deltaX);var c=40;var a=(document.all)?80:30;if(i>m&&g<c){window.scrollTo(d,o+a)}if(j<o&&o>0&&j-o<c){window.scrollTo(d,o-a)}if(n>b&&f<c){window.scrollTo(d+a,o)}if(k<d&&d>0&&k-d<c){window.scrollTo(d-a,o)}}},applyConfig:function(){YAHOO.util.DD.superclass.applyConfig.call(this);this.scroll=(this.config.scroll!==false)},b4MouseDown:function(a){this.setStartPosition();this.autoOffset(YAHOO.util.Event.getPageX(a),YAHOO.util.Event.getPageY(a))},b4Drag:function(a){this.setDragElPos(YAHOO.util.Event.getPageX(a),YAHOO.util.Event.getPageY(a))},toString:function(){return("DD "+this.id)}});YAHOO.util.DDProxy=function(c,a,b){if(c){this.init(c,a,b);this.initFrame()}};YAHOO.util.DDProxy.dragElId="ygddfdiv";YAHOO.extend(YAHOO.util.DDProxy,YAHOO.util.DD,{resizeFrame:true,centerFrame:false,createFrame:function(){var b=this,a=document.body;if(!a||!a.firstChild){setTimeout(function(){b.createFrame()},50);return}var f=this.getDragEl(),e=YAHOO.util.Dom;if(!f){f=document.createElement("div");f.id=this.dragElId;var d=f.style;d.position="absolute";d.visibility="hidden";d.cursor="move";d.border="2px solid #aaa";d.zIndex=999;d.height="25px";d.width="25px";var c=document.createElement("div");e.setStyle(c,"height","100%");e.setStyle(c,"width","100%");e.setStyle(c,"background-color","#ccc");e.setStyle(c,"opacity","0");f.appendChild(c);a.insertBefore(f,a.firstChild)}},initFrame:function(){this.createFrame()},applyConfig:function(){YAHOO.util.DDProxy.superclass.applyConfig.call(this);this.resizeFrame=(this.config.resizeFrame!==false);this.centerFrame=(this.config.centerFrame);this.setDragElId(this.config.dragElId||YAHOO.util.DDProxy.dragElId)},showFrame:function(e,d){var c=this.getEl();var a=this.getDragEl();var b=a.style;this._resizeProxy();if(this.centerFrame){this.setDelta(Math.round(parseInt(b.width,10)/2),Math.round(parseInt(b.height,10)/2))}this.setDragElPos(e,d);YAHOO.util.Dom.setStyle(a,"visibility","visible")},_resizeProxy:function(){if(this.resizeFrame){var h=YAHOO.util.Dom;var b=this.getEl();var c=this.getDragEl();var g=parseInt(h.getStyle(c,"borderTopWidth"),10);var i=parseInt(h.getStyle(c,"borderRightWidth"),10);var f=parseInt(h.getStyle(c,"borderBottomWidth"),10);var d=parseInt(h.getStyle(c,"borderLeftWidth"),10);if(isNaN(g)){g=0}if(isNaN(i)){i=0}if(isNaN(f)){f=0}if(isNaN(d)){d=0}var e=Math.max(0,b.offsetWidth-i-d);var a=Math.max(0,b.offsetHeight-g-f);h.setStyle(c,"width",e+"px");h.setStyle(c,"height",a+"px")}},b4MouseDown:function(b){this.setStartPosition();var a=YAHOO.util.Event.getPageX(b);var c=YAHOO.util.Event.getPageY(b);this.autoOffset(a,c)},b4StartDrag:function(a,b){this.showFrame(a,b)},b4EndDrag:function(a){YAHOO.util.Dom.setStyle(this.getDragEl(),"visibility","hidden")},endDrag:function(d){var c=YAHOO.util.Dom;var b=this.getEl();var a=this.getDragEl();c.setStyle(a,"visibility","");c.setStyle(b,"visibility","hidden");YAHOO.util.DDM.moveToEl(b,a);c.setStyle(a,"visibility","hidden");c.setStyle(b,"visibility","")},toString:function(){return("DDProxy "+this.id)}});YAHOO.util.DDTarget=function(c,a,b){if(c){this.initTarget(c,a,b)}};YAHOO.extend(YAHOO.util.DDTarget,YAHOO.util.DragDrop,{toString:function(){return("DDTarget "+this.id)}});YAHOO.register("dragdrop",YAHOO.util.DragDropMgr,{version:"2.9.0",build:"2800"});YAHOO.util.Attribute=function(b,a){if(a){this.owner=a;this.configure(b,true)}};YAHOO.util.Attribute.INVALID_VALUE={};YAHOO.util.Attribute.prototype={name:undefined,value:null,owner:null,readOnly:false,writeOnce:false,_initialConfig:null,_written:false,method:null,setter:null,getter:null,validator:null,getValue:function(){var a=this.value;if(this.getter){a=this.getter.call(this.owner,this.name,a)}return a},setValue:function(f,b){var e,a=this.owner,c=this.name,g=YAHOO.util.Attribute.INVALID_VALUE,d={type:c,prevValue:this.getValue(),newValue:f};if(this.readOnly||(this.writeOnce&&this._written)){return false}if(this.validator&&!this.validator.call(a,f)){return false}if(!b){e=a.fireBeforeChangeEvent(d);if(e===false){return false}}if(this.setter){f=this.setter.call(a,f,this.name);if(f===undefined){}if(f===g){return false}}if(this.method){if(this.method.call(a,f,this.name)===g){return false}}this.value=f;this._written=true;d.type=c;if(!b){this.owner.fireChangeEvent(d)}return true},configure:function(b,c){b=b||{};if(c){this._written=false}this._initialConfig=this._initialConfig||{};for(var a in b){if(b.hasOwnProperty(a)){this[a]=b[a];if(c){this._initialConfig[a]=b[a]}}}},resetValue:function(){return this.setValue(this._initialConfig.value)},resetConfig:function(){this.configure(this._initialConfig,true)},refresh:function(a){this.setValue(this.value,a)}};(function(){var a=YAHOO.util.Lang;YAHOO.util.AttributeProvider=function(){};YAHOO.util.AttributeProvider.prototype={_configs:null,get:function(c){this._configs=this._configs||{};var b=this._configs[c];if(!b||!this._configs.hasOwnProperty(c)){return null}return b.getValue()},set:function(d,e,b){this._configs=this._configs||{};var c=this._configs[d];if(!c){return false}return c.setValue(e,b)},getAttributeKeys:function(){this._configs=this._configs;var c=[],b;for(b in this._configs){if(a.hasOwnProperty(this._configs,b)&&!a.isUndefined(this._configs[b])){c[c.length]=b}}return c},setAttributes:function(d,b){for(var c in d){if(a.hasOwnProperty(d,c)){this.set(c,d[c],b)}}},resetValue:function(c,b){this._configs=this._configs||{};if(this._configs[c]){this.set(c,this._configs[c]._initialConfig.value,b);return true}return false},refresh:function(e,c){this._configs=this._configs||{};var f=this._configs;e=((a.isString(e))?[e]:e)||this.getAttributeKeys();for(var d=0,b=e.length;d<b;++d){if(f.hasOwnProperty(e[d])){this._configs[e[d]].refresh(c)}}},register:function(b,c){this.setAttributeConfig(b,c)},getAttributeConfig:function(c){this._configs=this._configs||{};var b=this._configs[c]||{};var d={};for(c in b){if(a.hasOwnProperty(b,c)){d[c]=b[c]}}return d},setAttributeConfig:function(b,c,d){this._configs=this._configs||{};c=c||{};if(!this._configs[b]){c.name=b;this._configs[b]=this.createAttribute(c)}else{this._configs[b].configure(c,d)}},configureAttribute:function(b,c,d){this.setAttributeConfig(b,c,d)},resetAttributeConfig:function(b){this._configs=this._configs||{};this._configs[b].resetConfig()},subscribe:function(b,c){this._events=this._events||{};if(!(b in this._events)){this._events[b]=this.createEvent(b)}YAHOO.util.EventProvider.prototype.subscribe.apply(this,arguments)},on:function(){this.subscribe.apply(this,arguments)},addListener:function(){this.subscribe.apply(this,arguments)},fireBeforeChangeEvent:function(c){var b="before";b+=c.type.charAt(0).toUpperCase()+c.type.substr(1)+"Change";c.type=b;return this.fireEvent(c.type,c)},fireChangeEvent:function(b){b.type+="Change";return this.fireEvent(b.type,b)},createAttribute:function(b){return new YAHOO.util.Attribute(b,this)}};YAHOO.augment(YAHOO.util.AttributeProvider,YAHOO.util.EventProvider)})();(function(){var b=YAHOO.util.Dom,d=YAHOO.util.AttributeProvider,c={mouseenter:true,mouseleave:true};var a=function(e,f){this.init.apply(this,arguments)};a.DOM_EVENTS={click:true,dblclick:true,keydown:true,keypress:true,keyup:true,mousedown:true,mousemove:true,mouseout:true,mouseover:true,mouseup:true,mouseenter:true,mouseleave:true,focus:true,blur:true,submit:true,change:true};a.prototype={DOM_EVENTS:null,DEFAULT_HTML_SETTER:function(g,e){var f=this.get("element");if(f){f[e]=g}return g},DEFAULT_HTML_GETTER:function(e){var f=this.get("element"),g;if(f){g=f[e]}return g},appendChild:function(e){e=e.get?e.get("element"):e;return this.get("element").appendChild(e)},getElementsByTagName:function(e){return this.get("element").getElementsByTagName(e)},hasChildNodes:function(){return this.get("element").hasChildNodes()},insertBefore:function(e,f){e=e.get?e.get("element"):e;f=(f&&f.get)?f.get("element"):f;return this.get("element").insertBefore(e,f)},removeChild:function(e){e=e.get?e.get("element"):e;return this.get("element").removeChild(e)},replaceChild:function(e,f){e=e.get?e.get("element"):e;f=f.get?f.get("element"):f;return this.get("element").replaceChild(e,f)},initAttributes:function(e){},addListener:function(j,i,k,h){h=h||this;var e=YAHOO.util.Event,g=this.get("element")||this.get("id"),f=this;if(c[j]&&!e._createMouseDelegate){return false}if(!this._events[j]){if(g&&this.DOM_EVENTS[j]){e.on(g,j,function(m,l){if(m.srcElement&&!m.target){m.target=m.srcElement}if((m.toElement&&!m.relatedTarget)||(m.fromElement&&!m.relatedTarget)){m.relatedTarget=e.getRelatedTarget(m)}if(!m.currentTarget){m.currentTarget=g}f.fireEvent(j,m,l)},k,h)}this.createEvent(j,{scope:this})}return YAHOO.util.EventProvider.prototype.subscribe.apply(this,arguments)},on:function(){return this.addListener.apply(this,arguments)},subscribe:function(){return this.addListener.apply(this,arguments)},removeListener:function(f,e){return this.unsubscribe.apply(this,arguments)},addClass:function(e){b.addClass(this.get("element"),e)},getElementsByClassName:function(f,e){return b.getElementsByClassName(f,e,this.get("element"))},hasClass:function(e){return b.hasClass(this.get("element"),e)},removeClass:function(e){return b.removeClass(this.get("element"),e)},replaceClass:function(f,e){return b.replaceClass(this.get("element"),f,e)},setStyle:function(f,e){return b.setStyle(this.get("element"),f,e)},getStyle:function(e){return b.getStyle(this.get("element"),e)},fireQueue:function(){var f=this._queue;for(var g=0,e=f.length;g<e;++g){this[f[g][0]].apply(this,f[g][1])}},appendTo:function(f,g){f=(f.get)?f.get("element"):b.get(f);this.fireEvent("beforeAppendTo",{type:"beforeAppendTo",target:f});g=(g&&g.get)?g.get("element"):b.get(g);var e=this.get("element");if(!e){return false}if(!f){return false}if(e.parent!=f){if(g){f.insertBefore(e,g)}else{f.appendChild(e)}}this.fireEvent("appendTo",{type:"appendTo",target:f});return e},get:function(e){var g=this._configs||{},f=g.element;if(f&&!g[e]&&!YAHOO.lang.isUndefined(f.value[e])){this._setHTMLAttrConfig(e)}return d.prototype.get.call(this,e)},setAttributes:function(l,h){var f={},j=this._configOrder;for(var k=0,e=j.length;k<e;++k){if(l[j[k]]!==undefined){f[j[k]]=true;this.set(j[k],l[j[k]],h)}}for(var g in l){if(l.hasOwnProperty(g)&&!f[g]){this.set(g,l[g],h)}}},set:function(f,h,e){var g=this.get("element");if(!g){this._queue[this._queue.length]=["set",arguments];if(this._configs[f]){this._configs[f].value=h}return}if(!this._configs[f]&&!YAHOO.lang.isUndefined(g[f])){this._setHTMLAttrConfig(f)}return d.prototype.set.apply(this,arguments)},setAttributeConfig:function(e,f,g){this._configOrder.push(e);d.prototype.setAttributeConfig.apply(this,arguments)},createEvent:function(f,e){this._events[f]=true;return d.prototype.createEvent.apply(this,arguments)},init:function(f,e){this._initElement(f,e)},destroy:function(){var e=this.get("element");YAHOO.util.Event.purgeElement(e,true);this.unsubscribeAll();if(e&&e.parentNode){e.parentNode.removeChild(e)}this._queue=[];this._events={};this._configs={};this._configOrder=[]},_initElement:function(g,f){this._queue=this._queue||[];this._events=this._events||{};this._configs=this._configs||{};this._configOrder=[];f=f||{};f.element=f.element||g||null;var i=false;var e=a.DOM_EVENTS;this.DOM_EVENTS=this.DOM_EVENTS||{};for(var h in e){if(e.hasOwnProperty(h)){this.DOM_EVENTS[h]=e[h]}}if(typeof f.element==="string"){this._setHTMLAttrConfig("id",{value:f.element})}if(b.get(f.element)){i=true;this._initHTMLElement(f);this._initContent(f)}YAHOO.util.Event.onAvailable(f.element,function(){if(!i){this._initHTMLElement(f)}this.fireEvent("available",{type:"available",target:b.get(f.element)})},this,true);YAHOO.util.Event.onContentReady(f.element,function(){if(!i){this._initContent(f)}this.fireEvent("contentReady",{type:"contentReady",target:b.get(f.element)})},this,true)},_initHTMLElement:function(e){this.setAttributeConfig("element",{value:b.get(e.element),readOnly:true})},_initContent:function(e){this.initAttributes(e);this.setAttributes(e,true);this.fireQueue()},_setHTMLAttrConfig:function(e,g){var f=this.get("element");g=g||{};g.name=e;g.setter=g.setter||this.DEFAULT_HTML_SETTER;g.getter=g.getter||this.DEFAULT_HTML_GETTER;g.value=g.value||f[e];this._configs[e]=new YAHOO.util.Attribute(g,this)}};YAHOO.augment(a,d);YAHOO.util.Element=a})();YAHOO.register("element",YAHOO.util.Element,{version:"2.9.0",build:"2800"});(function(){var lang=YAHOO.lang,util=YAHOO.util,Ev=util.Event;util.DataSourceBase=function(oLiveData,oConfigs){if(oLiveData===null||oLiveData===undefined){return}this.liveData=oLiveData;this._oQueue={interval:null,conn:null,requests:[]};this.responseSchema={};if(oConfigs&&(oConfigs.constructor==Object)){for(var sConfig in oConfigs){if(sConfig){this[sConfig]=oConfigs[sConfig]}}}var maxCacheEntries=this.maxCacheEntries;if(!lang.isNumber(maxCacheEntries)||(maxCacheEntries<0)){maxCacheEntries=0}this._aIntervals=[];this.createEvent("cacheRequestEvent");this.createEvent("cacheResponseEvent");this.createEvent("requestEvent");this.createEvent("responseEvent");this.createEvent("responseParseEvent");this.createEvent("responseCacheEvent");this.createEvent("dataErrorEvent");this.createEvent("cacheFlushEvent");var DS=util.DataSourceBase;this._sName="DataSource instance"+DS._nIndex;DS._nIndex++};var DS=util.DataSourceBase;lang.augmentObject(DS,{TYPE_UNKNOWN:-1,TYPE_JSARRAY:0,TYPE_JSFUNCTION:1,TYPE_XHR:2,TYPE_JSON:3,TYPE_XML:4,TYPE_TEXT:5,TYPE_HTMLTABLE:6,TYPE_SCRIPTNODE:7,TYPE_LOCAL:8,ERROR_DATAINVALID:"Invalid data",ERROR_DATANULL:"Null data",_nIndex:0,_nTransactionId:0,_cloneObject:function(o){if(!lang.isValue(o)){return o}var copy={};if(Object.prototype.toString.apply(o)==="[object RegExp]"){copy=o}else{if(lang.isFunction(o)){copy=o}else{if(lang.isArray(o)){var array=[];for(var i=0,len=o.length;i<len;i++){array[i]=DS._cloneObject(o[i])}copy=array}else{if(lang.isObject(o)){for(var x in o){if(lang.hasOwnProperty(o,x)){if(lang.isValue(o[x])&&lang.isObject(o[x])||lang.isArray(o[x])){copy[x]=DS._cloneObject(o[x])}else{copy[x]=o[x]}}}}else{copy=o}}}}return copy},_getLocationValue:function(field,context){var locator=field.locator||field.key||field,xmldoc=context.ownerDocument||context,result,res,value=null;try{if(!lang.isUndefined(xmldoc.evaluate)){result=xmldoc.evaluate(locator,context,xmldoc.createNSResolver(!context.ownerDocument?context.documentElement:context.ownerDocument.documentElement),0,null);while(res=result.iterateNext()){value=res.textContent}}else{xmldoc.setProperty("SelectionLanguage","XPath");result=context.selectNodes(locator)[0];value=result.value||result.text||null}return value}catch(e){}},issueCallback:function(callback,params,error,scope){if(lang.isFunction(callback)){callback.apply(scope,params)}else{if(lang.isObject(callback)){scope=callback.scope||scope||window;var callbackFunc=callback.success;if(error){callbackFunc=callback.failure}if(callbackFunc){callbackFunc.apply(scope,params.concat([callback.argument]))}}}},parseString:function(oData){if(!lang.isValue(oData)){return null}var string=oData+"";if(lang.isString(string)){return string}else{return null}},parseNumber:function(oData){if(!lang.isValue(oData)||(oData==="")){return null}var number=oData*1;if(lang.isNumber(number)){return number}else{return null}},convertNumber:function(oData){return DS.parseNumber(oData)},parseDate:function(oData){var date=null;if(lang.isValue(oData)&&!(oData instanceof Date)){date=new Date(oData)}else{return oData}if(date instanceof Date){return date}else{return null}},convertDate:function(oData){return DS.parseDate(oData)}});DS.Parser={string:DS.parseString,number:DS.parseNumber,date:DS.parseDate};DS.prototype={_sName:null,_aCache:null,_oQueue:null,_aIntervals:null,maxCacheEntries:0,liveData:null,dataType:DS.TYPE_UNKNOWN,responseType:DS.TYPE_UNKNOWN,responseSchema:null,useXPath:false,cloneBeforeCaching:false,toString:function(){return this._sName},getCachedResponse:function(oRequest,oCallback,oCaller){var aCache=this._aCache;if(this.maxCacheEntries>0){if(!aCache){this._aCache=[]}else{var nCacheLength=aCache.length;if(nCacheLength>0){var oResponse=null;this.fireEvent("cacheRequestEvent",{request:oRequest,callback:oCallback,caller:oCaller});for(var i=nCacheLength-1;i>=0;i--){var oCacheElem=aCache[i];if(this.isCacheHit(oRequest,oCacheElem.request)){oResponse=oCacheElem.response;this.fireEvent("cacheResponseEvent",{request:oRequest,response:oResponse,callback:oCallback,caller:oCaller});if(i<nCacheLength-1){aCache.splice(i,1);this.addToCache(oRequest,oResponse)}oResponse.cached=true;break}}return oResponse}}}else{if(aCache){this._aCache=null}}return null},isCacheHit:function(oRequest,oCachedRequest){return(oRequest===oCachedRequest)},addToCache:function(oRequest,oResponse){var aCache=this._aCache;if(!aCache){return}while(aCache.length>=this.maxCacheEntries){aCache.shift()}oResponse=(this.cloneBeforeCaching)?DS._cloneObject(oResponse):oResponse;var oCacheElem={request:oRequest,response:oResponse};aCache[aCache.length]=oCacheElem;this.fireEvent("responseCacheEvent",{request:oRequest,response:oResponse})},flushCache:function(){if(this._aCache){this._aCache=[];this.fireEvent("cacheFlushEvent")}},setInterval:function(nMsec,oRequest,oCallback,oCaller){if(lang.isNumber(nMsec)&&(nMsec>=0)){var oSelf=this;var nId=setInterval(function(){oSelf.makeConnection(oRequest,oCallback,oCaller)},nMsec);this._aIntervals.push(nId);return nId}else{}},clearInterval:function(nId){var tracker=this._aIntervals||[];for(var i=tracker.length-1;i>-1;i--){if(tracker[i]===nId){tracker.splice(i,1);clearInterval(nId)}}},clearAllIntervals:function(){var tracker=this._aIntervals||[];for(var i=tracker.length-1;i>-1;i--){clearInterval(tracker[i])}tracker=[]},sendRequest:function(oRequest,oCallback,oCaller){var oCachedResponse=this.getCachedResponse(oRequest,oCallback,oCaller);if(oCachedResponse){DS.issueCallback(oCallback,[oRequest,oCachedResponse],false,oCaller);return null}return this.makeConnection(oRequest,oCallback,oCaller)},makeConnection:function(oRequest,oCallback,oCaller){var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});var oRawResponse=this.liveData;this.handleResponse(oRequest,oRawResponse,oCallback,oCaller,tId);return tId},handleResponse:function(oRequest,oRawResponse,oCallback,oCaller,tId){this.fireEvent("responseEvent",{tId:tId,request:oRequest,response:oRawResponse,callback:oCallback,caller:oCaller});var xhr=(this.dataType==DS.TYPE_XHR)?true:false;var oParsedResponse=null;var oFullResponse=oRawResponse;if(this.responseType===DS.TYPE_UNKNOWN){var ctype=(oRawResponse&&oRawResponse.getResponseHeader)?oRawResponse.getResponseHeader["Content-Type"]:null;if(ctype){if(ctype.indexOf("text/xml")>-1){this.responseType=DS.TYPE_XML}else{if(ctype.indexOf("application/json")>-1){this.responseType=DS.TYPE_JSON}else{if(ctype.indexOf("text/plain")>-1){this.responseType=DS.TYPE_TEXT}}}}else{if(YAHOO.lang.isArray(oRawResponse)){this.responseType=DS.TYPE_JSARRAY}else{if(oRawResponse&&oRawResponse.nodeType&&(oRawResponse.nodeType===9||oRawResponse.nodeType===1||oRawResponse.nodeType===11)){this.responseType=DS.TYPE_XML}else{if(oRawResponse&&oRawResponse.nodeName&&(oRawResponse.nodeName.toLowerCase()=="table")){this.responseType=DS.TYPE_HTMLTABLE}else{if(YAHOO.lang.isObject(oRawResponse)){this.responseType=DS.TYPE_JSON}else{if(YAHOO.lang.isString(oRawResponse)){this.responseType=DS.TYPE_TEXT}}}}}}}switch(this.responseType){case DS.TYPE_JSARRAY:if(xhr&&oRawResponse&&oRawResponse.responseText){oFullResponse=oRawResponse.responseText}try{if(lang.isString(oFullResponse)){var parseArgs=[oFullResponse].concat(this.parseJSONArgs);if(lang.JSON){oFullResponse=lang.JSON.parse.apply(lang.JSON,parseArgs)}else{if(window.JSON&&JSON.parse){oFullResponse=JSON.parse.apply(JSON,parseArgs)}else{if(oFullResponse.parseJSON){oFullResponse=oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1))}else{while(oFullResponse.length>0&&(oFullResponse.charAt(0)!="{")&&(oFullResponse.charAt(0)!="[")){oFullResponse=oFullResponse.substring(1,oFullResponse.length)}if(oFullResponse.length>0){var arrayEnd=Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));oFullResponse=oFullResponse.substring(0,arrayEnd+1);oFullResponse=eval("("+oFullResponse+")")}}}}}}catch(e1){}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseArrayData(oRequest,oFullResponse);break;case DS.TYPE_JSON:if(xhr&&oRawResponse&&oRawResponse.responseText){oFullResponse=oRawResponse.responseText}try{if(lang.isString(oFullResponse)){var parseArgs=[oFullResponse].concat(this.parseJSONArgs);if(lang.JSON){oFullResponse=lang.JSON.parse.apply(lang.JSON,parseArgs)}else{if(window.JSON&&JSON.parse){oFullResponse=JSON.parse.apply(JSON,parseArgs)}else{if(oFullResponse.parseJSON){oFullResponse=oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1))}else{while(oFullResponse.length>0&&(oFullResponse.charAt(0)!="{")&&(oFullResponse.charAt(0)!="[")){oFullResponse=oFullResponse.substring(1,oFullResponse.length)}if(oFullResponse.length>0){var objEnd=Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));oFullResponse=oFullResponse.substring(0,objEnd+1);oFullResponse=eval("("+oFullResponse+")")}}}}}}catch(e){}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseJSONData(oRequest,oFullResponse);break;case DS.TYPE_HTMLTABLE:if(xhr&&oRawResponse.responseText){var el=document.createElement("div");el.innerHTML=oRawResponse.responseText;oFullResponse=el.getElementsByTagName("table")[0]}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseHTMLTableData(oRequest,oFullResponse);break;case DS.TYPE_XML:if(xhr&&oRawResponse.responseXML){oFullResponse=oRawResponse.responseXML}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseXMLData(oRequest,oFullResponse);break;case DS.TYPE_TEXT:if(xhr&&lang.isString(oRawResponse.responseText)){oFullResponse=oRawResponse.responseText}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseTextData(oRequest,oFullResponse);break;default:oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseData(oRequest,oFullResponse);break}oParsedResponse=oParsedResponse||{};if(!oParsedResponse.results){oParsedResponse.results=[]}if(!oParsedResponse.meta){oParsedResponse.meta={}}if(!oParsedResponse.error){oParsedResponse=this.doBeforeCallback(oRequest,oFullResponse,oParsedResponse,oCallback);this.fireEvent("responseParseEvent",{request:oRequest,response:oParsedResponse,callback:oCallback,caller:oCaller});this.addToCache(oRequest,oParsedResponse)}else{oParsedResponse.error=true;this.fireEvent("dataErrorEvent",{request:oRequest,response:oRawResponse,callback:oCallback,caller:oCaller,message:DS.ERROR_DATANULL})}oParsedResponse.tId=tId;DS.issueCallback(oCallback,[oRequest,oParsedResponse],oParsedResponse.error,oCaller)},doBeforeParseData:function(oRequest,oFullResponse,oCallback){return oFullResponse},doBeforeCallback:function(oRequest,oFullResponse,oParsedResponse,oCallback){return oParsedResponse},parseData:function(oRequest,oFullResponse){if(lang.isValue(oFullResponse)){var oParsedResponse={results:oFullResponse,meta:{}};return oParsedResponse}return null},parseArrayData:function(oRequest,oFullResponse){if(lang.isArray(oFullResponse)){var results=[],i,j,rec,field,data;if(lang.isArray(this.responseSchema.fields)){var fields=this.responseSchema.fields;for(i=fields.length-1;i>=0;--i){if(typeof fields[i]!=="object"){fields[i]={key:fields[i]}}}var parsers={},p;for(i=fields.length-1;i>=0;--i){p=(typeof fields[i].parser==="function"?fields[i].parser:DS.Parser[fields[i].parser+""])||fields[i].converter;if(p){parsers[fields[i].key]=p}}var arrType=lang.isArray(oFullResponse[0]);for(i=oFullResponse.length-1;i>-1;i--){var oResult={};rec=oFullResponse[i];if(typeof rec==="object"){for(j=fields.length-1;j>-1;j--){field=fields[j];data=arrType?rec[j]:rec[field.key];if(parsers[field.key]){data=parsers[field.key].call(this,data)}if(data===undefined){data=null}oResult[field.key]=data}}else{if(lang.isString(rec)){for(j=fields.length-1;j>-1;j--){field=fields[j];data=rec;if(parsers[field.key]){data=parsers[field.key].call(this,data)}if(data===undefined){data=null}oResult[field.key]=data}}}results[i]=oResult}}else{results=oFullResponse}var oParsedResponse={results:results};return oParsedResponse}return null},parseTextData:function(oRequest,oFullResponse){if(lang.isString(oFullResponse)){if(lang.isString(this.responseSchema.recordDelim)&&lang.isString(this.responseSchema.fieldDelim)){var oParsedResponse={results:[]};var recDelim=this.responseSchema.recordDelim;var fieldDelim=this.responseSchema.fieldDelim;if(oFullResponse.length>0){var newLength=oFullResponse.length-recDelim.length;if(oFullResponse.substr(newLength)==recDelim){oFullResponse=oFullResponse.substr(0,newLength)}if(oFullResponse.length>0){var recordsarray=oFullResponse.split(recDelim);for(var i=0,len=recordsarray.length,recIdx=0;i<len;++i){var bError=false,sRecord=recordsarray[i];if(lang.isString(sRecord)&&(sRecord.length>0)){var fielddataarray=recordsarray[i].split(fieldDelim);var oResult={};if(lang.isArray(this.responseSchema.fields)){var fields=this.responseSchema.fields;for(var j=fields.length-1;j>-1;j--){try{var data=fielddataarray[j];if(lang.isString(data)){if(data.charAt(0)=='"'){data=data.substr(1)}if(data.charAt(data.length-1)=='"'){data=data.substr(0,data.length-1)}var field=fields[j];var key=(lang.isValue(field.key))?field.key:field;if(!field.parser&&field.converter){field.parser=field.converter}var parser=(typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""];if(parser){data=parser.call(this,data)}if(data===undefined){data=null}oResult[key]=data}else{bError=true}}catch(e){bError=true}}}else{oResult=fielddataarray}if(!bError){oParsedResponse.results[recIdx++]=oResult}}}}}return oParsedResponse}}return null},parseXMLResult:function(result){var oResult={},schema=this.responseSchema;try{for(var m=schema.fields.length-1;m>=0;m--){var field=schema.fields[m];var key=(lang.isValue(field.key))?field.key:field;var data=null;if(this.useXPath){data=YAHOO.util.DataSource._getLocationValue(field,result)}else{var xmlAttr=result.attributes.getNamedItem(key);if(xmlAttr){data=xmlAttr.value}else{var xmlNode=result.getElementsByTagName(key);if(xmlNode&&xmlNode.item(0)){var item=xmlNode.item(0);data=(item)?((item.text)?item.text:(item.textContent)?item.textContent:null):null;if(!data){var datapieces=[];for(var j=0,len=item.childNodes.length;j<len;j++){if(item.childNodes[j].nodeValue){datapieces[datapieces.length]=item.childNodes[j].nodeValue}}if(datapieces.length>0){data=datapieces.join("")}}}}}if(data===null){data=""}if(!field.parser&&field.converter){field.parser=field.converter}var parser=(typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""];if(parser){data=parser.call(this,data)}if(data===undefined){data=null}oResult[key]=data}}catch(e){}return oResult},parseXMLData:function(oRequest,oFullResponse){var bError=false,schema=this.responseSchema,oParsedResponse={meta:{}},xmlList=null,metaNode=schema.metaNode,metaLocators=schema.metaFields||{},i,k,loc,v;try{if(this.useXPath){for(k in metaLocators){oParsedResponse.meta[k]=YAHOO.util.DataSource._getLocationValue(metaLocators[k],oFullResponse)}}else{metaNode=metaNode?oFullResponse.getElementsByTagName(metaNode)[0]:oFullResponse;if(metaNode){for(k in metaLocators){if(lang.hasOwnProperty(metaLocators,k)){loc=metaLocators[k];v=metaNode.getElementsByTagName(loc)[0];if(v){v=v.firstChild.nodeValue}else{v=metaNode.attributes.getNamedItem(loc);if(v){v=v.value}}if(lang.isValue(v)){oParsedResponse.meta[k]=v}}}}}xmlList=(schema.resultNode)?oFullResponse.getElementsByTagName(schema.resultNode):null}catch(e){}if(!xmlList||!lang.isArray(schema.fields)){bError=true}else{oParsedResponse.results=[];for(i=xmlList.length-1;i>=0;--i){var oResult=this.parseXMLResult(xmlList.item(i));oParsedResponse.results[i]=oResult}}if(bError){oParsedResponse.error=true}else{}return oParsedResponse},parseJSONData:function(oRequest,oFullResponse){var oParsedResponse={results:[],meta:{}};if(lang.isObject(oFullResponse)&&this.responseSchema.resultsList){var schema=this.responseSchema,fields=schema.fields,resultsList=oFullResponse,results=[],metaFields=schema.metaFields||{},fieldParsers=[],fieldPaths=[],simpleFields=[],bError=false,i,len,j,v,key,parser,path;var buildPath=function(needle){var path=null,keys=[],i=0;if(needle){needle=needle.replace(/\[(['"])(.*?)\1\]/g,function(x,$1,$2){keys[i]=$2;return".@"+(i++)}).replace(/\[(\d+)\]/g,function(x,$1){keys[i]=parseInt($1,10)|0;return".@"+(i++)}).replace(/^\./,"");if(!/[^\w\.\$@]/.test(needle)){path=needle.split(".");for(i=path.length-1;i>=0;--i){if(path[i].charAt(0)==="@"){path[i]=keys[parseInt(path[i].substr(1),10)]}}}else{}}return path};var walkPath=function(path,origin){var v=origin,i=0,len=path.length;for(;i<len&&v;++i){v=v[path[i]]}return v};path=buildPath(schema.resultsList);if(path){resultsList=walkPath(path,oFullResponse);if(resultsList===undefined){bError=true}}else{bError=true}if(!resultsList){resultsList=[]}if(!lang.isArray(resultsList)){resultsList=[resultsList]}if(!bError){if(schema.fields){var field;for(i=0,len=fields.length;i<len;i++){field=fields[i];key=field.key||field;parser=((typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""])||field.converter;path=buildPath(key);if(parser){fieldParsers[fieldParsers.length]={key:key,parser:parser}}if(path){if(path.length>1){fieldPaths[fieldPaths.length]={key:key,path:path}}else{simpleFields[simpleFields.length]={key:key,path:path[0]}}}else{}}for(i=resultsList.length-1;i>=0;--i){var r=resultsList[i],rec={};if(r){for(j=simpleFields.length-1;j>=0;--j){rec[simpleFields[j].key]=(r[simpleFields[j].path]!==undefined)?r[simpleFields[j].path]:r[j]}for(j=fieldPaths.length-1;j>=0;--j){rec[fieldPaths[j].key]=walkPath(fieldPaths[j].path,r)}for(j=fieldParsers.length-1;j>=0;--j){var p=fieldParsers[j].key;rec[p]=fieldParsers[j].parser.call(this,rec[p]);if(rec[p]===undefined){rec[p]=null}}}results[i]=rec}}else{results=resultsList}for(key in metaFields){if(lang.hasOwnProperty(metaFields,key)){path=buildPath(metaFields[key]);if(path){v=walkPath(path,oFullResponse);oParsedResponse.meta[key]=v}}}}else{oParsedResponse.error=true}oParsedResponse.results=results}else{oParsedResponse.error=true}return oParsedResponse},parseHTMLTableData:function(oRequest,oFullResponse){var bError=false;var elTable=oFullResponse;var fields=this.responseSchema.fields;var oParsedResponse={results:[]};if(lang.isArray(fields)){for(var i=0;i<elTable.tBodies.length;i++){var elTbody=elTable.tBodies[i];for(var j=elTbody.rows.length-1;j>-1;j--){var elRow=elTbody.rows[j];var oResult={};for(var k=fields.length-1;k>-1;k--){var field=fields[k];var key=(lang.isValue(field.key))?field.key:field;var data=elRow.cells[k].innerHTML;if(!field.parser&&field.converter){field.parser=field.converter}var parser=(typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""];if(parser){data=parser.call(this,data)}if(data===undefined){data=null}oResult[key]=data}oParsedResponse.results[j]=oResult}}}else{bError=true}if(bError){oParsedResponse.error=true}else{}return oParsedResponse}};lang.augmentProto(DS,util.EventProvider);util.LocalDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_LOCAL;if(oLiveData){if(YAHOO.lang.isArray(oLiveData)){this.responseType=DS.TYPE_JSARRAY}else{if(oLiveData.nodeType&&oLiveData.nodeType==9){this.responseType=DS.TYPE_XML}else{if(oLiveData.nodeName&&(oLiveData.nodeName.toLowerCase()=="table")){this.responseType=DS.TYPE_HTMLTABLE;oLiveData=oLiveData.cloneNode(true)}else{if(YAHOO.lang.isString(oLiveData)){this.responseType=DS.TYPE_TEXT}else{if(YAHOO.lang.isObject(oLiveData)){this.responseType=DS.TYPE_JSON}}}}}}else{oLiveData=[];this.responseType=DS.TYPE_JSARRAY}util.LocalDataSource.superclass.constructor.call(this,oLiveData,oConfigs)};lang.extend(util.LocalDataSource,DS);lang.augmentObject(util.LocalDataSource,DS);util.FunctionDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_JSFUNCTION;oLiveData=oLiveData||function(){};util.FunctionDataSource.superclass.constructor.call(this,oLiveData,oConfigs)};lang.extend(util.FunctionDataSource,DS,{scope:null,makeConnection:function(oRequest,oCallback,oCaller){var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});var oRawResponse=(this.scope)?this.liveData.call(this.scope,oRequest,this,oCallback):this.liveData(oRequest,oCallback);if(this.responseType===DS.TYPE_UNKNOWN){if(YAHOO.lang.isArray(oRawResponse)){this.responseType=DS.TYPE_JSARRAY}else{if(oRawResponse&&oRawResponse.nodeType&&oRawResponse.nodeType==9){this.responseType=DS.TYPE_XML}else{if(oRawResponse&&oRawResponse.nodeName&&(oRawResponse.nodeName.toLowerCase()=="table")){this.responseType=DS.TYPE_HTMLTABLE}else{if(YAHOO.lang.isObject(oRawResponse)){this.responseType=DS.TYPE_JSON}else{if(YAHOO.lang.isString(oRawResponse)){this.responseType=DS.TYPE_TEXT}}}}}}this.handleResponse(oRequest,oRawResponse,oCallback,oCaller,tId);return tId}});lang.augmentObject(util.FunctionDataSource,DS);util.ScriptNodeDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_SCRIPTNODE;oLiveData=oLiveData||"";util.ScriptNodeDataSource.superclass.constructor.call(this,oLiveData,oConfigs)};lang.extend(util.ScriptNodeDataSource,DS,{getUtility:util.Get,asyncMode:"allowAll",scriptCallbackParam:"callback",generateRequestCallback:function(id){return"&"+this.scriptCallbackParam+"=YAHOO.util.ScriptNodeDataSource.callbacks["+id+"]"},doBeforeGetScriptNode:function(sUri){return sUri},makeConnection:function(oRequest,oCallback,oCaller){var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});if(util.ScriptNodeDataSource._nPending===0){util.ScriptNodeDataSource.callbacks=[];util.ScriptNodeDataSource._nId=0}var id=util.ScriptNodeDataSource._nId;util.ScriptNodeDataSource._nId++;var oSelf=this;util.ScriptNodeDataSource.callbacks[id]=function(oRawResponse){if((oSelf.asyncMode!=="ignoreStaleResponses")||(id===util.ScriptNodeDataSource.callbacks.length-1)){if(oSelf.responseType===DS.TYPE_UNKNOWN){if(YAHOO.lang.isArray(oRawResponse)){oSelf.responseType=DS.TYPE_JSARRAY}else{if(oRawResponse.nodeType&&oRawResponse.nodeType==9){oSelf.responseType=DS.TYPE_XML}else{if(oRawResponse.nodeName&&(oRawResponse.nodeName.toLowerCase()=="table")){oSelf.responseType=DS.TYPE_HTMLTABLE}else{if(YAHOO.lang.isObject(oRawResponse)){oSelf.responseType=DS.TYPE_JSON}else{if(YAHOO.lang.isString(oRawResponse)){oSelf.responseType=DS.TYPE_TEXT}}}}}}oSelf.handleResponse(oRequest,oRawResponse,oCallback,oCaller,tId)}else{}delete util.ScriptNodeDataSource.callbacks[id]};util.ScriptNodeDataSource._nPending++;var sUri=this.liveData+oRequest+this.generateRequestCallback(id);sUri=this.doBeforeGetScriptNode(sUri);this.getUtility.script(sUri,{autopurge:true,onsuccess:util.ScriptNodeDataSource._bumpPendingDown,onfail:util.ScriptNodeDataSource._bumpPendingDown});return tId}});lang.augmentObject(util.ScriptNodeDataSource,DS);lang.augmentObject(util.ScriptNodeDataSource,{_nId:0,_nPending:0,callbacks:[]});util.XHRDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_XHR;this.connMgr=this.connMgr||util.Connect;oLiveData=oLiveData||"";util.XHRDataSource.superclass.constructor.call(this,oLiveData,oConfigs)};lang.extend(util.XHRDataSource,DS,{connMgr:null,connXhrMode:"allowAll",connMethodPost:false,connTimeout:0,makeConnection:function(oRequest,oCallback,oCaller){var oRawResponse=null;var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});var oSelf=this;var oConnMgr=this.connMgr;var oQueue=this._oQueue;var _xhrSuccess=function(oResponse){if(oResponse&&(this.connXhrMode=="ignoreStaleResponses")&&(oResponse.tId!=oQueue.conn.tId)){return null}else{if(!oResponse){this.fireEvent("dataErrorEvent",{request:oRequest,response:null,callback:oCallback,caller:oCaller,message:DS.ERROR_DATANULL});DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller);return null}else{if(this.responseType===DS.TYPE_UNKNOWN){var ctype=(oResponse.getResponseHeader)?oResponse.getResponseHeader["Content-Type"]:null;if(ctype){if(ctype.indexOf("text/xml")>-1){this.responseType=DS.TYPE_XML}else{if(ctype.indexOf("application/json")>-1){this.responseType=DS.TYPE_JSON}else{if(ctype.indexOf("text/plain")>-1){this.responseType=DS.TYPE_TEXT}}}}}this.handleResponse(oRequest,oResponse,oCallback,oCaller,tId)}}};var _xhrFailure=function(oResponse){this.fireEvent("dataErrorEvent",{request:oRequest,response:oResponse,callback:oCallback,caller:oCaller,message:DS.ERROR_DATAINVALID});if(lang.isString(this.liveData)&&lang.isString(oRequest)&&(this.liveData.lastIndexOf("?")!==this.liveData.length-1)&&(oRequest.indexOf("?")!==0)){}oResponse=oResponse||{};oResponse.error=true;DS.issueCallback(oCallback,[oRequest,oResponse],true,oCaller);return null};var _xhrCallback={success:_xhrSuccess,failure:_xhrFailure,scope:this};if(lang.isNumber(this.connTimeout)){_xhrCallback.timeout=this.connTimeout}if(this.connXhrMode=="cancelStaleRequests"){if(oQueue.conn){if(oConnMgr.abort){oConnMgr.abort(oQueue.conn);oQueue.conn=null}else{}}}if(oConnMgr&&oConnMgr.asyncRequest){var sLiveData=this.liveData;var isPost=this.connMethodPost;var sMethod=(isPost)?"POST":"GET";var sUri=(isPost||!lang.isValue(oRequest))?sLiveData:sLiveData+oRequest;var sRequest=(isPost)?oRequest:null;if(this.connXhrMode!="queueRequests"){oQueue.conn=oConnMgr.asyncRequest(sMethod,sUri,_xhrCallback,sRequest)}else{if(oQueue.conn){var allRequests=oQueue.requests;allRequests.push({request:oRequest,callback:_xhrCallback});if(!oQueue.interval){oQueue.interval=setInterval(function(){if(oConnMgr.isCallInProgress(oQueue.conn)){return}else{if(allRequests.length>0){sUri=(isPost||!lang.isValue(allRequests[0].request))?sLiveData:sLiveData+allRequests[0].request;sRequest=(isPost)?allRequests[0].request:null;oQueue.conn=oConnMgr.asyncRequest(sMethod,sUri,allRequests[0].callback,sRequest);allRequests.shift()}else{clearInterval(oQueue.interval);oQueue.interval=null}}},50)}}else{oQueue.conn=oConnMgr.asyncRequest(sMethod,sUri,_xhrCallback,sRequest)}}}else{DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller)}return tId}});lang.augmentObject(util.XHRDataSource,DS);util.DataSource=function(oLiveData,oConfigs){oConfigs=oConfigs||{};var dataType=oConfigs.dataType;if(dataType){if(dataType==DS.TYPE_LOCAL){return new util.LocalDataSource(oLiveData,oConfigs)}else{if(dataType==DS.TYPE_XHR){return new util.XHRDataSource(oLiveData,oConfigs)}else{if(dataType==DS.TYPE_SCRIPTNODE){return new util.ScriptNodeDataSource(oLiveData,oConfigs)}else{if(dataType==DS.TYPE_JSFUNCTION){return new util.FunctionDataSource(oLiveData,oConfigs)}}}}}if(YAHOO.lang.isString(oLiveData)){return new util.XHRDataSource(oLiveData,oConfigs)}else{if(YAHOO.lang.isFunction(oLiveData)){return new util.FunctionDataSource(oLiveData,oConfigs)}else{return new util.LocalDataSource(oLiveData,oConfigs)}}};lang.augmentObject(util.DataSource,DS)})();YAHOO.util.Number={format:function(e,k){if(e===""||e===null||!isFinite(e)){return""}e=+e;k=YAHOO.lang.merge(YAHOO.util.Number.format.defaults,(k||{}));var j=e+"",l=Math.abs(e),b=k.decimalPlaces||0,r=k.thousandsSeparator,f=k.negativeFormat||("-"+k.format),q,p,g,h;if(f.indexOf("#")>-1){f=f.replace(/#/,k.format)}if(b<0){q=l-(l%1)+"";g=q.length+b;if(g>0){q=Number("."+q).toFixed(g).slice(2)+new Array(q.length-g+1).join("0")}else{q="0"}}else{var a=l+"";if(b>0||a.indexOf(".")>0){var d=Math.pow(10,b);q=Math.round(l*d)/d+"";var c=q.indexOf("."),m,o;if(c<0){m=b;o=(Math.pow(10,m)+"").substring(1);if(b>0){q=q+"."+o}}else{m=b-(q.length-c-1);o=(Math.pow(10,m)+"").substring(1);q=q+o}}else{q=l.toFixed(b)+""}}p=q.split(/\D/);if(l>=1000){g=p[0].length%3||3;p[0]=p[0].slice(0,g)+p[0].slice(g).replace(/(\d{3})/g,r+"$1")}return YAHOO.util.Number.format._applyFormat((e<0?f:k.format),p.join(k.decimalSeparator),k)}};YAHOO.util.Number.format.defaults={format:"{prefix}{number}{suffix}",negativeFormat:null,decimalSeparator:".",decimalPlaces:null,thousandsSeparator:""};YAHOO.util.Number.format._applyFormat=function(a,b,c){return a.replace(/\{(\w+)\}/g,function(d,e){return e==="number"?b:e in c?c[e]:""})};(function(){var a=function(c,e,d){if(typeof d==="undefined"){d=10}for(;parseInt(c,10)<d&&d>1;d/=10){c=e.toString()+c}return c.toString()};var b={formats:{a:function(e,c){return c.a[e.getDay()]},A:function(e,c){return c.A[e.getDay()]},b:function(e,c){return c.b[e.getMonth()]},B:function(e,c){return c.B[e.getMonth()]},C:function(c){return a(parseInt(c.getFullYear()/100,10),0)},d:["getDate","0"],e:["getDate"," "],g:function(c){return a(parseInt(b.formats.G(c)%100,10),0)},G:function(f){var g=f.getFullYear();var e=parseInt(b.formats.V(f),10);var c=parseInt(b.formats.W(f),10);if(c>e){g++}else{if(c===0&&e>=52){g--}}return g},H:["getHours","0"],I:function(e){var c=e.getHours()%12;return a(c===0?12:c,0)},j:function(h){var g=new Date(""+h.getFullYear()+"/1/1 GMT");var e=new Date(""+h.getFullYear()+"/"+(h.getMonth()+1)+"/"+h.getDate()+" GMT");var c=e-g;var f=parseInt(c/60000/60/24,10)+1;return a(f,0,100)},k:["getHours"," "],l:function(e){var c=e.getHours()%12;return a(c===0?12:c," ")},m:function(c){return a(c.getMonth()+1,0)},M:["getMinutes","0"],p:function(e,c){return c.p[e.getHours()>=12?1:0]},P:function(e,c){return c.P[e.getHours()>=12?1:0]},s:function(e,c){return parseInt(e.getTime()/1000,10)},S:["getSeconds","0"],u:function(c){var e=c.getDay();return e===0?7:e},U:function(g){var c=parseInt(b.formats.j(g),10);var f=6-g.getDay();var e=parseInt((c+f)/7,10);return a(e,0)},V:function(g){var f=parseInt(b.formats.W(g),10);var c=(new Date(""+g.getFullYear()+"/1/1")).getDay();var e=f+(c>4||c<=1?0:1);if(e===53&&(new Date(""+g.getFullYear()+"/12/31")).getDay()<4){e=1}else{if(e===0){e=b.formats.V(new Date(""+(g.getFullYear()-1)+"/12/31"))}}return a(e,0)},w:"getDay",W:function(g){var c=parseInt(b.formats.j(g),10);var f=7-b.formats.u(g);var e=parseInt((c+f)/7,10);return a(e,0,10)},y:function(c){return a(c.getFullYear()%100,0)},Y:"getFullYear",z:function(f){var e=f.getTimezoneOffset();var c=a(parseInt(Math.abs(e/60),10),0);var g=a(Math.abs(e%60),0);return(e>0?"-":"+")+c+g},Z:function(c){var e=c.toString().replace(/^.*:\d\d( GMT[+-]\d+)? \(?([A-Za-z ]+)\)?\d*$/,"$2").replace(/[a-z ]/g,"");if(e.length>4){e=b.formats.z(c)}return e},"%":function(c){return"%"}},aggregates:{c:"locale",D:"%m/%d/%y",F:"%Y-%m-%d",h:"%b",n:"\n",r:"locale",R:"%H:%M",t:"\t",T:"%H:%M:%S",x:"locale",X:"locale"},format:function(g,f,d){f=f||{};if(!(g instanceof Date)){return YAHOO.lang.isValue(g)?g:""}var h=f.format||"%m/%d/%Y";if(h==="YYYY/MM/DD"){h="%Y/%m/%d"}else{if(h==="DD/MM/YYYY"){h="%d/%m/%Y"}else{if(h==="MM/DD/YYYY"){h="%m/%d/%Y"}}}d=d||"en";if(!(d in YAHOO.util.DateLocale)){if(d.replace(/-[a-zA-Z]+$/,"") in YAHOO.util.DateLocale){d=d.replace(/-[a-zA-Z]+$/,"")}else{d="en"}}var j=YAHOO.util.DateLocale[d];var c=function(l,k){var m=b.aggregates[k];return(m==="locale"?j[k]:m)};var e=function(l,k){var m=b.formats[k];if(typeof m==="string"){return g[m]()}else{if(typeof m==="function"){return m.call(g,g,j)}else{if(typeof m==="object"&&typeof m[0]==="string"){return a(g[m[0]](),m[1])}else{return k}}}};while(h.match(/%[cDFhnrRtTxX]/)){h=h.replace(/%([cDFhnrRtTxX])/g,c)}var i=h.replace(/%([aAbBCdegGHIjklmMpPsSuUVwWyYzZ%])/g,e);c=e=undefined;return i}};YAHOO.namespace("YAHOO.util");YAHOO.util.Date=b;YAHOO.util.DateLocale={a:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],A:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],b:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],B:["January","February","March","April","May","June","July","August","September","October","November","December"],c:"%a %d %b %Y %T %Z",p:["AM","PM"],P:["am","pm"],r:"%I:%M:%S %p",x:"%d/%m/%y",X:"%T"};YAHOO.util.DateLocale.en=YAHOO.lang.merge(YAHOO.util.DateLocale,{});YAHOO.util.DateLocale["en-US"]=YAHOO.lang.merge(YAHOO.util.DateLocale.en,{c:"%a %d %b %Y %I:%M:%S %p %Z",x:"%m/%d/%Y",X:"%I:%M:%S %p"});YAHOO.util.DateLocale["en-GB"]=YAHOO.lang.merge(YAHOO.util.DateLocale.en,{r:"%l:%M:%S %P %Z"});YAHOO.util.DateLocale["en-AU"]=YAHOO.lang.merge(YAHOO.util.DateLocale.en)})();YAHOO.register("datasource",YAHOO.util.DataSource,{version:"2.9.0",build:"2800"});YAHOO.widget.DS_JSArray=YAHOO.util.LocalDataSource;YAHOO.widget.DS_JSFunction=YAHOO.util.FunctionDataSource;YAHOO.widget.DS_XHR=function(b,a,d){var c=new YAHOO.util.XHRDataSource(b,d);c._aDeprecatedSchema=a;return c};YAHOO.widget.DS_ScriptNode=function(b,a,d){var c=new YAHOO.util.ScriptNodeDataSource(b,d);c._aDeprecatedSchema=a;return c};YAHOO.widget.DS_XHR.TYPE_JSON=YAHOO.util.DataSourceBase.TYPE_JSON;YAHOO.widget.DS_XHR.TYPE_XML=YAHOO.util.DataSourceBase.TYPE_XML;YAHOO.widget.DS_XHR.TYPE_FLAT=YAHOO.util.DataSourceBase.TYPE_TEXT;YAHOO.widget.AutoComplete=function(g,b,j,c){if(g&&b&&j){if(j&&YAHOO.lang.isFunction(j.sendRequest)){this.dataSource=j}else{return}this.key=0;var d=j.responseSchema;if(j._aDeprecatedSchema){var k=j._aDeprecatedSchema;if(YAHOO.lang.isArray(k)){if((j.responseType===YAHOO.util.DataSourceBase.TYPE_JSON)||(j.responseType===YAHOO.util.DataSourceBase.TYPE_UNKNOWN)){d.resultsList=k[0];this.key=k[1];d.fields=(k.length<3)?null:k.slice(1)}else{if(j.responseType===YAHOO.util.DataSourceBase.TYPE_XML){d.resultNode=k[0];this.key=k[1];d.fields=k.slice(1)}else{if(j.responseType===YAHOO.util.DataSourceBase.TYPE_TEXT){d.recordDelim=k[0];d.fieldDelim=k[1]}}}j.responseSchema=d}}if(YAHOO.util.Dom.inDocument(g)){if(YAHOO.lang.isString(g)){this._sName="instance"+YAHOO.widget.AutoComplete._nIndex+" "+g;this._elTextbox=document.getElementById(g)}else{this._sName=(g.id)?"instance"+YAHOO.widget.AutoComplete._nIndex+" "+g.id:"instance"+YAHOO.widget.AutoComplete._nIndex;this._elTextbox=g}YAHOO.util.Dom.addClass(this._elTextbox,"yui-ac-input")}else{return}if(YAHOO.util.Dom.inDocument(b)){if(YAHOO.lang.isString(b)){this._elContainer=document.getElementById(b)}else{this._elContainer=b}if(this._elContainer.style.display=="none"){}var e=this._elContainer.parentNode;var a=e.tagName.toLowerCase();if(a=="div"){YAHOO.util.Dom.addClass(e,"yui-ac")}else{}}else{return}if(this.dataSource.dataType===YAHOO.util.DataSourceBase.TYPE_LOCAL){this.applyLocalFilter=true}if(c&&(c.constructor==Object)){for(var i in c){if(i){this[i]=c[i]}}}this._initContainerEl();this._initProps();this._initListEl();this._initContainerHelperEls();var h=this;var f=this._elTextbox;YAHOO.util.Event.addListener(f,"keyup",h._onTextboxKeyUp,h);YAHOO.util.Event.addListener(f,"keydown",h._onTextboxKeyDown,h);YAHOO.util.Event.addListener(f,"focus",h._onTextboxFocus,h);YAHOO.util.Event.addListener(f,"blur",h._onTextboxBlur,h);YAHOO.util.Event.addListener(b,"mouseover",h._onContainerMouseover,h);YAHOO.util.Event.addListener(b,"mouseout",h._onContainerMouseout,h);YAHOO.util.Event.addListener(b,"click",h._onContainerClick,h);YAHOO.util.Event.addListener(b,"scroll",h._onContainerScroll,h);YAHOO.util.Event.addListener(b,"resize",h._onContainerResize,h);YAHOO.util.Event.addListener(f,"keypress",h._onTextboxKeyPress,h);YAHOO.util.Event.addListener(window,"unload",h._onWindowUnload,h);this.textboxFocusEvent=new YAHOO.util.CustomEvent("textboxFocus",this);this.textboxKeyEvent=new YAHOO.util.CustomEvent("textboxKey",this);this.dataRequestEvent=new YAHOO.util.CustomEvent("dataRequest",this);this.dataRequestCancelEvent=new YAHOO.util.CustomEvent("dataRequestCancel",this);this.dataReturnEvent=new YAHOO.util.CustomEvent("dataReturn",this);this.dataErrorEvent=new YAHOO.util.CustomEvent("dataError",this);this.containerPopulateEvent=new YAHOO.util.CustomEvent("containerPopulate",this);this.containerExpandEvent=new YAHOO.util.CustomEvent("containerExpand",this);this.typeAheadEvent=new YAHOO.util.CustomEvent("typeAhead",this);this.itemMouseOverEvent=new YAHOO.util.CustomEvent("itemMouseOver",this);this.itemMouseOutEvent=new YAHOO.util.CustomEvent("itemMouseOut",this);this.itemArrowToEvent=new YAHOO.util.CustomEvent("itemArrowTo",this);this.itemArrowFromEvent=new YAHOO.util.CustomEvent("itemArrowFrom",this);this.itemSelectEvent=new YAHOO.util.CustomEvent("itemSelect",this);this.unmatchedItemSelectEvent=new YAHOO.util.CustomEvent("unmatchedItemSelect",this);this.selectionEnforceEvent=new YAHOO.util.CustomEvent("selectionEnforce",this);this.containerCollapseEvent=new YAHOO.util.CustomEvent("containerCollapse",this);this.textboxBlurEvent=new YAHOO.util.CustomEvent("textboxBlur",this);this.textboxChangeEvent=new YAHOO.util.CustomEvent("textboxChange",this);f.setAttribute("autocomplete","off");YAHOO.widget.AutoComplete._nIndex++}else{}};YAHOO.widget.AutoComplete.prototype.dataSource=null;YAHOO.widget.AutoComplete.prototype.applyLocalFilter=null;YAHOO.widget.AutoComplete.prototype.queryMatchCase=false;YAHOO.widget.AutoComplete.prototype.queryMatchContains=false;YAHOO.widget.AutoComplete.prototype.queryMatchSubset=false;YAHOO.widget.AutoComplete.prototype.minQueryLength=1;YAHOO.widget.AutoComplete.prototype.maxResultsDisplayed=10;YAHOO.widget.AutoComplete.prototype.queryDelay=0.2;YAHOO.widget.AutoComplete.prototype.typeAheadDelay=0.5;YAHOO.widget.AutoComplete.prototype.queryInterval=500;YAHOO.widget.AutoComplete.prototype.highlightClassName="yui-ac-highlight";YAHOO.widget.AutoComplete.prototype.prehighlightClassName=null;YAHOO.widget.AutoComplete.prototype.delimChar=null;YAHOO.widget.AutoComplete.prototype.autoHighlight=true;YAHOO.widget.AutoComplete.prototype.typeAhead=false;YAHOO.widget.AutoComplete.prototype.animHoriz=false;YAHOO.widget.AutoComplete.prototype.animVert=true;YAHOO.widget.AutoComplete.prototype.animSpeed=0.3;YAHOO.widget.AutoComplete.prototype.forceSelection=false;YAHOO.widget.AutoComplete.prototype.allowBrowserAutocomplete=true;YAHOO.widget.AutoComplete.prototype.alwaysShowContainer=false;YAHOO.widget.AutoComplete.prototype.useIFrame=false;YAHOO.widget.AutoComplete.prototype.useShadow=false;YAHOO.widget.AutoComplete.prototype.suppressInputUpdate=false;YAHOO.widget.AutoComplete.prototype.resultTypeList=true;YAHOO.widget.AutoComplete.prototype.queryQuestionMark=true;YAHOO.widget.AutoComplete.prototype.autoSnapContainer=true;YAHOO.widget.AutoComplete.prototype.toString=function(){return"AutoComplete "+this._sName};YAHOO.widget.AutoComplete.prototype.getInputEl=function(){return this._elTextbox};YAHOO.widget.AutoComplete.prototype.getContainerEl=function(){return this._elContainer};YAHOO.widget.AutoComplete.prototype.isFocused=function(){return this._bFocused};YAHOO.widget.AutoComplete.prototype.isContainerOpen=function(){return this._bContainerOpen};YAHOO.widget.AutoComplete.prototype.getListEl=function(){return this._elList};YAHOO.widget.AutoComplete.prototype.getListItemMatch=function(a){if(a._sResultMatch){return a._sResultMatch}else{return null}};YAHOO.widget.AutoComplete.prototype.getListItemData=function(a){if(a._oResultData){return a._oResultData}else{return null}};YAHOO.widget.AutoComplete.prototype.getListItemIndex=function(a){if(YAHOO.lang.isNumber(a._nItemIndex)){return a._nItemIndex}else{return null}};YAHOO.widget.AutoComplete.prototype.setHeader=function(b){if(this._elHeader){var a=this._elHeader;if(b){a.innerHTML=b;a.style.display=""}else{a.innerHTML="";a.style.display="none"}}};YAHOO.widget.AutoComplete.prototype.setFooter=function(b){if(this._elFooter){var a=this._elFooter;if(b){a.innerHTML=b;a.style.display=""}else{a.innerHTML="";a.style.display="none"}}};YAHOO.widget.AutoComplete.prototype.setBody=function(a){if(this._elBody){var b=this._elBody;YAHOO.util.Event.purgeElement(b,true);if(a){b.innerHTML=a;b.style.display=""}else{b.innerHTML="";b.style.display="none"}this._elList=null}};YAHOO.widget.AutoComplete.prototype.generateRequest=function(b){var a=this.dataSource.dataType;if(a===YAHOO.util.DataSourceBase.TYPE_XHR){if(!this.dataSource.connMethodPost){b=(this.queryQuestionMark?"?":"")+(this.dataSource.scriptQueryParam||"query")+"="+b+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"")}else{b=(this.dataSource.scriptQueryParam||"query")+"="+b+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"")}}else{if(a===YAHOO.util.DataSourceBase.TYPE_SCRIPTNODE){b="&"+(this.dataSource.scriptQueryParam||"query")+"="+b+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"")}}return b};YAHOO.widget.AutoComplete.prototype.sendQuery=function(b){this._bFocused=true;var a=(this.delimChar)?this._elTextbox.value+b:b;this._sendQuery(a)};YAHOO.widget.AutoComplete.prototype.snapContainer=function(){var a=this._elTextbox,b=YAHOO.util.Dom.getXY(a);b[1]+=YAHOO.util.Dom.get(a).offsetHeight+2;YAHOO.util.Dom.setXY(this._elContainer,b)};YAHOO.widget.AutoComplete.prototype.expandContainer=function(){this._toggleContainer(true)};YAHOO.widget.AutoComplete.prototype.collapseContainer=function(){this._toggleContainer(false)};YAHOO.widget.AutoComplete.prototype.clearList=function(){var b=this._elList.childNodes,a=b.length-1;for(;a>-1;a--){b[a].style.display="none"}};YAHOO.widget.AutoComplete.prototype.getSubsetMatches=function(e){var d,c,a;for(var b=e.length;b>=this.minQueryLength;b--){a=this.generateRequest(e.substr(0,b));this.dataRequestEvent.fire(this,d,a);c=this.dataSource.getCachedResponse(a);if(c){return this.filterResults.apply(this.dataSource,[e,c,c,{scope:this}])}}return null};YAHOO.widget.AutoComplete.prototype.preparseRawResponse=function(c,b,a){var d=((this.responseStripAfter!=="")&&(b.indexOf))?b.indexOf(this.responseStripAfter):-1;if(d!=-1){b=b.substring(0,d)}return b};YAHOO.widget.AutoComplete.prototype.filterResults=function(l,n,r,m){if(m&&m.argument&&YAHOO.lang.isValue(m.argument.query)){l=m.argument.query}if(l&&l!==""){r=YAHOO.widget.AutoComplete._cloneObject(r);var j=m.scope,q=this,c=r.results,o=[],b=j.maxResultsDisplayed,k=(q.queryMatchCase||j.queryMatchCase),a=(q.queryMatchContains||j.queryMatchContains);for(var d=0,h=c.length;d<h;d++){var f=c[d];var e=null;if(YAHOO.lang.isString(f)){e=f}else{if(YAHOO.lang.isArray(f)){e=f[0]}else{if(this.responseSchema.fields){var p=this.responseSchema.fields[0].key||this.responseSchema.fields[0];e=f[p]}else{if(this.key){e=f[this.key]}}}}if(YAHOO.lang.isString(e)){var g=(k)?e.indexOf(decodeURIComponent(l)):e.toLowerCase().indexOf(decodeURIComponent(l).toLowerCase());if((!a&&(g===0))||(a&&(g>-1))){o.push(f)}}if(h>b&&o.length===b){break}}r.results=o}else{}return r};YAHOO.widget.AutoComplete.prototype.handleResponse=function(c,a,b){if((this instanceof YAHOO.widget.AutoComplete)&&this._sName){this._populateList(c,a,b)}};YAHOO.widget.AutoComplete.prototype.doBeforeLoadData=function(c,a,b){return true};YAHOO.widget.AutoComplete.prototype.formatResult=function(b,d,a){var c=(a)?a:"";return c};YAHOO.widget.AutoComplete.prototype.formatEscapedResult=function(c,d,b){var a=(b)?b:"";return YAHOO.lang.escapeHTML(a)};YAHOO.widget.AutoComplete.prototype.doBeforeExpandContainer=function(d,a,c,b){return true};YAHOO.widget.AutoComplete.prototype.destroy=function(){var b=this.toString();var a=this._elTextbox;var d=this._elContainer;this.textboxFocusEvent.unsubscribeAll();this.textboxKeyEvent.unsubscribeAll();this.dataRequestEvent.unsubscribeAll();this.dataReturnEvent.unsubscribeAll();this.dataErrorEvent.unsubscribeAll();this.containerPopulateEvent.unsubscribeAll();this.containerExpandEvent.unsubscribeAll();this.typeAheadEvent.unsubscribeAll();this.itemMouseOverEvent.unsubscribeAll();this.itemMouseOutEvent.unsubscribeAll();this.itemArrowToEvent.unsubscribeAll();this.itemArrowFromEvent.unsubscribeAll();this.itemSelectEvent.unsubscribeAll();this.unmatchedItemSelectEvent.unsubscribeAll();this.selectionEnforceEvent.unsubscribeAll();this.containerCollapseEvent.unsubscribeAll();this.textboxBlurEvent.unsubscribeAll();this.textboxChangeEvent.unsubscribeAll();YAHOO.util.Event.purgeElement(a,true);YAHOO.util.Event.purgeElement(d,true);d.innerHTML="";for(var c in this){if(YAHOO.lang.hasOwnProperty(this,c)){this[c]=null}}};YAHOO.widget.AutoComplete.prototype.textboxFocusEvent=null;YAHOO.widget.AutoComplete.prototype.textboxKeyEvent=null;YAHOO.widget.AutoComplete.prototype.dataRequestEvent=null;YAHOO.widget.AutoComplete.prototype.dataRequestCancelEvent=null;YAHOO.widget.AutoComplete.prototype.dataReturnEvent=null;YAHOO.widget.AutoComplete.prototype.dataErrorEvent=null;YAHOO.widget.AutoComplete.prototype.containerPopulateEvent=null;YAHOO.widget.AutoComplete.prototype.containerExpandEvent=null;YAHOO.widget.AutoComplete.prototype.typeAheadEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOverEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOutEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowToEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowFromEvent=null;YAHOO.widget.AutoComplete.prototype.itemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.unmatchedItemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.selectionEnforceEvent=null;YAHOO.widget.AutoComplete.prototype.containerCollapseEvent=null;YAHOO.widget.AutoComplete.prototype.textboxBlurEvent=null;YAHOO.widget.AutoComplete.prototype.textboxChangeEvent=null;YAHOO.widget.AutoComplete._nIndex=0;YAHOO.widget.AutoComplete.prototype._sName=null;YAHOO.widget.AutoComplete.prototype._elTextbox=null;YAHOO.widget.AutoComplete.prototype._elContainer=null;YAHOO.widget.AutoComplete.prototype._elContent=null;YAHOO.widget.AutoComplete.prototype._elHeader=null;YAHOO.widget.AutoComplete.prototype._elBody=null;YAHOO.widget.AutoComplete.prototype._elFooter=null;YAHOO.widget.AutoComplete.prototype._elShadow=null;YAHOO.widget.AutoComplete.prototype._elIFrame=null;YAHOO.widget.AutoComplete.prototype._bFocused=false;YAHOO.widget.AutoComplete.prototype._oAnim=null;YAHOO.widget.AutoComplete.prototype._bContainerOpen=false;YAHOO.widget.AutoComplete.prototype._bOverContainer=false;YAHOO.widget.AutoComplete.prototype._elList=null;YAHOO.widget.AutoComplete.prototype._nDisplayedItems=0;YAHOO.widget.AutoComplete.prototype._sCurQuery=null;YAHOO.widget.AutoComplete.prototype._sPastSelections="";YAHOO.widget.AutoComplete.prototype._sInitInputValue=null;YAHOO.widget.AutoComplete.prototype._elCurListItem=null;YAHOO.widget.AutoComplete.prototype._elCurPrehighlightItem=null;YAHOO.widget.AutoComplete.prototype._bItemSelected=false;YAHOO.widget.AutoComplete.prototype._nKeyCode=null;YAHOO.widget.AutoComplete.prototype._nDelayID=-1;YAHOO.widget.AutoComplete.prototype._nTypeAheadDelayID=-1;YAHOO.widget.AutoComplete.prototype._iFrameSrc="javascript:false;";YAHOO.widget.AutoComplete.prototype._queryInterval=null;YAHOO.widget.AutoComplete.prototype._sLastTextboxValue=null;YAHOO.widget.AutoComplete.prototype._initProps=function(){var b=this.minQueryLength;if(!YAHOO.lang.isNumber(b)){this.minQueryLength=1}var e=this.maxResultsDisplayed;if(!YAHOO.lang.isNumber(e)||(e<1)){this.maxResultsDisplayed=10}var f=this.queryDelay;if(!YAHOO.lang.isNumber(f)||(f<0)){this.queryDelay=0.2}var c=this.typeAheadDelay;if(!YAHOO.lang.isNumber(c)||(c<0)){this.typeAheadDelay=0.2}var a=this.delimChar;if(YAHOO.lang.isString(a)&&(a.length>0)){this.delimChar=[a]}else{if(!YAHOO.lang.isArray(a)){this.delimChar=null}}var d=this.animSpeed;if((this.animHoriz||this.animVert)&&YAHOO.util.Anim){if(!YAHOO.lang.isNumber(d)||(d<0)){this.animSpeed=0.3}if(!this._oAnim){this._oAnim=new YAHOO.util.Anim(this._elContent,{},this.animSpeed)}else{this._oAnim.duration=this.animSpeed}}if(this.forceSelection&&a){}};YAHOO.widget.AutoComplete.prototype._initContainerHelperEls=function(){if(this.useShadow&&!this._elShadow){var a=document.createElement("div");a.className="yui-ac-shadow";a.style.width=0;a.style.height=0;this._elShadow=this._elContainer.appendChild(a)}if(this.useIFrame&&!this._elIFrame){var b=document.createElement("iframe");b.src=this._iFrameSrc;b.frameBorder=0;b.scrolling="no";b.style.position="absolute";b.style.width=0;b.style.height=0;b.style.padding=0;b.tabIndex=-1;b.role="presentation";b.title="Presentational iframe shim";this._elIFrame=this._elContainer.appendChild(b)}};YAHOO.widget.AutoComplete.prototype._initContainerEl=function(){YAHOO.util.Dom.addClass(this._elContainer,"yui-ac-container");if(!this._elContent){var c=document.createElement("div");c.className="yui-ac-content";c.style.display="none";this._elContent=this._elContainer.appendChild(c);var b=document.createElement("div");b.className="yui-ac-hd";b.style.display="none";this._elHeader=this._elContent.appendChild(b);var d=document.createElement("div");d.className="yui-ac-bd";this._elBody=this._elContent.appendChild(d);var a=document.createElement("div");a.className="yui-ac-ft";a.style.display="none";this._elFooter=this._elContent.appendChild(a)}else{}};YAHOO.widget.AutoComplete.prototype._initListEl=function(){var c=this.maxResultsDisplayed,a=this._elList||document.createElement("ul"),b;while(a.childNodes.length<c){b=document.createElement("li");b.style.display="none";b._nItemIndex=a.childNodes.length;a.appendChild(b)}if(!this._elList){var d=this._elBody;YAHOO.util.Event.purgeElement(d,true);d.innerHTML="";this._elList=d.appendChild(a)}this._elBody.style.display=""};YAHOO.widget.AutoComplete.prototype._focus=function(){var a=this;setTimeout(function(){try{a._elTextbox.focus()}catch(b){}},0)};YAHOO.widget.AutoComplete.prototype._enableIntervalDetection=function(){var a=this;if(!a._queryInterval&&a.queryInterval){a._queryInterval=setInterval(function(){a._onInterval()},a.queryInterval)}};YAHOO.widget.AutoComplete.prototype.enableIntervalDetection=YAHOO.widget.AutoComplete.prototype._enableIntervalDetection;YAHOO.widget.AutoComplete.prototype._onInterval=function(){var a=this._elTextbox.value;var b=this._sLastTextboxValue;if(a!=b){this._sLastTextboxValue=a;this._sendQuery(a)}};YAHOO.widget.AutoComplete.prototype._clearInterval=function(){if(this._queryInterval){clearInterval(this._queryInterval);this._queryInterval=null}};YAHOO.widget.AutoComplete.prototype._isIgnoreKey=function(a){if((a==9)||(a==13)||(a==16)||(a==17)||(a>=18&&a<=20)||(a==27)||(a>=33&&a<=35)||(a>=36&&a<=40)||(a>=44&&a<=45)||(a==229)){return true}return false};YAHOO.widget.AutoComplete.prototype._sendQuery=function(d){if(this.minQueryLength<0){this._toggleContainer(false);return}if(this.delimChar){var a=this._extractQuery(d);d=a.query;this._sPastSelections=a.previous}if((d&&(d.length<this.minQueryLength))||(!d&&this.minQueryLength>0)){if(this._nDelayID!=-1){clearTimeout(this._nDelayID)}this._toggleContainer(false);return}d=encodeURIComponent(d);this._nDelayID=-1;if(this.dataSource.queryMatchSubset||this.queryMatchSubset){var c=this.getSubsetMatches(d);if(c){this.handleResponse(d,c,{query:d});return}}if(this.dataSource.responseStripAfter){this.dataSource.doBeforeParseData=this.preparseRawResponse}if(this.applyLocalFilter){this.dataSource.doBeforeCallback=this.filterResults}var b=this.generateRequest(d);if(b!==undefined){this.dataRequestEvent.fire(this,d,b);this.dataSource.sendRequest(b,{success:this.handleResponse,failure:this.handleResponse,scope:this,argument:{query:d}})}else{this.dataRequestCancelEvent.fire(this,d)}};YAHOO.widget.AutoComplete.prototype._populateListItem=function(b,a,c){b.innerHTML=this.formatResult(a,c,b._sResultMatch)};YAHOO.widget.AutoComplete.prototype._populateList=function(n,f,c){if(this._nTypeAheadDelayID!=-1){clearTimeout(this._nTypeAheadDelayID)}n=(c&&c.query)?c.query:n;var h=this.doBeforeLoadData(n,f,c);if(h&&!f.error){this.dataReturnEvent.fire(this,n,f.results);if(this._bFocused){var p=decodeURIComponent(n);this._sCurQuery=p;this._bItemSelected=false;var u=f.results,a=Math.min(u.length,this.maxResultsDisplayed),m=(this.dataSource.responseSchema.fields)?(this.dataSource.responseSchema.fields[0].key||this.dataSource.responseSchema.fields[0]):0;if(a>0){if(!this._elList||(this._elList.childNodes.length<a)){this._initListEl()}this._initContainerHelperEls();var l=this._elList.childNodes;for(var t=a-1;t>=0;t--){var s=l[t],e=u[t];if(this.resultTypeList){var b=[];b[0]=(YAHOO.lang.isString(e))?e:e[m]||e[this.key];var o=this.dataSource.responseSchema.fields;if(YAHOO.lang.isArray(o)&&(o.length>1)){for(var q=1,v=o.length;q<v;q++){b[b.length]=e[o[q].key||o[q]]}}else{if(YAHOO.lang.isArray(e)){b=e}else{if(YAHOO.lang.isString(e)){b=[e]}else{b[1]=e}}}e=b}s._sResultMatch=(YAHOO.lang.isString(e))?e:(YAHOO.lang.isArray(e))?e[0]:(e[m]||"");s._oResultData=e;this._populateListItem(s,e,p);s.style.display=""}if(a<l.length){var g;for(var r=l.length-1;r>=a;r--){g=l[r];g.style.display="none"}}this._nDisplayedItems=a;this.containerPopulateEvent.fire(this,n,u);if(this.autoHighlight){var d=this._elList.firstChild;this._toggleHighlight(d,"to");this.itemArrowToEvent.fire(this,d);this._typeAhead(d,n)}else{this._toggleHighlight(this._elCurListItem,"from")}h=this._doBeforeExpandContainer(this._elTextbox,this._elContainer,n,u);this._toggleContainer(h)}else{this._toggleContainer(false)}return}}else{this.dataErrorEvent.fire(this,n,f)}};YAHOO.widget.AutoComplete.prototype._doBeforeExpandContainer=function(d,a,c,b){if(this.autoSnapContainer){this.snapContainer()}return this.doBeforeExpandContainer(d,a,c,b)};YAHOO.widget.AutoComplete.prototype._clearSelection=function(){var a=(this.delimChar)?this._extractQuery(this._elTextbox.value):{previous:"",query:this._elTextbox.value};this._elTextbox.value=a.previous;this.selectionEnforceEvent.fire(this,a.query)};YAHOO.widget.AutoComplete.prototype._textMatchesOption=function(){var a=null;for(var b=0;b<this._nDisplayedItems;b++){var c=this._elList.childNodes[b];var d=(""+c._sResultMatch).toLowerCase();if(d==this._sCurQuery.toLowerCase()){a=c;break}}return(a)};YAHOO.widget.AutoComplete.prototype._typeAhead=function(b,d){if(!this.typeAhead||(this._nKeyCode==8)){return}var a=this,c=this._elTextbox;if(c.setSelectionRange||c.createTextRange){this._nTypeAheadDelayID=setTimeout(function(){var f=c.value.length;a._updateValue(b);var g=c.value.length;a._selectText(c,f,g);var e=c.value.substr(f,g);a._sCurQuery=b._sResultMatch;a.typeAheadEvent.fire(a,d,e)},(this.typeAheadDelay*1000))}};YAHOO.widget.AutoComplete.prototype._selectText=function(d,a,b){if(d.setSelectionRange){d.setSelectionRange(a,b)}else{if(d.createTextRange){var c=d.createTextRange();c.moveStart("character",a);c.moveEnd("character",b-d.value.length);c.select()}else{d.select()}}};YAHOO.widget.AutoComplete.prototype._extractQuery=function(h){var c=this.delimChar,f=-1,g,e,b=c.length-1,d;for(;b>=0;b--){g=h.lastIndexOf(c[b]);if(g>f){f=g}}if(c[b]==" "){for(var a=c.length-1;a>=0;a--){if(h[f-1]==c[a]){f--;break}}}if(f>-1){e=f+1;while(h.charAt(e)==" "){e+=1}d=h.substring(0,e);h=h.substr(e)}else{d=""}return{previous:d,query:h}};YAHOO.widget.AutoComplete.prototype._toggleContainerHelpers=function(d){var e=this._elContent.offsetWidth+"px";var b=this._elContent.offsetHeight+"px";if(this.useIFrame&&this._elIFrame){var c=this._elIFrame;if(d){c.style.width=e;c.style.height=b;c.style.padding=""}else{c.style.width=0;c.style.height=0;c.style.padding=0}}if(this.useShadow&&this._elShadow){var a=this._elShadow;if(d){a.style.width=e;a.style.height=b}else{a.style.width=0;a.style.height=0}}};YAHOO.widget.AutoComplete.prototype._toggleContainer=function(i){var d=this._elContainer;if(this.alwaysShowContainer&&this._bContainerOpen){return}if(!i){this._toggleHighlight(this._elCurListItem,"from");this._nDisplayedItems=0;this._sCurQuery=null;if(this._elContent.style.display=="none"){return}}var a=this._oAnim;if(a&&a.getEl()&&(this.animHoriz||this.animVert)){if(a.isAnimated()){a.stop(true)}var g=this._elContent.cloneNode(true);d.appendChild(g);g.style.top="-9000px";g.style.width="";g.style.height="";g.style.display="";var f=g.offsetWidth;var c=g.offsetHeight;var b=(this.animHoriz)?0:f;var e=(this.animVert)?0:c;a.attributes=(i)?{width:{to:f},height:{to:c}}:{width:{to:b},height:{to:e}};if(i&&!this._bContainerOpen){this._elContent.style.width=b+"px";this._elContent.style.height=e+"px"}else{this._elContent.style.width=f+"px";this._elContent.style.height=c+"px"}d.removeChild(g);g=null;var h=this;var j=function(){a.onComplete.unsubscribeAll();if(i){h._toggleContainerHelpers(true);h._bContainerOpen=i;h.containerExpandEvent.fire(h)}else{h._elContent.style.display="none";h._bContainerOpen=i;h.containerCollapseEvent.fire(h)}};this._toggleContainerHelpers(false);this._elContent.style.display="";a.onComplete.subscribe(j);a.animate()}else{if(i){this._elContent.style.display="";this._toggleContainerHelpers(true);this._bContainerOpen=i;this.containerExpandEvent.fire(this)}else{this._toggleContainerHelpers(false);this._elContent.style.display="none";this._bContainerOpen=i;this.containerCollapseEvent.fire(this)}}};YAHOO.widget.AutoComplete.prototype._toggleHighlight=function(a,c){if(a){var b=this.highlightClassName;if(this._elCurListItem){YAHOO.util.Dom.removeClass(this._elCurListItem,b);this._elCurListItem=null}if((c=="to")&&b){YAHOO.util.Dom.addClass(a,b);this._elCurListItem=a}}};YAHOO.widget.AutoComplete.prototype._togglePrehighlight=function(b,c){var a=this.prehighlightClassName;if(this._elCurPrehighlightItem){YAHOO.util.Dom.removeClass(this._elCurPrehighlightItem,a)}if(b==this._elCurListItem){return}if((c=="mouseover")&&a){YAHOO.util.Dom.addClass(b,a);this._elCurPrehighlightItem=b}else{YAHOO.util.Dom.removeClass(b,a)}};YAHOO.widget.AutoComplete.prototype._updateValue=function(c){if(!this.suppressInputUpdate){var f=this._elTextbox;var e=(this.delimChar)?(this.delimChar[0]||this.delimChar):null;var b=c._sResultMatch;var d="";if(e){d=this._sPastSelections;d+=b+e;if(e!=" "){d+=" "}}else{d=b}f.value=d;if(f.type=="textarea"){f.scrollTop=f.scrollHeight}var a=f.value.length;this._selectText(f,a,a);this._elCurListItem=c}};YAHOO.widget.AutoComplete.prototype._selectItem=function(a){this._bItemSelected=true;this._updateValue(a);this._sPastSelections=this._elTextbox.value;this._clearInterval();this.itemSelectEvent.fire(this,a,a._oResultData);this._toggleContainer(false)};YAHOO.widget.AutoComplete.prototype._jumpSelection=function(){if(this._elCurListItem){this._selectItem(this._elCurListItem)}else{this._toggleContainer(false)}};YAHOO.widget.AutoComplete.prototype._moveSelection=function(g){if(this._bContainerOpen){var h=this._elCurListItem,d=-1;if(h){d=h._nItemIndex}var e=(g==40)?(d+1):(d-1);if(e<-2||e>=this._nDisplayedItems){return}if(h){this._toggleHighlight(h,"from");this.itemArrowFromEvent.fire(this,h)}if(e==-1){if(this.delimChar){this._elTextbox.value=this._sPastSelections+this._sCurQuery}else{this._elTextbox.value=this._sCurQuery}return}if(e==-2){this._toggleContainer(false);return}var f=this._elList.childNodes[e],b=this._elContent,c=YAHOO.util.Dom.getStyle(b,"overflow"),i=YAHOO.util.Dom.getStyle(b,"overflowY"),a=((c=="auto")||(c=="scroll")||(i=="auto")||(i=="scroll"));if(a&&(e>-1)&&(e<this._nDisplayedItems)){if(g==40){if((f.offsetTop+f.offsetHeight)>(b.scrollTop+b.offsetHeight)){b.scrollTop=(f.offsetTop+f.offsetHeight)-b.offsetHeight}else{if((f.offsetTop+f.offsetHeight)<b.scrollTop){b.scrollTop=f.offsetTop}}}else{if(f.offsetTop<b.scrollTop){this._elContent.scrollTop=f.offsetTop}else{if(f.offsetTop>(b.scrollTop+b.offsetHeight)){this._elContent.scrollTop=(f.offsetTop+f.offsetHeight)-b.offsetHeight}}}}this._toggleHighlight(f,"to");this.itemArrowToEvent.fire(this,f);if(this.typeAhead){this._updateValue(f);this._sCurQuery=f._sResultMatch}}};YAHOO.widget.AutoComplete.prototype._onContainerMouseover=function(a,c){var d=YAHOO.util.Event.getTarget(a);var b=d.nodeName.toLowerCase();while(d&&(b!="table")){switch(b){case"body":return;case"li":if(c.prehighlightClassName){c._togglePrehighlight(d,"mouseover")}else{c._toggleHighlight(d,"to")}c.itemMouseOverEvent.fire(c,d);break;case"div":if(YAHOO.util.Dom.hasClass(d,"yui-ac-container")){c._bOverContainer=true;return}break;default:break}d=d.parentNode;if(d){b=d.nodeName.toLowerCase()}}};YAHOO.widget.AutoComplete.prototype._onContainerMouseout=function(a,c){var d=YAHOO.util.Event.getTarget(a);var b=d.nodeName.toLowerCase();while(d&&(b!="table")){switch(b){case"body":return;case"li":if(c.prehighlightClassName){c._togglePrehighlight(d,"mouseout")}else{c._toggleHighlight(d,"from")}c.itemMouseOutEvent.fire(c,d);break;case"ul":c._toggleHighlight(c._elCurListItem,"to");break;case"div":if(YAHOO.util.Dom.hasClass(d,"yui-ac-container")){c._bOverContainer=false;return}break;default:break}d=d.parentNode;if(d){b=d.nodeName.toLowerCase()}}};YAHOO.widget.AutoComplete.prototype._onContainerClick=function(a,c){var d=YAHOO.util.Event.getTarget(a);var b=d.nodeName.toLowerCase();while(d&&(b!="table")){switch(b){case"body":return;case"li":c._toggleHighlight(d,"to");c._selectItem(d);return;default:break}d=d.parentNode;if(d){b=d.nodeName.toLowerCase()}}};YAHOO.widget.AutoComplete.prototype._onContainerScroll=function(a,b){b._focus()};YAHOO.widget.AutoComplete.prototype._onContainerResize=function(a,b){b._toggleContainerHelpers(b._bContainerOpen)};YAHOO.widget.AutoComplete.prototype._onTextboxKeyDown=function(a,b){var c=a.keyCode;if(b._nTypeAheadDelayID!=-1){clearTimeout(b._nTypeAheadDelayID)}switch(c){case 9:if(!YAHOO.env.ua.opera&&(navigator.userAgent.toLowerCase().indexOf("mac")==-1)||(YAHOO.env.ua.webkit>420)){if(b._elCurListItem){if(b.delimChar&&(b._nKeyCode!=c)){if(b._bContainerOpen){YAHOO.util.Event.stopEvent(a)}}b._selectItem(b._elCurListItem)}else{b._toggleContainer(false)}}break;case 13:if(!YAHOO.env.ua.opera&&(navigator.userAgent.toLowerCase().indexOf("mac")==-1)||(YAHOO.env.ua.webkit>420)){if(b._elCurListItem){if(b._nKeyCode!=c){if(b._bContainerOpen){YAHOO.util.Event.stopEvent(a)}}b._selectItem(b._elCurListItem)}else{b._toggleContainer(false)}}break;case 27:b._toggleContainer(false);return;case 39:b._jumpSelection();break;case 38:if(b._bContainerOpen){YAHOO.util.Event.stopEvent(a);b._moveSelection(c)}break;case 40:if(b._bContainerOpen){YAHOO.util.Event.stopEvent(a);b._moveSelection(c)}break;default:b._bItemSelected=false;b._toggleHighlight(b._elCurListItem,"from");b.textboxKeyEvent.fire(b,c);break}if(c===18){b._enableIntervalDetection()}b._nKeyCode=c};YAHOO.widget.AutoComplete.prototype._onTextboxKeyPress=function(a,b){var c=a.keyCode;if(YAHOO.env.ua.opera||(navigator.userAgent.toLowerCase().indexOf("mac")!=-1)&&(YAHOO.env.ua.webkit<420)){switch(c){case 9:if(b._bContainerOpen){if(b.delimChar){YAHOO.util.Event.stopEvent(a)}if(b._elCurListItem){b._selectItem(b._elCurListItem)}else{b._toggleContainer(false)}}break;case 13:if(b._bContainerOpen){YAHOO.util.Event.stopEvent(a);if(b._elCurListItem){b._selectItem(b._elCurListItem)}else{b._toggleContainer(false)}}break;default:break}}else{if(c==229){b._enableIntervalDetection()}}};YAHOO.widget.AutoComplete.prototype._onTextboxKeyUp=function(a,c){var b=this.value;c._initProps();var d=a.keyCode;if(c._isIgnoreKey(d)){return}if(c._nDelayID!=-1){clearTimeout(c._nDelayID)}c._nDelayID=setTimeout(function(){c._sendQuery(b)},(c.queryDelay*1000))};YAHOO.widget.AutoComplete.prototype._onTextboxFocus=function(a,b){if(!b._bFocused){b._elTextbox.setAttribute("autocomplete","off");b._bFocused=true;b._sInitInputValue=b._elTextbox.value;b.textboxFocusEvent.fire(b)}};YAHOO.widget.AutoComplete.prototype._onTextboxBlur=function(a,c){if(!c._bOverContainer||(c._nKeyCode==9)){if(!c._bItemSelected){var b=c._textMatchesOption();if(!c._bContainerOpen||(c._bContainerOpen&&(b===null))){if(c.forceSelection){c._clearSelection()}else{c.unmatchedItemSelectEvent.fire(c,c._sCurQuery)}}else{if(c.forceSelection){c._selectItem(b)}}}c._clearInterval();c._bFocused=false;if(c._sInitInputValue!==c._elTextbox.value){c.textboxChangeEvent.fire(c)}c.textboxBlurEvent.fire(c);c._toggleContainer(false)}else{c._focus()}};YAHOO.widget.AutoComplete.prototype._onWindowUnload=function(a,b){if(b&&b._elTextbox&&b.allowBrowserAutocomplete){b._elTextbox.setAttribute("autocomplete","on")}};YAHOO.widget.AutoComplete.prototype.doBeforeSendQuery=function(a){return this.generateRequest(a)};YAHOO.widget.AutoComplete.prototype.getListItems=function(){var c=[],b=this._elList.childNodes;for(var a=b.length-1;a>=0;a--){c[a]=b[a]}return c};YAHOO.widget.AutoComplete._cloneObject=function(d){if(!YAHOO.lang.isValue(d)){return d}var f={};if(YAHOO.lang.isFunction(d)){f=d}else{if(YAHOO.lang.isArray(d)){var e=[];for(var c=0,b=d.length;c<b;c++){e[c]=YAHOO.widget.AutoComplete._cloneObject(d[c])}f=e}else{if(YAHOO.lang.isObject(d)){for(var a in d){if(YAHOO.lang.hasOwnProperty(d,a)){if(YAHOO.lang.isValue(d[a])&&YAHOO.lang.isObject(d[a])||YAHOO.lang.isArray(d[a])){f[a]=YAHOO.widget.AutoComplete._cloneObject(d[a])}else{f[a]=d[a]}}}}else{f=d}}}return f};YAHOO.register("autocomplete",YAHOO.widget.AutoComplete,{version:"2.9.0",build:"2800"});(function(){YAHOO.util.Config=function(d){if(d){this.init(d)}};var b=YAHOO.lang,c=YAHOO.util.CustomEvent,a=YAHOO.util.Config;a.CONFIG_CHANGED_EVENT="configChanged";a.BOOLEAN_TYPE="boolean";a.prototype={owner:null,queueInProgress:false,config:null,initialConfig:null,eventQueue:null,configChangedEvent:null,init:function(d){this.owner=d;this.configChangedEvent=this.createEvent(a.CONFIG_CHANGED_EVENT);this.configChangedEvent.signature=c.LIST;this.queueInProgress=false;this.config={};this.initialConfig={};this.eventQueue=[]},checkBoolean:function(d){return(typeof d==a.BOOLEAN_TYPE)},checkNumber:function(d){return(!isNaN(d))},fireEvent:function(d,f){var e=this.config[d];if(e&&e.event){e.event.fire(f)}},addProperty:function(e,d){e=e.toLowerCase();this.config[e]=d;d.event=this.createEvent(e,{scope:this.owner});d.event.signature=c.LIST;d.key=e;if(d.handler){d.event.subscribe(d.handler,this.owner)}this.setProperty(e,d.value,true);if(!d.suppressEvent){this.queueProperty(e,d.value)}},getConfig:function(){var d={},f=this.config,g,e;for(g in f){if(b.hasOwnProperty(f,g)){e=f[g];if(e&&e.event){d[g]=e.value}}}return d},getProperty:function(d){var e=this.config[d.toLowerCase()];if(e&&e.event){return e.value}else{return undefined}},resetProperty:function(d){d=d.toLowerCase();var e=this.config[d];if(e&&e.event){if(d in this.initialConfig){this.setProperty(d,this.initialConfig[d]);return true}}else{return false}},setProperty:function(e,g,d){var f;e=e.toLowerCase();if(this.queueInProgress&&!d){this.queueProperty(e,g);return true}else{f=this.config[e];if(f&&f.event){if(f.validator&&!f.validator(g)){return false}else{f.value=g;if(!d){this.fireEvent(e,g);this.configChangedEvent.fire([e,g])}return true}}else{return false}}},queueProperty:function(v,r){v=v.toLowerCase();var u=this.config[v],l=false,k,g,h,j,p,t,f,n,o,d,m,w,e;if(u&&u.event){if(!b.isUndefined(r)&&u.validator&&!u.validator(r)){return false}else{if(!b.isUndefined(r)){u.value=r}else{r=u.value}l=false;k=this.eventQueue.length;for(m=0;m<k;m++){g=this.eventQueue[m];if(g){h=g[0];j=g[1];if(h==v){this.eventQueue[m]=null;this.eventQueue.push([v,(!b.isUndefined(r)?r:j)]);l=true;break}}}if(!l&&!b.isUndefined(r)){this.eventQueue.push([v,r])}}if(u.supercedes){p=u.supercedes.length;for(w=0;w<p;w++){t=u.supercedes[w];f=this.eventQueue.length;for(e=0;e<f;e++){n=this.eventQueue[e];if(n){o=n[0];d=n[1];if(o==t.toLowerCase()){this.eventQueue.push([o,d]);this.eventQueue[e]=null;break}}}}}return true}else{return false}},refireEvent:function(d){d=d.toLowerCase();var e=this.config[d];if(e&&e.event&&!b.isUndefined(e.value)){if(this.queueInProgress){this.queueProperty(d)}else{this.fireEvent(d,e.value)}}},applyConfig:function(d,g){var f,e;if(g){e={};for(f in d){if(b.hasOwnProperty(d,f)){e[f.toLowerCase()]=d[f]}}this.initialConfig=e}for(f in d){if(b.hasOwnProperty(d,f)){this.queueProperty(f,d[f])}}},refresh:function(){var d;for(d in this.config){if(b.hasOwnProperty(this.config,d)){this.refireEvent(d)}}},fireQueue:function(){var e,h,d,g,f;this.queueInProgress=true;for(e=0;e<this.eventQueue.length;e++){h=this.eventQueue[e];if(h){d=h[0];g=h[1];f=this.config[d];f.value=g;this.eventQueue[e]=null;this.fireEvent(d,g)}}this.queueInProgress=false;this.eventQueue=[]},subscribeToConfigEvent:function(d,e,g,h){var f=this.config[d.toLowerCase()];if(f&&f.event){if(!a.alreadySubscribed(f.event,e,g)){f.event.subscribe(e,g,h)}return true}else{return false}},unsubscribeFromConfigEvent:function(d,e,g){var f=this.config[d.toLowerCase()];if(f&&f.event){return f.event.unsubscribe(e,g)}else{return false}},toString:function(){var d="Config";if(this.owner){d+=" ["+this.owner.toString()+"]"}return d},outputEventQueue:function(){var d="",g,e,f=this.eventQueue.length;for(e=0;e<f;e++){g=this.eventQueue[e];if(g){d+=g[0]+"="+g[1]+", "}}return d},destroy:function(){var e=this.config,d,f;for(d in e){if(b.hasOwnProperty(e,d)){f=e[d];f.event.unsubscribeAll();f.event=null}}this.configChangedEvent.unsubscribeAll();this.configChangedEvent=null;this.owner=null;this.config=null;this.initialConfig=null;this.eventQueue=null}};a.alreadySubscribed=function(e,h,j){var f=e.subscribers.length,d,g;if(f>0){g=f-1;do{d=e.subscribers[g];if(d&&d.obj==j&&d.fn==h){return true}}while(g--)}return false};YAHOO.lang.augmentProto(a,YAHOO.util.EventProvider)}());(function(){YAHOO.widget.Module=function(r,q){if(r){this.init(r,q)}else{}};var f=YAHOO.util.Dom,d=YAHOO.util.Config,n=YAHOO.util.Event,m=YAHOO.util.CustomEvent,g=YAHOO.widget.Module,i=YAHOO.env.ua,h,p,o,e,a={BEFORE_INIT:"beforeInit",INIT:"init",APPEND:"append",BEFORE_RENDER:"beforeRender",RENDER:"render",CHANGE_HEADER:"changeHeader",CHANGE_BODY:"changeBody",CHANGE_FOOTER:"changeFooter",CHANGE_CONTENT:"changeContent",DESTROY:"destroy",BEFORE_SHOW:"beforeShow",SHOW:"show",BEFORE_HIDE:"beforeHide",HIDE:"hide"},j={VISIBLE:{key:"visible",value:true,validator:YAHOO.lang.isBoolean},EFFECT:{key:"effect",suppressEvent:true,supercedes:["visible"]},MONITOR_RESIZE:{key:"monitorresize",value:true},APPEND_TO_DOCUMENT_BODY:{key:"appendtodocumentbody",value:false}};g.IMG_ROOT=null;g.IMG_ROOT_SSL=null;g.CSS_MODULE="yui-module";g.CSS_HEADER="hd";g.CSS_BODY="bd";g.CSS_FOOTER="ft";g.RESIZE_MONITOR_SECURE_URL="javascript:false;";g.RESIZE_MONITOR_BUFFER=1;g.textResizeEvent=new m("textResize");g.forceDocumentRedraw=function(){var q=document.documentElement;if(q){q.className+=" ";q.className=YAHOO.lang.trim(q.className)}};function l(){if(!h){h=document.createElement("div");h.innerHTML=('<div class="'+g.CSS_HEADER+'"></div><div class="'+g.CSS_BODY+'"></div><div class="'+g.CSS_FOOTER+'"></div>');p=h.firstChild;o=p.nextSibling;e=o.nextSibling}return h}function k(){if(!p){l()}return(p.cloneNode(false))}function b(){if(!o){l()}return(o.cloneNode(false))}function c(){if(!e){l()}return(e.cloneNode(false))}g.prototype={constructor:g,element:null,header:null,body:null,footer:null,id:null,imageRoot:g.IMG_ROOT,initEvents:function(){var q=m.LIST;this.beforeInitEvent=this.createEvent(a.BEFORE_INIT);this.beforeInitEvent.signature=q;this.initEvent=this.createEvent(a.INIT);this.initEvent.signature=q;this.appendEvent=this.createEvent(a.APPEND);this.appendEvent.signature=q;this.beforeRenderEvent=this.createEvent(a.BEFORE_RENDER);this.beforeRenderEvent.signature=q;this.renderEvent=this.createEvent(a.RENDER);this.renderEvent.signature=q;this.changeHeaderEvent=this.createEvent(a.CHANGE_HEADER);this.changeHeaderEvent.signature=q;this.changeBodyEvent=this.createEvent(a.CHANGE_BODY);this.changeBodyEvent.signature=q;this.changeFooterEvent=this.createEvent(a.CHANGE_FOOTER);this.changeFooterEvent.signature=q;this.changeContentEvent=this.createEvent(a.CHANGE_CONTENT);this.changeContentEvent.signature=q;this.destroyEvent=this.createEvent(a.DESTROY);this.destroyEvent.signature=q;this.beforeShowEvent=this.createEvent(a.BEFORE_SHOW);this.beforeShowEvent.signature=q;this.showEvent=this.createEvent(a.SHOW);this.showEvent.signature=q;this.beforeHideEvent=this.createEvent(a.BEFORE_HIDE);this.beforeHideEvent.signature=q;this.hideEvent=this.createEvent(a.HIDE);this.hideEvent.signature=q},platform:function(){var q=navigator.userAgent.toLowerCase();if(q.indexOf("windows")!=-1||q.indexOf("win32")!=-1){return"windows"}else{if(q.indexOf("macintosh")!=-1){return"mac"}else{return false}}}(),browser:function(){var q=navigator.userAgent.toLowerCase();if(q.indexOf("opera")!=-1){return"opera"}else{if(q.indexOf("msie 7")!=-1){return"ie7"}else{if(q.indexOf("msie")!=-1){return"ie"}else{if(q.indexOf("safari")!=-1){return"safari"}else{if(q.indexOf("gecko")!=-1){return"gecko"}else{return false}}}}}}(),isSecure:function(){if(window.location.href.toLowerCase().indexOf("https")===0){return true}else{return false}}(),initDefaultConfig:function(){this.cfg.addProperty(j.VISIBLE.key,{handler:this.configVisible,value:j.VISIBLE.value,validator:j.VISIBLE.validator});this.cfg.addProperty(j.EFFECT.key,{handler:this.configEffect,suppressEvent:j.EFFECT.suppressEvent,supercedes:j.EFFECT.supercedes});this.cfg.addProperty(j.MONITOR_RESIZE.key,{handler:this.configMonitorResize,value:j.MONITOR_RESIZE.value});this.cfg.addProperty(j.APPEND_TO_DOCUMENT_BODY.key,{value:j.APPEND_TO_DOCUMENT_BODY.value})},init:function(v,u){var s,w;this.initEvents();this.beforeInitEvent.fire(g);this.cfg=new d(this);if(this.isSecure){this.imageRoot=g.IMG_ROOT_SSL}if(typeof v=="string"){s=v;v=document.getElementById(v);if(!v){v=(l()).cloneNode(false);v.id=s}}this.id=f.generateId(v);this.element=v;w=this.element.firstChild;if(w){var r=false,q=false,t=false;do{if(1==w.nodeType){if(!r&&f.hasClass(w,g.CSS_HEADER)){this.header=w;r=true}else{if(!q&&f.hasClass(w,g.CSS_BODY)){this.body=w;q=true}else{if(!t&&f.hasClass(w,g.CSS_FOOTER)){this.footer=w;t=true}}}}}while((w=w.nextSibling))}this.initDefaultConfig();f.addClass(this.element,g.CSS_MODULE);if(u){this.cfg.applyConfig(u,true)}if(!d.alreadySubscribed(this.renderEvent,this.cfg.fireQueue,this.cfg)){this.renderEvent.subscribe(this.cfg.fireQueue,this.cfg,true)}this.initEvent.fire(g)},initResizeMonitor:function(){var r=(i.gecko&&this.platform=="windows");if(r){var q=this;setTimeout(function(){q._initResizeMonitor()},0)}else{this._initResizeMonitor()}},_initResizeMonitor:function(){var q,s,u;function w(){g.textResizeEvent.fire()}if(!i.opera){s=f.get("_yuiResizeMonitor");var v=this._supportsCWResize();if(!s){s=document.createElement("iframe");if(this.isSecure&&g.RESIZE_MONITOR_SECURE_URL&&i.ie){s.src=g.RESIZE_MONITOR_SECURE_URL}if(!v){u=["<html><head><script ",'type="text/javascript">',"window.onresize=function(){window.parent.","YAHOO.widget.Module.textResizeEvent.","fire();};<","/script></head>","<body></body></html>"].join("");s.src="data:text/html;charset=utf-8,"+encodeURIComponent(u)}s.id="_yuiResizeMonitor";s.title="Text Resize Monitor";s.tabIndex=-1;s.setAttribute("role","presentation");s.style.position="absolute";s.style.visibility="hidden";var r=document.body,t=r.firstChild;if(t){r.insertBefore(s,t)}else{r.appendChild(s)}s.style.backgroundColor="transparent";s.style.borderWidth="0";s.style.width="2em";s.style.height="2em";s.style.left="0";s.style.top=(-1*(s.offsetHeight+g.RESIZE_MONITOR_BUFFER))+"px";s.style.visibility="visible";if(i.webkit){q=s.contentWindow.document;q.open();q.close()}}if(s&&s.contentWindow){g.textResizeEvent.subscribe(this.onDomResize,this,true);if(!g.textResizeInitialized){if(v){if(!n.on(s.contentWindow,"resize",w)){n.on(s,"resize",w)}}g.textResizeInitialized=true}this.resizeMonitor=s}}},_supportsCWResize:function(){var q=true;if(i.gecko&&i.gecko<=1.8){q=false}return q},onDomResize:function(s,r){var q=-1*(this.resizeMonitor.offsetHeight+g.RESIZE_MONITOR_BUFFER);this.resizeMonitor.style.top=q+"px";this.resizeMonitor.style.left="0"},setHeader:function(r){var q=this.header||(this.header=k());if(r.nodeName){q.innerHTML="";q.appendChild(r)}else{q.innerHTML=r}if(this._rendered){this._renderHeader()}this.changeHeaderEvent.fire(r);this.changeContentEvent.fire()},appendToHeader:function(r){var q=this.header||(this.header=k());q.appendChild(r);this.changeHeaderEvent.fire(r);this.changeContentEvent.fire()},setBody:function(r){var q=this.body||(this.body=b());if(r.nodeName){q.innerHTML="";q.appendChild(r)}else{q.innerHTML=r}if(this._rendered){this._renderBody()}this.changeBodyEvent.fire(r);this.changeContentEvent.fire()},appendToBody:function(r){var q=this.body||(this.body=b());q.appendChild(r);this.changeBodyEvent.fire(r);this.changeContentEvent.fire()},setFooter:function(r){var q=this.footer||(this.footer=c());if(r.nodeName){q.innerHTML="";q.appendChild(r)}else{q.innerHTML=r}if(this._rendered){this._renderFooter()}this.changeFooterEvent.fire(r);this.changeContentEvent.fire()},appendToFooter:function(r){var q=this.footer||(this.footer=c());q.appendChild(r);this.changeFooterEvent.fire(r);this.changeContentEvent.fire()},render:function(s,q){var t=this;function r(u){if(typeof u=="string"){u=document.getElementById(u)}if(u){t._addToParent(u,t.element);t.appendEvent.fire()}}this.beforeRenderEvent.fire();if(!q){q=this.element}if(s){r(s)}else{if(!f.inDocument(this.element)){return false}}this._renderHeader(q);this._renderBody(q);this._renderFooter(q);this._rendered=true;this.renderEvent.fire();return true},_renderHeader:function(q){q=q||this.element;if(this.header&&!f.inDocument(this.header)){var r=q.firstChild;if(r){q.insertBefore(this.header,r)}else{q.appendChild(this.header)}}},_renderBody:function(q){q=q||this.element;if(this.body&&!f.inDocument(this.body)){if(this.footer&&f.isAncestor(q,this.footer)){q.insertBefore(this.body,this.footer)}else{q.appendChild(this.body)}}},_renderFooter:function(q){q=q||this.element;if(this.footer&&!f.inDocument(this.footer)){q.appendChild(this.footer)}},destroy:function(q){var r,s=!(q);if(this.element){n.purgeElement(this.element,s);r=this.element.parentNode}if(r){r.removeChild(this.element)}this.element=null;this.header=null;this.body=null;this.footer=null;g.textResizeEvent.unsubscribe(this.onDomResize,this);this.cfg.destroy();this.cfg=null;this.destroyEvent.fire()},show:function(){this.cfg.setProperty("visible",true)},hide:function(){this.cfg.setProperty("visible",false)},configVisible:function(r,q,s){var t=q[0];if(t){if(this.beforeShowEvent.fire()){f.setStyle(this.element,"display","block");this.showEvent.fire()}}else{if(this.beforeHideEvent.fire()){f.setStyle(this.element,"display","none");this.hideEvent.fire()}}},configEffect:function(r,q,s){this._cachedEffects=(this.cacheEffects)?this._createEffects(q[0]):null},cacheEffects:true,_createEffects:function(t){var q=null,u,r,s;if(t){if(t instanceof Array){q=[];u=t.length;for(r=0;r<u;r++){s=t[r];if(s.effect){q[q.length]=s.effect(this,s.duration)}}}else{if(t.effect){q=[t.effect(this,t.duration)]}}}return q},configMonitorResize:function(s,r,t){var q=r[0];if(q){this.initResizeMonitor()}else{g.textResizeEvent.unsubscribe(this.onDomResize,this,true);this.resizeMonitor=null}},_addToParent:function(q,r){if(!this.cfg.getProperty("appendtodocumentbody")&&q===document.body&&q.firstChild){q.insertBefore(r,q.firstChild)}else{q.appendChild(r)}},toString:function(){return"Module "+this.id}};YAHOO.lang.augmentProto(g,YAHOO.util.EventProvider)}());(function(){YAHOO.widget.Overlay=function(p,o){YAHOO.widget.Overlay.superclass.constructor.call(this,p,o)};var i=YAHOO.lang,m=YAHOO.util.CustomEvent,g=YAHOO.widget.Module,n=YAHOO.util.Event,f=YAHOO.util.Dom,d=YAHOO.util.Config,k=YAHOO.env.ua,b=YAHOO.widget.Overlay,h="subscribe",e="unsubscribe",c="contained",j,a={BEFORE_MOVE:"beforeMove",MOVE:"move"},l={X:{key:"x",validator:i.isNumber,suppressEvent:true,supercedes:["iframe"]},Y:{key:"y",validator:i.isNumber,suppressEvent:true,supercedes:["iframe"]},XY:{key:"xy",suppressEvent:true,supercedes:["iframe"]},CONTEXT:{key:"context",suppressEvent:true,supercedes:["iframe"]},FIXED_CENTER:{key:"fixedcenter",value:false,supercedes:["iframe","visible"]},WIDTH:{key:"width",suppressEvent:true,supercedes:["context","fixedcenter","iframe"]},HEIGHT:{key:"height",suppressEvent:true,supercedes:["context","fixedcenter","iframe"]},AUTO_FILL_HEIGHT:{key:"autofillheight",supercedes:["height"],value:"body"},ZINDEX:{key:"zindex",value:null},CONSTRAIN_TO_VIEWPORT:{key:"constraintoviewport",value:false,validator:i.isBoolean,supercedes:["iframe","x","y","xy"]},IFRAME:{key:"iframe",value:(k.ie==6?true:false),validator:i.isBoolean,supercedes:["zindex"]},PREVENT_CONTEXT_OVERLAP:{key:"preventcontextoverlap",value:false,validator:i.isBoolean,supercedes:["constraintoviewport"]}};b.IFRAME_SRC="javascript:false;";b.IFRAME_OFFSET=3;b.VIEWPORT_OFFSET=10;b.TOP_LEFT="tl";b.TOP_RIGHT="tr";b.BOTTOM_LEFT="bl";b.BOTTOM_RIGHT="br";b.PREVENT_OVERLAP_X={tltr:true,blbr:true,brbl:true,trtl:true};b.PREVENT_OVERLAP_Y={trbr:true,tlbl:true,bltl:true,brtr:true};b.CSS_OVERLAY="yui-overlay";b.CSS_HIDDEN="yui-overlay-hidden";b.CSS_IFRAME="yui-overlay-iframe";b.STD_MOD_RE=/^\s*?(body|footer|header)\s*?$/i;b.windowScrollEvent=new m("windowScroll");b.windowResizeEvent=new m("windowResize");b.windowScrollHandler=function(p){var o=n.getTarget(p);if(!o||o===window||o===window.document){if(k.ie){if(!window.scrollEnd){window.scrollEnd=-1}clearTimeout(window.scrollEnd);window.scrollEnd=setTimeout(function(){b.windowScrollEvent.fire()},1)}else{b.windowScrollEvent.fire()}}};b.windowResizeHandler=function(o){if(k.ie){if(!window.resizeEnd){window.resizeEnd=-1}clearTimeout(window.resizeEnd);window.resizeEnd=setTimeout(function(){b.windowResizeEvent.fire()},100)}else{b.windowResizeEvent.fire()}};b._initialized=null;if(b._initialized===null){n.on(window,"scroll",b.windowScrollHandler);n.on(window,"resize",b.windowResizeHandler);b._initialized=true}b._TRIGGER_MAP={windowScroll:b.windowScrollEvent,windowResize:b.windowResizeEvent,textResize:g.textResizeEvent};YAHOO.extend(b,g,{CONTEXT_TRIGGERS:[],init:function(p,o){b.superclass.init.call(this,p);this.beforeInitEvent.fire(b);f.addClass(this.element,b.CSS_OVERLAY);if(o){this.cfg.applyConfig(o,true)}if(this.platform=="mac"&&k.gecko){if(!d.alreadySubscribed(this.showEvent,this.showMacGeckoScrollbars,this)){this.showEvent.subscribe(this.showMacGeckoScrollbars,this,true)}if(!d.alreadySubscribed(this.hideEvent,this.hideMacGeckoScrollbars,this)){this.hideEvent.subscribe(this.hideMacGeckoScrollbars,this,true)}}this.initEvent.fire(b)},initEvents:function(){b.superclass.initEvents.call(this);var o=m.LIST;this.beforeMoveEvent=this.createEvent(a.BEFORE_MOVE);this.beforeMoveEvent.signature=o;this.moveEvent=this.createEvent(a.MOVE);this.moveEvent.signature=o},initDefaultConfig:function(){b.superclass.initDefaultConfig.call(this);var o=this.cfg;o.addProperty(l.X.key,{handler:this.configX,validator:l.X.validator,suppressEvent:l.X.suppressEvent,supercedes:l.X.supercedes});o.addProperty(l.Y.key,{handler:this.configY,validator:l.Y.validator,suppressEvent:l.Y.suppressEvent,supercedes:l.Y.supercedes});o.addProperty(l.XY.key,{handler:this.configXY,suppressEvent:l.XY.suppressEvent,supercedes:l.XY.supercedes});o.addProperty(l.CONTEXT.key,{handler:this.configContext,suppressEvent:l.CONTEXT.suppressEvent,supercedes:l.CONTEXT.supercedes});o.addProperty(l.FIXED_CENTER.key,{handler:this.configFixedCenter,value:l.FIXED_CENTER.value,validator:l.FIXED_CENTER.validator,supercedes:l.FIXED_CENTER.supercedes});o.addProperty(l.WIDTH.key,{handler:this.configWidth,suppressEvent:l.WIDTH.suppressEvent,supercedes:l.WIDTH.supercedes});o.addProperty(l.HEIGHT.key,{handler:this.configHeight,suppressEvent:l.HEIGHT.suppressEvent,supercedes:l.HEIGHT.supercedes});o.addProperty(l.AUTO_FILL_HEIGHT.key,{handler:this.configAutoFillHeight,value:l.AUTO_FILL_HEIGHT.value,validator:this._validateAutoFill,supercedes:l.AUTO_FILL_HEIGHT.supercedes});o.addProperty(l.ZINDEX.key,{handler:this.configzIndex,value:l.ZINDEX.value});o.addProperty(l.CONSTRAIN_TO_VIEWPORT.key,{handler:this.configConstrainToViewport,value:l.CONSTRAIN_TO_VIEWPORT.value,validator:l.CONSTRAIN_TO_VIEWPORT.validator,supercedes:l.CONSTRAIN_TO_VIEWPORT.supercedes});o.addProperty(l.IFRAME.key,{handler:this.configIframe,value:l.IFRAME.value,validator:l.IFRAME.validator,supercedes:l.IFRAME.supercedes});o.addProperty(l.PREVENT_CONTEXT_OVERLAP.key,{value:l.PREVENT_CONTEXT_OVERLAP.value,validator:l.PREVENT_CONTEXT_OVERLAP.validator,supercedes:l.PREVENT_CONTEXT_OVERLAP.supercedes})},moveTo:function(o,p){this.cfg.setProperty("xy",[o,p])},hideMacGeckoScrollbars:function(){f.replaceClass(this.element,"show-scrollbars","hide-scrollbars")},showMacGeckoScrollbars:function(){f.replaceClass(this.element,"hide-scrollbars","show-scrollbars")},_setDomVisibility:function(o){f.setStyle(this.element,"visibility",(o)?"visible":"hidden");var p=b.CSS_HIDDEN;if(o){f.removeClass(this.element,p)}else{f.addClass(this.element,p)}},configVisible:function(x,w,t){var p=w[0],B=f.getStyle(this.element,"visibility"),o=this._cachedEffects||this._createEffects(this.cfg.getProperty("effect")),A=(this.platform=="mac"&&k.gecko),y=d.alreadySubscribed,q,v,s,r,u,z;if(B=="inherit"){v=this.element.parentNode;while(v.nodeType!=9&&v.nodeType!=11){B=f.getStyle(v,"visibility");if(B!="inherit"){break}v=v.parentNode}if(B=="inherit"){B="visible"}}if(p){if(A){this.showMacGeckoScrollbars()}if(o){if(p){if(B!="visible"||B===""||this._fadingOut){if(this.beforeShowEvent.fire()){z=o.length;for(s=0;s<z;s++){q=o[s];if(s===0&&!y(q.animateInCompleteEvent,this.showEvent.fire,this.showEvent)){q.animateInCompleteEvent.subscribe(this.showEvent.fire,this.showEvent,true)}q.animateIn()}}}}}else{if(B!="visible"||B===""){if(this.beforeShowEvent.fire()){this._setDomVisibility(true);this.cfg.refireEvent("iframe");this.showEvent.fire()}}else{this._setDomVisibility(true)}}}else{if(A){this.hideMacGeckoScrollbars()}if(o){if(B=="visible"||this._fadingIn){if(this.beforeHideEvent.fire()){z=o.length;for(r=0;r<z;r++){u=o[r];if(r===0&&!y(u.animateOutCompleteEvent,this.hideEvent.fire,this.hideEvent)){u.animateOutCompleteEvent.subscribe(this.hideEvent.fire,this.hideEvent,true)}u.animateOut()}}}else{if(B===""){this._setDomVisibility(false)}}}else{if(B=="visible"||B===""){if(this.beforeHideEvent.fire()){this._setDomVisibility(false);this.hideEvent.fire()}}else{this._setDomVisibility(false)}}}},doCenterOnDOMEvent:function(){var o=this.cfg,p=o.getProperty("fixedcenter");if(o.getProperty("visible")){if(p&&(p!==c||this.fitsInViewport())){this.center()}}},fitsInViewport:function(){var s=b.VIEWPORT_OFFSET,q=this.element,t=q.offsetWidth,r=q.offsetHeight,o=f.getViewportWidth(),p=f.getViewportHeight();return((t+s<o)&&(r+s<p))},configFixedCenter:function(s,q,t){var u=q[0],p=d.alreadySubscribed,r=b.windowResizeEvent,o=b.windowScrollEvent;if(u){this.center();if(!p(this.beforeShowEvent,this.center)){this.beforeShowEvent.subscribe(this.center)}if(!p(r,this.doCenterOnDOMEvent,this)){r.subscribe(this.doCenterOnDOMEvent,this,true)}if(!p(o,this.doCenterOnDOMEvent,this)){o.subscribe(this.doCenterOnDOMEvent,this,true)}}else{this.beforeShowEvent.unsubscribe(this.center);r.unsubscribe(this.doCenterOnDOMEvent,this);o.unsubscribe(this.doCenterOnDOMEvent,this)}},configHeight:function(r,p,s){var o=p[0],q=this.element;f.setStyle(q,"height",o);this.cfg.refireEvent("iframe")},configAutoFillHeight:function(t,s,p){var v=s[0],q=this.cfg,u="autofillheight",w="height",r=q.getProperty(u),o=this._autoFillOnHeightChange;q.unsubscribeFromConfigEvent(w,o);g.textResizeEvent.unsubscribe(o);this.changeContentEvent.unsubscribe(o);if(r&&v!==r&&this[r]){f.setStyle(this[r],w,"")}if(v){v=i.trim(v.toLowerCase());q.subscribeToConfigEvent(w,o,this[v],this);g.textResizeEvent.subscribe(o,this[v],this);this.changeContentEvent.subscribe(o,this[v],this);q.setProperty(u,v,true)}},configWidth:function(r,o,s){var q=o[0],p=this.element;f.setStyle(p,"width",q);this.cfg.refireEvent("iframe")},configzIndex:function(q,o,r){var s=o[0],p=this.element;if(!s){s=f.getStyle(p,"zIndex");if(!s||isNaN(s)){s=0}}if(this.iframe||this.cfg.getProperty("iframe")===true){if(s<=0){s=1}}f.setStyle(p,"zIndex",s);this.cfg.setProperty("zIndex",s,true);if(this.iframe){this.stackIframe()}},configXY:function(q,p,r){var t=p[0],o=t[0],s=t[1];this.cfg.setProperty("x",o);this.cfg.setProperty("y",s);this.beforeMoveEvent.fire([o,s]);o=this.cfg.getProperty("x");s=this.cfg.getProperty("y");this.cfg.refireEvent("iframe");this.moveEvent.fire([o,s])},configX:function(q,p,r){var o=p[0],s=this.cfg.getProperty("y");this.cfg.setProperty("x",o,true);this.cfg.setProperty("y",s,true);this.beforeMoveEvent.fire([o,s]);o=this.cfg.getProperty("x");s=this.cfg.getProperty("y");f.setX(this.element,o,true);this.cfg.setProperty("xy",[o,s],true);this.cfg.refireEvent("iframe");this.moveEvent.fire([o,s])},configY:function(q,p,r){var o=this.cfg.getProperty("x"),s=p[0];this.cfg.setProperty("x",o,true);this.cfg.setProperty("y",s,true);this.beforeMoveEvent.fire([o,s]);o=this.cfg.getProperty("x");s=this.cfg.getProperty("y");f.setY(this.element,s,true);this.cfg.setProperty("xy",[o,s],true);this.cfg.refireEvent("iframe");this.moveEvent.fire([o,s])},showIframe:function(){var p=this.iframe,o;if(p){o=this.element.parentNode;if(o!=p.parentNode){this._addToParent(o,p)}p.style.display="block"}},hideIframe:function(){if(this.iframe){this.iframe.style.display="none"}},syncIframe:function(){var o=this.iframe,q=this.element,s=b.IFRAME_OFFSET,p=(s*2),r;if(o){o.style.width=(q.offsetWidth+p+"px");o.style.height=(q.offsetHeight+p+"px");r=this.cfg.getProperty("xy");if(!i.isArray(r)||(isNaN(r[0])||isNaN(r[1]))){this.syncPosition();r=this.cfg.getProperty("xy")}f.setXY(o,[(r[0]-s),(r[1]-s)])}},stackIframe:function(){if(this.iframe){var o=f.getStyle(this.element,"zIndex");if(!YAHOO.lang.isUndefined(o)&&!isNaN(o)){f.setStyle(this.iframe,"zIndex",(o-1))}}},configIframe:function(r,q,s){var o=q[0];function t(){var v=this.iframe,w=this.element,x;if(!v){if(!j){j=document.createElement("iframe");if(this.isSecure){j.src=b.IFRAME_SRC}if(k.ie){j.style.filter="alpha(opacity=0)";j.frameBorder=0}else{j.style.opacity="0"}j.style.position="absolute";j.style.border="none";j.style.margin="0";j.style.padding="0";j.style.display="none";j.tabIndex=-1;j.className=b.CSS_IFRAME}v=j.cloneNode(false);v.id=this.id+"_f";x=w.parentNode;var u=x||document.body;this._addToParent(u,v);this.iframe=v}this.showIframe();this.syncIframe();this.stackIframe();if(!this._hasIframeEventListeners){this.showEvent.subscribe(this.showIframe);this.hideEvent.subscribe(this.hideIframe);this.changeContentEvent.subscribe(this.syncIframe);this._hasIframeEventListeners=true}}function p(){t.call(this);this.beforeShowEvent.unsubscribe(p);this._iframeDeferred=false}if(o){if(this.cfg.getProperty("visible")){t.call(this)}else{if(!this._iframeDeferred){this.beforeShowEvent.subscribe(p);this._iframeDeferred=true}}}else{this.hideIframe();if(this._hasIframeEventListeners){this.showEvent.unsubscribe(this.showIframe);this.hideEvent.unsubscribe(this.hideIframe);this.changeContentEvent.unsubscribe(this.syncIframe);this._hasIframeEventListeners=false}}},_primeXYFromDOM:function(){if(YAHOO.lang.isUndefined(this.cfg.getProperty("xy"))){this.syncPosition();this.cfg.refireEvent("xy");this.beforeShowEvent.unsubscribe(this._primeXYFromDOM)}},configConstrainToViewport:function(p,o,q){var r=o[0];if(r){if(!d.alreadySubscribed(this.beforeMoveEvent,this.enforceConstraints,this)){this.beforeMoveEvent.subscribe(this.enforceConstraints,this,true)}if(!d.alreadySubscribed(this.beforeShowEvent,this._primeXYFromDOM)){this.beforeShowEvent.subscribe(this._primeXYFromDOM)}}else{this.beforeShowEvent.unsubscribe(this._primeXYFromDOM);this.beforeMoveEvent.unsubscribe(this.enforceConstraints,this)}},configContext:function(u,t,q){var x=t[0],r,o,v,s,p,w=this.CONTEXT_TRIGGERS;if(x){r=x[0];o=x[1];v=x[2];s=x[3];p=x[4];if(w&&w.length>0){s=(s||[]).concat(w)}if(r){if(typeof r=="string"){this.cfg.setProperty("context",[document.getElementById(r),o,v,s,p],true)}if(o&&v){this.align(o,v,p)}if(this._contextTriggers){this._processTriggers(this._contextTriggers,e,this._alignOnTrigger)}if(s){this._processTriggers(s,h,this._alignOnTrigger);this._contextTriggers=s}}}},_alignOnTrigger:function(p,o){this.align()},_findTriggerCE:function(o){var p=null;if(o instanceof m){p=o}else{if(b._TRIGGER_MAP[o]){p=b._TRIGGER_MAP[o]}}return p},_processTriggers:function(s,v,r){var q,u;for(var p=0,o=s.length;p<o;++p){q=s[p];u=this._findTriggerCE(q);if(u){u[v](r,this,true)}else{this[v](q,r)}}},align:function(p,w,s){var v=this.cfg.getProperty("context"),t=this,o,q,u;function r(z,A){var y=null,x=null;switch(p){case b.TOP_LEFT:y=A;x=z;break;case b.TOP_RIGHT:y=A-q.offsetWidth;x=z;break;case b.BOTTOM_LEFT:y=A;x=z-q.offsetHeight;break;case b.BOTTOM_RIGHT:y=A-q.offsetWidth;x=z-q.offsetHeight;break}if(y!==null&&x!==null){if(s){y+=s[0];x+=s[1]}t.moveTo(y,x)}}if(v){o=v[0];q=this.element;t=this;if(!p){p=v[1]}if(!w){w=v[2]}if(!s&&v[4]){s=v[4]}if(q&&o){u=f.getRegion(o);switch(w){case b.TOP_LEFT:r(u.top,u.left);break;case b.TOP_RIGHT:r(u.top,u.right);break;case b.BOTTOM_LEFT:r(u.bottom,u.left);break;case b.BOTTOM_RIGHT:r(u.bottom,u.right);break}}}},enforceConstraints:function(p,o,q){var s=o[0];var r=this.getConstrainedXY(s[0],s[1]);this.cfg.setProperty("x",r[0],true);this.cfg.setProperty("y",r[1],true);this.cfg.setProperty("xy",r,true)},_getConstrainedPos:function(y,p){var t=this.element,r=b.VIEWPORT_OFFSET,A=(y=="x"),z=(A)?t.offsetWidth:t.offsetHeight,s=(A)?f.getViewportWidth():f.getViewportHeight(),D=(A)?f.getDocumentScrollLeft():f.getDocumentScrollTop(),C=(A)?b.PREVENT_OVERLAP_X:b.PREVENT_OVERLAP_Y,o=this.cfg.getProperty("context"),u=(z+r<s),w=this.cfg.getProperty("preventcontextoverlap")&&o&&C[(o[1]+o[2])],v=D+r,B=D+s-z-r,q=p;if(p<v||p>B){if(w){q=this._preventOverlap(y,o[0],z,s,D)}else{if(u){if(p<v){q=v}else{if(p>B){q=B}}}else{q=v}}}return q},_preventOverlap:function(y,w,z,u,C){var A=(y=="x"),t=b.VIEWPORT_OFFSET,s=this,q=((A)?f.getX(w):f.getY(w))-C,o=(A)?w.offsetWidth:w.offsetHeight,p=q-t,r=(u-(q+o))-t,D=false,v=function(){var x;if((s.cfg.getProperty(y)-C)>q){x=(q-z)}else{x=(q+o)}s.cfg.setProperty(y,(x+C),true);return x},B=function(){var E=((s.cfg.getProperty(y)-C)>q)?r:p,x;if(z>E){if(D){v()}else{v();D=true;x=B()}}return x};B();return this.cfg.getProperty(y)},getConstrainedX:function(o){return this._getConstrainedPos("x",o)},getConstrainedY:function(o){return this._getConstrainedPos("y",o)},getConstrainedXY:function(o,p){return[this.getConstrainedX(o),this.getConstrainedY(p)]},center:function(){var r=b.VIEWPORT_OFFSET,s=this.element.offsetWidth,q=this.element.offsetHeight,p=f.getViewportWidth(),t=f.getViewportHeight(),o,u;if(s<p){o=(p/2)-(s/2)+f.getDocumentScrollLeft()}else{o=r+f.getDocumentScrollLeft()}if(q<t){u=(t/2)-(q/2)+f.getDocumentScrollTop()}else{u=r+f.getDocumentScrollTop()}this.cfg.setProperty("xy",[parseInt(o,10),parseInt(u,10)]);this.cfg.refireEvent("iframe");if(k.webkit){this.forceContainerRedraw()}},syncPosition:function(){var o=f.getXY(this.element);this.cfg.setProperty("x",o[0],true);this.cfg.setProperty("y",o[1],true);this.cfg.setProperty("xy",o,true)},onDomResize:function(q,p){var o=this;b.superclass.onDomResize.call(this,q,p);setTimeout(function(){o.syncPosition();o.cfg.refireEvent("iframe");o.cfg.refireEvent("context")},0)},_getComputedHeight:(function(){if(document.defaultView&&document.defaultView.getComputedStyle){return function(p){var o=null;if(p.ownerDocument&&p.ownerDocument.defaultView){var q=p.ownerDocument.defaultView.getComputedStyle(p,"");if(q){o=parseInt(q.height,10)}}return(i.isNumber(o))?o:null}}else{return function(p){var o=null;if(p.style.pixelHeight){o=p.style.pixelHeight}return(i.isNumber(o))?o:null}}})(),_validateAutoFillHeight:function(o){return(!o)||(i.isString(o)&&b.STD_MOD_RE.test(o))},_autoFillOnHeightChange:function(r,p,q){var o=this.cfg.getProperty("height");if((o&&o!=="auto")||(o===0)){this.fillHeight(q)}},_getPreciseHeight:function(p){var o=p.offsetHeight;if(p.getBoundingClientRect){var q=p.getBoundingClientRect();o=q.bottom-q.top}return o},fillHeight:function(r){if(r){var p=this.innerElement||this.element,o=[this.header,this.body,this.footer],v,w=0,x=0,t=0,q=false;for(var u=0,s=o.length;u<s;u++){v=o[u];if(v){if(r!==v){x+=this._getPreciseHeight(v)}else{q=true}}}if(q){if(k.ie||k.opera){f.setStyle(r,"height",0+"px")}w=this._getComputedHeight(p);if(w===null){f.addClass(p,"yui-override-padding");w=p.clientHeight;f.removeClass(p,"yui-override-padding")}t=Math.max(w-x,0);f.setStyle(r,"height",t+"px");if(r.offsetHeight!=t){t=Math.max(t-(r.offsetHeight-t),0)}f.setStyle(r,"height",t+"px")}}},bringToTop:function(){var s=[],r=this.element;function v(z,y){var B=f.getStyle(z,"zIndex"),A=f.getStyle(y,"zIndex"),x=(!B||isNaN(B))?0:parseInt(B,10),w=(!A||isNaN(A))?0:parseInt(A,10);if(x>w){return -1}else{if(x<w){return 1}else{return 0}}}function q(y){var x=f.hasClass(y,b.CSS_OVERLAY),w=YAHOO.widget.Panel;if(x&&!f.isAncestor(r,y)){if(w&&f.hasClass(y,w.CSS_PANEL)){s[s.length]=y.parentNode}else{s[s.length]=y}}}f.getElementsBy(q,"div",document.body);s.sort(v);var o=s[0],u;if(o){u=f.getStyle(o,"zIndex");if(!isNaN(u)){var t=false;if(o!=r){t=true}else{if(s.length>1){var p=f.getStyle(s[1],"zIndex");if(!isNaN(p)&&(u==p)){t=true}}}if(t){this.cfg.setProperty("zindex",(parseInt(u,10)+2))}}}},destroy:function(o){if(this.iframe){this.iframe.parentNode.removeChild(this.iframe)}this.iframe=null;b.windowResizeEvent.unsubscribe(this.doCenterOnDOMEvent,this);b.windowScrollEvent.unsubscribe(this.doCenterOnDOMEvent,this);g.textResizeEvent.unsubscribe(this._autoFillOnHeightChange);if(this._contextTriggers){this._processTriggers(this._contextTriggers,e,this._alignOnTrigger)}b.superclass.destroy.call(this,o)},forceContainerRedraw:function(){var o=this;f.addClass(o.element,"yui-force-redraw");setTimeout(function(){f.removeClass(o.element,"yui-force-redraw")},0)},toString:function(){return"Overlay "+this.id}})}());(function(){YAHOO.widget.OverlayManager=function(g){this.init(g)};var d=YAHOO.widget.Overlay,c=YAHOO.util.Event,e=YAHOO.util.Dom,b=YAHOO.util.Config,f=YAHOO.util.CustomEvent,a=YAHOO.widget.OverlayManager;a.CSS_FOCUSED="focused";a.prototype={constructor:a,overlays:null,initDefaultConfig:function(){this.cfg.addProperty("overlays",{suppressEvent:true});this.cfg.addProperty("focusevent",{value:"mousedown"})},init:function(i){this.cfg=new b(this);this.initDefaultConfig();if(i){this.cfg.applyConfig(i,true)}this.cfg.fireQueue();var h=null;this.getActive=function(){return h};this.focus=function(j){var k=this.find(j);if(k){k.focus()}};this.remove=function(k){var m=this.find(k),j;if(m){if(h==m){h=null}var l=(m.element===null&&m.cfg===null)?true:false;if(!l){j=e.getStyle(m.element,"zIndex");m.cfg.setProperty("zIndex",-1000,true)}this.overlays.sort(this.compareZIndexDesc);this.overlays=this.overlays.slice(0,(this.overlays.length-1));m.hideEvent.unsubscribe(m.blur);m.destroyEvent.unsubscribe(this._onOverlayDestroy,m);m.focusEvent.unsubscribe(this._onOverlayFocusHandler,m);m.blurEvent.unsubscribe(this._onOverlayBlurHandler,m);if(!l){c.removeListener(m.element,this.cfg.getProperty("focusevent"),this._onOverlayElementFocus);m.cfg.setProperty("zIndex",j,true);m.cfg.setProperty("manager",null)}if(m.focusEvent._managed){m.focusEvent=null}if(m.blurEvent._managed){m.blurEvent=null}if(m.focus._managed){m.focus=null}if(m.blur._managed){m.blur=null}}};this.blurAll=function(){var k=this.overlays.length,j;if(k>0){j=k-1;do{this.overlays[j].blur()}while(j--)}};this._manageBlur=function(j){var k=false;if(h==j){e.removeClass(h.element,a.CSS_FOCUSED);h=null;k=true}return k};this._manageFocus=function(j){var k=false;if(h!=j){if(h){h.blur()}h=j;this.bringToTop(h);e.addClass(h.element,a.CSS_FOCUSED);k=true}return k};var g=this.cfg.getProperty("overlays");if(!this.overlays){this.overlays=[]}if(g){this.register(g);this.overlays.sort(this.compareZIndexDesc)}},_onOverlayElementFocus:function(i){var g=c.getTarget(i),h=this.close;if(h&&(g==h||e.isAncestor(h,g))){this.blur()}else{this.focus()}},_onOverlayDestroy:function(h,g,i){this.remove(i)},_onOverlayFocusHandler:function(h,g,i){this._manageFocus(i)},_onOverlayBlurHandler:function(h,g,i){this._manageBlur(i)},_bindFocus:function(g){var h=this;if(!g.focusEvent){g.focusEvent=g.createEvent("focus");g.focusEvent.signature=f.LIST;g.focusEvent._managed=true}else{g.focusEvent.subscribe(h._onOverlayFocusHandler,g,h)}if(!g.focus){c.on(g.element,h.cfg.getProperty("focusevent"),h._onOverlayElementFocus,null,g);g.focus=function(){if(h._manageFocus(this)){if(this.cfg.getProperty("visible")&&this.focusFirst){this.focusFirst()}this.focusEvent.fire()}};g.focus._managed=true}},_bindBlur:function(g){var h=this;if(!g.blurEvent){g.blurEvent=g.createEvent("blur");g.blurEvent.signature=f.LIST;g.focusEvent._managed=true}else{g.blurEvent.subscribe(h._onOverlayBlurHandler,g,h)}if(!g.blur){g.blur=function(){if(h._manageBlur(this)){this.blurEvent.fire()}};g.blur._managed=true}g.hideEvent.subscribe(g.blur)},_bindDestroy:function(g){var h=this;g.destroyEvent.subscribe(h._onOverlayDestroy,g,h)},_syncZIndex:function(g){var h=e.getStyle(g.element,"zIndex");if(!isNaN(h)){g.cfg.setProperty("zIndex",parseInt(h,10))}else{g.cfg.setProperty("zIndex",0)}},register:function(g){var k=false,h,j;if(g instanceof d){g.cfg.addProperty("manager",{value:this});this._bindFocus(g);this._bindBlur(g);this._bindDestroy(g);this._syncZIndex(g);this.overlays.push(g);this.bringToTop(g);k=true}else{if(g instanceof Array){for(h=0,j=g.length;h<j;h++){k=this.register(g[h])||k}}}return k},bringToTop:function(m){var i=this.find(m),l,g,j;if(i){j=this.overlays;j.sort(this.compareZIndexDesc);g=j[0];if(g){l=e.getStyle(g.element,"zIndex");if(!isNaN(l)){var k=false;if(g!==i){k=true}else{if(j.length>1){var h=e.getStyle(j[1].element,"zIndex");if(!isNaN(h)&&(l==h)){k=true}}}if(k){i.cfg.setProperty("zindex",(parseInt(l,10)+2))}}j.sort(this.compareZIndexDesc)}}},find:function(g){var l=g instanceof d,j=this.overlays,p=j.length,k=null,m,h;if(l||typeof g=="string"){for(h=p-1;h>=0;h--){m=j[h];if((l&&(m===g))||(m.id==g)){k=m;break}}}return k},compareZIndexDesc:function(j,i){var h=(j.cfg)?j.cfg.getProperty("zIndex"):null,g=(i.cfg)?i.cfg.getProperty("zIndex"):null;if(h===null&&g===null){return 0}else{if(h===null){return 1}else{if(g===null){return -1}else{if(h>g){return -1}else{if(h<g){return 1}else{return 0}}}}}},showAll:function(){var h=this.overlays,j=h.length,g;for(g=j-1;g>=0;g--){h[g].show()}},hideAll:function(){var h=this.overlays,j=h.length,g;for(g=j-1;g>=0;g--){h[g].hide()}},toString:function(){return"OverlayManager"}}}());(function(){YAHOO.widget.Tooltip=function(p,o){YAHOO.widget.Tooltip.superclass.constructor.call(this,p,o)};var e=YAHOO.lang,n=YAHOO.util.Event,m=YAHOO.util.CustomEvent,c=YAHOO.util.Dom,j=YAHOO.widget.Tooltip,h=YAHOO.env.ua,g=(h.ie&&(h.ie<=6||document.compatMode=="BackCompat")),f,i={PREVENT_OVERLAP:{key:"preventoverlap",value:true,validator:e.isBoolean,supercedes:["x","y","xy"]},SHOW_DELAY:{key:"showdelay",value:200,validator:e.isNumber},AUTO_DISMISS_DELAY:{key:"autodismissdelay",value:5000,validator:e.isNumber},HIDE_DELAY:{key:"hidedelay",value:250,validator:e.isNumber},TEXT:{key:"text",suppressEvent:true},CONTAINER:{key:"container"},DISABLED:{key:"disabled",value:false,suppressEvent:true},XY_OFFSET:{key:"xyoffset",value:[0,25],suppressEvent:true}},a={CONTEXT_MOUSE_OVER:"contextMouseOver",CONTEXT_MOUSE_OUT:"contextMouseOut",CONTEXT_TRIGGER:"contextTrigger"};j.CSS_TOOLTIP="yui-tt";function k(q,o){var p=this.cfg,r=p.getProperty("width");if(r==o){p.setProperty("width",q)}}function d(p,o){if("_originalWidth" in this){k.call(this,this._originalWidth,this._forcedWidth)}var q=document.body,u=this.cfg,t=u.getProperty("width"),r,s;if((!t||t=="auto")&&(u.getProperty("container")!=q||u.getProperty("x")>=c.getViewportWidth()||u.getProperty("y")>=c.getViewportHeight())){s=this.element.cloneNode(true);s.style.visibility="hidden";s.style.top="0px";s.style.left="0px";q.appendChild(s);r=(s.offsetWidth+"px");q.removeChild(s);s=null;u.setProperty("width",r);u.refireEvent("xy");this._originalWidth=t||"";this._forcedWidth=r}}function b(p,o,q){this.render(q)}function l(){n.onDOMReady(b,this.cfg.getProperty("container"),this)}YAHOO.extend(j,YAHOO.widget.Overlay,{init:function(p,o){j.superclass.init.call(this,p);this.beforeInitEvent.fire(j);c.addClass(this.element,j.CSS_TOOLTIP);if(o){this.cfg.applyConfig(o,true)}this.cfg.queueProperty("visible",false);this.cfg.queueProperty("constraintoviewport",true);this.setBody("");this.subscribe("changeContent",d);this.subscribe("init",l);this.subscribe("render",this.onRender);this.initEvent.fire(j)},initEvents:function(){j.superclass.initEvents.call(this);var o=m.LIST;this.contextMouseOverEvent=this.createEvent(a.CONTEXT_MOUSE_OVER);this.contextMouseOverEvent.signature=o;this.contextMouseOutEvent=this.createEvent(a.CONTEXT_MOUSE_OUT);this.contextMouseOutEvent.signature=o;this.contextTriggerEvent=this.createEvent(a.CONTEXT_TRIGGER);this.contextTriggerEvent.signature=o},initDefaultConfig:function(){j.superclass.initDefaultConfig.call(this);this.cfg.addProperty(i.PREVENT_OVERLAP.key,{value:i.PREVENT_OVERLAP.value,validator:i.PREVENT_OVERLAP.validator,supercedes:i.PREVENT_OVERLAP.supercedes});this.cfg.addProperty(i.SHOW_DELAY.key,{handler:this.configShowDelay,value:200,validator:i.SHOW_DELAY.validator});this.cfg.addProperty(i.AUTO_DISMISS_DELAY.key,{handler:this.configAutoDismissDelay,value:i.AUTO_DISMISS_DELAY.value,validator:i.AUTO_DISMISS_DELAY.validator});this.cfg.addProperty(i.HIDE_DELAY.key,{handler:this.configHideDelay,value:i.HIDE_DELAY.value,validator:i.HIDE_DELAY.validator});this.cfg.addProperty(i.TEXT.key,{handler:this.configText,suppressEvent:i.TEXT.suppressEvent});this.cfg.addProperty(i.CONTAINER.key,{handler:this.configContainer,value:document.body});this.cfg.addProperty(i.DISABLED.key,{handler:this.configContainer,value:i.DISABLED.value,supressEvent:i.DISABLED.suppressEvent});this.cfg.addProperty(i.XY_OFFSET.key,{value:i.XY_OFFSET.value.concat(),supressEvent:i.XY_OFFSET.suppressEvent})},configText:function(p,o,q){var r=o[0];if(r){this.setBody(r)}},configContainer:function(q,p,r){var o=p[0];if(typeof o=="string"){this.cfg.setProperty("container",document.getElementById(o),true)}},_removeEventListeners:function(){var r=this._context,o,q,p;if(r){o=r.length;if(o>0){p=o-1;do{q=r[p];n.removeListener(q,"mouseover",this.onContextMouseOver);n.removeListener(q,"mousemove",this.onContextMouseMove);n.removeListener(q,"mouseout",this.onContextMouseOut)}while(p--)}}},configContext:function(t,p,u){var s=p[0],v,o,r,q;if(s){if(!(s instanceof Array)){if(typeof s=="string"){this.cfg.setProperty("context",[document.getElementById(s)],true)}else{this.cfg.setProperty("context",[s],true)}s=this.cfg.getProperty("context")}this._removeEventListeners();this._context=s;v=this._context;if(v){o=v.length;if(o>0){q=o-1;do{r=v[q];n.on(r,"mouseover",this.onContextMouseOver,this);n.on(r,"mousemove",this.onContextMouseMove,this);n.on(r,"mouseout",this.onContextMouseOut,this)}while(q--)}}}},onContextMouseMove:function(p,o){o.pageX=n.getPageX(p);o.pageY=n.getPageY(p)},onContextMouseOver:function(q,p){var o=this;if(o.title){p._tempTitle=o.title;o.title=""}if(p.fireEvent("contextMouseOver",o,q)!==false&&!p.cfg.getProperty("disabled")){if(p.hideProcId){clearTimeout(p.hideProcId);p.hideProcId=null}n.on(o,"mousemove",p.onContextMouseMove,p);p.showProcId=p.doShow(q,o)}},onContextMouseOut:function(q,p){var o=this;if(p._tempTitle){o.title=p._tempTitle;p._tempTitle=null}if(p.showProcId){clearTimeout(p.showProcId);p.showProcId=null}if(p.hideProcId){clearTimeout(p.hideProcId);p.hideProcId=null}p.fireEvent("contextMouseOut",o,q);p.hideProcId=setTimeout(function(){p.hide()},p.cfg.getProperty("hidedelay"))},doShow:function(r,o){var t=this.cfg.getProperty("xyoffset"),p=t[0],s=t[1],q=this;if(h.opera&&o.tagName&&o.tagName.toUpperCase()=="A"){s+=12}return setTimeout(function(){var u=q.cfg.getProperty("text");if(q._tempTitle&&(u===""||YAHOO.lang.isUndefined(u)||YAHOO.lang.isNull(u))){q.setBody(q._tempTitle)}else{q.cfg.refireEvent("text")}q.moveTo(q.pageX+p,q.pageY+s);if(q.cfg.getProperty("preventoverlap")){q.preventOverlap(q.pageX,q.pageY)}n.removeListener(o,"mousemove",q.onContextMouseMove);q.contextTriggerEvent.fire(o);q.show();q.hideProcId=q.doHide()},this.cfg.getProperty("showdelay"))},doHide:function(){var o=this;return setTimeout(function(){o.hide()},this.cfg.getProperty("autodismissdelay"))},preventOverlap:function(s,r){var o=this.element.offsetHeight,q=new YAHOO.util.Point(s,r),p=c.getRegion(this.element);p.top-=5;p.left-=5;p.right+=5;p.bottom+=5;if(p.contains(q)){this.cfg.setProperty("y",(r-o-5))}},onRender:function(s,r){function t(){var w=this.element,v=this.underlay;if(v){v.style.width=(w.offsetWidth+6)+"px";v.style.height=(w.offsetHeight+1)+"px"}}function p(){c.addClass(this.underlay,"yui-tt-shadow-visible");if(h.ie){this.forceUnderlayRedraw()}}function o(){c.removeClass(this.underlay,"yui-tt-shadow-visible")}function u(){var x=this.underlay,w,v,z,y;if(!x){w=this.element;v=YAHOO.widget.Module;z=h.ie;y=this;if(!f){f=document.createElement("div");f.className="yui-tt-shadow"}x=f.cloneNode(false);w.appendChild(x);this.underlay=x;this._shadow=this.underlay;p.call(this);this.subscribe("beforeShow",p);this.subscribe("hide",o);if(g){window.setTimeout(function(){t.call(y)},0);this.cfg.subscribeToConfigEvent("width",t);this.cfg.subscribeToConfigEvent("height",t);this.subscribe("changeContent",t);v.textResizeEvent.subscribe(t,this,true);this.subscribe("destroy",function(){v.textResizeEvent.unsubscribe(t,this)})}}}function q(){u.call(this);this.unsubscribe("beforeShow",q)}if(this.cfg.getProperty("visible")){u.call(this)}else{this.subscribe("beforeShow",q)}},forceUnderlayRedraw:function(){var o=this;c.addClass(o.underlay,"yui-force-redraw");setTimeout(function(){c.removeClass(o.underlay,"yui-force-redraw")},0)},destroy:function(){this._removeEventListeners();j.superclass.destroy.call(this)},toString:function(){return"Tooltip "+this.id}})}());(function(){YAHOO.widget.Panel=function(v,u){YAHOO.widget.Panel.superclass.constructor.call(this,v,u)};var s=null;var e=YAHOO.lang,f=YAHOO.util,a=f.Dom,t=f.Event,m=f.CustomEvent,k=YAHOO.util.KeyListener,i=f.Config,h=YAHOO.widget.Overlay,o=YAHOO.widget.Panel,l=YAHOO.env.ua,p=(l.ie&&(l.ie<=6||document.compatMode=="BackCompat")),g,q,c,d={BEFORE_SHOW_MASK:"beforeShowMask",BEFORE_HIDE_MASK:"beforeHideMask",SHOW_MASK:"showMask",HIDE_MASK:"hideMask",DRAG:"drag"},n={CLOSE:{key:"close",value:true,validator:e.isBoolean,supercedes:["visible"]},DRAGGABLE:{key:"draggable",value:(f.DD?true:false),validator:e.isBoolean,supercedes:["visible"]},DRAG_ONLY:{key:"dragonly",value:false,validator:e.isBoolean,supercedes:["draggable"]},UNDERLAY:{key:"underlay",value:"shadow",supercedes:["visible"]},MODAL:{key:"modal",value:false,validator:e.isBoolean,supercedes:["visible","zindex"]},KEY_LISTENERS:{key:"keylisteners",suppressEvent:true,supercedes:["visible"]},STRINGS:{key:"strings",supercedes:["close"],validator:e.isObject,value:{close:"Close"}}};o.CSS_PANEL="yui-panel";o.CSS_PANEL_CONTAINER="yui-panel-container";o.FOCUSABLE=["a","button","select","textarea","input","iframe"];function j(v,u){if(!this.header&&this.cfg.getProperty("draggable")){this.setHeader("&#160;")}}function r(v,u,w){var z=w[0],x=w[1],y=this.cfg,A=y.getProperty("width");if(A==x){y.setProperty("width",z)}this.unsubscribe("hide",r,w)}function b(v,u){var y,x,w;if(p){y=this.cfg;x=y.getProperty("width");if(!x||x=="auto"){w=(this.element.offsetWidth+"px");y.setProperty("width",w);this.subscribe("hide",r,[(x||""),w])}}}YAHOO.extend(o,h,{init:function(v,u){o.superclass.init.call(this,v);this.beforeInitEvent.fire(o);a.addClass(this.element,o.CSS_PANEL);this.buildWrapper();if(u){this.cfg.applyConfig(u,true)}this.subscribe("showMask",this._addFocusHandlers);this.subscribe("hideMask",this._removeFocusHandlers);this.subscribe("beforeRender",j);this.subscribe("render",function(){this.setFirstLastFocusable();this.subscribe("changeContent",this.setFirstLastFocusable)});this.subscribe("show",this._focusOnShow);this.initEvent.fire(o)},_onElementFocus:function(z){if(s===this){var y=t.getTarget(z),x=document.documentElement,v=(y!==x&&y!==window);if(v&&y!==this.element&&y!==this.mask&&!a.isAncestor(this.element,y)){try{this._focusFirstModal()}catch(w){try{if(v&&y!==document.body){y.blur()}}catch(u){}}}}},_focusFirstModal:function(){var u=this.firstElement;if(u){u.focus()}else{if(this._modalFocus){this._modalFocus.focus()}else{this.innerElement.focus()}}},_addFocusHandlers:function(v,u){if(!this.firstElement){if(l.webkit||l.opera){if(!this._modalFocus){this._createHiddenFocusElement()}}else{this.innerElement.tabIndex=0}}this._setTabLoop(this.firstElement,this.lastElement);t.onFocus(document.documentElement,this._onElementFocus,this,true);s=this},_createHiddenFocusElement:function(){var u=document.createElement("button");u.style.height="1px";u.style.width="1px";u.style.position="absolute";u.style.left="-10000em";u.style.opacity=0;u.tabIndex=-1;this.innerElement.appendChild(u);this._modalFocus=u},_removeFocusHandlers:function(v,u){t.removeFocusListener(document.documentElement,this._onElementFocus,this);if(s==this){s=null}},_focusOnShow:function(v,u,w){if(u&&u[1]){t.stopEvent(u[1])}if(!this.focusFirst(v,u,w)){if(this.cfg.getProperty("modal")){this._focusFirstModal()}}},focusFirst:function(w,u,z){var v=this.firstElement,y=false;if(u&&u[1]){t.stopEvent(u[1])}if(v){try{v.focus();y=true}catch(x){}}return y},focusLast:function(w,u,z){var v=this.lastElement,y=false;if(u&&u[1]){t.stopEvent(u[1])}if(v){try{v.focus();y=true}catch(x){}}return y},_setTabLoop:function(u,v){this.setTabLoop(u,v)},setTabLoop:function(x,z){var v=this.preventBackTab,w=this.preventTabOut,u=this.showEvent,y=this.hideEvent;if(v){v.disable();u.unsubscribe(v.enable,v);y.unsubscribe(v.disable,v);v=this.preventBackTab=null}if(w){w.disable();u.unsubscribe(w.enable,w);y.unsubscribe(w.disable,w);w=this.preventTabOut=null}if(x){this.preventBackTab=new k(x,{shift:true,keys:9},{fn:this.focusLast,scope:this,correctScope:true});v=this.preventBackTab;u.subscribe(v.enable,v,true);y.subscribe(v.disable,v,true)}if(z){this.preventTabOut=new k(z,{shift:false,keys:9},{fn:this.focusFirst,scope:this,correctScope:true});w=this.preventTabOut;u.subscribe(w.enable,w,true);y.subscribe(w.disable,w,true)}},getFocusableElements:function(v){v=v||this.innerElement;var x={},u=this;for(var w=0;w<o.FOCUSABLE.length;w++){x[o.FOCUSABLE[w]]=true}return a.getElementsBy(function(y){return u._testIfFocusable(y,x)},null,v)},_testIfFocusable:function(u,v){if(u.focus&&u.type!=="hidden"&&!u.disabled&&v[u.tagName.toLowerCase()]){return true}return false},setFirstLastFocusable:function(){this.firstElement=null;this.lastElement=null;var u=this.getFocusableElements();this.focusableElements=u;if(u.length>0){this.firstElement=u[0];this.lastElement=u[u.length-1]}if(this.cfg.getProperty("modal")){this._setTabLoop(this.firstElement,this.lastElement)}},initEvents:function(){o.superclass.initEvents.call(this);var u=m.LIST;this.showMaskEvent=this.createEvent(d.SHOW_MASK);this.showMaskEvent.signature=u;this.beforeShowMaskEvent=this.createEvent(d.BEFORE_SHOW_MASK);this.beforeShowMaskEvent.signature=u;this.hideMaskEvent=this.createEvent(d.HIDE_MASK);this.hideMaskEvent.signature=u;this.beforeHideMaskEvent=this.createEvent(d.BEFORE_HIDE_MASK);this.beforeHideMaskEvent.signature=u;this.dragEvent=this.createEvent(d.DRAG);this.dragEvent.signature=u},initDefaultConfig:function(){o.superclass.initDefaultConfig.call(this);this.cfg.addProperty(n.CLOSE.key,{handler:this.configClose,value:n.CLOSE.value,validator:n.CLOSE.validator,supercedes:n.CLOSE.supercedes});this.cfg.addProperty(n.DRAGGABLE.key,{handler:this.configDraggable,value:(f.DD)?true:false,validator:n.DRAGGABLE.validator,supercedes:n.DRAGGABLE.supercedes});this.cfg.addProperty(n.DRAG_ONLY.key,{value:n.DRAG_ONLY.value,validator:n.DRAG_ONLY.validator,supercedes:n.DRAG_ONLY.supercedes});this.cfg.addProperty(n.UNDERLAY.key,{handler:this.configUnderlay,value:n.UNDERLAY.value,supercedes:n.UNDERLAY.supercedes});this.cfg.addProperty(n.MODAL.key,{handler:this.configModal,value:n.MODAL.value,validator:n.MODAL.validator,supercedes:n.MODAL.supercedes});this.cfg.addProperty(n.KEY_LISTENERS.key,{handler:this.configKeyListeners,suppressEvent:n.KEY_LISTENERS.suppressEvent,supercedes:n.KEY_LISTENERS.supercedes});this.cfg.addProperty(n.STRINGS.key,{value:n.STRINGS.value,handler:this.configStrings,validator:n.STRINGS.validator,supercedes:n.STRINGS.supercedes})},configClose:function(y,v,z){var A=v[0],x=this.close,u=this.cfg.getProperty("strings"),w;if(A){if(!x){if(!c){c=document.createElement("a");c.className="container-close";c.href="#"}x=c.cloneNode(true);w=this.innerElement.firstChild;if(w){this.innerElement.insertBefore(x,w)}else{this.innerElement.appendChild(x)}x.innerHTML=(u&&u.close)?u.close:"&#160;";t.on(x,"click",this._doClose,this,true);this.close=x}else{x.style.display="block"}}else{if(x){x.style.display="none"}}},_doClose:function(u){t.preventDefault(u);this.hide()},configDraggable:function(v,u,w){var x=u[0];if(x){if(!f.DD){this.cfg.setProperty("draggable",false);return}if(this.header){a.setStyle(this.header,"cursor","move");this.registerDragDrop()}this.subscribe("beforeShow",b)}else{if(this.dd){this.dd.unreg()}if(this.header){a.setStyle(this.header,"cursor","auto")}this.unsubscribe("beforeShow",b)}},configUnderlay:function(D,C,z){var B=(this.platform=="mac"&&l.gecko),E=C[0].toLowerCase(),v=this.underlay,w=this.element;function x(){var F=false;if(!v){if(!q){q=document.createElement("div");q.className="underlay"}v=q.cloneNode(false);this.element.appendChild(v);this.underlay=v;if(p){this.sizeUnderlay();this.cfg.subscribeToConfigEvent("width",this.sizeUnderlay);this.cfg.subscribeToConfigEvent("height",this.sizeUnderlay);this.changeContentEvent.subscribe(this.sizeUnderlay);YAHOO.widget.Module.textResizeEvent.subscribe(this.sizeUnderlay,this,true)}if(l.webkit&&l.webkit<420){this.changeContentEvent.subscribe(this.forceUnderlayRedraw)}F=true}}function A(){var F=x.call(this);if(!F&&p){this.sizeUnderlay()}this._underlayDeferred=false;this.beforeShowEvent.unsubscribe(A)}function y(){if(this._underlayDeferred){this.beforeShowEvent.unsubscribe(A);this._underlayDeferred=false}if(v){this.cfg.unsubscribeFromConfigEvent("width",this.sizeUnderlay);this.cfg.unsubscribeFromConfigEvent("height",this.sizeUnderlay);this.changeContentEvent.unsubscribe(this.sizeUnderlay);this.changeContentEvent.unsubscribe(this.forceUnderlayRedraw);YAHOO.widget.Module.textResizeEvent.unsubscribe(this.sizeUnderlay,this,true);this.element.removeChild(v);this.underlay=null}}switch(E){case"shadow":a.removeClass(w,"matte");a.addClass(w,"shadow");break;case"matte":if(!B){y.call(this)}a.removeClass(w,"shadow");a.addClass(w,"matte");break;default:if(!B){y.call(this)}a.removeClass(w,"shadow");a.removeClass(w,"matte");break}if((E=="shadow")||(B&&!v)){if(this.cfg.getProperty("visible")){var u=x.call(this);if(!u&&p){this.sizeUnderlay()}}else{if(!this._underlayDeferred){this.beforeShowEvent.subscribe(A);this._underlayDeferred=true}}}},configModal:function(v,u,x){var w=u[0];if(w){if(!this._hasModalityEventListeners){this.subscribe("beforeShow",this.buildMask);this.subscribe("beforeShow",this.bringToTop);this.subscribe("beforeShow",this.showMask);this.subscribe("hide",this.hideMask);h.windowResizeEvent.subscribe(this.sizeMask,this,true);this._hasModalityEventListeners=true}}else{if(this._hasModalityEventListeners){if(this.cfg.getProperty("visible")){this.hideMask();this.removeMask()}this.unsubscribe("beforeShow",this.buildMask);this.unsubscribe("beforeShow",this.bringToTop);this.unsubscribe("beforeShow",this.showMask);this.unsubscribe("hide",this.hideMask);h.windowResizeEvent.unsubscribe(this.sizeMask,this);this._hasModalityEventListeners=false}}},removeMask:function(){var v=this.mask,u;if(v){this.hideMask();u=v.parentNode;if(u){u.removeChild(v)}this.mask=null}},configKeyListeners:function(x,u,A){var w=u[0],z,y,v;if(w){if(w instanceof Array){y=w.length;for(v=0;v<y;v++){z=w[v];if(!i.alreadySubscribed(this.showEvent,z.enable,z)){this.showEvent.subscribe(z.enable,z,true)}if(!i.alreadySubscribed(this.hideEvent,z.disable,z)){this.hideEvent.subscribe(z.disable,z,true);this.destroyEvent.subscribe(z.disable,z,true)}}}else{if(!i.alreadySubscribed(this.showEvent,w.enable,w)){this.showEvent.subscribe(w.enable,w,true)}if(!i.alreadySubscribed(this.hideEvent,w.disable,w)){this.hideEvent.subscribe(w.disable,w,true);this.destroyEvent.subscribe(w.disable,w,true)}}}},configStrings:function(v,u,w){var x=e.merge(n.STRINGS.value,u[0]);this.cfg.setProperty(n.STRINGS.key,x,true)},configHeight:function(x,v,y){var u=v[0],w=this.innerElement;a.setStyle(w,"height",u);this.cfg.refireEvent("iframe")},_autoFillOnHeightChange:function(x,v,w){o.superclass._autoFillOnHeightChange.apply(this,arguments);if(p){var u=this;setTimeout(function(){u.sizeUnderlay()},0)}},configWidth:function(x,u,y){var w=u[0],v=this.innerElement;a.setStyle(v,"width",w);this.cfg.refireEvent("iframe")},configzIndex:function(v,u,x){o.superclass.configzIndex.call(this,v,u,x);if(this.mask||this.cfg.getProperty("modal")===true){var w=a.getStyle(this.element,"zIndex");if(!w||isNaN(w)){w=0}if(w===0){this.cfg.setProperty("zIndex",1)}else{this.stackMask()}}},buildWrapper:function(){var w=this.element.parentNode,u=this.element,v=document.createElement("div");v.className=o.CSS_PANEL_CONTAINER;v.id=u.id+"_c";if(w){w.insertBefore(v,u)}v.appendChild(u);this.element=v;this.innerElement=u;a.setStyle(this.innerElement,"visibility","inherit")},sizeUnderlay:function(){var v=this.underlay,u;if(v){u=this.element;v.style.width=u.offsetWidth+"px";v.style.height=u.offsetHeight+"px"}},registerDragDrop:function(){var v=this;if(this.header){if(!f.DD){return}var u=(this.cfg.getProperty("dragonly")===true);this.dd=new f.DD(this.element.id,this.id,{dragOnly:u});if(!this.header.id){this.header.id=this.id+"_h"}this.dd.startDrag=function(){var x,z,w,C,B,A;if(YAHOO.env.ua.ie==6){a.addClass(v.element,"drag")}if(v.cfg.getProperty("constraintoviewport")){var y=h.VIEWPORT_OFFSET;x=v.element.offsetHeight;z=v.element.offsetWidth;w=a.getViewportWidth();C=a.getViewportHeight();B=a.getDocumentScrollLeft();A=a.getDocumentScrollTop();if(x+y<C){this.minY=A+y;this.maxY=A+C-x-y}else{this.minY=A+y;this.maxY=A+y}if(z+y<w){this.minX=B+y;this.maxX=B+w-z-y}else{this.minX=B+y;this.maxX=B+y}this.constrainX=true;this.constrainY=true}else{this.constrainX=false;this.constrainY=false}v.dragEvent.fire("startDrag",arguments)};this.dd.onDrag=function(){v.syncPosition();v.cfg.refireEvent("iframe");if(this.platform=="mac"&&YAHOO.env.ua.gecko){this.showMacGeckoScrollbars()}v.dragEvent.fire("onDrag",arguments)};this.dd.endDrag=function(){if(YAHOO.env.ua.ie==6){a.removeClass(v.element,"drag")}v.dragEvent.fire("endDrag",arguments);v.moveEvent.fire(v.cfg.getProperty("xy"))};this.dd.setHandleElId(this.header.id);this.dd.addInvalidHandleType("INPUT");this.dd.addInvalidHandleType("SELECT");this.dd.addInvalidHandleType("TEXTAREA")}},buildMask:function(){var u=this.mask;if(!u){if(!g){g=document.createElement("div");g.className="mask";g.innerHTML="&#160;"}u=g.cloneNode(true);u.id=this.id+"_mask";document.body.insertBefore(u,document.body.firstChild);this.mask=u;if(YAHOO.env.ua.gecko&&this.platform=="mac"){a.addClass(this.mask,"block-scrollbars")}this.stackMask()}},hideMask:function(){if(this.cfg.getProperty("modal")&&this.mask&&this.beforeHideMaskEvent.fire()){this.mask.style.display="none";a.removeClass(document.body,"masked");this.hideMaskEvent.fire()}},showMask:function(){if(this.cfg.getProperty("modal")&&this.mask&&this.beforeShowMaskEvent.fire()){a.addClass(document.body,"masked");this.sizeMask();this.mask.style.display="block";this.showMaskEvent.fire()}},sizeMask:function(){if(this.mask){var v=this.mask,w=a.getViewportWidth(),u=a.getViewportHeight();if(v.offsetHeight>u){v.style.height=u+"px"}if(v.offsetWidth>w){v.style.width=w+"px"}v.style.height=a.getDocumentHeight()+"px";v.style.width=a.getDocumentWidth()+"px"}},stackMask:function(){if(this.mask){var u=a.getStyle(this.element,"zIndex");if(!YAHOO.lang.isUndefined(u)&&!isNaN(u)){a.setStyle(this.mask,"zIndex",u-1)}}},render:function(u){return o.superclass.render.call(this,u,this.innerElement)},_renderHeader:function(u){u=u||this.innerElement;o.superclass._renderHeader.call(this,u)},_renderBody:function(u){u=u||this.innerElement;o.superclass._renderBody.call(this,u)},_renderFooter:function(u){u=u||this.innerElement;o.superclass._renderFooter.call(this,u)},destroy:function(u){h.windowResizeEvent.unsubscribe(this.sizeMask,this);this.removeMask();if(this.close){t.purgeElement(this.close)}o.superclass.destroy.call(this,u)},forceUnderlayRedraw:function(){var v=this.underlay;a.addClass(v,"yui-force-redraw");setTimeout(function(){a.removeClass(v,"yui-force-redraw")},0)},toString:function(){return"Panel "+this.id}})}());(function(){YAHOO.widget.Dialog=function(j,i){YAHOO.widget.Dialog.superclass.constructor.call(this,j,i)};var b=YAHOO.util.Event,g=YAHOO.util.CustomEvent,e=YAHOO.util.Dom,a=YAHOO.widget.Dialog,f=YAHOO.lang,h={BEFORE_SUBMIT:"beforeSubmit",SUBMIT:"submit",MANUAL_SUBMIT:"manualSubmit",ASYNC_SUBMIT:"asyncSubmit",FORM_SUBMIT:"formSubmit",CANCEL:"cancel"},c={POST_METHOD:{key:"postmethod",value:"async"},POST_DATA:{key:"postdata",value:null},BUTTONS:{key:"buttons",value:"none",supercedes:["visible"]},HIDEAFTERSUBMIT:{key:"hideaftersubmit",value:true}};a.CSS_DIALOG="yui-dialog";function d(){var m=this._aButtons,k,l,j;if(f.isArray(m)){k=m.length;if(k>0){j=k-1;do{l=m[j];if(YAHOO.widget.Button&&l instanceof YAHOO.widget.Button){l.destroy()}else{if(l.tagName.toUpperCase()=="BUTTON"){b.purgeElement(l);b.purgeElement(l,false)}}}while(j--)}}}YAHOO.extend(a,YAHOO.widget.Panel,{form:null,initDefaultConfig:function(){a.superclass.initDefaultConfig.call(this);this.callback={success:null,failure:null,argument:null};this.cfg.addProperty(c.POST_METHOD.key,{handler:this.configPostMethod,value:c.POST_METHOD.value,validator:function(i){if(i!="form"&&i!="async"&&i!="none"&&i!="manual"){return false}else{return true}}});this.cfg.addProperty(c.POST_DATA.key,{value:c.POST_DATA.value});this.cfg.addProperty(c.HIDEAFTERSUBMIT.key,{value:c.HIDEAFTERSUBMIT.value});this.cfg.addProperty(c.BUTTONS.key,{handler:this.configButtons,value:c.BUTTONS.value,supercedes:c.BUTTONS.supercedes})},initEvents:function(){a.superclass.initEvents.call(this);var i=g.LIST;this.beforeSubmitEvent=this.createEvent(h.BEFORE_SUBMIT);this.beforeSubmitEvent.signature=i;this.submitEvent=this.createEvent(h.SUBMIT);this.submitEvent.signature=i;this.manualSubmitEvent=this.createEvent(h.MANUAL_SUBMIT);this.manualSubmitEvent.signature=i;this.asyncSubmitEvent=this.createEvent(h.ASYNC_SUBMIT);this.asyncSubmitEvent.signature=i;this.formSubmitEvent=this.createEvent(h.FORM_SUBMIT);this.formSubmitEvent.signature=i;this.cancelEvent=this.createEvent(h.CANCEL);this.cancelEvent.signature=i},init:function(j,i){a.superclass.init.call(this,j);this.beforeInitEvent.fire(a);e.addClass(this.element,a.CSS_DIALOG);this.cfg.setProperty("visible",false);if(i){this.cfg.applyConfig(i,true)}this.beforeHideEvent.subscribe(this.blurButtons,this,true);this.subscribe("changeBody",this.registerForm);this.initEvent.fire(a)},doSubmit:function(){var q=YAHOO.util.Connect,r=this.form,l=false,o=false,s,n,m,j;switch(this.cfg.getProperty("postmethod")){case"async":s=r.elements;n=s.length;if(n>0){m=n-1;do{if(s[m].type=="file"){l=true;break}}while(m--)}if(l&&YAHOO.env.ua.ie&&this.isSecure){o=true}j=this._getFormAttributes(r);q.setForm(r,l,o);var k=this.cfg.getProperty("postdata");var p=q.asyncRequest(j.method,j.action,this.callback,k);this.asyncSubmitEvent.fire(p);break;case"form":r.submit();this.formSubmitEvent.fire();break;case"none":case"manual":this.manualSubmitEvent.fire();break}},_getFormAttributes:function(k){var i={method:null,action:null};if(k){if(k.getAttributeNode){var j=k.getAttributeNode("action");var l=k.getAttributeNode("method");if(j){i.action=j.value}if(l){i.method=l.value}}else{i.action=k.getAttribute("action");i.method=k.getAttribute("method")}}i.method=(f.isString(i.method)?i.method:"POST").toUpperCase();i.action=f.isString(i.action)?i.action:"";return i},registerForm:function(){var i=this.element.getElementsByTagName("form")[0];if(this.form){if(this.form==i&&e.isAncestor(this.element,this.form)){return}else{b.purgeElement(this.form);this.form=null}}if(!i){i=document.createElement("form");i.name="frm_"+this.id;this.body.appendChild(i)}if(i){this.form=i;b.on(i,"submit",this._submitHandler,this,true)}},_submitHandler:function(i){b.stopEvent(i);this.submit();this.form.blur()},setTabLoop:function(i,j){i=i||this.firstButton;j=j||this.lastButton;a.superclass.setTabLoop.call(this,i,j)},_setTabLoop:function(i,j){i=i||this.firstButton;j=this.lastButton||j;this.setTabLoop(i,j)},setFirstLastFocusable:function(){a.superclass.setFirstLastFocusable.call(this);var k,j,m,n=this.focusableElements;this.firstFormElement=null;this.lastFormElement=null;if(this.form&&n&&n.length>0){j=n.length;for(k=0;k<j;++k){m=n[k];if(this.form===m.form){this.firstFormElement=m;break}}for(k=j-1;k>=0;--k){m=n[k];if(this.form===m.form){this.lastFormElement=m;break}}}},configClose:function(j,i,k){a.superclass.configClose.apply(this,arguments)},_doClose:function(i){b.preventDefault(i);this.cancel()},configButtons:function(t,s,n){var o=YAHOO.widget.Button,v=s[0],l=this.innerElement,u,q,k,r,p,j,m;d.call(this);this._aButtons=null;if(f.isArray(v)){p=document.createElement("span");p.className="button-group";r=v.length;this._aButtons=[];this.defaultHtmlButton=null;for(m=0;m<r;m++){u=v[m];if(o){k=new o({label:u.text,type:u.type});k.appendTo(p);q=k.get("element");if(u.isDefault){k.addClass("default");this.defaultHtmlButton=q}if(f.isFunction(u.handler)){k.set("onclick",{fn:u.handler,obj:this,scope:this})}else{if(f.isObject(u.handler)&&f.isFunction(u.handler.fn)){k.set("onclick",{fn:u.handler.fn,obj:((!f.isUndefined(u.handler.obj))?u.handler.obj:this),scope:(u.handler.scope||this)})}}this._aButtons[this._aButtons.length]=k}else{q=document.createElement("button");q.setAttribute("type","button");if(u.isDefault){q.className="default";this.defaultHtmlButton=q}q.innerHTML=u.text;if(f.isFunction(u.handler)){b.on(q,"click",u.handler,this,true)}else{if(f.isObject(u.handler)&&f.isFunction(u.handler.fn)){b.on(q,"click",u.handler.fn,((!f.isUndefined(u.handler.obj))?u.handler.obj:this),(u.handler.scope||this))}}p.appendChild(q);this._aButtons[this._aButtons.length]=q}u.htmlButton=q;if(m===0){this.firstButton=q}if(m==(r-1)){this.lastButton=q}}this.setFooter(p);j=this.footer;if(e.inDocument(this.element)&&!e.isAncestor(l,j)){l.appendChild(j)}this.buttonSpan=p}else{p=this.buttonSpan;j=this.footer;if(p&&j){j.removeChild(p);this.buttonSpan=null;this.firstButton=null;this.lastButton=null;this.defaultHtmlButton=null}}this.changeContentEvent.fire()},getButtons:function(){return this._aButtons||null},focusFirst:function(k,i,n){var j=this.firstFormElement,m=false;if(i&&i[1]){b.stopEvent(i[1]);if(i[0]===9&&this.firstElement){j=this.firstElement}}if(j){try{j.focus();m=true}catch(l){}}else{if(this.defaultHtmlButton){m=this.focusDefaultButton()}else{m=this.focusFirstButton()}}return m},focusLast:function(k,i,n){var o=this.cfg.getProperty("buttons"),j=this.lastFormElement,m=false;if(i&&i[1]){b.stopEvent(i[1]);if(i[0]===9&&this.lastElement){j=this.lastElement}}if(o&&f.isArray(o)){m=this.focusLastButton()}else{if(j){try{j.focus();m=true}catch(l){}}}return m},_getButton:function(j){var i=YAHOO.widget.Button;if(i&&j&&j.nodeName&&j.id){j=i.getButton(j.id)||j}return j},focusDefaultButton:function(){var i=this._getButton(this.defaultHtmlButton),k=false;if(i){try{i.focus();k=true}catch(j){}}return k},blurButtons:function(){var o=this.cfg.getProperty("buttons"),l,n,k,j;if(o&&f.isArray(o)){l=o.length;if(l>0){j=(l-1);do{n=o[j];if(n){k=this._getButton(n.htmlButton);if(k){try{k.blur()}catch(m){}}}}while(j--)}}},focusFirstButton:function(){var m=this.cfg.getProperty("buttons"),k,i,l=false;if(m&&f.isArray(m)){k=m[0];if(k){i=this._getButton(k.htmlButton);if(i){try{i.focus();l=true}catch(j){}}}}return l},focusLastButton:function(){var n=this.cfg.getProperty("buttons"),j,l,i,m=false;if(n&&f.isArray(n)){j=n.length;if(j>0){l=n[(j-1)];if(l){i=this._getButton(l.htmlButton);if(i){try{i.focus();m=true}catch(k){}}}}}return m},configPostMethod:function(j,i,k){this.registerForm()},validate:function(){return true},submit:function(){if(this.validate()){if(this.beforeSubmitEvent.fire()){this.doSubmit();this.submitEvent.fire();if(this.cfg.getProperty("hideaftersubmit")){this.hide()}return true}else{return false}}else{return false}},cancel:function(){this.cancelEvent.fire();this.hide()},getData:function(){var A=this.form,k,t,w,m,u,r,q,j,x,l,y,B,p,C,o,z,v;function s(n){var i=n.tagName.toUpperCase();return((i=="INPUT"||i=="TEXTAREA"||i=="SELECT")&&n.name==m)}if(A){k=A.elements;t=k.length;w={};for(z=0;z<t;z++){m=k[z].name;u=e.getElementsBy(s,"*",A);r=u.length;if(r>0){if(r==1){u=u[0];q=u.type;j=u.tagName.toUpperCase();switch(j){case"INPUT":if(q=="checkbox"){w[m]=u.checked}else{if(q!="radio"){w[m]=u.value}}break;case"TEXTAREA":w[m]=u.value;break;case"SELECT":x=u.options;l=x.length;y=[];for(v=0;v<l;v++){B=x[v];if(B.selected){o=B.attributes.value;y[y.length]=(o&&o.specified)?B.value:B.text}}w[m]=y;break}}else{q=u[0].type;switch(q){case"radio":for(v=0;v<r;v++){p=u[v];if(p.checked){w[m]=p.value;break}}break;case"checkbox":y=[];for(v=0;v<r;v++){C=u[v];if(C.checked){y[y.length]=C.value}}w[m]=y;break}}}}}return w},destroy:function(i){d.call(this);this._aButtons=null;var j=this.element.getElementsByTagName("form"),k;if(j.length>0){k=j[0];if(k){b.purgeElement(k);if(k.parentNode){k.parentNode.removeChild(k)}this.form=null}}a.superclass.destroy.call(this,i)},toString:function(){return"Dialog "+this.id}})}());(function(){YAHOO.widget.SimpleDialog=function(e,d){YAHOO.widget.SimpleDialog.superclass.constructor.call(this,e,d)};var c=YAHOO.util.Dom,b=YAHOO.widget.SimpleDialog,a={ICON:{key:"icon",value:"none",suppressEvent:true},TEXT:{key:"text",value:"",suppressEvent:true,supercedes:["icon"]}};b.ICON_BLOCK="blckicon";b.ICON_ALARM="alrticon";b.ICON_HELP="hlpicon";b.ICON_INFO="infoicon";b.ICON_WARN="warnicon";b.ICON_TIP="tipicon";b.ICON_CSS_CLASSNAME="yui-icon";b.CSS_SIMPLEDIALOG="yui-simple-dialog";YAHOO.extend(b,YAHOO.widget.Dialog,{initDefaultConfig:function(){b.superclass.initDefaultConfig.call(this);this.cfg.addProperty(a.ICON.key,{handler:this.configIcon,value:a.ICON.value,suppressEvent:a.ICON.suppressEvent});this.cfg.addProperty(a.TEXT.key,{handler:this.configText,value:a.TEXT.value,suppressEvent:a.TEXT.suppressEvent,supercedes:a.TEXT.supercedes})},init:function(e,d){b.superclass.init.call(this,e);this.beforeInitEvent.fire(b);c.addClass(this.element,b.CSS_SIMPLEDIALOG);this.cfg.queueProperty("postmethod","manual");if(d){this.cfg.applyConfig(d,true)}this.beforeRenderEvent.subscribe(function(){if(!this.body){this.setBody("")}},this,true);this.initEvent.fire(b)},registerForm:function(){b.superclass.registerForm.call(this);var e=this.form.ownerDocument,d=e.createElement("input");d.type="hidden";d.name=this.id;d.value="";this.form.appendChild(d)},configIcon:function(k,j,h){var d=j[0],e=this.body,f=b.ICON_CSS_CLASSNAME,l,i,g;if(d&&d!="none"){l=c.getElementsByClassName(f,"*",e);if(l.length===1){i=l[0];g=i.parentNode;if(g){g.removeChild(i);i=null}}if(d.indexOf(".")==-1){i=document.createElement("span");i.className=(f+" "+d);i.innerHTML="&#160;"}else{i=document.createElement("img");i.src=(this.imageRoot+d);i.className=f}if(i){e.insertBefore(i,e.firstChild)}}},configText:function(e,d,f){var g=d[0];if(g){this.setBody(g);this.cfg.refireEvent("icon")}},toString:function(){return"SimpleDialog "+this.id}})}());(function(){YAHOO.widget.ContainerEffect=function(e,h,g,d,f){if(!f){f=YAHOO.util.Anim}this.overlay=e;this.attrIn=h;this.attrOut=g;this.targetElement=d||e.element;this.animClass=f};var b=YAHOO.util.Dom,c=YAHOO.util.CustomEvent,a=YAHOO.widget.ContainerEffect;a.FADE=function(d,f){var g=YAHOO.util.Easing,i={attributes:{opacity:{from:0,to:1}},duration:f,method:g.easeIn},e={attributes:{opacity:{to:0}},duration:f,method:g.easeOut},h=new a(d,i,e,d.element);h.handleUnderlayStart=function(){var k=this.overlay.underlay;if(k&&YAHOO.env.ua.ie){var j=(k.filters&&k.filters.length>0);if(j){b.addClass(d.element,"yui-effect-fade")}}};h.handleUnderlayComplete=function(){var j=this.overlay.underlay;if(j&&YAHOO.env.ua.ie){b.removeClass(d.element,"yui-effect-fade")}};h.handleStartAnimateIn=function(k,j,l){l.overlay._fadingIn=true;b.addClass(l.overlay.element,"hide-select");if(!l.overlay.underlay){l.overlay.cfg.refireEvent("underlay")}l.handleUnderlayStart();l.overlay._setDomVisibility(true);b.setStyle(l.overlay.element,"opacity",0)};h.handleCompleteAnimateIn=function(k,j,l){l.overlay._fadingIn=false;b.removeClass(l.overlay.element,"hide-select");if(l.overlay.element.style.filter){l.overlay.element.style.filter=null}l.handleUnderlayComplete();l.overlay.cfg.refireEvent("iframe");l.animateInCompleteEvent.fire()};h.handleStartAnimateOut=function(k,j,l){l.overlay._fadingOut=true;b.addClass(l.overlay.element,"hide-select");l.handleUnderlayStart()};h.handleCompleteAnimateOut=function(k,j,l){l.overlay._fadingOut=false;b.removeClass(l.overlay.element,"hide-select");if(l.overlay.element.style.filter){l.overlay.element.style.filter=null}l.overlay._setDomVisibility(false);b.setStyle(l.overlay.element,"opacity",1);l.handleUnderlayComplete();l.overlay.cfg.refireEvent("iframe");l.animateOutCompleteEvent.fire()};h.init();return h};a.SLIDE=function(f,d){var i=YAHOO.util.Easing,l=f.cfg.getProperty("x")||b.getX(f.element),k=f.cfg.getProperty("y")||b.getY(f.element),m=b.getClientWidth(),h=f.element.offsetWidth,j={attributes:{points:{to:[l,k]}},duration:d,method:i.easeIn},e={attributes:{points:{to:[(m+25),k]}},duration:d,method:i.easeOut},g=new a(f,j,e,f.element,YAHOO.util.Motion);g.handleStartAnimateIn=function(o,n,p){p.overlay.element.style.left=((-25)-h)+"px";p.overlay.element.style.top=k+"px"};g.handleTweenAnimateIn=function(q,p,r){var s=b.getXY(r.overlay.element),o=s[0],n=s[1];if(b.getStyle(r.overlay.element,"visibility")=="hidden"&&o<l){r.overlay._setDomVisibility(true)}r.overlay.cfg.setProperty("xy",[o,n],true);r.overlay.cfg.refireEvent("iframe")};g.handleCompleteAnimateIn=function(o,n,p){p.overlay.cfg.setProperty("xy",[l,k],true);p.startX=l;p.startY=k;p.overlay.cfg.refireEvent("iframe");p.animateInCompleteEvent.fire()};g.handleStartAnimateOut=function(o,n,r){var p=b.getViewportWidth(),s=b.getXY(r.overlay.element),q=s[1];r.animOut.attributes.points.to=[(p+25),q]};g.handleTweenAnimateOut=function(p,o,q){var s=b.getXY(q.overlay.element),n=s[0],r=s[1];q.overlay.cfg.setProperty("xy",[n,r],true);q.overlay.cfg.refireEvent("iframe")};g.handleCompleteAnimateOut=function(o,n,p){p.overlay._setDomVisibility(false);p.overlay.cfg.setProperty("xy",[l,k]);p.animateOutCompleteEvent.fire()};g.init();return g};a.prototype={init:function(){this.beforeAnimateInEvent=this.createEvent("beforeAnimateIn");this.beforeAnimateInEvent.signature=c.LIST;this.beforeAnimateOutEvent=this.createEvent("beforeAnimateOut");this.beforeAnimateOutEvent.signature=c.LIST;this.animateInCompleteEvent=this.createEvent("animateInComplete");this.animateInCompleteEvent.signature=c.LIST;this.animateOutCompleteEvent=this.createEvent("animateOutComplete");this.animateOutCompleteEvent.signature=c.LIST;this.animIn=new this.animClass(this.targetElement,this.attrIn.attributes,this.attrIn.duration,this.attrIn.method);this.animIn.onStart.subscribe(this.handleStartAnimateIn,this);this.animIn.onTween.subscribe(this.handleTweenAnimateIn,this);this.animIn.onComplete.subscribe(this.handleCompleteAnimateIn,this);this.animOut=new this.animClass(this.targetElement,this.attrOut.attributes,this.attrOut.duration,this.attrOut.method);this.animOut.onStart.subscribe(this.handleStartAnimateOut,this);this.animOut.onTween.subscribe(this.handleTweenAnimateOut,this);this.animOut.onComplete.subscribe(this.handleCompleteAnimateOut,this)},animateIn:function(){this._stopAnims(this.lastFrameOnStop);this.beforeAnimateInEvent.fire();this.animIn.animate()},animateOut:function(){this._stopAnims(this.lastFrameOnStop);this.beforeAnimateOutEvent.fire();this.animOut.animate()},lastFrameOnStop:true,_stopAnims:function(d){if(this.animOut&&this.animOut.isAnimated()){this.animOut.stop(d)}if(this.animIn&&this.animIn.isAnimated()){this.animIn.stop(d)}},handleStartAnimateIn:function(e,d,f){},handleTweenAnimateIn:function(e,d,f){},handleCompleteAnimateIn:function(e,d,f){},handleStartAnimateOut:function(e,d,f){},handleTweenAnimateOut:function(e,d,f){},handleCompleteAnimateOut:function(e,d,f){},toString:function(){var d="ContainerEffect";if(this.overlay){d+=" ["+this.overlay.toString()+"]"}return d}};YAHOO.lang.augmentProto(a,YAHOO.util.EventProvider)})();YAHOO.register("container",YAHOO.widget.Module,{version:"2.9.0",build:"2800"});(function(){var a=YAHOO.util.Event,c=YAHOO.lang,b=[],d=function(h,e,f){var g;if(!h||h===f){g=false}else{g=YAHOO.util.Selector.test(h,e)?h:d(h.parentNode,e,f)}return g};c.augmentObject(a,{_createDelegate:function(f,e,g,h){return function(i){var j=this,n=a.getTarget(i),l=e,p=(j.nodeType===9),q,k,o,m;if(c.isFunction(e)){q=e(n)}else{if(c.isString(e)){if(!p){o=j.id;if(!o){o=a.generateId(j)}m=("#"+o+" ");l=(m+e).replace(/,/gi,(","+m))}if(YAHOO.util.Selector.test(n,l)){q=n}else{if(YAHOO.util.Selector.test(n,((l.replace(/,/gi," *,"))+" *"))){q=d(n,l,j)}}}}if(q){k=q;if(h){if(h===true){k=g}else{k=h}}return f.call(k,i,q,j,g)}}},delegate:function(f,j,l,g,h,i){var e=j,k,m;if(c.isString(g)&&!YAHOO.util.Selector){return false}if(j=="mouseenter"||j=="mouseleave"){if(!a._createMouseDelegate){return false}e=a._getType(j);k=a._createMouseDelegate(l,h,i);m=a._createDelegate(function(p,o,n){return k.call(o,p,n)},g,h,i)}else{m=a._createDelegate(l,g,h,i)}b.push([f,e,l,m]);return a.on(f,e,m)},removeDelegate:function(f,j,i){var k=j,h=false,g,e;if(j=="mouseenter"||j=="mouseleave"){k=a._getType(j)}g=a._getCacheIndex(b,f,k,i);if(g>=0){e=b[g]}if(f&&e){h=a.removeListener(e[0],e[1],e[3]);if(h){delete b[g][2];delete b[g][3];b.splice(g,1)}}return h}})}());YAHOO.register("event-delegate",YAHOO.util.Event,{version:"2.9.0",build:"2800"});(function(){var l=YAHOO.lang,isFunction=l.isFunction,isObject=l.isObject,isArray=l.isArray,_toStr=Object.prototype.toString,Native=(YAHOO.env.ua.caja?window:this).JSON,_UNICODE_EXCEPTIONS=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,_ESCAPES=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,_VALUES=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,_BRACKETS=/(?:^|:|,)(?:\s*\[)+/g,_UNSAFE=/[^\],:{}\s]/,_SPECIAL_CHARS=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,_CHARS={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},UNDEFINED="undefined",OBJECT="object",NULL="null",STRING="string",NUMBER="number",BOOLEAN="boolean",DATE="date",_allowable={"undefined":UNDEFINED,string:STRING,"[object String]":STRING,number:NUMBER,"[object Number]":NUMBER,"boolean":BOOLEAN,"[object Boolean]":BOOLEAN,"[object Date]":DATE,"[object RegExp]":OBJECT},EMPTY="",OPEN_O="{",CLOSE_O="}",OPEN_A="[",CLOSE_A="]",COMMA=",",COMMA_CR=",\n",CR="\n",COLON=":",COLON_SP=": ",QUOTE='"';Native=_toStr.call(Native)==="[object JSON]"&&Native;function _char(c){if(!_CHARS[c]){_CHARS[c]="\\u"+("0000"+(+(c.charCodeAt(0))).toString(16)).slice(-4)}return _CHARS[c]}function _revive(data,reviver){var walk=function(o,key){var k,v,value=o[key];if(value&&typeof value==="object"){for(k in value){if(l.hasOwnProperty(value,k)){v=walk(value,k);if(v===undefined){delete value[k]}else{value[k]=v}}}}return reviver.call(o,key,value)};return typeof reviver==="function"?walk({"":data},""):data}function _prepare(s){return s.replace(_UNICODE_EXCEPTIONS,_char)}function _isSafe(str){return l.isString(str)&&!_UNSAFE.test(str.replace(_ESCAPES,"@").replace(_VALUES,"]").replace(_BRACKETS,""))}function _parse(s,reviver){s=_prepare(s);if(_isSafe(s)){return _revive(eval("("+s+")"),reviver)}throw new SyntaxError("JSON.parse")}function _type(o){var t=typeof o;return _allowable[t]||_allowable[_toStr.call(o)]||(t===OBJECT?(o?OBJECT:NULL):UNDEFINED)}function _string(s){return QUOTE+s.replace(_SPECIAL_CHARS,_char)+QUOTE}function _indent(s,space){return s.replace(/^/gm,space)}function _stringify(o,w,space){if(o===undefined){return undefined}var replacer=isFunction(w)?w:null,format=_toStr.call(space).match(/String|Number/)||[],_date=YAHOO.lang.JSON.dateToString,stack=[],tmp,i,len;if(replacer||!isArray(w)){w=undefined}if(w){tmp={};for(i=0,len=w.length;i<len;++i){tmp[w[i]]=true}w=tmp}space=format[0]==="Number"?new Array(Math.min(Math.max(0,space),10)+1).join(" "):(space||EMPTY).slice(0,10);function _serialize(h,key){var value=h[key],t=_type(value),a=[],colon=space?COLON_SP:COLON,arr,i,keys,k,v;if(isObject(value)&&isFunction(value.toJSON)){value=value.toJSON(key)}else{if(t===DATE){value=_date(value)}}if(isFunction(replacer)){value=replacer.call(h,key,value)}if(value!==h[key]){t=_type(value)}switch(t){case DATE:case OBJECT:break;case STRING:return _string(value);case NUMBER:return isFinite(value)?value+EMPTY:NULL;case BOOLEAN:return value+EMPTY;case NULL:return NULL;default:return undefined}for(i=stack.length-1;i>=0;--i){if(stack[i]===value){throw new Error("JSON.stringify. Cyclical reference")}}arr=isArray(value);stack.push(value);if(arr){for(i=value.length-1;i>=0;--i){a[i]=_serialize(value,i)||NULL}}else{keys=w||value;i=0;for(k in keys){if(l.hasOwnProperty(keys,k)){v=_serialize(value,k);if(v){a[i++]=_string(k)+colon+v}}}}stack.pop();if(space&&a.length){return arr?OPEN_A+CR+_indent(a.join(COMMA_CR),space)+CR+CLOSE_A:OPEN_O+CR+_indent(a.join(COMMA_CR),space)+CR+CLOSE_O}else{return arr?OPEN_A+a.join(COMMA)+CLOSE_A:OPEN_O+a.join(COMMA)+CLOSE_O}}return _serialize({"":o},"")}YAHOO.lang.JSON={useNativeParse:!!Native,useNativeStringify:!!Native,isSafe:function(s){return _isSafe(_prepare(s))},parse:function(s,reviver){if(typeof s!=="string"){s+=""}return Native&&YAHOO.lang.JSON.useNativeParse?Native.parse(s,reviver):_parse(s,reviver)},stringify:function(o,w,space){return Native&&YAHOO.lang.JSON.useNativeStringify?Native.stringify(o,w,space):_stringify(o,w,space)},dateToString:function(d){function _zeroPad(v){return v<10?"0"+v:v}return d.getUTCFullYear()+"-"+_zeroPad(d.getUTCMonth()+1)+"-"+_zeroPad(d.getUTCDate())+"T"+_zeroPad(d.getUTCHours())+COLON+_zeroPad(d.getUTCMinutes())+COLON+_zeroPad(d.getUTCSeconds())+"Z"},stringToDate:function(str){var m=str.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{3}))?Z$/);if(m){var d=new Date();d.setUTCFullYear(m[1],m[2]-1,m[3]);d.setUTCHours(m[4],m[5],m[6],(m[7]||0));return d}return str}};YAHOO.lang.JSON.isValid=YAHOO.lang.JSON.isSafe})();YAHOO.register("json",YAHOO.lang.JSON,{version:"2.9.0",build:"2800"});YAHOO.util.Chain=function(){this.q=[].slice.call(arguments);this.createEvent("end")};YAHOO.util.Chain.prototype={id:0,run:function(){var g=this.q[0],d;if(!g){this.fireEvent("end");return this}else{if(this.id){return this}}d=g.method||g;if(typeof d==="function"){var f=g.scope||{},b=g.argument||[],a=g.timeout||0,e=this;if(!(b instanceof Array)){b=[b]}if(a<0){this.id=a;if(g.until){for(;!g.until();){d.apply(f,b)}}else{if(g.iterations){for(;g.iterations-->0;){d.apply(f,b)}}else{d.apply(f,b)}}this.q.shift();this.id=0;return this.run()}else{if(g.until){if(g.until()){this.q.shift();return this.run()}}else{if(!g.iterations||!--g.iterations){this.q.shift()}}this.id=setTimeout(function(){d.apply(f,b);if(e.id){e.id=0;e.run()}},a)}}return this},add:function(a){this.q.push(a);return this},pause:function(){if(this.id>0){clearTimeout(this.id)}this.id=0;return this},stop:function(){this.pause();this.q=[];return this}};YAHOO.lang.augmentProto(YAHOO.util.Chain,YAHOO.util.EventProvider);(function(){var a=YAHOO.util.Event,c=YAHOO.lang,b=[],d=function(h,e,f){var g;if(!h||h===f){g=false}else{g=YAHOO.util.Selector.test(h,e)?h:d(h.parentNode,e,f)}return g};c.augmentObject(a,{_createDelegate:function(f,e,g,h){return function(i){var j=this,n=a.getTarget(i),l=e,p=(j.nodeType===9),q,k,o,m;if(c.isFunction(e)){q=e(n)}else{if(c.isString(e)){if(!p){o=j.id;if(!o){o=a.generateId(j)}m=("#"+o+" ");l=(m+e).replace(/,/gi,(","+m))}if(YAHOO.util.Selector.test(n,l)){q=n}else{if(YAHOO.util.Selector.test(n,((l.replace(/,/gi," *,"))+" *"))){q=d(n,l,j)}}}}if(q){k=q;if(h){if(h===true){k=g}else{k=h}}return f.call(k,i,q,j,g)}}},delegate:function(f,j,l,g,h,i){var e=j,k,m;if(c.isString(g)&&!YAHOO.util.Selector){return false}if(j=="mouseenter"||j=="mouseleave"){if(!a._createMouseDelegate){return false}e=a._getType(j);k=a._createMouseDelegate(l,h,i);m=a._createDelegate(function(p,o,n){return k.call(o,p,n)},g,h,i)}else{m=a._createDelegate(l,g,h,i)}b.push([f,e,l,m]);return a.on(f,e,m)},removeDelegate:function(f,j,i){var k=j,h=false,g,e;if(j=="mouseenter"||j=="mouseleave"){k=a._getType(j)}g=a._getCacheIndex(b,f,k,i);if(g>=0){e=b[g]}if(f&&e){h=a.removeListener(e[0],e[1],e[3]);if(h){delete b[g][2];delete b[g][3];b.splice(g,1)}}return h}})}());(function(){var b=YAHOO.util.Event,g=YAHOO.lang,e=b.addListener,f=b.removeListener,c=b.getListeners,d=[],h={mouseenter:"mouseover",mouseleave:"mouseout"},a=function(n,m,l){var j=b._getCacheIndex(d,n,m,l),i,k;if(j>=0){i=d[j]}if(n&&i){k=f.call(b,i[0],m,i[3]);if(k){delete d[j][2];delete d[j][3];d.splice(j,1)}}return k};g.augmentObject(b._specialTypes,h);g.augmentObject(b,{_createMouseDelegate:function(i,j,k){return function(q,m){var p=this,l=b.getRelatedTarget(q),o,n;if(p!=l&&!YAHOO.util.Dom.isAncestor(p,l)){o=p;if(k){if(k===true){o=j}else{o=k}}n=[q,j];if(m){n.splice(1,0,p,m)}return i.apply(o,n)}}},addListener:function(m,l,k,n,o){var i,j;if(h[l]){i=b._createMouseDelegate(k,n,o);i.mouseDelegate=true;d.push([m,l,k,i]);j=e.call(b,m,l,i)}else{j=e.apply(b,arguments)}return j},removeListener:function(l,k,j){var i;if(h[k]){i=a.apply(b,arguments)}else{i=f.apply(b,arguments)}return i},getListeners:function(p,o){var n=[],r,m=(o==="mouseover"||o==="mouseout"),q,k,j;if(o&&(m||h[o])){r=c.call(b,p,this._getType(o));if(r){for(k=r.length-1;k>-1;k--){j=r[k];q=j.fn.mouseDelegate;if((h[o]&&q)||(m&&!q)){n.push(j)}}}}else{n=c.apply(b,arguments)}return(n&&n.length)?n:null}},true);b.on=b.addListener}());YAHOO.register("event-mouseenter",YAHOO.util.Event,{version:"2.9.0",build:"2800"});var Y=YAHOO,Y_DOM=YAHOO.util.Dom,EMPTY_ARRAY=[],Y_UA=Y.env.ua,Y_Lang=Y.lang,Y_DOC=document,Y_DOCUMENT_ELEMENT=Y_DOC.documentElement,Y_DOM_inDoc=Y_DOM.inDocument,Y_mix=Y_Lang.augmentObject,Y_guid=Y_DOM.generateId,Y_getDoc=function(a){var b=Y_DOC;if(a){b=(a.nodeType===9)?a:a.ownerDocument||a.document||Y_DOC}return b},Y_Array=function(g,d){var c,b,h=d||0;try{return Array.prototype.slice.call(g,h)}catch(f){b=[];c=g.length;for(;h<c;h++){b.push(g[h])}return b}},Y_DOM_allById=function(f,a){a=a||Y_DOC;var b=[],c=[],d,e;if(a.querySelectorAll){c=a.querySelectorAll('[id="'+f+'"]')}else{if(a.all){b=a.all(f);if(b){if(b.nodeName){if(b.id===f){c.push(b);b=EMPTY_ARRAY}else{b=[b]}}if(b.length){for(d=0;e=b[d++];){if(e.id===f||(e.attributes&&e.attributes.id&&e.attributes.id.value===f)){c.push(e)}}}}}else{c=[Y_getDoc(a).getElementById(f)]}}return c};var COMPARE_DOCUMENT_POSITION="compareDocumentPosition",OWNER_DOCUMENT="ownerDocument",Selector={_foundCache:[],useNative:true,_compare:("sourceIndex" in Y_DOCUMENT_ELEMENT)?function(f,e){var d=f.sourceIndex,c=e.sourceIndex;if(d===c){return 0}else{if(d>c){return 1}}return -1}:(Y_DOCUMENT_ELEMENT[COMPARE_DOCUMENT_POSITION]?function(b,a){if(b[COMPARE_DOCUMENT_POSITION](a)&4){return -1}else{return 1}}:function(e,d){var c,a,b;if(e&&d){c=e[OWNER_DOCUMENT].createRange();c.setStart(e,0);a=d[OWNER_DOCUMENT].createRange();a.setStart(d,0);b=c.compareBoundaryPoints(1,a)}return b}),_sort:function(a){if(a){a=Y_Array(a,0,true);if(a.sort){a.sort(Selector._compare)}}return a},_deDupe:function(a){var b=[],c,d;for(c=0;(d=a[c++]);){if(!d._found){b[b.length]=d;d._found=true}}for(c=0;(d=b[c++]);){d._found=null;d.removeAttribute("_found")}return b},query:function(b,j,k,a){if(typeof j=="string"){j=Y_DOM.get(j);if(!j){return(k)?null:[]}}else{j=j||Y_DOC}var f=[],c=(Selector.useNative&&Y_DOC.querySelector&&!a),e=[[b,j]],g,l,d,h=(c)?Selector._nativeQuery:Selector._bruteQuery;if(b&&h){if(!a&&(!c||j.tagName)){e=Selector._splitQueries(b,j)}for(d=0;(g=e[d++]);){l=h(g[0],g[1],k);if(!k){l=Y_Array(l,0,true)}if(l){f=f.concat(l)}}if(e.length>1){f=Selector._sort(Selector._deDupe(f))}}Y.log("query: "+b+" returning: "+f.length,"info","Selector");return(k)?(f[0]||null):f},_splitQueries:function(c,f){var b=c.split(","),d=[],g="",e,a;if(f){if(f.tagName){f.id=f.id||Y_guid();g='[id="'+f.id+'"] '}for(e=0,a=b.length;e<a;++e){c=g+b[e];d.push([c,f])}}return d},_nativeQuery:function(a,b,c){if(Y_UA.webkit&&a.indexOf(":checked")>-1&&(Selector.pseudos&&Selector.pseudos.checked)){return Selector.query(a,b,c,true)}try{return b["querySelector"+(c?"":"All")](a)}catch(d){return Selector.query(a,b,c,true)}},filter:function(b,a){var c=[],d,e;if(b&&a){for(d=0;(e=b[d++]);){if(Selector.test(e,a)){c[c.length]=e}}}else{Y.log("invalid filter input (nodes: "+b+", selector: "+a+")","warn","Selector")}return c},test:function(c,d,k){var g=false,b=d.split(","),a=false,l,o,h,n,f,e,m;if(c&&c.tagName){if(!k&&!Y_DOM_inDoc(c)){l=c.parentNode;if(l){k=l}else{n=c[OWNER_DOCUMENT].createDocumentFragment();n.appendChild(c);k=n;a=true}}k=k||c[OWNER_DOCUMENT];if(!c.id){c.id=Y_guid()}for(f=0;(m=b[f++]);){m+='[id="'+c.id+'"]';h=Selector.query(m,k);for(e=0;o=h[e++];){if(o===c){g=true;break}}if(g){break}}if(a){n.removeChild(c)}}return g}};YAHOO.util.Selector=Selector;var PARENT_NODE="parentNode",TAG_NAME="tagName",ATTRIBUTES="attributes",COMBINATOR="combinator",PSEUDOS="pseudos",SelectorCSS2={_reRegExpTokens:/([\^\$\?\[\]\*\+\-\.\(\)\|\\])/,SORT_RESULTS:true,_children:function(e,a){var b=e.children,d,c=[],f,g;if(e.children&&a&&e.children.tags){c=e.children.tags(a)}else{if((!b&&e[TAG_NAME])||(b&&a)){f=b||e.childNodes;b=[];for(d=0;(g=f[d++]);){if(g.tagName){if(!a||a===g.tagName){b.push(g)}}}}}return b||[]},_re:{attr:/(\[[^\]]*\])/g,esc:/\\[:\[\]\(\)#\.\'\>+~"]/gi,pseudos:/(\([^\)]*\))/g},shorthand:{"\\#(-?[_a-z]+[-\\w\\uE000]*)":"[id=$1]","\\.(-?[_a-z]+[-\\w\\uE000]*)":"[className~=$1]"},operators:{"":function(b,a){return !!b.getAttribute(a)},"~=":"(?:^|\\s+){val}(?:\\s+|$)","|=":"^{val}(?:-|$)"},pseudos:{"first-child":function(a){return Selector._children(a[PARENT_NODE])[0]===a}},_bruteQuery:function(f,j,l){var g=[],a=[],i=Selector._tokenize(f),e=i[i.length-1],k=Y_getDoc(j),c,b,h,d;if(e){b=e.id;h=e.className;d=e.tagName||"*";if(j.getElementsByTagName){if(b&&(j.all||(j.nodeType===9||Y_DOM_inDoc(j)))){a=Y_DOM_allById(b,j)}else{if(h){a=j.getElementsByClassName(h)}else{a=j.getElementsByTagName(d)}}}else{c=j.firstChild;while(c){if(c.tagName){a.push(c)}c=c.nextSilbing||c.firstChild}}if(a.length){g=Selector._filterNodes(a,i,l)}}return g},_filterNodes:function(l,f,h){var r=0,q,s=f.length,k=s-1,e=[],o=l[0],v=o,t=Selector.getters,d,p,c,g,a,m,b,u;for(r=0;(v=o=l[r++]);){k=s-1;g=null;testLoop:while(v&&v.tagName){c=f[k];b=c.tests;q=b.length;if(q&&!a){while((u=b[--q])){d=u[1];if(t[u[0]]){m=t[u[0]](v,u[0])}else{m=v[u[0]];if(m===undefined&&v.getAttribute){m=v.getAttribute(u[0])}}if((d==="="&&m!==u[2])||(typeof d!=="string"&&d.test&&!d.test(m))||(!d.test&&typeof d==="function"&&!d(v,u[0],u[2]))){if((v=v[g])){while(v&&(!v.tagName||(c.tagName&&c.tagName!==v.tagName))){v=v[g]}}continue testLoop}}}k--;if(!a&&(p=c.combinator)){g=p.axis;v=v[g];while(v&&!v.tagName){v=v[g]}if(p.direct){g=null}}else{e.push(o);if(h){return e}break}}}o=v=null;return e},combinators:{" ":{axis:"parentNode"},">":{axis:"parentNode",direct:true},"+":{axis:"previousSibling",direct:true}},_parsers:[{name:ATTRIBUTES,re:/^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i,fn:function(d,e){var c=d[2]||"",a=Selector.operators,b=(d[3])?d[3].replace(/\\/g,""):"",f;if((d[1]==="id"&&c==="=")||(d[1]==="className"&&Y_DOCUMENT_ELEMENT.getElementsByClassName&&(c==="~="||c==="="))){e.prefilter=d[1];d[3]=b;e[d[1]]=(d[1]==="id")?d[3]:b}if(c in a){f=a[c];if(typeof f==="string"){d[3]=b.replace(Selector._reRegExpTokens,"\\$1");f=new RegExp(f.replace("{val}",d[3]))}d[2]=f}if(!e.last||e.prefilter!==d[1]){return d.slice(1)}}},{name:TAG_NAME,re:/^((?:-?[_a-z]+[\w-]*)|\*)/i,fn:function(b,c){var a=b[1].toUpperCase();c.tagName=a;if(a!=="*"&&(!c.last||c.prefilter)){return[TAG_NAME,"=",a]}if(!c.prefilter){c.prefilter="tagName"}}},{name:COMBINATOR,re:/^\s*([>+~]|\s)\s*/,fn:function(a,b){}},{name:PSEUDOS,re:/^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i,fn:function(a,b){var c=Selector[PSEUDOS][a[1]];if(c){if(a[2]){a[2]=a[2].replace(/\\/g,"")}return[a[2],c]}else{return false}}}],_getToken:function(a){return{tagName:null,id:null,className:null,attributes:{},combinator:null,tests:[]}},_tokenize:function(c){c=c||"";c=Selector._replaceShorthand(Y_Lang.trim(c));var b=Selector._getToken(),h=c,g=[],j=false,e,f,d,a;outer:do{j=false;for(d=0;(a=Selector._parsers[d++]);){if((e=a.re.exec(c))){if(a.name!==COMBINATOR){b.selector=c}c=c.replace(e[0],"");if(!c.length){b.last=true}if(Selector._attrFilters[e[1]]){e[1]=Selector._attrFilters[e[1]]}f=a.fn(e,b);if(f===false){j=false;break outer}else{if(f){b.tests.push(f)}}if(!c.length||a.name===COMBINATOR){g.push(b);b=Selector._getToken(b);if(a.name===COMBINATOR){b.combinator=Selector.combinators[e[1]]}}j=true}}}while(j&&c.length);if(!j||c.length){Y.log("query: "+h+" contains unsupported token in: "+c,"warn","Selector");g=[]}return g},_replaceShorthand:function(b){var d=Selector.shorthand,c=b.match(Selector._re.esc),e,h,g,f,a;if(c){b=b.replace(Selector._re.esc,"\uE000")}e=b.match(Selector._re.attr);h=b.match(Selector._re.pseudos);if(e){b=b.replace(Selector._re.attr,"\uE001")}if(h){b=b.replace(Selector._re.pseudos,"\uE002")}for(g in d){if(d.hasOwnProperty(g)){b=b.replace(new RegExp(g,"gi"),d[g])}}if(e){for(f=0,a=e.length;f<a;++f){b=b.replace(/\uE001/,e[f])}}if(h){for(f=0,a=h.length;f<a;++f){b=b.replace(/\uE002/,h[f])}}b=b.replace(/\[/g,"\uE003");b=b.replace(/\]/g,"\uE004");b=b.replace(/\(/g,"\uE005");b=b.replace(/\)/g,"\uE006");if(c){for(f=0,a=c.length;f<a;++f){b=b.replace("\uE000",c[f])}}return b},_attrFilters:{"class":"className","for":"htmlFor"},getters:{href:function(b,a){return Y_DOM.getAttribute(b,a)}}};Y_mix(Selector,SelectorCSS2,true);Selector.getters.src=Selector.getters.rel=Selector.getters.href;if(Selector.useNative&&Y_DOC.querySelector){Selector.shorthand["\\.([^\\s\\\\(\\[:]*)"]="[class~=$1]"}Selector._reNth=/^(?:([\-]?\d*)(n){1}|(odd|even)$)*([\-+]?\d*)$/;Selector._getNth=function(d,o,q,h){Selector._reNth.test(o);var m=parseInt(RegExp.$1,10),c=RegExp.$2,j=RegExp.$3,k=parseInt(RegExp.$4,10)||0,p=[],l=Selector._children(d.parentNode,q),f;if(j){m=2;f="+";c="n";k=(j==="odd")?1:0}else{if(isNaN(m)){m=(c)?1:0}}if(m===0){if(h){k=l.length-k+1}if(l[k-1]===d){return true}else{return false}}else{if(m<0){h=!!h;m=Math.abs(m)}}if(!h){for(var e=k-1,g=l.length;e<g;e+=m){if(e>=0&&l[e]===d){return true}}}else{for(var e=l.length-k,g=l.length;e>=0;e-=m){if(e<g&&l[e]===d){return true}}}return false};Y_mix(Selector.pseudos,{root:function(a){return a===a.ownerDocument.documentElement},"nth-child":function(a,b){return Selector._getNth(a,b)},"nth-last-child":function(a,b){return Selector._getNth(a,b,null,true)},"nth-of-type":function(a,b){return Selector._getNth(a,b,a.tagName)},"nth-last-of-type":function(a,b){return Selector._getNth(a,b,a.tagName,true)},"last-child":function(b){var a=Selector._children(b.parentNode);return a[a.length-1]===b},"first-of-type":function(a){return Selector._children(a.parentNode,a.tagName)[0]===a},"last-of-type":function(b){var a=Selector._children(b.parentNode,b.tagName);return a[a.length-1]===b},"only-child":function(b){var a=Selector._children(b.parentNode);return a.length===1&&a[0]===b},"only-of-type":function(b){var a=Selector._children(b.parentNode,b.tagName);return a.length===1&&a[0]===b},empty:function(a){return a.childNodes.length===0},not:function(a,b){return !Selector.test(a,b)},contains:function(a,b){var c=a.innerText||a.textContent||"";return c.indexOf(b)>-1},checked:function(a){return(a.checked===true||a.selected===true)},enabled:function(a){return(a.disabled!==undefined&&!a.disabled)},disabled:function(a){return(a.disabled)}});Y_mix(Selector.operators,{"^=":"^{val}","!=":function(b,a,c){return b[a]!==c},"$=":"{val}$","*=":"{val}"});Selector.combinators["~"]={axis:"previousSibling"};YAHOO.register("selector",YAHOO.util.Selector,{version:"2.9.0",build:"2800"});var Dom=YAHOO.util.Dom;YAHOO.widget.ColumnSet=function(a){this._sId=Dom.generateId(null,"yui-cs");a=YAHOO.widget.DataTable._cloneObject(a);this._init(a);YAHOO.widget.ColumnSet._nCount++};YAHOO.widget.ColumnSet._nCount=0;YAHOO.widget.ColumnSet.prototype={_sId:null,_aDefinitions:null,tree:null,flat:null,keys:null,headers:null,_init:function(j){var k=[];var a=[];var g=[];var e=[];var c=-1;var b=function(m,s){c++;if(!k[c]){k[c]=[]}for(var o=0;o<m.length;o++){var i=m[o];var q=new YAHOO.widget.Column(i);i.yuiColumnId=q._sId;a.push(q);if(s){q._oParent=s}if(YAHOO.lang.isArray(i.children)){q.children=i.children;var r=0;var p=function(v){var w=v.children;for(var u=0;u<w.length;u++){if(YAHOO.lang.isArray(w[u].children)){p(w[u])}else{r++}}};p(i);q._nColspan=r;var t=i.children;for(var n=0;n<t.length;n++){var l=t[n];if(q.className&&(l.className===undefined)){l.className=q.className}if(q.editor&&(l.editor===undefined)){l.editor=q.editor}if(q.editorOptions&&(l.editorOptions===undefined)){l.editorOptions=q.editorOptions}if(q.formatter&&(l.formatter===undefined)){l.formatter=q.formatter}if(q.resizeable&&(l.resizeable===undefined)){l.resizeable=q.resizeable}if(q.sortable&&(l.sortable===undefined)){l.sortable=q.sortable}if(q.hidden){l.hidden=true}if(q.width&&(l.width===undefined)){l.width=q.width}if(q.minWidth&&(l.minWidth===undefined)){l.minWidth=q.minWidth}if(q.maxAutoWidth&&(l.maxAutoWidth===undefined)){l.maxAutoWidth=q.maxAutoWidth}if(q.type&&(l.type===undefined)){l.type=q.type}if(q.type&&!q.formatter){q.formatter=q.type}if(q.text&&!YAHOO.lang.isValue(q.label)){q.label=q.text}if(q.parser){}if(q.sortOptions&&((q.sortOptions.ascFunction)||(q.sortOptions.descFunction))){}}if(!k[c+1]){k[c+1]=[]}b(t,q)}else{q._nKeyIndex=g.length;q._nColspan=1;g.push(q)}k[c].push(q)}c--};if(YAHOO.lang.isArray(j)){b(j);this._aDefinitions=j}else{return null}var f;var d=function(l){var n=1;var q;var o;var r=function(t,p){p=p||1;for(var u=0;u<t.length;u++){var m=t[u];if(YAHOO.lang.isArray(m.children)){p++;r(m.children,p);p--}else{if(p>n){n=p}}}};for(var i=0;i<l.length;i++){q=l[i];r(q);for(var s=0;s<q.length;s++){o=q[s];if(!YAHOO.lang.isArray(o.children)){o._nRowspan=n}else{o._nRowspan=1}}n=1}};d(k);for(f=0;f<k[0].length;f++){k[0][f]._nTreeIndex=f}var h=function(l,m){e[l].push(m.getSanitizedKey());if(m._oParent){h(l,m._oParent)}};for(f=0;f<g.length;f++){e[f]=[];h(f,g[f]);e[f]=e[f].reverse()}this.tree=k;this.flat=a;this.keys=g;this.headers=e},getId:function(){return this._sId},toString:function(){return"ColumnSet instance "+this._sId},getDefinitions:function(){var a=this._aDefinitions;var b=function(e,g){for(var d=0;d<e.length;d++){var f=e[d];var i=g.getColumnById(f.yuiColumnId);if(i){var h=i.getDefinition();for(var c in h){if(YAHOO.lang.hasOwnProperty(h,c)){f[c]=h[c]}}}if(YAHOO.lang.isArray(f.children)){b(f.children,g)}}};b(a,this);this._aDefinitions=a;return a},getColumnById:function(c){if(YAHOO.lang.isString(c)){var a=this.flat;for(var b=a.length-1;b>-1;b--){if(a[b]._sId===c){return a[b]}}}return null},getColumn:function(c){if(YAHOO.lang.isNumber(c)&&this.keys[c]){return this.keys[c]}else{if(YAHOO.lang.isString(c)){var a=this.flat;var d=[];for(var b=0;b<a.length;b++){if(a[b].key===c){d.push(a[b])}}if(d.length===1){return d[0]}else{if(d.length>1){return d}}}}return null},getDescendants:function(d){var b=this;var c=[];var a;var e=function(f){c.push(f);if(f.children){for(a=0;a<f.children.length;a++){e(b.getColumn(f.children[a].key))}}};e(d);return c}};YAHOO.widget.Column=function(b){this._sId=Dom.generateId(null,"yui-col");if(b&&YAHOO.lang.isObject(b)){for(var a in b){if(a){this[a]=b[a]}}}if(!YAHOO.lang.isValue(this.key)){this.key=Dom.generateId(null,"yui-dt-col")}if(!YAHOO.lang.isValue(this.field)){this.field=this.key}YAHOO.widget.Column._nCount++;if(this.width&&!YAHOO.lang.isNumber(this.width)){this.width=null}if(this.editor&&YAHOO.lang.isString(this.editor)){this.editor=new YAHOO.widget.CellEditor(this.editor,this.editorOptions)}};YAHOO.lang.augmentObject(YAHOO.widget.Column,{_nCount:0,formatCheckbox:function(b,a,c,d){YAHOO.widget.DataTable.formatCheckbox(b,a,c,d)},formatCurrency:function(b,a,c,d){YAHOO.widget.DataTable.formatCurrency(b,a,c,d)},formatDate:function(b,a,c,d){YAHOO.widget.DataTable.formatDate(b,a,c,d)},formatEmail:function(b,a,c,d){YAHOO.widget.DataTable.formatEmail(b,a,c,d)},formatLink:function(b,a,c,d){YAHOO.widget.DataTable.formatLink(b,a,c,d)},formatNumber:function(b,a,c,d){YAHOO.widget.DataTable.formatNumber(b,a,c,d)},formatSelect:function(b,a,c,d){YAHOO.widget.DataTable.formatDropdown(b,a,c,d)}});YAHOO.widget.Column.prototype={_sId:null,_nKeyIndex:null,_nTreeIndex:null,_nColspan:1,_nRowspan:1,_oParent:null,_elTh:null,_elThLiner:null,_elThLabel:null,_elResizer:null,_nWidth:null,_dd:null,_ddResizer:null,key:null,field:null,label:null,abbr:null,children:null,width:null,minWidth:null,maxAutoWidth:null,hidden:false,selected:false,className:null,formatter:null,currencyOptions:null,dateOptions:null,dropdownOptions:null,editor:null,resizeable:false,sortable:false,sortOptions:null,getId:function(){return this._sId},toString:function(){return"Column instance "+this._sId},getDefinition:function(){var a={};a.abbr=this.abbr;a.className=this.className;a.editor=this.editor;a.editorOptions=this.editorOptions;a.field=this.field;a.formatter=this.formatter;a.hidden=this.hidden;a.key=this.key;a.label=this.label;a.minWidth=this.minWidth;a.maxAutoWidth=this.maxAutoWidth;a.resizeable=this.resizeable;a.selected=this.selected;a.sortable=this.sortable;a.sortOptions=this.sortOptions;a.width=this.width;a._calculatedWidth=this._calculatedWidth;return a},getKey:function(){return this.key},getField:function(){return this.field},getSanitizedKey:function(){return this.getKey().replace(/[^\w\-]/g,"")},getKeyIndex:function(){return this._nKeyIndex},getTreeIndex:function(){return this._nTreeIndex},getParent:function(){return this._oParent},getColspan:function(){return this._nColspan},getColSpan:function(){return this.getColspan()},getRowspan:function(){return this._nRowspan},getThEl:function(){return this._elTh},getThLinerEl:function(){return this._elThLiner},getResizerEl:function(){return this._elResizer},getColEl:function(){return this.getThEl()},getIndex:function(){return this.getKeyIndex()},format:function(){}};YAHOO.util.Sort={compare:function(d,c,e){if((d===null)||(typeof d=="undefined")){if((c===null)||(typeof c=="undefined")){return 0}else{return 1}}else{if((c===null)||(typeof c=="undefined")){return -1}}if(d.constructor==String){d=d.toLowerCase()}if(c.constructor==String){c=c.toLowerCase()}if(d<c){return(e)?1:-1}else{if(d>c){return(e)?-1:1}else{return 0}}}};YAHOO.widget.ColumnDD=function(d,a,c,b){if(d&&a&&c&&b){this.datatable=d;this.table=d.getTableEl();this.column=a;this.headCell=c;this.pointer=b;this.newIndex=null;this.init(c);this.initFrame();this.invalidHandleTypes={};this.setPadding(10,0,(this.datatable.getTheadEl().offsetHeight+10),0);YAHOO.util.Event.on(window,"resize",function(){this.initConstraints()},this,true)}else{}};if(YAHOO.util.DDProxy){YAHOO.extend(YAHOO.widget.ColumnDD,YAHOO.util.DDProxy,{initConstraints:function(){var g=YAHOO.util.Dom.getRegion(this.table),d=this.getEl(),f=YAHOO.util.Dom.getXY(d),c=parseInt(YAHOO.util.Dom.getStyle(d,"width"),10),a=parseInt(YAHOO.util.Dom.getStyle(d,"height"),10),e=((f[0]-g.left)+15),b=((g.right-f[0]-c)+15);this.setXConstraint(e,b);this.setYConstraint(10,10)},_resizeProxy:function(){YAHOO.widget.ColumnDD.superclass._resizeProxy.apply(this,arguments);var a=this.getDragEl(),b=this.getEl();YAHOO.util.Dom.setStyle(this.pointer,"height",(this.table.parentNode.offsetHeight+10)+"px");YAHOO.util.Dom.setStyle(this.pointer,"display","block");var c=YAHOO.util.Dom.getXY(b);YAHOO.util.Dom.setXY(this.pointer,[c[0],(c[1]-5)]);YAHOO.util.Dom.setStyle(a,"height",this.datatable.getContainerEl().offsetHeight+"px");YAHOO.util.Dom.setStyle(a,"width",(parseInt(YAHOO.util.Dom.getStyle(a,"width"),10)+4)+"px");YAHOO.util.Dom.setXY(this.dragEl,c)},onMouseDown:function(){this.initConstraints();this.resetConstraints()},clickValidator:function(b){if(!this.column.hidden){var a=YAHOO.util.Event.getTarget(b);return(this.isValidHandleChild(a)&&(this.id==this.handleElId||this.DDM.handleWasClicked(a,this.id)))}},onDragOver:function(h,a){var f=this.datatable.getColumn(a);if(f){var c=f.getTreeIndex();while((c===null)&&f.getParent()){f=f.getParent();c=f.getTreeIndex()}if(c!==null){var b=f.getThEl();var k=c;var d=YAHOO.util.Event.getPageX(h),i=YAHOO.util.Dom.getX(b),j=i+((YAHOO.util.Dom.get(b).offsetWidth)/2),e=this.column.getTreeIndex();if(d<j){YAHOO.util.Dom.setX(this.pointer,i)}else{var g=parseInt(b.offsetWidth,10);YAHOO.util.Dom.setX(this.pointer,(i+g));k++}if(c>e){k--}if(k<0){k=0}else{if(k>this.datatable.getColumnSet().tree[0].length){k=this.datatable.getColumnSet().tree[0].length}}this.newIndex=k}}},onDragDrop:function(){this.datatable.reorderColumn(this.column,this.newIndex)},endDrag:function(){this.newIndex=null;YAHOO.util.Dom.setStyle(this.pointer,"display","none")}})}YAHOO.util.ColumnResizer=function(e,c,d,a,b){if(e&&c&&d&&a){this.datatable=e;this.column=c;this.headCell=d;this.headCellLiner=c.getThLinerEl();this.resizerLiner=d.firstChild;this.init(a,a,{dragOnly:true,dragElId:b.id});this.initFrame();this.resetResizerEl();this.setPadding(0,1,0,0)}else{}};if(YAHOO.util.DD){YAHOO.extend(YAHOO.util.ColumnResizer,YAHOO.util.DDProxy,{resetResizerEl:function(){var a=YAHOO.util.Dom.get(this.handleElId).style;a.left="auto";a.right=0;a.top="auto";a.bottom=0;a.height=this.headCell.offsetHeight+"px"},onMouseUp:function(h){var f=this.datatable.getColumnSet().keys,b;for(var c=0,a=f.length;c<a;c++){b=f[c];if(b._ddResizer){b._ddResizer.resetResizerEl()}}this.resetResizerEl();var d=this.headCellLiner;var g=d.offsetWidth-(parseInt(YAHOO.util.Dom.getStyle(d,"paddingLeft"),10)|0)-(parseInt(YAHOO.util.Dom.getStyle(d,"paddingRight"),10)|0);this.datatable.fireEvent("columnResizeEvent",{column:this.column,target:this.headCell,width:g})},onMouseDown:function(a){this.startWidth=this.headCellLiner.offsetWidth;this.startX=YAHOO.util.Event.getXY(a)[0];this.nLinerPadding=(parseInt(YAHOO.util.Dom.getStyle(this.headCellLiner,"paddingLeft"),10)|0)+(parseInt(YAHOO.util.Dom.getStyle(this.headCellLiner,"paddingRight"),10)|0)},clickValidator:function(b){if(!this.column.hidden){var a=YAHOO.util.Event.getTarget(b);return(this.isValidHandleChild(a)&&(this.id==this.handleElId||this.DDM.handleWasClicked(a,this.id)))}},startDrag:function(){var e=this.datatable.getColumnSet().keys,d=this.column.getKeyIndex(),b;for(var c=0,a=e.length;c<a;c++){b=e[c];if(b._ddResizer){YAHOO.util.Dom.get(b._ddResizer.handleElId).style.height="1em"}}},onDrag:function(c){var d=YAHOO.util.Event.getXY(c)[0];if(d>YAHOO.util.Dom.getX(this.headCellLiner)){var a=d-this.startX;var b=this.startWidth+a-this.nLinerPadding;if(b>0){this.datatable.setColumnWidth(this.column,b)}}}})}(function(){var g=YAHOO.lang,a=YAHOO.util,e=YAHOO.widget,c=a.Dom,f=a.Event,d=e.DataTable;YAHOO.widget.RecordSet=function(h){this._init(h)};var b=e.RecordSet;b._nCount=0;b.prototype={_sId:null,_init:function(h){this._sId=c.generateId(null,"yui-rs");e.RecordSet._nCount++;this._records=[];this._initEvents();if(h){if(g.isArray(h)){this.addRecords(h)}else{if(g.isObject(h)){this.addRecord(h)}}}},_initEvents:function(){this.createEvent("recordAddEvent");this.createEvent("recordsAddEvent");this.createEvent("recordSetEvent");this.createEvent("recordsSetEvent");this.createEvent("recordUpdateEvent");this.createEvent("recordDeleteEvent");this.createEvent("recordsDeleteEvent");this.createEvent("resetEvent");this.createEvent("recordValueUpdateEvent")},_addRecord:function(j,h){var i=new YAHOO.widget.Record(j);if(YAHOO.lang.isNumber(h)&&(h>-1)){this._records.splice(h,0,i)}else{this._records[this._records.length]=i}return i},_setRecord:function(i,h){if(!g.isNumber(h)||h<0){h=this._records.length}return(this._records[h]=new e.Record(i))},_deleteRecord:function(i,h){if(!g.isNumber(h)||(h<0)){h=1}this._records.splice(i,h)},getId:function(){return this._sId},toString:function(){return"RecordSet instance "+this._sId},getLength:function(){return this._records.length},getRecord:function(h){var j;if(h instanceof e.Record){for(j=0;j<this._records.length;j++){if(this._records[j]&&(this._records[j]._sId===h._sId)){return h}}}else{if(g.isNumber(h)){if((h>-1)&&(h<this.getLength())){return this._records[h]}}else{if(g.isString(h)){for(j=0;j<this._records.length;j++){if(this._records[j]&&(this._records[j]._sId===h)){return this._records[j]}}}}}return null},getRecords:function(i,h){if(!g.isNumber(i)){return this._records}if(!g.isNumber(h)){return this._records.slice(i)}return this._records.slice(i,i+h)},hasRecords:function(j,h){var l=this.getRecords(j,h);for(var k=0;k<h;++k){if(typeof l[k]==="undefined"){return false}}return true},getRecordIndex:function(j){if(j){for(var h=this._records.length-1;h>-1;h--){if(this._records[h]&&j.getId()===this._records[h].getId()){return h}}}return null},addRecord:function(j,h){if(g.isObject(j)){var i=this._addRecord(j,h);this.fireEvent("recordAddEvent",{record:i,data:j});return i}else{return null}},addRecords:function(m,l){if(g.isArray(m)){var p=[],j,n,h;l=g.isNumber(l)?l:this._records.length;j=l;for(n=0,h=m.length;n<h;++n){if(g.isObject(m[n])){var k=this._addRecord(m[n],j++);p.push(k)}}this.fireEvent("recordsAddEvent",{records:p,data:m});return p}else{if(g.isObject(m)){var o=this._addRecord(m);this.fireEvent("recordsAddEvent",{records:[o],data:m});return o}else{return null}}},setRecord:function(j,h){if(g.isObject(j)){var i=this._setRecord(j,h);this.fireEvent("recordSetEvent",{record:i,data:j});return i}else{return null}},setRecords:function(o,n){var r=e.Record,k=g.isArray(o)?o:[o],q=[],p=0,h=k.length,m=0;n=parseInt(n,10)|0;for(;p<h;++p){if(typeof k[p]==="object"&&k[p]){q[m++]=this._records[n+p]=new r(k[p])}}this.fireEvent("recordsSetEvent",{records:q,data:o});this.fireEvent("recordsSet",{records:q,data:o});if(k.length&&!q.length){}return q},updateRecord:function(h,l){var j=this.getRecord(h);if(j&&g.isObject(l)){var k={};for(var i in j._oData){if(g.hasOwnProperty(j._oData,i)){k[i]=j._oData[i]}}j._oData=l;this.fireEvent("recordUpdateEvent",{record:j,newData:l,oldData:k});return j}else{return null}},updateKey:function(h,i,j){this.updateRecordValue(h,i,j)},updateRecordValue:function(h,k,n){var j=this.getRecord(h);if(j){var m=null;var l=j._oData[k];if(l&&g.isObject(l)){m={};for(var i in l){if(g.hasOwnProperty(l,i)){m[i]=l[i]}}}else{m=l}j._oData[k]=n;this.fireEvent("keyUpdateEvent",{record:j,key:k,newData:n,oldData:m});this.fireEvent("recordValueUpdateEvent",{record:j,key:k,newData:n,oldData:m})}else{}},replaceRecords:function(h){this.reset();return this.addRecords(h)},sortRecords:function(h,j,i){return this._records.sort(function(l,k){return h(l,k,j,i)})},reverseRecords:function(){return this._records.reverse()},deleteRecord:function(h){if(g.isNumber(h)&&(h>-1)&&(h<this.getLength())){var i=this.getRecord(h).getData();this._deleteRecord(h);this.fireEvent("recordDeleteEvent",{data:i,index:h});return i}else{return null}},deleteRecords:function(k,h){if(!g.isNumber(h)){h=1}if(g.isNumber(k)&&(k>-1)&&(k<this.getLength())){var m=this.getRecords(k,h);var j=[],n=[];for(var l=0;l<m.length;l++){j[j.length]=m[l];n[n.length]=m[l].getData()}this._deleteRecord(k,h);this.fireEvent("recordsDeleteEvent",{data:j,deletedData:n,index:k});return j}else{return null}},reset:function(){this._records=[];this.fireEvent("resetEvent")}};g.augmentProto(b,a.EventProvider);YAHOO.widget.Record=function(h){this._nCount=e.Record._nCount;this._sId=c.generateId(null,"yui-rec");e.Record._nCount++;this._oData={};if(g.isObject(h)){for(var i in h){if(g.hasOwnProperty(h,i)){this._oData[i]=h[i]}}}};YAHOO.widget.Record._nCount=0;YAHOO.widget.Record.prototype={_nCount:null,_sId:null,_oData:null,getCount:function(){return this._nCount},getId:function(){return this._sId},getData:function(h){if(g.isString(h)){return this._oData[h]}else{return this._oData}},setData:function(h,i){this._oData[h]=i}}})();(function(){var h=YAHOO.lang,a=YAHOO.util,e=YAHOO.widget,b=YAHOO.env.ua,c=a.Dom,g=a.Event,f=a.DataSourceBase;YAHOO.widget.DataTable=function(i,m,o,k){var l=e.DataTable;if(k&&k.scrollable){return new YAHOO.widget.ScrollingDataTable(i,m,o,k)}this._nIndex=l._nCount;this._sId=c.generateId(null,"yui-dt");this._oChainRender=new YAHOO.util.Chain();this._oChainRender.subscribe("end",this._onRenderChainEnd,this,true);this._initConfigs(k);this._initDataSource(o);if(!this._oDataSource){return}this._initColumnSet(m);if(!this._oColumnSet){return}this._initRecordSet();if(!this._oRecordSet){}l.superclass.constructor.call(this,i,this.configs);var q=this._initDomElements(i);if(!q){return}this.showTableMessage(this.get("MSG_LOADING"),l.CLASS_LOADING);this._initEvents();l._nCount++;l._nCurrentCount++;var n={success:this.onDataReturnSetRows,failure:this.onDataReturnSetRows,scope:this,argument:this.getState()};var p=this.get("initialLoad");if(p===true){this._oDataSource.sendRequest(this.get("initialRequest"),n)}else{if(p===false){this.showTableMessage(this.get("MSG_EMPTY"),l.CLASS_EMPTY)}else{var j=p||{};n.argument=j.argument||{};this._oDataSource.sendRequest(j.request,n)}}};var d=e.DataTable;h.augmentObject(d,{CLASS_DATATABLE:"yui-dt",CLASS_LINER:"yui-dt-liner",CLASS_LABEL:"yui-dt-label",CLASS_MESSAGE:"yui-dt-message",CLASS_MASK:"yui-dt-mask",CLASS_DATA:"yui-dt-data",CLASS_COLTARGET:"yui-dt-coltarget",CLASS_RESIZER:"yui-dt-resizer",CLASS_RESIZERLINER:"yui-dt-resizerliner",CLASS_RESIZERPROXY:"yui-dt-resizerproxy",CLASS_EDITOR:"yui-dt-editor",CLASS_EDITOR_SHIM:"yui-dt-editor-shim",CLASS_PAGINATOR:"yui-dt-paginator",CLASS_PAGE:"yui-dt-page",CLASS_DEFAULT:"yui-dt-default",CLASS_PREVIOUS:"yui-dt-previous",CLASS_NEXT:"yui-dt-next",CLASS_FIRST:"yui-dt-first",CLASS_LAST:"yui-dt-last",CLASS_REC:"yui-dt-rec",CLASS_EVEN:"yui-dt-even",CLASS_ODD:"yui-dt-odd",CLASS_SELECTED:"yui-dt-selected",CLASS_HIGHLIGHTED:"yui-dt-highlighted",CLASS_HIDDEN:"yui-dt-hidden",CLASS_DISABLED:"yui-dt-disabled",CLASS_EMPTY:"yui-dt-empty",CLASS_LOADING:"yui-dt-loading",CLASS_ERROR:"yui-dt-error",CLASS_EDITABLE:"yui-dt-editable",CLASS_DRAGGABLE:"yui-dt-draggable",CLASS_RESIZEABLE:"yui-dt-resizeable",CLASS_SCROLLABLE:"yui-dt-scrollable",CLASS_SORTABLE:"yui-dt-sortable",CLASS_ASC:"yui-dt-asc",CLASS_DESC:"yui-dt-desc",CLASS_BUTTON:"yui-dt-button",CLASS_CHECKBOX:"yui-dt-checkbox",CLASS_DROPDOWN:"yui-dt-dropdown",CLASS_RADIO:"yui-dt-radio",_nCount:0,_nCurrentCount:0,_elDynStyleNode:null,_bDynStylesFallback:(b.ie)?true:false,_oDynStyles:{},_cloneObject:function(m){if(!h.isValue(m)){return m}var p={};if(m instanceof YAHOO.widget.BaseCellEditor){p=m}else{if(Object.prototype.toString.apply(m)==="[object RegExp]"){p=m}else{if(h.isFunction(m)){p=m}else{if(h.isArray(m)){var n=[];for(var l=0,k=m.length;l<k;l++){n[l]=d._cloneObject(m[l])}p=n}else{if(h.isObject(m)){for(var j in m){if(h.hasOwnProperty(m,j)){if(h.isValue(m[j])&&h.isObject(m[j])||h.isArray(m[j])){p[j]=d._cloneObject(m[j])}else{p[j]=m[j]}}}}else{p=m}}}}}return p},formatButton:function(i,j,k,n,m){var l=h.isValue(n)?n:"Click";i.innerHTML='<button type="button" class="'+d.CLASS_BUTTON+'">'+l+"</button>"},formatCheckbox:function(i,j,k,n,m){var l=n;l=(l)?' checked="checked"':"";i.innerHTML='<input type="checkbox"'+l+' class="'+d.CLASS_CHECKBOX+'" />'},formatCurrency:function(j,k,l,n,m){var i=m||this;j.innerHTML=a.Number.format(n,l.currencyOptions||i.get("currencyOptions"))},formatDate:function(j,l,m,o,n){var i=n||this,k=m.dateOptions||i.get("dateOptions");j.innerHTML=a.Date.format(o,k,k.locale)},formatDropdown:function(l,u,q,j,t){var s=t||this,r=(h.isValue(j))?j:u.getData(q.field),v=(h.isArray(q.dropdownOptions))?q.dropdownOptions:null,k,p=l.getElementsByTagName("select");if(p.length===0){k=document.createElement("select");k.className=d.CLASS_DROPDOWN;k=l.appendChild(k);g.addListener(k,"change",s._onDropdownChange,s)}k=p[0];if(k){k.innerHTML="";if(v){for(var n=0;n<v.length;n++){var o=v[n];var m=document.createElement("option");m.value=(h.isValue(o.value))?o.value:o;m.innerHTML=(h.isValue(o.text))?o.text:(h.isValue(o.label))?o.label:o;m=k.appendChild(m);if(m.value==r){m.selected=true}}}else{k.innerHTML='<option selected value="'+r+'">'+r+"</option>"}}else{l.innerHTML=h.isValue(j)?j:""}},formatEmail:function(i,j,k,m,l){if(h.isString(m)){m=h.escapeHTML(m);i.innerHTML='<a href="mailto:'+m+'">'+m+"</a>"}else{i.innerHTML=h.isValue(m)?h.escapeHTML(m.toString()):""}},formatLink:function(i,j,k,m,l){if(h.isString(m)){m=h.escapeHTML(m);i.innerHTML='<a href="'+m+'">'+m+"</a>"}else{i.innerHTML=h.isValue(m)?h.escapeHTML(m.toString()):""}},formatNumber:function(j,k,l,n,m){var i=m||this;j.innerHTML=a.Number.format(n,l.numberOptions||i.get("numberOptions"))},formatRadio:function(j,k,l,o,n){var i=n||this,m=o;m=(m)?' checked="checked"':"";j.innerHTML='<input type="radio"'+m+' name="'+i.getId()+"-col-"+l.getSanitizedKey()+'" class="'+d.CLASS_RADIO+'" />'},formatText:function(i,j,l,n,m){var k=(h.isValue(n))?n:"";i.innerHTML=h.escapeHTML(k.toString())},formatTextarea:function(j,k,m,o,n){var l=(h.isValue(o))?h.escapeHTML(o.toString()):"",i="<textarea>"+l+"</textarea>";j.innerHTML=i},formatTextbox:function(j,k,m,o,n){var l=(h.isValue(o))?h.escapeHTML(o.toString()):"",i='<input type="text" value="'+l+'" />';j.innerHTML=i},formatDefault:function(i,j,k,m,l){i.innerHTML=(h.isValue(m)&&m!=="")?m.toString():"&#160;"},validateNumber:function(j){var i=j*1;if(h.isNumber(i)){return i}else{return undefined}}});d.Formatter={button:d.formatButton,checkbox:d.formatCheckbox,currency:d.formatCurrency,date:d.formatDate,dropdown:d.formatDropdown,email:d.formatEmail,link:d.formatLink,number:d.formatNumber,radio:d.formatRadio,text:d.formatText,textarea:d.formatTextarea,textbox:d.formatTextbox,defaultFormatter:d.formatDefault};h.extend(d,a.Element,{initAttributes:function(i){i=i||{};d.superclass.initAttributes.call(this,i);this.setAttributeConfig("summary",{value:"",validator:h.isString,method:function(j){if(this._elTable){this._elTable.summary=j}}});this.setAttributeConfig("selectionMode",{value:"standard",validator:h.isString});this.setAttributeConfig("sortedBy",{value:null,validator:function(j){if(j){return(h.isObject(j)&&j.key)}else{return(j===null)}},method:function(k){var r=this.get("sortedBy");this._configs.sortedBy.value=k;var j,o,m,q;if(this._elThead){if(r&&r.key&&r.dir){j=this._oColumnSet.getColumn(r.key);o=j.getKeyIndex();var u=j.getThEl();c.removeClass(u,r.dir);this.formatTheadCell(j.getThLinerEl().firstChild,j,k)}if(k){m=(k.column)?k.column:this._oColumnSet.getColumn(k.key);q=m.getKeyIndex();var v=m.getThEl();if(k.dir&&((k.dir=="asc")||(k.dir=="desc"))){var p=(k.dir=="desc")?d.CLASS_DESC:d.CLASS_ASC;c.addClass(v,p)}else{var l=k.dir||d.CLASS_ASC;c.addClass(v,l)}this.formatTheadCell(m.getThLinerEl().firstChild,m,k)}}if(this._elTbody){this._elTbody.style.display="none";var s=this._elTbody.rows,t;for(var n=s.length-1;n>-1;n--){t=s[n].childNodes;if(t[o]){c.removeClass(t[o],r.dir)}if(t[q]){c.addClass(t[q],k.dir)}}this._elTbody.style.display=""}this._clearTrTemplateEl()}});this.setAttributeConfig("paginator",{value:null,validator:function(j){return j===null||j instanceof e.Paginator},method:function(){this._updatePaginator.apply(this,arguments)}});this.setAttributeConfig("caption",{value:null,validator:h.isString,method:function(j){this._initCaptionEl(j)}});this.setAttributeConfig("draggableColumns",{value:false,validator:h.isBoolean,method:function(j){if(this._elThead){if(j){this._initDraggableColumns()}else{this._destroyDraggableColumns()}}}});this.setAttributeConfig("renderLoopSize",{value:0,validator:h.isNumber});this.setAttributeConfig("sortFunction",{value:function(k,j,o,n){var m=YAHOO.util.Sort.compare,l=m(k.getData(n),j.getData(n),o);if(l===0){return m(k.getCount(),j.getCount(),o)}else{return l}}});this.setAttributeConfig("formatRow",{value:null,validator:h.isFunction});this.setAttributeConfig("generateRequest",{value:function(k,n){k=k||{pagination:null,sortedBy:null};var m=encodeURIComponent((k.sortedBy)?k.sortedBy.key:n.getColumnSet().keys[0].getKey());var j=(k.sortedBy&&k.sortedBy.dir===YAHOO.widget.DataTable.CLASS_DESC)?"desc":"asc";var o=(k.pagination)?k.pagination.recordOffset:0;var l=(k.pagination)?k.pagination.rowsPerPage:null;return"sort="+m+"&dir="+j+"&startIndex="+o+((l!==null)?"&results="+l:"")},validator:h.isFunction});this.setAttributeConfig("initialRequest",{value:null});this.setAttributeConfig("initialLoad",{value:true});this.setAttributeConfig("dynamicData",{value:false,validator:h.isBoolean});this.setAttributeConfig("MSG_EMPTY",{value:"No records found.",validator:h.isString});this.setAttributeConfig("MSG_LOADING",{value:"Loading...",validator:h.isString});this.setAttributeConfig("MSG_ERROR",{value:"Data error.",validator:h.isString});this.setAttributeConfig("MSG_SORTASC",{value:"Click to sort ascending",validator:h.isString,method:function(k){if(this._elThead){for(var l=0,m=this.getColumnSet().keys,j=m.length;l<j;l++){if(m[l].sortable&&this.getColumnSortDir(m[l])===d.CLASS_ASC){m[l]._elThLabel.firstChild.title=k}}}}});this.setAttributeConfig("MSG_SORTDESC",{value:"Click to sort descending",validator:h.isString,method:function(k){if(this._elThead){for(var l=0,m=this.getColumnSet().keys,j=m.length;l<j;l++){if(m[l].sortable&&this.getColumnSortDir(m[l])===d.CLASS_DESC){m[l]._elThLabel.firstChild.title=k}}}}});this.setAttributeConfig("currencySymbol",{value:"$",validator:h.isString});this.setAttributeConfig("currencyOptions",{value:{prefix:this.get("currencySymbol"),decimalPlaces:2,decimalSeparator:".",thousandsSeparator:","}});this.setAttributeConfig("dateOptions",{value:{format:"%m/%d/%Y",locale:"en"}});this.setAttributeConfig("numberOptions",{value:{decimalPlaces:0,thousandsSeparator:","}})},_bInit:true,_nIndex:null,_nTrCount:0,_nTdCount:0,_sId:null,_oChainRender:null,_elContainer:null,_elMask:null,_elTable:null,_elCaption:null,_elColgroup:null,_elThead:null,_elTbody:null,_elMsgTbody:null,_elMsgTr:null,_elMsgTd:null,_elColumnDragTarget:null,_elColumnResizerProxy:null,_oDataSource:null,_oColumnSet:null,_oRecordSet:null,_oCellEditor:null,_sFirstTrId:null,_sLastTrId:null,_elTrTemplate:null,_aDynFunctions:[],_disabled:false,clearTextSelection:function(){var i;if(window.getSelection){i=window.getSelection()}else{if(document.getSelection){i=document.getSelection()}else{if(document.selection){i=document.selection}}}if(i){if(i.empty){i.empty()}else{if(i.removeAllRanges){i.removeAllRanges()}else{if(i.collapse){i.collapse()}}}}},_focusEl:function(i){i=i||this._elTbody;setTimeout(function(){try{i.focus()}catch(j){}},0)},_repaintGecko:(b.gecko)?function(j){j=j||this._elContainer;var i=j.parentNode;var k=j.nextSibling;i.insertBefore(i.removeChild(j),k)}:function(){},_repaintOpera:(b.opera)?function(){if(b.opera){document.documentElement.className+=" ";document.documentElement.className=YAHOO.lang.trim(document.documentElement.className)}}:function(){},_repaintWebkit:(b.webkit)?function(j){j=j||this._elContainer;var i=j.parentNode;var k=j.nextSibling;i.insertBefore(i.removeChild(j),k)}:function(){},_initConfigs:function(i){if(!i||!h.isObject(i)){i={}}this.configs=i},_initColumnSet:function(n){var m,k,j;if(this._oColumnSet){for(k=0,j=this._oColumnSet.keys.length;k<j;k++){m=this._oColumnSet.keys[k];d._oDynStyles["."+this.getId()+"-col-"+m.getSanitizedKey()+" ."+d.CLASS_LINER]=undefined;if(m.editor&&m.editor.unsubscribeAll){m.editor.unsubscribeAll()}}this._oColumnSet=null;this._clearTrTemplateEl()}if(h.isArray(n)){this._oColumnSet=new YAHOO.widget.ColumnSet(n)}else{if(n instanceof YAHOO.widget.ColumnSet){this._oColumnSet=n}}var l=this._oColumnSet.keys;for(k=0,j=l.length;k<j;k++){m=l[k];if(m.editor&&m.editor.subscribe){m.editor.subscribe("showEvent",this._onEditorShowEvent,this,true);m.editor.subscribe("keydownEvent",this._onEditorKeydownEvent,this,true);m.editor.subscribe("revertEvent",this._onEditorRevertEvent,this,true);m.editor.subscribe("saveEvent",this._onEditorSaveEvent,this,true);m.editor.subscribe("cancelEvent",this._onEditorCancelEvent,this,true);m.editor.subscribe("blurEvent",this._onEditorBlurEvent,this,true);m.editor.subscribe("blockEvent",this._onEditorBlockEvent,this,true);m.editor.subscribe("unblockEvent",this._onEditorUnblockEvent,this,true)}}},_initDataSource:function(j){this._oDataSource=null;if(j&&(h.isFunction(j.sendRequest))){this._oDataSource=j}else{var k=null;var o=this._elContainer;var l=0;if(o.hasChildNodes()){var n=o.childNodes;for(l=0;l<n.length;l++){if(n[l].nodeName&&n[l].nodeName.toLowerCase()=="table"){k=n[l];break}}if(k){var m=[];for(;l<this._oColumnSet.keys.length;l++){m.push({key:this._oColumnSet.keys[l].key})}this._oDataSource=new f(k);this._oDataSource.responseType=f.TYPE_HTMLTABLE;this._oDataSource.responseSchema={fields:m}}}}},_initRecordSet:function(){if(this._oRecordSet){this._oRecordSet.reset()}else{this._oRecordSet=new YAHOO.widget.RecordSet()}},_initDomElements:function(i){this._initContainerEl(i);this._initTableEl(this._elContainer);this._initColgroupEl(this._elTable);this._initTheadEl(this._elTable);this._initMsgTbodyEl(this._elTable);this._initTbodyEl(this._elTable);if(!this._elContainer||!this._elTable||!this._elColgroup||!this._elThead||!this._elTbody||!this._elMsgTbody){return false}else{return true}},_destroyContainerEl:function(m){var k=this._oColumnSet.keys,l,j;c.removeClass(m,d.CLASS_DATATABLE);g.purgeElement(m);g.purgeElement(this._elThead,true);g.purgeElement(this._elTbody);g.purgeElement(this._elMsgTbody);l=m.getElementsByTagName("select");if(l.length){g.detachListener(l,"change")}for(j=k.length-1;j>=0;--j){if(k[j].editor){g.purgeElement(k[j].editor._elContainer)}}m.innerHTML="";this._elContainer=null;this._elColgroup=null;this._elThead=null;this._elTbody=null},_initContainerEl:function(j){j=c.get(j);if(j&&j.nodeName&&(j.nodeName.toLowerCase()=="div")){this._destroyContainerEl(j);c.addClass(j,d.CLASS_DATATABLE);g.addListener(j,"focus",this._onTableFocus,this);g.addListener(j,"dblclick",this._onTableDblclick,this);this._elContainer=j;var i=document.createElement("div");i.className=d.CLASS_MASK;i.style.display="none";this._elMask=j.appendChild(i)}},_destroyTableEl:function(){var i=this._elTable;if(i){g.purgeElement(i,true);i.parentNode.removeChild(i);this._elCaption=null;this._elColgroup=null;this._elThead=null;this._elTbody=null}},_initCaptionEl:function(i){if(this._elTable&&i){if(!this._elCaption){this._elCaption=this._elTable.createCaption()}this._elCaption.innerHTML=i}else{if(this._elCaption){this._elCaption.parentNode.removeChild(this._elCaption)}}},_initTableEl:function(i){if(i){this._destroyTableEl();this._elTable=i.appendChild(document.createElement("table"));this._elTable.summary=this.get("summary");if(this.get("caption")){this._initCaptionEl(this.get("caption"))}g.delegate(this._elTable,"mouseenter",this._onTableMouseover,"thead ."+d.CLASS_LABEL,this);g.delegate(this._elTable,"mouseleave",this._onTableMouseout,"thead ."+d.CLASS_LABEL,this);g.delegate(this._elTable,"mouseenter",this._onTableMouseover,"tbody.yui-dt-data>tr>td",this);g.delegate(this._elTable,"mouseleave",this._onTableMouseout,"tbody.yui-dt-data>tr>td",this);g.delegate(this._elTable,"mouseenter",this._onTableMouseover,"tbody.yui-dt-message>tr>td",this);g.delegate(this._elTable,"mouseleave",this._onTableMouseout,"tbody.yui-dt-message>tr>td",this)}},_destroyColgroupEl:function(){var i=this._elColgroup;if(i){var j=i.parentNode;g.purgeElement(i,true);j.removeChild(i);this._elColgroup=null}},_initColgroupEl:function(s){if(s){this._destroyColgroupEl();var l=this._aColIds||[],r=this._oColumnSet.keys,m=0,p=l.length,j,o,q=document.createDocumentFragment(),n=document.createElement("col");for(m=0,p=r.length;m<p;m++){o=r[m];j=q.appendChild(n.cloneNode(false))}var k=s.insertBefore(document.createElement("colgroup"),s.firstChild);k.appendChild(q);this._elColgroup=k}},_insertColgroupColEl:function(i){if(h.isNumber(i)&&this._elColgroup){var j=this._elColgroup.childNodes[i]||null;this._elColgroup.insertBefore(document.createElement("col"),j)}},_removeColgroupColEl:function(i){if(h.isNumber(i)&&this._elColgroup&&this._elColgroup.childNodes[i]){this._elColgroup.removeChild(this._elColgroup.childNodes[i])}},_reorderColgroupColEl:function(l,k){if(h.isArray(l)&&h.isNumber(k)&&this._elColgroup&&(this._elColgroup.childNodes.length>l[l.length-1])){var j,n=[];for(j=l.length-1;j>-1;j--){n.push(this._elColgroup.removeChild(this._elColgroup.childNodes[l[j]]))}var m=this._elColgroup.childNodes[k]||null;for(j=n.length-1;j>-1;j--){this._elColgroup.insertBefore(n[j],m)}}},_destroyTheadEl:function(){var j=this._elThead;if(j){var i=j.parentNode;g.purgeElement(j,true);this._destroyColumnHelpers();i.removeChild(j);this._elThead=null}},_initTheadEl:function(v){v=v||this._elTable;if(v){this._destroyTheadEl();var q=(this._elColgroup)?v.insertBefore(document.createElement("thead"),this._elColgroup.nextSibling):v.appendChild(document.createElement("thead"));g.addListener(q,"focus",this._onTheadFocus,this);g.addListener(q,"keydown",this._onTheadKeydown,this);g.addListener(q,"mousedown",this._onTableMousedown,this);g.addListener(q,"mouseup",this._onTableMouseup,this);g.addListener(q,"click",this._onTheadClick,this);var x=this._oColumnSet,t,r,p,n;var w=x.tree;var o;for(r=0;r<w.length;r++){var m=q.appendChild(document.createElement("tr"));for(p=0;p<w[r].length;p++){t=w[r][p];o=m.appendChild(document.createElement("th"));this._initThEl(o,t)}if(r===0){c.addClass(m,d.CLASS_FIRST)}if(r===(w.length-1)){c.addClass(m,d.CLASS_LAST)}}var k=x.headers[0]||[];for(r=0;r<k.length;r++){c.addClass(c.get(this.getId()+"-th-"+k[r]),d.CLASS_FIRST)}var s=x.headers[x.headers.length-1]||[];for(r=0;r<s.length;r++){c.addClass(c.get(this.getId()+"-th-"+s[r]),d.CLASS_LAST)}if(b.webkit&&b.webkit<420){var u=this;setTimeout(function(){q.style.display=""},0);q.style.display="none"}this._elThead=q;this._initColumnHelpers()}},_initThEl:function(m,l){m.id=this.getId()+"-th-"+l.getSanitizedKey();m.innerHTML="";m.rowSpan=l.getRowspan();m.colSpan=l.getColspan();l._elTh=m;var i=m.appendChild(document.createElement("div"));i.id=m.id+"-liner";i.className=d.CLASS_LINER;l._elThLiner=i;var j=i.appendChild(document.createElement("span"));j.className=d.CLASS_LABEL;if(l.abbr){m.abbr=l.abbr}if(l.hidden){this._clearMinWidth(l)}m.className=this._getColumnClassNames(l);if(l.width){var k=(l.minWidth&&(l.width<l.minWidth))?l.minWidth:l.width;if(d._bDynStylesFallback){m.firstChild.style.overflow="hidden";m.firstChild.style.width=k+"px"}else{this._setColumnWidthDynStyles(l,k+"px","hidden")}}this.formatTheadCell(j,l,this.get("sortedBy"));l._elThLabel=j},formatTheadCell:function(i,m,k){var q=m.getKey();var p=h.isValue(m.label)?m.label:q;if(m.sortable){var n=this.getColumnSortDir(m,k);var j=(n===d.CLASS_DESC);if(k&&(m.key===k.key)){j=!(k.dir===d.CLASS_DESC)}var l=this.getId()+"-href-"+m.getSanitizedKey();var o=(j)?this.get("MSG_SORTDESC"):this.get("MSG_SORTASC");i.innerHTML='<a href="'+l+'" title="'+o+'" class="'+d.CLASS_SORTABLE+'">'+p+"</a>"}else{i.innerHTML=p}},_destroyDraggableColumns:function(){var l,m;for(var k=0,j=this._oColumnSet.tree[0].length;k<j;k++){l=this._oColumnSet.tree[0][k];if(l._dd){l._dd=l._dd.unreg();c.removeClass(l.getThEl(),d.CLASS_DRAGGABLE)}}this._destroyColumnDragTargetEl()},_initDraggableColumns:function(){this._destroyDraggableColumns();if(a.DD){var m,n,k;for(var l=0,j=this._oColumnSet.tree[0].length;l<j;l++){m=this._oColumnSet.tree[0][l];n=m.getThEl();c.addClass(n,d.CLASS_DRAGGABLE);k=this._initColumnDragTargetEl();m._dd=new YAHOO.widget.ColumnDD(this,m,n,k)}}else{}},_destroyColumnDragTargetEl:function(){if(this._elColumnDragTarget){var i=this._elColumnDragTarget;YAHOO.util.Event.purgeElement(i);i.parentNode.removeChild(i);this._elColumnDragTarget=null}},_initColumnDragTargetEl:function(){if(!this._elColumnDragTarget){var i=document.createElement("div");i.id=this.getId()+"-coltarget";i.className=d.CLASS_COLTARGET;i.style.display="none";document.body.insertBefore(i,document.body.firstChild);this._elColumnDragTarget=i}return this._elColumnDragTarget},_destroyResizeableColumns:function(){var k=this._oColumnSet.keys;for(var l=0,j=k.length;l<j;l++){if(k[l]._ddResizer){k[l]._ddResizer=k[l]._ddResizer.unreg();c.removeClass(k[l].getThEl(),d.CLASS_RESIZEABLE)}}this._destroyColumnResizerProxyEl()},_initResizeableColumns:function(){this._destroyResizeableColumns();if(a.DD){var p,k,n,q,j,r,m;for(var l=0,o=this._oColumnSet.keys.length;l<o;l++){p=this._oColumnSet.keys[l];if(p.resizeable){k=p.getThEl();c.addClass(k,d.CLASS_RESIZEABLE);n=p.getThLinerEl();q=k.appendChild(document.createElement("div"));q.className=d.CLASS_RESIZERLINER;q.appendChild(n);j=q.appendChild(document.createElement("div"));j.id=k.id+"-resizer";j.className=d.CLASS_RESIZER;p._elResizer=j;r=this._initColumnResizerProxyEl();p._ddResizer=new YAHOO.util.ColumnResizer(this,p,k,j,r);m=function(i){g.stopPropagation(i)};g.addListener(j,"click",m)}}}else{}},_destroyColumnResizerProxyEl:function(){if(this._elColumnResizerProxy){var i=this._elColumnResizerProxy;YAHOO.util.Event.purgeElement(i);i.parentNode.removeChild(i);this._elColumnResizerProxy=null}},_initColumnResizerProxyEl:function(){if(!this._elColumnResizerProxy){var i=document.createElement("div");i.id=this.getId()+"-colresizerproxy";i.className=d.CLASS_RESIZERPROXY;document.body.insertBefore(i,document.body.firstChild);this._elColumnResizerProxy=i}return this._elColumnResizerProxy},_destroyColumnHelpers:function(){this._destroyDraggableColumns();this._destroyResizeableColumns()},_initColumnHelpers:function(){if(this.get("draggableColumns")){this._initDraggableColumns()}this._initResizeableColumns()},_destroyTbodyEl:function(){var i=this._elTbody;if(i){var j=i.parentNode;g.purgeElement(i,true);j.removeChild(i);this._elTbody=null}},_initTbodyEl:function(j){if(j){this._destroyTbodyEl();var i=j.appendChild(document.createElement("tbody"));i.tabIndex=0;i.className=d.CLASS_DATA;g.addListener(i,"focus",this._onTbodyFocus,this);g.addListener(i,"mousedown",this._onTableMousedown,this);g.addListener(i,"mouseup",this._onTableMouseup,this);g.addListener(i,"keydown",this._onTbodyKeydown,this);g.addListener(i,"click",this._onTbodyClick,this);if(b.ie){i.hideFocus=true}this._elTbody=i}},_destroyMsgTbodyEl:function(){var i=this._elMsgTbody;if(i){var j=i.parentNode;g.purgeElement(i,true);j.removeChild(i);this._elTbody=null}},_initMsgTbodyEl:function(l){if(l){var k=document.createElement("tbody");k.className=d.CLASS_MESSAGE;var j=k.appendChild(document.createElement("tr"));j.className=d.CLASS_FIRST+" "+d.CLASS_LAST;this._elMsgTr=j;var m=j.appendChild(document.createElement("td"));m.colSpan=this._oColumnSet.keys.length||1;m.className=d.CLASS_FIRST+" "+d.CLASS_LAST;this._elMsgTd=m;k=l.insertBefore(k,this._elTbody);var i=m.appendChild(document.createElement("div"));i.className=d.CLASS_LINER;this._elMsgTbody=k;g.addListener(k,"focus",this._onTbodyFocus,this);g.addListener(k,"mousedown",this._onTableMousedown,this);g.addListener(k,"mouseup",this._onTableMouseup,this);g.addListener(k,"keydown",this._onTbodyKeydown,this);g.addListener(k,"click",this._onTbodyClick,this)}},_initEvents:function(){this._initColumnSort();YAHOO.util.Event.addListener(document,"click",this._onDocumentClick,this);this.subscribe("paginatorChange",function(){this._handlePaginatorChange.apply(this,arguments)});this.subscribe("initEvent",function(){this.renderPaginator()});this._initCellEditing()},_initColumnSort:function(){this.subscribe("theadCellClickEvent",this.onEventSortColumn);var i=this.get("sortedBy");if(i){if(i.dir=="desc"){this._configs.sortedBy.value.dir=d.CLASS_DESC}else{if(i.dir=="asc"){this._configs.sortedBy.value.dir=d.CLASS_ASC}}}},_initCellEditing:function(){this.subscribe("editorBlurEvent",function(){this.onEditorBlurEvent.apply(this,arguments)});this.subscribe("editorBlockEvent",function(){this.onEditorBlockEvent.apply(this,arguments)});this.subscribe("editorUnblockEvent",function(){this.onEditorUnblockEvent.apply(this,arguments)})},_getColumnClassNames:function(l,k){var i;if(h.isString(l.className)){i=[l.className]}else{if(h.isArray(l.className)){i=l.className}else{i=[]}}i[i.length]=this.getId()+"-col-"+l.getSanitizedKey();i[i.length]="yui-dt-col-"+l.getSanitizedKey();var j=this.get("sortedBy")||{};if(l.key===j.key){i[i.length]=j.dir||""}if(l.hidden){i[i.length]=d.CLASS_HIDDEN}if(l.selected){i[i.length]=d.CLASS_SELECTED}if(l.sortable){i[i.length]=d.CLASS_SORTABLE}if(l.resizeable){i[i.length]=d.CLASS_RESIZEABLE}if(l.editor){i[i.length]=d.CLASS_EDITABLE}if(k){i=i.concat(k)}return i.join(" ")},_clearTrTemplateEl:function(){this._elTrTemplate=null},_getTrTemplateEl:function(u,o){if(this._elTrTemplate){return this._elTrTemplate}else{var q=document,s=q.createElement("tr"),l=q.createElement("td"),k=q.createElement("div");l.appendChild(k);var t=document.createDocumentFragment(),r=this._oColumnSet.keys,n;var p;for(var m=0,j=r.length;m<j;m++){n=l.cloneNode(true);n=this._formatTdEl(r[m],n,m,(m===j-1));t.appendChild(n)}s.appendChild(t);s.className=d.CLASS_REC;this._elTrTemplate=s;return s}},_formatTdEl:function(n,p,q,m){var t=this._oColumnSet;var i=t.headers,k=i[q],o="",v;for(var l=0,u=k.length;l<u;l++){v=this._sId+"-th-"+k[l]+" ";o+=v}p.headers=o;var s=[];if(q===0){s[s.length]=d.CLASS_FIRST}if(m){s[s.length]=d.CLASS_LAST}p.className=this._getColumnClassNames(n,s);p.firstChild.className=d.CLASS_LINER;if(n.width&&d._bDynStylesFallback){var r=(n.minWidth&&(n.width<n.minWidth))?n.minWidth:n.width;p.firstChild.style.overflow="hidden";p.firstChild.style.width=r+"px"}return p},_addTrEl:function(k){var j=this._getTrTemplateEl();var i=j.cloneNode(true);return this._updateTrEl(i,k)},_updateTrEl:function(q,r){var p=this.get("formatRow")?this.get("formatRow").call(this,q,r):true;if(p){q.style.display="none";var o=q.childNodes,m;for(var l=0,n=o.length;l<n;++l){m=o[l];this.formatCell(o[l].firstChild,r,this._oColumnSet.keys[l])}q.style.display=""}var j=q.id,k=r.getId();if(this._sFirstTrId===j){this._sFirstTrId=k}if(this._sLastTrId===j){this._sLastTrId=k}q.id=k;return q},_deleteTrEl:function(i){var j;if(!h.isNumber(i)){j=c.get(i).sectionRowIndex}else{j=i}if(h.isNumber(j)&&(j>-2)&&(j<this._elTbody.rows.length)){return this._elTbody.removeChild(this._elTbody.rows[i])}else{return null}},_unsetFirstRow:function(){if(this._sFirstTrId){c.removeClass(this._sFirstTrId,d.CLASS_FIRST);this._sFirstTrId=null}},_setFirstRow:function(){this._unsetFirstRow();var i=this.getFirstTrEl();if(i){c.addClass(i,d.CLASS_FIRST);this._sFirstTrId=i.id}},_unsetLastRow:function(){if(this._sLastTrId){c.removeClass(this._sLastTrId,d.CLASS_LAST);this._sLastTrId=null}},_setLastRow:function(){this._unsetLastRow();var i=this.getLastTrEl();if(i){c.addClass(i,d.CLASS_LAST);this._sLastTrId=i.id}},_setRowStripes:function(t,l){var m=this._elTbody.rows,q=0,s=m.length,p=[],r=0,n=[],j=0;if((t!==null)&&(t!==undefined)){var o=this.getTrEl(t);if(o){q=o.sectionRowIndex;if(h.isNumber(l)&&(l>1)){s=q+l}}}for(var k=q;k<s;k++){if(k%2){p[r++]=m[k]}else{n[j++]=m[k]}}if(p.length){c.replaceClass(p,d.CLASS_EVEN,d.CLASS_ODD)}if(n.length){c.replaceClass(n,d.CLASS_ODD,d.CLASS_EVEN)}},_setSelections:function(){var l=this.getSelectedRows();var n=this.getSelectedCells();if((l.length>0)||(n.length>0)){var m=this._oColumnSet,k;for(var j=0;j<l.length;j++){k=c.get(l[j]);if(k){c.addClass(k,d.CLASS_SELECTED)}}for(j=0;j<n.length;j++){k=c.get(n[j].recordId);if(k){c.addClass(k.childNodes[m.getColumn(n[j].columnKey).getKeyIndex()],d.CLASS_SELECTED)}}}},_onRenderChainEnd:function(){this.hideTableMessage();if(this._elTbody.rows.length===0){this.showTableMessage(this.get("MSG_EMPTY"),d.CLASS_EMPTY)}var i=this;setTimeout(function(){if((i instanceof d)&&i._sId){if(i._bInit){i._bInit=false;i.fireEvent("initEvent")}i.fireEvent("renderEvent");i.fireEvent("refreshEvent");i.validateColumnWidths();i.fireEvent("postRenderEvent")}},0)},_onDocumentClick:function(l,j){var m=g.getTarget(l);var i=m.nodeName.toLowerCase();if(!c.isAncestor(j._elContainer,m)){j.fireEvent("tableBlurEvent");if(j._oCellEditor){if(j._oCellEditor.getContainerEl){var k=j._oCellEditor.getContainerEl();if(!c.isAncestor(k,m)&&(k.id!==m.id)){j._oCellEditor.fireEvent("blurEvent",{editor:j._oCellEditor})}}else{if(j._oCellEditor.isActive){if(!c.isAncestor(j._oCellEditor.container,m)&&(j._oCellEditor.container.id!==m.id)){j.fireEvent("editorBlurEvent",{editor:j._oCellEditor})}}}}}},_onTableFocus:function(j,i){i.fireEvent("tableFocusEvent")},_onTheadFocus:function(j,i){i.fireEvent("theadFocusEvent");i.fireEvent("tableFocusEvent")},_onTbodyFocus:function(j,i){i.fireEvent("tbodyFocusEvent");i.fireEvent("tableFocusEvent")},_onTableMouseover:function(n,m,i,k){var o=m;var j=o.nodeName&&o.nodeName.toLowerCase();var l=true;while(o&&(j!="table")){switch(j){case"body":return;case"a":break;case"td":l=k.fireEvent("cellMouseoverEvent",{target:o,event:n});break;case"span":if(c.hasClass(o,d.CLASS_LABEL)){l=k.fireEvent("theadLabelMouseoverEvent",{target:o,event:n});l=k.fireEvent("headerLabelMouseoverEvent",{target:o,event:n})}break;case"th":l=k.fireEvent("theadCellMouseoverEvent",{target:o,event:n});l=k.fireEvent("headerCellMouseoverEvent",{target:o,event:n});break;case"tr":if(o.parentNode.nodeName.toLowerCase()=="thead"){l=k.fireEvent("theadRowMouseoverEvent",{target:o,event:n});l=k.fireEvent("headerRowMouseoverEvent",{target:o,event:n})}else{l=k.fireEvent("rowMouseoverEvent",{target:o,event:n})}break;default:break}if(l===false){return}else{o=o.parentNode;if(o){j=o.nodeName.toLowerCase()}}}k.fireEvent("tableMouseoverEvent",{target:(o||k._elContainer),event:n})},_onTableMouseout:function(n,m,i,k){var o=m;var j=o.nodeName&&o.nodeName.toLowerCase();var l=true;while(o&&(j!="table")){switch(j){case"body":return;case"a":break;case"td":l=k.fireEvent("cellMouseoutEvent",{target:o,event:n});break;case"span":if(c.hasClass(o,d.CLASS_LABEL)){l=k.fireEvent("theadLabelMouseoutEvent",{target:o,event:n});l=k.fireEvent("headerLabelMouseoutEvent",{target:o,event:n})}break;case"th":l=k.fireEvent("theadCellMouseoutEvent",{target:o,event:n});l=k.fireEvent("headerCellMouseoutEvent",{target:o,event:n});break;case"tr":if(o.parentNode.nodeName.toLowerCase()=="thead"){l=k.fireEvent("theadRowMouseoutEvent",{target:o,event:n});l=k.fireEvent("headerRowMouseoutEvent",{target:o,event:n})}else{l=k.fireEvent("rowMouseoutEvent",{target:o,event:n})}break;default:break}if(l===false){return}else{o=o.parentNode;if(o){j=o.nodeName.toLowerCase()}}}k.fireEvent("tableMouseoutEvent",{target:(o||k._elContainer),event:n})},_onTableMousedown:function(l,j){var m=g.getTarget(l);var i=m.nodeName&&m.nodeName.toLowerCase();var k=true;while(m&&(i!="table")){switch(i){case"body":return;case"a":break;case"td":k=j.fireEvent("cellMousedownEvent",{target:m,event:l});break;case"span":if(c.hasClass(m,d.CLASS_LABEL)){k=j.fireEvent("theadLabelMousedownEvent",{target:m,event:l});k=j.fireEvent("headerLabelMousedownEvent",{target:m,event:l})}break;case"th":k=j.fireEvent("theadCellMousedownEvent",{target:m,event:l});k=j.fireEvent("headerCellMousedownEvent",{target:m,event:l});break;case"tr":if(m.parentNode.nodeName.toLowerCase()=="thead"){k=j.fireEvent("theadRowMousedownEvent",{target:m,event:l});k=j.fireEvent("headerRowMousedownEvent",{target:m,event:l})}else{k=j.fireEvent("rowMousedownEvent",{target:m,event:l})}break;default:break}if(k===false){return}else{m=m.parentNode;if(m){i=m.nodeName.toLowerCase()}}}j.fireEvent("tableMousedownEvent",{target:(m||j._elContainer),event:l})},_onTableMouseup:function(l,j){var m=g.getTarget(l);var i=m.nodeName&&m.nodeName.toLowerCase();var k=true;while(m&&(i!="table")){switch(i){case"body":return;case"a":break;case"td":k=j.fireEvent("cellMouseupEvent",{target:m,event:l});break;case"span":if(c.hasClass(m,d.CLASS_LABEL)){k=j.fireEvent("theadLabelMouseupEvent",{target:m,event:l});k=j.fireEvent("headerLabelMouseupEvent",{target:m,event:l})}break;case"th":k=j.fireEvent("theadCellMouseupEvent",{target:m,event:l});k=j.fireEvent("headerCellMouseupEvent",{target:m,event:l});break;case"tr":if(m.parentNode.nodeName.toLowerCase()=="thead"){k=j.fireEvent("theadRowMouseupEvent",{target:m,event:l});k=j.fireEvent("headerRowMouseupEvent",{target:m,event:l})}else{k=j.fireEvent("rowMouseupEvent",{target:m,event:l})}break;default:break}if(k===false){return}else{m=m.parentNode;if(m){i=m.nodeName.toLowerCase()}}}j.fireEvent("tableMouseupEvent",{target:(m||j._elContainer),event:l})},_onTableDblclick:function(l,j){var m=g.getTarget(l);var i=m.nodeName&&m.nodeName.toLowerCase();var k=true;while(m&&(i!="table")){switch(i){case"body":return;case"td":k=j.fireEvent("cellDblclickEvent",{target:m,event:l});break;case"span":if(c.hasClass(m,d.CLASS_LABEL)){k=j.fireEvent("theadLabelDblclickEvent",{target:m,event:l});k=j.fireEvent("headerLabelDblclickEvent",{target:m,event:l})}break;case"th":k=j.fireEvent("theadCellDblclickEvent",{target:m,event:l});k=j.fireEvent("headerCellDblclickEvent",{target:m,event:l});break;case"tr":if(m.parentNode.nodeName.toLowerCase()=="thead"){k=j.fireEvent("theadRowDblclickEvent",{target:m,event:l});k=j.fireEvent("headerRowDblclickEvent",{target:m,event:l})}else{k=j.fireEvent("rowDblclickEvent",{target:m,event:l})}break;default:break}if(k===false){return}else{m=m.parentNode;if(m){i=m.nodeName.toLowerCase()}}}j.fireEvent("tableDblclickEvent",{target:(m||j._elContainer),event:l})},_onTheadKeydown:function(l,j){var m=g.getTarget(l);var i=m.nodeName&&m.nodeName.toLowerCase();var k=true;while(m&&(i!="table")){switch(i){case"body":return;case"input":case"textarea":break;case"thead":k=j.fireEvent("theadKeyEvent",{target:m,event:l});break;default:break}if(k===false){return}else{m=m.parentNode;if(m){i=m.nodeName.toLowerCase()}}}j.fireEvent("tableKeyEvent",{target:(m||j._elContainer),event:l})},_onTbodyKeydown:function(m,k){var j=k.get("selectionMode");if(j=="standard"){k._handleStandardSelectionByKey(m)}else{if(j=="single"){k._handleSingleSelectionByKey(m)}else{if(j=="cellblock"){k._handleCellBlockSelectionByKey(m)}else{if(j=="cellrange"){k._handleCellRangeSelectionByKey(m)}else{if(j=="singlecell"){k._handleSingleCellSelectionByKey(m)}}}}}if(k._oCellEditor){if(k._oCellEditor.fireEvent){k._oCellEditor.fireEvent("blurEvent",{editor:k._oCellEditor})}else{if(k._oCellEditor.isActive){k.fireEvent("editorBlurEvent",{editor:k._oCellEditor})}}}var n=g.getTarget(m);var i=n.nodeName&&n.nodeName.toLowerCase();var l=true;while(n&&(i!="table")){switch(i){case"body":return;case"tbody":l=k.fireEvent("tbodyKeyEvent",{target:n,event:m});break;default:break}if(l===false){return}else{n=n.parentNode;if(n){i=n.nodeName.toLowerCase()}}}k.fireEvent("tableKeyEvent",{target:(n||k._elContainer),event:m})},_onTheadClick:function(l,j){if(j._oCellEditor){if(j._oCellEditor.fireEvent){j._oCellEditor.fireEvent("blurEvent",{editor:j._oCellEditor})}else{if(j._oCellEditor.isActive){j.fireEvent("editorBlurEvent",{editor:j._oCellEditor})}}}var m=g.getTarget(l),i=m.nodeName&&m.nodeName.toLowerCase(),k=true;while(m&&(i!="table")){switch(i){case"body":return;case"input":var n=m.type.toLowerCase();if(n=="checkbox"){k=j.fireEvent("theadCheckboxClickEvent",{target:m,event:l})}else{if(n=="radio"){k=j.fireEvent("theadRadioClickEvent",{target:m,event:l})}else{if((n=="button")||(n=="image")||(n=="submit")||(n=="reset")){if(!m.disabled){k=j.fireEvent("theadButtonClickEvent",{target:m,event:l})}else{k=false}}else{if(m.disabled){k=false}}}}break;case"a":k=j.fireEvent("theadLinkClickEvent",{target:m,event:l});break;case"button":if(!m.disabled){k=j.fireEvent("theadButtonClickEvent",{target:m,event:l})}else{k=false}break;case"span":if(c.hasClass(m,d.CLASS_LABEL)){k=j.fireEvent("theadLabelClickEvent",{target:m,event:l});k=j.fireEvent("headerLabelClickEvent",{target:m,event:l})}break;case"th":k=j.fireEvent("theadCellClickEvent",{target:m,event:l});k=j.fireEvent("headerCellClickEvent",{target:m,event:l});break;case"tr":k=j.fireEvent("theadRowClickEvent",{target:m,event:l});k=j.fireEvent("headerRowClickEvent",{target:m,event:l});break;default:break}if(k===false){return}else{m=m.parentNode;if(m){i=m.nodeName.toLowerCase()}}}j.fireEvent("tableClickEvent",{target:(m||j._elContainer),event:l})},_onTbodyClick:function(l,j){if(j._oCellEditor){if(j._oCellEditor.fireEvent){j._oCellEditor.fireEvent("blurEvent",{editor:j._oCellEditor})}else{if(j._oCellEditor.isActive){j.fireEvent("editorBlurEvent",{editor:j._oCellEditor})}}}var m=g.getTarget(l),i=m.nodeName&&m.nodeName.toLowerCase(),k=true;while(m&&(i!="table")){switch(i){case"body":return;case"input":var n=m.type.toLowerCase();if(n=="checkbox"){k=j.fireEvent("checkboxClickEvent",{target:m,event:l})}else{if(n=="radio"){k=j.fireEvent("radioClickEvent",{target:m,event:l})}else{if((n=="button")||(n=="image")||(n=="submit")||(n=="reset")){if(!m.disabled){k=j.fireEvent("buttonClickEvent",{target:m,event:l})}else{k=false}}else{if(m.disabled){k=false}}}}break;case"a":k=j.fireEvent("linkClickEvent",{target:m,event:l});break;case"button":if(!m.disabled){k=j.fireEvent("buttonClickEvent",{target:m,event:l})}else{k=false}break;case"td":k=j.fireEvent("cellClickEvent",{target:m,event:l});break;case"tr":k=j.fireEvent("rowClickEvent",{target:m,event:l});break;default:break}if(k===false){return}else{m=m.parentNode;if(m){i=m.nodeName.toLowerCase()}}}j.fireEvent("tableClickEvent",{target:(m||j._elContainer),event:l})},_onDropdownChange:function(j,i){var k=g.getTarget(j);i.fireEvent("dropdownChangeEvent",{event:j,target:k})},configs:null,getId:function(){return this._sId},toString:function(){return"DataTable instance "+this._sId},getDataSource:function(){return this._oDataSource},getColumnSet:function(){return this._oColumnSet},getRecordSet:function(){return this._oRecordSet},getState:function(){return{totalRecords:this.get("paginator")?this.get("paginator").get("totalRecords"):this._oRecordSet.getLength(),pagination:this.get("paginator")?this.get("paginator").getState():null,sortedBy:this.get("sortedBy"),selectedRows:this.getSelectedRows(),selectedCells:this.getSelectedCells()}},getContainerEl:function(){return this._elContainer},getTableEl:function(){return this._elTable},getTheadEl:function(){return this._elThead},getTbodyEl:function(){return this._elTbody},getMsgTbodyEl:function(){return this._elMsgTbody},getMsgTdEl:function(){return this._elMsgTd},getTrEl:function(k){if(k instanceof YAHOO.widget.Record){return document.getElementById(k.getId())}else{if(h.isNumber(k)){var j=c.getElementsByClassName(d.CLASS_REC,"tr",this._elTbody);return j&&j[k]?j[k]:null}else{if(k){var i=(h.isString(k))?document.getElementById(k):k;if(i&&i.ownerDocument==document){if(i.nodeName.toLowerCase()!="tr"){i=c.getAncestorByTagName(i,"tr")}return i}}}}return null},getFirstTrEl:function(){var k=this._elTbody.rows,j=0;while(k[j]){if(this.getRecord(k[j])){return k[j]}j++}return null},getLastTrEl:function(){var k=this._elTbody.rows,j=k.length-1;while(j>-1){if(this.getRecord(k[j])){return k[j]}j--}return null},getNextTrEl:function(l,i){var j=this.getTrIndex(l);if(j!==null){var k=this._elTbody.rows;if(i){while(j<k.length-1){l=k[j+1];if(this.getRecord(l)){return l}j++}}else{if(j<k.length-1){return k[j+1]}}}return null},getPreviousTrEl:function(l,i){var j=this.getTrIndex(l);if(j!==null){var k=this._elTbody.rows;if(i){while(j>0){l=k[j-1];if(this.getRecord(l)){return l}j--}}else{if(j>0){return k[j-1]}}}return null},getCellIndex:function(k){k=this.getTdEl(k);if(k){if(b.ie>0){var l=0,n=k.parentNode,m=n.childNodes,j=m.length;for(;l<j;l++){if(m[l]==k){return l}}}else{return k.cellIndex}}},getTdLinerEl:function(i){var j=this.getTdEl(i);return j.firstChild||null},getTdEl:function(i){var n;var l=c.get(i);if(l&&(l.ownerDocument==document)){if(l.nodeName.toLowerCase()!="td"){n=c.getAncestorByTagName(l,"td")}else{n=l}if(n&&((n.parentNode.parentNode==this._elTbody)||(n.parentNode.parentNode===null)||(n.parentNode.parentNode.nodeType===11))){return n}}else{if(i){var m,k;if(h.isString(i.columnKey)&&h.isString(i.recordId)){m=this.getRecord(i.recordId);var o=this.getColumn(i.columnKey);if(o){k=o.getKeyIndex()}}if(i.record&&i.column&&i.column.getKeyIndex){m=i.record;k=i.column.getKeyIndex()}var j=this.getTrEl(m);if((k!==null)&&j&&j.cells&&j.cells.length>0){return j.cells[k]||null}}}return null},getFirstTdEl:function(j){var i=h.isValue(j)?this.getTrEl(j):this.getFirstTrEl();if(i){if(i.cells&&i.cells.length>0){return i.cells[0]}else{if(i.childNodes&&i.childNodes.length>0){return i.childNodes[0]}}}return null},getLastTdEl:function(j){var i=h.isValue(j)?this.getTrEl(j):this.getLastTrEl();if(i){if(i.cells&&i.cells.length>0){return i.cells[i.cells.length-1]}else{if(i.childNodes&&i.childNodes.length>0){return i.childNodes[i.childNodes.length-1]}}}return null},getNextTdEl:function(i){var m=this.getTdEl(i);if(m){var k=this.getCellIndex(m);var j=this.getTrEl(m);if(j.cells&&(j.cells.length)>0&&(k<j.cells.length-1)){return j.cells[k+1]}else{if(j.childNodes&&(j.childNodes.length)>0&&(k<j.childNodes.length-1)){return j.childNodes[k+1]}else{var l=this.getNextTrEl(j);if(l){return l.cells[0]}}}}return null},getPreviousTdEl:function(i){var m=this.getTdEl(i);if(m){var k=this.getCellIndex(m);var j=this.getTrEl(m);if(k>0){if(j.cells&&j.cells.length>0){return j.cells[k-1]}else{if(j.childNodes&&j.childNodes.length>0){return j.childNodes[k-1]}}}else{var l=this.getPreviousTrEl(j);if(l){return this.getLastTdEl(l)}}}return null},getAboveTdEl:function(j,i){var m=this.getTdEl(j);if(m){var l=this.getPreviousTrEl(m,i);if(l){var k=this.getCellIndex(m);if(l.cells&&l.cells.length>0){return l.cells[k]?l.cells[k]:null}else{if(l.childNodes&&l.childNodes.length>0){return l.childNodes[k]?l.childNodes[k]:null}}}}return null},getBelowTdEl:function(j,i){var m=this.getTdEl(j);if(m){var l=this.getNextTrEl(m,i);if(l){var k=this.getCellIndex(m);if(l.cells&&l.cells.length>0){return l.cells[k]?l.cells[k]:null}else{if(l.childNodes&&l.childNodes.length>0){return l.childNodes[k]?l.childNodes[k]:null}}}}return null},getThLinerEl:function(j){var i=this.getColumn(j);return(i)?i.getThLinerEl():null},getThEl:function(k){var l;if(k instanceof YAHOO.widget.Column){var j=k;l=j.getThEl();if(l){return l}}else{var i=c.get(k);if(i&&(i.ownerDocument==document)){if(i.nodeName.toLowerCase()!="th"){l=c.getAncestorByTagName(i,"th")}else{l=i}return l}}return null},getTrIndex:function(m){var i=this.getRecord(m),k=this.getRecordIndex(i),l;if(i){l=this.getTrEl(i);if(l){return l.sectionRowIndex}else{var j=this.get("paginator");if(j){return j.get("recordOffset")+k}else{return k}}}return null},load:function(i){i=i||{};(i.datasource||this._oDataSource).sendRequest(i.request||this.get("initialRequest"),i.callback||{success:this.onDataReturnInitializeTable,failure:this.onDataReturnInitializeTable,scope:this,argument:this.getState()})},initializeTable:function(){this._bInit=true;this._oRecordSet.reset();var i=this.get("paginator");if(i){i.set("totalRecords",0)}this._unselectAllTrEls();this._unselectAllTdEls();this._aSelections=null;this._oAnchorRecord=null;this._oAnchorCell=null;this.set("sortedBy",null)},_runRenderChain:function(){this._oChainRender.run()},_getViewRecords:function(){var i=this.get("paginator");if(i){return this._oRecordSet.getRecords(i.getStartIndex(),i.getRowsPerPage())}else{return this._oRecordSet.getRecords()}},render:function(){this._oChainRender.stop();this.fireEvent("beforeRenderEvent");var r,p,o,s,l=this._getViewRecords();var m=this._elTbody,q=this.get("renderLoopSize"),t=l.length;if(t>0){m.style.display="none";while(m.lastChild){m.removeChild(m.lastChild)}m.style.display="";this._oChainRender.add({method:function(u){if((this instanceof d)&&this._sId){var k=u.nCurrentRecord,w=((u.nCurrentRecord+u.nLoopLength)>t)?t:(u.nCurrentRecord+u.nLoopLength),j,v;m.style.display="none";for(;k<w;k++){j=c.get(l[k].getId());j=j||this._addTrEl(l[k]);v=m.childNodes[k]||null;m.insertBefore(j,v)}m.style.display="";u.nCurrentRecord=k}},scope:this,iterations:(q>0)?Math.ceil(t/q):1,argument:{nCurrentRecord:0,nLoopLength:(q>0)?q:t},timeout:(q>0)?0:-1});this._oChainRender.add({method:function(i){if((this instanceof d)&&this._sId){while(m.rows.length>t){m.removeChild(m.lastChild)}this._setFirstRow();this._setLastRow();this._setRowStripes();this._setSelections()}},scope:this,timeout:(q>0)?0:-1})}else{var n=m.rows.length;if(n>0){this._oChainRender.add({method:function(k){if((this instanceof d)&&this._sId){var j=k.nCurrent,v=k.nLoopLength,u=(j-v<0)?0:j-v;m.style.display="none";for(;j>u;j--){m.deleteRow(-1)}m.style.display="";k.nCurrent=j}},scope:this,iterations:(q>0)?Math.ceil(n/q):1,argument:{nCurrent:n,nLoopLength:(q>0)?q:n},timeout:(q>0)?0:-1})}}this._runRenderChain()},disable:function(){this._disabled=true;var i=this._elTable;var j=this._elMask;j.style.width=i.offsetWidth+"px";j.style.height=i.offsetHeight+"px";j.style.left=i.offsetLeft+"px";j.style.display="";this.fireEvent("disableEvent")},undisable:function(){this._disabled=false;this._elMask.style.display="none";this.fireEvent("undisableEvent")},isDisabled:function(){return this._disabled},destroy:function(){var k=this.toString();this._oChainRender.stop();this._destroyColumnHelpers();var m;for(var l=0,j=this._oColumnSet.flat.length;l<j;l++){m=this._oColumnSet.flat[l].editor;if(m&&m.destroy){m.destroy();this._oColumnSet.flat[l].editor=null}}this._destroyPaginator();this._oRecordSet.unsubscribeAll();this.unsubscribeAll();g.removeListener(document,"click",this._onDocumentClick);this._destroyContainerEl(this._elContainer);for(var n in this){if(h.hasOwnProperty(this,n)){this[n]=null}}d._nCurrentCount--;if(d._nCurrentCount<1){if(d._elDynStyleNode){document.getElementsByTagName("head")[0].removeChild(d._elDynStyleNode);d._elDynStyleNode=null}}},showTableMessage:function(j,i){var k=this._elMsgTd;if(h.isString(j)){k.firstChild.innerHTML=j}if(h.isString(i)){k.className=i}this._elMsgTbody.style.display="";this.fireEvent("tableMsgShowEvent",{html:j,className:i})},hideTableMessage:function(){if(this._elMsgTbody.style.display!="none"){this._elMsgTbody.style.display="none";this._elMsgTbody.parentNode.style.width="";this.fireEvent("tableMsgHideEvent")}},focus:function(){this.focusTbodyEl()},focusTheadEl:function(){this._focusEl(this._elThead)},focusTbodyEl:function(){this._focusEl(this._elTbody)},onShow:function(){this.validateColumnWidths();for(var m=this._oColumnSet.keys,l=0,j=m.length,k;l<j;l++){k=m[l];if(k._ddResizer){k._ddResizer.resetResizerEl()}}},getRecordIndex:function(l){var k;if(!h.isNumber(l)){if(l instanceof YAHOO.widget.Record){return this._oRecordSet.getRecordIndex(l)}else{var j=this.getTrEl(l);if(j){k=j.sectionRowIndex}}}else{k=l}if(h.isNumber(k)){var i=this.get("paginator");if(i){return i.get("recordOffset")+k}else{return k}}return null},getRecord:function(k){var j=this._oRecordSet.getRecord(k);if(!j){var i=this.getTrEl(k);if(i){j=this._oRecordSet.getRecord(i.id)}}if(j instanceof YAHOO.widget.Record){return this._oRecordSet.getRecord(j)}else{return null}},getColumn:function(m){var o=this._oColumnSet.getColumn(m);if(!o){var n=this.getTdEl(m);if(n){o=this._oColumnSet.getColumn(this.getCellIndex(n))}else{n=this.getThEl(m);if(n){var k=this._oColumnSet.flat;for(var l=0,j=k.length;l<j;l++){if(k[l].getThEl().id===n.id){o=k[l]}}}}}if(!o){}return o},getColumnById:function(i){return this._oColumnSet.getColumnById(i)},getColumnSortDir:function(k,l){if(k.sortOptions&&k.sortOptions.defaultDir){if(k.sortOptions.defaultDir=="asc"){k.sortOptions.defaultDir=d.CLASS_ASC}else{if(k.sortOptions.defaultDir=="desc"){k.sortOptions.defaultDir=d.CLASS_DESC}}}var j=(k.sortOptions&&k.sortOptions.defaultDir)?k.sortOptions.defaultDir:d.CLASS_ASC;var i=false;l=l||this.get("sortedBy");if(l&&(l.key===k.key)){i=true;if(l.dir){j=(l.dir===d.CLASS_ASC)?d.CLASS_DESC:d.CLASS_ASC}else{j=(j===d.CLASS_ASC)?d.CLASS_DESC:d.CLASS_ASC}}return j},doBeforeSortColumn:function(j,i){this.showTableMessage(this.get("MSG_LOADING"),d.CLASS_LOADING);return true},sortColumn:function(m,j){if(m&&(m instanceof YAHOO.widget.Column)){if(!m.sortable){c.addClass(this.getThEl(m),d.CLASS_SORTABLE)}if(j&&(j!==d.CLASS_ASC)&&(j!==d.CLASS_DESC)){j=null}var n=j||this.getColumnSortDir(m);var l=this.get("sortedBy")||{};var t=(l.key===m.key)?true:false;var p=this.doBeforeSortColumn(m,n);if(p){if(this.get("dynamicData")){var s=this.getState();if(s.pagination){s.pagination.recordOffset=0}s.sortedBy={key:m.key,dir:n};var k=this.get("generateRequest")(s,this);this.unselectAllRows();this.unselectAllCells();var r={success:this.onDataReturnSetRows,failure:this.onDataReturnSetRows,argument:s,scope:this};this._oDataSource.sendRequest(k,r)}else{var i=(m.sortOptions&&h.isFunction(m.sortOptions.sortFunction))?m.sortOptions.sortFunction:null;if(!t||j||i){i=i||this.get("sortFunction");var q=(m.sortOptions&&m.sortOptions.field)?m.sortOptions.field:m.field;this._oRecordSet.sortRecords(i,((n==d.CLASS_DESC)?true:false),q)}else{this._oRecordSet.reverseRecords()}var o=this.get("paginator");if(o){o.setPage(1,true)}this.render();this.set("sortedBy",{key:m.key,dir:n,column:m})}this.fireEvent("columnSortEvent",{column:m,dir:n});return}}},setColumnWidth:function(j,i){if(!(j instanceof YAHOO.widget.Column)){j=this.getColumn(j)}if(j){if(h.isNumber(i)){i=(i>j.minWidth)?i:j.minWidth;j.width=i;this._setColumnWidth(j,i+"px");this.fireEvent("columnSetWidthEvent",{column:j,width:i})}else{if(i===null){j.width=i;this._setColumnWidth(j,"auto");this.validateColumnWidths(j);this.fireEvent("columnUnsetWidthEvent",{column:j})}}this._clearTrTemplateEl()}else{}},_setColumnWidth:function(j,i,k){if(j&&(j.getKeyIndex()!==null)){k=k||(((i==="")||(i==="auto"))?"visible":"hidden");if(!d._bDynStylesFallback){this._setColumnWidthDynStyles(j,i,k)}else{this._setColumnWidthDynFunction(j,i,k)}}else{}},_setColumnWidthDynStyles:function(m,l,n){var j=d._elDynStyleNode,k;if(!j){j=document.createElement("style");j.type="text/css";j=document.getElementsByTagName("head").item(0).appendChild(j);d._elDynStyleNode=j}if(j){var i="."+this.getId()+"-col-"+m.getSanitizedKey()+" ."+d.CLASS_LINER;if(this._elTbody){this._elTbody.style.display="none"}k=d._oDynStyles[i];if(!k){if(j.styleSheet&&j.styleSheet.addRule){j.styleSheet.addRule(i,"overflow:"+n);j.styleSheet.addRule(i,"width:"+l);k=j.styleSheet.rules[j.styleSheet.rules.length-1];d._oDynStyles[i]=k}else{if(j.sheet&&j.sheet.insertRule){j.sheet.insertRule(i+" {overflow:"+n+";width:"+l+";}",j.sheet.cssRules.length);k=j.sheet.cssRules[j.sheet.cssRules.length-1];d._oDynStyles[i]=k}}}else{k.style.overflow=n;k.style.width=l}if(this._elTbody){this._elTbody.style.display=""}}if(!k){d._bDynStylesFallback=true;this._setColumnWidthDynFunction(m,l)}},_setColumnWidthDynFunction:function(r,m,s){if(m=="auto"){m=""}var l=this._elTbody?this._elTbody.rows.length:0;if(!this._aDynFunctions[l]){var q,p,o;var t=["var colIdx=oColumn.getKeyIndex();","oColumn.getThLinerEl().style.overflow="];for(q=l-1,p=2;q>=0;--q){t[p++]="this._elTbody.rows[";t[p++]=q;t[p++]="].cells[colIdx].firstChild.style.overflow="}t[p]="sOverflow;";t[p+1]="oColumn.getThLinerEl().style.width=";for(q=l-1,o=p+2;q>=0;--q){t[o++]="this._elTbody.rows[";t[o++]=q;t[o++]="].cells[colIdx].firstChild.style.width="}t[o]="sWidth;";this._aDynFunctions[l]=new Function("oColumn","sWidth","sOverflow",t.join(""))}var n=this._aDynFunctions[l];if(n){n.call(this,r,m,s)}},validateColumnWidths:function(o){var l=this._elColgroup;var q=l.cloneNode(true);var p=false;var n=this._oColumnSet.keys;var k;if(o&&!o.hidden&&!o.width&&(o.getKeyIndex()!==null)){k=o.getThLinerEl();if((o.minWidth>0)&&(k.offsetWidth<o.minWidth)){q.childNodes[o.getKeyIndex()].style.width=o.minWidth+(parseInt(c.getStyle(k,"paddingLeft"),10)|0)+(parseInt(c.getStyle(k,"paddingRight"),10)|0)+"px";p=true}else{if((o.maxAutoWidth>0)&&(k.offsetWidth>o.maxAutoWidth)){this._setColumnWidth(o,o.maxAutoWidth+"px","hidden")}}}else{for(var m=0,j=n.length;m<j;m++){o=n[m];if(!o.hidden&&!o.width){k=o.getThLinerEl();if((o.minWidth>0)&&(k.offsetWidth<o.minWidth)){q.childNodes[m].style.width=o.minWidth+(parseInt(c.getStyle(k,"paddingLeft"),10)|0)+(parseInt(c.getStyle(k,"paddingRight"),10)|0)+"px";p=true}else{if((o.maxAutoWidth>0)&&(k.offsetWidth>o.maxAutoWidth)){this._setColumnWidth(o,o.maxAutoWidth+"px","hidden")}}}}}if(p){l.parentNode.replaceChild(q,l);this._elColgroup=q}},_clearMinWidth:function(i){if(i.getKeyIndex()!==null){this._elColgroup.childNodes[i.getKeyIndex()].style.width=""}},_restoreMinWidth:function(i){if(i.minWidth&&(i.getKeyIndex()!==null)){this._elColgroup.childNodes[i.getKeyIndex()].style.width=i.minWidth+"px"}},hideColumn:function(r){if(!(r instanceof YAHOO.widget.Column)){r=this.getColumn(r)}if(r&&!r.hidden&&r.getTreeIndex()!==null){var o=this.getTbodyEl().rows;var n=o.length;var m=this._oColumnSet.getDescendants(r);for(var q=0,s=m.length;q<s;q++){var t=m[q];t.hidden=true;c.addClass(t.getThEl(),d.CLASS_HIDDEN);var k=t.getKeyIndex();if(k!==null){this._clearMinWidth(r);for(var p=0;p<n;p++){c.addClass(o[p].cells[k],d.CLASS_HIDDEN)}}this.fireEvent("columnHideEvent",{column:t})}this._repaintOpera();this._clearTrTemplateEl()}else{}},showColumn:function(r){if(!(r instanceof YAHOO.widget.Column)){r=this.getColumn(r)}if(r&&r.hidden&&(r.getTreeIndex()!==null)){var o=this.getTbodyEl().rows;var n=o.length;var m=this._oColumnSet.getDescendants(r);for(var q=0,s=m.length;q<s;q++){var t=m[q];t.hidden=false;c.removeClass(t.getThEl(),d.CLASS_HIDDEN);var k=t.getKeyIndex();if(k!==null){this._restoreMinWidth(r);for(var p=0;p<n;p++){c.removeClass(o[p].cells[k],d.CLASS_HIDDEN)}}this.fireEvent("columnShowEvent",{column:t})}this._clearTrTemplateEl()}else{}},removeColumn:function(p){if(!(p instanceof YAHOO.widget.Column)){p=this.getColumn(p)}if(p){var m=p.getTreeIndex();if(m!==null){var o,r,q=p.getKeyIndex();if(q===null){var u=[];var j=this._oColumnSet.getDescendants(p);for(o=0,r=j.length;o<r;o++){var s=j[o].getKeyIndex();if(s!==null){u[u.length]=s}}if(u.length>0){q=u}}else{q=[q]}if(q!==null){q.sort(function(v,i){return YAHOO.util.Sort.compare(v,i)});this._destroyTheadEl();var k=this._oColumnSet.getDefinitions();p=k.splice(m,1)[0];this._initColumnSet(k);this._initTheadEl();for(o=q.length-1;o>-1;o--){this._removeColgroupColEl(q[o])}var t=this._elTbody.rows;if(t.length>0){var n=this.get("renderLoopSize"),l=t.length;this._oChainRender.add({method:function(y){if((this instanceof d)&&this._sId){var x=y.nCurrentRow,v=n>0?Math.min(x+n,t.length):t.length,z=y.aIndexes,w;for(;x<v;++x){for(w=z.length-1;w>-1;w--){t[x].removeChild(t[x].childNodes[z[w]])}}y.nCurrentRow=x}},iterations:(n>0)?Math.ceil(l/n):1,argument:{nCurrentRow:0,aIndexes:q},scope:this,timeout:(n>0)?0:-1});this._runRenderChain()}this.fireEvent("columnRemoveEvent",{column:p});return p}}}},insertColumn:function(r,s){if(r instanceof YAHOO.widget.Column){r=r.getDefinition()}else{if(r.constructor!==Object){return}}var x=this._oColumnSet;if(!h.isValue(s)||!h.isNumber(s)){s=x.tree[0].length}this._destroyTheadEl();var z=this._oColumnSet.getDefinitions();z.splice(s,0,r);this._initColumnSet(z);this._initTheadEl();x=this._oColumnSet;var n=x.tree[0][s];var p,t,w=[];var l=x.getDescendants(n);for(p=0,t=l.length;p<t;p++){var u=l[p].getKeyIndex();if(u!==null){w[w.length]=u}}if(w.length>0){var y=w.sort(function(A,i){return YAHOO.util.Sort.compare(A,i)})[0];for(p=w.length-1;p>-1;p--){this._insertColgroupColEl(w[p])}var v=this._elTbody.rows;if(v.length>0){var o=this.get("renderLoopSize"),m=v.length;var k=[],q;for(p=0,t=w.length;p<t;p++){var j=w[p];q=this._getTrTemplateEl().childNodes[p].cloneNode(true);q=this._formatTdEl(this._oColumnSet.keys[j],q,j,(j===this._oColumnSet.keys.length-1));k[j]=q}this._oChainRender.add({method:function(D){if((this instanceof d)&&this._sId){var C=D.nCurrentRow,B,F=D.descKeyIndexes,A=o>0?Math.min(C+o,v.length):v.length,E;for(;C<A;++C){E=v[C].childNodes[y]||null;for(B=F.length-1;B>-1;B--){v[C].insertBefore(D.aTdTemplates[F[B]].cloneNode(true),E)}}D.nCurrentRow=C}},iterations:(o>0)?Math.ceil(m/o):1,argument:{nCurrentRow:0,aTdTemplates:k,descKeyIndexes:w},scope:this,timeout:(o>0)?0:-1});this._runRenderChain()}this.fireEvent("columnInsertEvent",{column:r,index:s});return n}},reorderColumn:function(q,r){if(!(q instanceof YAHOO.widget.Column)){q=this.getColumn(q)}if(q&&YAHOO.lang.isNumber(r)){var z=q.getTreeIndex();if((z!==null)&&(z!==r)){var p,s,l=q.getKeyIndex(),k,v=[],t;if(l===null){k=this._oColumnSet.getDescendants(q);for(p=0,s=k.length;p<s;p++){t=k[p].getKeyIndex();if(t!==null){v[v.length]=t}}if(v.length>0){l=v}}else{l=[l]}if(l!==null){l.sort(function(A,i){return YAHOO.util.Sort.compare(A,i)});this._destroyTheadEl();var w=this._oColumnSet.getDefinitions();var j=w.splice(z,1)[0];w.splice(r,0,j);this._initColumnSet(w);this._initTheadEl();var n=this._oColumnSet.tree[0][r];var y=n.getKeyIndex();if(y===null){v=[];k=this._oColumnSet.getDescendants(n);for(p=0,s=k.length;p<s;p++){t=k[p].getKeyIndex();if(t!==null){v[v.length]=t}}if(v.length>0){y=v}}else{y=[y]}var x=y.sort(function(A,i){return YAHOO.util.Sort.compare(A,i)})[0];this._reorderColgroupColEl(l,x);var u=this._elTbody.rows;if(u.length>0){var o=this.get("renderLoopSize"),m=u.length;this._oChainRender.add({method:function(D){if((this instanceof d)&&this._sId){var C=D.nCurrentRow,B,F,E,A=o>0?Math.min(C+o,u.length):u.length,H=D.aIndexes,G;for(;C<A;++C){F=[];G=u[C];for(B=H.length-1;B>-1;B--){F.push(G.removeChild(G.childNodes[H[B]]))}E=G.childNodes[x]||null;for(B=F.length-1;B>-1;B--){G.insertBefore(F[B],E)}}D.nCurrentRow=C}},iterations:(o>0)?Math.ceil(m/o):1,argument:{nCurrentRow:0,aIndexes:l},scope:this,timeout:(o>0)?0:-1});this._runRenderChain()}this.fireEvent("columnReorderEvent",{column:n,oldIndex:z});return n}}}},selectColumn:function(k){k=this.getColumn(k);if(k&&!k.selected){if(k.getKeyIndex()!==null){k.selected=true;var l=k.getThEl();c.addClass(l,d.CLASS_SELECTED);var j=this.getTbodyEl().rows;var i=this._oChainRender;i.add({method:function(m){if((this instanceof d)&&this._sId&&j[m.rowIndex]&&j[m.rowIndex].cells[m.cellIndex]){c.addClass(j[m.rowIndex].cells[m.cellIndex],d.CLASS_SELECTED)}m.rowIndex++},scope:this,iterations:j.length,argument:{rowIndex:0,cellIndex:k.getKeyIndex()}});this._clearTrTemplateEl();this._elTbody.style.display="none";this._runRenderChain();this._elTbody.style.display="";this.fireEvent("columnSelectEvent",{column:k})}else{}}},unselectColumn:function(k){k=this.getColumn(k);if(k&&k.selected){if(k.getKeyIndex()!==null){k.selected=false;var l=k.getThEl();c.removeClass(l,d.CLASS_SELECTED);var j=this.getTbodyEl().rows;var i=this._oChainRender;i.add({method:function(m){if((this instanceof d)&&this._sId&&j[m.rowIndex]&&j[m.rowIndex].cells[m.cellIndex]){c.removeClass(j[m.rowIndex].cells[m.cellIndex],d.CLASS_SELECTED)}m.rowIndex++},scope:this,iterations:j.length,argument:{rowIndex:0,cellIndex:k.getKeyIndex()}});this._clearTrTemplateEl();this._elTbody.style.display="none";this._runRenderChain();this._elTbody.style.display="";this.fireEvent("columnUnselectEvent",{column:k})}else{}}},getSelectedColumns:function(n){var k=[];var l=this._oColumnSet.keys;for(var m=0,j=l.length;m<j;m++){if(l[m].selected){k[k.length]=l[m]}}return k},highlightColumn:function(i){var l=this.getColumn(i);if(l&&(l.getKeyIndex()!==null)){var m=l.getThEl();c.addClass(m,d.CLASS_HIGHLIGHTED);var k=this.getTbodyEl().rows;var j=this._oChainRender;j.add({method:function(n){if((this instanceof d)&&this._sId&&k[n.rowIndex]&&k[n.rowIndex].cells[n.cellIndex]){c.addClass(k[n.rowIndex].cells[n.cellIndex],d.CLASS_HIGHLIGHTED)}n.rowIndex++},scope:this,iterations:k.length,argument:{rowIndex:0,cellIndex:l.getKeyIndex()},timeout:-1});this._elTbody.style.display="none";this._runRenderChain();this._elTbody.style.display="";this.fireEvent("columnHighlightEvent",{column:l})}else{}},unhighlightColumn:function(i){var l=this.getColumn(i);if(l&&(l.getKeyIndex()!==null)){var m=l.getThEl();c.removeClass(m,d.CLASS_HIGHLIGHTED);var k=this.getTbodyEl().rows;var j=this._oChainRender;j.add({method:function(n){if((this instanceof d)&&this._sId&&k[n.rowIndex]&&k[n.rowIndex].cells[n.cellIndex]){c.removeClass(k[n.rowIndex].cells[n.cellIndex],d.CLASS_HIGHLIGHTED)}n.rowIndex++},scope:this,iterations:k.length,argument:{rowIndex:0,cellIndex:l.getKeyIndex()},timeout:-1});this._elTbody.style.display="none";this._runRenderChain();this._elTbody.style.display="";this.fireEvent("columnUnhighlightEvent",{column:l})}else{}},addRow:function(o,k){if(h.isNumber(k)&&(k<0||k>this._oRecordSet.getLength())){return}if(o&&h.isObject(o)){var m=this._oRecordSet.addRecord(o,k);if(m){var i;var j=this.get("paginator");if(j){var n=j.get("totalRecords");if(n!==e.Paginator.VALUE_UNLIMITED){j.set("totalRecords",n+1)}i=this.getRecordIndex(m);var l=(j.getPageRecords())[1];if(i<=l){this.render()}this.fireEvent("rowAddEvent",{record:m});return}else{i=this.getRecordIndex(m);if(h.isNumber(i)){this._oChainRender.add({method:function(r){if((this instanceof d)&&this._sId){var s=r.record;var p=r.recIndex;var t=this._addTrEl(s);if(t){var q=(this._elTbody.rows[p])?this._elTbody.rows[p]:null;this._elTbody.insertBefore(t,q);if(p===0){this._setFirstRow()}if(q===null){this._setLastRow()}this._setRowStripes();this.hideTableMessage();this.fireEvent("rowAddEvent",{record:s})}}},argument:{record:m,recIndex:i},scope:this,timeout:(this.get("renderLoopSize")>0)?0:-1});this._runRenderChain();return}}}}},addRows:function(k,n){if(h.isNumber(n)&&(n<0||n>this._oRecordSet.getLength())){return}if(h.isArray(k)){var o=this._oRecordSet.addRecords(k,n);if(o){var s=this.getRecordIndex(o[0]);var r=this.get("paginator");if(r){var p=r.get("totalRecords");if(p!==e.Paginator.VALUE_UNLIMITED){r.set("totalRecords",p+o.length)}var q=(r.getPageRecords())[1];if(s<=q){this.render()}this.fireEvent("rowsAddEvent",{records:o});return}else{var m=this.get("renderLoopSize");var j=s+k.length;var i=(j-s);var l=(s>=this._elTbody.rows.length);this._oChainRender.add({method:function(x){if((this instanceof d)&&this._sId){var y=x.aRecords,w=x.nCurrentRow,v=x.nCurrentRecord,t=m>0?Math.min(w+m,j):j,z=document.createDocumentFragment(),u=(this._elTbody.rows[w])?this._elTbody.rows[w]:null;for(;w<t;w++,v++){z.appendChild(this._addTrEl(y[v]))}this._elTbody.insertBefore(z,u);x.nCurrentRow=w;x.nCurrentRecord=v}},iterations:(m>0)?Math.ceil(j/m):1,argument:{nCurrentRow:s,nCurrentRecord:0,aRecords:o},scope:this,timeout:(m>0)?0:-1});this._oChainRender.add({method:function(u){var t=u.recIndex;if(t===0){this._setFirstRow()}if(u.isLast){this._setLastRow()}this._setRowStripes();this.fireEvent("rowsAddEvent",{records:o})},argument:{recIndex:s,isLast:l},scope:this,timeout:-1});this._runRenderChain();this.hideTableMessage();return}}}},updateRow:function(u,k){var r=u;if(!h.isNumber(r)){r=this.getRecordIndex(u)}if(h.isNumber(r)&&(r>=0)){var s=this._oRecordSet,q=s.getRecord(r);if(q){var o=this._oRecordSet.setRecord(k,r),j=this.getTrEl(q),p=q?q.getData():null;if(o){var t=this._aSelections||[],n=0,l=q.getId(),m=o.getId();for(;n<t.length;n++){if((t[n]===l)){t[n]=m}else{if(t[n].recordId===l){t[n].recordId=m}}}if(this._oAnchorRecord&&this._oAnchorRecord.getId()===l){this._oAnchorRecord=o}if(this._oAnchorCell&&this._oAnchorCell.record.getId()===l){this._oAnchorCell.record=o}this._oChainRender.add({method:function(){if((this instanceof d)&&this._sId){var v=this.get("paginator");if(v){var i=(v.getPageRecords())[0],w=(v.getPageRecords())[1];if((r>=i)||(r<=w)){this.render()}}else{if(j){this._updateTrEl(j,o)}else{this.getTbodyEl().appendChild(this._addTrEl(o))}}this.fireEvent("rowUpdateEvent",{record:o,oldData:p})}},scope:this,timeout:(this.get("renderLoopSize")>0)?0:-1});this._runRenderChain();return}}}return},updateRows:function(A,m){if(h.isArray(m)){var s=A,l=this._oRecordSet,o=l.getLength();if(!h.isNumber(A)){s=this.getRecordIndex(A)}if(h.isNumber(s)&&(s>=0)&&(s<l.getLength())){var E=s+m.length,B=l.getRecords(s,m.length),G=l.setRecords(m,s);if(G){var t=this._aSelections||[],D=0,C,u,x,z,y=this._oAnchorRecord?this._oAnchorRecord.getId():null,n=this._oAnchorCell?this._oAnchorCell.record.getId():null;for(;D<B.length;D++){z=B[D].getId();u=G[D];x=u.getId();for(C=0;C<t.length;C++){if((t[C]===z)){t[C]=x}else{if(t[C].recordId===z){t[C].recordId=x}}}if(y&&y===z){this._oAnchorRecord=u}if(n&&n===z){this._oAnchorCell.record=u}}var F=this.get("paginator");if(F){var r=(F.getPageRecords())[0],p=(F.getPageRecords())[1];if((s>=r)||(E<=p)){this.render()}this.fireEvent("rowsAddEvent",{newRecords:G,oldRecords:B});return}else{var k=this.get("renderLoopSize"),v=m.length,w=(E>=o),q=(E>o);this._oChainRender.add({method:function(K){if((this instanceof d)&&this._sId){var L=K.aRecords,J=K.nCurrentRow,I=K.nDataPointer,H=k>0?Math.min(J+k,s+L.length):s+L.length;for(;J<H;J++,I++){if(q&&(J>=o)){this._elTbody.appendChild(this._addTrEl(L[I]))}else{this._updateTrEl(this._elTbody.rows[J],L[I])}}K.nCurrentRow=J;K.nDataPointer=I}},iterations:(k>0)?Math.ceil(v/k):1,argument:{nCurrentRow:s,aRecords:G,nDataPointer:0,isAdding:q},scope:this,timeout:(k>0)?0:-1});this._oChainRender.add({method:function(j){var i=j.recIndex;if(i===0){this._setFirstRow()}if(j.isLast){this._setLastRow()}this._setRowStripes();this.fireEvent("rowsAddEvent",{newRecords:G,oldRecords:B})},argument:{recIndex:s,isLast:w},scope:this,timeout:-1});this._runRenderChain();this.hideTableMessage();return}}}}},deleteRow:function(s){var k=(h.isNumber(s))?s:this.getRecordIndex(s);if(h.isNumber(k)){var t=this.getRecord(k);if(t){var m=this.getTrIndex(k);var p=t.getId();var r=this._aSelections||[];for(var n=r.length-1;n>-1;n--){if((h.isString(r[n])&&(r[n]===p))||(h.isObject(r[n])&&(r[n].recordId===p))){r.splice(n,1)}}var l=this._oRecordSet.deleteRecord(k);if(l){var q=this.get("paginator");if(q){var o=q.get("totalRecords"),i=q.getPageRecords();if(o!==e.Paginator.VALUE_UNLIMITED){q.set("totalRecords",o-1)}if(!i||k<=i[1]){this.render()}this._oChainRender.add({method:function(){if((this instanceof d)&&this._sId){this.fireEvent("rowDeleteEvent",{recordIndex:k,oldData:l,trElIndex:m})}},scope:this,timeout:(this.get("renderLoopSize")>0)?0:-1});this._runRenderChain()}else{if(h.isNumber(m)){this._oChainRender.add({method:function(){if((this instanceof d)&&this._sId){var j=(k===this._oRecordSet.getLength());this._deleteTrEl(m);if(this._elTbody.rows.length>0){if(m===0){this._setFirstRow()}if(j){this._setLastRow()}if(m!=this._elTbody.rows.length){this._setRowStripes(m)}}this.fireEvent("rowDeleteEvent",{recordIndex:k,oldData:l,trElIndex:m})}},scope:this,timeout:(this.get("renderLoopSize")>0)?0:-1});this._runRenderChain();return}}}}}return null},deleteRows:function(y,s){var l=(h.isNumber(y))?y:this.getRecordIndex(y);if(h.isNumber(l)){var z=this.getRecord(l);if(z){var m=this.getTrIndex(l);var u=z.getId();var x=this._aSelections||[];for(var q=x.length-1;q>-1;q--){if((h.isString(x[q])&&(x[q]===u))||(h.isObject(x[q])&&(x[q].recordId===u))){x.splice(q,1)}}var n=l;var w=l;if(s&&h.isNumber(s)){n=(s>0)?l+s-1:l;w=(s>0)?l:l+s+1;s=(s>0)?s:s*-1;if(w<0){w=0;s=n-w+1}}else{s=1}var p=this._oRecordSet.deleteRecords(w,s);if(p){var v=this.get("paginator"),r=this.get("renderLoopSize");if(v){var t=v.get("totalRecords"),k=v.getPageRecords();if(t!==e.Paginator.VALUE_UNLIMITED){v.set("totalRecords",t-p.length)}if(!k||w<=k[1]){this.render()}this._oChainRender.add({method:function(j){if((this instanceof d)&&this._sId){this.fireEvent("rowsDeleteEvent",{recordIndex:w,oldData:p,count:s})}},scope:this,timeout:(r>0)?0:-1});this._runRenderChain();return}else{if(h.isNumber(m)){var o=w;var i=s;this._oChainRender.add({method:function(B){if((this instanceof d)&&this._sId){var A=B.nCurrentRow,j=(r>0)?(Math.max(A-r,o)-1):o-1;for(;A>j;--A){this._deleteTrEl(A)}B.nCurrentRow=A}},iterations:(r>0)?Math.ceil(s/r):1,argument:{nCurrentRow:n},scope:this,timeout:(r>0)?0:-1});this._oChainRender.add({method:function(){if(this._elTbody.rows.length>0){this._setFirstRow();this._setLastRow();this._setRowStripes()}this.fireEvent("rowsDeleteEvent",{recordIndex:w,oldData:p,count:s})},scope:this,timeout:-1});this._runRenderChain();return}}}}}return null},formatCell:function(j,l,m){if(!l){l=this.getRecord(j)}if(!m){m=this.getColumn(this.getCellIndex(j.parentNode))}if(l&&m){var i=m.field;var n=l.getData(i);var k=typeof m.formatter==="function"?m.formatter:d.Formatter[m.formatter+""]||d.Formatter.defaultFormatter;if(k){k.call(this,j,l,m,n)}else{j.innerHTML=n}this.fireEvent("cellFormatEvent",{record:l,column:m,key:m.key,el:j})}else{}},updateCell:function(k,m,o,j){m=(m instanceof YAHOO.widget.Column)?m:this.getColumn(m);if(m&&m.getField()&&(k instanceof YAHOO.widget.Record)){var l=m.getField(),n=k.getData(l);this._oRecordSet.updateRecordValue(k,l,o);var i=this.getTdEl({record:k,column:m});if(i){this._oChainRender.add({method:function(){if((this instanceof d)&&this._sId){this.formatCell(i.firstChild,k,m);this.fireEvent("cellUpdateEvent",{record:k,column:m,oldData:n})}},scope:this,timeout:(this.get("renderLoopSize")>0)?0:-1});if(!j){this._runRenderChain()}}else{this.fireEvent("cellUpdateEvent",{record:k,column:m,oldData:n})}}},_updatePaginator:function(j){var i=this.get("paginator");if(i&&j!==i){i.unsubscribe("changeRequest",this.onPaginatorChangeRequest,this,true)}if(j){j.subscribe("changeRequest",this.onPaginatorChangeRequest,this,true)}},_handlePaginatorChange:function(l){if(l.prevValue===l.newValue){return}var n=l.newValue,m=l.prevValue,k=this._defaultPaginatorContainers();if(m){if(m.getContainerNodes()[0]==k[0]){m.set("containers",[])}m.destroy();if(k[0]){if(n&&!n.getContainerNodes().length){n.set("containers",k)}else{for(var j=k.length-1;j>=0;--j){if(k[j]){k[j].parentNode.removeChild(k[j])}}}}}if(!this._bInit){this.render()}if(n){this.renderPaginator()}},_defaultPaginatorContainers:function(l){var j=this._sId+"-paginator0",k=this._sId+"-paginator1",i=c.get(j),m=c.get(k);if(l&&(!i||!m)){if(!i){i=document.createElement("div");i.id=j;c.addClass(i,d.CLASS_PAGINATOR);this._elContainer.insertBefore(i,this._elContainer.firstChild)}if(!m){m=document.createElement("div");m.id=k;c.addClass(m,d.CLASS_PAGINATOR);this._elContainer.appendChild(m)}}return[i,m]},_destroyPaginator:function(){var i=this.get("paginator");if(i){i.destroy()}},renderPaginator:function(){var i=this.get("paginator");if(!i){return}if(!i.getContainerNodes().length){i.set("containers",this._defaultPaginatorContainers(true))}i.render()},doBeforePaginatorChange:function(i){this.showTableMessage(this.get("MSG_LOADING"),d.CLASS_LOADING);return true},onPaginatorChangeRequest:function(l){var j=this.doBeforePaginatorChange(l);if(j){if(this.get("dynamicData")){var i=this.getState();i.pagination=l;var k=this.get("generateRequest")(i,this);this.unselectAllRows();this.unselectAllCells();var m={success:this.onDataReturnSetRows,failure:this.onDataReturnSetRows,argument:i,scope:this};this._oDataSource.sendRequest(k,m)}else{l.paginator.setStartIndex(l.recordOffset,true);l.paginator.setRowsPerPage(l.rowsPerPage,true);this.render()}}else{}},_elLastHighlightedTd:null,_aSelections:null,_oAnchorRecord:null,_oAnchorCell:null,_unselectAllTrEls:function(){var i=c.getElementsByClassName(d.CLASS_SELECTED,"tr",this._elTbody);c.removeClass(i,d.CLASS_SELECTED)},_getSelectionTrigger:function(){var l=this.get("selectionMode");var k={};var o,i,j,n,m;if((l=="cellblock")||(l=="cellrange")||(l=="singlecell")){o=this.getLastSelectedCell();if(!o){return null}else{i=this.getRecord(o.recordId);j=this.getRecordIndex(i);n=this.getTrEl(i);m=this.getTrIndex(n);if(m===null){return null}else{k.record=i;k.recordIndex=j;k.el=this.getTdEl(o);k.trIndex=m;k.column=this.getColumn(o.columnKey);k.colKeyIndex=k.column.getKeyIndex();k.cell=o;return k}}}else{i=this.getLastSelectedRecord();if(!i){return null}else{i=this.getRecord(i);j=this.getRecordIndex(i);n=this.getTrEl(i);m=this.getTrIndex(n);if(m===null){return null}else{k.record=i;k.recordIndex=j;k.el=n;k.trIndex=m;return k}}}},_getSelectionAnchor:function(k){var j=this.get("selectionMode");var l={};var m,o,i;if((j=="cellblock")||(j=="cellrange")||(j=="singlecell")){var n=this._oAnchorCell;if(!n){if(k){n=this._oAnchorCell=k.cell}else{return null}}m=this._oAnchorCell.record;o=this._oRecordSet.getRecordIndex(m);i=this.getTrIndex(m);if(i===null){if(o<this.getRecordIndex(this.getFirstTrEl())){i=0}else{i=this.getRecordIndex(this.getLastTrEl())}}l.record=m;l.recordIndex=o;l.trIndex=i;l.column=this._oAnchorCell.column;l.colKeyIndex=l.column.getKeyIndex();l.cell=n;return l}else{m=this._oAnchorRecord;if(!m){if(k){m=this._oAnchorRecord=k.record}else{return null}}o=this.getRecordIndex(m);i=this.getTrIndex(m);if(i===null){if(o<this.getRecordIndex(this.getFirstTrEl())){i=0}else{i=this.getRecordIndex(this.getLastTrEl())}}l.record=m;l.recordIndex=o;l.trIndex=i;return l}},_handleStandardSelectionByMouse:function(k){var j=k.target;var m=this.getTrEl(j);if(m){var p=k.event;var s=p.shiftKey;var o=p.ctrlKey||((navigator.userAgent.toLowerCase().indexOf("mac")!=-1)&&p.metaKey);var r=this.getRecord(m);var l=this._oRecordSet.getRecordIndex(r);var q=this._getSelectionAnchor();var n;if(s&&o){if(q){if(this.isSelected(q.record)){if(q.recordIndex<l){for(n=q.recordIndex+1;n<=l;n++){if(!this.isSelected(n)){this.selectRow(n)}}}else{for(n=q.recordIndex-1;n>=l;n--){if(!this.isSelected(n)){this.selectRow(n)}}}}else{if(q.recordIndex<l){for(n=q.recordIndex+1;n<=l-1;n++){if(this.isSelected(n)){this.unselectRow(n)}}}else{for(n=l+1;n<=q.recordIndex-1;n++){if(this.isSelected(n)){this.unselectRow(n)}}}this.selectRow(r)}}else{this._oAnchorRecord=r;if(this.isSelected(r)){this.unselectRow(r)}else{this.selectRow(r)}}}else{if(s){this.unselectAllRows();if(q){if(q.recordIndex<l){for(n=q.recordIndex;n<=l;n++){this.selectRow(n)}}else{for(n=q.recordIndex;n>=l;n--){this.selectRow(n)}}}else{this._oAnchorRecord=r;this.selectRow(r)}}else{if(o){this._oAnchorRecord=r;if(this.isSelected(r)){this.unselectRow(r)}else{this.selectRow(r)}}else{this._handleSingleSelectionByMouse(k);return}}}}},_handleStandardSelectionByKey:function(m){var i=g.getCharCode(m);if((i==38)||(i==40)){var k=m.shiftKey;var j=this._getSelectionTrigger();if(!j){return null}g.stopEvent(m);var l=this._getSelectionAnchor(j);if(k){if((i==40)&&(l.recordIndex<=j.trIndex)){this.selectRow(this.getNextTrEl(j.el))}else{if((i==38)&&(l.recordIndex>=j.trIndex)){this.selectRow(this.getPreviousTrEl(j.el))}else{this.unselectRow(j.el)}}}else{this._handleSingleSelectionByKey(m)}}},_handleSingleSelectionByMouse:function(k){var l=k.target;var j=this.getTrEl(l);if(j){var i=this.getRecord(j);this._oAnchorRecord=i;this.unselectAllRows();this.selectRow(i)}},_handleSingleSelectionByKey:function(l){var i=g.getCharCode(l);if((i==38)||(i==40)){var j=this._getSelectionTrigger();if(!j){return null}g.stopEvent(l);var k;if(i==38){k=this.getPreviousTrEl(j.el);if(k===null){k=this.getFirstTrEl()}}else{if(i==40){k=this.getNextTrEl(j.el);if(k===null){k=this.getLastTrEl()}}}this.unselectAllRows();this.selectRow(k);this._oAnchorRecord=this.getRecord(k)}},_handleCellBlockSelectionByMouse:function(A){var B=A.target;var l=this.getTdEl(B);if(l){var z=A.event;var q=z.shiftKey;var m=z.ctrlKey||((navigator.userAgent.toLowerCase().indexOf("mac")!=-1)&&z.metaKey);var s=this.getTrEl(l);var r=this.getTrIndex(s);var v=this.getColumn(l);var w=v.getKeyIndex();var u=this.getRecord(s);var D=this._oRecordSet.getRecordIndex(u);var p={record:u,column:v};var t=this._getSelectionAnchor();var o=this.getTbodyEl().rows;var n,k,C,y,x;if(q&&m){if(t){if(this.isSelected(t.cell)){if(t.recordIndex===D){if(t.colKeyIndex<w){for(y=t.colKeyIndex+1;y<=w;y++){this.selectCell(s.cells[y])}}else{if(w<t.colKeyIndex){for(y=w;y<t.colKeyIndex;y++){this.selectCell(s.cells[y])}}}}else{if(t.recordIndex<D){n=Math.min(t.colKeyIndex,w);k=Math.max(t.colKeyIndex,w);for(y=t.trIndex;y<=r;y++){for(x=n;x<=k;x++){this.selectCell(o[y].cells[x])}}}else{n=Math.min(t.trIndex,w);k=Math.max(t.trIndex,w);for(y=t.trIndex;y>=r;y--){for(x=k;x>=n;x--){this.selectCell(o[y].cells[x])}}}}}else{if(t.recordIndex===D){if(t.colKeyIndex<w){for(y=t.colKeyIndex+1;y<w;y++){this.unselectCell(s.cells[y])}}else{if(w<t.colKeyIndex){for(y=w+1;y<t.colKeyIndex;y++){this.unselectCell(s.cells[y])}}}}if(t.recordIndex<D){for(y=t.trIndex;y<=r;y++){C=o[y];for(x=0;x<C.cells.length;x++){if(C.sectionRowIndex===t.trIndex){if(x>t.colKeyIndex){this.unselectCell(C.cells[x])}}else{if(C.sectionRowIndex===r){if(x<w){this.unselectCell(C.cells[x])}}else{this.unselectCell(C.cells[x])}}}}}else{for(y=r;y<=t.trIndex;y++){C=o[y];for(x=0;x<C.cells.length;x++){if(C.sectionRowIndex==r){if(x>w){this.unselectCell(C.cells[x])}}else{if(C.sectionRowIndex==t.trIndex){if(x<t.colKeyIndex){this.unselectCell(C.cells[x])}}else{this.unselectCell(C.cells[x])}}}}}this.selectCell(l)}}else{this._oAnchorCell=p;if(this.isSelected(p)){this.unselectCell(p)}else{this.selectCell(p)}}}else{if(q){this.unselectAllCells();if(t){if(t.recordIndex===D){if(t.colKeyIndex<w){for(y=t.colKeyIndex;y<=w;y++){this.selectCell(s.cells[y])}}else{if(w<t.colKeyIndex){for(y=w;y<=t.colKeyIndex;y++){this.selectCell(s.cells[y])}}}}else{if(t.recordIndex<D){n=Math.min(t.colKeyIndex,w);k=Math.max(t.colKeyIndex,w);for(y=t.trIndex;y<=r;y++){for(x=n;x<=k;x++){this.selectCell(o[y].cells[x])}}}else{n=Math.min(t.colKeyIndex,w);k=Math.max(t.colKeyIndex,w);for(y=r;y<=t.trIndex;y++){for(x=n;x<=k;x++){this.selectCell(o[y].cells[x])}}}}}else{this._oAnchorCell=p;this.selectCell(p)}}else{if(m){this._oAnchorCell=p;if(this.isSelected(p)){this.unselectCell(p)}else{this.selectCell(p)}}else{this._handleSingleCellSelectionByMouse(A)}}}}},_handleCellBlockSelectionByKey:function(o){var j=g.getCharCode(o);var t=o.shiftKey;if((j==9)||!t){this._handleSingleCellSelectionByKey(o);return}if((j>36)&&(j<41)){var u=this._getSelectionTrigger();if(!u){return null}g.stopEvent(o);var r=this._getSelectionAnchor(u);var k,s,l,q,m;var p=this.getTbodyEl().rows;var n=u.el.parentNode;if(j==40){if(r.recordIndex<=u.recordIndex){m=this.getNextTrEl(u.el);if(m){s=r.colKeyIndex;l=u.colKeyIndex;if(s>l){for(k=s;k>=l;k--){q=m.cells[k];this.selectCell(q)}}else{for(k=s;k<=l;k++){q=m.cells[k];this.selectCell(q)}}}}else{s=Math.min(r.colKeyIndex,u.colKeyIndex);l=Math.max(r.colKeyIndex,u.colKeyIndex);for(k=s;k<=l;k++){this.unselectCell(n.cells[k])}}}else{if(j==38){if(r.recordIndex>=u.recordIndex){m=this.getPreviousTrEl(u.el);if(m){s=r.colKeyIndex;l=u.colKeyIndex;if(s>l){for(k=s;k>=l;k--){q=m.cells[k];this.selectCell(q)}}else{for(k=s;k<=l;k++){q=m.cells[k];this.selectCell(q)}}}}else{s=Math.min(r.colKeyIndex,u.colKeyIndex);l=Math.max(r.colKeyIndex,u.colKeyIndex);for(k=s;k<=l;k++){this.unselectCell(n.cells[k])}}}else{if(j==39){if(r.colKeyIndex<=u.colKeyIndex){if(u.colKeyIndex<n.cells.length-1){s=r.trIndex;l=u.trIndex;if(s>l){for(k=s;k>=l;k--){q=p[k].cells[u.colKeyIndex+1];this.selectCell(q)}}else{for(k=s;k<=l;k++){q=p[k].cells[u.colKeyIndex+1];this.selectCell(q)}}}}else{s=Math.min(r.trIndex,u.trIndex);l=Math.max(r.trIndex,u.trIndex);for(k=s;k<=l;k++){this.unselectCell(p[k].cells[u.colKeyIndex])}}}else{if(j==37){if(r.colKeyIndex>=u.colKeyIndex){if(u.colKeyIndex>0){s=r.trIndex;l=u.trIndex;if(s>l){for(k=s;k>=l;k--){q=p[k].cells[u.colKeyIndex-1];this.selectCell(q)}}else{for(k=s;k<=l;k++){q=p[k].cells[u.colKeyIndex-1];this.selectCell(q)}}}}else{s=Math.min(r.trIndex,u.trIndex);l=Math.max(r.trIndex,u.trIndex);for(k=s;k<=l;k++){this.unselectCell(p[k].cells[u.colKeyIndex])}}}}}}}},_handleCellRangeSelectionByMouse:function(y){var z=y.target;var k=this.getTdEl(z);if(k){var x=y.event;var o=x.shiftKey;var l=x.ctrlKey||((navigator.userAgent.toLowerCase().indexOf("mac")!=-1)&&x.metaKey);var q=this.getTrEl(k);var p=this.getTrIndex(q);var t=this.getColumn(k);var u=t.getKeyIndex();var s=this.getRecord(q);var B=this._oRecordSet.getRecordIndex(s);var n={record:s,column:t};var r=this._getSelectionAnchor();var m=this.getTbodyEl().rows;var A,w,v;if(o&&l){if(r){if(this.isSelected(r.cell)){if(r.recordIndex===B){if(r.colKeyIndex<u){for(w=r.colKeyIndex+1;w<=u;w++){this.selectCell(q.cells[w])}}else{if(u<r.colKeyIndex){for(w=u;w<r.colKeyIndex;w++){this.selectCell(q.cells[w])}}}}else{if(r.recordIndex<B){for(w=r.colKeyIndex+1;w<q.cells.length;w++){this.selectCell(q.cells[w])}for(w=r.trIndex+1;w<p;w++){for(v=0;v<m[w].cells.length;v++){this.selectCell(m[w].cells[v])}}for(w=0;w<=u;w++){this.selectCell(q.cells[w])}}else{for(w=u;w<q.cells.length;w++){this.selectCell(q.cells[w])}for(w=p+1;w<r.trIndex;w++){for(v=0;v<m[w].cells.length;v++){this.selectCell(m[w].cells[v])}}for(w=0;w<r.colKeyIndex;w++){this.selectCell(q.cells[w])}}}}else{if(r.recordIndex===B){if(r.colKeyIndex<u){for(w=r.colKeyIndex+1;w<u;w++){this.unselectCell(q.cells[w])}}else{if(u<r.colKeyIndex){for(w=u+1;w<r.colKeyIndex;w++){this.unselectCell(q.cells[w])}}}}if(r.recordIndex<B){for(w=r.trIndex;w<=p;w++){A=m[w];for(v=0;v<A.cells.length;v++){if(A.sectionRowIndex===r.trIndex){if(v>r.colKeyIndex){this.unselectCell(A.cells[v])}}else{if(A.sectionRowIndex===p){if(v<u){this.unselectCell(A.cells[v])}}else{this.unselectCell(A.cells[v])}}}}}else{for(w=p;w<=r.trIndex;w++){A=m[w];for(v=0;v<A.cells.length;v++){if(A.sectionRowIndex==p){if(v>u){this.unselectCell(A.cells[v])}}else{if(A.sectionRowIndex==r.trIndex){if(v<r.colKeyIndex){this.unselectCell(A.cells[v])}}else{this.unselectCell(A.cells[v])}}}}}this.selectCell(k)}}else{this._oAnchorCell=n;if(this.isSelected(n)){this.unselectCell(n)}else{this.selectCell(n)}}}else{if(o){this.unselectAllCells();if(r){if(r.recordIndex===B){if(r.colKeyIndex<u){for(w=r.colKeyIndex;w<=u;w++){this.selectCell(q.cells[w])}}else{if(u<r.colKeyIndex){for(w=u;w<=r.colKeyIndex;w++){this.selectCell(q.cells[w])}}}}else{if(r.recordIndex<B){for(w=r.trIndex;w<=p;w++){A=m[w];for(v=0;v<A.cells.length;v++){if(A.sectionRowIndex==r.trIndex){if(v>=r.colKeyIndex){this.selectCell(A.cells[v])}}else{if(A.sectionRowIndex==p){if(v<=u){this.selectCell(A.cells[v])}}else{this.selectCell(A.cells[v])}}}}}else{for(w=p;w<=r.trIndex;w++){A=m[w];for(v=0;v<A.cells.length;v++){if(A.sectionRowIndex==p){if(v>=u){this.selectCell(A.cells[v])}}else{if(A.sectionRowIndex==r.trIndex){if(v<=r.colKeyIndex){this.selectCell(A.cells[v])}}else{this.selectCell(A.cells[v])}}}}}}}else{this._oAnchorCell=n;this.selectCell(n)}}else{if(l){this._oAnchorCell=n;if(this.isSelected(n)){this.unselectCell(n)}else{this.selectCell(n)}}else{this._handleSingleCellSelectionByMouse(y)}}}}},_handleCellRangeSelectionByKey:function(n){var j=g.getCharCode(n);var r=n.shiftKey;if((j==9)||!r){this._handleSingleCellSelectionByKey(n);return}if((j>36)&&(j<41)){var s=this._getSelectionTrigger();if(!s){return null}g.stopEvent(n);var q=this._getSelectionAnchor(s);var k,l,p;var o=this.getTbodyEl().rows;var m=s.el.parentNode;if(j==40){l=this.getNextTrEl(s.el);if(q.recordIndex<=s.recordIndex){for(k=s.colKeyIndex+1;k<m.cells.length;k++){p=m.cells[k];this.selectCell(p)}if(l){for(k=0;k<=s.colKeyIndex;k++){p=l.cells[k];this.selectCell(p)}}}else{for(k=s.colKeyIndex;k<m.cells.length;k++){this.unselectCell(m.cells[k])}if(l){for(k=0;k<s.colKeyIndex;k++){this.unselectCell(l.cells[k])}}}}else{if(j==38){l=this.getPreviousTrEl(s.el);if(q.recordIndex>=s.recordIndex){for(k=s.colKeyIndex-1;k>-1;k--){p=m.cells[k];this.selectCell(p)}if(l){for(k=m.cells.length-1;k>=s.colKeyIndex;k--){p=l.cells[k];this.selectCell(p)}}}else{for(k=s.colKeyIndex;k>-1;k--){this.unselectCell(m.cells[k])}if(l){for(k=m.cells.length-1;k>s.colKeyIndex;k--){this.unselectCell(l.cells[k])}}}}else{if(j==39){l=this.getNextTrEl(s.el);if(q.recordIndex<s.recordIndex){if(s.colKeyIndex<m.cells.length-1){p=m.cells[s.colKeyIndex+1];this.selectCell(p)}else{if(l){p=l.cells[0];this.selectCell(p)}}}else{if(q.recordIndex>s.recordIndex){this.unselectCell(m.cells[s.colKeyIndex]);if(s.colKeyIndex<m.cells.length-1){}else{}}else{if(q.colKeyIndex<=s.colKeyIndex){if(s.colKeyIndex<m.cells.length-1){p=m.cells[s.colKeyIndex+1];this.selectCell(p)}else{if(s.trIndex<o.length-1){p=l.cells[0];this.selectCell(p)}}}else{this.unselectCell(m.cells[s.colKeyIndex])}}}}else{if(j==37){l=this.getPreviousTrEl(s.el);if(q.recordIndex<s.recordIndex){this.unselectCell(m.cells[s.colKeyIndex]);if(s.colKeyIndex>0){}else{}}else{if(q.recordIndex>s.recordIndex){if(s.colKeyIndex>0){p=m.cells[s.colKeyIndex-1];this.selectCell(p)}else{if(s.trIndex>0){p=l.cells[l.cells.length-1];this.selectCell(p)}}}else{if(q.colKeyIndex>=s.colKeyIndex){if(s.colKeyIndex>0){p=m.cells[s.colKeyIndex-1];this.selectCell(p)}else{if(s.trIndex>0){p=l.cells[l.cells.length-1];this.selectCell(p)}}}else{this.unselectCell(m.cells[s.colKeyIndex]);if(s.colKeyIndex>0){}else{}}}}}}}}}},_handleSingleCellSelectionByMouse:function(n){var o=n.target;var k=this.getTdEl(o);if(k){var j=this.getTrEl(k);var i=this.getRecord(j);var m=this.getColumn(k);var l={record:i,column:m};this._oAnchorCell=l;this.unselectAllCells();this.selectCell(l)}},_handleSingleCellSelectionByKey:function(m){var i=g.getCharCode(m);if((i==9)||((i>36)&&(i<41))){var k=m.shiftKey;var j=this._getSelectionTrigger();if(!j){return null}var l;if(i==40){l=this.getBelowTdEl(j.el);if(l===null){l=j.el}}else{if(i==38){l=this.getAboveTdEl(j.el);if(l===null){l=j.el}}else{if((i==39)||(!k&&(i==9))){l=this.getNextTdEl(j.el);if(l===null){return}}else{if((i==37)||(k&&(i==9))){l=this.getPreviousTdEl(j.el);if(l===null){return}}}}}g.stopEvent(m);this.unselectAllCells();this.selectCell(l);this._oAnchorCell={record:this.getRecord(l),column:this.getColumn(l)}}},getSelectedTrEls:function(){return c.getElementsByClassName(d.CLASS_SELECTED,"tr",this._elTbody)},selectRow:function(p){var o,i;if(p instanceof YAHOO.widget.Record){o=this._oRecordSet.getRecord(p);i=this.getTrEl(o)}else{if(h.isNumber(p)){o=this.getRecord(p);i=this.getTrEl(o)}else{i=this.getTrEl(p);o=this.getRecord(i)}}if(o){var n=this._aSelections||[];var m=o.getId();var l=-1;if(n.indexOf){l=n.indexOf(m)}else{for(var k=n.length-1;k>-1;k--){if(n[k]===m){l=k;break}}}if(l>-1){n.splice(l,1)}n.push(m);this._aSelections=n;if(!this._oAnchorRecord){this._oAnchorRecord=o}if(i){c.addClass(i,d.CLASS_SELECTED)}this.fireEvent("rowSelectEvent",{record:o,el:i})}else{}},unselectRow:function(p){var i=this.getTrEl(p);var o;if(p instanceof YAHOO.widget.Record){o=this._oRecordSet.getRecord(p)}else{if(h.isNumber(p)){o=this.getRecord(p)}else{o=this.getRecord(i)}}if(o){var n=this._aSelections||[];var m=o.getId();var l=-1;if(n.indexOf){l=n.indexOf(m)}else{for(var k=n.length-1;k>-1;k--){if(n[k]===m){l=k;break}}}if(l>-1){n.splice(l,1);this._aSelections=n;c.removeClass(i,d.CLASS_SELECTED);this.fireEvent("rowUnselectEvent",{record:o,el:i});return}}},unselectAllRows:function(){var k=this._aSelections||[],m,l=[];for(var i=k.length-1;i>-1;i--){if(h.isString(k[i])){m=k.splice(i,1);l[l.length]=this.getRecord(h.isArray(m)?m[0]:m)}}this._aSelections=k;this._unselectAllTrEls();this.fireEvent("unselectAllRowsEvent",{records:l})},_unselectAllTdEls:function(){var i=c.getElementsByClassName(d.CLASS_SELECTED,"td",this._elTbody);c.removeClass(i,d.CLASS_SELECTED)},getSelectedTdEls:function(){return c.getElementsByClassName(d.CLASS_SELECTED,"td",this._elTbody)},selectCell:function(i){var p=this.getTdEl(i);if(p){var o=this.getRecord(p);var q=this.getColumn(this.getCellIndex(p));var m=q.getKey();if(o&&m){var n=this._aSelections||[];var l=o.getId();for(var k=n.length-1;k>-1;k--){if((n[k].recordId===l)&&(n[k].columnKey===m)){n.splice(k,1);break}}n.push({recordId:l,columnKey:m});this._aSelections=n;if(!this._oAnchorCell){this._oAnchorCell={record:o,column:q}}c.addClass(p,d.CLASS_SELECTED);this.fireEvent("cellSelectEvent",{record:o,column:q,key:m,el:p});return}}},unselectCell:function(i){var o=this.getTdEl(i);if(o){var n=this.getRecord(o);var p=this.getColumn(this.getCellIndex(o));var l=p.getKey();if(n&&l){var m=this._aSelections||[];var q=n.getId();for(var k=m.length-1;k>-1;k--){if((m[k].recordId===q)&&(m[k].columnKey===l)){m.splice(k,1);this._aSelections=m;c.removeClass(o,d.CLASS_SELECTED);this.fireEvent("cellUnselectEvent",{record:n,column:p,key:l,el:o});return}}}}},unselectAllCells:function(){var k=this._aSelections||[];for(var i=k.length-1;i>-1;i--){if(h.isObject(k[i])){k.splice(i,1)}}this._aSelections=k;this._unselectAllTdEls();this.fireEvent("unselectAllCellsEvent")},isSelected:function(p){if(p&&(p.ownerDocument==document)){return(c.hasClass(this.getTdEl(p),d.CLASS_SELECTED)||c.hasClass(this.getTrEl(p),d.CLASS_SELECTED))}else{var n,k,i;var m=this._aSelections;if(m&&m.length>0){if(p instanceof YAHOO.widget.Record){n=p}else{if(h.isNumber(p)){n=this.getRecord(p)}}if(n){k=n.getId();if(m.indexOf){if(m.indexOf(k)>-1){return true}}else{for(i=m.length-1;i>-1;i--){if(m[i]===k){return true}}}}else{if(p.record&&p.column){k=p.record.getId();var l=p.column.getKey();for(i=m.length-1;i>-1;i--){if((m[i].recordId===k)&&(m[i].columnKey===l)){return true}}}}}}return false},getSelectedRows:function(){var i=[];var l=this._aSelections||[];for(var k=0;k<l.length;k++){if(h.isString(l[k])){i.push(l[k])}}return i},getSelectedCells:function(){var k=[];var l=this._aSelections||[];for(var i=0;i<l.length;i++){if(l[i]&&h.isObject(l[i])){k.push(l[i])}}return k},getLastSelectedRecord:function(){var k=this._aSelections;if(k&&k.length>0){for(var j=k.length-1;j>-1;j--){if(h.isString(k[j])){return k[j]}}}},getLastSelectedCell:function(){var k=this._aSelections;if(k&&k.length>0){for(var j=k.length-1;j>-1;j--){if(k[j].recordId&&k[j].columnKey){return k[j]}}}},highlightRow:function(k){var i=this.getTrEl(k);if(i){var j=this.getRecord(i);c.addClass(i,d.CLASS_HIGHLIGHTED);this.fireEvent("rowHighlightEvent",{record:j,el:i});return}},unhighlightRow:function(k){var i=this.getTrEl(k);if(i){var j=this.getRecord(i);c.removeClass(i,d.CLASS_HIGHLIGHTED);this.fireEvent("rowUnhighlightEvent",{record:j,el:i});return}},highlightCell:function(i){var l=this.getTdEl(i);if(l){if(this._elLastHighlightedTd){this.unhighlightCell(this._elLastHighlightedTd)}var k=this.getRecord(l);var m=this.getColumn(this.getCellIndex(l));var j=m.getKey();c.addClass(l,d.CLASS_HIGHLIGHTED);this._elLastHighlightedTd=l;this.fireEvent("cellHighlightEvent",{record:k,column:m,key:j,el:l});return}},unhighlightCell:function(i){var k=this.getTdEl(i);if(k){var j=this.getRecord(k);c.removeClass(k,d.CLASS_HIGHLIGHTED);this._elLastHighlightedTd=null;this.fireEvent("cellUnhighlightEvent",{record:j,column:this.getColumn(this.getCellIndex(k)),key:this.getColumn(this.getCellIndex(k)).getKey(),el:k});return}},addCellEditor:function(j,i){j.editor=i;j.editor.subscribe("showEvent",this._onEditorShowEvent,this,true);j.editor.subscribe("keydownEvent",this._onEditorKeydownEvent,this,true);j.editor.subscribe("revertEvent",this._onEditorRevertEvent,this,true);j.editor.subscribe("saveEvent",this._onEditorSaveEvent,this,true);j.editor.subscribe("cancelEvent",this._onEditorCancelEvent,this,true);j.editor.subscribe("blurEvent",this._onEditorBlurEvent,this,true);j.editor.subscribe("blockEvent",this._onEditorBlockEvent,this,true);j.editor.subscribe("unblockEvent",this._onEditorUnblockEvent,this,true)},getCellEditor:function(){return this._oCellEditor},showCellEditor:function(p,q,l){p=this.getTdEl(p);if(p){l=this.getColumn(p);if(l&&l.editor){var j=this._oCellEditor;if(j){if(this._oCellEditor.cancel){this._oCellEditor.cancel()}else{if(j.isActive){this.cancelCellEditor()}}}if(l.editor instanceof YAHOO.widget.BaseCellEditor){j=l.editor;var n=j.attach(this,p);if(n){j.render();j.move();n=this.doBeforeShowCellEditor(j);if(n){j.show();this._oCellEditor=j}}}else{if(!q||!(q instanceof YAHOO.widget.Record)){q=this.getRecord(p)}if(!l||!(l instanceof YAHOO.widget.Column)){l=this.getColumn(p)}if(q&&l){if(!this._oCellEditor||this._oCellEditor.container){this._initCellEditorEl()}j=this._oCellEditor;j.cell=p;j.record=q;j.column=l;j.validator=(l.editorOptions&&h.isFunction(l.editorOptions.validator))?l.editorOptions.validator:null;j.value=q.getData(l.key);j.defaultValue=null;var k=j.container;var o=c.getX(p);var m=c.getY(p);if(isNaN(o)||isNaN(m)){o=p.offsetLeft+c.getX(this._elTbody.parentNode)-this._elTbody.scrollLeft;m=p.offsetTop+c.getY(this._elTbody.parentNode)-this._elTbody.scrollTop+this._elThead.offsetHeight}k.style.left=o+"px";k.style.top=m+"px";this.doBeforeShowCellEditor(this._oCellEditor);k.style.display="";g.addListener(k,"keydown",function(s,r){if((s.keyCode==27)){r.cancelCellEditor();r.focusTbodyEl()}else{r.fireEvent("editorKeydownEvent",{editor:r._oCellEditor,event:s})}},this);var i;if(h.isString(l.editor)){switch(l.editor){case"checkbox":i=d.editCheckbox;break;case"date":i=d.editDate;break;case"dropdown":i=d.editDropdown;break;case"radio":i=d.editRadio;break;case"textarea":i=d.editTextarea;break;case"textbox":i=d.editTextbox;break;default:i=null}}else{if(h.isFunction(l.editor)){i=l.editor}}if(i){i(this._oCellEditor,this);if(!l.editorOptions||!l.editorOptions.disableBtns){this.showCellEditorBtns(k)}j.isActive=true;this.fireEvent("editorShowEvent",{editor:j});return}}}}}},_initCellEditorEl:function(){var i=document.createElement("div");i.id=this._sId+"-celleditor";i.style.display="none";i.tabIndex=0;c.addClass(i,d.CLASS_EDITOR);var k=c.getFirstChild(document.body);if(k){i=c.insertBefore(i,k)}else{i=document.body.appendChild(i)}var j={};j.container=i;j.value=null;j.isActive=false;this._oCellEditor=j},doBeforeShowCellEditor:function(i){return true},saveCellEditor:function(){if(this._oCellEditor){if(this._oCellEditor.save){this._oCellEditor.save()}else{if(this._oCellEditor.isActive){var i=this._oCellEditor.value;var j=this._oCellEditor.record.getData(this._oCellEditor.column.key);if(this._oCellEditor.validator){i=this._oCellEditor.value=this._oCellEditor.validator.call(this,i,j,this._oCellEditor);if(i===null){this.resetCellEditor();this.fireEvent("editorRevertEvent",{editor:this._oCellEditor,oldData:j,newData:i});return}}this._oRecordSet.updateRecordValue(this._oCellEditor.record,this._oCellEditor.column.key,this._oCellEditor.value);this.formatCell(this._oCellEditor.cell.firstChild,this._oCellEditor.record,this._oCellEditor.column);this._oChainRender.add({method:function(){this.validateColumnWidths()},scope:this});this._oChainRender.run();this.resetCellEditor();this.fireEvent("editorSaveEvent",{editor:this._oCellEditor,oldData:j,newData:i})}}}},cancelCellEditor:function(){if(this._oCellEditor){if(this._oCellEditor.cancel){this._oCellEditor.cancel()}else{if(this._oCellEditor.isActive){this.resetCellEditor();this.fireEvent("editorCancelEvent",{editor:this._oCellEditor})}}}},destroyCellEditor:function(){if(this._oCellEditor){this._oCellEditor.destroy();this._oCellEditor=null}},_onEditorShowEvent:function(i){this.fireEvent("editorShowEvent",i)},_onEditorKeydownEvent:function(i){this.fireEvent("editorKeydownEvent",i)},_onEditorRevertEvent:function(i){this.fireEvent("editorRevertEvent",i)},_onEditorSaveEvent:function(i){this.fireEvent("editorSaveEvent",i)},_onEditorCancelEvent:function(i){this.fireEvent("editorCancelEvent",i)},_onEditorBlurEvent:function(i){this.fireEvent("editorBlurEvent",i)},_onEditorBlockEvent:function(i){this.fireEvent("editorBlockEvent",i)},_onEditorUnblockEvent:function(i){this.fireEvent("editorUnblockEvent",i)},onEditorBlurEvent:function(i){if(i.editor.disableBtns){if(i.editor.save){i.editor.save()}}else{if(i.editor.cancel){i.editor.cancel()}}},onEditorBlockEvent:function(i){this.disable()},onEditorUnblockEvent:function(i){this.undisable()},doBeforeLoadData:function(i,j,k){return true},onEventSortColumn:function(k){var i=k.event;var m=k.target;var j=this.getThEl(m)||this.getTdEl(m);if(j){var l=this.getColumn(j);if(l.sortable){g.stopEvent(i);this.sortColumn(l)}}else{}},onEventSelectColumn:function(i){this.selectColumn(i.target)},onEventHighlightColumn:function(i){this.highlightColumn(i.target)},onEventUnhighlightColumn:function(i){this.unhighlightColumn(i.target)},onEventSelectRow:function(j){var i=this.get("selectionMode");if(i=="single"){this._handleSingleSelectionByMouse(j)}else{this._handleStandardSelectionByMouse(j)}},onEventSelectCell:function(j){var i=this.get("selectionMode");if(i=="cellblock"){this._handleCellBlockSelectionByMouse(j)}else{if(i=="cellrange"){this._handleCellRangeSelectionByMouse(j)}else{this._handleSingleCellSelectionByMouse(j)}}},onEventHighlightRow:function(i){this.highlightRow(i.target)},onEventUnhighlightRow:function(i){this.unhighlightRow(i.target)},onEventHighlightCell:function(i){this.highlightCell(i.target)},onEventUnhighlightCell:function(i){this.unhighlightCell(i.target)},onEventFormatCell:function(i){var l=i.target;var j=this.getTdEl(l);if(j){var k=this.getColumn(this.getCellIndex(j));this.formatCell(j.firstChild,this.getRecord(j),k)}else{}},onEventShowCellEditor:function(i){if(!this.isDisabled()){this.showCellEditor(i.target)}},onEventSaveCellEditor:function(i){if(this._oCellEditor){if(this._oCellEditor.save){this._oCellEditor.save()}else{this.saveCellEditor()}}},onEventCancelCellEditor:function(i){if(this._oCellEditor){if(this._oCellEditor.cancel){this._oCellEditor.cancel()}else{this.cancelCellEditor()}}},onDataReturnInitializeTable:function(i,j,k){if((this instanceof d)&&this._sId){this.initializeTable();this.onDataReturnSetRows(i,j,k)}},onDataReturnReplaceRows:function(m,l,n){if((this instanceof d)&&this._sId){this.fireEvent("dataReturnEvent",{request:m,response:l,payload:n});var j=this.doBeforeLoadData(m,l,n),k=this.get("paginator"),i=0;if(j&&l&&!l.error&&h.isArray(l.results)){this._oRecordSet.reset();if(this.get("dynamicData")){if(n&&n.pagination&&h.isNumber(n.pagination.recordOffset)){i=n.pagination.recordOffset}else{if(k){i=k.getStartIndex()}}}this._oRecordSet.setRecords(l.results,i|0);this._handleDataReturnPayload(m,l,n);this.render()}else{if(j&&l.error){this.showTableMessage(this.get("MSG_ERROR"),d.CLASS_ERROR)}}}},onDataReturnAppendRows:function(j,k,l){if((this instanceof d)&&this._sId){this.fireEvent("dataReturnEvent",{request:j,response:k,payload:l});var i=this.doBeforeLoadData(j,k,l);if(i&&k&&!k.error&&h.isArray(k.results)){this.addRows(k.results);this._handleDataReturnPayload(j,k,l)}else{if(i&&k.error){this.showTableMessage(this.get("MSG_ERROR"),d.CLASS_ERROR)}}}},onDataReturnInsertRows:function(j,k,l){if((this instanceof d)&&this._sId){this.fireEvent("dataReturnEvent",{request:j,response:k,payload:l});var i=this.doBeforeLoadData(j,k,l);if(i&&k&&!k.error&&h.isArray(k.results)){this.addRows(k.results,(l?l.insertIndex:0));this._handleDataReturnPayload(j,k,l)}else{if(i&&k.error){this.showTableMessage(this.get("MSG_ERROR"),d.CLASS_ERROR)}}}},onDataReturnUpdateRows:function(j,k,l){if((this instanceof d)&&this._sId){this.fireEvent("dataReturnEvent",{request:j,response:k,payload:l});var i=this.doBeforeLoadData(j,k,l);if(i&&k&&!k.error&&h.isArray(k.results)){this.updateRows((l?l.updateIndex:0),k.results);this._handleDataReturnPayload(j,k,l)}else{if(i&&k.error){this.showTableMessage(this.get("MSG_ERROR"),d.CLASS_ERROR)}}}},onDataReturnSetRows:function(m,l,n){if((this instanceof d)&&this._sId){this.fireEvent("dataReturnEvent",{request:m,response:l,payload:n});var j=this.doBeforeLoadData(m,l,n),k=this.get("paginator"),i=0;if(j&&l&&!l.error&&h.isArray(l.results)){if(this.get("dynamicData")){if(n&&n.pagination&&h.isNumber(n.pagination.recordOffset)){i=n.pagination.recordOffset}else{if(k){i=k.getStartIndex()}}this._oRecordSet.reset()}this._oRecordSet.setRecords(l.results,i|0);this._handleDataReturnPayload(m,l,n);this.render()}else{if(j&&l.error){this.showTableMessage(this.get("MSG_ERROR"),d.CLASS_ERROR)}}}else{}},handleDataReturnPayload:function(j,i,k){return k||{}},_handleDataReturnPayload:function(k,j,l){l=this.handleDataReturnPayload(k,j,l);if(l){var i=this.get("paginator");if(i){if(this.get("dynamicData")){if(e.Paginator.isNumeric(l.totalRecords)){i.set("totalRecords",l.totalRecords)}}else{i.set("totalRecords",this._oRecordSet.getLength())}if(h.isObject(l.pagination)){i.set("rowsPerPage",l.pagination.rowsPerPage);i.set("recordOffset",l.pagination.recordOffset)}}if(l.sortedBy){this.set("sortedBy",l.sortedBy)}else{if(l.sorting){this.set("sortedBy",l.sorting)}}}},showCellEditorBtns:function(k){var l=k.appendChild(document.createElement("div"));c.addClass(l,d.CLASS_BUTTON);var j=l.appendChild(document.createElement("button"));c.addClass(j,d.CLASS_DEFAULT);j.innerHTML="OK";g.addListener(j,"click",function(n,m){m.onEventSaveCellEditor(n,m);m.focusTbodyEl()},this,true);var i=l.appendChild(document.createElement("button"));i.innerHTML="Cancel";g.addListener(i,"click",function(n,m){m.onEventCancelCellEditor(n,m);m.focusTbodyEl()},this,true)},resetCellEditor:function(){var i=this._oCellEditor.container;i.style.display="none";g.purgeElement(i,true);i.innerHTML="";this._oCellEditor.value=null;this._oCellEditor.isActive=false},getBody:function(){return this.getTbodyEl()},getCell:function(i){return this.getTdEl(i)},getRow:function(i){return this.getTrEl(i)},refreshView:function(){this.render()},select:function(k){if(!h.isArray(k)){k=[k]}for(var j=0;j<k.length;j++){this.selectRow(k[j])}},onEventEditCell:function(i){this.onEventShowCellEditor(i)},_syncColWidths:function(){this.validateColumnWidths()}});d.prototype.onDataReturnSetRecords=d.prototype.onDataReturnSetRows;d.prototype.onPaginatorChange=d.prototype.onPaginatorChangeRequest;d.editCheckbox=function(){};d.editDate=function(){};d.editDropdown=function(){};d.editRadio=function(){};d.editTextarea=function(){};d.editTextbox=function(){}})();(function(){var c=YAHOO.lang,f=YAHOO.util,e=YAHOO.widget,a=YAHOO.env.ua,d=f.Dom,j=f.Event,i=f.DataSourceBase,g=e.DataTable,b=e.Paginator;e.ScrollingDataTable=function(n,m,k,l){l=l||{};if(l.scrollable){l.scrollable=false}this._init();e.ScrollingDataTable.superclass.constructor.call(this,n,m,k,l);this.subscribe("columnShowEvent",this._onColumnChange)};var h=e.ScrollingDataTable;c.augmentObject(h,{CLASS_HEADER:"yui-dt-hd",CLASS_BODY:"yui-dt-bd"});c.extend(h,g,{_elHdContainer:null,_elHdTable:null,_elBdContainer:null,_elBdThead:null,_elTmpContainer:null,_elTmpTable:null,_bScrollbarX:null,initAttributes:function(k){k=k||{};h.superclass.initAttributes.call(this,k);this.setAttributeConfig("width",{value:null,validator:c.isString,method:function(l){if(this._elHdContainer&&this._elBdContainer){this._elHdContainer.style.width=l;this._elBdContainer.style.width=l;this._syncScrollX();this._syncScrollOverhang()}}});this.setAttributeConfig("height",{value:null,validator:c.isString,method:function(l){if(this._elHdContainer&&this._elBdContainer){this._elBdContainer.style.height=l;this._syncScrollX();this._syncScrollY();this._syncScrollOverhang()}}});this.setAttributeConfig("COLOR_COLUMNFILLER",{value:"#F2F2F2",validator:c.isString,method:function(l){if(this._elHdContainer){this._elHdContainer.style.backgroundColor=l}}})},_init:function(){this._elHdContainer=null;this._elHdTable=null;this._elBdContainer=null;this._elBdThead=null;this._elTmpContainer=null;this._elTmpTable=null},_initDomElements:function(k){this._initContainerEl(k);if(this._elContainer&&this._elHdContainer&&this._elBdContainer){this._initTableEl();if(this._elHdTable&&this._elTable){this._initColgroupEl(this._elHdTable);this._initTheadEl(this._elHdTable,this._elTable);this._initTbodyEl(this._elTable);this._initMsgTbodyEl(this._elTable)}}if(!this._elContainer||!this._elTable||!this._elColgroup||!this._elThead||!this._elTbody||!this._elMsgTbody||!this._elHdTable||!this._elBdThead){return false}else{return true}},_destroyContainerEl:function(k){d.removeClass(k,g.CLASS_SCROLLABLE);h.superclass._destroyContainerEl.call(this,k);this._elHdContainer=null;this._elBdContainer=null},_initContainerEl:function(l){h.superclass._initContainerEl.call(this,l);if(this._elContainer){l=this._elContainer;d.addClass(l,g.CLASS_SCROLLABLE);var k=document.createElement("div");k.style.width=this.get("width")||"";k.style.backgroundColor=this.get("COLOR_COLUMNFILLER");d.addClass(k,h.CLASS_HEADER);this._elHdContainer=k;l.appendChild(k);var m=document.createElement("div");m.style.width=this.get("width")||"";m.style.height=this.get("height")||"";d.addClass(m,h.CLASS_BODY);j.addListener(m,"scroll",this._onScroll,this);this._elBdContainer=m;l.appendChild(m)}},_initCaptionEl:function(k){},_destroyHdTableEl:function(){var k=this._elHdTable;if(k){j.purgeElement(k,true);k.parentNode.removeChild(k);this._elBdThead=null}},_initTableEl:function(){if(this._elHdContainer){this._destroyHdTableEl();this._elHdTable=this._elHdContainer.appendChild(document.createElement("table"));j.delegate(this._elHdTable,"mouseenter",this._onTableMouseover,"thead ."+g.CLASS_LABEL,this);j.delegate(this._elHdTable,"mouseleave",this._onTableMouseout,"thead ."+g.CLASS_LABEL,this)}h.superclass._initTableEl.call(this,this._elBdContainer)},_initTheadEl:function(l,k){l=l||this._elHdTable;k=k||this._elTable;this._initBdTheadEl(k);h.superclass._initTheadEl.call(this,l)},_initThEl:function(l,k){h.superclass._initThEl.call(this,l,k);l.id=this.getId()+"-fixedth-"+k.getSanitizedKey()},_destroyBdTheadEl:function(){var k=this._elBdThead;if(k){var l=k.parentNode;j.purgeElement(k,true);l.removeChild(k);this._elBdThead=null;this._destroyColumnHelpers()}},_initBdTheadEl:function(t){if(t){this._destroyBdTheadEl();var p=t.insertBefore(document.createElement("thead"),t.firstChild);var v=this._oColumnSet,u=v.tree,o,l,s,q,n,m,r;for(q=0,m=u.length;q<m;q++){l=p.appendChild(document.createElement("tr"));for(n=0,r=u[q].length;n<r;n++){s=u[q][n];o=l.appendChild(document.createElement("th"));this._initBdThEl(o,s,q,n)}}this._elBdThead=p}},_initBdThEl:function(n,m){n.id=this.getId()+"-th-"+m.getSanitizedKey();n.rowSpan=m.getRowspan();n.colSpan=m.getColspan();if(m.abbr){n.abbr=m.abbr}var l=m.getKey();var k=c.isValue(m.label)?m.label:l;n.innerHTML=k},_initTbodyEl:function(k){h.superclass._initTbodyEl.call(this,k);k.style.marginTop=(this._elTbody.offsetTop>0)?"-"+this._elTbody.offsetTop+"px":0},_focusEl:function(l){l=l||this._elTbody;var k=this;this._storeScrollPositions();setTimeout(function(){setTimeout(function(){try{l.focus();k._restoreScrollPositions()}catch(m){}},0)},0)},_runRenderChain:function(){this._storeScrollPositions();this._oChainRender.run()},_storeScrollPositions:function(){this._nScrollTop=this._elBdContainer.scrollTop;this._nScrollLeft=this._elBdContainer.scrollLeft},clearScrollPositions:function(){this._nScrollTop=0;this._nScrollLeft=0},_restoreScrollPositions:function(){if(this._nScrollTop){this._elBdContainer.scrollTop=this._nScrollTop;this._nScrollTop=null}if(this._nScrollLeft){this._elBdContainer.scrollLeft=this._nScrollLeft;this._elHdContainer.scrollLeft=this._nScrollLeft;this._nScrollLeft=null}},_validateColumnWidth:function(n,k){if(!n.width&&!n.hidden){var p=n.getThEl();if(n._calculatedWidth){this._setColumnWidth(n,"auto","visible")}if(p.offsetWidth!==k.offsetWidth){var m=(p.offsetWidth>k.offsetWidth)?n.getThLinerEl():k.firstChild;var l=Math.max(0,(m.offsetWidth-(parseInt(d.getStyle(m,"paddingLeft"),10)|0)-(parseInt(d.getStyle(m,"paddingRight"),10)|0)),n.minWidth);var o="visible";if((n.maxAutoWidth>0)&&(l>n.maxAutoWidth)){l=n.maxAutoWidth;o="hidden"}this._elTbody.style.display="none";this._setColumnWidth(n,l+"px",o);n._calculatedWidth=l;this._elTbody.style.display=""}}},validateColumnWidths:function(s){var u=this._oColumnSet.keys,w=u.length,l=this.getFirstTrEl();if(a.ie){this._setOverhangValue(1)}if(u&&l&&(l.childNodes.length===w)){var m=this.get("width");if(m){this._elHdContainer.style.width="";this._elBdContainer.style.width=""}this._elContainer.style.width="";if(s&&c.isNumber(s.getKeyIndex())){this._validateColumnWidth(s,l.childNodes[s.getKeyIndex()])}else{var t,k=[],o,q,r;for(q=0;q<w;q++){s=u[q];if(!s.width&&!s.hidden&&s._calculatedWidth){k[k.length]=s}}this._elTbody.style.display="none";for(q=0,r=k.length;q<r;q++){this._setColumnWidth(k[q],"auto","visible")}this._elTbody.style.display="";k=[];for(q=0;q<w;q++){s=u[q];t=l.childNodes[q];if(!s.width&&!s.hidden){var n=s.getThEl();if(n.offsetWidth!==t.offsetWidth){var v=(n.offsetWidth>t.offsetWidth)?s.getThLinerEl():t.firstChild;var p=Math.max(0,(v.offsetWidth-(parseInt(d.getStyle(v,"paddingLeft"),10)|0)-(parseInt(d.getStyle(v,"paddingRight"),10)|0)),s.minWidth);var x="visible";if((s.maxAutoWidth>0)&&(p>s.maxAutoWidth)){p=s.maxAutoWidth;x="hidden"}k[k.length]=[s,p,x]}}}this._elTbody.style.display="none";for(q=0,r=k.length;q<r;q++){o=k[q];this._setColumnWidth(o[0],o[1]+"px",o[2]);o[0]._calculatedWidth=o[1]}this._elTbody.style.display=""}if(m){this._elHdContainer.style.width=m;this._elBdContainer.style.width=m}}this._syncScroll();this._restoreScrollPositions()},_syncScroll:function(){this._syncScrollX();this._syncScrollY();this._syncScrollOverhang();if(a.opera){this._elHdContainer.scrollLeft=this._elBdContainer.scrollLeft;if(!this.get("width")){document.body.style+=""}}},_syncScrollY:function(){var k=this._elTbody,l=this._elBdContainer;if(!this.get("width")){this._elContainer.style.width=(l.scrollHeight>l.clientHeight)?(k.parentNode.clientWidth+19)+"px":(k.parentNode.clientWidth+2)+"px"}},_syncScrollX:function(){var k=this._elTbody,l=this._elBdContainer;if(!this.get("height")&&(a.ie)){l.style.height=(l.scrollWidth>l.offsetWidth)?(k.parentNode.offsetHeight+18)+"px":k.parentNode.offsetHeight+"px"}if(this._elTbody.rows.length===0){this._elMsgTbody.parentNode.style.width=this.getTheadEl().parentNode.offsetWidth+"px"}else{this._elMsgTbody.parentNode.style.width=""}},_syncScrollOverhang:function(){var l=this._elBdContainer,k=1;if((l.scrollHeight>l.clientHeight)&&(l.scrollWidth>l.clientWidth)){k=18}this._setOverhangValue(k)},_setOverhangValue:function(n){var p=this._oColumnSet.headers[this._oColumnSet.headers.length-1]||[],l=p.length,k=this._sId+"-fixedth-",o=n+"px solid "+this.get("COLOR_COLUMNFILLER");this._elThead.style.display="none";for(var m=0;m<l;m++){d.get(k+p[m]).style.borderRight=o}this._elThead.style.display=""},getHdContainerEl:function(){return this._elHdContainer},getBdContainerEl:function(){return this._elBdContainer},getHdTableEl:function(){return this._elHdTable},getBdTableEl:function(){return this._elTable},disable:function(){var k=this._elMask;k.style.width=this._elBdContainer.offsetWidth+"px";k.style.height=this._elHdContainer.offsetHeight+this._elBdContainer.offsetHeight+"px";k.style.display="";this.fireEvent("disableEvent")},removeColumn:function(m){var k=this._elHdContainer.scrollLeft;var l=this._elBdContainer.scrollLeft;m=h.superclass.removeColumn.call(this,m);this._elHdContainer.scrollLeft=k;this._elBdContainer.scrollLeft=l;return m},insertColumn:function(n,l){var k=this._elHdContainer.scrollLeft;var m=this._elBdContainer.scrollLeft;var o=h.superclass.insertColumn.call(this,n,l);this._elHdContainer.scrollLeft=k;this._elBdContainer.scrollLeft=m;return o},reorderColumn:function(n,l){var k=this._elHdContainer.scrollLeft;var m=this._elBdContainer.scrollLeft;var o=h.superclass.reorderColumn.call(this,n,l);this._elHdContainer.scrollLeft=k;this._elBdContainer.scrollLeft=m;return o},setColumnWidth:function(l,k){l=this.getColumn(l);if(l){this._storeScrollPositions();if(c.isNumber(k)){k=(k>l.minWidth)?k:l.minWidth;l.width=k;this._setColumnWidth(l,k+"px");this._syncScroll();this.fireEvent("columnSetWidthEvent",{column:l,width:k})}else{if(k===null){l.width=k;this._setColumnWidth(l,"auto");this.validateColumnWidths(l);this.fireEvent("columnUnsetWidthEvent",{column:l})}}this._clearTrTemplateEl()}else{}},scrollTo:function(m){var l=this.getTdEl(m);if(l){this.clearScrollPositions();this.getBdContainerEl().scrollLeft=l.offsetLeft;this.getBdContainerEl().scrollTop=l.parentNode.offsetTop}else{var k=this.getTrEl(m);if(k){this.clearScrollPositions();this.getBdContainerEl().scrollTop=k.offsetTop}}},showTableMessage:function(o,k){var p=this._elMsgTd;if(c.isString(o)){p.firstChild.innerHTML=o}if(c.isString(k)){d.addClass(p.firstChild,k)}var n=this.getTheadEl();var l=n.parentNode;var m=l.offsetWidth;this._elMsgTbody.parentNode.style.width=this.getTheadEl().parentNode.offsetWidth+"px";this._elMsgTbody.style.display="";this.fireEvent("tableMsgShowEvent",{html:o,className:k})},_onColumnChange:function(k){var l=(k.column)?k.column:(k.editor)?k.editor.column:null;this._storeScrollPositions();this.validateColumnWidths(l)},_onScroll:function(m,l){l._elHdContainer.scrollLeft=l._elBdContainer.scrollLeft;if(l._oCellEditor&&l._oCellEditor.isActive){l.fireEvent("editorBlurEvent",{editor:l._oCellEditor});l.cancelCellEditor()}var n=j.getTarget(m);var k=n.nodeName.toLowerCase();l.fireEvent("tableScrollEvent",{event:m,target:n})},_onTheadKeydown:function(n,l){if(j.getCharCode(n)===9){setTimeout(function(){if((l instanceof h)&&l._sId){l._elBdContainer.scrollLeft=l._elHdContainer.scrollLeft}},0)}var o=j.getTarget(n);var k=o.nodeName.toLowerCase();var m=true;while(o&&(k!="table")){switch(k){case"body":return;case"input":case"textarea":break;case"thead":m=l.fireEvent("theadKeyEvent",{target:o,event:n});break;default:break}if(m===false){return}else{o=o.parentNode;if(o){k=o.nodeName.toLowerCase()}}}l.fireEvent("tableKeyEvent",{target:(o||l._elContainer),event:n})}})})();(function(){var c=YAHOO.lang,f=YAHOO.util,e=YAHOO.widget,b=YAHOO.env.ua,d=f.Dom,i=f.Event,h=e.DataTable;e.BaseCellEditor=function(k,j){this._sId=this._sId||d.generateId(null,"yui-ceditor");YAHOO.widget.BaseCellEditor._nCount++;this._sType=k;this._initConfigs(j);this._initEvents();this._needsRender=true};var a=e.BaseCellEditor;c.augmentObject(a,{_nCount:0,CLASS_CELLEDITOR:"yui-ceditor"});a.prototype={_sId:null,_sType:null,_oDataTable:null,_oColumn:null,_oRecord:null,_elTd:null,_elContainer:null,_elCancelBtn:null,_elSaveBtn:null,_initConfigs:function(k){if(k&&YAHOO.lang.isObject(k)){for(var j in k){if(j){this[j]=k[j]}}}},_initEvents:function(){this.createEvent("showEvent");this.createEvent("keydownEvent");this.createEvent("invalidDataEvent");this.createEvent("revertEvent");this.createEvent("saveEvent");this.createEvent("cancelEvent");this.createEvent("blurEvent");this.createEvent("blockEvent");this.createEvent("unblockEvent")},_initContainerEl:function(){if(this._elContainer){YAHOO.util.Event.purgeElement(this._elContainer,true);this._elContainer.innerHTML=""}var j=document.createElement("div");j.id=this.getId()+"-container";j.style.display="none";j.tabIndex=0;this.className=c.isArray(this.className)?this.className:this.className?[this.className]:[];this.className[this.className.length]=h.CLASS_EDITOR;j.className=this.className.join(" ");document.body.insertBefore(j,document.body.firstChild);this._elContainer=j},_initShimEl:function(){if(this.useIFrame){if(!this._elIFrame){var j=document.createElement("iframe");j.src="javascript:false";j.frameBorder=0;j.scrolling="no";j.style.display="none";j.className=h.CLASS_EDITOR_SHIM;j.tabIndex=-1;j.role="presentation";j.title="Presentational iframe shim";document.body.insertBefore(j,document.body.firstChild);this._elIFrame=j}}},_hide:function(){this.getContainerEl().style.display="none";if(this._elIFrame){this._elIFrame.style.display="none"}this.isActive=false;this.getDataTable()._oCellEditor=null},asyncSubmitter:null,value:null,defaultValue:null,validator:null,resetInvalidData:true,isActive:false,LABEL_SAVE:"Save",LABEL_CANCEL:"Cancel",disableBtns:false,useIFrame:false,className:null,toString:function(){return"CellEditor instance "+this._sId},getId:function(){return this._sId},getDataTable:function(){return this._oDataTable},getColumn:function(){return this._oColumn},getRecord:function(){return this._oRecord},getTdEl:function(){return this._elTd},getContainerEl:function(){return this._elContainer},destroy:function(){this.unsubscribeAll();var k=this.getColumn();if(k){k.editor=null}var j=this.getContainerEl();if(j){i.purgeElement(j,true);j.parentNode.removeChild(j)}},render:function(){if(!this._needsRender){return}this._initContainerEl();this._initShimEl();i.addListener(this.getContainerEl(),"keydown",function(l,j){if((l.keyCode==27)){var k=i.getTarget(l);if(k.nodeName&&k.nodeName.toLowerCase()==="select"){k.blur()}j.cancel()}j.fireEvent("keydownEvent",{editor:j,event:l})},this);this.renderForm();if(!this.disableBtns){this.renderBtns()}this.doAfterRender();this._needsRender=false},renderBtns:function(){var l=this.getContainerEl().appendChild(document.createElement("div"));l.className=h.CLASS_BUTTON;var k=l.appendChild(document.createElement("button"));k.className=h.CLASS_DEFAULT;k.innerHTML=this.LABEL_SAVE;i.addListener(k,"click",function(m){this.save()},this,true);this._elSaveBtn=k;var j=l.appendChild(document.createElement("button"));j.innerHTML=this.LABEL_CANCEL;i.addListener(j,"click",function(m){this.cancel()},this,true);this._elCancelBtn=j},attach:function(n,l){if(n instanceof YAHOO.widget.DataTable){this._oDataTable=n;l=n.getTdEl(l);if(l){this._elTd=l;var m=n.getColumn(l);if(m){this._oColumn=m;var j=n.getRecord(l);if(j){this._oRecord=j;var k=j.getData(this.getColumn().getField());this.value=(k!==undefined)?k:this.defaultValue;return true}}}}return false},move:function(){var m=this.getContainerEl(),l=this.getTdEl(),j=d.getX(l),n=d.getY(l);if(isNaN(j)||isNaN(n)){var k=this.getDataTable().getTbodyEl();j=l.offsetLeft+d.getX(k.parentNode)-k.scrollLeft;n=l.offsetTop+d.getY(k.parentNode)-k.scrollTop+this.getDataTable().getTheadEl().offsetHeight}m.style.left=j+"px";m.style.top=n+"px";if(this._elIFrame){this._elIFrame.style.left=j+"px";this._elIFrame.style.top=n+"px"}},show:function(){var k=this.getContainerEl(),j=this._elIFrame;this.resetForm();this.isActive=true;k.style.display="";if(j){j.style.width=k.offsetWidth+"px";j.style.height=k.offsetHeight+"px";j.style.display=""}this.focus();this.fireEvent("showEvent",{editor:this})},block:function(){this.fireEvent("blockEvent",{editor:this})},unblock:function(){this.fireEvent("unblockEvent",{editor:this})},save:function(){var k=this.getInputValue();var l=k;if(this.validator){l=this.validator.call(this.getDataTable(),k,this.value,this);if(l===undefined){if(this.resetInvalidData){this.resetForm()}this.fireEvent("invalidDataEvent",{editor:this,oldData:this.value,newData:k});return}}var m=this;var j=function(o,n){var p=m.value;if(o){m.value=n;m.getDataTable().updateCell(m.getRecord(),m.getColumn(),n);m._hide();m.fireEvent("saveEvent",{editor:m,oldData:p,newData:m.value})}else{m.resetForm();m.fireEvent("revertEvent",{editor:m,oldData:p,newData:n})}m.unblock()};this.block();if(c.isFunction(this.asyncSubmitter)){this.asyncSubmitter.call(this,j,l)}else{j(true,l)}},cancel:function(){if(this.isActive){this._hide();this.fireEvent("cancelEvent",{editor:this})}else{}},renderForm:function(){},doAfterRender:function(){},handleDisabledBtns:function(){},resetForm:function(){},focus:function(){},getInputValue:function(){}};c.augmentProto(a,f.EventProvider);e.CheckboxCellEditor=function(j){j=j||{};this._sId=this._sId||d.generateId(null,"yui-checkboxceditor");YAHOO.widget.BaseCellEditor._nCount++;e.CheckboxCellEditor.superclass.constructor.call(this,j.type||"checkbox",j)};c.extend(e.CheckboxCellEditor,a,{checkboxOptions:null,checkboxes:null,value:null,renderForm:function(){if(c.isArray(this.checkboxOptions)){var n,o,q,l,m,k;for(m=0,k=this.checkboxOptions.length;m<k;m++){n=this.checkboxOptions[m];o=c.isValue(n.value)?n.value:n;q=this.getId()+"-chk"+m;this.getContainerEl().innerHTML+='<input type="checkbox" id="'+q+'" value="'+o+'" />';l=this.getContainerEl().appendChild(document.createElement("label"));l.htmlFor=q;l.innerHTML=c.isValue(n.label)?n.label:n}var p=[];for(m=0;m<k;m++){p[p.length]=this.getContainerEl().childNodes[m*2]}this.checkboxes=p;if(this.disableBtns){this.handleDisabledBtns()}}else{}},handleDisabledBtns:function(){i.addListener(this.getContainerEl(),"click",function(j){if(i.getTarget(j).tagName.toLowerCase()==="input"){this.save()}},this,true)},resetForm:function(){var p=c.isArray(this.value)?this.value:[this.value];for(var o=0,n=this.checkboxes.length;o<n;o++){this.checkboxes[o].checked=false;for(var m=0,l=p.length;m<l;m++){if(this.checkboxes[o].value==p[m]){this.checkboxes[o].checked=true}}}},focus:function(){this.checkboxes[0].focus()},getInputValue:function(){var k=[];for(var m=0,l=this.checkboxes.length;m<l;m++){if(this.checkboxes[m].checked){k[k.length]=this.checkboxes[m].value}}return k}});c.augmentObject(e.CheckboxCellEditor,a);e.DateCellEditor=function(j){j=j||{};this._sId=this._sId||d.generateId(null,"yui-dateceditor");YAHOO.widget.BaseCellEditor._nCount++;e.DateCellEditor.superclass.constructor.call(this,j.type||"date",j)};c.extend(e.DateCellEditor,a,{calendar:null,calendarOptions:null,defaultValue:new Date(),renderForm:function(){if(YAHOO.widget.Calendar){var k=this.getContainerEl().appendChild(document.createElement("div"));k.id=this.getId()+"-dateContainer";var l=new YAHOO.widget.Calendar(this.getId()+"-date",k.id,this.calendarOptions);l.render();k.style.cssFloat="none";l.hideEvent.subscribe(function(){this.cancel()},this,true);if(b.ie){var j=this.getContainerEl().appendChild(document.createElement("div"));j.style.clear="both"}this.calendar=l;if(this.disableBtns){this.handleDisabledBtns()}}else{}},handleDisabledBtns:function(){this.calendar.selectEvent.subscribe(function(j){this.save()},this,true)},resetForm:function(){var j=this.value||(new Date());this.calendar.select(j);this.calendar.cfg.setProperty("pagedate",j,false);this.calendar.render();this.calendar.show()},focus:function(){},getInputValue:function(){return this.calendar.getSelectedDates()[0]}});c.augmentObject(e.DateCellEditor,a);e.DropdownCellEditor=function(j){j=j||{};this._sId=this._sId||d.generateId(null,"yui-dropdownceditor");YAHOO.widget.BaseCellEditor._nCount++;e.DropdownCellEditor.superclass.constructor.call(this,j.type||"dropdown",j)};c.extend(e.DropdownCellEditor,a,{dropdownOptions:null,dropdown:null,multiple:false,size:null,renderForm:function(){var n=this.getContainerEl().appendChild(document.createElement("select"));n.style.zoom=1;if(this.multiple){n.multiple="multiple"}if(c.isNumber(this.size)){n.size=this.size}this.dropdown=n;if(c.isArray(this.dropdownOptions)){var o,m;for(var l=0,k=this.dropdownOptions.length;l<k;l++){o=this.dropdownOptions[l];m=document.createElement("option");m.value=(c.isValue(o.value))?o.value:o;m.innerHTML=(c.isValue(o.label))?o.label:o;m=n.appendChild(m)}if(this.disableBtns){this.handleDisabledBtns()}}},handleDisabledBtns:function(){if(this.multiple){i.addListener(this.dropdown,"blur",function(j){this.save()},this,true)}else{if(!b.ie){i.addListener(this.dropdown,"change",function(j){this.save()},this,true)}else{i.addListener(this.dropdown,"blur",function(j){this.save()},this,true);i.addListener(this.dropdown,"click",function(j){this.save()},this,true)}}},resetForm:function(){var s=this.dropdown.options,p=0,o=s.length;if(c.isArray(this.value)){var l=this.value,k=0,r=l.length,q={};for(;p<o;p++){s[p].selected=false;q[s[p].value]=s[p]}for(;k<r;k++){if(q[l[k]]){q[l[k]].selected=true}}}else{for(;p<o;p++){if(this.value==s[p].value){s[p].selected=true}}}},focus:function(){this.getDataTable()._focusEl(this.dropdown)},getInputValue:function(){var n=this.dropdown.options;if(this.multiple){var k=[],m=0,l=n.length;for(;m<l;m++){if(n[m].selected){k.push(n[m].value)}}return k}else{return n[n.selectedIndex].value}}});c.augmentObject(e.DropdownCellEditor,a);e.RadioCellEditor=function(j){j=j||{};this._sId=this._sId||d.generateId(null,"yui-radioceditor");YAHOO.widget.BaseCellEditor._nCount++;e.RadioCellEditor.superclass.constructor.call(this,j.type||"radio",j)};c.extend(e.RadioCellEditor,a,{radios:null,radioOptions:null,renderForm:function(){if(c.isArray(this.radioOptions)){var k,l,r,o;for(var n=0,p=this.radioOptions.length;n<p;n++){k=this.radioOptions[n];l=c.isValue(k.value)?k.value:k;r=this.getId()+"-radio"+n;this.getContainerEl().innerHTML+='<input type="radio" name="'+this.getId()+'" value="'+l+'" id="'+r+'" />';o=this.getContainerEl().appendChild(document.createElement("label"));o.htmlFor=r;o.innerHTML=(c.isValue(k.label))?k.label:k}var q=[],s;for(var m=0;m<p;m++){s=this.getContainerEl().childNodes[m*2];q[q.length]=s}this.radios=q;if(this.disableBtns){this.handleDisabledBtns()}}else{}},handleDisabledBtns:function(){i.addListener(this.getContainerEl(),"click",function(j){if(i.getTarget(j).tagName.toLowerCase()==="input"){this.save()}},this,true)},resetForm:function(){for(var m=0,l=this.radios.length;m<l;m++){var k=this.radios[m];if(this.value==k.value){k.checked=true;return}}},focus:function(){for(var l=0,k=this.radios.length;l<k;l++){if(this.radios[l].checked){this.radios[l].focus();return}}},getInputValue:function(){for(var l=0,k=this.radios.length;l<k;l++){if(this.radios[l].checked){return this.radios[l].value}}}});c.augmentObject(e.RadioCellEditor,a);e.TextareaCellEditor=function(j){j=j||{};this._sId=this._sId||d.generateId(null,"yui-textareaceditor");YAHOO.widget.BaseCellEditor._nCount++;e.TextareaCellEditor.superclass.constructor.call(this,j.type||"textarea",j)};c.extend(e.TextareaCellEditor,a,{textarea:null,renderForm:function(){var j=this.getContainerEl().appendChild(document.createElement("textarea"));this.textarea=j;if(this.disableBtns){this.handleDisabledBtns()}},handleDisabledBtns:function(){i.addListener(this.textarea,"blur",function(j){this.save()},this,true)},move:function(){this.textarea.style.width=this.getTdEl().offsetWidth+"px";this.textarea.style.height="3em";YAHOO.widget.TextareaCellEditor.superclass.move.call(this)},resetForm:function(){this.textarea.value=this.value},focus:function(){this.getDataTable()._focusEl(this.textarea);this.textarea.select()},getInputValue:function(){return this.textarea.value}});c.augmentObject(e.TextareaCellEditor,a);e.TextboxCellEditor=function(j){j=j||{};this._sId=this._sId||d.generateId(null,"yui-textboxceditor");YAHOO.widget.BaseCellEditor._nCount++;e.TextboxCellEditor.superclass.constructor.call(this,j.type||"textbox",j)};c.extend(e.TextboxCellEditor,a,{textbox:null,renderForm:function(){var j;if(b.webkit>420){j=this.getContainerEl().appendChild(document.createElement("form")).appendChild(document.createElement("input"))}else{j=this.getContainerEl().appendChild(document.createElement("input"))}j.type="text";this.textbox=j;i.addListener(j,"keypress",function(k){if((k.keyCode===13)){YAHOO.util.Event.preventDefault(k);this.save()}},this,true);if(this.disableBtns){this.handleDisabledBtns()}},move:function(){this.textbox.style.width=this.getTdEl().offsetWidth+"px";e.TextboxCellEditor.superclass.move.call(this)},resetForm:function(){this.textbox.value=c.isValue(this.value)?this.value.toString():""},focus:function(){this.getDataTable()._focusEl(this.textbox);this.textbox.select()},getInputValue:function(){return this.textbox.value}});c.augmentObject(e.TextboxCellEditor,a);h.Editors={checkbox:e.CheckboxCellEditor,date:e.DateCellEditor,dropdown:e.DropdownCellEditor,radio:e.RadioCellEditor,textarea:e.TextareaCellEditor,textbox:e.TextboxCellEditor};e.CellEditor=function(k,j){if(k&&h.Editors[k]){c.augmentObject(a,h.Editors[k]);return new h.Editors[k](j)}else{return new a(null,j)}};var g=e.CellEditor;c.augmentObject(g,a)})();YAHOO.register("datatable",YAHOO.widget.DataTable,{version:"2.9.0",build:"2800"});(function(){var d=YAHOO.util.Dom,f=YAHOO.lang,b=f.isObject,e=f.isFunction,c=f.isArray,a=f.isString;function g(k){var n=g.VALUE_UNLIMITED,l,h,i,j,m;k=b(k)?k:{};this.initConfig();this.initEvents();this.set("rowsPerPage",k.rowsPerPage,true);if(g.isNumeric(k.totalRecords)){this.set("totalRecords",k.totalRecords,true)}this.initUIComponents();for(l in k){if(k.hasOwnProperty(l)){this.set(l,k[l],true)}}h=this.get("initialPage");i=this.get("totalRecords");j=this.get("rowsPerPage");if(h>1&&j!==n){m=(h-1)*j;if(i===n||m<i){this.set("recordOffset",m,true)}}}f.augmentObject(g,{id:0,ID_BASE:"yui-pg",VALUE_UNLIMITED:-1,TEMPLATE_DEFAULT:"{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}",TEMPLATE_ROWS_PER_PAGE:"{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}",ui:{},isNumeric:function(h){return isFinite(+h)},toNumber:function(h){return isFinite(+h)?+h:null}},true);g.prototype={_containers:[],_batch:false,_pageChanged:false,_state:null,initConfig:function(){var h=g.VALUE_UNLIMITED;this.setAttributeConfig("rowsPerPage",{value:0,validator:g.isNumeric,setter:g.toNumber});this.setAttributeConfig("containers",{value:null,validator:function(l){if(!c(l)){l=[l]}for(var k=0,j=l.length;k<j;++k){if(a(l[k])||(b(l[k])&&l[k].nodeType===1)){continue}return false}return true},method:function(i){i=d.get(i);if(!c(i)){i=[i]}this._containers=i}});this.setAttributeConfig("totalRecords",{value:0,validator:g.isNumeric,setter:g.toNumber});this.setAttributeConfig("recordOffset",{value:0,validator:function(j){var i=this.get("totalRecords");if(g.isNumeric(j)){j=+j;return i===h||i>j||(i===0&&j===0)}return false},setter:g.toNumber});this.setAttributeConfig("initialPage",{value:1,validator:g.isNumeric,setter:g.toNumber});this.setAttributeConfig("template",{value:g.TEMPLATE_DEFAULT,validator:a});this.setAttributeConfig("containerClass",{value:"yui-pg-container",validator:a});this.setAttributeConfig("alwaysVisible",{value:true,validator:f.isBoolean});this.setAttributeConfig("updateOnChange",{value:false,validator:f.isBoolean});this.setAttributeConfig("id",{value:g.id++,readOnly:true});this.setAttributeConfig("rendered",{value:false,readOnly:true})},initUIComponents:function(){var j=g.ui,i,h;for(i in j){if(j.hasOwnProperty(i)){h=j[i];if(b(h)&&e(h.init)){h.init(this)}}}},initEvents:function(){this.createEvent("render");this.createEvent("rendered");this.createEvent("changeRequest");this.createEvent("pageChange");this.createEvent("beforeDestroy");this.createEvent("destroy");this._selfSubscribe()},_selfSubscribe:function(){this.subscribe("totalRecordsChange",this.updateVisibility,this,true);this.subscribe("alwaysVisibleChange",this.updateVisibility,this,true);this.subscribe("totalRecordsChange",this._handleStateChange,this,true);this.subscribe("recordOffsetChange",this._handleStateChange,this,true);this.subscribe("rowsPerPageChange",this._handleStateChange,this,true);this.subscribe("totalRecordsChange",this._syncRecordOffset,this,true)},_syncRecordOffset:function(k){var h=k.newValue,j,i;if(k.prevValue!==h){if(h!==g.VALUE_UNLIMITED){j=this.get("rowsPerPage");if(j&&this.get("recordOffset")>=h){i=this.getState({totalRecords:k.prevValue,recordOffset:this.get("recordOffset")});this.set("recordOffset",i.before.recordOffset);this._firePageChange(i)}}}},_handleStateChange:function(i){if(i.prevValue!==i.newValue){var j=this._state||{},h;j[i.type.replace(/Change$/,"")]=i.prevValue;h=this.getState(j);if(h.page!==h.before.page){if(this._batch){this._pageChanged=true}else{this._firePageChange(h)}}}},_firePageChange:function(h){if(b(h)){var i=h.before;delete h.before;this.fireEvent("pageChange",{type:"pageChange",prevValue:h.page,newValue:i.page,prevState:h,newState:i})}},render:function(){if(this.get("rendered")){return this}var l=this.get("template"),m=this.getState(),k=g.ID_BASE+this.get("id")+"-",j,h;for(j=0,h=this._containers.length;j<h;++j){this._renderTemplate(this._containers[j],l,k+j,true)}this.updateVisibility();if(this._containers.length){this.setAttributeConfig("rendered",{value:true});this.fireEvent("render",m);this.fireEvent("rendered",m)}return this},_renderTemplate:function(j,n,m,l){var p=this.get("containerClass"),o,k,h;if(!j){return}d.setStyle(j,"display","none");d.addClass(j,p);j.innerHTML=n.replace(/\{([a-z0-9_ \-]+)\}/gi,'<span class="yui-pg-ui yui-pg-ui-$1"></span>');o=d.getElementsByClassName("yui-pg-ui","span",j);for(k=0,h=o.length;k<h;++k){this.renderUIComponent(o[k],m)}if(!l){d.setStyle(j,"display","")}},renderUIComponent:function(h,m){var l=h.parentNode,k=/yui-pg-ui-(\w+)/.exec(h.className),j=k&&g.ui[k[1]],i;if(e(j)){i=new j(this);if(e(i.render)){l.replaceChild(i.render(m),h)}}return this},destroy:function(){this.fireEvent("beforeDestroy");this.fireEvent("destroy");this.setAttributeConfig("rendered",{value:false});this.unsubscribeAll()},updateVisibility:function(m){var p=this.get("alwaysVisible"),n,j,q,o,k,l,h;if(!m||m.type==="alwaysVisibleChange"||!p){n=this.get("totalRecords");j=true;q=this.get("rowsPerPage");o=this.get("rowsPerPageOptions");if(c(o)){for(k=0,l=o.length;k<l;++k){h=o[k];if(f.isNumber(h||h.value)){q=Math.min(q,(h.value||h))}}}if(n!==g.VALUE_UNLIMITED&&n<=q){j=false}j=j||p;for(k=0,l=this._containers.length;k<l;++k){d.setStyle(this._containers[k],"display",j?"":"none")}}},getContainerNodes:function(){return this._containers},getTotalPages:function(){var h=this.get("totalRecords"),i=this.get("rowsPerPage");if(!i){return null}if(h===g.VALUE_UNLIMITED){return g.VALUE_UNLIMITED}return Math.ceil(h/i)},hasPage:function(i){if(!f.isNumber(i)||i<1){return false}var h=this.getTotalPages();return(h===g.VALUE_UNLIMITED||h>=i)},getCurrentPage:function(){var h=this.get("rowsPerPage");if(!h||!this.get("totalRecords")){return 0}return Math.floor(this.get("recordOffset")/h)+1},hasNextPage:function(){var h=this.getCurrentPage(),i=this.getTotalPages();return h&&(i===g.VALUE_UNLIMITED||h<i)},getNextPage:function(){return this.hasNextPage()?this.getCurrentPage()+1:null},hasPreviousPage:function(){return(this.getCurrentPage()>1)},getPreviousPage:function(){return(this.hasPreviousPage()?this.getCurrentPage()-1:1)},getPageRecords:function(k){if(!f.isNumber(k)){k=this.getCurrentPage()}var j=this.get("rowsPerPage"),i=this.get("totalRecords"),l,h;if(!k||!j){return null}l=(k-1)*j;if(i!==g.VALUE_UNLIMITED){if(l>=i){return null}h=Math.min(l+j,i)-1}else{h=l+j-1}return[l,h]},setPage:function(i,h){if(this.hasPage(i)&&i!==this.getCurrentPage()){if(this.get("updateOnChange")||h){this.set("recordOffset",(i-1)*this.get("rowsPerPage"))}else{this.fireEvent("changeRequest",this.getState({page:i}))}}},getRowsPerPage:function(){return this.get("rowsPerPage")},setRowsPerPage:function(i,h){if(g.isNumeric(i)&&+i>0&&+i!==this.get("rowsPerPage")){if(this.get("updateOnChange")||h){this.set("rowsPerPage",i)}else{this.fireEvent("changeRequest",this.getState({rowsPerPage:+i}))}}},getTotalRecords:function(){return this.get("totalRecords")},setTotalRecords:function(i,h){if(g.isNumeric(i)&&+i>=0&&+i!==this.get("totalRecords")){if(this.get("updateOnChange")||h){this.set("totalRecords",i)}else{this.fireEvent("changeRequest",this.getState({totalRecords:+i}))}}},getStartIndex:function(){return this.get("recordOffset")},setStartIndex:function(i,h){if(g.isNumeric(i)&&+i>=0&&+i!==this.get("recordOffset")){if(this.get("updateOnChange")||h){this.set("recordOffset",i)}else{this.fireEvent("changeRequest",this.getState({recordOffset:+i}))}}},getState:function(n){var p=g.VALUE_UNLIMITED,l=Math,m=l.max,o=l.ceil,j,h,k;function i(s,q,r){if(s<=0||q===0){return 0}if(q===p||q>s){return s-(s%r)}return q-(q%r||r)}j={paginator:this,totalRecords:this.get("totalRecords"),rowsPerPage:this.get("rowsPerPage"),records:this.getPageRecords()};j.recordOffset=i(this.get("recordOffset"),j.totalRecords,j.rowsPerPage);j.page=o(j.recordOffset/j.rowsPerPage)+1;if(!n){return j}h={paginator:this,before:j,rowsPerPage:n.rowsPerPage||j.rowsPerPage,totalRecords:(g.isNumeric(n.totalRecords)?m(n.totalRecords,p):+j.totalRecords)};if(h.totalRecords===0){h.recordOffset=h.page=0}else{k=g.isNumeric(n.page)?(n.page-1)*h.rowsPerPage:g.isNumeric(n.recordOffset)?+n.recordOffset:j.recordOffset;h.recordOffset=i(k,h.totalRecords,h.rowsPerPage);h.page=o(h.recordOffset/h.rowsPerPage)+1}h.records=[h.recordOffset,h.recordOffset+h.rowsPerPage-1];if(h.totalRecords!==p&&h.recordOffset<h.totalRecords&&h.records&&h.records[1]>h.totalRecords-1){h.records[1]=h.totalRecords-1}return h},setState:function(i){if(b(i)){this._state=this.getState({});i={page:i.page,rowsPerPage:i.rowsPerPage,totalRecords:i.totalRecords,recordOffset:i.recordOffset};if(i.page&&i.recordOffset===undefined){i.recordOffset=(i.page-1)*(i.rowsPerPage||this.get("rowsPerPage"))}this._batch=true;this._pageChanged=false;for(var h in i){if(i.hasOwnProperty(h)&&this._configs.hasOwnProperty(h)){this.set(h,i[h])}}this._batch=false;if(this._pageChanged){this._pageChanged=false;this._firePageChange(this.getState(this._state))}}}};f.augmentProto(g,YAHOO.util.AttributeProvider);YAHOO.widget.Paginator=g})();(function(){var c=YAHOO.widget.Paginator,b=YAHOO.lang,a=YAHOO.util.Dom.generateId;c.ui.CurrentPageReport=function(d){this.paginator=d;d.subscribe("recordOffsetChange",this.update,this,true);d.subscribe("rowsPerPageChange",this.update,this,true);d.subscribe("totalRecordsChange",this.update,this,true);d.subscribe("pageReportTemplateChange",this.update,this,true);d.subscribe("destroy",this.destroy,this,true);d.subscribe("pageReportClassChange",this.update,this,true)};c.ui.CurrentPageReport.init=function(d){d.setAttributeConfig("pageReportClass",{value:"yui-pg-current",validator:b.isString});d.setAttributeConfig("pageReportTemplate",{value:"({currentPage} of {totalPages})",validator:b.isString});d.setAttributeConfig("pageReportValueGenerator",{value:function(g){var f=g.getCurrentPage(),e=g.getPageRecords();return{currentPage:e?f:0,totalPages:g.getTotalPages(),startIndex:e?e[0]:0,endIndex:e?e[1]:0,startRecord:e?e[0]+1:0,endRecord:e?e[1]+1:0,totalRecords:g.get("totalRecords")}},validator:b.isFunction})};c.ui.CurrentPageReport.sprintf=function(e,d){return e.replace(/\{([\w\s\-]+)\}/g,function(f,g){return(g in d)?d[g]:""})};c.ui.CurrentPageReport.prototype={span:null,render:function(d){this.span=document.createElement("span");this.span.className=this.paginator.get("pageReportClass");a(this.span,d+"-page-report");this.update();return this.span},update:function(d){if(d&&d.prevValue===d.newValue){return}this.span.innerHTML=c.ui.CurrentPageReport.sprintf(this.paginator.get("pageReportTemplate"),this.paginator.get("pageReportValueGenerator")(this.paginator))},destroy:function(){this.span.parentNode.removeChild(this.span);this.span=null}}})();(function(){var c=YAHOO.widget.Paginator,b=YAHOO.lang,a=YAHOO.util.Dom.generateId;c.ui.PageLinks=function(d){this.paginator=d;d.subscribe("recordOffsetChange",this.update,this,true);d.subscribe("rowsPerPageChange",this.update,this,true);d.subscribe("totalRecordsChange",this.update,this,true);d.subscribe("pageLinksChange",this.rebuild,this,true);d.subscribe("pageLinkClassChange",this.rebuild,this,true);d.subscribe("currentPageClassChange",this.rebuild,this,true);d.subscribe("destroy",this.destroy,this,true);d.subscribe("pageLinksContainerClassChange",this.rebuild,this,true)};c.ui.PageLinks.init=function(d){d.setAttributeConfig("pageLinkClass",{value:"yui-pg-page",validator:b.isString});d.setAttributeConfig("currentPageClass",{value:"yui-pg-current-page",validator:b.isString});d.setAttributeConfig("pageLinksContainerClass",{value:"yui-pg-pages",validator:b.isString});d.setAttributeConfig("pageLinks",{value:10,validator:c.isNumeric});d.setAttributeConfig("pageLabelBuilder",{value:function(e,f){return e},validator:b.isFunction});d.setAttributeConfig("pageTitleBuilder",{value:function(e,f){return"Page "+e},validator:b.isFunction})};c.ui.PageLinks.calculateRange=function(f,g,e){var j=c.VALUE_UNLIMITED,i,d,h;if(!f||e===0||g===0||(g===j&&e===j)){return[0,-1]}if(g!==j){e=e===j?g:Math.min(e,g)}i=Math.max(1,Math.ceil(f-(e/2)));if(g===j){d=i+e-1}else{d=Math.min(g,i+e-1)}h=e-(d-i+1);i=Math.max(1,i-h);return[i,d]};c.ui.PageLinks.prototype={current:0,container:null,render:function(d){var e=this.paginator;this.container=document.createElement("span");a(this.container,d+"-pages");this.container.className=e.get("pageLinksContainerClass");YAHOO.util.Event.on(this.container,"click",this.onClick,this,true);this.update({newValue:null,rebuild:true});return this.container},update:function(q){if(q&&q.prevValue===q.newValue){return}var g=this.paginator,m=g.getCurrentPage();if(this.current!==m||!m||q.rebuild){var r=g.get("pageLabelBuilder"),l=g.get("pageTitleBuilder"),k=c.ui.PageLinks.calculateRange(m,g.getTotalPages(),g.get("pageLinks")),f=k[0],h=k[1],o="",d,j,n;d='<a href="#" class="{class}" page="{page}" title="{title}">{label}</a>';n='<span class="{class}">{label}</span>';for(j=f;j<=h;++j){if(j===m){o+=b.substitute(n,{"class":g.get("currentPageClass")+" "+g.get("pageLinkClass"),label:r(j,g)})}else{o+=b.substitute(d,{"class":g.get("pageLinkClass"),page:j,label:r(j,g),title:l(j,g)})}}this.container.innerHTML=o}},rebuild:function(d){d.rebuild=true;this.update(d)},destroy:function(){YAHOO.util.Event.purgeElement(this.container,true);this.container.parentNode.removeChild(this.container);this.container=null},onClick:function(f){var d=YAHOO.util.Event.getTarget(f);if(d&&YAHOO.util.Dom.hasClass(d,this.paginator.get("pageLinkClass"))){YAHOO.util.Event.stopEvent(f);this.paginator.setPage(parseInt(d.getAttribute("page"),10))}}}})();(function(){var c=YAHOO.widget.Paginator,b=YAHOO.lang,a=YAHOO.util.Dom.generateId;c.ui.FirstPageLink=function(d){this.paginator=d;d.subscribe("recordOffsetChange",this.update,this,true);d.subscribe("rowsPerPageChange",this.update,this,true);d.subscribe("totalRecordsChange",this.update,this,true);d.subscribe("destroy",this.destroy,this,true);d.subscribe("firstPageLinkLabelChange",this.update,this,true);d.subscribe("firstPageLinkClassChange",this.update,this,true)};c.ui.FirstPageLink.init=function(d){d.setAttributeConfig("firstPageLinkLabel",{value:"&lt;&lt; first",validator:b.isString});d.setAttributeConfig("firstPageLinkClass",{value:"yui-pg-first",validator:b.isString});d.setAttributeConfig("firstPageLinkTitle",{value:"First Page",validator:b.isString})};c.ui.FirstPageLink.prototype={current:null,link:null,span:null,render:function(e){var f=this.paginator,h=f.get("firstPageLinkClass"),d=f.get("firstPageLinkLabel"),g=f.get("firstPageLinkTitle");this.link=document.createElement("a");this.span=document.createElement("span");a(this.link,e+"-first-link");this.link.href="#";this.link.className=h;this.link.innerHTML=d;this.link.title=g;YAHOO.util.Event.on(this.link,"click",this.onClick,this,true);a(this.span,e+"-first-span");this.span.className=h;this.span.innerHTML=d;this.current=f.getCurrentPage()>1?this.link:this.span;return this.current},update:function(f){if(f&&f.prevValue===f.newValue){return}var d=this.current?this.current.parentNode:null;if(this.paginator.getCurrentPage()>1){if(d&&this.current===this.span){d.replaceChild(this.link,this.current);this.current=this.link}}else{if(d&&this.current===this.link){d.replaceChild(this.span,this.current);this.current=this.span}}},destroy:function(){YAHOO.util.Event.purgeElement(this.link);this.current.parentNode.removeChild(this.current);this.link=this.span=null},onClick:function(d){YAHOO.util.Event.stopEvent(d);this.paginator.setPage(1)}}})();(function(){var c=YAHOO.widget.Paginator,b=YAHOO.lang,a=YAHOO.util.Dom.generateId;c.ui.LastPageLink=function(d){this.paginator=d;d.subscribe("recordOffsetChange",this.update,this,true);d.subscribe("rowsPerPageChange",this.update,this,true);d.subscribe("totalRecordsChange",this.update,this,true);d.subscribe("destroy",this.destroy,this,true);d.subscribe("lastPageLinkLabelChange",this.update,this,true);d.subscribe("lastPageLinkClassChange",this.update,this,true)};c.ui.LastPageLink.init=function(d){d.setAttributeConfig("lastPageLinkLabel",{value:"last &gt;&gt;",validator:b.isString});d.setAttributeConfig("lastPageLinkClass",{value:"yui-pg-last",validator:b.isString});d.setAttributeConfig("lastPageLinkTitle",{value:"Last Page",validator:b.isString})};c.ui.LastPageLink.prototype={current:null,link:null,span:null,na:null,render:function(e){var g=this.paginator,i=g.get("lastPageLinkClass"),d=g.get("lastPageLinkLabel"),f=g.getTotalPages(),h=g.get("lastPageLinkTitle");this.link=document.createElement("a");this.span=document.createElement("span");this.na=this.span.cloneNode(false);a(this.link,e+"-last-link");this.link.href="#";this.link.className=i;this.link.innerHTML=d;this.link.title=h;YAHOO.util.Event.on(this.link,"click",this.onClick,this,true);a(this.span,e+"-last-span");this.span.className=i;this.span.innerHTML=d;a(this.na,e+"-last-na");switch(f){case c.VALUE_UNLIMITED:this.current=this.na;break;case g.getCurrentPage():this.current=this.span;break;default:this.current=this.link}return this.current},update:function(f){if(f&&f.prevValue===f.newValue){return}var d=this.current?this.current.parentNode:null,g=this.link;if(d){switch(this.paginator.getTotalPages()){case c.VALUE_UNLIMITED:g=this.na;break;case this.paginator.getCurrentPage():g=this.span;break}if(this.current!==g){d.replaceChild(g,this.current);this.current=g}}},destroy:function(){YAHOO.util.Event.purgeElement(this.link);this.current.parentNode.removeChild(this.current);this.link=this.span=null},onClick:function(d){YAHOO.util.Event.stopEvent(d);this.paginator.setPage(this.paginator.getTotalPages())}}})();(function(){var c=YAHOO.widget.Paginator,b=YAHOO.lang,a=YAHOO.util.Dom.generateId;c.ui.NextPageLink=function(d){this.paginator=d;d.subscribe("recordOffsetChange",this.update,this,true);d.subscribe("rowsPerPageChange",this.update,this,true);d.subscribe("totalRecordsChange",this.update,this,true);d.subscribe("destroy",this.destroy,this,true);d.subscribe("nextPageLinkLabelChange",this.update,this,true);d.subscribe("nextPageLinkClassChange",this.update,this,true)};c.ui.NextPageLink.init=function(d){d.setAttributeConfig("nextPageLinkLabel",{value:"next &gt;",validator:b.isString});d.setAttributeConfig("nextPageLinkClass",{value:"yui-pg-next",validator:b.isString});d.setAttributeConfig("nextPageLinkTitle",{value:"Next Page",validator:b.isString})};c.ui.NextPageLink.prototype={current:null,link:null,span:null,render:function(e){var g=this.paginator,i=g.get("nextPageLinkClass"),d=g.get("nextPageLinkLabel"),f=g.getTotalPages(),h=g.get("nextPageLinkTitle");this.link=document.createElement("a");this.span=document.createElement("span");a(this.link,e+"-next-link");this.link.href="#";this.link.className=i;this.link.innerHTML=d;this.link.title=h;YAHOO.util.Event.on(this.link,"click",this.onClick,this,true);a(this.span,e+"-next-span");this.span.className=i;this.span.innerHTML=d;this.current=g.getCurrentPage()===f?this.span:this.link;return this.current},update:function(g){if(g&&g.prevValue===g.newValue){return}var f=this.paginator.getTotalPages(),d=this.current?this.current.parentNode:null;if(this.paginator.getCurrentPage()!==f){if(d&&this.current===this.span){d.replaceChild(this.link,this.current);this.current=this.link}}else{if(this.current===this.link){if(d){d.replaceChild(this.span,this.current);this.current=this.span}}}},destroy:function(){YAHOO.util.Event.purgeElement(this.link);this.current.parentNode.removeChild(this.current);this.link=this.span=null},onClick:function(d){YAHOO.util.Event.stopEvent(d);this.paginator.setPage(this.paginator.getNextPage())}}})();(function(){var c=YAHOO.widget.Paginator,b=YAHOO.lang,a=YAHOO.util.Dom.generateId;c.ui.PreviousPageLink=function(d){this.paginator=d;d.subscribe("recordOffsetChange",this.update,this,true);d.subscribe("rowsPerPageChange",this.update,this,true);d.subscribe("totalRecordsChange",this.update,this,true);d.subscribe("destroy",this.destroy,this,true);d.subscribe("previousPageLinkLabelChange",this.update,this,true);d.subscribe("previousPageLinkClassChange",this.update,this,true)};c.ui.PreviousPageLink.init=function(d){d.setAttributeConfig("previousPageLinkLabel",{value:"&lt; prev",validator:b.isString});d.setAttributeConfig("previousPageLinkClass",{value:"yui-pg-previous",validator:b.isString});d.setAttributeConfig("previousPageLinkTitle",{value:"Previous Page",validator:b.isString})};c.ui.PreviousPageLink.prototype={current:null,link:null,span:null,render:function(e){var f=this.paginator,h=f.get("previousPageLinkClass"),d=f.get("previousPageLinkLabel"),g=f.get("previousPageLinkTitle");this.link=document.createElement("a");this.span=document.createElement("span");a(this.link,e+"-prev-link");this.link.href="#";this.link.className=h;this.link.innerHTML=d;this.link.title=g;YAHOO.util.Event.on(this.link,"click",this.onClick,this,true);a(this.span,e+"-prev-span");this.span.className=h;this.span.innerHTML=d;this.current=f.getCurrentPage()>1?this.link:this.span;return this.current},update:function(f){if(f&&f.prevValue===f.newValue){return}var d=this.current?this.current.parentNode:null;if(this.paginator.getCurrentPage()>1){if(d&&this.current===this.span){d.replaceChild(this.link,this.current);this.current=this.link}}else{if(d&&this.current===this.link){d.replaceChild(this.span,this.current);this.current=this.span}}},destroy:function(){YAHOO.util.Event.purgeElement(this.link);this.current.parentNode.removeChild(this.current);this.link=this.span=null},onClick:function(d){YAHOO.util.Event.stopEvent(d);this.paginator.setPage(this.paginator.getPreviousPage())}}})();(function(){var c=YAHOO.widget.Paginator,b=YAHOO.lang,a=YAHOO.util.Dom.generateId;c.ui.RowsPerPageDropdown=function(d){this.paginator=d;d.subscribe("rowsPerPageChange",this.update,this,true);d.subscribe("rowsPerPageOptionsChange",this.rebuild,this,true);d.subscribe("totalRecordsChange",this._handleTotalRecordsChange,this,true);d.subscribe("destroy",this.destroy,this,true);d.subscribe("rowsPerPageDropdownClassChange",this.rebuild,this,true)};c.ui.RowsPerPageDropdown.init=function(d){d.setAttributeConfig("rowsPerPageOptions",{value:[],validator:b.isArray});d.setAttributeConfig("rowsPerPageDropdownClass",{value:"yui-pg-rpp-options",validator:b.isString})};c.ui.RowsPerPageDropdown.prototype={select:null,all:null,render:function(d){this.select=document.createElement("select");a(this.select,d+"-rpp");this.select.className=this.paginator.get("rowsPerPageDropdownClass");this.select.title="Rows per page";YAHOO.util.Event.on(this.select,"change",this.onChange,this,true);this.rebuild();return this.select},rebuild:function(m){var d=this.paginator,g=this.select,n=d.get("rowsPerPageOptions"),f,l,h,j,k;this.all=null;for(j=0,k=n.length;j<k;++j){l=n[j];f=g.options[j]||g.appendChild(document.createElement("option"));h=b.isValue(l.value)?l.value:l;f.text=b.isValue(l.text)?l.text:l;if(b.isString(h)&&h.toLowerCase()==="all"){this.all=f;f.value=d.get("totalRecords")}else{f.value=h}}while(g.options.length>n.length){g.removeChild(g.firstChild)}this.update()},update:function(j){if(j&&j.prevValue===j.newValue){return}var h=this.paginator.get("rowsPerPage")+"",f=this.select.options,g,d;for(g=0,d=f.length;g<d;++g){if(f[g].value===h){f[g].selected=true;break}}},onChange:function(d){this.paginator.setRowsPerPage(parseInt(this.select.options[this.select.selectedIndex].value,10))},_handleTotalRecordsChange:function(d){if(!this.all||(d&&d.prevValue===d.newValue)){return}this.all.value=d.newValue;if(this.all.selected){this.paginator.set("rowsPerPage",d.newValue)}},destroy:function(){YAHOO.util.Event.purgeElement(this.select);this.select.parentNode.removeChild(this.select);this.select=null}}})();(function(){var c=YAHOO.widget.Paginator,b=YAHOO.lang,a=YAHOO.util.Dom.generateId;c.ui.JumpToPageDropdown=function(d){this.paginator=d;d.subscribe("rowsPerPageChange",this.rebuild,this,true);d.subscribe("rowsPerPageOptionsChange",this.rebuild,this,true);d.subscribe("pageChange",this.update,this,true);d.subscribe("totalRecordsChange",this.rebuild,this,true);d.subscribe("destroy",this.destroy,this,true)};c.ui.JumpToPageDropdown.init=function(d){d.setAttributeConfig("jumpToPageDropdownClass",{value:"yui-pg-jtp-options",validator:b.isString})};c.ui.JumpToPageDropdown.prototype={select:null,render:function(d){this.select=document.createElement("select");a(this.select,d+"-jtp");this.select.className=this.paginator.get("jumpToPageDropdownClass");this.select.title="Jump to page";YAHOO.util.Event.on(this.select,"change",this.onChange,this,true);this.rebuild();return this.select},rebuild:function(l){var k=this.paginator,j=this.select,f=k.getTotalPages(),h,g,d;this.all=null;for(g=0,d=f;g<d;++g){h=j.options[g]||j.appendChild(document.createElement("option"));h.innerHTML=g+1;h.value=g+1}for(g=f,d=j.options.length;g<d;g++){j.removeChild(j.lastChild)}this.update()},update:function(j){if(j&&j.prevValue===j.newValue){return}var h=this.paginator.getCurrentPage()+"",f=this.select.options,g,d;for(g=0,d=f.length;g<d;++g){if(f[g].value===h){f[g].selected=true;break}}},onChange:function(d){this.paginator.setPage(parseInt(this.select.options[this.select.selectedIndex].value,false))},destroy:function(){YAHOO.util.Event.purgeElement(this.select);this.select.parentNode.removeChild(this.select);this.select=null}}})();YAHOO.register("paginator",YAHOO.widget.Paginator,{version:"2.9.0",build:"2800"});
\ No newline at end of file
+YAHOO.util.Easing={easeNone:function(e,a,g,f){return g*e/f+a},easeIn:function(e,a,g,f){return g*(e/=f)*e+a},easeOut:function(e,a,g,f){return -g*(e/=f)*(e-2)+a},easeBoth:function(e,a,g,f){if((e/=f/2)<1){return g/2*e*e+a}return -g/2*((--e)*(e-2)-1)+a},easeInStrong:function(e,a,g,f){return g*(e/=f)*e*e*e+a},easeOutStrong:function(e,a,g,f){return -g*((e=e/f-1)*e*e*e-1)+a},easeBothStrong:function(e,a,g,f){if((e/=f/2)<1){return g/2*e*e*e*e+a}return -g/2*((e-=2)*e*e*e-2)+a},elasticIn:function(g,e,k,j,f,i){if(g==0){return e}if((g/=j)==1){return e+k}if(!i){i=j*0.3}if(!f||f<Math.abs(k)){f=k;var h=i/4}else{var h=i/(2*Math.PI)*Math.asin(k/f)}return -(f*Math.pow(2,10*(g-=1))*Math.sin((g*j-h)*(2*Math.PI)/i))+e},elasticOut:function(g,e,k,j,f,i){if(g==0){return e}if((g/=j)==1){return e+k}if(!i){i=j*0.3}if(!f||f<Math.abs(k)){f=k;var h=i/4}else{var h=i/(2*Math.PI)*Math.asin(k/f)}return f*Math.pow(2,-10*g)*Math.sin((g*j-h)*(2*Math.PI)/i)+k+e},elasticBoth:function(g,e,k,j,f,i){if(g==0){return e}if((g/=j/2)==2){return e+k}if(!i){i=j*(0.3*1.5)}if(!f||f<Math.abs(k)){f=k;var h=i/4}else{var h=i/(2*Math.PI)*Math.asin(k/f)}if(g<1){return -0.5*(f*Math.pow(2,10*(g-=1))*Math.sin((g*j-h)*(2*Math.PI)/i))+e}return f*Math.pow(2,-10*(g-=1))*Math.sin((g*j-h)*(2*Math.PI)/i)*0.5+k+e},backIn:function(e,a,h,g,f){if(typeof f=="undefined"){f=1.70158}return h*(e/=g)*e*((f+1)*e-f)+a},backOut:function(e,a,h,g,f){if(typeof f=="undefined"){f=1.70158}return h*((e=e/g-1)*e*((f+1)*e+f)+1)+a},backBoth:function(e,a,h,g,f){if(typeof f=="undefined"){f=1.70158}if((e/=g/2)<1){return h/2*(e*e*(((f*=(1.525))+1)*e-f))+a}return h/2*((e-=2)*e*(((f*=(1.525))+1)*e+f)+2)+a},bounceIn:function(e,a,g,f){return g-YAHOO.util.Easing.bounceOut(f-e,0,g,f)+a},bounceOut:function(e,a,g,f){if((e/=f)<(1/2.75)){return g*(7.5625*e*e)+a}else{if(e<(2/2.75)){return g*(7.5625*(e-=(1.5/2.75))*e+0.75)+a}else{if(e<(2.5/2.75)){return g*(7.5625*(e-=(2.25/2.75))*e+0.9375)+a}}}return g*(7.5625*(e-=(2.625/2.75))*e+0.984375)+a},bounceBoth:function(e,a,g,f){if(e<f/2){return YAHOO.util.Easing.bounceIn(e*2,0,g,f)*0.5+a}return YAHOO.util.Easing.bounceOut(e*2-f,0,g,f)*0.5+g*0.5+a}};(function(){var a=function(h,g,i,j){if(h){a.superclass.constructor.call(this,h,g,i,j)}};a.NAME="Motion";var e=YAHOO.util;YAHOO.extend(a,e.ColorAnim);var f=a.superclass;var c=a.prototype;c.patterns.points=/^points$/i;c.setAttribute=function(g,i,h){if(this.patterns.points.test(g)){h=h||"px";f.setAttribute.call(this,"left",i[0],h);f.setAttribute.call(this,"top",i[1],h)}else{f.setAttribute.call(this,g,i,h)}};c.getAttribute=function(g){if(this.patterns.points.test(g)){var h=[f.getAttribute.call(this,"left"),f.getAttribute.call(this,"top")]}else{h=f.getAttribute.call(this,g)}return h};c.doMethod=function(g,k,h){var j=null;if(this.patterns.points.test(g)){var i=this.method(this.currentFrame,0,100,this.totalFrames)/100;j=e.Bezier.getPosition(this.runtimeAttributes[g],i)}else{j=f.doMethod.call(this,g,k,h)}return j};c.setRuntimeAttribute=function(q){if(this.patterns.points.test(q)){var h=this.getEl();var k=this.attributes;var g;var m=k.points["control"]||[];var j;var n,p;if(m.length>0&&!(m[0] instanceof Array)){m=[m]}else{var l=[];for(n=0,p=m.length;n<p;++n){l[n]=m[n]}m=l}if(e.Dom.getStyle(h,"position")=="static"){e.Dom.setStyle(h,"position","relative")}if(d(k.points["from"])){e.Dom.setXY(h,k.points["from"])}else{e.Dom.setXY(h,e.Dom.getXY(h))}g=this.getAttribute("points");if(d(k.points["to"])){j=b.call(this,k.points["to"],g);var o=e.Dom.getXY(this.getEl());for(n=0,p=m.length;n<p;++n){m[n]=b.call(this,m[n],g)}}else{if(d(k.points["by"])){j=[g[0]+k.points["by"][0],g[1]+k.points["by"][1]];for(n=0,p=m.length;n<p;++n){m[n]=[g[0]+m[n][0],g[1]+m[n][1]]}}}this.runtimeAttributes[q]=[g];if(m.length>0){this.runtimeAttributes[q]=this.runtimeAttributes[q].concat(m)}this.runtimeAttributes[q][this.runtimeAttributes[q].length]=j}else{f.setRuntimeAttribute.call(this,q)}};var b=function(g,i){var h=e.Dom.getXY(this.getEl());g=[g[0]-h[0]+i[0],g[1]-h[1]+i[1]];return g};var d=function(g){return(typeof g!=="undefined")};e.Motion=a})();(function(){var d=function(f,e,g,h){if(f){d.superclass.constructor.call(this,f,e,g,h)}};d.NAME="Scroll";var b=YAHOO.util;YAHOO.extend(d,b.ColorAnim);var c=d.superclass;var a=d.prototype;a.doMethod=function(e,h,f){var g=null;if(e=="scroll"){g=[this.method(this.currentFrame,h[0],f[0]-h[0],this.totalFrames),this.method(this.currentFrame,h[1],f[1]-h[1],this.totalFrames)]}else{g=c.doMethod.call(this,e,h,f)}return g};a.getAttribute=function(e){var g=null;var f=this.getEl();if(e=="scroll"){g=[f.scrollLeft,f.scrollTop]}else{g=c.getAttribute.call(this,e)}return g};a.setAttribute=function(e,h,g){var f=this.getEl();if(e=="scroll"){f.scrollLeft=h[0];f.scrollTop=h[1]}else{c.setAttribute.call(this,e,h,g)}};b.Scroll=d})();YAHOO.register("animation",YAHOO.util.Anim,{version:"2.9.0",build:"2800"});YAHOO.util.Attribute=function(b,a){if(a){this.owner=a;this.configure(b,true)}};YAHOO.util.Attribute.INVALID_VALUE={};YAHOO.util.Attribute.prototype={name:undefined,value:null,owner:null,readOnly:false,writeOnce:false,_initialConfig:null,_written:false,method:null,setter:null,getter:null,validator:null,getValue:function(){var a=this.value;if(this.getter){a=this.getter.call(this.owner,this.name,a)}return a},setValue:function(f,b){var e,a=this.owner,c=this.name,g=YAHOO.util.Attribute.INVALID_VALUE,d={type:c,prevValue:this.getValue(),newValue:f};if(this.readOnly||(this.writeOnce&&this._written)){return false}if(this.validator&&!this.validator.call(a,f)){return false}if(!b){e=a.fireBeforeChangeEvent(d);if(e===false){return false}}if(this.setter){f=this.setter.call(a,f,this.name);if(f===undefined){}if(f===g){return false}}if(this.method){if(this.method.call(a,f,this.name)===g){return false}}this.value=f;this._written=true;d.type=c;if(!b){this.owner.fireChangeEvent(d)}return true},configure:function(b,c){b=b||{};if(c){this._written=false}this._initialConfig=this._initialConfig||{};for(var a in b){if(b.hasOwnProperty(a)){this[a]=b[a];if(c){this._initialConfig[a]=b[a]}}}},resetValue:function(){return this.setValue(this._initialConfig.value)},resetConfig:function(){this.configure(this._initialConfig,true)},refresh:function(a){this.setValue(this.value,a)}};(function(){var a=YAHOO.util.Lang;YAHOO.util.AttributeProvider=function(){};YAHOO.util.AttributeProvider.prototype={_configs:null,get:function(c){this._configs=this._configs||{};var b=this._configs[c];if(!b||!this._configs.hasOwnProperty(c)){return null}return b.getValue()},set:function(d,e,b){this._configs=this._configs||{};var c=this._configs[d];if(!c){return false}return c.setValue(e,b)},getAttributeKeys:function(){this._configs=this._configs;var c=[],b;for(b in this._configs){if(a.hasOwnProperty(this._configs,b)&&!a.isUndefined(this._configs[b])){c[c.length]=b}}return c},setAttributes:function(d,b){for(var c in d){if(a.hasOwnProperty(d,c)){this.set(c,d[c],b)}}},resetValue:function(c,b){this._configs=this._configs||{};if(this._configs[c]){this.set(c,this._configs[c]._initialConfig.value,b);return true}return false},refresh:function(e,c){this._configs=this._configs||{};var f=this._configs;e=((a.isString(e))?[e]:e)||this.getAttributeKeys();for(var d=0,b=e.length;d<b;++d){if(f.hasOwnProperty(e[d])){this._configs[e[d]].refresh(c)}}},register:function(b,c){this.setAttributeConfig(b,c)},getAttributeConfig:function(c){this._configs=this._configs||{};var b=this._configs[c]||{};var d={};for(c in b){if(a.hasOwnProperty(b,c)){d[c]=b[c]}}return d},setAttributeConfig:function(b,c,d){this._configs=this._configs||{};c=c||{};if(!this._configs[b]){c.name=b;this._configs[b]=this.createAttribute(c)}else{this._configs[b].configure(c,d)}},configureAttribute:function(b,c,d){this.setAttributeConfig(b,c,d)},resetAttributeConfig:function(b){this._configs=this._configs||{};this._configs[b].resetConfig()},subscribe:function(b,c){this._events=this._events||{};if(!(b in this._events)){this._events[b]=this.createEvent(b)}YAHOO.util.EventProvider.prototype.subscribe.apply(this,arguments)},on:function(){this.subscribe.apply(this,arguments)},addListener:function(){this.subscribe.apply(this,arguments)},fireBeforeChangeEvent:function(c){var b="before";b+=c.type.charAt(0).toUpperCase()+c.type.substr(1)+"Change";c.type=b;return this.fireEvent(c.type,c)},fireChangeEvent:function(b){b.type+="Change";return this.fireEvent(b.type,b)},createAttribute:function(b){return new YAHOO.util.Attribute(b,this)}};YAHOO.augment(YAHOO.util.AttributeProvider,YAHOO.util.EventProvider)})();(function(){var b=YAHOO.util.Dom,d=YAHOO.util.AttributeProvider,c={mouseenter:true,mouseleave:true};var a=function(e,f){this.init.apply(this,arguments)};a.DOM_EVENTS={click:true,dblclick:true,keydown:true,keypress:true,keyup:true,mousedown:true,mousemove:true,mouseout:true,mouseover:true,mouseup:true,mouseenter:true,mouseleave:true,focus:true,blur:true,submit:true,change:true};a.prototype={DOM_EVENTS:null,DEFAULT_HTML_SETTER:function(g,e){var f=this.get("element");if(f){f[e]=g}return g},DEFAULT_HTML_GETTER:function(e){var f=this.get("element"),g;if(f){g=f[e]}return g},appendChild:function(e){e=e.get?e.get("element"):e;return this.get("element").appendChild(e)},getElementsByTagName:function(e){return this.get("element").getElementsByTagName(e)},hasChildNodes:function(){return this.get("element").hasChildNodes()},insertBefore:function(e,f){e=e.get?e.get("element"):e;f=(f&&f.get)?f.get("element"):f;return this.get("element").insertBefore(e,f)},removeChild:function(e){e=e.get?e.get("element"):e;return this.get("element").removeChild(e)},replaceChild:function(e,f){e=e.get?e.get("element"):e;f=f.get?f.get("element"):f;return this.get("element").replaceChild(e,f)},initAttributes:function(e){},addListener:function(j,i,k,h){h=h||this;var e=YAHOO.util.Event,g=this.get("element")||this.get("id"),f=this;if(c[j]&&!e._createMouseDelegate){return false}if(!this._events[j]){if(g&&this.DOM_EVENTS[j]){e.on(g,j,function(m,l){if(m.srcElement&&!m.target){m.target=m.srcElement}if((m.toElement&&!m.relatedTarget)||(m.fromElement&&!m.relatedTarget)){m.relatedTarget=e.getRelatedTarget(m)}if(!m.currentTarget){m.currentTarget=g}f.fireEvent(j,m,l)},k,h)}this.createEvent(j,{scope:this})}return YAHOO.util.EventProvider.prototype.subscribe.apply(this,arguments)},on:function(){return this.addListener.apply(this,arguments)},subscribe:function(){return this.addListener.apply(this,arguments)},removeListener:function(f,e){return this.unsubscribe.apply(this,arguments)},addClass:function(e){b.addClass(this.get("element"),e)},getElementsByClassName:function(f,e){return b.getElementsByClassName(f,e,this.get("element"))},hasClass:function(e){return b.hasClass(this.get("element"),e)},removeClass:function(e){return b.removeClass(this.get("element"),e)},replaceClass:function(f,e){return b.replaceClass(this.get("element"),f,e)},setStyle:function(f,e){return b.setStyle(this.get("element"),f,e)},getStyle:function(e){return b.getStyle(this.get("element"),e)},fireQueue:function(){var f=this._queue;for(var g=0,e=f.length;g<e;++g){this[f[g][0]].apply(this,f[g][1])}},appendTo:function(f,g){f=(f.get)?f.get("element"):b.get(f);this.fireEvent("beforeAppendTo",{type:"beforeAppendTo",target:f});g=(g&&g.get)?g.get("element"):b.get(g);var e=this.get("element");if(!e){return false}if(!f){return false}if(e.parent!=f){if(g){f.insertBefore(e,g)}else{f.appendChild(e)}}this.fireEvent("appendTo",{type:"appendTo",target:f});return e},get:function(e){var g=this._configs||{},f=g.element;if(f&&!g[e]&&!YAHOO.lang.isUndefined(f.value[e])){this._setHTMLAttrConfig(e)}return d.prototype.get.call(this,e)},setAttributes:function(l,h){var f={},j=this._configOrder;for(var k=0,e=j.length;k<e;++k){if(l[j[k]]!==undefined){f[j[k]]=true;this.set(j[k],l[j[k]],h)}}for(var g in l){if(l.hasOwnProperty(g)&&!f[g]){this.set(g,l[g],h)}}},set:function(f,h,e){var g=this.get("element");if(!g){this._queue[this._queue.length]=["set",arguments];if(this._configs[f]){this._configs[f].value=h}return}if(!this._configs[f]&&!YAHOO.lang.isUndefined(g[f])){this._setHTMLAttrConfig(f)}return d.prototype.set.apply(this,arguments)},setAttributeConfig:function(e,f,g){this._configOrder.push(e);d.prototype.setAttributeConfig.apply(this,arguments)},createEvent:function(f,e){this._events[f]=true;return d.prototype.createEvent.apply(this,arguments)},init:function(f,e){this._initElement(f,e)},destroy:function(){var e=this.get("element");YAHOO.util.Event.purgeElement(e,true);this.unsubscribeAll();if(e&&e.parentNode){e.parentNode.removeChild(e)}this._queue=[];this._events={};this._configs={};this._configOrder=[]},_initElement:function(g,f){this._queue=this._queue||[];this._events=this._events||{};this._configs=this._configs||{};this._configOrder=[];f=f||{};f.element=f.element||g||null;var i=false;var e=a.DOM_EVENTS;this.DOM_EVENTS=this.DOM_EVENTS||{};for(var h in e){if(e.hasOwnProperty(h)){this.DOM_EVENTS[h]=e[h]}}if(typeof f.element==="string"){this._setHTMLAttrConfig("id",{value:f.element})}if(b.get(f.element)){i=true;this._initHTMLElement(f);this._initContent(f)}YAHOO.util.Event.onAvailable(f.element,function(){if(!i){this._initHTMLElement(f)}this.fireEvent("available",{type:"available",target:b.get(f.element)})},this,true);YAHOO.util.Event.onContentReady(f.element,function(){if(!i){this._initContent(f)}this.fireEvent("contentReady",{type:"contentReady",target:b.get(f.element)})},this,true)},_initHTMLElement:function(e){this.setAttributeConfig("element",{value:b.get(e.element),readOnly:true})},_initContent:function(e){this.initAttributes(e);this.setAttributes(e,true);this.fireQueue()},_setHTMLAttrConfig:function(e,g){var f=this.get("element");g=g||{};g.name=e;g.setter=g.setter||this.DEFAULT_HTML_SETTER;g.getter=g.getter||this.DEFAULT_HTML_GETTER;g.value=g.value||f[e];this._configs[e]=new YAHOO.util.Attribute(g,this)}};YAHOO.augment(a,d);YAHOO.util.Element=a})();YAHOO.register("element",YAHOO.util.Element,{version:"2.9.0",build:"2800"});(function(){var lang=YAHOO.lang,util=YAHOO.util,Ev=util.Event;util.DataSourceBase=function(oLiveData,oConfigs){if(oLiveData===null||oLiveData===undefined){return}this.liveData=oLiveData;this._oQueue={interval:null,conn:null,requests:[]};this.responseSchema={};if(oConfigs&&(oConfigs.constructor==Object)){for(var sConfig in oConfigs){if(sConfig){this[sConfig]=oConfigs[sConfig]}}}var maxCacheEntries=this.maxCacheEntries;if(!lang.isNumber(maxCacheEntries)||(maxCacheEntries<0)){maxCacheEntries=0}this._aIntervals=[];this.createEvent("cacheRequestEvent");this.createEvent("cacheResponseEvent");this.createEvent("requestEvent");this.createEvent("responseEvent");this.createEvent("responseParseEvent");this.createEvent("responseCacheEvent");this.createEvent("dataErrorEvent");this.createEvent("cacheFlushEvent");var DS=util.DataSourceBase;this._sName="DataSource instance"+DS._nIndex;DS._nIndex++};var DS=util.DataSourceBase;lang.augmentObject(DS,{TYPE_UNKNOWN:-1,TYPE_JSARRAY:0,TYPE_JSFUNCTION:1,TYPE_XHR:2,TYPE_JSON:3,TYPE_XML:4,TYPE_TEXT:5,TYPE_HTMLTABLE:6,TYPE_SCRIPTNODE:7,TYPE_LOCAL:8,ERROR_DATAINVALID:"Invalid data",ERROR_DATANULL:"Null data",_nIndex:0,_nTransactionId:0,_cloneObject:function(o){if(!lang.isValue(o)){return o}var copy={};if(Object.prototype.toString.apply(o)==="[object RegExp]"){copy=o}else{if(lang.isFunction(o)){copy=o}else{if(lang.isArray(o)){var array=[];for(var i=0,len=o.length;i<len;i++){array[i]=DS._cloneObject(o[i])}copy=array}else{if(lang.isObject(o)){for(var x in o){if(lang.hasOwnProperty(o,x)){if(lang.isValue(o[x])&&lang.isObject(o[x])||lang.isArray(o[x])){copy[x]=DS._cloneObject(o[x])}else{copy[x]=o[x]}}}}else{copy=o}}}}return copy},_getLocationValue:function(field,context){var locator=field.locator||field.key||field,xmldoc=context.ownerDocument||context,result,res,value=null;try{if(!lang.isUndefined(xmldoc.evaluate)){result=xmldoc.evaluate(locator,context,xmldoc.createNSResolver(!context.ownerDocument?context.documentElement:context.ownerDocument.documentElement),0,null);while(res=result.iterateNext()){value=res.textContent}}else{xmldoc.setProperty("SelectionLanguage","XPath");result=context.selectNodes(locator)[0];value=result.value||result.text||null}return value}catch(e){}},issueCallback:function(callback,params,error,scope){if(lang.isFunction(callback)){callback.apply(scope,params)}else{if(lang.isObject(callback)){scope=callback.scope||scope||window;var callbackFunc=callback.success;if(error){callbackFunc=callback.failure}if(callbackFunc){callbackFunc.apply(scope,params.concat([callback.argument]))}}}},parseString:function(oData){if(!lang.isValue(oData)){return null}var string=oData+"";if(lang.isString(string)){return string}else{return null}},parseNumber:function(oData){if(!lang.isValue(oData)||(oData==="")){return null}var number=oData*1;if(lang.isNumber(number)){return number}else{return null}},convertNumber:function(oData){return DS.parseNumber(oData)},parseDate:function(oData){var date=null;if(lang.isValue(oData)&&!(oData instanceof Date)){date=new Date(oData)}else{return oData}if(date instanceof Date){return date}else{return null}},convertDate:function(oData){return DS.parseDate(oData)}});DS.Parser={string:DS.parseString,number:DS.parseNumber,date:DS.parseDate};DS.prototype={_sName:null,_aCache:null,_oQueue:null,_aIntervals:null,maxCacheEntries:0,liveData:null,dataType:DS.TYPE_UNKNOWN,responseType:DS.TYPE_UNKNOWN,responseSchema:null,useXPath:false,cloneBeforeCaching:false,toString:function(){return this._sName},getCachedResponse:function(oRequest,oCallback,oCaller){var aCache=this._aCache;if(this.maxCacheEntries>0){if(!aCache){this._aCache=[]}else{var nCacheLength=aCache.length;if(nCacheLength>0){var oResponse=null;this.fireEvent("cacheRequestEvent",{request:oRequest,callback:oCallback,caller:oCaller});for(var i=nCacheLength-1;i>=0;i--){var oCacheElem=aCache[i];if(this.isCacheHit(oRequest,oCacheElem.request)){oResponse=oCacheElem.response;this.fireEvent("cacheResponseEvent",{request:oRequest,response:oResponse,callback:oCallback,caller:oCaller});if(i<nCacheLength-1){aCache.splice(i,1);this.addToCache(oRequest,oResponse)}oResponse.cached=true;break}}return oResponse}}}else{if(aCache){this._aCache=null}}return null},isCacheHit:function(oRequest,oCachedRequest){return(oRequest===oCachedRequest)},addToCache:function(oRequest,oResponse){var aCache=this._aCache;if(!aCache){return}while(aCache.length>=this.maxCacheEntries){aCache.shift()}oResponse=(this.cloneBeforeCaching)?DS._cloneObject(oResponse):oResponse;var oCacheElem={request:oRequest,response:oResponse};aCache[aCache.length]=oCacheElem;this.fireEvent("responseCacheEvent",{request:oRequest,response:oResponse})},flushCache:function(){if(this._aCache){this._aCache=[];this.fireEvent("cacheFlushEvent")}},setInterval:function(nMsec,oRequest,oCallback,oCaller){if(lang.isNumber(nMsec)&&(nMsec>=0)){var oSelf=this;var nId=setInterval(function(){oSelf.makeConnection(oRequest,oCallback,oCaller)},nMsec);this._aIntervals.push(nId);return nId}else{}},clearInterval:function(nId){var tracker=this._aIntervals||[];for(var i=tracker.length-1;i>-1;i--){if(tracker[i]===nId){tracker.splice(i,1);clearInterval(nId)}}},clearAllIntervals:function(){var tracker=this._aIntervals||[];for(var i=tracker.length-1;i>-1;i--){clearInterval(tracker[i])}tracker=[]},sendRequest:function(oRequest,oCallback,oCaller){var oCachedResponse=this.getCachedResponse(oRequest,oCallback,oCaller);if(oCachedResponse){DS.issueCallback(oCallback,[oRequest,oCachedResponse],false,oCaller);return null}return this.makeConnection(oRequest,oCallback,oCaller)},makeConnection:function(oRequest,oCallback,oCaller){var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});var oRawResponse=this.liveData;this.handleResponse(oRequest,oRawResponse,oCallback,oCaller,tId);return tId},handleResponse:function(oRequest,oRawResponse,oCallback,oCaller,tId){this.fireEvent("responseEvent",{tId:tId,request:oRequest,response:oRawResponse,callback:oCallback,caller:oCaller});var xhr=(this.dataType==DS.TYPE_XHR)?true:false;var oParsedResponse=null;var oFullResponse=oRawResponse;if(this.responseType===DS.TYPE_UNKNOWN){var ctype=(oRawResponse&&oRawResponse.getResponseHeader)?oRawResponse.getResponseHeader["Content-Type"]:null;if(ctype){if(ctype.indexOf("text/xml")>-1){this.responseType=DS.TYPE_XML}else{if(ctype.indexOf("application/json")>-1){this.responseType=DS.TYPE_JSON}else{if(ctype.indexOf("text/plain")>-1){this.responseType=DS.TYPE_TEXT}}}}else{if(YAHOO.lang.isArray(oRawResponse)){this.responseType=DS.TYPE_JSARRAY}else{if(oRawResponse&&oRawResponse.nodeType&&(oRawResponse.nodeType===9||oRawResponse.nodeType===1||oRawResponse.nodeType===11)){this.responseType=DS.TYPE_XML}else{if(oRawResponse&&oRawResponse.nodeName&&(oRawResponse.nodeName.toLowerCase()=="table")){this.responseType=DS.TYPE_HTMLTABLE}else{if(YAHOO.lang.isObject(oRawResponse)){this.responseType=DS.TYPE_JSON}else{if(YAHOO.lang.isString(oRawResponse)){this.responseType=DS.TYPE_TEXT}}}}}}}switch(this.responseType){case DS.TYPE_JSARRAY:if(xhr&&oRawResponse&&oRawResponse.responseText){oFullResponse=oRawResponse.responseText}try{if(lang.isString(oFullResponse)){var parseArgs=[oFullResponse].concat(this.parseJSONArgs);if(lang.JSON){oFullResponse=lang.JSON.parse.apply(lang.JSON,parseArgs)}else{if(window.JSON&&JSON.parse){oFullResponse=JSON.parse.apply(JSON,parseArgs)}else{if(oFullResponse.parseJSON){oFullResponse=oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1))}else{while(oFullResponse.length>0&&(oFullResponse.charAt(0)!="{")&&(oFullResponse.charAt(0)!="[")){oFullResponse=oFullResponse.substring(1,oFullResponse.length)}if(oFullResponse.length>0){var arrayEnd=Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));oFullResponse=oFullResponse.substring(0,arrayEnd+1);oFullResponse=eval("("+oFullResponse+")")}}}}}}catch(e1){}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseArrayData(oRequest,oFullResponse);break;case DS.TYPE_JSON:if(xhr&&oRawResponse&&oRawResponse.responseText){oFullResponse=oRawResponse.responseText}try{if(lang.isString(oFullResponse)){var parseArgs=[oFullResponse].concat(this.parseJSONArgs);if(lang.JSON){oFullResponse=lang.JSON.parse.apply(lang.JSON,parseArgs)}else{if(window.JSON&&JSON.parse){oFullResponse=JSON.parse.apply(JSON,parseArgs)}else{if(oFullResponse.parseJSON){oFullResponse=oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1))}else{while(oFullResponse.length>0&&(oFullResponse.charAt(0)!="{")&&(oFullResponse.charAt(0)!="[")){oFullResponse=oFullResponse.substring(1,oFullResponse.length)}if(oFullResponse.length>0){var objEnd=Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));oFullResponse=oFullResponse.substring(0,objEnd+1);oFullResponse=eval("("+oFullResponse+")")}}}}}}catch(e){}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseJSONData(oRequest,oFullResponse);break;case DS.TYPE_HTMLTABLE:if(xhr&&oRawResponse.responseText){var el=document.createElement("div");el.innerHTML=oRawResponse.responseText;oFullResponse=el.getElementsByTagName("table")[0]}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseHTMLTableData(oRequest,oFullResponse);break;case DS.TYPE_XML:if(xhr&&oRawResponse.responseXML){oFullResponse=oRawResponse.responseXML}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseXMLData(oRequest,oFullResponse);break;case DS.TYPE_TEXT:if(xhr&&lang.isString(oRawResponse.responseText)){oFullResponse=oRawResponse.responseText}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseTextData(oRequest,oFullResponse);break;default:oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseData(oRequest,oFullResponse);break}oParsedResponse=oParsedResponse||{};if(!oParsedResponse.results){oParsedResponse.results=[]}if(!oParsedResponse.meta){oParsedResponse.meta={}}if(!oParsedResponse.error){oParsedResponse=this.doBeforeCallback(oRequest,oFullResponse,oParsedResponse,oCallback);this.fireEvent("responseParseEvent",{request:oRequest,response:oParsedResponse,callback:oCallback,caller:oCaller});this.addToCache(oRequest,oParsedResponse)}else{oParsedResponse.error=true;this.fireEvent("dataErrorEvent",{request:oRequest,response:oRawResponse,callback:oCallback,caller:oCaller,message:DS.ERROR_DATANULL})}oParsedResponse.tId=tId;DS.issueCallback(oCallback,[oRequest,oParsedResponse],oParsedResponse.error,oCaller)},doBeforeParseData:function(oRequest,oFullResponse,oCallback){return oFullResponse},doBeforeCallback:function(oRequest,oFullResponse,oParsedResponse,oCallback){return oParsedResponse},parseData:function(oRequest,oFullResponse){if(lang.isValue(oFullResponse)){var oParsedResponse={results:oFullResponse,meta:{}};return oParsedResponse}return null},parseArrayData:function(oRequest,oFullResponse){if(lang.isArray(oFullResponse)){var results=[],i,j,rec,field,data;if(lang.isArray(this.responseSchema.fields)){var fields=this.responseSchema.fields;for(i=fields.length-1;i>=0;--i){if(typeof fields[i]!=="object"){fields[i]={key:fields[i]}}}var parsers={},p;for(i=fields.length-1;i>=0;--i){p=(typeof fields[i].parser==="function"?fields[i].parser:DS.Parser[fields[i].parser+""])||fields[i].converter;if(p){parsers[fields[i].key]=p}}var arrType=lang.isArray(oFullResponse[0]);for(i=oFullResponse.length-1;i>-1;i--){var oResult={};rec=oFullResponse[i];if(typeof rec==="object"){for(j=fields.length-1;j>-1;j--){field=fields[j];data=arrType?rec[j]:rec[field.key];if(parsers[field.key]){data=parsers[field.key].call(this,data)}if(data===undefined){data=null}oResult[field.key]=data}}else{if(lang.isString(rec)){for(j=fields.length-1;j>-1;j--){field=fields[j];data=rec;if(parsers[field.key]){data=parsers[field.key].call(this,data)}if(data===undefined){data=null}oResult[field.key]=data}}}results[i]=oResult}}else{results=oFullResponse}var oParsedResponse={results:results};return oParsedResponse}return null},parseTextData:function(oRequest,oFullResponse){if(lang.isString(oFullResponse)){if(lang.isString(this.responseSchema.recordDelim)&&lang.isString(this.responseSchema.fieldDelim)){var oParsedResponse={results:[]};var recDelim=this.responseSchema.recordDelim;var fieldDelim=this.responseSchema.fieldDelim;if(oFullResponse.length>0){var newLength=oFullResponse.length-recDelim.length;if(oFullResponse.substr(newLength)==recDelim){oFullResponse=oFullResponse.substr(0,newLength)}if(oFullResponse.length>0){var recordsarray=oFullResponse.split(recDelim);for(var i=0,len=recordsarray.length,recIdx=0;i<len;++i){var bError=false,sRecord=recordsarray[i];if(lang.isString(sRecord)&&(sRecord.length>0)){var fielddataarray=recordsarray[i].split(fieldDelim);var oResult={};if(lang.isArray(this.responseSchema.fields)){var fields=this.responseSchema.fields;for(var j=fields.length-1;j>-1;j--){try{var data=fielddataarray[j];if(lang.isString(data)){if(data.charAt(0)=='"'){data=data.substr(1)}if(data.charAt(data.length-1)=='"'){data=data.substr(0,data.length-1)}var field=fields[j];var key=(lang.isValue(field.key))?field.key:field;if(!field.parser&&field.converter){field.parser=field.converter}var parser=(typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""];if(parser){data=parser.call(this,data)}if(data===undefined){data=null}oResult[key]=data}else{bError=true}}catch(e){bError=true}}}else{oResult=fielddataarray}if(!bError){oParsedResponse.results[recIdx++]=oResult}}}}}return oParsedResponse}}return null},parseXMLResult:function(result){var oResult={},schema=this.responseSchema;try{for(var m=schema.fields.length-1;m>=0;m--){var field=schema.fields[m];var key=(lang.isValue(field.key))?field.key:field;var data=null;if(this.useXPath){data=YAHOO.util.DataSource._getLocationValue(field,result)}else{var xmlAttr=result.attributes.getNamedItem(key);if(xmlAttr){data=xmlAttr.value}else{var xmlNode=result.getElementsByTagName(key);if(xmlNode&&xmlNode.item(0)){var item=xmlNode.item(0);data=(item)?((item.text)?item.text:(item.textContent)?item.textContent:null):null;if(!data){var datapieces=[];for(var j=0,len=item.childNodes.length;j<len;j++){if(item.childNodes[j].nodeValue){datapieces[datapieces.length]=item.childNodes[j].nodeValue}}if(datapieces.length>0){data=datapieces.join("")}}}}}if(data===null){data=""}if(!field.parser&&field.converter){field.parser=field.converter}var parser=(typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""];if(parser){data=parser.call(this,data)}if(data===undefined){data=null}oResult[key]=data}}catch(e){}return oResult},parseXMLData:function(oRequest,oFullResponse){var bError=false,schema=this.responseSchema,oParsedResponse={meta:{}},xmlList=null,metaNode=schema.metaNode,metaLocators=schema.metaFields||{},i,k,loc,v;try{if(this.useXPath){for(k in metaLocators){oParsedResponse.meta[k]=YAHOO.util.DataSource._getLocationValue(metaLocators[k],oFullResponse)}}else{metaNode=metaNode?oFullResponse.getElementsByTagName(metaNode)[0]:oFullResponse;if(metaNode){for(k in metaLocators){if(lang.hasOwnProperty(metaLocators,k)){loc=metaLocators[k];v=metaNode.getElementsByTagName(loc)[0];if(v){v=v.firstChild.nodeValue}else{v=metaNode.attributes.getNamedItem(loc);if(v){v=v.value}}if(lang.isValue(v)){oParsedResponse.meta[k]=v}}}}}xmlList=(schema.resultNode)?oFullResponse.getElementsByTagName(schema.resultNode):null}catch(e){}if(!xmlList||!lang.isArray(schema.fields)){bError=true}else{oParsedResponse.results=[];for(i=xmlList.length-1;i>=0;--i){var oResult=this.parseXMLResult(xmlList.item(i));oParsedResponse.results[i]=oResult}}if(bError){oParsedResponse.error=true}else{}return oParsedResponse},parseJSONData:function(oRequest,oFullResponse){var oParsedResponse={results:[],meta:{}};if(lang.isObject(oFullResponse)&&this.responseSchema.resultsList){var schema=this.responseSchema,fields=schema.fields,resultsList=oFullResponse,results=[],metaFields=schema.metaFields||{},fieldParsers=[],fieldPaths=[],simpleFields=[],bError=false,i,len,j,v,key,parser,path;var buildPath=function(needle){var path=null,keys=[],i=0;if(needle){needle=needle.replace(/\[(['"])(.*?)\1\]/g,function(x,$1,$2){keys[i]=$2;return".@"+(i++)}).replace(/\[(\d+)\]/g,function(x,$1){keys[i]=parseInt($1,10)|0;return".@"+(i++)}).replace(/^\./,"");if(!/[^\w\.\$@]/.test(needle)){path=needle.split(".");for(i=path.length-1;i>=0;--i){if(path[i].charAt(0)==="@"){path[i]=keys[parseInt(path[i].substr(1),10)]}}}else{}}return path};var walkPath=function(path,origin){var v=origin,i=0,len=path.length;for(;i<len&&v;++i){v=v[path[i]]}return v};path=buildPath(schema.resultsList);if(path){resultsList=walkPath(path,oFullResponse);if(resultsList===undefined){bError=true}}else{bError=true}if(!resultsList){resultsList=[]}if(!lang.isArray(resultsList)){resultsList=[resultsList]}if(!bError){if(schema.fields){var field;for(i=0,len=fields.length;i<len;i++){field=fields[i];key=field.key||field;parser=((typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""])||field.converter;path=buildPath(key);if(parser){fieldParsers[fieldParsers.length]={key:key,parser:parser}}if(path){if(path.length>1){fieldPaths[fieldPaths.length]={key:key,path:path}}else{simpleFields[simpleFields.length]={key:key,path:path[0]}}}else{}}for(i=resultsList.length-1;i>=0;--i){var r=resultsList[i],rec={};if(r){for(j=simpleFields.length-1;j>=0;--j){rec[simpleFields[j].key]=(r[simpleFields[j].path]!==undefined)?r[simpleFields[j].path]:r[j]}for(j=fieldPaths.length-1;j>=0;--j){rec[fieldPaths[j].key]=walkPath(fieldPaths[j].path,r)}for(j=fieldParsers.length-1;j>=0;--j){var p=fieldParsers[j].key;rec[p]=fieldParsers[j].parser.call(this,rec[p]);if(rec[p]===undefined){rec[p]=null}}}results[i]=rec}}else{results=resultsList}for(key in metaFields){if(lang.hasOwnProperty(metaFields,key)){path=buildPath(metaFields[key]);if(path){v=walkPath(path,oFullResponse);oParsedResponse.meta[key]=v}}}}else{oParsedResponse.error=true}oParsedResponse.results=results}else{oParsedResponse.error=true}return oParsedResponse},parseHTMLTableData:function(oRequest,oFullResponse){var bError=false;var elTable=oFullResponse;var fields=this.responseSchema.fields;var oParsedResponse={results:[]};if(lang.isArray(fields)){for(var i=0;i<elTable.tBodies.length;i++){var elTbody=elTable.tBodies[i];for(var j=elTbody.rows.length-1;j>-1;j--){var elRow=elTbody.rows[j];var oResult={};for(var k=fields.length-1;k>-1;k--){var field=fields[k];var key=(lang.isValue(field.key))?field.key:field;var data=elRow.cells[k].innerHTML;if(!field.parser&&field.converter){field.parser=field.converter}var parser=(typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""];if(parser){data=parser.call(this,data)}if(data===undefined){data=null}oResult[key]=data}oParsedResponse.results[j]=oResult}}}else{bError=true}if(bError){oParsedResponse.error=true}else{}return oParsedResponse}};lang.augmentProto(DS,util.EventProvider);util.LocalDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_LOCAL;if(oLiveData){if(YAHOO.lang.isArray(oLiveData)){this.responseType=DS.TYPE_JSARRAY}else{if(oLiveData.nodeType&&oLiveData.nodeType==9){this.responseType=DS.TYPE_XML}else{if(oLiveData.nodeName&&(oLiveData.nodeName.toLowerCase()=="table")){this.responseType=DS.TYPE_HTMLTABLE;oLiveData=oLiveData.cloneNode(true)}else{if(YAHOO.lang.isString(oLiveData)){this.responseType=DS.TYPE_TEXT}else{if(YAHOO.lang.isObject(oLiveData)){this.responseType=DS.TYPE_JSON}}}}}}else{oLiveData=[];this.responseType=DS.TYPE_JSARRAY}util.LocalDataSource.superclass.constructor.call(this,oLiveData,oConfigs)};lang.extend(util.LocalDataSource,DS);lang.augmentObject(util.LocalDataSource,DS);util.FunctionDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_JSFUNCTION;oLiveData=oLiveData||function(){};util.FunctionDataSource.superclass.constructor.call(this,oLiveData,oConfigs)};lang.extend(util.FunctionDataSource,DS,{scope:null,makeConnection:function(oRequest,oCallback,oCaller){var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});var oRawResponse=(this.scope)?this.liveData.call(this.scope,oRequest,this,oCallback):this.liveData(oRequest,oCallback);if(this.responseType===DS.TYPE_UNKNOWN){if(YAHOO.lang.isArray(oRawResponse)){this.responseType=DS.TYPE_JSARRAY}else{if(oRawResponse&&oRawResponse.nodeType&&oRawResponse.nodeType==9){this.responseType=DS.TYPE_XML}else{if(oRawResponse&&oRawResponse.nodeName&&(oRawResponse.nodeName.toLowerCase()=="table")){this.responseType=DS.TYPE_HTMLTABLE}else{if(YAHOO.lang.isObject(oRawResponse)){this.responseType=DS.TYPE_JSON}else{if(YAHOO.lang.isString(oRawResponse)){this.responseType=DS.TYPE_TEXT}}}}}}this.handleResponse(oRequest,oRawResponse,oCallback,oCaller,tId);return tId}});lang.augmentObject(util.FunctionDataSource,DS);util.ScriptNodeDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_SCRIPTNODE;oLiveData=oLiveData||"";util.ScriptNodeDataSource.superclass.constructor.call(this,oLiveData,oConfigs)};lang.extend(util.ScriptNodeDataSource,DS,{getUtility:util.Get,asyncMode:"allowAll",scriptCallbackParam:"callback",generateRequestCallback:function(id){return"&"+this.scriptCallbackParam+"=YAHOO.util.ScriptNodeDataSource.callbacks["+id+"]"},doBeforeGetScriptNode:function(sUri){return sUri},makeConnection:function(oRequest,oCallback,oCaller){var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});if(util.ScriptNodeDataSource._nPending===0){util.ScriptNodeDataSource.callbacks=[];util.ScriptNodeDataSource._nId=0}var id=util.ScriptNodeDataSource._nId;util.ScriptNodeDataSource._nId++;var oSelf=this;util.ScriptNodeDataSource.callbacks[id]=function(oRawResponse){if((oSelf.asyncMode!=="ignoreStaleResponses")||(id===util.ScriptNodeDataSource.callbacks.length-1)){if(oSelf.responseType===DS.TYPE_UNKNOWN){if(YAHOO.lang.isArray(oRawResponse)){oSelf.responseType=DS.TYPE_JSARRAY}else{if(oRawResponse.nodeType&&oRawResponse.nodeType==9){oSelf.responseType=DS.TYPE_XML}else{if(oRawResponse.nodeName&&(oRawResponse.nodeName.toLowerCase()=="table")){oSelf.responseType=DS.TYPE_HTMLTABLE}else{if(YAHOO.lang.isObject(oRawResponse)){oSelf.responseType=DS.TYPE_JSON}else{if(YAHOO.lang.isString(oRawResponse)){oSelf.responseType=DS.TYPE_TEXT}}}}}}oSelf.handleResponse(oRequest,oRawResponse,oCallback,oCaller,tId)}else{}delete util.ScriptNodeDataSource.callbacks[id]};util.ScriptNodeDataSource._nPending++;var sUri=this.liveData+oRequest+this.generateRequestCallback(id);sUri=this.doBeforeGetScriptNode(sUri);this.getUtility.script(sUri,{autopurge:true,onsuccess:util.ScriptNodeDataSource._bumpPendingDown,onfail:util.ScriptNodeDataSource._bumpPendingDown});return tId}});lang.augmentObject(util.ScriptNodeDataSource,DS);lang.augmentObject(util.ScriptNodeDataSource,{_nId:0,_nPending:0,callbacks:[]});util.XHRDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_XHR;this.connMgr=this.connMgr||util.Connect;oLiveData=oLiveData||"";util.XHRDataSource.superclass.constructor.call(this,oLiveData,oConfigs)};lang.extend(util.XHRDataSource,DS,{connMgr:null,connXhrMode:"allowAll",connMethodPost:false,connTimeout:0,makeConnection:function(oRequest,oCallback,oCaller){var oRawResponse=null;var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});var oSelf=this;var oConnMgr=this.connMgr;var oQueue=this._oQueue;var _xhrSuccess=function(oResponse){if(oResponse&&(this.connXhrMode=="ignoreStaleResponses")&&(oResponse.tId!=oQueue.conn.tId)){return null}else{if(!oResponse){this.fireEvent("dataErrorEvent",{request:oRequest,response:null,callback:oCallback,caller:oCaller,message:DS.ERROR_DATANULL});DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller);return null}else{if(this.responseType===DS.TYPE_UNKNOWN){var ctype=(oResponse.getResponseHeader)?oResponse.getResponseHeader["Content-Type"]:null;if(ctype){if(ctype.indexOf("text/xml")>-1){this.responseType=DS.TYPE_XML}else{if(ctype.indexOf("application/json")>-1){this.responseType=DS.TYPE_JSON}else{if(ctype.indexOf("text/plain")>-1){this.responseType=DS.TYPE_TEXT}}}}}this.handleResponse(oRequest,oResponse,oCallback,oCaller,tId)}}};var _xhrFailure=function(oResponse){this.fireEvent("dataErrorEvent",{request:oRequest,response:oResponse,callback:oCallback,caller:oCaller,message:DS.ERROR_DATAINVALID});if(lang.isString(this.liveData)&&lang.isString(oRequest)&&(this.liveData.lastIndexOf("?")!==this.liveData.length-1)&&(oRequest.indexOf("?")!==0)){}oResponse=oResponse||{};oResponse.error=true;DS.issueCallback(oCallback,[oRequest,oResponse],true,oCaller);return null};var _xhrCallback={success:_xhrSuccess,failure:_xhrFailure,scope:this};if(lang.isNumber(this.connTimeout)){_xhrCallback.timeout=this.connTimeout}if(this.connXhrMode=="cancelStaleRequests"){if(oQueue.conn){if(oConnMgr.abort){oConnMgr.abort(oQueue.conn);oQueue.conn=null}else{}}}if(oConnMgr&&oConnMgr.asyncRequest){var sLiveData=this.liveData;var isPost=this.connMethodPost;var sMethod=(isPost)?"POST":"GET";var sUri=(isPost||!lang.isValue(oRequest))?sLiveData:sLiveData+oRequest;var sRequest=(isPost)?oRequest:null;if(this.connXhrMode!="queueRequests"){oQueue.conn=oConnMgr.asyncRequest(sMethod,sUri,_xhrCallback,sRequest)}else{if(oQueue.conn){var allRequests=oQueue.requests;allRequests.push({request:oRequest,callback:_xhrCallback});if(!oQueue.interval){oQueue.interval=setInterval(function(){if(oConnMgr.isCallInProgress(oQueue.conn)){return}else{if(allRequests.length>0){sUri=(isPost||!lang.isValue(allRequests[0].request))?sLiveData:sLiveData+allRequests[0].request;sRequest=(isPost)?allRequests[0].request:null;oQueue.conn=oConnMgr.asyncRequest(sMethod,sUri,allRequests[0].callback,sRequest);allRequests.shift()}else{clearInterval(oQueue.interval);oQueue.interval=null}}},50)}}else{oQueue.conn=oConnMgr.asyncRequest(sMethod,sUri,_xhrCallback,sRequest)}}}else{DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller)}return tId}});lang.augmentObject(util.XHRDataSource,DS);util.DataSource=function(oLiveData,oConfigs){oConfigs=oConfigs||{};var dataType=oConfigs.dataType;if(dataType){if(dataType==DS.TYPE_LOCAL){return new util.LocalDataSource(oLiveData,oConfigs)}else{if(dataType==DS.TYPE_XHR){return new util.XHRDataSource(oLiveData,oConfigs)}else{if(dataType==DS.TYPE_SCRIPTNODE){return new util.ScriptNodeDataSource(oLiveData,oConfigs)}else{if(dataType==DS.TYPE_JSFUNCTION){return new util.FunctionDataSource(oLiveData,oConfigs)}}}}}if(YAHOO.lang.isString(oLiveData)){return new util.XHRDataSource(oLiveData,oConfigs)}else{if(YAHOO.lang.isFunction(oLiveData)){return new util.FunctionDataSource(oLiveData,oConfigs)}else{return new util.LocalDataSource(oLiveData,oConfigs)}}};lang.augmentObject(util.DataSource,DS)})();YAHOO.util.Number={format:function(e,k){if(e===""||e===null||!isFinite(e)){return""}e=+e;k=YAHOO.lang.merge(YAHOO.util.Number.format.defaults,(k||{}));var j=e+"",l=Math.abs(e),b=k.decimalPlaces||0,r=k.thousandsSeparator,f=k.negativeFormat||("-"+k.format),q,p,g,h;if(f.indexOf("#")>-1){f=f.replace(/#/,k.format)}if(b<0){q=l-(l%1)+"";g=q.length+b;if(g>0){q=Number("."+q).toFixed(g).slice(2)+new Array(q.length-g+1).join("0")}else{q="0"}}else{var a=l+"";if(b>0||a.indexOf(".")>0){var d=Math.pow(10,b);q=Math.round(l*d)/d+"";var c=q.indexOf("."),m,o;if(c<0){m=b;o=(Math.pow(10,m)+"").substring(1);if(b>0){q=q+"."+o}}else{m=b-(q.length-c-1);o=(Math.pow(10,m)+"").substring(1);q=q+o}}else{q=l.toFixed(b)+""}}p=q.split(/\D/);if(l>=1000){g=p[0].length%3||3;p[0]=p[0].slice(0,g)+p[0].slice(g).replace(/(\d{3})/g,r+"$1")}return YAHOO.util.Number.format._applyFormat((e<0?f:k.format),p.join(k.decimalSeparator),k)}};YAHOO.util.Number.format.defaults={format:"{prefix}{number}{suffix}",negativeFormat:null,decimalSeparator:".",decimalPlaces:null,thousandsSeparator:""};YAHOO.util.Number.format._applyFormat=function(a,b,c){return a.replace(/\{(\w+)\}/g,function(d,e){return e==="number"?b:e in c?c[e]:""})};(function(){var a=function(c,e,d){if(typeof d==="undefined"){d=10}for(;parseInt(c,10)<d&&d>1;d/=10){c=e.toString()+c}return c.toString()};var b={formats:{a:function(e,c){return c.a[e.getDay()]},A:function(e,c){return c.A[e.getDay()]},b:function(e,c){return c.b[e.getMonth()]},B:function(e,c){return c.B[e.getMonth()]},C:function(c){return a(parseInt(c.getFullYear()/100,10),0)},d:["getDate","0"],e:["getDate"," "],g:function(c){return a(parseInt(b.formats.G(c)%100,10),0)},G:function(f){var g=f.getFullYear();var e=parseInt(b.formats.V(f),10);var c=parseInt(b.formats.W(f),10);if(c>e){g++}else{if(c===0&&e>=52){g--}}return g},H:["getHours","0"],I:function(e){var c=e.getHours()%12;return a(c===0?12:c,0)},j:function(h){var g=new Date(""+h.getFullYear()+"/1/1 GMT");var e=new Date(""+h.getFullYear()+"/"+(h.getMonth()+1)+"/"+h.getDate()+" GMT");var c=e-g;var f=parseInt(c/60000/60/24,10)+1;return a(f,0,100)},k:["getHours"," "],l:function(e){var c=e.getHours()%12;return a(c===0?12:c," ")},m:function(c){return a(c.getMonth()+1,0)},M:["getMinutes","0"],p:function(e,c){return c.p[e.getHours()>=12?1:0]},P:function(e,c){return c.P[e.getHours()>=12?1:0]},s:function(e,c){return parseInt(e.getTime()/1000,10)},S:["getSeconds","0"],u:function(c){var e=c.getDay();return e===0?7:e},U:function(g){var c=parseInt(b.formats.j(g),10);var f=6-g.getDay();var e=parseInt((c+f)/7,10);return a(e,0)},V:function(g){var f=parseInt(b.formats.W(g),10);var c=(new Date(""+g.getFullYear()+"/1/1")).getDay();var e=f+(c>4||c<=1?0:1);if(e===53&&(new Date(""+g.getFullYear()+"/12/31")).getDay()<4){e=1}else{if(e===0){e=b.formats.V(new Date(""+(g.getFullYear()-1)+"/12/31"))}}return a(e,0)},w:"getDay",W:function(g){var c=parseInt(b.formats.j(g),10);var f=7-b.formats.u(g);var e=parseInt((c+f)/7,10);return a(e,0,10)},y:function(c){return a(c.getFullYear()%100,0)},Y:"getFullYear",z:function(f){var e=f.getTimezoneOffset();var c=a(parseInt(Math.abs(e/60),10),0);var g=a(Math.abs(e%60),0);return(e>0?"-":"+")+c+g},Z:function(c){var e=c.toString().replace(/^.*:\d\d( GMT[+-]\d+)? \(?([A-Za-z ]+)\)?\d*$/,"$2").replace(/[a-z ]/g,"");if(e.length>4){e=b.formats.z(c)}return e},"%":function(c){return"%"}},aggregates:{c:"locale",D:"%m/%d/%y",F:"%Y-%m-%d",h:"%b",n:"\n",r:"locale",R:"%H:%M",t:"\t",T:"%H:%M:%S",x:"locale",X:"locale"},format:function(g,f,d){f=f||{};if(!(g instanceof Date)){return YAHOO.lang.isValue(g)?g:""}var h=f.format||"%m/%d/%Y";if(h==="YYYY/MM/DD"){h="%Y/%m/%d"}else{if(h==="DD/MM/YYYY"){h="%d/%m/%Y"}else{if(h==="MM/DD/YYYY"){h="%m/%d/%Y"}}}d=d||"en";if(!(d in YAHOO.util.DateLocale)){if(d.replace(/-[a-zA-Z]+$/,"") in YAHOO.util.DateLocale){d=d.replace(/-[a-zA-Z]+$/,"")}else{d="en"}}var j=YAHOO.util.DateLocale[d];var c=function(l,k){var m=b.aggregates[k];return(m==="locale"?j[k]:m)};var e=function(l,k){var m=b.formats[k];if(typeof m==="string"){return g[m]()}else{if(typeof m==="function"){return m.call(g,g,j)}else{if(typeof m==="object"&&typeof m[0]==="string"){return a(g[m[0]](),m[1])}else{return k}}}};while(h.match(/%[cDFhnrRtTxX]/)){h=h.replace(/%([cDFhnrRtTxX])/g,c)}var i=h.replace(/%([aAbBCdegGHIjklmMpPsSuUVwWyYzZ%])/g,e);c=e=undefined;return i}};YAHOO.namespace("YAHOO.util");YAHOO.util.Date=b;YAHOO.util.DateLocale={a:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],A:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],b:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],B:["January","February","March","April","May","June","July","August","September","October","November","December"],c:"%a %d %b %Y %T %Z",p:["AM","PM"],P:["am","pm"],r:"%I:%M:%S %p",x:"%d/%m/%y",X:"%T"};YAHOO.util.DateLocale.en=YAHOO.lang.merge(YAHOO.util.DateLocale,{});YAHOO.util.DateLocale["en-US"]=YAHOO.lang.merge(YAHOO.util.DateLocale.en,{c:"%a %d %b %Y %I:%M:%S %p %Z",x:"%m/%d/%Y",X:"%I:%M:%S %p"});YAHOO.util.DateLocale["en-GB"]=YAHOO.lang.merge(YAHOO.util.DateLocale.en,{r:"%l:%M:%S %P %Z"});YAHOO.util.DateLocale["en-AU"]=YAHOO.lang.merge(YAHOO.util.DateLocale.en)})();YAHOO.register("datasource",YAHOO.util.DataSource,{version:"2.9.0",build:"2800"});YAHOO.widget.DS_JSArray=YAHOO.util.LocalDataSource;YAHOO.widget.DS_JSFunction=YAHOO.util.FunctionDataSource;YAHOO.widget.DS_XHR=function(b,a,d){var c=new YAHOO.util.XHRDataSource(b,d);c._aDeprecatedSchema=a;return c};YAHOO.widget.DS_ScriptNode=function(b,a,d){var c=new YAHOO.util.ScriptNodeDataSource(b,d);c._aDeprecatedSchema=a;return c};YAHOO.widget.DS_XHR.TYPE_JSON=YAHOO.util.DataSourceBase.TYPE_JSON;YAHOO.widget.DS_XHR.TYPE_XML=YAHOO.util.DataSourceBase.TYPE_XML;YAHOO.widget.DS_XHR.TYPE_FLAT=YAHOO.util.DataSourceBase.TYPE_TEXT;YAHOO.widget.AutoComplete=function(g,b,j,c){if(g&&b&&j){if(j&&YAHOO.lang.isFunction(j.sendRequest)){this.dataSource=j}else{return}this.key=0;var d=j.responseSchema;if(j._aDeprecatedSchema){var k=j._aDeprecatedSchema;if(YAHOO.lang.isArray(k)){if((j.responseType===YAHOO.util.DataSourceBase.TYPE_JSON)||(j.responseType===YAHOO.util.DataSourceBase.TYPE_UNKNOWN)){d.resultsList=k[0];this.key=k[1];d.fields=(k.length<3)?null:k.slice(1)}else{if(j.responseType===YAHOO.util.DataSourceBase.TYPE_XML){d.resultNode=k[0];this.key=k[1];d.fields=k.slice(1)}else{if(j.responseType===YAHOO.util.DataSourceBase.TYPE_TEXT){d.recordDelim=k[0];d.fieldDelim=k[1]}}}j.responseSchema=d}}if(YAHOO.util.Dom.inDocument(g)){if(YAHOO.lang.isString(g)){this._sName="instance"+YAHOO.widget.AutoComplete._nIndex+" "+g;this._elTextbox=document.getElementById(g)}else{this._sName=(g.id)?"instance"+YAHOO.widget.AutoComplete._nIndex+" "+g.id:"instance"+YAHOO.widget.AutoComplete._nIndex;this._elTextbox=g}YAHOO.util.Dom.addClass(this._elTextbox,"yui-ac-input")}else{return}if(YAHOO.util.Dom.inDocument(b)){if(YAHOO.lang.isString(b)){this._elContainer=document.getElementById(b)}else{this._elContainer=b}if(this._elContainer.style.display=="none"){}var e=this._elContainer.parentNode;var a=e.tagName.toLowerCase();if(a=="div"){YAHOO.util.Dom.addClass(e,"yui-ac")}else{}}else{return}if(this.dataSource.dataType===YAHOO.util.DataSourceBase.TYPE_LOCAL){this.applyLocalFilter=true}if(c&&(c.constructor==Object)){for(var i in c){if(i){this[i]=c[i]}}}this._initContainerEl();this._initProps();this._initListEl();this._initContainerHelperEls();var h=this;var f=this._elTextbox;YAHOO.util.Event.addListener(f,"keyup",h._onTextboxKeyUp,h);YAHOO.util.Event.addListener(f,"keydown",h._onTextboxKeyDown,h);YAHOO.util.Event.addListener(f,"focus",h._onTextboxFocus,h);YAHOO.util.Event.addListener(f,"blur",h._onTextboxBlur,h);YAHOO.util.Event.addListener(b,"mouseover",h._onContainerMouseover,h);YAHOO.util.Event.addListener(b,"mouseout",h._onContainerMouseout,h);YAHOO.util.Event.addListener(b,"click",h._onContainerClick,h);YAHOO.util.Event.addListener(b,"scroll",h._onContainerScroll,h);YAHOO.util.Event.addListener(b,"resize",h._onContainerResize,h);YAHOO.util.Event.addListener(f,"keypress",h._onTextboxKeyPress,h);YAHOO.util.Event.addListener(window,"unload",h._onWindowUnload,h);this.textboxFocusEvent=new YAHOO.util.CustomEvent("textboxFocus",this);this.textboxKeyEvent=new YAHOO.util.CustomEvent("textboxKey",this);this.dataRequestEvent=new YAHOO.util.CustomEvent("dataRequest",this);this.dataRequestCancelEvent=new YAHOO.util.CustomEvent("dataRequestCancel",this);this.dataReturnEvent=new YAHOO.util.CustomEvent("dataReturn",this);this.dataErrorEvent=new YAHOO.util.CustomEvent("dataError",this);this.containerPopulateEvent=new YAHOO.util.CustomEvent("containerPopulate",this);this.containerExpandEvent=new YAHOO.util.CustomEvent("containerExpand",this);this.typeAheadEvent=new YAHOO.util.CustomEvent("typeAhead",this);this.itemMouseOverEvent=new YAHOO.util.CustomEvent("itemMouseOver",this);this.itemMouseOutEvent=new YAHOO.util.CustomEvent("itemMouseOut",this);this.itemArrowToEvent=new YAHOO.util.CustomEvent("itemArrowTo",this);this.itemArrowFromEvent=new YAHOO.util.CustomEvent("itemArrowFrom",this);this.itemSelectEvent=new YAHOO.util.CustomEvent("itemSelect",this);this.unmatchedItemSelectEvent=new YAHOO.util.CustomEvent("unmatchedItemSelect",this);this.selectionEnforceEvent=new YAHOO.util.CustomEvent("selectionEnforce",this);this.containerCollapseEvent=new YAHOO.util.CustomEvent("containerCollapse",this);this.textboxBlurEvent=new YAHOO.util.CustomEvent("textboxBlur",this);this.textboxChangeEvent=new YAHOO.util.CustomEvent("textboxChange",this);f.setAttribute("autocomplete","off");YAHOO.widget.AutoComplete._nIndex++}else{}};YAHOO.widget.AutoComplete.prototype.dataSource=null;YAHOO.widget.AutoComplete.prototype.applyLocalFilter=null;YAHOO.widget.AutoComplete.prototype.queryMatchCase=false;YAHOO.widget.AutoComplete.prototype.queryMatchContains=false;YAHOO.widget.AutoComplete.prototype.queryMatchSubset=false;YAHOO.widget.AutoComplete.prototype.minQueryLength=1;YAHOO.widget.AutoComplete.prototype.maxResultsDisplayed=10;YAHOO.widget.AutoComplete.prototype.queryDelay=0.2;YAHOO.widget.AutoComplete.prototype.typeAheadDelay=0.5;YAHOO.widget.AutoComplete.prototype.queryInterval=500;YAHOO.widget.AutoComplete.prototype.highlightClassName="yui-ac-highlight";YAHOO.widget.AutoComplete.prototype.prehighlightClassName=null;YAHOO.widget.AutoComplete.prototype.delimChar=null;YAHOO.widget.AutoComplete.prototype.autoHighlight=true;YAHOO.widget.AutoComplete.prototype.typeAhead=false;YAHOO.widget.AutoComplete.prototype.animHoriz=false;YAHOO.widget.AutoComplete.prototype.animVert=true;YAHOO.widget.AutoComplete.prototype.animSpeed=0.3;YAHOO.widget.AutoComplete.prototype.forceSelection=false;YAHOO.widget.AutoComplete.prototype.allowBrowserAutocomplete=true;YAHOO.widget.AutoComplete.prototype.alwaysShowContainer=false;YAHOO.widget.AutoComplete.prototype.useIFrame=false;YAHOO.widget.AutoComplete.prototype.useShadow=false;YAHOO.widget.AutoComplete.prototype.suppressInputUpdate=false;YAHOO.widget.AutoComplete.prototype.resultTypeList=true;YAHOO.widget.AutoComplete.prototype.queryQuestionMark=true;YAHOO.widget.AutoComplete.prototype.autoSnapContainer=true;YAHOO.widget.AutoComplete.prototype.toString=function(){return"AutoComplete "+this._sName};YAHOO.widget.AutoComplete.prototype.getInputEl=function(){return this._elTextbox};YAHOO.widget.AutoComplete.prototype.getContainerEl=function(){return this._elContainer};YAHOO.widget.AutoComplete.prototype.isFocused=function(){return this._bFocused};YAHOO.widget.AutoComplete.prototype.isContainerOpen=function(){return this._bContainerOpen};YAHOO.widget.AutoComplete.prototype.getListEl=function(){return this._elList};YAHOO.widget.AutoComplete.prototype.getListItemMatch=function(a){if(a._sResultMatch){return a._sResultMatch}else{return null}};YAHOO.widget.AutoComplete.prototype.getListItemData=function(a){if(a._oResultData){return a._oResultData}else{return null}};YAHOO.widget.AutoComplete.prototype.getListItemIndex=function(a){if(YAHOO.lang.isNumber(a._nItemIndex)){return a._nItemIndex}else{return null}};YAHOO.widget.AutoComplete.prototype.setHeader=function(b){if(this._elHeader){var a=this._elHeader;if(b){a.innerHTML=b;a.style.display=""}else{a.innerHTML="";a.style.display="none"}}};YAHOO.widget.AutoComplete.prototype.setFooter=function(b){if(this._elFooter){var a=this._elFooter;if(b){a.innerHTML=b;a.style.display=""}else{a.innerHTML="";a.style.display="none"}}};YAHOO.widget.AutoComplete.prototype.setBody=function(a){if(this._elBody){var b=this._elBody;YAHOO.util.Event.purgeElement(b,true);if(a){b.innerHTML=a;b.style.display=""}else{b.innerHTML="";b.style.display="none"}this._elList=null}};YAHOO.widget.AutoComplete.prototype.generateRequest=function(b){var a=this.dataSource.dataType;if(a===YAHOO.util.DataSourceBase.TYPE_XHR){if(!this.dataSource.connMethodPost){b=(this.queryQuestionMark?"?":"")+(this.dataSource.scriptQueryParam||"query")+"="+b+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"")}else{b=(this.dataSource.scriptQueryParam||"query")+"="+b+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"")}}else{if(a===YAHOO.util.DataSourceBase.TYPE_SCRIPTNODE){b="&"+(this.dataSource.scriptQueryParam||"query")+"="+b+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"")}}return b};YAHOO.widget.AutoComplete.prototype.sendQuery=function(b){this._bFocused=true;var a=(this.delimChar)?this._elTextbox.value+b:b;this._sendQuery(a)};YAHOO.widget.AutoComplete.prototype.snapContainer=function(){var a=this._elTextbox,b=YAHOO.util.Dom.getXY(a);b[1]+=YAHOO.util.Dom.get(a).offsetHeight+2;YAHOO.util.Dom.setXY(this._elContainer,b)};YAHOO.widget.AutoComplete.prototype.expandContainer=function(){this._toggleContainer(true)};YAHOO.widget.AutoComplete.prototype.collapseContainer=function(){this._toggleContainer(false)};YAHOO.widget.AutoComplete.prototype.clearList=function(){var b=this._elList.childNodes,a=b.length-1;for(;a>-1;a--){b[a].style.display="none"}};YAHOO.widget.AutoComplete.prototype.getSubsetMatches=function(e){var d,c,a;for(var b=e.length;b>=this.minQueryLength;b--){a=this.generateRequest(e.substr(0,b));this.dataRequestEvent.fire(this,d,a);c=this.dataSource.getCachedResponse(a);if(c){return this.filterResults.apply(this.dataSource,[e,c,c,{scope:this}])}}return null};YAHOO.widget.AutoComplete.prototype.preparseRawResponse=function(c,b,a){var d=((this.responseStripAfter!=="")&&(b.indexOf))?b.indexOf(this.responseStripAfter):-1;if(d!=-1){b=b.substring(0,d)}return b};YAHOO.widget.AutoComplete.prototype.filterResults=function(l,n,r,m){if(m&&m.argument&&YAHOO.lang.isValue(m.argument.query)){l=m.argument.query}if(l&&l!==""){r=YAHOO.widget.AutoComplete._cloneObject(r);var j=m.scope,q=this,c=r.results,o=[],b=j.maxResultsDisplayed,k=(q.queryMatchCase||j.queryMatchCase),a=(q.queryMatchContains||j.queryMatchContains);for(var d=0,h=c.length;d<h;d++){var f=c[d];var e=null;if(YAHOO.lang.isString(f)){e=f}else{if(YAHOO.lang.isArray(f)){e=f[0]}else{if(this.responseSchema.fields){var p=this.responseSchema.fields[0].key||this.responseSchema.fields[0];e=f[p]}else{if(this.key){e=f[this.key]}}}}if(YAHOO.lang.isString(e)){var g=(k)?e.indexOf(decodeURIComponent(l)):e.toLowerCase().indexOf(decodeURIComponent(l).toLowerCase());if((!a&&(g===0))||(a&&(g>-1))){o.push(f)}}if(h>b&&o.length===b){break}}r.results=o}else{}return r};YAHOO.widget.AutoComplete.prototype.handleResponse=function(c,a,b){if((this instanceof YAHOO.widget.AutoComplete)&&this._sName){this._populateList(c,a,b)}};YAHOO.widget.AutoComplete.prototype.doBeforeLoadData=function(c,a,b){return true};YAHOO.widget.AutoComplete.prototype.formatResult=function(b,d,a){var c=(a)?a:"";return c};YAHOO.widget.AutoComplete.prototype.formatEscapedResult=function(c,d,b){var a=(b)?b:"";return YAHOO.lang.escapeHTML(a)};YAHOO.widget.AutoComplete.prototype.doBeforeExpandContainer=function(d,a,c,b){return true};YAHOO.widget.AutoComplete.prototype.destroy=function(){var b=this.toString();var a=this._elTextbox;var d=this._elContainer;this.textboxFocusEvent.unsubscribeAll();this.textboxKeyEvent.unsubscribeAll();this.dataRequestEvent.unsubscribeAll();this.dataReturnEvent.unsubscribeAll();this.dataErrorEvent.unsubscribeAll();this.containerPopulateEvent.unsubscribeAll();this.containerExpandEvent.unsubscribeAll();this.typeAheadEvent.unsubscribeAll();this.itemMouseOverEvent.unsubscribeAll();this.itemMouseOutEvent.unsubscribeAll();this.itemArrowToEvent.unsubscribeAll();this.itemArrowFromEvent.unsubscribeAll();this.itemSelectEvent.unsubscribeAll();this.unmatchedItemSelectEvent.unsubscribeAll();this.selectionEnforceEvent.unsubscribeAll();this.containerCollapseEvent.unsubscribeAll();this.textboxBlurEvent.unsubscribeAll();this.textboxChangeEvent.unsubscribeAll();YAHOO.util.Event.purgeElement(a,true);YAHOO.util.Event.purgeElement(d,true);d.innerHTML="";for(var c in this){if(YAHOO.lang.hasOwnProperty(this,c)){this[c]=null}}};YAHOO.widget.AutoComplete.prototype.textboxFocusEvent=null;YAHOO.widget.AutoComplete.prototype.textboxKeyEvent=null;YAHOO.widget.AutoComplete.prototype.dataRequestEvent=null;YAHOO.widget.AutoComplete.prototype.dataRequestCancelEvent=null;YAHOO.widget.AutoComplete.prototype.dataReturnEvent=null;YAHOO.widget.AutoComplete.prototype.dataErrorEvent=null;YAHOO.widget.AutoComplete.prototype.containerPopulateEvent=null;YAHOO.widget.AutoComplete.prototype.containerExpandEvent=null;YAHOO.widget.AutoComplete.prototype.typeAheadEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOverEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOutEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowToEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowFromEvent=null;YAHOO.widget.AutoComplete.prototype.itemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.unmatchedItemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.selectionEnforceEvent=null;YAHOO.widget.AutoComplete.prototype.containerCollapseEvent=null;YAHOO.widget.AutoComplete.prototype.textboxBlurEvent=null;YAHOO.widget.AutoComplete.prototype.textboxChangeEvent=null;YAHOO.widget.AutoComplete._nIndex=0;YAHOO.widget.AutoComplete.prototype._sName=null;YAHOO.widget.AutoComplete.prototype._elTextbox=null;YAHOO.widget.AutoComplete.prototype._elContainer=null;YAHOO.widget.AutoComplete.prototype._elContent=null;YAHOO.widget.AutoComplete.prototype._elHeader=null;YAHOO.widget.AutoComplete.prototype._elBody=null;YAHOO.widget.AutoComplete.prototype._elFooter=null;YAHOO.widget.AutoComplete.prototype._elShadow=null;YAHOO.widget.AutoComplete.prototype._elIFrame=null;YAHOO.widget.AutoComplete.prototype._bFocused=false;YAHOO.widget.AutoComplete.prototype._oAnim=null;YAHOO.widget.AutoComplete.prototype._bContainerOpen=false;YAHOO.widget.AutoComplete.prototype._bOverContainer=false;YAHOO.widget.AutoComplete.prototype._elList=null;YAHOO.widget.AutoComplete.prototype._nDisplayedItems=0;YAHOO.widget.AutoComplete.prototype._sCurQuery=null;YAHOO.widget.AutoComplete.prototype._sPastSelections="";YAHOO.widget.AutoComplete.prototype._sInitInputValue=null;YAHOO.widget.AutoComplete.prototype._elCurListItem=null;YAHOO.widget.AutoComplete.prototype._elCurPrehighlightItem=null;YAHOO.widget.AutoComplete.prototype._bItemSelected=false;YAHOO.widget.AutoComplete.prototype._nKeyCode=null;YAHOO.widget.AutoComplete.prototype._nDelayID=-1;YAHOO.widget.AutoComplete.prototype._nTypeAheadDelayID=-1;YAHOO.widget.AutoComplete.prototype._iFrameSrc="javascript:false;";YAHOO.widget.AutoComplete.prototype._queryInterval=null;YAHOO.widget.AutoComplete.prototype._sLastTextboxValue=null;YAHOO.widget.AutoComplete.prototype._initProps=function(){var b=this.minQueryLength;if(!YAHOO.lang.isNumber(b)){this.minQueryLength=1}var e=this.maxResultsDisplayed;if(!YAHOO.lang.isNumber(e)||(e<1)){this.maxResultsDisplayed=10}var f=this.queryDelay;if(!YAHOO.lang.isNumber(f)||(f<0)){this.queryDelay=0.2}var c=this.typeAheadDelay;if(!YAHOO.lang.isNumber(c)||(c<0)){this.typeAheadDelay=0.2}var a=this.delimChar;if(YAHOO.lang.isString(a)&&(a.length>0)){this.delimChar=[a]}else{if(!YAHOO.lang.isArray(a)){this.delimChar=null}}var d=this.animSpeed;if((this.animHoriz||this.animVert)&&YAHOO.util.Anim){if(!YAHOO.lang.isNumber(d)||(d<0)){this.animSpeed=0.3}if(!this._oAnim){this._oAnim=new YAHOO.util.Anim(this._elContent,{},this.animSpeed)}else{this._oAnim.duration=this.animSpeed}}if(this.forceSelection&&a){}};YAHOO.widget.AutoComplete.prototype._initContainerHelperEls=function(){if(this.useShadow&&!this._elShadow){var a=document.createElement("div");a.className="yui-ac-shadow";a.style.width=0;a.style.height=0;this._elShadow=this._elContainer.appendChild(a)}if(this.useIFrame&&!this._elIFrame){var b=document.createElement("iframe");b.src=this._iFrameSrc;b.frameBorder=0;b.scrolling="no";b.style.position="absolute";b.style.width=0;b.style.height=0;b.style.padding=0;b.tabIndex=-1;b.role="presentation";b.title="Presentational iframe shim";this._elIFrame=this._elContainer.appendChild(b)}};YAHOO.widget.AutoComplete.prototype._initContainerEl=function(){YAHOO.util.Dom.addClass(this._elContainer,"yui-ac-container");if(!this._elContent){var c=document.createElement("div");c.className="yui-ac-content";c.style.display="none";this._elContent=this._elContainer.appendChild(c);var b=document.createElement("div");b.className="yui-ac-hd";b.style.display="none";this._elHeader=this._elContent.appendChild(b);var d=document.createElement("div");d.className="yui-ac-bd";this._elBody=this._elContent.appendChild(d);var a=document.createElement("div");a.className="yui-ac-ft";a.style.display="none";this._elFooter=this._elContent.appendChild(a)}else{}};YAHOO.widget.AutoComplete.prototype._initListEl=function(){var c=this.maxResultsDisplayed,a=this._elList||document.createElement("ul"),b;while(a.childNodes.length<c){b=document.createElement("li");b.style.display="none";b._nItemIndex=a.childNodes.length;a.appendChild(b)}if(!this._elList){var d=this._elBody;YAHOO.util.Event.purgeElement(d,true);d.innerHTML="";this._elList=d.appendChild(a)}this._elBody.style.display=""};YAHOO.widget.AutoComplete.prototype._focus=function(){var a=this;setTimeout(function(){try{a._elTextbox.focus()}catch(b){}},0)};YAHOO.widget.AutoComplete.prototype._enableIntervalDetection=function(){var a=this;if(!a._queryInterval&&a.queryInterval){a._queryInterval=setInterval(function(){a._onInterval()},a.queryInterval)}};YAHOO.widget.AutoComplete.prototype.enableIntervalDetection=YAHOO.widget.AutoComplete.prototype._enableIntervalDetection;YAHOO.widget.AutoComplete.prototype._onInterval=function(){var a=this._elTextbox.value;var b=this._sLastTextboxValue;if(a!=b){this._sLastTextboxValue=a;this._sendQuery(a)}};YAHOO.widget.AutoComplete.prototype._clearInterval=function(){if(this._queryInterval){clearInterval(this._queryInterval);this._queryInterval=null}};YAHOO.widget.AutoComplete.prototype._isIgnoreKey=function(a){if((a==9)||(a==13)||(a==16)||(a==17)||(a>=18&&a<=20)||(a==27)||(a>=33&&a<=35)||(a>=36&&a<=40)||(a>=44&&a<=45)||(a==229)){return true}return false};YAHOO.widget.AutoComplete.prototype._sendQuery=function(d){if(this.minQueryLength<0){this._toggleContainer(false);return}if(this.delimChar){var a=this._extractQuery(d);d=a.query;this._sPastSelections=a.previous}if((d&&(d.length<this.minQueryLength))||(!d&&this.minQueryLength>0)){if(this._nDelayID!=-1){clearTimeout(this._nDelayID)}this._toggleContainer(false);return}d=encodeURIComponent(d);this._nDelayID=-1;if(this.dataSource.queryMatchSubset||this.queryMatchSubset){var c=this.getSubsetMatches(d);if(c){this.handleResponse(d,c,{query:d});return}}if(this.dataSource.responseStripAfter){this.dataSource.doBeforeParseData=this.preparseRawResponse}if(this.applyLocalFilter){this.dataSource.doBeforeCallback=this.filterResults}var b=this.generateRequest(d);if(b!==undefined){this.dataRequestEvent.fire(this,d,b);this.dataSource.sendRequest(b,{success:this.handleResponse,failure:this.handleResponse,scope:this,argument:{query:d}})}else{this.dataRequestCancelEvent.fire(this,d)}};YAHOO.widget.AutoComplete.prototype._populateListItem=function(b,a,c){b.innerHTML=this.formatResult(a,c,b._sResultMatch)};YAHOO.widget.AutoComplete.prototype._populateList=function(n,f,c){if(this._nTypeAheadDelayID!=-1){clearTimeout(this._nTypeAheadDelayID)}n=(c&&c.query)?c.query:n;var h=this.doBeforeLoadData(n,f,c);if(h&&!f.error){this.dataReturnEvent.fire(this,n,f.results);if(this._bFocused){var p=decodeURIComponent(n);this._sCurQuery=p;this._bItemSelected=false;var u=f.results,a=Math.min(u.length,this.maxResultsDisplayed),m=(this.dataSource.responseSchema.fields)?(this.dataSource.responseSchema.fields[0].key||this.dataSource.responseSchema.fields[0]):0;if(a>0){if(!this._elList||(this._elList.childNodes.length<a)){this._initListEl()}this._initContainerHelperEls();var l=this._elList.childNodes;for(var t=a-1;t>=0;t--){var s=l[t],e=u[t];if(this.resultTypeList){var b=[];b[0]=(YAHOO.lang.isString(e))?e:e[m]||e[this.key];var o=this.dataSource.responseSchema.fields;if(YAHOO.lang.isArray(o)&&(o.length>1)){for(var q=1,v=o.length;q<v;q++){b[b.length]=e[o[q].key||o[q]]}}else{if(YAHOO.lang.isArray(e)){b=e}else{if(YAHOO.lang.isString(e)){b=[e]}else{b[1]=e}}}e=b}s._sResultMatch=(YAHOO.lang.isString(e))?e:(YAHOO.lang.isArray(e))?e[0]:(e[m]||"");s._oResultData=e;this._populateListItem(s,e,p);s.style.display=""}if(a<l.length){var g;for(var r=l.length-1;r>=a;r--){g=l[r];g.style.display="none"}}this._nDisplayedItems=a;this.containerPopulateEvent.fire(this,n,u);if(this.autoHighlight){var d=this._elList.firstChild;this._toggleHighlight(d,"to");this.itemArrowToEvent.fire(this,d);this._typeAhead(d,n)}else{this._toggleHighlight(this._elCurListItem,"from")}h=this._doBeforeExpandContainer(this._elTextbox,this._elContainer,n,u);this._toggleContainer(h)}else{this._toggleContainer(false)}return}}else{this.dataErrorEvent.fire(this,n,f)}};YAHOO.widget.AutoComplete.prototype._doBeforeExpandContainer=function(d,a,c,b){if(this.autoSnapContainer){this.snapContainer()}return this.doBeforeExpandContainer(d,a,c,b)};YAHOO.widget.AutoComplete.prototype._clearSelection=function(){var a=(this.delimChar)?this._extractQuery(this._elTextbox.value):{previous:"",query:this._elTextbox.value};this._elTextbox.value=a.previous;this.selectionEnforceEvent.fire(this,a.query)};YAHOO.widget.AutoComplete.prototype._textMatchesOption=function(){var a=null;for(var b=0;b<this._nDisplayedItems;b++){var c=this._elList.childNodes[b];var d=(""+c._sResultMatch).toLowerCase();if(d==this._sCurQuery.toLowerCase()){a=c;break}}return(a)};YAHOO.widget.AutoComplete.prototype._typeAhead=function(b,d){if(!this.typeAhead||(this._nKeyCode==8)){return}var a=this,c=this._elTextbox;if(c.setSelectionRange||c.createTextRange){this._nTypeAheadDelayID=setTimeout(function(){var f=c.value.length;a._updateValue(b);var g=c.value.length;a._selectText(c,f,g);var e=c.value.substr(f,g);a._sCurQuery=b._sResultMatch;a.typeAheadEvent.fire(a,d,e)},(this.typeAheadDelay*1000))}};YAHOO.widget.AutoComplete.prototype._selectText=function(d,a,b){if(d.setSelectionRange){d.setSelectionRange(a,b)}else{if(d.createTextRange){var c=d.createTextRange();c.moveStart("character",a);c.moveEnd("character",b-d.value.length);c.select()}else{d.select()}}};YAHOO.widget.AutoComplete.prototype._extractQuery=function(h){var c=this.delimChar,f=-1,g,e,b=c.length-1,d;for(;b>=0;b--){g=h.lastIndexOf(c[b]);if(g>f){f=g}}if(c[b]==" "){for(var a=c.length-1;a>=0;a--){if(h[f-1]==c[a]){f--;break}}}if(f>-1){e=f+1;while(h.charAt(e)==" "){e+=1}d=h.substring(0,e);h=h.substr(e)}else{d=""}return{previous:d,query:h}};YAHOO.widget.AutoComplete.prototype._toggleContainerHelpers=function(d){var e=this._elContent.offsetWidth+"px";var b=this._elContent.offsetHeight+"px";if(this.useIFrame&&this._elIFrame){var c=this._elIFrame;if(d){c.style.width=e;c.style.height=b;c.style.padding=""}else{c.style.width=0;c.style.height=0;c.style.padding=0}}if(this.useShadow&&this._elShadow){var a=this._elShadow;if(d){a.style.width=e;a.style.height=b}else{a.style.width=0;a.style.height=0}}};YAHOO.widget.AutoComplete.prototype._toggleContainer=function(i){var d=this._elContainer;if(this.alwaysShowContainer&&this._bContainerOpen){return}if(!i){this._toggleHighlight(this._elCurListItem,"from");this._nDisplayedItems=0;this._sCurQuery=null;if(this._elContent.style.display=="none"){return}}var a=this._oAnim;if(a&&a.getEl()&&(this.animHoriz||this.animVert)){if(a.isAnimated()){a.stop(true)}var g=this._elContent.cloneNode(true);d.appendChild(g);g.style.top="-9000px";g.style.width="";g.style.height="";g.style.display="";var f=g.offsetWidth;var c=g.offsetHeight;var b=(this.animHoriz)?0:f;var e=(this.animVert)?0:c;a.attributes=(i)?{width:{to:f},height:{to:c}}:{width:{to:b},height:{to:e}};if(i&&!this._bContainerOpen){this._elContent.style.width=b+"px";this._elContent.style.height=e+"px"}else{this._elContent.style.width=f+"px";this._elContent.style.height=c+"px"}d.removeChild(g);g=null;var h=this;var j=function(){a.onComplete.unsubscribeAll();if(i){h._toggleContainerHelpers(true);h._bContainerOpen=i;h.containerExpandEvent.fire(h)}else{h._elContent.style.display="none";h._bContainerOpen=i;h.containerCollapseEvent.fire(h)}};this._toggleContainerHelpers(false);this._elContent.style.display="";a.onComplete.subscribe(j);a.animate()}else{if(i){this._elContent.style.display="";this._toggleContainerHelpers(true);this._bContainerOpen=i;this.containerExpandEvent.fire(this)}else{this._toggleContainerHelpers(false);this._elContent.style.display="none";this._bContainerOpen=i;this.containerCollapseEvent.fire(this)}}};YAHOO.widget.AutoComplete.prototype._toggleHighlight=function(a,c){if(a){var b=this.highlightClassName;if(this._elCurListItem){YAHOO.util.Dom.removeClass(this._elCurListItem,b);this._elCurListItem=null}if((c=="to")&&b){YAHOO.util.Dom.addClass(a,b);this._elCurListItem=a}}};YAHOO.widget.AutoComplete.prototype._togglePrehighlight=function(b,c){var a=this.prehighlightClassName;if(this._elCurPrehighlightItem){YAHOO.util.Dom.removeClass(this._elCurPrehighlightItem,a)}if(b==this._elCurListItem){return}if((c=="mouseover")&&a){YAHOO.util.Dom.addClass(b,a);this._elCurPrehighlightItem=b}else{YAHOO.util.Dom.removeClass(b,a)}};YAHOO.widget.AutoComplete.prototype._updateValue=function(c){if(!this.suppressInputUpdate){var f=this._elTextbox;var e=(this.delimChar)?(this.delimChar[0]||this.delimChar):null;var b=c._sResultMatch;var d="";if(e){d=this._sPastSelections;d+=b+e;if(e!=" "){d+=" "}}else{d=b}f.value=d;if(f.type=="textarea"){f.scrollTop=f.scrollHeight}var a=f.value.length;this._selectText(f,a,a);this._elCurListItem=c}};YAHOO.widget.AutoComplete.prototype._selectItem=function(a){this._bItemSelected=true;this._updateValue(a);this._sPastSelections=this._elTextbox.value;this._clearInterval();this.itemSelectEvent.fire(this,a,a._oResultData);this._toggleContainer(false)};YAHOO.widget.AutoComplete.prototype._jumpSelection=function(){if(this._elCurListItem){this._selectItem(this._elCurListItem)}else{this._toggleContainer(false)}};YAHOO.widget.AutoComplete.prototype._moveSelection=function(g){if(this._bContainerOpen){var h=this._elCurListItem,d=-1;if(h){d=h._nItemIndex}var e=(g==40)?(d+1):(d-1);if(e<-2||e>=this._nDisplayedItems){return}if(h){this._toggleHighlight(h,"from");this.itemArrowFromEvent.fire(this,h)}if(e==-1){if(this.delimChar){this._elTextbox.value=this._sPastSelections+this._sCurQuery}else{this._elTextbox.value=this._sCurQuery}return}if(e==-2){this._toggleContainer(false);return}var f=this._elList.childNodes[e],b=this._elContent,c=YAHOO.util.Dom.getStyle(b,"overflow"),i=YAHOO.util.Dom.getStyle(b,"overflowY"),a=((c=="auto")||(c=="scroll")||(i=="auto")||(i=="scroll"));if(a&&(e>-1)&&(e<this._nDisplayedItems)){if(g==40){if((f.offsetTop+f.offsetHeight)>(b.scrollTop+b.offsetHeight)){b.scrollTop=(f.offsetTop+f.offsetHeight)-b.offsetHeight}else{if((f.offsetTop+f.offsetHeight)<b.scrollTop){b.scrollTop=f.offsetTop}}}else{if(f.offsetTop<b.scrollTop){this._elContent.scrollTop=f.offsetTop}else{if(f.offsetTop>(b.scrollTop+b.offsetHeight)){this._elContent.scrollTop=(f.offsetTop+f.offsetHeight)-b.offsetHeight}}}}this._toggleHighlight(f,"to");this.itemArrowToEvent.fire(this,f);if(this.typeAhead){this._updateValue(f);this._sCurQuery=f._sResultMatch}}};YAHOO.widget.AutoComplete.prototype._onContainerMouseover=function(a,c){var d=YAHOO.util.Event.getTarget(a);var b=d.nodeName.toLowerCase();while(d&&(b!="table")){switch(b){case"body":return;case"li":if(c.prehighlightClassName){c._togglePrehighlight(d,"mouseover")}else{c._toggleHighlight(d,"to")}c.itemMouseOverEvent.fire(c,d);break;case"div":if(YAHOO.util.Dom.hasClass(d,"yui-ac-container")){c._bOverContainer=true;return}break;default:break}d=d.parentNode;if(d){b=d.nodeName.toLowerCase()}}};YAHOO.widget.AutoComplete.prototype._onContainerMouseout=function(a,c){var d=YAHOO.util.Event.getTarget(a);var b=d.nodeName.toLowerCase();while(d&&(b!="table")){switch(b){case"body":return;case"li":if(c.prehighlightClassName){c._togglePrehighlight(d,"mouseout")}else{c._toggleHighlight(d,"from")}c.itemMouseOutEvent.fire(c,d);break;case"ul":c._toggleHighlight(c._elCurListItem,"to");break;case"div":if(YAHOO.util.Dom.hasClass(d,"yui-ac-container")){c._bOverContainer=false;return}break;default:break}d=d.parentNode;if(d){b=d.nodeName.toLowerCase()}}};YAHOO.widget.AutoComplete.prototype._onContainerClick=function(a,c){var d=YAHOO.util.Event.getTarget(a);var b=d.nodeName.toLowerCase();while(d&&(b!="table")){switch(b){case"body":return;case"li":c._toggleHighlight(d,"to");c._selectItem(d);return;default:break}d=d.parentNode;if(d){b=d.nodeName.toLowerCase()}}};YAHOO.widget.AutoComplete.prototype._onContainerScroll=function(a,b){b._focus()};YAHOO.widget.AutoComplete.prototype._onContainerResize=function(a,b){b._toggleContainerHelpers(b._bContainerOpen)};YAHOO.widget.AutoComplete.prototype._onTextboxKeyDown=function(a,b){var c=a.keyCode;if(b._nTypeAheadDelayID!=-1){clearTimeout(b._nTypeAheadDelayID)}switch(c){case 9:if(!YAHOO.env.ua.opera&&(navigator.userAgent.toLowerCase().indexOf("mac")==-1)||(YAHOO.env.ua.webkit>420)){if(b._elCurListItem){if(b.delimChar&&(b._nKeyCode!=c)){if(b._bContainerOpen){YAHOO.util.Event.stopEvent(a)}}b._selectItem(b._elCurListItem)}else{b._toggleContainer(false)}}break;case 13:if(!YAHOO.env.ua.opera&&(navigator.userAgent.toLowerCase().indexOf("mac")==-1)||(YAHOO.env.ua.webkit>420)){if(b._elCurListItem){if(b._nKeyCode!=c){if(b._bContainerOpen){YAHOO.util.Event.stopEvent(a)}}b._selectItem(b._elCurListItem)}else{b._toggleContainer(false)}}break;case 27:b._toggleContainer(false);return;case 39:b._jumpSelection();break;case 38:if(b._bContainerOpen){YAHOO.util.Event.stopEvent(a);b._moveSelection(c)}break;case 40:if(b._bContainerOpen){YAHOO.util.Event.stopEvent(a);b._moveSelection(c)}break;default:b._bItemSelected=false;b._toggleHighlight(b._elCurListItem,"from");b.textboxKeyEvent.fire(b,c);break}if(c===18){b._enableIntervalDetection()}b._nKeyCode=c};YAHOO.widget.AutoComplete.prototype._onTextboxKeyPress=function(a,b){var c=a.keyCode;if(YAHOO.env.ua.opera||(navigator.userAgent.toLowerCase().indexOf("mac")!=-1)&&(YAHOO.env.ua.webkit<420)){switch(c){case 9:if(b._bContainerOpen){if(b.delimChar){YAHOO.util.Event.stopEvent(a)}if(b._elCurListItem){b._selectItem(b._elCurListItem)}else{b._toggleContainer(false)}}break;case 13:if(b._bContainerOpen){YAHOO.util.Event.stopEvent(a);if(b._elCurListItem){b._selectItem(b._elCurListItem)}else{b._toggleContainer(false)}}break;default:break}}else{if(c==229){b._enableIntervalDetection()}}};YAHOO.widget.AutoComplete.prototype._onTextboxKeyUp=function(a,c){var b=this.value;c._initProps();var d=a.keyCode;if(c._isIgnoreKey(d)){return}if(c._nDelayID!=-1){clearTimeout(c._nDelayID)}c._nDelayID=setTimeout(function(){c._sendQuery(b)},(c.queryDelay*1000))};YAHOO.widget.AutoComplete.prototype._onTextboxFocus=function(a,b){if(!b._bFocused){b._elTextbox.setAttribute("autocomplete","off");b._bFocused=true;b._sInitInputValue=b._elTextbox.value;b.textboxFocusEvent.fire(b)}};YAHOO.widget.AutoComplete.prototype._onTextboxBlur=function(a,c){if(!c._bOverContainer||(c._nKeyCode==9)){if(!c._bItemSelected){var b=c._textMatchesOption();if(!c._bContainerOpen||(c._bContainerOpen&&(b===null))){if(c.forceSelection){c._clearSelection()}else{c.unmatchedItemSelectEvent.fire(c,c._sCurQuery)}}else{if(c.forceSelection){c._selectItem(b)}}}c._clearInterval();c._bFocused=false;if(c._sInitInputValue!==c._elTextbox.value){c.textboxChangeEvent.fire(c)}c.textboxBlurEvent.fire(c);c._toggleContainer(false)}else{c._focus()}};YAHOO.widget.AutoComplete.prototype._onWindowUnload=function(a,b){if(b&&b._elTextbox&&b.allowBrowserAutocomplete){b._elTextbox.setAttribute("autocomplete","on")}};YAHOO.widget.AutoComplete.prototype.doBeforeSendQuery=function(a){return this.generateRequest(a)};YAHOO.widget.AutoComplete.prototype.getListItems=function(){var c=[],b=this._elList.childNodes;for(var a=b.length-1;a>=0;a--){c[a]=b[a]}return c};YAHOO.widget.AutoComplete._cloneObject=function(d){if(!YAHOO.lang.isValue(d)){return d}var f={};if(YAHOO.lang.isFunction(d)){f=d}else{if(YAHOO.lang.isArray(d)){var e=[];for(var c=0,b=d.length;c<b;c++){e[c]=YAHOO.widget.AutoComplete._cloneObject(d[c])}f=e}else{if(YAHOO.lang.isObject(d)){for(var a in d){if(YAHOO.lang.hasOwnProperty(d,a)){if(YAHOO.lang.isValue(d[a])&&YAHOO.lang.isObject(d[a])||YAHOO.lang.isArray(d[a])){f[a]=YAHOO.widget.AutoComplete._cloneObject(d[a])}else{f[a]=d[a]}}}}else{f=d}}}return f};YAHOO.register("autocomplete",YAHOO.widget.AutoComplete,{version:"2.9.0",build:"2800"});(function(){YAHOO.util.Config=function(d){if(d){this.init(d)}};var b=YAHOO.lang,c=YAHOO.util.CustomEvent,a=YAHOO.util.Config;a.CONFIG_CHANGED_EVENT="configChanged";a.BOOLEAN_TYPE="boolean";a.prototype={owner:null,queueInProgress:false,config:null,initialConfig:null,eventQueue:null,configChangedEvent:null,init:function(d){this.owner=d;this.configChangedEvent=this.createEvent(a.CONFIG_CHANGED_EVENT);this.configChangedEvent.signature=c.LIST;this.queueInProgress=false;this.config={};this.initialConfig={};this.eventQueue=[]},checkBoolean:function(d){return(typeof d==a.BOOLEAN_TYPE)},checkNumber:function(d){return(!isNaN(d))},fireEvent:function(d,f){var e=this.config[d];if(e&&e.event){e.event.fire(f)}},addProperty:function(e,d){e=e.toLowerCase();this.config[e]=d;d.event=this.createEvent(e,{scope:this.owner});d.event.signature=c.LIST;d.key=e;if(d.handler){d.event.subscribe(d.handler,this.owner)}this.setProperty(e,d.value,true);if(!d.suppressEvent){this.queueProperty(e,d.value)}},getConfig:function(){var d={},f=this.config,g,e;for(g in f){if(b.hasOwnProperty(f,g)){e=f[g];if(e&&e.event){d[g]=e.value}}}return d},getProperty:function(d){var e=this.config[d.toLowerCase()];if(e&&e.event){return e.value}else{return undefined}},resetProperty:function(d){d=d.toLowerCase();var e=this.config[d];if(e&&e.event){if(d in this.initialConfig){this.setProperty(d,this.initialConfig[d]);return true}}else{return false}},setProperty:function(e,g,d){var f;e=e.toLowerCase();if(this.queueInProgress&&!d){this.queueProperty(e,g);return true}else{f=this.config[e];if(f&&f.event){if(f.validator&&!f.validator(g)){return false}else{f.value=g;if(!d){this.fireEvent(e,g);this.configChangedEvent.fire([e,g])}return true}}else{return false}}},queueProperty:function(v,r){v=v.toLowerCase();var u=this.config[v],l=false,k,g,h,j,p,t,f,n,o,d,m,w,e;if(u&&u.event){if(!b.isUndefined(r)&&u.validator&&!u.validator(r)){return false}else{if(!b.isUndefined(r)){u.value=r}else{r=u.value}l=false;k=this.eventQueue.length;for(m=0;m<k;m++){g=this.eventQueue[m];if(g){h=g[0];j=g[1];if(h==v){this.eventQueue[m]=null;this.eventQueue.push([v,(!b.isUndefined(r)?r:j)]);l=true;break}}}if(!l&&!b.isUndefined(r)){this.eventQueue.push([v,r])}}if(u.supercedes){p=u.supercedes.length;for(w=0;w<p;w++){t=u.supercedes[w];f=this.eventQueue.length;for(e=0;e<f;e++){n=this.eventQueue[e];if(n){o=n[0];d=n[1];if(o==t.toLowerCase()){this.eventQueue.push([o,d]);this.eventQueue[e]=null;break}}}}}return true}else{return false}},refireEvent:function(d){d=d.toLowerCase();var e=this.config[d];if(e&&e.event&&!b.isUndefined(e.value)){if(this.queueInProgress){this.queueProperty(d)}else{this.fireEvent(d,e.value)}}},applyConfig:function(d,g){var f,e;if(g){e={};for(f in d){if(b.hasOwnProperty(d,f)){e[f.toLowerCase()]=d[f]}}this.initialConfig=e}for(f in d){if(b.hasOwnProperty(d,f)){this.queueProperty(f,d[f])}}},refresh:function(){var d;for(d in this.config){if(b.hasOwnProperty(this.config,d)){this.refireEvent(d)}}},fireQueue:function(){var e,h,d,g,f;this.queueInProgress=true;for(e=0;e<this.eventQueue.length;e++){h=this.eventQueue[e];if(h){d=h[0];g=h[1];f=this.config[d];f.value=g;this.eventQueue[e]=null;this.fireEvent(d,g)}}this.queueInProgress=false;this.eventQueue=[]},subscribeToConfigEvent:function(d,e,g,h){var f=this.config[d.toLowerCase()];if(f&&f.event){if(!a.alreadySubscribed(f.event,e,g)){f.event.subscribe(e,g,h)}return true}else{return false}},unsubscribeFromConfigEvent:function(d,e,g){var f=this.config[d.toLowerCase()];if(f&&f.event){return f.event.unsubscribe(e,g)}else{return false}},toString:function(){var d="Config";if(this.owner){d+=" ["+this.owner.toString()+"]"}return d},outputEventQueue:function(){var d="",g,e,f=this.eventQueue.length;for(e=0;e<f;e++){g=this.eventQueue[e];if(g){d+=g[0]+"="+g[1]+", "}}return d},destroy:function(){var e=this.config,d,f;for(d in e){if(b.hasOwnProperty(e,d)){f=e[d];f.event.unsubscribeAll();f.event=null}}this.configChangedEvent.unsubscribeAll();this.configChangedEvent=null;this.owner=null;this.config=null;this.initialConfig=null;this.eventQueue=null}};a.alreadySubscribed=function(e,h,j){var f=e.subscribers.length,d,g;if(f>0){g=f-1;do{d=e.subscribers[g];if(d&&d.obj==j&&d.fn==h){return true}}while(g--)}return false};YAHOO.lang.augmentProto(a,YAHOO.util.EventProvider)}());(function(){YAHOO.widget.Module=function(r,q){if(r){this.init(r,q)}else{}};var f=YAHOO.util.Dom,d=YAHOO.util.Config,n=YAHOO.util.Event,m=YAHOO.util.CustomEvent,g=YAHOO.widget.Module,i=YAHOO.env.ua,h,p,o,e,a={BEFORE_INIT:"beforeInit",INIT:"init",APPEND:"append",BEFORE_RENDER:"beforeRender",RENDER:"render",CHANGE_HEADER:"changeHeader",CHANGE_BODY:"changeBody",CHANGE_FOOTER:"changeFooter",CHANGE_CONTENT:"changeContent",DESTROY:"destroy",BEFORE_SHOW:"beforeShow",SHOW:"show",BEFORE_HIDE:"beforeHide",HIDE:"hide"},j={VISIBLE:{key:"visible",value:true,validator:YAHOO.lang.isBoolean},EFFECT:{key:"effect",suppressEvent:true,supercedes:["visible"]},MONITOR_RESIZE:{key:"monitorresize",value:true},APPEND_TO_DOCUMENT_BODY:{key:"appendtodocumentbody",value:false}};g.IMG_ROOT=null;g.IMG_ROOT_SSL=null;g.CSS_MODULE="yui-module";g.CSS_HEADER="hd";g.CSS_BODY="bd";g.CSS_FOOTER="ft";g.RESIZE_MONITOR_SECURE_URL="javascript:false;";g.RESIZE_MONITOR_BUFFER=1;g.textResizeEvent=new m("textResize");g.forceDocumentRedraw=function(){var q=document.documentElement;if(q){q.className+=" ";q.className=YAHOO.lang.trim(q.className)}};function l(){if(!h){h=document.createElement("div");h.innerHTML=('<div class="'+g.CSS_HEADER+'"></div><div class="'+g.CSS_BODY+'"></div><div class="'+g.CSS_FOOTER+'"></div>');p=h.firstChild;o=p.nextSibling;e=o.nextSibling}return h}function k(){if(!p){l()}return(p.cloneNode(false))}function b(){if(!o){l()}return(o.cloneNode(false))}function c(){if(!e){l()}return(e.cloneNode(false))}g.prototype={constructor:g,element:null,header:null,body:null,footer:null,id:null,imageRoot:g.IMG_ROOT,initEvents:function(){var q=m.LIST;this.beforeInitEvent=this.createEvent(a.BEFORE_INIT);this.beforeInitEvent.signature=q;this.initEvent=this.createEvent(a.INIT);this.initEvent.signature=q;this.appendEvent=this.createEvent(a.APPEND);this.appendEvent.signature=q;this.beforeRenderEvent=this.createEvent(a.BEFORE_RENDER);this.beforeRenderEvent.signature=q;this.renderEvent=this.createEvent(a.RENDER);this.renderEvent.signature=q;this.changeHeaderEvent=this.createEvent(a.CHANGE_HEADER);this.changeHeaderEvent.signature=q;this.changeBodyEvent=this.createEvent(a.CHANGE_BODY);this.changeBodyEvent.signature=q;this.changeFooterEvent=this.createEvent(a.CHANGE_FOOTER);this.changeFooterEvent.signature=q;this.changeContentEvent=this.createEvent(a.CHANGE_CONTENT);this.changeContentEvent.signature=q;this.destroyEvent=this.createEvent(a.DESTROY);this.destroyEvent.signature=q;this.beforeShowEvent=this.createEvent(a.BEFORE_SHOW);this.beforeShowEvent.signature=q;this.showEvent=this.createEvent(a.SHOW);this.showEvent.signature=q;this.beforeHideEvent=this.createEvent(a.BEFORE_HIDE);this.beforeHideEvent.signature=q;this.hideEvent=this.createEvent(a.HIDE);this.hideEvent.signature=q},platform:function(){var q=navigator.userAgent.toLowerCase();if(q.indexOf("windows")!=-1||q.indexOf("win32")!=-1){return"windows"}else{if(q.indexOf("macintosh")!=-1){return"mac"}else{return false}}}(),browser:function(){var q=navigator.userAgent.toLowerCase();if(q.indexOf("opera")!=-1){return"opera"}else{if(q.indexOf("msie 7")!=-1){return"ie7"}else{if(q.indexOf("msie")!=-1){return"ie"}else{if(q.indexOf("safari")!=-1){return"safari"}else{if(q.indexOf("gecko")!=-1){return"gecko"}else{return false}}}}}}(),isSecure:function(){if(window.location.href.toLowerCase().indexOf("https")===0){return true}else{return false}}(),initDefaultConfig:function(){this.cfg.addProperty(j.VISIBLE.key,{handler:this.configVisible,value:j.VISIBLE.value,validator:j.VISIBLE.validator});this.cfg.addProperty(j.EFFECT.key,{handler:this.configEffect,suppressEvent:j.EFFECT.suppressEvent,supercedes:j.EFFECT.supercedes});this.cfg.addProperty(j.MONITOR_RESIZE.key,{handler:this.configMonitorResize,value:j.MONITOR_RESIZE.value});this.cfg.addProperty(j.APPEND_TO_DOCUMENT_BODY.key,{value:j.APPEND_TO_DOCUMENT_BODY.value})},init:function(v,u){var s,w;this.initEvents();this.beforeInitEvent.fire(g);this.cfg=new d(this);if(this.isSecure){this.imageRoot=g.IMG_ROOT_SSL}if(typeof v=="string"){s=v;v=document.getElementById(v);if(!v){v=(l()).cloneNode(false);v.id=s}}this.id=f.generateId(v);this.element=v;w=this.element.firstChild;if(w){var r=false,q=false,t=false;do{if(1==w.nodeType){if(!r&&f.hasClass(w,g.CSS_HEADER)){this.header=w;r=true}else{if(!q&&f.hasClass(w,g.CSS_BODY)){this.body=w;q=true}else{if(!t&&f.hasClass(w,g.CSS_FOOTER)){this.footer=w;t=true}}}}}while((w=w.nextSibling))}this.initDefaultConfig();f.addClass(this.element,g.CSS_MODULE);if(u){this.cfg.applyConfig(u,true)}if(!d.alreadySubscribed(this.renderEvent,this.cfg.fireQueue,this.cfg)){this.renderEvent.subscribe(this.cfg.fireQueue,this.cfg,true)}this.initEvent.fire(g)},initResizeMonitor:function(){var r=(i.gecko&&this.platform=="windows");if(r){var q=this;setTimeout(function(){q._initResizeMonitor()},0)}else{this._initResizeMonitor()}},_initResizeMonitor:function(){var q,s,u;function w(){g.textResizeEvent.fire()}if(!i.opera){s=f.get("_yuiResizeMonitor");var v=this._supportsCWResize();if(!s){s=document.createElement("iframe");if(this.isSecure&&g.RESIZE_MONITOR_SECURE_URL&&i.ie){s.src=g.RESIZE_MONITOR_SECURE_URL}if(!v){u=["<html><head><script ",'type="text/javascript">',"window.onresize=function(){window.parent.","YAHOO.widget.Module.textResizeEvent.","fire();};<","/script></head>","<body></body></html>"].join("");s.src="data:text/html;charset=utf-8,"+encodeURIComponent(u)}s.id="_yuiResizeMonitor";s.title="Text Resize Monitor";s.tabIndex=-1;s.setAttribute("role","presentation");s.style.position="absolute";s.style.visibility="hidden";var r=document.body,t=r.firstChild;if(t){r.insertBefore(s,t)}else{r.appendChild(s)}s.style.backgroundColor="transparent";s.style.borderWidth="0";s.style.width="2em";s.style.height="2em";s.style.left="0";s.style.top=(-1*(s.offsetHeight+g.RESIZE_MONITOR_BUFFER))+"px";s.style.visibility="visible";if(i.webkit){q=s.contentWindow.document;q.open();q.close()}}if(s&&s.contentWindow){g.textResizeEvent.subscribe(this.onDomResize,this,true);if(!g.textResizeInitialized){if(v){if(!n.on(s.contentWindow,"resize",w)){n.on(s,"resize",w)}}g.textResizeInitialized=true}this.resizeMonitor=s}}},_supportsCWResize:function(){var q=true;if(i.gecko&&i.gecko<=1.8){q=false}return q},onDomResize:function(s,r){var q=-1*(this.resizeMonitor.offsetHeight+g.RESIZE_MONITOR_BUFFER);this.resizeMonitor.style.top=q+"px";this.resizeMonitor.style.left="0"},setHeader:function(r){var q=this.header||(this.header=k());if(r.nodeName){q.innerHTML="";q.appendChild(r)}else{q.innerHTML=r}if(this._rendered){this._renderHeader()}this.changeHeaderEvent.fire(r);this.changeContentEvent.fire()},appendToHeader:function(r){var q=this.header||(this.header=k());q.appendChild(r);this.changeHeaderEvent.fire(r);this.changeContentEvent.fire()},setBody:function(r){var q=this.body||(this.body=b());if(r.nodeName){q.innerHTML="";q.appendChild(r)}else{q.innerHTML=r}if(this._rendered){this._renderBody()}this.changeBodyEvent.fire(r);this.changeContentEvent.fire()},appendToBody:function(r){var q=this.body||(this.body=b());q.appendChild(r);this.changeBodyEvent.fire(r);this.changeContentEvent.fire()},setFooter:function(r){var q=this.footer||(this.footer=c());if(r.nodeName){q.innerHTML="";q.appendChild(r)}else{q.innerHTML=r}if(this._rendered){this._renderFooter()}this.changeFooterEvent.fire(r);this.changeContentEvent.fire()},appendToFooter:function(r){var q=this.footer||(this.footer=c());q.appendChild(r);this.changeFooterEvent.fire(r);this.changeContentEvent.fire()},render:function(s,q){var t=this;function r(u){if(typeof u=="string"){u=document.getElementById(u)}if(u){t._addToParent(u,t.element);t.appendEvent.fire()}}this.beforeRenderEvent.fire();if(!q){q=this.element}if(s){r(s)}else{if(!f.inDocument(this.element)){return false}}this._renderHeader(q);this._renderBody(q);this._renderFooter(q);this._rendered=true;this.renderEvent.fire();return true},_renderHeader:function(q){q=q||this.element;if(this.header&&!f.inDocument(this.header)){var r=q.firstChild;if(r){q.insertBefore(this.header,r)}else{q.appendChild(this.header)}}},_renderBody:function(q){q=q||this.element;if(this.body&&!f.inDocument(this.body)){if(this.footer&&f.isAncestor(q,this.footer)){q.insertBefore(this.body,this.footer)}else{q.appendChild(this.body)}}},_renderFooter:function(q){q=q||this.element;if(this.footer&&!f.inDocument(this.footer)){q.appendChild(this.footer)}},destroy:function(q){var r,s=!(q);if(this.element){n.purgeElement(this.element,s);r=this.element.parentNode}if(r){r.removeChild(this.element)}this.element=null;this.header=null;this.body=null;this.footer=null;g.textResizeEvent.unsubscribe(this.onDomResize,this);this.cfg.destroy();this.cfg=null;this.destroyEvent.fire()},show:function(){this.cfg.setProperty("visible",true)},hide:function(){this.cfg.setProperty("visible",false)},configVisible:function(r,q,s){var t=q[0];if(t){if(this.beforeShowEvent.fire()){f.setStyle(this.element,"display","block");this.showEvent.fire()}}else{if(this.beforeHideEvent.fire()){f.setStyle(this.element,"display","none");this.hideEvent.fire()}}},configEffect:function(r,q,s){this._cachedEffects=(this.cacheEffects)?this._createEffects(q[0]):null},cacheEffects:true,_createEffects:function(t){var q=null,u,r,s;if(t){if(t instanceof Array){q=[];u=t.length;for(r=0;r<u;r++){s=t[r];if(s.effect){q[q.length]=s.effect(this,s.duration)}}}else{if(t.effect){q=[t.effect(this,t.duration)]}}}return q},configMonitorResize:function(s,r,t){var q=r[0];if(q){this.initResizeMonitor()}else{g.textResizeEvent.unsubscribe(this.onDomResize,this,true);this.resizeMonitor=null}},_addToParent:function(q,r){if(!this.cfg.getProperty("appendtodocumentbody")&&q===document.body&&q.firstChild){q.insertBefore(r,q.firstChild)}else{q.appendChild(r)}},toString:function(){return"Module "+this.id}};YAHOO.lang.augmentProto(g,YAHOO.util.EventProvider)}());(function(){YAHOO.widget.Overlay=function(p,o){YAHOO.widget.Overlay.superclass.constructor.call(this,p,o)};var i=YAHOO.lang,m=YAHOO.util.CustomEvent,g=YAHOO.widget.Module,n=YAHOO.util.Event,f=YAHOO.util.Dom,d=YAHOO.util.Config,k=YAHOO.env.ua,b=YAHOO.widget.Overlay,h="subscribe",e="unsubscribe",c="contained",j,a={BEFORE_MOVE:"beforeMove",MOVE:"move"},l={X:{key:"x",validator:i.isNumber,suppressEvent:true,supercedes:["iframe"]},Y:{key:"y",validator:i.isNumber,suppressEvent:true,supercedes:["iframe"]},XY:{key:"xy",suppressEvent:true,supercedes:["iframe"]},CONTEXT:{key:"context",suppressEvent:true,supercedes:["iframe"]},FIXED_CENTER:{key:"fixedcenter",value:false,supercedes:["iframe","visible"]},WIDTH:{key:"width",suppressEvent:true,supercedes:["context","fixedcenter","iframe"]},HEIGHT:{key:"height",suppressEvent:true,supercedes:["context","fixedcenter","iframe"]},AUTO_FILL_HEIGHT:{key:"autofillheight",supercedes:["height"],value:"body"},ZINDEX:{key:"zindex",value:null},CONSTRAIN_TO_VIEWPORT:{key:"constraintoviewport",value:false,validator:i.isBoolean,supercedes:["iframe","x","y","xy"]},IFRAME:{key:"iframe",value:(k.ie==6?true:false),validator:i.isBoolean,supercedes:["zindex"]},PREVENT_CONTEXT_OVERLAP:{key:"preventcontextoverlap",value:false,validator:i.isBoolean,supercedes:["constraintoviewport"]}};b.IFRAME_SRC="javascript:false;";b.IFRAME_OFFSET=3;b.VIEWPORT_OFFSET=10;b.TOP_LEFT="tl";b.TOP_RIGHT="tr";b.BOTTOM_LEFT="bl";b.BOTTOM_RIGHT="br";b.PREVENT_OVERLAP_X={tltr:true,blbr:true,brbl:true,trtl:true};b.PREVENT_OVERLAP_Y={trbr:true,tlbl:true,bltl:true,brtr:true};b.CSS_OVERLAY="yui-overlay";b.CSS_HIDDEN="yui-overlay-hidden";b.CSS_IFRAME="yui-overlay-iframe";b.STD_MOD_RE=/^\s*?(body|footer|header)\s*?$/i;b.windowScrollEvent=new m("windowScroll");b.windowResizeEvent=new m("windowResize");b.windowScrollHandler=function(p){var o=n.getTarget(p);if(!o||o===window||o===window.document){if(k.ie){if(!window.scrollEnd){window.scrollEnd=-1}clearTimeout(window.scrollEnd);window.scrollEnd=setTimeout(function(){b.windowScrollEvent.fire()},1)}else{b.windowScrollEvent.fire()}}};b.windowResizeHandler=function(o){if(k.ie){if(!window.resizeEnd){window.resizeEnd=-1}clearTimeout(window.resizeEnd);window.resizeEnd=setTimeout(function(){b.windowResizeEvent.fire()},100)}else{b.windowResizeEvent.fire()}};b._initialized=null;if(b._initialized===null){n.on(window,"scroll",b.windowScrollHandler);n.on(window,"resize",b.windowResizeHandler);b._initialized=true}b._TRIGGER_MAP={windowScroll:b.windowScrollEvent,windowResize:b.windowResizeEvent,textResize:g.textResizeEvent};YAHOO.extend(b,g,{CONTEXT_TRIGGERS:[],init:function(p,o){b.superclass.init.call(this,p);this.beforeInitEvent.fire(b);f.addClass(this.element,b.CSS_OVERLAY);if(o){this.cfg.applyConfig(o,true)}if(this.platform=="mac"&&k.gecko){if(!d.alreadySubscribed(this.showEvent,this.showMacGeckoScrollbars,this)){this.showEvent.subscribe(this.showMacGeckoScrollbars,this,true)}if(!d.alreadySubscribed(this.hideEvent,this.hideMacGeckoScrollbars,this)){this.hideEvent.subscribe(this.hideMacGeckoScrollbars,this,true)}}this.initEvent.fire(b)},initEvents:function(){b.superclass.initEvents.call(this);var o=m.LIST;this.beforeMoveEvent=this.createEvent(a.BEFORE_MOVE);this.beforeMoveEvent.signature=o;this.moveEvent=this.createEvent(a.MOVE);this.moveEvent.signature=o},initDefaultConfig:function(){b.superclass.initDefaultConfig.call(this);var o=this.cfg;o.addProperty(l.X.key,{handler:this.configX,validator:l.X.validator,suppressEvent:l.X.suppressEvent,supercedes:l.X.supercedes});o.addProperty(l.Y.key,{handler:this.configY,validator:l.Y.validator,suppressEvent:l.Y.suppressEvent,supercedes:l.Y.supercedes});o.addProperty(l.XY.key,{handler:this.configXY,suppressEvent:l.XY.suppressEvent,supercedes:l.XY.supercedes});o.addProperty(l.CONTEXT.key,{handler:this.configContext,suppressEvent:l.CONTEXT.suppressEvent,supercedes:l.CONTEXT.supercedes});o.addProperty(l.FIXED_CENTER.key,{handler:this.configFixedCenter,value:l.FIXED_CENTER.value,validator:l.FIXED_CENTER.validator,supercedes:l.FIXED_CENTER.supercedes});o.addProperty(l.WIDTH.key,{handler:this.configWidth,suppressEvent:l.WIDTH.suppressEvent,supercedes:l.WIDTH.supercedes});o.addProperty(l.HEIGHT.key,{handler:this.configHeight,suppressEvent:l.HEIGHT.suppressEvent,supercedes:l.HEIGHT.supercedes});o.addProperty(l.AUTO_FILL_HEIGHT.key,{handler:this.configAutoFillHeight,value:l.AUTO_FILL_HEIGHT.value,validator:this._validateAutoFill,supercedes:l.AUTO_FILL_HEIGHT.supercedes});o.addProperty(l.ZINDEX.key,{handler:this.configzIndex,value:l.ZINDEX.value});o.addProperty(l.CONSTRAIN_TO_VIEWPORT.key,{handler:this.configConstrainToViewport,value:l.CONSTRAIN_TO_VIEWPORT.value,validator:l.CONSTRAIN_TO_VIEWPORT.validator,supercedes:l.CONSTRAIN_TO_VIEWPORT.supercedes});o.addProperty(l.IFRAME.key,{handler:this.configIframe,value:l.IFRAME.value,validator:l.IFRAME.validator,supercedes:l.IFRAME.supercedes});o.addProperty(l.PREVENT_CONTEXT_OVERLAP.key,{value:l.PREVENT_CONTEXT_OVERLAP.value,validator:l.PREVENT_CONTEXT_OVERLAP.validator,supercedes:l.PREVENT_CONTEXT_OVERLAP.supercedes})},moveTo:function(o,p){this.cfg.setProperty("xy",[o,p])},hideMacGeckoScrollbars:function(){f.replaceClass(this.element,"show-scrollbars","hide-scrollbars")},showMacGeckoScrollbars:function(){f.replaceClass(this.element,"hide-scrollbars","show-scrollbars")},_setDomVisibility:function(o){f.setStyle(this.element,"visibility",(o)?"visible":"hidden");var p=b.CSS_HIDDEN;if(o){f.removeClass(this.element,p)}else{f.addClass(this.element,p)}},configVisible:function(x,w,t){var p=w[0],B=f.getStyle(this.element,"visibility"),o=this._cachedEffects||this._createEffects(this.cfg.getProperty("effect")),A=(this.platform=="mac"&&k.gecko),y=d.alreadySubscribed,q,v,s,r,u,z;if(B=="inherit"){v=this.element.parentNode;while(v.nodeType!=9&&v.nodeType!=11){B=f.getStyle(v,"visibility");if(B!="inherit"){break}v=v.parentNode}if(B=="inherit"){B="visible"}}if(p){if(A){this.showMacGeckoScrollbars()}if(o){if(p){if(B!="visible"||B===""||this._fadingOut){if(this.beforeShowEvent.fire()){z=o.length;for(s=0;s<z;s++){q=o[s];if(s===0&&!y(q.animateInCompleteEvent,this.showEvent.fire,this.showEvent)){q.animateInCompleteEvent.subscribe(this.showEvent.fire,this.showEvent,true)}q.animateIn()}}}}}else{if(B!="visible"||B===""){if(this.beforeShowEvent.fire()){this._setDomVisibility(true);this.cfg.refireEvent("iframe");this.showEvent.fire()}}else{this._setDomVisibility(true)}}}else{if(A){this.hideMacGeckoScrollbars()}if(o){if(B=="visible"||this._fadingIn){if(this.beforeHideEvent.fire()){z=o.length;for(r=0;r<z;r++){u=o[r];if(r===0&&!y(u.animateOutCompleteEvent,this.hideEvent.fire,this.hideEvent)){u.animateOutCompleteEvent.subscribe(this.hideEvent.fire,this.hideEvent,true)}u.animateOut()}}}else{if(B===""){this._setDomVisibility(false)}}}else{if(B=="visible"||B===""){if(this.beforeHideEvent.fire()){this._setDomVisibility(false);this.hideEvent.fire()}}else{this._setDomVisibility(false)}}}},doCenterOnDOMEvent:function(){var o=this.cfg,p=o.getProperty("fixedcenter");if(o.getProperty("visible")){if(p&&(p!==c||this.fitsInViewport())){this.center()}}},fitsInViewport:function(){var s=b.VIEWPORT_OFFSET,q=this.element,t=q.offsetWidth,r=q.offsetHeight,o=f.getViewportWidth(),p=f.getViewportHeight();return((t+s<o)&&(r+s<p))},configFixedCenter:function(s,q,t){var u=q[0],p=d.alreadySubscribed,r=b.windowResizeEvent,o=b.windowScrollEvent;if(u){this.center();if(!p(this.beforeShowEvent,this.center)){this.beforeShowEvent.subscribe(this.center)}if(!p(r,this.doCenterOnDOMEvent,this)){r.subscribe(this.doCenterOnDOMEvent,this,true)}if(!p(o,this.doCenterOnDOMEvent,this)){o.subscribe(this.doCenterOnDOMEvent,this,true)}}else{this.beforeShowEvent.unsubscribe(this.center);r.unsubscribe(this.doCenterOnDOMEvent,this);o.unsubscribe(this.doCenterOnDOMEvent,this)}},configHeight:function(r,p,s){var o=p[0],q=this.element;f.setStyle(q,"height",o);this.cfg.refireEvent("iframe")},configAutoFillHeight:function(t,s,p){var v=s[0],q=this.cfg,u="autofillheight",w="height",r=q.getProperty(u),o=this._autoFillOnHeightChange;q.unsubscribeFromConfigEvent(w,o);g.textResizeEvent.unsubscribe(o);this.changeContentEvent.unsubscribe(o);if(r&&v!==r&&this[r]){f.setStyle(this[r],w,"")}if(v){v=i.trim(v.toLowerCase());q.subscribeToConfigEvent(w,o,this[v],this);g.textResizeEvent.subscribe(o,this[v],this);this.changeContentEvent.subscribe(o,this[v],this);q.setProperty(u,v,true)}},configWidth:function(r,o,s){var q=o[0],p=this.element;f.setStyle(p,"width",q);this.cfg.refireEvent("iframe")},configzIndex:function(q,o,r){var s=o[0],p=this.element;if(!s){s=f.getStyle(p,"zIndex");if(!s||isNaN(s)){s=0}}if(this.iframe||this.cfg.getProperty("iframe")===true){if(s<=0){s=1}}f.setStyle(p,"zIndex",s);this.cfg.setProperty("zIndex",s,true);if(this.iframe){this.stackIframe()}},configXY:function(q,p,r){var t=p[0],o=t[0],s=t[1];this.cfg.setProperty("x",o);this.cfg.setProperty("y",s);this.beforeMoveEvent.fire([o,s]);o=this.cfg.getProperty("x");s=this.cfg.getProperty("y");this.cfg.refireEvent("iframe");this.moveEvent.fire([o,s])},configX:function(q,p,r){var o=p[0],s=this.cfg.getProperty("y");this.cfg.setProperty("x",o,true);this.cfg.setProperty("y",s,true);this.beforeMoveEvent.fire([o,s]);o=this.cfg.getProperty("x");s=this.cfg.getProperty("y");f.setX(this.element,o,true);this.cfg.setProperty("xy",[o,s],true);this.cfg.refireEvent("iframe");this.moveEvent.fire([o,s])},configY:function(q,p,r){var o=this.cfg.getProperty("x"),s=p[0];this.cfg.setProperty("x",o,true);this.cfg.setProperty("y",s,true);this.beforeMoveEvent.fire([o,s]);o=this.cfg.getProperty("x");s=this.cfg.getProperty("y");f.setY(this.element,s,true);this.cfg.setProperty("xy",[o,s],true);this.cfg.refireEvent("iframe");this.moveEvent.fire([o,s])},showIframe:function(){var p=this.iframe,o;if(p){o=this.element.parentNode;if(o!=p.parentNode){this._addToParent(o,p)}p.style.display="block"}},hideIframe:function(){if(this.iframe){this.iframe.style.display="none"}},syncIframe:function(){var o=this.iframe,q=this.element,s=b.IFRAME_OFFSET,p=(s*2),r;if(o){o.style.width=(q.offsetWidth+p+"px");o.style.height=(q.offsetHeight+p+"px");r=this.cfg.getProperty("xy");if(!i.isArray(r)||(isNaN(r[0])||isNaN(r[1]))){this.syncPosition();r=this.cfg.getProperty("xy")}f.setXY(o,[(r[0]-s),(r[1]-s)])}},stackIframe:function(){if(this.iframe){var o=f.getStyle(this.element,"zIndex");if(!YAHOO.lang.isUndefined(o)&&!isNaN(o)){f.setStyle(this.iframe,"zIndex",(o-1))}}},configIframe:function(r,q,s){var o=q[0];function t(){var v=this.iframe,w=this.element,x;if(!v){if(!j){j=document.createElement("iframe");if(this.isSecure){j.src=b.IFRAME_SRC}if(k.ie){j.style.filter="alpha(opacity=0)";j.frameBorder=0}else{j.style.opacity="0"}j.style.position="absolute";j.style.border="none";j.style.margin="0";j.style.padding="0";j.style.display="none";j.tabIndex=-1;j.className=b.CSS_IFRAME}v=j.cloneNode(false);v.id=this.id+"_f";x=w.parentNode;var u=x||document.body;this._addToParent(u,v);this.iframe=v}this.showIframe();this.syncIframe();this.stackIframe();if(!this._hasIframeEventListeners){this.showEvent.subscribe(this.showIframe);this.hideEvent.subscribe(this.hideIframe);this.changeContentEvent.subscribe(this.syncIframe);this._hasIframeEventListeners=true}}function p(){t.call(this);this.beforeShowEvent.unsubscribe(p);this._iframeDeferred=false}if(o){if(this.cfg.getProperty("visible")){t.call(this)}else{if(!this._iframeDeferred){this.beforeShowEvent.subscribe(p);this._iframeDeferred=true}}}else{this.hideIframe();if(this._hasIframeEventListeners){this.showEvent.unsubscribe(this.showIframe);this.hideEvent.unsubscribe(this.hideIframe);this.changeContentEvent.unsubscribe(this.syncIframe);this._hasIframeEventListeners=false}}},_primeXYFromDOM:function(){if(YAHOO.lang.isUndefined(this.cfg.getProperty("xy"))){this.syncPosition();this.cfg.refireEvent("xy");this.beforeShowEvent.unsubscribe(this._primeXYFromDOM)}},configConstrainToViewport:function(p,o,q){var r=o[0];if(r){if(!d.alreadySubscribed(this.beforeMoveEvent,this.enforceConstraints,this)){this.beforeMoveEvent.subscribe(this.enforceConstraints,this,true)}if(!d.alreadySubscribed(this.beforeShowEvent,this._primeXYFromDOM)){this.beforeShowEvent.subscribe(this._primeXYFromDOM)}}else{this.beforeShowEvent.unsubscribe(this._primeXYFromDOM);this.beforeMoveEvent.unsubscribe(this.enforceConstraints,this)}},configContext:function(u,t,q){var x=t[0],r,o,v,s,p,w=this.CONTEXT_TRIGGERS;if(x){r=x[0];o=x[1];v=x[2];s=x[3];p=x[4];if(w&&w.length>0){s=(s||[]).concat(w)}if(r){if(typeof r=="string"){this.cfg.setProperty("context",[document.getElementById(r),o,v,s,p],true)}if(o&&v){this.align(o,v,p)}if(this._contextTriggers){this._processTriggers(this._contextTriggers,e,this._alignOnTrigger)}if(s){this._processTriggers(s,h,this._alignOnTrigger);this._contextTriggers=s}}}},_alignOnTrigger:function(p,o){this.align()},_findTriggerCE:function(o){var p=null;if(o instanceof m){p=o}else{if(b._TRIGGER_MAP[o]){p=b._TRIGGER_MAP[o]}}return p},_processTriggers:function(s,v,r){var q,u;for(var p=0,o=s.length;p<o;++p){q=s[p];u=this._findTriggerCE(q);if(u){u[v](r,this,true)}else{this[v](q,r)}}},align:function(p,w,s){var v=this.cfg.getProperty("context"),t=this,o,q,u;function r(z,A){var y=null,x=null;switch(p){case b.TOP_LEFT:y=A;x=z;break;case b.TOP_RIGHT:y=A-q.offsetWidth;x=z;break;case b.BOTTOM_LEFT:y=A;x=z-q.offsetHeight;break;case b.BOTTOM_RIGHT:y=A-q.offsetWidth;x=z-q.offsetHeight;break}if(y!==null&&x!==null){if(s){y+=s[0];x+=s[1]}t.moveTo(y,x)}}if(v){o=v[0];q=this.element;t=this;if(!p){p=v[1]}if(!w){w=v[2]}if(!s&&v[4]){s=v[4]}if(q&&o){u=f.getRegion(o);switch(w){case b.TOP_LEFT:r(u.top,u.left);break;case b.TOP_RIGHT:r(u.top,u.right);break;case b.BOTTOM_LEFT:r(u.bottom,u.left);break;case b.BOTTOM_RIGHT:r(u.bottom,u.right);break}}}},enforceConstraints:function(p,o,q){var s=o[0];var r=this.getConstrainedXY(s[0],s[1]);this.cfg.setProperty("x",r[0],true);this.cfg.setProperty("y",r[1],true);this.cfg.setProperty("xy",r,true)},_getConstrainedPos:function(y,p){var t=this.element,r=b.VIEWPORT_OFFSET,A=(y=="x"),z=(A)?t.offsetWidth:t.offsetHeight,s=(A)?f.getViewportWidth():f.getViewportHeight(),D=(A)?f.getDocumentScrollLeft():f.getDocumentScrollTop(),C=(A)?b.PREVENT_OVERLAP_X:b.PREVENT_OVERLAP_Y,o=this.cfg.getProperty("context"),u=(z+r<s),w=this.cfg.getProperty("preventcontextoverlap")&&o&&C[(o[1]+o[2])],v=D+r,B=D+s-z-r,q=p;if(p<v||p>B){if(w){q=this._preventOverlap(y,o[0],z,s,D)}else{if(u){if(p<v){q=v}else{if(p>B){q=B}}}else{q=v}}}return q},_preventOverlap:function(y,w,z,u,C){var A=(y=="x"),t=b.VIEWPORT_OFFSET,s=this,q=((A)?f.getX(w):f.getY(w))-C,o=(A)?w.offsetWidth:w.offsetHeight,p=q-t,r=(u-(q+o))-t,D=false,v=function(){var x;if((s.cfg.getProperty(y)-C)>q){x=(q-z)}else{x=(q+o)}s.cfg.setProperty(y,(x+C),true);return x},B=function(){var E=((s.cfg.getProperty(y)-C)>q)?r:p,x;if(z>E){if(D){v()}else{v();D=true;x=B()}}return x};B();return this.cfg.getProperty(y)},getConstrainedX:function(o){return this._getConstrainedPos("x",o)},getConstrainedY:function(o){return this._getConstrainedPos("y",o)},getConstrainedXY:function(o,p){return[this.getConstrainedX(o),this.getConstrainedY(p)]},center:function(){var r=b.VIEWPORT_OFFSET,s=this.element.offsetWidth,q=this.element.offsetHeight,p=f.getViewportWidth(),t=f.getViewportHeight(),o,u;if(s<p){o=(p/2)-(s/2)+f.getDocumentScrollLeft()}else{o=r+f.getDocumentScrollLeft()}if(q<t){u=(t/2)-(q/2)+f.getDocumentScrollTop()}else{u=r+f.getDocumentScrollTop()}this.cfg.setProperty("xy",[parseInt(o,10),parseInt(u,10)]);this.cfg.refireEvent("iframe");if(k.webkit){this.forceContainerRedraw()}},syncPosition:function(){var o=f.getXY(this.element);this.cfg.setProperty("x",o[0],true);this.cfg.setProperty("y",o[1],true);this.cfg.setProperty("xy",o,true)},onDomResize:function(q,p){var o=this;b.superclass.onDomResize.call(this,q,p);setTimeout(function(){o.syncPosition();o.cfg.refireEvent("iframe");o.cfg.refireEvent("context")},0)},_getComputedHeight:(function(){if(document.defaultView&&document.defaultView.getComputedStyle){return function(p){var o=null;if(p.ownerDocument&&p.ownerDocument.defaultView){var q=p.ownerDocument.defaultView.getComputedStyle(p,"");if(q){o=parseInt(q.height,10)}}return(i.isNumber(o))?o:null}}else{return function(p){var o=null;if(p.style.pixelHeight){o=p.style.pixelHeight}return(i.isNumber(o))?o:null}}})(),_validateAutoFillHeight:function(o){return(!o)||(i.isString(o)&&b.STD_MOD_RE.test(o))},_autoFillOnHeightChange:function(r,p,q){var o=this.cfg.getProperty("height");if((o&&o!=="auto")||(o===0)){this.fillHeight(q)}},_getPreciseHeight:function(p){var o=p.offsetHeight;if(p.getBoundingClientRect){var q=p.getBoundingClientRect();o=q.bottom-q.top}return o},fillHeight:function(r){if(r){var p=this.innerElement||this.element,o=[this.header,this.body,this.footer],v,w=0,x=0,t=0,q=false;for(var u=0,s=o.length;u<s;u++){v=o[u];if(v){if(r!==v){x+=this._getPreciseHeight(v)}else{q=true}}}if(q){if(k.ie||k.opera){f.setStyle(r,"height",0+"px")}w=this._getComputedHeight(p);if(w===null){f.addClass(p,"yui-override-padding");w=p.clientHeight;f.removeClass(p,"yui-override-padding")}t=Math.max(w-x,0);f.setStyle(r,"height",t+"px");if(r.offsetHeight!=t){t=Math.max(t-(r.offsetHeight-t),0)}f.setStyle(r,"height",t+"px")}}},bringToTop:function(){var s=[],r=this.element;function v(z,y){var B=f.getStyle(z,"zIndex"),A=f.getStyle(y,"zIndex"),x=(!B||isNaN(B))?0:parseInt(B,10),w=(!A||isNaN(A))?0:parseInt(A,10);if(x>w){return -1}else{if(x<w){return 1}else{return 0}}}function q(y){var x=f.hasClass(y,b.CSS_OVERLAY),w=YAHOO.widget.Panel;if(x&&!f.isAncestor(r,y)){if(w&&f.hasClass(y,w.CSS_PANEL)){s[s.length]=y.parentNode}else{s[s.length]=y}}}f.getElementsBy(q,"div",document.body);s.sort(v);var o=s[0],u;if(o){u=f.getStyle(o,"zIndex");if(!isNaN(u)){var t=false;if(o!=r){t=true}else{if(s.length>1){var p=f.getStyle(s[1],"zIndex");if(!isNaN(p)&&(u==p)){t=true}}}if(t){this.cfg.setProperty("zindex",(parseInt(u,10)+2))}}}},destroy:function(o){if(this.iframe){this.iframe.parentNode.removeChild(this.iframe)}this.iframe=null;b.windowResizeEvent.unsubscribe(this.doCenterOnDOMEvent,this);b.windowScrollEvent.unsubscribe(this.doCenterOnDOMEvent,this);g.textResizeEvent.unsubscribe(this._autoFillOnHeightChange);if(this._contextTriggers){this._processTriggers(this._contextTriggers,e,this._alignOnTrigger)}b.superclass.destroy.call(this,o)},forceContainerRedraw:function(){var o=this;f.addClass(o.element,"yui-force-redraw");setTimeout(function(){f.removeClass(o.element,"yui-force-redraw")},0)},toString:function(){return"Overlay "+this.id}})}());(function(){YAHOO.widget.OverlayManager=function(g){this.init(g)};var d=YAHOO.widget.Overlay,c=YAHOO.util.Event,e=YAHOO.util.Dom,b=YAHOO.util.Config,f=YAHOO.util.CustomEvent,a=YAHOO.widget.OverlayManager;a.CSS_FOCUSED="focused";a.prototype={constructor:a,overlays:null,initDefaultConfig:function(){this.cfg.addProperty("overlays",{suppressEvent:true});this.cfg.addProperty("focusevent",{value:"mousedown"})},init:function(i){this.cfg=new b(this);this.initDefaultConfig();if(i){this.cfg.applyConfig(i,true)}this.cfg.fireQueue();var h=null;this.getActive=function(){return h};this.focus=function(j){var k=this.find(j);if(k){k.focus()}};this.remove=function(k){var m=this.find(k),j;if(m){if(h==m){h=null}var l=(m.element===null&&m.cfg===null)?true:false;if(!l){j=e.getStyle(m.element,"zIndex");m.cfg.setProperty("zIndex",-1000,true)}this.overlays.sort(this.compareZIndexDesc);this.overlays=this.overlays.slice(0,(this.overlays.length-1));m.hideEvent.unsubscribe(m.blur);m.destroyEvent.unsubscribe(this._onOverlayDestroy,m);m.focusEvent.unsubscribe(this._onOverlayFocusHandler,m);m.blurEvent.unsubscribe(this._onOverlayBlurHandler,m);if(!l){c.removeListener(m.element,this.cfg.getProperty("focusevent"),this._onOverlayElementFocus);m.cfg.setProperty("zIndex",j,true);m.cfg.setProperty("manager",null)}if(m.focusEvent._managed){m.focusEvent=null}if(m.blurEvent._managed){m.blurEvent=null}if(m.focus._managed){m.focus=null}if(m.blur._managed){m.blur=null}}};this.blurAll=function(){var k=this.overlays.length,j;if(k>0){j=k-1;do{this.overlays[j].blur()}while(j--)}};this._manageBlur=function(j){var k=false;if(h==j){e.removeClass(h.element,a.CSS_FOCUSED);h=null;k=true}return k};this._manageFocus=function(j){var k=false;if(h!=j){if(h){h.blur()}h=j;this.bringToTop(h);e.addClass(h.element,a.CSS_FOCUSED);k=true}return k};var g=this.cfg.getProperty("overlays");if(!this.overlays){this.overlays=[]}if(g){this.register(g);this.overlays.sort(this.compareZIndexDesc)}},_onOverlayElementFocus:function(i){var g=c.getTarget(i),h=this.close;if(h&&(g==h||e.isAncestor(h,g))){this.blur()}else{this.focus()}},_onOverlayDestroy:function(h,g,i){this.remove(i)},_onOverlayFocusHandler:function(h,g,i){this._manageFocus(i)},_onOverlayBlurHandler:function(h,g,i){this._manageBlur(i)},_bindFocus:function(g){var h=this;if(!g.focusEvent){g.focusEvent=g.createEvent("focus");g.focusEvent.signature=f.LIST;g.focusEvent._managed=true}else{g.focusEvent.subscribe(h._onOverlayFocusHandler,g,h)}if(!g.focus){c.on(g.element,h.cfg.getProperty("focusevent"),h._onOverlayElementFocus,null,g);g.focus=function(){if(h._manageFocus(this)){if(this.cfg.getProperty("visible")&&this.focusFirst){this.focusFirst()}this.focusEvent.fire()}};g.focus._managed=true}},_bindBlur:function(g){var h=this;if(!g.blurEvent){g.blurEvent=g.createEvent("blur");g.blurEvent.signature=f.LIST;g.focusEvent._managed=true}else{g.blurEvent.subscribe(h._onOverlayBlurHandler,g,h)}if(!g.blur){g.blur=function(){if(h._manageBlur(this)){this.blurEvent.fire()}};g.blur._managed=true}g.hideEvent.subscribe(g.blur)},_bindDestroy:function(g){var h=this;g.destroyEvent.subscribe(h._onOverlayDestroy,g,h)},_syncZIndex:function(g){var h=e.getStyle(g.element,"zIndex");if(!isNaN(h)){g.cfg.setProperty("zIndex",parseInt(h,10))}else{g.cfg.setProperty("zIndex",0)}},register:function(g){var k=false,h,j;if(g instanceof d){g.cfg.addProperty("manager",{value:this});this._bindFocus(g);this._bindBlur(g);this._bindDestroy(g);this._syncZIndex(g);this.overlays.push(g);this.bringToTop(g);k=true}else{if(g instanceof Array){for(h=0,j=g.length;h<j;h++){k=this.register(g[h])||k}}}return k},bringToTop:function(m){var i=this.find(m),l,g,j;if(i){j=this.overlays;j.sort(this.compareZIndexDesc);g=j[0];if(g){l=e.getStyle(g.element,"zIndex");if(!isNaN(l)){var k=false;if(g!==i){k=true}else{if(j.length>1){var h=e.getStyle(j[1].element,"zIndex");if(!isNaN(h)&&(l==h)){k=true}}}if(k){i.cfg.setProperty("zindex",(parseInt(l,10)+2))}}j.sort(this.compareZIndexDesc)}}},find:function(g){var l=g instanceof d,j=this.overlays,p=j.length,k=null,m,h;if(l||typeof g=="string"){for(h=p-1;h>=0;h--){m=j[h];if((l&&(m===g))||(m.id==g)){k=m;break}}}return k},compareZIndexDesc:function(j,i){var h=(j.cfg)?j.cfg.getProperty("zIndex"):null,g=(i.cfg)?i.cfg.getProperty("zIndex"):null;if(h===null&&g===null){return 0}else{if(h===null){return 1}else{if(g===null){return -1}else{if(h>g){return -1}else{if(h<g){return 1}else{return 0}}}}}},showAll:function(){var h=this.overlays,j=h.length,g;for(g=j-1;g>=0;g--){h[g].show()}},hideAll:function(){var h=this.overlays,j=h.length,g;for(g=j-1;g>=0;g--){h[g].hide()}},toString:function(){return"OverlayManager"}}}());(function(){YAHOO.widget.Tooltip=function(p,o){YAHOO.widget.Tooltip.superclass.constructor.call(this,p,o)};var e=YAHOO.lang,n=YAHOO.util.Event,m=YAHOO.util.CustomEvent,c=YAHOO.util.Dom,j=YAHOO.widget.Tooltip,h=YAHOO.env.ua,g=(h.ie&&(h.ie<=6||document.compatMode=="BackCompat")),f,i={PREVENT_OVERLAP:{key:"preventoverlap",value:true,validator:e.isBoolean,supercedes:["x","y","xy"]},SHOW_DELAY:{key:"showdelay",value:200,validator:e.isNumber},AUTO_DISMISS_DELAY:{key:"autodismissdelay",value:5000,validator:e.isNumber},HIDE_DELAY:{key:"hidedelay",value:250,validator:e.isNumber},TEXT:{key:"text",suppressEvent:true},CONTAINER:{key:"container"},DISABLED:{key:"disabled",value:false,suppressEvent:true},XY_OFFSET:{key:"xyoffset",value:[0,25],suppressEvent:true}},a={CONTEXT_MOUSE_OVER:"contextMouseOver",CONTEXT_MOUSE_OUT:"contextMouseOut",CONTEXT_TRIGGER:"contextTrigger"};j.CSS_TOOLTIP="yui-tt";function k(q,o){var p=this.cfg,r=p.getProperty("width");if(r==o){p.setProperty("width",q)}}function d(p,o){if("_originalWidth" in this){k.call(this,this._originalWidth,this._forcedWidth)}var q=document.body,u=this.cfg,t=u.getProperty("width"),r,s;if((!t||t=="auto")&&(u.getProperty("container")!=q||u.getProperty("x")>=c.getViewportWidth()||u.getProperty("y")>=c.getViewportHeight())){s=this.element.cloneNode(true);s.style.visibility="hidden";s.style.top="0px";s.style.left="0px";q.appendChild(s);r=(s.offsetWidth+"px");q.removeChild(s);s=null;u.setProperty("width",r);u.refireEvent("xy");this._originalWidth=t||"";this._forcedWidth=r}}function b(p,o,q){this.render(q)}function l(){n.onDOMReady(b,this.cfg.getProperty("container"),this)}YAHOO.extend(j,YAHOO.widget.Overlay,{init:function(p,o){j.superclass.init.call(this,p);this.beforeInitEvent.fire(j);c.addClass(this.element,j.CSS_TOOLTIP);if(o){this.cfg.applyConfig(o,true)}this.cfg.queueProperty("visible",false);this.cfg.queueProperty("constraintoviewport",true);this.setBody("");this.subscribe("changeContent",d);this.subscribe("init",l);this.subscribe("render",this.onRender);this.initEvent.fire(j)},initEvents:function(){j.superclass.initEvents.call(this);var o=m.LIST;this.contextMouseOverEvent=this.createEvent(a.CONTEXT_MOUSE_OVER);this.contextMouseOverEvent.signature=o;this.contextMouseOutEvent=this.createEvent(a.CONTEXT_MOUSE_OUT);this.contextMouseOutEvent.signature=o;this.contextTriggerEvent=this.createEvent(a.CONTEXT_TRIGGER);this.contextTriggerEvent.signature=o},initDefaultConfig:function(){j.superclass.initDefaultConfig.call(this);this.cfg.addProperty(i.PREVENT_OVERLAP.key,{value:i.PREVENT_OVERLAP.value,validator:i.PREVENT_OVERLAP.validator,supercedes:i.PREVENT_OVERLAP.supercedes});this.cfg.addProperty(i.SHOW_DELAY.key,{handler:this.configShowDelay,value:200,validator:i.SHOW_DELAY.validator});this.cfg.addProperty(i.AUTO_DISMISS_DELAY.key,{handler:this.configAutoDismissDelay,value:i.AUTO_DISMISS_DELAY.value,validator:i.AUTO_DISMISS_DELAY.validator});this.cfg.addProperty(i.HIDE_DELAY.key,{handler:this.configHideDelay,value:i.HIDE_DELAY.value,validator:i.HIDE_DELAY.validator});this.cfg.addProperty(i.TEXT.key,{handler:this.configText,suppressEvent:i.TEXT.suppressEvent});this.cfg.addProperty(i.CONTAINER.key,{handler:this.configContainer,value:document.body});this.cfg.addProperty(i.DISABLED.key,{handler:this.configContainer,value:i.DISABLED.value,supressEvent:i.DISABLED.suppressEvent});this.cfg.addProperty(i.XY_OFFSET.key,{value:i.XY_OFFSET.value.concat(),supressEvent:i.XY_OFFSET.suppressEvent})},configText:function(p,o,q){var r=o[0];if(r){this.setBody(r)}},configContainer:function(q,p,r){var o=p[0];if(typeof o=="string"){this.cfg.setProperty("container",document.getElementById(o),true)}},_removeEventListeners:function(){var r=this._context,o,q,p;if(r){o=r.length;if(o>0){p=o-1;do{q=r[p];n.removeListener(q,"mouseover",this.onContextMouseOver);n.removeListener(q,"mousemove",this.onContextMouseMove);n.removeListener(q,"mouseout",this.onContextMouseOut)}while(p--)}}},configContext:function(t,p,u){var s=p[0],v,o,r,q;if(s){if(!(s instanceof Array)){if(typeof s=="string"){this.cfg.setProperty("context",[document.getElementById(s)],true)}else{this.cfg.setProperty("context",[s],true)}s=this.cfg.getProperty("context")}this._removeEventListeners();this._context=s;v=this._context;if(v){o=v.length;if(o>0){q=o-1;do{r=v[q];n.on(r,"mouseover",this.onContextMouseOver,this);n.on(r,"mousemove",this.onContextMouseMove,this);n.on(r,"mouseout",this.onContextMouseOut,this)}while(q--)}}}},onContextMouseMove:function(p,o){o.pageX=n.getPageX(p);o.pageY=n.getPageY(p)},onContextMouseOver:function(q,p){var o=this;if(o.title){p._tempTitle=o.title;o.title=""}if(p.fireEvent("contextMouseOver",o,q)!==false&&!p.cfg.getProperty("disabled")){if(p.hideProcId){clearTimeout(p.hideProcId);p.hideProcId=null}n.on(o,"mousemove",p.onContextMouseMove,p);p.showProcId=p.doShow(q,o)}},onContextMouseOut:function(q,p){var o=this;if(p._tempTitle){o.title=p._tempTitle;p._tempTitle=null}if(p.showProcId){clearTimeout(p.showProcId);p.showProcId=null}if(p.hideProcId){clearTimeout(p.hideProcId);p.hideProcId=null}p.fireEvent("contextMouseOut",o,q);p.hideProcId=setTimeout(function(){p.hide()},p.cfg.getProperty("hidedelay"))},doShow:function(r,o){var t=this.cfg.getProperty("xyoffset"),p=t[0],s=t[1],q=this;if(h.opera&&o.tagName&&o.tagName.toUpperCase()=="A"){s+=12}return setTimeout(function(){var u=q.cfg.getProperty("text");if(q._tempTitle&&(u===""||YAHOO.lang.isUndefined(u)||YAHOO.lang.isNull(u))){q.setBody(q._tempTitle)}else{q.cfg.refireEvent("text")}q.moveTo(q.pageX+p,q.pageY+s);if(q.cfg.getProperty("preventoverlap")){q.preventOverlap(q.pageX,q.pageY)}n.removeListener(o,"mousemove",q.onContextMouseMove);q.contextTriggerEvent.fire(o);q.show();q.hideProcId=q.doHide()},this.cfg.getProperty("showdelay"))},doHide:function(){var o=this;return setTimeout(function(){o.hide()},this.cfg.getProperty("autodismissdelay"))},preventOverlap:function(s,r){var o=this.element.offsetHeight,q=new YAHOO.util.Point(s,r),p=c.getRegion(this.element);p.top-=5;p.left-=5;p.right+=5;p.bottom+=5;if(p.contains(q)){this.cfg.setProperty("y",(r-o-5))}},onRender:function(s,r){function t(){var w=this.element,v=this.underlay;if(v){v.style.width=(w.offsetWidth+6)+"px";v.style.height=(w.offsetHeight+1)+"px"}}function p(){c.addClass(this.underlay,"yui-tt-shadow-visible");if(h.ie){this.forceUnderlayRedraw()}}function o(){c.removeClass(this.underlay,"yui-tt-shadow-visible")}function u(){var x=this.underlay,w,v,z,y;if(!x){w=this.element;v=YAHOO.widget.Module;z=h.ie;y=this;if(!f){f=document.createElement("div");f.className="yui-tt-shadow"}x=f.cloneNode(false);w.appendChild(x);this.underlay=x;this._shadow=this.underlay;p.call(this);this.subscribe("beforeShow",p);this.subscribe("hide",o);if(g){window.setTimeout(function(){t.call(y)},0);this.cfg.subscribeToConfigEvent("width",t);this.cfg.subscribeToConfigEvent("height",t);this.subscribe("changeContent",t);v.textResizeEvent.subscribe(t,this,true);this.subscribe("destroy",function(){v.textResizeEvent.unsubscribe(t,this)})}}}function q(){u.call(this);this.unsubscribe("beforeShow",q)}if(this.cfg.getProperty("visible")){u.call(this)}else{this.subscribe("beforeShow",q)}},forceUnderlayRedraw:function(){var o=this;c.addClass(o.underlay,"yui-force-redraw");setTimeout(function(){c.removeClass(o.underlay,"yui-force-redraw")},0)},destroy:function(){this._removeEventListeners();j.superclass.destroy.call(this)},toString:function(){return"Tooltip "+this.id}})}());(function(){YAHOO.widget.Panel=function(v,u){YAHOO.widget.Panel.superclass.constructor.call(this,v,u)};var s=null;var e=YAHOO.lang,f=YAHOO.util,a=f.Dom,t=f.Event,m=f.CustomEvent,k=YAHOO.util.KeyListener,i=f.Config,h=YAHOO.widget.Overlay,o=YAHOO.widget.Panel,l=YAHOO.env.ua,p=(l.ie&&(l.ie<=6||document.compatMode=="BackCompat")),g,q,c,d={BEFORE_SHOW_MASK:"beforeShowMask",BEFORE_HIDE_MASK:"beforeHideMask",SHOW_MASK:"showMask",HIDE_MASK:"hideMask",DRAG:"drag"},n={CLOSE:{key:"close",value:true,validator:e.isBoolean,supercedes:["visible"]},DRAGGABLE:{key:"draggable",value:(f.DD?true:false),validator:e.isBoolean,supercedes:["visible"]},DRAG_ONLY:{key:"dragonly",value:false,validator:e.isBoolean,supercedes:["draggable"]},UNDERLAY:{key:"underlay",value:"shadow",supercedes:["visible"]},MODAL:{key:"modal",value:false,validator:e.isBoolean,supercedes:["visible","zindex"]},KEY_LISTENERS:{key:"keylisteners",suppressEvent:true,supercedes:["visible"]},STRINGS:{key:"strings",supercedes:["close"],validator:e.isObject,value:{close:"Close"}}};o.CSS_PANEL="yui-panel";o.CSS_PANEL_CONTAINER="yui-panel-container";o.FOCUSABLE=["a","button","select","textarea","input","iframe"];function j(v,u){if(!this.header&&this.cfg.getProperty("draggable")){this.setHeader("&#160;")}}function r(v,u,w){var z=w[0],x=w[1],y=this.cfg,A=y.getProperty("width");if(A==x){y.setProperty("width",z)}this.unsubscribe("hide",r,w)}function b(v,u){var y,x,w;if(p){y=this.cfg;x=y.getProperty("width");if(!x||x=="auto"){w=(this.element.offsetWidth+"px");y.setProperty("width",w);this.subscribe("hide",r,[(x||""),w])}}}YAHOO.extend(o,h,{init:function(v,u){o.superclass.init.call(this,v);this.beforeInitEvent.fire(o);a.addClass(this.element,o.CSS_PANEL);this.buildWrapper();if(u){this.cfg.applyConfig(u,true)}this.subscribe("showMask",this._addFocusHandlers);this.subscribe("hideMask",this._removeFocusHandlers);this.subscribe("beforeRender",j);this.subscribe("render",function(){this.setFirstLastFocusable();this.subscribe("changeContent",this.setFirstLastFocusable)});this.subscribe("show",this._focusOnShow);this.initEvent.fire(o)},_onElementFocus:function(z){if(s===this){var y=t.getTarget(z),x=document.documentElement,v=(y!==x&&y!==window);if(v&&y!==this.element&&y!==this.mask&&!a.isAncestor(this.element,y)){try{this._focusFirstModal()}catch(w){try{if(v&&y!==document.body){y.blur()}}catch(u){}}}}},_focusFirstModal:function(){var u=this.firstElement;if(u){u.focus()}else{if(this._modalFocus){this._modalFocus.focus()}else{this.innerElement.focus()}}},_addFocusHandlers:function(v,u){if(!this.firstElement){if(l.webkit||l.opera){if(!this._modalFocus){this._createHiddenFocusElement()}}else{this.innerElement.tabIndex=0}}this._setTabLoop(this.firstElement,this.lastElement);t.onFocus(document.documentElement,this._onElementFocus,this,true);s=this},_createHiddenFocusElement:function(){var u=document.createElement("button");u.style.height="1px";u.style.width="1px";u.style.position="absolute";u.style.left="-10000em";u.style.opacity=0;u.tabIndex=-1;this.innerElement.appendChild(u);this._modalFocus=u},_removeFocusHandlers:function(v,u){t.removeFocusListener(document.documentElement,this._onElementFocus,this);if(s==this){s=null}},_focusOnShow:function(v,u,w){if(u&&u[1]){t.stopEvent(u[1])}if(!this.focusFirst(v,u,w)){if(this.cfg.getProperty("modal")){this._focusFirstModal()}}},focusFirst:function(w,u,z){var v=this.firstElement,y=false;if(u&&u[1]){t.stopEvent(u[1])}if(v){try{v.focus();y=true}catch(x){}}return y},focusLast:function(w,u,z){var v=this.lastElement,y=false;if(u&&u[1]){t.stopEvent(u[1])}if(v){try{v.focus();y=true}catch(x){}}return y},_setTabLoop:function(u,v){this.setTabLoop(u,v)},setTabLoop:function(x,z){var v=this.preventBackTab,w=this.preventTabOut,u=this.showEvent,y=this.hideEvent;if(v){v.disable();u.unsubscribe(v.enable,v);y.unsubscribe(v.disable,v);v=this.preventBackTab=null}if(w){w.disable();u.unsubscribe(w.enable,w);y.unsubscribe(w.disable,w);w=this.preventTabOut=null}if(x){this.preventBackTab=new k(x,{shift:true,keys:9},{fn:this.focusLast,scope:this,correctScope:true});v=this.preventBackTab;u.subscribe(v.enable,v,true);y.subscribe(v.disable,v,true)}if(z){this.preventTabOut=new k(z,{shift:false,keys:9},{fn:this.focusFirst,scope:this,correctScope:true});w=this.preventTabOut;u.subscribe(w.enable,w,true);y.subscribe(w.disable,w,true)}},getFocusableElements:function(v){v=v||this.innerElement;var x={},u=this;for(var w=0;w<o.FOCUSABLE.length;w++){x[o.FOCUSABLE[w]]=true}return a.getElementsBy(function(y){return u._testIfFocusable(y,x)},null,v)},_testIfFocusable:function(u,v){if(u.focus&&u.type!=="hidden"&&!u.disabled&&v[u.tagName.toLowerCase()]){return true}return false},setFirstLastFocusable:function(){this.firstElement=null;this.lastElement=null;var u=this.getFocusableElements();this.focusableElements=u;if(u.length>0){this.firstElement=u[0];this.lastElement=u[u.length-1]}if(this.cfg.getProperty("modal")){this._setTabLoop(this.firstElement,this.lastElement)}},initEvents:function(){o.superclass.initEvents.call(this);var u=m.LIST;this.showMaskEvent=this.createEvent(d.SHOW_MASK);this.showMaskEvent.signature=u;this.beforeShowMaskEvent=this.createEvent(d.BEFORE_SHOW_MASK);this.beforeShowMaskEvent.signature=u;this.hideMaskEvent=this.createEvent(d.HIDE_MASK);this.hideMaskEvent.signature=u;this.beforeHideMaskEvent=this.createEvent(d.BEFORE_HIDE_MASK);this.beforeHideMaskEvent.signature=u;this.dragEvent=this.createEvent(d.DRAG);this.dragEvent.signature=u},initDefaultConfig:function(){o.superclass.initDefaultConfig.call(this);this.cfg.addProperty(n.CLOSE.key,{handler:this.configClose,value:n.CLOSE.value,validator:n.CLOSE.validator,supercedes:n.CLOSE.supercedes});this.cfg.addProperty(n.DRAGGABLE.key,{handler:this.configDraggable,value:(f.DD)?true:false,validator:n.DRAGGABLE.validator,supercedes:n.DRAGGABLE.supercedes});this.cfg.addProperty(n.DRAG_ONLY.key,{value:n.DRAG_ONLY.value,validator:n.DRAG_ONLY.validator,supercedes:n.DRAG_ONLY.supercedes});this.cfg.addProperty(n.UNDERLAY.key,{handler:this.configUnderlay,value:n.UNDERLAY.value,supercedes:n.UNDERLAY.supercedes});this.cfg.addProperty(n.MODAL.key,{handler:this.configModal,value:n.MODAL.value,validator:n.MODAL.validator,supercedes:n.MODAL.supercedes});this.cfg.addProperty(n.KEY_LISTENERS.key,{handler:this.configKeyListeners,suppressEvent:n.KEY_LISTENERS.suppressEvent,supercedes:n.KEY_LISTENERS.supercedes});this.cfg.addProperty(n.STRINGS.key,{value:n.STRINGS.value,handler:this.configStrings,validator:n.STRINGS.validator,supercedes:n.STRINGS.supercedes})},configClose:function(y,v,z){var A=v[0],x=this.close,u=this.cfg.getProperty("strings"),w;if(A){if(!x){if(!c){c=document.createElement("a");c.className="container-close";c.href="#"}x=c.cloneNode(true);w=this.innerElement.firstChild;if(w){this.innerElement.insertBefore(x,w)}else{this.innerElement.appendChild(x)}x.innerHTML=(u&&u.close)?u.close:"&#160;";t.on(x,"click",this._doClose,this,true);this.close=x}else{x.style.display="block"}}else{if(x){x.style.display="none"}}},_doClose:function(u){t.preventDefault(u);this.hide()},configDraggable:function(v,u,w){var x=u[0];if(x){if(!f.DD){this.cfg.setProperty("draggable",false);return}if(this.header){a.setStyle(this.header,"cursor","move");this.registerDragDrop()}this.subscribe("beforeShow",b)}else{if(this.dd){this.dd.unreg()}if(this.header){a.setStyle(this.header,"cursor","auto")}this.unsubscribe("beforeShow",b)}},configUnderlay:function(D,C,z){var B=(this.platform=="mac"&&l.gecko),E=C[0].toLowerCase(),v=this.underlay,w=this.element;function x(){var F=false;if(!v){if(!q){q=document.createElement("div");q.className="underlay"}v=q.cloneNode(false);this.element.appendChild(v);this.underlay=v;if(p){this.sizeUnderlay();this.cfg.subscribeToConfigEvent("width",this.sizeUnderlay);this.cfg.subscribeToConfigEvent("height",this.sizeUnderlay);this.changeContentEvent.subscribe(this.sizeUnderlay);YAHOO.widget.Module.textResizeEvent.subscribe(this.sizeUnderlay,this,true)}if(l.webkit&&l.webkit<420){this.changeContentEvent.subscribe(this.forceUnderlayRedraw)}F=true}}function A(){var F=x.call(this);if(!F&&p){this.sizeUnderlay()}this._underlayDeferred=false;this.beforeShowEvent.unsubscribe(A)}function y(){if(this._underlayDeferred){this.beforeShowEvent.unsubscribe(A);this._underlayDeferred=false}if(v){this.cfg.unsubscribeFromConfigEvent("width",this.sizeUnderlay);this.cfg.unsubscribeFromConfigEvent("height",this.sizeUnderlay);this.changeContentEvent.unsubscribe(this.sizeUnderlay);this.changeContentEvent.unsubscribe(this.forceUnderlayRedraw);YAHOO.widget.Module.textResizeEvent.unsubscribe(this.sizeUnderlay,this,true);this.element.removeChild(v);this.underlay=null}}switch(E){case"shadow":a.removeClass(w,"matte");a.addClass(w,"shadow");break;case"matte":if(!B){y.call(this)}a.removeClass(w,"shadow");a.addClass(w,"matte");break;default:if(!B){y.call(this)}a.removeClass(w,"shadow");a.removeClass(w,"matte");break}if((E=="shadow")||(B&&!v)){if(this.cfg.getProperty("visible")){var u=x.call(this);if(!u&&p){this.sizeUnderlay()}}else{if(!this._underlayDeferred){this.beforeShowEvent.subscribe(A);this._underlayDeferred=true}}}},configModal:function(v,u,x){var w=u[0];if(w){if(!this._hasModalityEventListeners){this.subscribe("beforeShow",this.buildMask);this.subscribe("beforeShow",this.bringToTop);this.subscribe("beforeShow",this.showMask);this.subscribe("hide",this.hideMask);h.windowResizeEvent.subscribe(this.sizeMask,this,true);this._hasModalityEventListeners=true}}else{if(this._hasModalityEventListeners){if(this.cfg.getProperty("visible")){this.hideMask();this.removeMask()}this.unsubscribe("beforeShow",this.buildMask);this.unsubscribe("beforeShow",this.bringToTop);this.unsubscribe("beforeShow",this.showMask);this.unsubscribe("hide",this.hideMask);h.windowResizeEvent.unsubscribe(this.sizeMask,this);this._hasModalityEventListeners=false}}},removeMask:function(){var v=this.mask,u;if(v){this.hideMask();u=v.parentNode;if(u){u.removeChild(v)}this.mask=null}},configKeyListeners:function(x,u,A){var w=u[0],z,y,v;if(w){if(w instanceof Array){y=w.length;for(v=0;v<y;v++){z=w[v];if(!i.alreadySubscribed(this.showEvent,z.enable,z)){this.showEvent.subscribe(z.enable,z,true)}if(!i.alreadySubscribed(this.hideEvent,z.disable,z)){this.hideEvent.subscribe(z.disable,z,true);this.destroyEvent.subscribe(z.disable,z,true)}}}else{if(!i.alreadySubscribed(this.showEvent,w.enable,w)){this.showEvent.subscribe(w.enable,w,true)}if(!i.alreadySubscribed(this.hideEvent,w.disable,w)){this.hideEvent.subscribe(w.disable,w,true);this.destroyEvent.subscribe(w.disable,w,true)}}}},configStrings:function(v,u,w){var x=e.merge(n.STRINGS.value,u[0]);this.cfg.setProperty(n.STRINGS.key,x,true)},configHeight:function(x,v,y){var u=v[0],w=this.innerElement;a.setStyle(w,"height",u);this.cfg.refireEvent("iframe")},_autoFillOnHeightChange:function(x,v,w){o.superclass._autoFillOnHeightChange.apply(this,arguments);if(p){var u=this;setTimeout(function(){u.sizeUnderlay()},0)}},configWidth:function(x,u,y){var w=u[0],v=this.innerElement;a.setStyle(v,"width",w);this.cfg.refireEvent("iframe")},configzIndex:function(v,u,x){o.superclass.configzIndex.call(this,v,u,x);if(this.mask||this.cfg.getProperty("modal")===true){var w=a.getStyle(this.element,"zIndex");if(!w||isNaN(w)){w=0}if(w===0){this.cfg.setProperty("zIndex",1)}else{this.stackMask()}}},buildWrapper:function(){var w=this.element.parentNode,u=this.element,v=document.createElement("div");v.className=o.CSS_PANEL_CONTAINER;v.id=u.id+"_c";if(w){w.insertBefore(v,u)}v.appendChild(u);this.element=v;this.innerElement=u;a.setStyle(this.innerElement,"visibility","inherit")},sizeUnderlay:function(){var v=this.underlay,u;if(v){u=this.element;v.style.width=u.offsetWidth+"px";v.style.height=u.offsetHeight+"px"}},registerDragDrop:function(){var v=this;if(this.header){if(!f.DD){return}var u=(this.cfg.getProperty("dragonly")===true);this.dd=new f.DD(this.element.id,this.id,{dragOnly:u});if(!this.header.id){this.header.id=this.id+"_h"}this.dd.startDrag=function(){var x,z,w,C,B,A;if(YAHOO.env.ua.ie==6){a.addClass(v.element,"drag")}if(v.cfg.getProperty("constraintoviewport")){var y=h.VIEWPORT_OFFSET;x=v.element.offsetHeight;z=v.element.offsetWidth;w=a.getViewportWidth();C=a.getViewportHeight();B=a.getDocumentScrollLeft();A=a.getDocumentScrollTop();if(x+y<C){this.minY=A+y;this.maxY=A+C-x-y}else{this.minY=A+y;this.maxY=A+y}if(z+y<w){this.minX=B+y;this.maxX=B+w-z-y}else{this.minX=B+y;this.maxX=B+y}this.constrainX=true;this.constrainY=true}else{this.constrainX=false;this.constrainY=false}v.dragEvent.fire("startDrag",arguments)};this.dd.onDrag=function(){v.syncPosition();v.cfg.refireEvent("iframe");if(this.platform=="mac"&&YAHOO.env.ua.gecko){this.showMacGeckoScrollbars()}v.dragEvent.fire("onDrag",arguments)};this.dd.endDrag=function(){if(YAHOO.env.ua.ie==6){a.removeClass(v.element,"drag")}v.dragEvent.fire("endDrag",arguments);v.moveEvent.fire(v.cfg.getProperty("xy"))};this.dd.setHandleElId(this.header.id);this.dd.addInvalidHandleType("INPUT");this.dd.addInvalidHandleType("SELECT");this.dd.addInvalidHandleType("TEXTAREA")}},buildMask:function(){var u=this.mask;if(!u){if(!g){g=document.createElement("div");g.className="mask";g.innerHTML="&#160;"}u=g.cloneNode(true);u.id=this.id+"_mask";document.body.insertBefore(u,document.body.firstChild);this.mask=u;if(YAHOO.env.ua.gecko&&this.platform=="mac"){a.addClass(this.mask,"block-scrollbars")}this.stackMask()}},hideMask:function(){if(this.cfg.getProperty("modal")&&this.mask&&this.beforeHideMaskEvent.fire()){this.mask.style.display="none";a.removeClass(document.body,"masked");this.hideMaskEvent.fire()}},showMask:function(){if(this.cfg.getProperty("modal")&&this.mask&&this.beforeShowMaskEvent.fire()){a.addClass(document.body,"masked");this.sizeMask();this.mask.style.display="block";this.showMaskEvent.fire()}},sizeMask:function(){if(this.mask){var v=this.mask,w=a.getViewportWidth(),u=a.getViewportHeight();if(v.offsetHeight>u){v.style.height=u+"px"}if(v.offsetWidth>w){v.style.width=w+"px"}v.style.height=a.getDocumentHeight()+"px";v.style.width=a.getDocumentWidth()+"px"}},stackMask:function(){if(this.mask){var u=a.getStyle(this.element,"zIndex");if(!YAHOO.lang.isUndefined(u)&&!isNaN(u)){a.setStyle(this.mask,"zIndex",u-1)}}},render:function(u){return o.superclass.render.call(this,u,this.innerElement)},_renderHeader:function(u){u=u||this.innerElement;o.superclass._renderHeader.call(this,u)},_renderBody:function(u){u=u||this.innerElement;o.superclass._renderBody.call(this,u)},_renderFooter:function(u){u=u||this.innerElement;o.superclass._renderFooter.call(this,u)},destroy:function(u){h.windowResizeEvent.unsubscribe(this.sizeMask,this);this.removeMask();if(this.close){t.purgeElement(this.close)}o.superclass.destroy.call(this,u)},forceUnderlayRedraw:function(){var v=this.underlay;a.addClass(v,"yui-force-redraw");setTimeout(function(){a.removeClass(v,"yui-force-redraw")},0)},toString:function(){return"Panel "+this.id}})}());(function(){YAHOO.widget.Dialog=function(j,i){YAHOO.widget.Dialog.superclass.constructor.call(this,j,i)};var b=YAHOO.util.Event,g=YAHOO.util.CustomEvent,e=YAHOO.util.Dom,a=YAHOO.widget.Dialog,f=YAHOO.lang,h={BEFORE_SUBMIT:"beforeSubmit",SUBMIT:"submit",MANUAL_SUBMIT:"manualSubmit",ASYNC_SUBMIT:"asyncSubmit",FORM_SUBMIT:"formSubmit",CANCEL:"cancel"},c={POST_METHOD:{key:"postmethod",value:"async"},POST_DATA:{key:"postdata",value:null},BUTTONS:{key:"buttons",value:"none",supercedes:["visible"]},HIDEAFTERSUBMIT:{key:"hideaftersubmit",value:true}};a.CSS_DIALOG="yui-dialog";function d(){var m=this._aButtons,k,l,j;if(f.isArray(m)){k=m.length;if(k>0){j=k-1;do{l=m[j];if(YAHOO.widget.Button&&l instanceof YAHOO.widget.Button){l.destroy()}else{if(l.tagName.toUpperCase()=="BUTTON"){b.purgeElement(l);b.purgeElement(l,false)}}}while(j--)}}}YAHOO.extend(a,YAHOO.widget.Panel,{form:null,initDefaultConfig:function(){a.superclass.initDefaultConfig.call(this);this.callback={success:null,failure:null,argument:null};this.cfg.addProperty(c.POST_METHOD.key,{handler:this.configPostMethod,value:c.POST_METHOD.value,validator:function(i){if(i!="form"&&i!="async"&&i!="none"&&i!="manual"){return false}else{return true}}});this.cfg.addProperty(c.POST_DATA.key,{value:c.POST_DATA.value});this.cfg.addProperty(c.HIDEAFTERSUBMIT.key,{value:c.HIDEAFTERSUBMIT.value});this.cfg.addProperty(c.BUTTONS.key,{handler:this.configButtons,value:c.BUTTONS.value,supercedes:c.BUTTONS.supercedes})},initEvents:function(){a.superclass.initEvents.call(this);var i=g.LIST;this.beforeSubmitEvent=this.createEvent(h.BEFORE_SUBMIT);this.beforeSubmitEvent.signature=i;this.submitEvent=this.createEvent(h.SUBMIT);this.submitEvent.signature=i;this.manualSubmitEvent=this.createEvent(h.MANUAL_SUBMIT);this.manualSubmitEvent.signature=i;this.asyncSubmitEvent=this.createEvent(h.ASYNC_SUBMIT);this.asyncSubmitEvent.signature=i;this.formSubmitEvent=this.createEvent(h.FORM_SUBMIT);this.formSubmitEvent.signature=i;this.cancelEvent=this.createEvent(h.CANCEL);this.cancelEvent.signature=i},init:function(j,i){a.superclass.init.call(this,j);this.beforeInitEvent.fire(a);e.addClass(this.element,a.CSS_DIALOG);this.cfg.setProperty("visible",false);if(i){this.cfg.applyConfig(i,true)}this.beforeHideEvent.subscribe(this.blurButtons,this,true);this.subscribe("changeBody",this.registerForm);this.initEvent.fire(a)},doSubmit:function(){var q=YAHOO.util.Connect,r=this.form,l=false,o=false,s,n,m,j;switch(this.cfg.getProperty("postmethod")){case"async":s=r.elements;n=s.length;if(n>0){m=n-1;do{if(s[m].type=="file"){l=true;break}}while(m--)}if(l&&YAHOO.env.ua.ie&&this.isSecure){o=true}j=this._getFormAttributes(r);q.setForm(r,l,o);var k=this.cfg.getProperty("postdata");var p=q.asyncRequest(j.method,j.action,this.callback,k);this.asyncSubmitEvent.fire(p);break;case"form":r.submit();this.formSubmitEvent.fire();break;case"none":case"manual":this.manualSubmitEvent.fire();break}},_getFormAttributes:function(k){var i={method:null,action:null};if(k){if(k.getAttributeNode){var j=k.getAttributeNode("action");var l=k.getAttributeNode("method");if(j){i.action=j.value}if(l){i.method=l.value}}else{i.action=k.getAttribute("action");i.method=k.getAttribute("method")}}i.method=(f.isString(i.method)?i.method:"POST").toUpperCase();i.action=f.isString(i.action)?i.action:"";return i},registerForm:function(){var i=this.element.getElementsByTagName("form")[0];if(this.form){if(this.form==i&&e.isAncestor(this.element,this.form)){return}else{b.purgeElement(this.form);this.form=null}}if(!i){i=document.createElement("form");i.name="frm_"+this.id;this.body.appendChild(i)}if(i){this.form=i;b.on(i,"submit",this._submitHandler,this,true)}},_submitHandler:function(i){b.stopEvent(i);this.submit();this.form.blur()},setTabLoop:function(i,j){i=i||this.firstButton;j=j||this.lastButton;a.superclass.setTabLoop.call(this,i,j)},_setTabLoop:function(i,j){i=i||this.firstButton;j=this.lastButton||j;this.setTabLoop(i,j)},setFirstLastFocusable:function(){a.superclass.setFirstLastFocusable.call(this);var k,j,m,n=this.focusableElements;this.firstFormElement=null;this.lastFormElement=null;if(this.form&&n&&n.length>0){j=n.length;for(k=0;k<j;++k){m=n[k];if(this.form===m.form){this.firstFormElement=m;break}}for(k=j-1;k>=0;--k){m=n[k];if(this.form===m.form){this.lastFormElement=m;break}}}},configClose:function(j,i,k){a.superclass.configClose.apply(this,arguments)},_doClose:function(i){b.preventDefault(i);this.cancel()},configButtons:function(t,s,n){var o=YAHOO.widget.Button,v=s[0],l=this.innerElement,u,q,k,r,p,j,m;d.call(this);this._aButtons=null;if(f.isArray(v)){p=document.createElement("span");p.className="button-group";r=v.length;this._aButtons=[];this.defaultHtmlButton=null;for(m=0;m<r;m++){u=v[m];if(o){k=new o({label:u.text,type:u.type});k.appendTo(p);q=k.get("element");if(u.isDefault){k.addClass("default");this.defaultHtmlButton=q}if(f.isFunction(u.handler)){k.set("onclick",{fn:u.handler,obj:this,scope:this})}else{if(f.isObject(u.handler)&&f.isFunction(u.handler.fn)){k.set("onclick",{fn:u.handler.fn,obj:((!f.isUndefined(u.handler.obj))?u.handler.obj:this),scope:(u.handler.scope||this)})}}this._aButtons[this._aButtons.length]=k}else{q=document.createElement("button");q.setAttribute("type","button");if(u.isDefault){q.className="default";this.defaultHtmlButton=q}q.innerHTML=u.text;if(f.isFunction(u.handler)){b.on(q,"click",u.handler,this,true)}else{if(f.isObject(u.handler)&&f.isFunction(u.handler.fn)){b.on(q,"click",u.handler.fn,((!f.isUndefined(u.handler.obj))?u.handler.obj:this),(u.handler.scope||this))}}p.appendChild(q);this._aButtons[this._aButtons.length]=q}u.htmlButton=q;if(m===0){this.firstButton=q}if(m==(r-1)){this.lastButton=q}}this.setFooter(p);j=this.footer;if(e.inDocument(this.element)&&!e.isAncestor(l,j)){l.appendChild(j)}this.buttonSpan=p}else{p=this.buttonSpan;j=this.footer;if(p&&j){j.removeChild(p);this.buttonSpan=null;this.firstButton=null;this.lastButton=null;this.defaultHtmlButton=null}}this.changeContentEvent.fire()},getButtons:function(){return this._aButtons||null},focusFirst:function(k,i,n){var j=this.firstFormElement,m=false;if(i&&i[1]){b.stopEvent(i[1]);if(i[0]===9&&this.firstElement){j=this.firstElement}}if(j){try{j.focus();m=true}catch(l){}}else{if(this.defaultHtmlButton){m=this.focusDefaultButton()}else{m=this.focusFirstButton()}}return m},focusLast:function(k,i,n){var o=this.cfg.getProperty("buttons"),j=this.lastFormElement,m=false;if(i&&i[1]){b.stopEvent(i[1]);if(i[0]===9&&this.lastElement){j=this.lastElement}}if(o&&f.isArray(o)){m=this.focusLastButton()}else{if(j){try{j.focus();m=true}catch(l){}}}return m},_getButton:function(j){var i=YAHOO.widget.Button;if(i&&j&&j.nodeName&&j.id){j=i.getButton(j.id)||j}return j},focusDefaultButton:function(){var i=this._getButton(this.defaultHtmlButton),k=false;if(i){try{i.focus();k=true}catch(j){}}return k},blurButtons:function(){var o=this.cfg.getProperty("buttons"),l,n,k,j;if(o&&f.isArray(o)){l=o.length;if(l>0){j=(l-1);do{n=o[j];if(n){k=this._getButton(n.htmlButton);if(k){try{k.blur()}catch(m){}}}}while(j--)}}},focusFirstButton:function(){var m=this.cfg.getProperty("buttons"),k,i,l=false;if(m&&f.isArray(m)){k=m[0];if(k){i=this._getButton(k.htmlButton);if(i){try{i.focus();l=true}catch(j){}}}}return l},focusLastButton:function(){var n=this.cfg.getProperty("buttons"),j,l,i,m=false;if(n&&f.isArray(n)){j=n.length;if(j>0){l=n[(j-1)];if(l){i=this._getButton(l.htmlButton);if(i){try{i.focus();m=true}catch(k){}}}}}return m},configPostMethod:function(j,i,k){this.registerForm()},validate:function(){return true},submit:function(){if(this.validate()){if(this.beforeSubmitEvent.fire()){this.doSubmit();this.submitEvent.fire();if(this.cfg.getProperty("hideaftersubmit")){this.hide()}return true}else{return false}}else{return false}},cancel:function(){this.cancelEvent.fire();this.hide()},getData:function(){var A=this.form,k,t,w,m,u,r,q,j,x,l,y,B,p,C,o,z,v;function s(n){var i=n.tagName.toUpperCase();return((i=="INPUT"||i=="TEXTAREA"||i=="SELECT")&&n.name==m)}if(A){k=A.elements;t=k.length;w={};for(z=0;z<t;z++){m=k[z].name;u=e.getElementsBy(s,"*",A);r=u.length;if(r>0){if(r==1){u=u[0];q=u.type;j=u.tagName.toUpperCase();switch(j){case"INPUT":if(q=="checkbox"){w[m]=u.checked}else{if(q!="radio"){w[m]=u.value}}break;case"TEXTAREA":w[m]=u.value;break;case"SELECT":x=u.options;l=x.length;y=[];for(v=0;v<l;v++){B=x[v];if(B.selected){o=B.attributes.value;y[y.length]=(o&&o.specified)?B.value:B.text}}w[m]=y;break}}else{q=u[0].type;switch(q){case"radio":for(v=0;v<r;v++){p=u[v];if(p.checked){w[m]=p.value;break}}break;case"checkbox":y=[];for(v=0;v<r;v++){C=u[v];if(C.checked){y[y.length]=C.value}}w[m]=y;break}}}}}return w},destroy:function(i){d.call(this);this._aButtons=null;var j=this.element.getElementsByTagName("form"),k;if(j.length>0){k=j[0];if(k){b.purgeElement(k);if(k.parentNode){k.parentNode.removeChild(k)}this.form=null}}a.superclass.destroy.call(this,i)},toString:function(){return"Dialog "+this.id}})}());(function(){YAHOO.widget.SimpleDialog=function(e,d){YAHOO.widget.SimpleDialog.superclass.constructor.call(this,e,d)};var c=YAHOO.util.Dom,b=YAHOO.widget.SimpleDialog,a={ICON:{key:"icon",value:"none",suppressEvent:true},TEXT:{key:"text",value:"",suppressEvent:true,supercedes:["icon"]}};b.ICON_BLOCK="blckicon";b.ICON_ALARM="alrticon";b.ICON_HELP="hlpicon";b.ICON_INFO="infoicon";b.ICON_WARN="warnicon";b.ICON_TIP="tipicon";b.ICON_CSS_CLASSNAME="yui-icon";b.CSS_SIMPLEDIALOG="yui-simple-dialog";YAHOO.extend(b,YAHOO.widget.Dialog,{initDefaultConfig:function(){b.superclass.initDefaultConfig.call(this);this.cfg.addProperty(a.ICON.key,{handler:this.configIcon,value:a.ICON.value,suppressEvent:a.ICON.suppressEvent});this.cfg.addProperty(a.TEXT.key,{handler:this.configText,value:a.TEXT.value,suppressEvent:a.TEXT.suppressEvent,supercedes:a.TEXT.supercedes})},init:function(e,d){b.superclass.init.call(this,e);this.beforeInitEvent.fire(b);c.addClass(this.element,b.CSS_SIMPLEDIALOG);this.cfg.queueProperty("postmethod","manual");if(d){this.cfg.applyConfig(d,true)}this.beforeRenderEvent.subscribe(function(){if(!this.body){this.setBody("")}},this,true);this.initEvent.fire(b)},registerForm:function(){b.superclass.registerForm.call(this);var e=this.form.ownerDocument,d=e.createElement("input");d.type="hidden";d.name=this.id;d.value="";this.form.appendChild(d)},configIcon:function(k,j,h){var d=j[0],e=this.body,f=b.ICON_CSS_CLASSNAME,l,i,g;if(d&&d!="none"){l=c.getElementsByClassName(f,"*",e);if(l.length===1){i=l[0];g=i.parentNode;if(g){g.removeChild(i);i=null}}if(d.indexOf(".")==-1){i=document.createElement("span");i.className=(f+" "+d);i.innerHTML="&#160;"}else{i=document.createElement("img");i.src=(this.imageRoot+d);i.className=f}if(i){e.insertBefore(i,e.firstChild)}}},configText:function(e,d,f){var g=d[0];if(g){this.setBody(g);this.cfg.refireEvent("icon")}},toString:function(){return"SimpleDialog "+this.id}})}());(function(){YAHOO.widget.ContainerEffect=function(e,h,g,d,f){if(!f){f=YAHOO.util.Anim}this.overlay=e;this.attrIn=h;this.attrOut=g;this.targetElement=d||e.element;this.animClass=f};var b=YAHOO.util.Dom,c=YAHOO.util.CustomEvent,a=YAHOO.widget.ContainerEffect;a.FADE=function(d,f){var g=YAHOO.util.Easing,i={attributes:{opacity:{from:0,to:1}},duration:f,method:g.easeIn},e={attributes:{opacity:{to:0}},duration:f,method:g.easeOut},h=new a(d,i,e,d.element);h.handleUnderlayStart=function(){var k=this.overlay.underlay;if(k&&YAHOO.env.ua.ie){var j=(k.filters&&k.filters.length>0);if(j){b.addClass(d.element,"yui-effect-fade")}}};h.handleUnderlayComplete=function(){var j=this.overlay.underlay;if(j&&YAHOO.env.ua.ie){b.removeClass(d.element,"yui-effect-fade")}};h.handleStartAnimateIn=function(k,j,l){l.overlay._fadingIn=true;b.addClass(l.overlay.element,"hide-select");if(!l.overlay.underlay){l.overlay.cfg.refireEvent("underlay")}l.handleUnderlayStart();l.overlay._setDomVisibility(true);b.setStyle(l.overlay.element,"opacity",0)};h.handleCompleteAnimateIn=function(k,j,l){l.overlay._fadingIn=false;b.removeClass(l.overlay.element,"hide-select");if(l.overlay.element.style.filter){l.overlay.element.style.filter=null}l.handleUnderlayComplete();l.overlay.cfg.refireEvent("iframe");l.animateInCompleteEvent.fire()};h.handleStartAnimateOut=function(k,j,l){l.overlay._fadingOut=true;b.addClass(l.overlay.element,"hide-select");l.handleUnderlayStart()};h.handleCompleteAnimateOut=function(k,j,l){l.overlay._fadingOut=false;b.removeClass(l.overlay.element,"hide-select");if(l.overlay.element.style.filter){l.overlay.element.style.filter=null}l.overlay._setDomVisibility(false);b.setStyle(l.overlay.element,"opacity",1);l.handleUnderlayComplete();l.overlay.cfg.refireEvent("iframe");l.animateOutCompleteEvent.fire()};h.init();return h};a.SLIDE=function(f,d){var i=YAHOO.util.Easing,l=f.cfg.getProperty("x")||b.getX(f.element),k=f.cfg.getProperty("y")||b.getY(f.element),m=b.getClientWidth(),h=f.element.offsetWidth,j={attributes:{points:{to:[l,k]}},duration:d,method:i.easeIn},e={attributes:{points:{to:[(m+25),k]}},duration:d,method:i.easeOut},g=new a(f,j,e,f.element,YAHOO.util.Motion);g.handleStartAnimateIn=function(o,n,p){p.overlay.element.style.left=((-25)-h)+"px";p.overlay.element.style.top=k+"px"};g.handleTweenAnimateIn=function(q,p,r){var s=b.getXY(r.overlay.element),o=s[0],n=s[1];if(b.getStyle(r.overlay.element,"visibility")=="hidden"&&o<l){r.overlay._setDomVisibility(true)}r.overlay.cfg.setProperty("xy",[o,n],true);r.overlay.cfg.refireEvent("iframe")};g.handleCompleteAnimateIn=function(o,n,p){p.overlay.cfg.setProperty("xy",[l,k],true);p.startX=l;p.startY=k;p.overlay.cfg.refireEvent("iframe");p.animateInCompleteEvent.fire()};g.handleStartAnimateOut=function(o,n,r){var p=b.getViewportWidth(),s=b.getXY(r.overlay.element),q=s[1];r.animOut.attributes.points.to=[(p+25),q]};g.handleTweenAnimateOut=function(p,o,q){var s=b.getXY(q.overlay.element),n=s[0],r=s[1];q.overlay.cfg.setProperty("xy",[n,r],true);q.overlay.cfg.refireEvent("iframe")};g.handleCompleteAnimateOut=function(o,n,p){p.overlay._setDomVisibility(false);p.overlay.cfg.setProperty("xy",[l,k]);p.animateOutCompleteEvent.fire()};g.init();return g};a.prototype={init:function(){this.beforeAnimateInEvent=this.createEvent("beforeAnimateIn");this.beforeAnimateInEvent.signature=c.LIST;this.beforeAnimateOutEvent=this.createEvent("beforeAnimateOut");this.beforeAnimateOutEvent.signature=c.LIST;this.animateInCompleteEvent=this.createEvent("animateInComplete");this.animateInCompleteEvent.signature=c.LIST;this.animateOutCompleteEvent=this.createEvent("animateOutComplete");this.animateOutCompleteEvent.signature=c.LIST;this.animIn=new this.animClass(this.targetElement,this.attrIn.attributes,this.attrIn.duration,this.attrIn.method);this.animIn.onStart.subscribe(this.handleStartAnimateIn,this);this.animIn.onTween.subscribe(this.handleTweenAnimateIn,this);this.animIn.onComplete.subscribe(this.handleCompleteAnimateIn,this);this.animOut=new this.animClass(this.targetElement,this.attrOut.attributes,this.attrOut.duration,this.attrOut.method);this.animOut.onStart.subscribe(this.handleStartAnimateOut,this);this.animOut.onTween.subscribe(this.handleTweenAnimateOut,this);this.animOut.onComplete.subscribe(this.handleCompleteAnimateOut,this)},animateIn:function(){this._stopAnims(this.lastFrameOnStop);this.beforeAnimateInEvent.fire();this.animIn.animate()},animateOut:function(){this._stopAnims(this.lastFrameOnStop);this.beforeAnimateOutEvent.fire();this.animOut.animate()},lastFrameOnStop:true,_stopAnims:function(d){if(this.animOut&&this.animOut.isAnimated()){this.animOut.stop(d)}if(this.animIn&&this.animIn.isAnimated()){this.animIn.stop(d)}},handleStartAnimateIn:function(e,d,f){},handleTweenAnimateIn:function(e,d,f){},handleCompleteAnimateIn:function(e,d,f){},handleStartAnimateOut:function(e,d,f){},handleTweenAnimateOut:function(e,d,f){},handleCompleteAnimateOut:function(e,d,f){},toString:function(){var d="ContainerEffect";if(this.overlay){d+=" ["+this.overlay.toString()+"]"}return d}};YAHOO.lang.augmentProto(a,YAHOO.util.EventProvider)})();YAHOO.register("container",YAHOO.widget.Module,{version:"2.9.0",build:"2800"});(function(){var a=YAHOO.util.Event,c=YAHOO.lang,b=[],d=function(h,e,f){var g;if(!h||h===f){g=false}else{g=YAHOO.util.Selector.test(h,e)?h:d(h.parentNode,e,f)}return g};c.augmentObject(a,{_createDelegate:function(f,e,g,h){return function(i){var j=this,n=a.getTarget(i),l=e,p=(j.nodeType===9),q,k,o,m;if(c.isFunction(e)){q=e(n)}else{if(c.isString(e)){if(!p){o=j.id;if(!o){o=a.generateId(j)}m=("#"+o+" ");l=(m+e).replace(/,/gi,(","+m))}if(YAHOO.util.Selector.test(n,l)){q=n}else{if(YAHOO.util.Selector.test(n,((l.replace(/,/gi," *,"))+" *"))){q=d(n,l,j)}}}}if(q){k=q;if(h){if(h===true){k=g}else{k=h}}return f.call(k,i,q,j,g)}}},delegate:function(f,j,l,g,h,i){var e=j,k,m;if(c.isString(g)&&!YAHOO.util.Selector){return false}if(j=="mouseenter"||j=="mouseleave"){if(!a._createMouseDelegate){return false}e=a._getType(j);k=a._createMouseDelegate(l,h,i);m=a._createDelegate(function(p,o,n){return k.call(o,p,n)},g,h,i)}else{m=a._createDelegate(l,g,h,i)}b.push([f,e,l,m]);return a.on(f,e,m)},removeDelegate:function(f,j,i){var k=j,h=false,g,e;if(j=="mouseenter"||j=="mouseleave"){k=a._getType(j)}g=a._getCacheIndex(b,f,k,i);if(g>=0){e=b[g]}if(f&&e){h=a.removeListener(e[0],e[1],e[3]);if(h){delete b[g][2];delete b[g][3];b.splice(g,1)}}return h}})}());YAHOO.register("event-delegate",YAHOO.util.Event,{version:"2.9.0",build:"2800"});(function(){var l=YAHOO.lang,isFunction=l.isFunction,isObject=l.isObject,isArray=l.isArray,_toStr=Object.prototype.toString,Native=(YAHOO.env.ua.caja?window:this).JSON,_UNICODE_EXCEPTIONS=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,_ESCAPES=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,_VALUES=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,_BRACKETS=/(?:^|:|,)(?:\s*\[)+/g,_UNSAFE=/[^\],:{}\s]/,_SPECIAL_CHARS=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,_CHARS={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},UNDEFINED="undefined",OBJECT="object",NULL="null",STRING="string",NUMBER="number",BOOLEAN="boolean",DATE="date",_allowable={"undefined":UNDEFINED,string:STRING,"[object String]":STRING,number:NUMBER,"[object Number]":NUMBER,"boolean":BOOLEAN,"[object Boolean]":BOOLEAN,"[object Date]":DATE,"[object RegExp]":OBJECT},EMPTY="",OPEN_O="{",CLOSE_O="}",OPEN_A="[",CLOSE_A="]",COMMA=",",COMMA_CR=",\n",CR="\n",COLON=":",COLON_SP=": ",QUOTE='"';Native=_toStr.call(Native)==="[object JSON]"&&Native;function _char(c){if(!_CHARS[c]){_CHARS[c]="\\u"+("0000"+(+(c.charCodeAt(0))).toString(16)).slice(-4)}return _CHARS[c]}function _revive(data,reviver){var walk=function(o,key){var k,v,value=o[key];if(value&&typeof value==="object"){for(k in value){if(l.hasOwnProperty(value,k)){v=walk(value,k);if(v===undefined){delete value[k]}else{value[k]=v}}}}return reviver.call(o,key,value)};return typeof reviver==="function"?walk({"":data},""):data}function _prepare(s){return s.replace(_UNICODE_EXCEPTIONS,_char)}function _isSafe(str){return l.isString(str)&&!_UNSAFE.test(str.replace(_ESCAPES,"@").replace(_VALUES,"]").replace(_BRACKETS,""))}function _parse(s,reviver){s=_prepare(s);if(_isSafe(s)){return _revive(eval("("+s+")"),reviver)}throw new SyntaxError("JSON.parse")}function _type(o){var t=typeof o;return _allowable[t]||_allowable[_toStr.call(o)]||(t===OBJECT?(o?OBJECT:NULL):UNDEFINED)}function _string(s){return QUOTE+s.replace(_SPECIAL_CHARS,_char)+QUOTE}function _indent(s,space){return s.replace(/^/gm,space)}function _stringify(o,w,space){if(o===undefined){return undefined}var replacer=isFunction(w)?w:null,format=_toStr.call(space).match(/String|Number/)||[],_date=YAHOO.lang.JSON.dateToString,stack=[],tmp,i,len;if(replacer||!isArray(w)){w=undefined}if(w){tmp={};for(i=0,len=w.length;i<len;++i){tmp[w[i]]=true}w=tmp}space=format[0]==="Number"?new Array(Math.min(Math.max(0,space),10)+1).join(" "):(space||EMPTY).slice(0,10);function _serialize(h,key){var value=h[key],t=_type(value),a=[],colon=space?COLON_SP:COLON,arr,i,keys,k,v;if(isObject(value)&&isFunction(value.toJSON)){value=value.toJSON(key)}else{if(t===DATE){value=_date(value)}}if(isFunction(replacer)){value=replacer.call(h,key,value)}if(value!==h[key]){t=_type(value)}switch(t){case DATE:case OBJECT:break;case STRING:return _string(value);case NUMBER:return isFinite(value)?value+EMPTY:NULL;case BOOLEAN:return value+EMPTY;case NULL:return NULL;default:return undefined}for(i=stack.length-1;i>=0;--i){if(stack[i]===value){throw new Error("JSON.stringify. Cyclical reference")}}arr=isArray(value);stack.push(value);if(arr){for(i=value.length-1;i>=0;--i){a[i]=_serialize(value,i)||NULL}}else{keys=w||value;i=0;for(k in keys){if(l.hasOwnProperty(keys,k)){v=_serialize(value,k);if(v){a[i++]=_string(k)+colon+v}}}}stack.pop();if(space&&a.length){return arr?OPEN_A+CR+_indent(a.join(COMMA_CR),space)+CR+CLOSE_A:OPEN_O+CR+_indent(a.join(COMMA_CR),space)+CR+CLOSE_O}else{return arr?OPEN_A+a.join(COMMA)+CLOSE_A:OPEN_O+a.join(COMMA)+CLOSE_O}}return _serialize({"":o},"")}YAHOO.lang.JSON={useNativeParse:!!Native,useNativeStringify:!!Native,isSafe:function(s){return _isSafe(_prepare(s))},parse:function(s,reviver){if(typeof s!=="string"){s+=""}return Native&&YAHOO.lang.JSON.useNativeParse?Native.parse(s,reviver):_parse(s,reviver)},stringify:function(o,w,space){return Native&&YAHOO.lang.JSON.useNativeStringify?Native.stringify(o,w,space):_stringify(o,w,space)},dateToString:function(d){function _zeroPad(v){return v<10?"0"+v:v}return d.getUTCFullYear()+"-"+_zeroPad(d.getUTCMonth()+1)+"-"+_zeroPad(d.getUTCDate())+"T"+_zeroPad(d.getUTCHours())+COLON+_zeroPad(d.getUTCMinutes())+COLON+_zeroPad(d.getUTCSeconds())+"Z"},stringToDate:function(str){var m=str.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{3}))?Z$/);if(m){var d=new Date();d.setUTCFullYear(m[1],m[2]-1,m[3]);d.setUTCHours(m[4],m[5],m[6],(m[7]||0));return d}return str}};YAHOO.lang.JSON.isValid=YAHOO.lang.JSON.isSafe})();YAHOO.register("json",YAHOO.lang.JSON,{version:"2.9.0",build:"2800"});
\ No newline at end of file
--- a/kallithea/templates/about.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/about.html	Fri Nov 18 01:11:13 2016 +0100
@@ -11,9 +11,9 @@
 </%block>
 <%def name="main()">
 
-<div class="box">
+<div class="panel panel-primary">
   <!-- box / title -->
-  <div class="title">
+  <div class="panel-heading">
     <h5>${_('About')} Kallithea</h5>
   </div>
 
@@ -31,16 +31,26 @@
   <li>Copyright &copy; 2012&ndash;2016, Takumi IINO</li>
   <li>Copyright &copy; 2012&ndash;2016, Unity Technologies</li>
   <li>Copyright &copy; 2012, 2014&ndash;2016, Andrew Shadura</li>
-  <li>Copyright &copy; 2012, 2014, 2016, Dominik Ruf</li>
+  <li>Copyright &copy; 2012, 2014&ndash;2016, Dominik Ruf</li>
+  <li>Copyright &copy; 2014&ndash;2016, Thomas De Schampheleire</li>
+  <li>Copyright &copy; 2015&ndash;2016, Étienne Gilli</li>
+  <li>Copyright &copy; 2015&ndash;2016, Jan Heylen</li>
+  <li>Copyright &copy; 2015&ndash;2016, Robert Martinez</li>
+  <li>Copyright &copy; 2015&ndash;2016, Robert Rauch</li>
   <li>Copyright &copy; 2015&ndash;2016, Søren Løvborg</li>
+  <li>Copyright &copy; 2016, Angel Ezquerra</li>
+  <li>Copyright &copy; 2016, Asterios Dimitriou</li>
+  <li>Copyright &copy; 2016, Kateryna Musina</li>
   <li>Copyright &copy; 2016, Konstantin Veretennicov</li>
+  <li>Copyright &copy; 2016, Oscar Curero</li>
   <li>Copyright &copy; 2016, Robert James Dennington</li>
+  <li>Copyright &copy; 2016, timeless@gmail.com</li>
+  <li>Copyright &copy; 2016, YFdyh000</li>
   <li>Copyright &copy; 2012&ndash;2013, 2015, Aras Pranckevičius</li>
   <li>Copyright &copy; 2014&ndash;2015, Christian Oyarzun</li>
   <li>Copyright &copy; 2014&ndash;2015, Joseph Rivera</li>
   <li>Copyright &copy; 2014&ndash;2015, Michal Čihař</li>
   <li>Copyright &copy; 2014&ndash;2015, Sean Farley</li>
-  <li>Copyright &copy; 2014&ndash;2015, Thomas De Schampheleire</li>
   <li>Copyright &copy; 2015, Anatoly Bubenkov</li>
   <li>Copyright &copy; 2015, Andrew Bartlett</li>
   <li>Copyright &copy; 2015, Balázs Úr</li>
@@ -51,9 +61,8 @@
   <li>Copyright &copy; 2015, Denis Blanchette</li>
   <li>Copyright &copy; 2015, duanhongyi</li>
   <li>Copyright &copy; 2015, EriCSN Chang</li>
-  <li>Copyright &copy; 2015, Étienne Gilli</li>
   <li>Copyright &copy; 2015, Grzegorz Krason</li>
-  <li>Copyright &copy; 2015, Jan Heylen</li>
+  <li>Copyright &copy; 2015, Jiří Suchan</li>
   <li>Copyright &copy; 2015, Kazunari Kobayashi</li>
   <li>Copyright &copy; 2015, Kevin Bullock</li>
   <li>Copyright &copy; 2015, kobanari</li>
@@ -66,12 +75,11 @@
   <li>Copyright &copy; 2015, Nick High</li>
   <li>Copyright &copy; 2015, Niemand Jedermann</li>
   <li>Copyright &copy; 2015, Peter Vitt</li>
-  <li>Copyright &copy; 2015, Robert Martinez</li>
-  <li>Copyright &copy; 2015, Robert Rauch</li>
   <li>Copyright &copy; 2015, Ronny Pfannschmidt</li>
   <li>Copyright &copy; 2015, Sam Jaques</li>
   <li>Copyright &copy; 2015, Tuux</li>
   <li>Copyright &copy; 2015, Viktar Palstsiuk</li>
+  <li>Copyright &copy; 2014, Ante Ilic</li>
   <li>Copyright &copy; 2014, Bradley M. Kuhn</li>
   <li>Copyright &copy; 2014, Calinou</li>
   <li>Copyright &copy; 2014, Daniel Anderson</li>
--- a/kallithea/templates/admin/admin.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/admin.html	Fri Nov 18 01:11:13 2016 +0100
@@ -8,8 +8,8 @@
 <%def name="breadcrumbs_links()">
     <form id="filter_form">
     <input class="q_filter_box ${'' if c.search_term else 'initial'}" id="j_filter" size="15" type="text" name="filter" value="${c.search_term or _('journal filter...')}"/>
-    <span class="tooltip" title="${h.journal_filter_help()}">?</span>
-    <input type='submit' value="${_('Filter')}" class="btn btn-mini" style="padding:0px 2px 0px 2px;margin:0px"/>
+    <span data-toggle="tooltip" title="${h.journal_filter_help()}">?</span>
+    <input type='submit' value="${_('Filter')}" class="btn btn-default btn-xs"/>
     ${_('Admin Journal')} - ${ungettext('%s Entry', '%s Entries', c.users_log.item_count) % (c.users_log.item_count)}
     </form>
     ${h.end_form()}
@@ -19,9 +19,9 @@
     ${self.menu('admin')}
 </%block>
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
     <!-- end box / title -->
--- a/kallithea/templates/admin/admin_log.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/admin_log.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,6 +1,6 @@
 ## -*- coding: utf-8 -*-
 %if c.users_log:
-<table>
+<table class="table">
     <tr>
         <th class="left">${_('Username')}</th>
         <th class="left">${_('Action')}</th>
@@ -56,8 +56,9 @@
   });
 </script>
 
-<div class="pagination-wh pagination-left">
-${c.users_log.pager('$link_previous ~2~ $link_next')}
+<ul class="pagination">
+    ${c.users_log.pager()}
+</ul>
 </div>
 %else:
     ${_('No actions yet')}
--- a/kallithea/templates/admin/auth/auth_settings.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/auth/auth_settings.html	Fri Nov 18 01:11:13 2016 +0100
@@ -16,9 +16,9 @@
 </%block>
 
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading">
         ${self.breadcrumbs()}
     </div>
     ${h.form(url('auth_settings'))}
@@ -26,69 +26,71 @@
 
     ## enabled auth plugins
     <h1>${_('Authentication Plugins')}</h1>
-    <div class="fields">
-       <div class="field">
-           <div class="label"><label for="auth_plugins">${_("Enabled Plugins")}</label></div>
-           <div class="input">${h.text("auth_plugins", class_='large')}
-           <span class="help-block">${_('Comma-separated list of plugins; Kallithea will try user authentication in plugin order')}</span>
-               <div style="padding:10px 0px 10px 0px;font-weight: bold">${_('Available built-in plugins')}</div>
-               <ul>
-               %for plugin_path in c.available_plugins:
+    <div class="form-horizontal">
+        <div class="form-group">
+            <label class="control-label" for="auth_plugins">${_("Enabled Plugins")}</label>
+            <div class="input">${h.text("auth_plugins", class_='large')}
+            <span class="help-block">${_('Comma-separated list of plugins; Kallithea will try user authentication in plugin order')}</span>
+                <div style="padding:10px 0px 10px 0px;font-weight: bold">${_('Available built-in plugins')}</div>
+                <ul>
+                %for plugin_path in c.available_plugins:
                     <li>
                       <div style="padding:3px 0px 3px 0px">
-                          <span style="margin: 0px 10px 0px 0px" plugin_id="${plugin_path}" class="toggle-plugin btn btn-mini ${'btn-success' if plugin_path in c.enabled_plugins else ''}">
-                          ${_('Enabled') if plugin_path in c.enabled_plugins else _('Disabled')}</span>${plugin_path}
+                        <span style="margin: 0px 10px 0px 0px" plugin_id="${plugin_path}" class="toggle-plugin btn btn-default btn-xs ${'active' if plugin_path in c.enabled_plugins else ''}">
+                            ${_('Enabled') if plugin_path in c.enabled_plugins else _('Disabled')}
+                        </span>
+                        ${plugin_path}
                       </div>
                     </li>
-               %endfor
-               </ul>
-           </div>
-       </div>
+                %endfor
+                </ul>
+            </div>
+        </div>
     </div>
 
     %for cnt, module in enumerate(c.enabled_plugins):
         <% pluginName = c.plugin_shortnames[module] %>
         <h1>${_('Plugin')}: ${pluginName}</h1>
-        <div class="fields">
+        <div class="form-horizontal">
         ## autoform generation, based on plugin definition from it's settings
         %for setting in c.plugin_settings[module]:
             <% fullsetting = "auth_%s_%s" % (pluginName, setting["name"]) %>
             <% displayname = (setting["formname"] if ("formname" in setting) else setting["name"]) %>
             %if setting["type"] == "password":
-            <div class="field">
-                <div class="label"><label for="${fullsetting}">${_(displayname)}</label></div>
+            <div class="form-group">
+                <label class="control-label" for="${fullsetting}">${_(displayname)}</label>
                 <div class="input">
                     ${h.password(fullsetting,class_='small')}
                     <span class="help-block">${setting["description"]}</span>
                 </div>
             </div>
             %elif setting["type"] in ["string", "int"]:
-            <div class="field">
-                <div class="label"><label for="${fullsetting}">${_(displayname)}</label></div>
+            <div class="form-group">
+                <label class="control-label" for="${fullsetting}">${_(displayname)}</label>
                 <div class="input">
                     ${h.text(fullsetting,class_='small')}
                     <span class="help-block">${setting["description"]}</span>
                 </div>
             </div>
             %elif setting["type"] == "bool":
-            <div class="field">
-                <div class="label label-checkbox"><label for="${fullsetting}">${_(displayname)}</label></div>
+            <div class="form-group">
+                <label class="control-label" for="${fullsetting}">${_(displayname)}</label>
                 <div class="checkboxes">
                     <div class="checkbox">${h.checkbox(fullsetting,True,class_='small')}</div>
                     <span class="help-block">${setting["description"]}</span>
                 </div>
             </div>
             %elif setting["type"] == "select":
-            <div class="field">
-                <div class="label"><label for="${fullsetting}">${_(displayname)}</label></div>
+            <div class="form-group">
+                <label class="control-label" for="${fullsetting}">${_(displayname)}</label>
                 <div class="select">
                     ${h.select(fullsetting,setting['values'][0],setting['values'],class_='small')}
                     <span class="help-block">${setting["description"]}</span>
                 </div>
             </div>
             %else:
-            <div class="field">
-                <div class="label"><label for="${fullsetting}">${_(displayname)}</label></div>
+            <div class="form-group">
+                <label class="control-label" for="${fullsetting}">${_(displayname)}</label>
                 <div class="input">This field is of type ${setting['type']}, which cannot be displayed. Must be one of [string|int|bool|select].</div>
                 <span class="help-block">${setting["description"]}</span>
             </div>
@@ -96,9 +98,11 @@
         %endfor
         </div>
     %endfor
-        <div class="fields">
-            <div class="buttons">
-                ${h.submit('save',_('Save'),class_="btn")}
+        <div class="form-horizontal">
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Save'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
@@ -115,19 +119,19 @@
         var $cur_button = $(e.currentTarget);
         var plugin_id = $cur_button.attr('plugin_id');
 
-        if($cur_button.hasClass('btn-success')){
+        if($cur_button.hasClass('active')){
             elems.splice(elems.indexOf(plugin_id), 1);
             $auth_plugins_input.val(elems.join(','));
-            $cur_button.removeClass('btn-success');
-            $cur_button.html(_TM['disabled']);
+            $cur_button.removeClass('active');
+            $cur_button.html(_TM['Disabled']);
         }
         else{
             if(elems.indexOf(plugin_id) == -1){
                 elems.push(plugin_id);
             }
             $auth_plugins_input.val(elems.join(','));
-            $cur_button.addClass('btn-success');
-            $cur_button.html(_TM['enabled']);
+            $cur_button.addClass('active');
+            $cur_button.html(_TM['Enabled']);
         }
     });
 </script>
--- a/kallithea/templates/admin/defaults/defaults.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/defaults/defaults.html	Fri Nov 18 01:11:13 2016 +0100
@@ -16,70 +16,61 @@
 </%block>
 
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading">
         ${self.breadcrumbs()}
     </div>
 
-    ${h.form(url('default', id='defaults'),method='put')}
+    ${h.form(url('defaults_update', id='defaults'))}
     <div class="form">
         <!-- fields -->
 
-        <div class="fields">
+        <div class="form-horizontal">
 
-            <div class="field">
-                <div class="label">
-                    <label for="default_repo_type">${_('Type')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="default_repo_type">${_('Type')}:</label>
                 <div class="input">
                     ${h.select('default_repo_type','hg',c.backends,class_="medium")}
                 </div>
             </div>
 
-            <div class="field">
-                <div class="label label-checkbox">
-                    <label for="default_repo_private">${_('Private repository')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="default_repo_private">${_('Private repository')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('default_repo_private',value="True")}
                     <span class="help-block">${_('Private repositories are only visible to people explicitly added as collaborators.')}</span>
                 </div>
             </div>
 
-
-            <div class="field">
-                <div class="label label-checkbox">
-                    <label for="default_repo_enable_statistics">${_('Enable statistics')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="default_repo_enable_statistics">${_('Enable statistics')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('default_repo_enable_statistics',value="True")}
                     <span class="help-block">${_('Enable statistics window on summary page.')}</span>
                 </div>
             </div>
 
-            <div class="field">
-                <div class="label label-checkbox">
-                    <label for="default_repo_enable_downloads">${_('Enable downloads')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="default_repo_enable_downloads">${_('Enable downloads')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('default_repo_enable_downloads',value="True")}
                     <span class="help-block">${_('Enable download menu on summary page.')}</span>
                 </div>
             </div>
 
-            <div class="field">
-                <div class="label label-checkbox">
-                    <label for="default_repo_enable_locking">${_('Enable locking')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="default_repo_enable_locking">${_('Enable locking')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('default_repo_enable_locking',value="True")}
                     <span class="help-block">${_('Enable lock-by-pulling on repository.')}</span>
                 </div>
             </div>
 
-            <div class="buttons">
-            ${h.submit('save',_('Save'),class_="btn")}
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Save'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/admin/gists/edit.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/gists/edit.html	Fri Nov 18 01:11:13 2016 +0100
@@ -23,9 +23,9 @@
 </%block>
 
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading">
         ${self.breadcrumbs()}
     </div>
 
@@ -46,9 +46,7 @@
         <div id="files_data">
           ${h.form(h.url('edit_gist', gist_id=c.gist.gist_access_id), method='post', id='eform')}
             <div>
-                <div class="gravatar">
-                  ${h.gravatar(c.authuser.email, size=32)}
-                </div>
+                ${h.gravatar_div(c.authuser.email, size=32)}
                 <input type="hidden" value="${c.file_changeset.raw_id}" name="parent_hash">
                 <textarea style="resize:vertical; width:400px;border: 1px solid #ccc;border-radius: 3px;"
                           id="description" name="description"
@@ -56,7 +54,7 @@
                 <div style="padding:0px 0px 0px 42px">
                     <label for='lifetime'>${_('Gist lifetime')}</label>
                     ${h.select('lifetime', '0', c.lifetime_options)}
-                    <span class="" style="color: #AAA">
+                    <span class="text-muted">
                      %if c.gist.gist_expires == -1:
                       ${_('Expires')}: ${_('Never')}
                      %else:
@@ -81,69 +79,70 @@
 
                 ## dynamic edit box.
                 <script type="text/javascript">
-                var myCodeMirror = initCodeMirror("editor_${h.FID('f',file.path)}", "${request.script_name}", '');
+                    $(document).ready(function(){
+                        var myCodeMirror = initCodeMirror("editor_${h.FID('f',file.path)}", "${request.script_name}", '');
+
+                        //inject new modes
+                        var $mimetype_select = $('#mimetype_${h.FID('f',file.path)}');
+                        $mimetype_select.each(function(){
+                            var modes_select = this;
+                            var index = 1;
+                            for(var i=0;i<CodeMirror.modeInfo.length;i++) {
+                                var m = CodeMirror.modeInfo[i];
+                                var opt = new Option(m.name, m.mime);
+                                $(opt).attr('mode', m.mode);
+                                if (m.mime == 'text/plain') {
+                                    // default plain text
+                                    $(opt).prop('selected', true);
+                                    modes_select.options[0] = opt;
+                                } else {
+                                    modes_select.options[index++] = opt;
+                                }
+                            }
+                        });
 
-                //inject new modes
-                var $modes_select = $('#mimetype_${h.FID('f',file.path)}');
-                $modes_select.each(function(){
-                    var modes_select = this;
-                    var index = 1;
-                    for(var i=0;i<CodeMirror.modeInfo.length;i++) {
-                        var m = CodeMirror.modeInfo[i];
-                        var opt = new Option(m.name, m.mime);
-                        $(opt).attr('mode', m.mode);
-                        if (m.mime == 'text/plain') {
-                            // default plain text
-                            $(opt).prop('selected', true);
-                            modes_select.options[0] = opt;
-                        } else {
-                            modes_select.options[index++] = opt;
-                        }
-                    }
-                });
+                        var $filename_input = $('#filename_${h.FID('f',file.path)}');
+                        // on select change set new mode
+                        $mimetype_select.change(function(e){
+                            var selected = e.currentTarget;
+                            var node = selected.options[selected.selectedIndex];
+                            var detected_mode = CodeMirror.findModeByMIME(node.value);
+                            setCodeMirrorMode(myCodeMirror, detected_mode);
+
+                            var proposed_ext = CodeMirror.findExtensionByMode(detected_mode);
+                            var file_data = CodeMirror.getFilenameAndExt($filename_input.val());
+                            var filename = file_data['filename'] || 'filename1';
+                            $filename_input.val(filename + '.' + proposed_ext);
+                        });
 
-                var $filename = $('#filename_${h.FID('f',file.path)}');
-                // on select change set new mode
-                $modes_select.change(function(e){
-                    var selected = e.currentTarget;
-                    var node = selected.options[selected.selectedIndex];
-                    var detected_mode = CodeMirror.findModeByMIME(node.value);
-                    setCodeMirrorMode(myCodeMirror, detected_mode);
+                        // on type the new filename set mode
+                        $filename_input.keyup(function(e){
+                            var file_data = CodeMirror.getFilenameAndExt(this.value);
+                            if(file_data['ext'] != null){
+                                var detected_mode = CodeMirror.findModeByExtension(file_data['ext']) || CodeMirror.findModeByMIME('text/plain');
 
-                    var proposed_ext = CodeMirror.findExtensionByMode(detected_mode);
-                    var file_data = CodeMirror.getFilenameAndExt($filename.val());
-                    var filename = file_data['filename'] || 'filename1';
-                    $filename.val(filename + '.' + proposed_ext);
-                });
+                                if (detected_mode){
+                                    setCodeMirrorMode(myCodeMirror, detected_mode);
+                                    $mimetype_select.val(detected_mode.mime);
+                                }
+                            }
+                        });
 
-                // on type the new filename set mode
-                $filename.keyup(function(e){
-                    var file_data = CodeMirror.getFilenameAndExt(this.value);
-                    if(file_data['ext'] != null){
-                        var detected_mode = CodeMirror.findModeByExtension(file_data['ext']) || CodeMirror.findModeByMIME('text/plain');
+                        // set mode on page load
+                        var detected_mode = CodeMirror.findModeByExtension("${file.extension}");
 
                         if (detected_mode){
                             setCodeMirrorMode(myCodeMirror, detected_mode);
-                            $modes_select.val(detected_mode.mime);
+                            $mimetype_select.val(detected_mode.mime);
                         }
-                    }
-                });
-
-                // set mode on page load
-                var detected_mode = CodeMirror.findModeByExtension("${file.extension}");
-
-                if (detected_mode){
-                    setCodeMirrorMode(myCodeMirror, detected_mode);
-                    $modes_select.val(detected_mode.mime);
-                }
-
+                    });
                 </script>
 
             %endfor
 
             <div style="padding-top: 5px">
-            ${h.submit('update',_('Update Gist'),class_="btn btn-mini btn-success")}
-            <a class="btn btn-mini" href="${h.url('gist', gist_id=c.gist.gist_access_id)}">${_('Cancel')}</a>
+            ${h.submit('update',_('Update Gist'),class_="btn btn-success")}
+            <a class="btn btn-default" href="${h.url('gist', gist_id=c.gist.gist_access_id)}">${_('Cancel')}</a>
             </div>
           ${h.end_form()}
           <script>
--- a/kallithea/templates/admin/gists/index.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/gists/index.html	Fri Nov 18 01:11:13 2016 +0100
@@ -27,14 +27,14 @@
 </%block>
 
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
         %if c.authuser.username != 'default':
         <ul class="links">
           <li>
-             <a href="${h.url('new_gist')}" class="btn btn-small btn-success"><i class="icon-plus"></i> ${_('Create New Gist')}</a>
+             <a href="${h.url('new_gist')}" class="btn btn-success btn-xs"><i class="icon-plus"></i> ${_('Create New Gist')}</a>
           </li>
         </ul>
         %endif
@@ -43,16 +43,14 @@
         % for gist in c.gists_pager:
           <div class="gist-item" style="padding:10px 20px 10px 15px">
 
-            <div class="gravatar">
-              ${h.gravatar(gist.owner.email, size=28)}
-            </div>
+            ${h.gravatar_div(gist.owner.email, size=28)}
             <div title="${gist.owner.full_contact}" class="user" style="font-size: 16px">
                 <b>${h.person(gist.owner.full_contact)}</b> /
                 <b><a href="${h.url('gist',gist_id=gist.gist_access_id)}">gist: ${gist.gist_access_id}</a></b>
             </div>
             <div style="padding: 4px 0px 0px 0px">
                 ${_('Created')} ${h.age(gist.created_on)} /
-                <span style="color: #AAA">
+                <span class="text-muted">
                   %if gist.gist_expires == -1:
                    ${_('Expires')}: ${_('Never')}
                   %else:
@@ -61,15 +59,13 @@
                 </span>
             </div>
 
-            <div style="border:0px;padding:10px 0px 0px 40px;color:#AAA">${gist.gist_description}</div>
+            <div class="text-muted" style="border:0px;padding:10px 0px 0px 40px">${gist.gist_description}</div>
           </div>
         % endfor
 
-        <div class="notification-paginator">
-          <div class="pagination-wh pagination-left">
-          ${c.gists_pager.pager('$link_previous ~2~ $link_next', **request.GET.mixed())}
-          </div>
-        </div>
+        <ul class="pagination">
+            ${c.gists_pager.pager(**request.GET.mixed())}
+        </ul>
     %else:
         <div class="table">${_('There are no gists yet')}</div>
     %endif
--- a/kallithea/templates/admin/gists/new.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/gists/new.html	Fri Nov 18 01:11:13 2016 +0100
@@ -23,9 +23,9 @@
 </%block>
 
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading">
         ${self.breadcrumbs()}
     </div>
 
@@ -33,9 +33,7 @@
         <div id="files_data">
           ${h.form(h.url('gists'), method='post',id='eform')}
             <div>
-                <div class="gravatar">
-                  ${h.gravatar(c.authuser.email, size=32)}
-                </div>
+                ${h.gravatar_div(c.authuser.email, size=32)}
                 <textarea style="resize:vertical; width:400px;border: 1px solid #ccc;border-radius: 3px;" id="description" name="description" placeholder="${_('Gist description ...')}"></textarea>
                 <div style="padding:0px 0px 0px 42px">
                 <label for='lifetime'>${_('Gist lifetime')}</label>
@@ -53,57 +51,59 @@
                 </div>
             </div>
             <div style="padding-top: 5px">
-            ${h.submit('private',_('Create Private Gist'),class_="btn btn-mini btn-success")}
-            ${h.submit('public',_('Create Public Gist'),class_="btn btn-mini")}
-            ${h.reset('reset',_('Reset'),class_="btn btn-mini")}
+            ${h.submit('private',_('Create Private Gist'),class_="btn btn-success btn-xs")}
+            ${h.submit('public',_('Create Public Gist'),class_="btn btn-default btn-xs")}
+            ${h.reset('reset',_('Reset'),class_="btn btn-default btn-xs")}
             </div>
           ${h.end_form()}
           <script type="text/javascript">
-            var myCodeMirror = initCodeMirror('editor', "${request.script_name}", '');
+            $(document).ready(function(){
+                var myCodeMirror = initCodeMirror('editor', "${request.script_name}", '');
 
-            //inject new modes
-            var $modes_select = $('#mimetype');
-            $modes_select.each(function(){
-                var modes_select = this;
-                var index = 1;
-                for(var i=0;i<CodeMirror.modeInfo.length;i++) {
-                    var m = CodeMirror.modeInfo[i];
-                    var opt = new Option(m.name, m.mime);
-                    $(opt).attr('mode', m.mode);
-                    if (m.mime == 'text/plain') {
-                        // default plain text
-                        $(opt).prop('selected', true);
-                        modes_select.options[0] = opt;
-                    } else {
-                        modes_select.options[index++] = opt;
+                //inject new modes
+                var $mimetype_select = $('#mimetype');
+                $mimetype_select.each(function(){
+                    var modes_select = this;
+                    var index = 1;
+                    for(var i=0;i<CodeMirror.modeInfo.length;i++) {
+                        var m = CodeMirror.modeInfo[i];
+                        var opt = new Option(m.name, m.mime);
+                        $(opt).attr('mode', m.mode);
+                        if (m.mime == 'text/plain') {
+                            // default plain text
+                            $(opt).prop('selected', true);
+                            modes_select.options[0] = opt;
+                        } else {
+                            modes_select.options[index++] = opt;
+                        }
                     }
-                }
-            });
+                });
 
-            var $filename = $('#filename');
-            // on select change set new mode
-            $modes_select.change(function(e){
-                var selected = e.currentTarget;
-                var node = selected.options[selected.selectedIndex];
-                var detected_mode = CodeMirror.findModeByMIME(node.value);
-                setCodeMirrorMode(myCodeMirror, detected_mode);
+                var $filename_input = $('#filename');
+                // on select change set new mode
+                $mimetype_select.change(function(e){
+                    var selected = e.currentTarget;
+                    var node = selected.options[selected.selectedIndex];
+                    var detected_mode = CodeMirror.findModeByMIME(node.value);
+                    setCodeMirrorMode(myCodeMirror, detected_mode);
 
-                var proposed_ext = CodeMirror.findExtensionByMode(detected_mode);
-                var file_data = CodeMirror.getFilenameAndExt($filename.val());
-                var filename = file_data['filename'] || 'filename1';
-                $filename.val(filename + '.' + proposed_ext);
-            });
+                    var proposed_ext = CodeMirror.findExtensionByMode(detected_mode);
+                    var file_data = CodeMirror.getFilenameAndExt($filename_input.val());
+                    var filename = file_data['filename'] || 'filename1';
+                    $filename_input.val(filename + '.' + proposed_ext);
+                });
 
-            // on type the new filename set mode
-            $filename.keyup(function(e){
-                var file_data = CodeMirror.getFilenameAndExt(this.value);
-                if(file_data['ext'] != null){
-                    var detected_mode = CodeMirror.findModeByExtension(file_data['ext']) || CodeMirror.findModeByMIME('text/plain');
-                    if (detected_mode){
-                        setCodeMirrorMode(myCodeMirror, detected_mode);
-                        $modes_select.val(detected_mode.mime);
+                // on type the new filename set mode
+                $filename_input.keyup(function(e){
+                    var file_data = CodeMirror.getFilenameAndExt(this.value);
+                    if(file_data['ext'] != null){
+                        var detected_mode = CodeMirror.findModeByExtension(file_data['ext']) || CodeMirror.findModeByMIME('text/plain');
+                        if (detected_mode){
+                            setCodeMirrorMode(myCodeMirror, detected_mode);
+                            $mimetype_select.val(detected_mode.mime);
+                        }
                     }
-                }
+                });
             });
           </script>
         </div>
--- a/kallithea/templates/admin/gists/show.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/gists/show.html	Fri Nov 18 01:11:13 2016 +0100
@@ -15,14 +15,14 @@
 </%block>
 
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
         %if c.authuser.username != 'default':
         <ul class="links">
           <li>
-              <a href="${h.url('new_gist')}" class="btn btn-small btn-success"><i class="icon-plus"></i> ${_('Create New Gist')}</a>
+              <a href="${h.url('new_gist')}" class="btn btn-success btn-sm"><i class="icon-plus"></i> ${_('Create New Gist')}</a>
           </li>
         </ul>
         %endif
@@ -34,45 +34,43 @@
                     <div class="stats">
                         <div class="left" style="margin: -4px 0px 0px 0px">
                           %if c.gist.gist_type == 'public':
-                            <div class="btn btn-mini btn-success disabled">${_('Public Gist')}</div>
+                            <div class="label label-success">${_('Public Gist')}</div>
                           %else:
-                            <div class="btn btn-mini btn-warning disabled">${_('Private Gist')}</div>
+                            <div class="label label-warning">${_('Private Gist')}</div>
                           %endif
                         </div>
                         <div class="left item">
                             ${c.gist.gist_description}
                         </div>
-                        <div class="left item last" style="color: #AAA">
+                        <div class="left item last text-muted">
                          %if c.gist.gist_expires == -1:
                           ${_('Expires')}: ${_('Never')}
                          %else:
                           ${_('Expires')}: ${h.age(h.time_to_datetime(c.gist.gist_expires))}
                          %endif
-                       </div>
+                        </div>
 
-                       %if h.HasPermissionAny('hg.admin')() or c.gist.gist_owner == c.authuser.user_id:
+                       %if h.HasPermissionAny('hg.admin')() or c.gist.owner_id == c.authuser.user_id:
                         <div style="float:right">
-                            ${h.form(url('gist', gist_id=c.gist.gist_id),method='delete')}
-                                ${h.submit('remove_gist', _('Delete'),class_="btn btn-mini btn-danger",onclick="return confirm('"+_('Confirm to delete this Gist')+"');")}
+                            ${h.form(url('gist_delete', gist_id=c.gist.gist_id))}
+                                ${h.submit('remove_gist', _('Delete'),class_="btn btn-danger btn-xs",onclick="return confirm('"+_('Confirm to delete this Gist')+"');")}
                             ${h.end_form()}
                         </div>
                        %endif
                         <div class="buttons">
                           ## only owner should see that
-                          %if h.HasPermissionAny('hg.admin')() or c.gist.gist_owner == c.authuser.user_id:
-                            ${h.link_to(_('Edit'),h.url('edit_gist', gist_id=c.gist.gist_access_id),class_="btn btn-mini")}
+                          %if h.HasPermissionAny('hg.admin')() or c.gist.owner_id == c.authuser.user_id:
+                            ${h.link_to(_('Edit'),h.url('edit_gist', gist_id=c.gist.gist_access_id),class_="btn btn-default btn-xs")}
                           %endif
-                          ${h.link_to(_('Show as Raw'),h.url('formatted_gist', gist_id=c.gist.gist_access_id, format='raw'),class_="btn btn-mini")}
+                          ${h.link_to(_('Show as Raw'),h.url('formatted_gist', gist_id=c.gist.gist_access_id, format='raw'),class_="btn btn-default btn-xs")}
                         </div>
                     </div>
 
                     <div class="author">
-                        <div class="gravatar">
-                          ${h.gravatar(h.email_or_none(c.file_changeset.author), size=16)}
-                        </div>
+                        ${h.gravatar_div(h.email_or_none(c.file_changeset.author), size=16)}
                         <div title="${c.file_changeset.author}" class="user">${h.person(c.file_changeset.author)} - ${_('created')} ${h.age(c.file_changeset.date)}</div>
                     </div>
-                    <div class="commit">${h.urlify_commit(c.file_changeset.message,c.repo_name)}</div>
+                    <div class="commit">${h.urlify_text(c.file_changeset.message,c.repo_name)}</div>
                 </div>
             </div>
 
@@ -83,7 +81,7 @@
                     <a href="${c.gist.gist_url()}">¶</a>
                     <b style="margin:0px 0px 0px 4px">${h.safe_unicode(file.path)}</b>
                     <div style="float:right; margin: -5px">
-                       ${h.link_to(_('Show as raw'),h.url('formatted_gist_file', gist_id=c.gist.gist_access_id, format='raw', revision=file.changeset.raw_id, f_path=h.safe_unicode(file.path)),class_="btn btn-mini")}
+                       ${h.link_to(_('Show as raw'),h.url('formatted_gist_file', gist_id=c.gist.gist_access_id, format='raw', revision=file.changeset.raw_id, f_path=h.safe_unicode(file.path)),class_="btn btn-default btn-xs")}
                     </div>
                 </div>
                 <div class="code-body">
--- a/kallithea/templates/admin/my_account/my_account.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/my_account/my_account.html	Fri Nov 18 01:11:13 2016 +0100
@@ -14,31 +14,29 @@
 </%block>
 
 <%def name="main()">
-<div class="box" style="overflow:auto">
-    <div class="title">
+<div class="panel panel-primary" style="overflow:auto">
+    <div class="panel-heading">
         ${self.breadcrumbs()}
     </div>
 
     ##main
     <div style="width: 150px; float:left">
         <ul class="nav nav-pills nav-stacked">
-          <li>
-           <div class="gravatar_box" style="height: 26px">
-               <div class="gravatar" style="float: left">
-                 ${h.gravatar(c.user.email)}
-               </div>
-               <div class="truncate" style="margin:10px 0px 10px 0px; color:#5f5f5f; float:left; width: 100px">
-                <strong>${c.user.username}</strong>
-               </div>
-           </div>
-          </li>
-          <li class="${'active' if c.active=='profile' else ''}"><a href="${h.url('my_account')}">${_('Profile')}</a></li>
-          <li class="${'active' if c.active=='emails' else ''}"><a href="${h.url('my_account_emails')}">${_('Email Addresses')}</a></li>
-          <li class="${'active' if c.active=='password' else ''}"><a href="${h.url('my_account_password')}">${_('Password')}</a></li>
-          <li class="${'active' if c.active=='api_keys' else ''}"><a href="${h.url('my_account_api_keys')}">${_('API Keys')}</a></li>
-          <li class="${'active' if c.active=='repos' else ''}"><a href="${h.url('my_account_repos')}">${_('Owned Repositories')}</a></li>
-          <li class="${'active' if c.active=='watched' else ''}"><a href="${h.url('my_account_watched')}">${_('Watched Repositories')}</a></li>
-          <li class="${'active' if c.active=='perms' else ''}"><a href="${h.url('my_account_perms')}">${_('Show Permissions')}</a></li>
+            <li>
+              <div class="gravatar_box" style="height: 26px">
+                ${h.gravatar_div(c.user.email, div_style="float: left")}
+                <div class="truncate" style="margin:10px 0px 10px 0px; color:#5f5f5f; float:left; width: 100px">
+                    <strong>${c.user.username}</strong>
+                </div>
+              </div>
+            </li>
+            <li class="${'active' if c.active=='profile' else ''}"><a href="${h.url('my_account')}">${_('Profile')}</a></li>
+            <li class="${'active' if c.active=='emails' else ''}"><a href="${h.url('my_account_emails')}">${_('Email Addresses')}</a></li>
+            <li class="${'active' if c.active=='password' else ''}"><a href="${h.url('my_account_password')}">${_('Password')}</a></li>
+            <li class="${'active' if c.active=='api_keys' else ''}"><a href="${h.url('my_account_api_keys')}">${_('API Keys')}</a></li>
+            <li class="${'active' if c.active=='repos' else ''}"><a href="${h.url('my_account_repos')}">${_('Owned Repositories')}</a></li>
+            <li class="${'active' if c.active=='watched' else ''}"><a href="${h.url('my_account_watched')}">${_('Watched Repositories')}</a></li>
+            <li class="${'active' if c.active=='perms' else ''}"><a href="${h.url('my_account_perms')}">${_('Show Permissions')}</a></li>
         </ul>
     </div>
 
--- a/kallithea/templates/admin/my_account/my_account_api_keys.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/my_account/my_account_api_keys.html	Fri Nov 18 01:11:13 2016 +0100
@@ -3,14 +3,14 @@
     <tr>
         <td style="width: 450px"><div class="truncate autoexpand" style="width:120px;font-size:16px;font-family: monospace">${c.user.api_key}</div></td>
         <td>
-            <span class="btn btn-mini btn-success disabled">${_('Built-in')}</span>
+            <span class="label label-success">${_('Built-in')}</span>
         </td>
         <td>${_('Expires')}: ${_('Never')}</td>
         <td>
-            ${h.form(url('my_account_api_keys'),method='delete')}
+            ${h.form(url('my_account_api_keys_delete'))}
                 ${h.hidden('del_api_key',c.user.api_key)}
                 ${h.hidden('del_api_key_builtin',1)}
-                <button class="btn btn-mini btn-danger" type="submit"
+                <button class="btn btn-danger btn-xs" type="submit"
                         onclick="return confirm('${_('Confirm to reset this API key: %s') % c.user.api_key}');">
                     ${_('Reset')}
                 </button>
@@ -34,9 +34,9 @@
                  %endif
             </td>
             <td>
-                ${h.form(url('my_account_api_keys'),method='delete')}
+                ${h.form(url('my_account_api_keys_delete'))}
                     ${h.hidden('del_api_key',api_key.api_key)}
-                    <button class="btn btn-mini btn-danger" type="submit"
+                    <button class="btn btn-danger btn-xs" type="submit"
                             onclick="return confirm('${_('Confirm to remove this API key: %s') % api_key.api_key}');">
                         <i class="icon-minus-circled"></i>
                         ${_('Remove')}
@@ -55,19 +55,19 @@
     ${h.form(url('my_account_api_keys'), method='post')}
     <div class="form">
         <!-- fields -->
-        <div class="fields">
-             <div class="field">
-                <div class="label">
-                    <label for="description">${_('New API key')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label for="description">${_('New API key')}:</label>
                 <div class="input">
                     ${h.text('description', class_='medium', placeholder=_('Description'))}
                     ${h.select('lifetime', '', c.lifetime_options)}
                 </div>
-             </div>
-            <div class="buttons">
-              ${h.submit('save',_('Add'),class_="btn")}
-              ${h.reset('reset',_('Reset'),class_="btn")}
+            </div>
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Add'),class_="btn btn-default")}
+                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/admin/my_account/my_account_emails.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/my_account/my_account_emails.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,23 +1,27 @@
 <div class="emails_wrap">
   <table class="noborder">
     <tr>
-    <td><div class="gravatar">${h.gravatar(c.user.email, size=16)}</div></td>
+    %if c.visual.use_gravatar:
+    <td>${h.gravatar_div(c.user.email, size=16)}</td>
+    %endif
     <td><div class="email">${c.user.email}</div></td>
     <td>
-        <span class="btn btn-mini btn-success disabled">${_('Primary')}</span>
+        <span class="label label-success">${_('Primary')}</span>
     </td>
     </tr>
     %if c.user_email_map:
         %for em in c.user_email_map:
           <tr>
-            <td><div class="gravatar">${h.gravatar(em.email, size=16)}</div></td>
+            %if c.visual.use_gravatar:
+            <td>${h.gravatar_div(em.email, size=16)}</td>
+            %endif
             <td><div class="email">${em.email}</div></td>
             <td>
-                ${h.form(url('my_account_emails'),method='delete')}
+                ${h.form(url('my_account_emails_delete'))}
                     ${h.hidden('del_email_id',em.email_id)}
                     <i class="icon-minus-circled" style="color:#FF4444"></i>
                     ${h.submit('remove_',_('Delete'),id="remove_email_%s" % em.email_id,
-                    class_="action_button", onclick="return  confirm('"+_('Confirm to delete this email: %s') % em.email+"');")}
+                    class_="btn btn-default btn-xs", onclick="return  confirm('"+_('Confirm to delete this email: %s') % em.email+"');")}
                 ${h.end_form()}
             </td>
           </tr>
@@ -32,18 +36,18 @@
     ${h.form(url('my_account_emails'), method='post')}
     <div class="form">
         <!-- fields -->
-        <div class="fields">
-             <div class="field">
-                <div class="label">
-                    <label for="new_email">${_('New email address')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label class="control-label" for="new_email">${_('New email address')}:</label>
                 <div class="input">
                     ${h.text('new_email', class_='medium')}
                 </div>
-             </div>
-            <div class="buttons">
-              ${h.submit('save',_('Add'),class_="btn")}
-              ${h.reset('reset',_('Reset'),class_="btn")}
+            </div>
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Add'),class_="btn btn-default")}
+                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/admin/my_account/my_account_password.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/my_account/my_account_password.html	Fri Nov 18 01:11:13 2016 +0100
@@ -4,39 +4,35 @@
 
 ${h.form(url('my_account_password'), method='post')}
 <div class="form">
-    <div class="fields">
-     <div class="field">
-        <div class="label">
-            <label for="current_password">${_('Current password')}:</label>
-        </div>
+  <div class="form-horizontal">
+    <div class="form-group">
+        <label class="control-label" for="current_password">${_('Current password')}:</label>
         <div class="input">
             ${h.password('current_password',class_='medium')}
         </div>
-     </div>
+    </div>
 
-     <div class="field">
-        <div class="label">
-            <label for="new_password">${_('New password')}:</label>
-        </div>
+    <div class="form-group">
+        <label class="control-label" for="new_password">${_('New password')}:</label>
         <div class="input">
             ${h.password('new_password',class_='medium')}
         </div>
-     </div>
+    </div>
 
-     <div class="field">
-        <div class="label">
-            <label for="new_password_confirmation">${_('Confirm new password')}:</label>
-        </div>
+    <div class="form-group">
+        <label class="control-label" for="new_password_confirmation">${_('Confirm new password')}:</label>
         <div class="input">
             ${h.password('new_password_confirmation',class_='medium')}
         </div>
-     </div>
+    </div>
 
+    <div class="form-group">
         <div class="buttons">
-          ${h.submit('save',_('Save'),class_="btn")}
-          ${h.reset('reset',_('Reset'),class_="btn")}
+            ${h.submit('save',_('Save'),class_="btn btn-default")}
+            ${h.reset('reset',_('Reset'),class_="btn btn-default")}
         </div>
     </div>
+  </div>
 </div>
 ${h.end_form()}
 
--- a/kallithea/templates/admin/my_account/my_account_profile.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/my_account/my_account_profile.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,64 +1,55 @@
 ${h.form(url('my_account'), method='post')}
     <div class="form">
+        <div class="form-horizontal">
+            <div class="form-group">
+                <div class="gravatar_box">
+                    ${h.gravatar_div(c.user.email)}
+                    <p>
+                    %if c.visual.use_gravatar:
+                        <strong>${_('Change your avatar at')} <a href="http://gravatar.com">gravatar.com</a></strong>
+                        <br/>${_('Using')} ${c.user.email}
+                    %else:
+                        <strong>${_('Avatars are disabled')}</strong>
+                        <br/>${c.user.email or _('Missing email, please update your user email address.')}
+                        [${_('Current IP')}: ${c.ip_addr}]
+                    %endif
+                    </p>
+                </div>
+            </div>
 
-         <div class="field">
-           <div class="gravatar_box">
-               <div class="gravatar">
-                 ${h.gravatar(c.user.email)}
-               </div>
-                <p>
-                %if c.visual.use_gravatar:
-                <strong>${_('Change your avatar at')} <a href="http://gravatar.com">gravatar.com</a></strong>
-                <br/>${_('Using')} ${c.user.email}
-                %else:
-                <strong>${_('Avatars are disabled')}</strong>
-                <br/>${c.user.email or _('Missing email, please update your user email address.')}
-                    [${_('Current IP')}: ${c.ip_addr}]
-                %endif
-               </p>
-           </div>
-         </div>
+            <div class="form-group">
+                <label class="control-label" for="username">${_('Username')}:</label>
+                <div class="input">
+                    ${h.text('username',class_='medium', readonly=c.readonly('username'))}
+                </div>
+            </div>
 
-        <div class="fields">
-             <div class="field">
-                <div class="label">
-                    <label for="username">${_('Username')}:</label>
-                </div>
-                <div class="input">
-                  ${h.text('username',class_='medium', readonly=c.readonly('username'))}
-                </div>
-             </div>
-
-             <div class="field">
-                <div class="label">
-                    <label for="name">${_('First Name')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="firstname">${_('First Name')}:</label>
                 <div class="input">
                     ${h.text('firstname',class_="medium", readonly=c.readonly('firstname'))}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label">
-                    <label for="lastname">${_('Last Name')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="lastname">${_('Last Name')}:</label>
                 <div class="input">
                     ${h.text('lastname',class_="medium", readonly=c.readonly('lastname'))}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label">
-                    <label for="email">${_('Email')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="email">${_('Email')}:</label>
                 <div class="input">
                     ${h.text('email',class_="medium", readonly=c.readonly('email'))}
                 </div>
-             </div>
+            </div>
 
-            <div class="buttons">
-              ${h.submit('save',_('Save'),class_="btn")}
-              ${h.reset('reset',_('Reset'),class_="btn")}
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Save'),class_="btn btn-default")}
+                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/admin/my_account/my_account_repos.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/my_account/my_account_repos.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,107 +1,22 @@
 <div style="font-size: 20px; color: #666666; padding: 0px 0px 10px 0px">${_('Repositories You Own')}</div>
-<input class="q_filter_box" id="q_filter" size="15" type="text" name="filter"
-       placeholder="${_('quick filter...')}" value=""/>
 
-<div class="table-grid table yui-skin-sam" id="repos_list_wrap"></div>
-<div id="user-paginator" style="padding: 0px 0px 0px 20px"></div>
+<div class="table">
+    <table id="datatable_list_wrap"></table>
+</div>
 
 <script>
-function table_renderer(data){
-    var myDataSource = new YAHOO.util.DataSource(data);
-    myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
-
-    myDataSource.responseSchema = {
-        resultsList: "records",
-        fields: [
-            {key:"menu"},
-            {key:"raw_name"},
-            {key:"name"},
-            {key:"last_changeset"},
-            {key:"last_rev_raw"},
-            {key:"action"}
-            ]
-        };
-    myDataSource.doBeforeCallback = function(req,raw,res,cb) {
-        // This is the filter function
-        var data     = res.results || [],
-            filtered = [],
-            i,l;
-
-        if (req) {
-            req = req.toLowerCase();
-            for (i = 0; i<data.length; i++) {
-                var pos = data[i].raw_name.toLowerCase().indexOf(req);
-                if (pos != -1) {
-                    filtered.push(data[i]);
-                }
-            }
-            res.results = filtered;
-        }
-        return res;
-    }
-
-      // main table sorting
-      var myColumnDefs = [
-          {key:"menu",label:"",sortable:false,className:"quick_repo_menu hidden"},
-          {key:"name",label:"${_('Name')}",sortable:true,
-              sortOptions: { sortFunction: nameSort }},
-          {key:"last_changeset",label:"${_('Tip')}",sortable:true,
-              sortOptions: { sortFunction: revisionSort }},
-          {key:"action",label:"${_('Action')}",sortable:false}
-      ];
-
-      var myDataTable = new YAHOO.widget.DataTable("repos_list_wrap", myColumnDefs, myDataSource,{
-        sortedBy:{key:"name",dir:"asc"},
-        paginator: YUI_paginator(50, ['user-paginator']),
-
-        MSG_SORTASC:"${_('Click to sort ascending')}",
-        MSG_SORTDESC:"${_('Click to sort descending')}",
-        MSG_EMPTY:"${_('No records found.')}",
-        MSG_ERROR:"${_('Data error.')}",
-        MSG_LOADING:"${_('Loading...')}"
-      }
-      );
-      myDataTable.subscribe('postRenderEvent',function(oArgs) {
-          tooltip_activate();
-          quick_repo_menu();
-      });
-
-      var filterTimeout = null;
-
-      updateFilter = function() {
-          // Reset timeout
-          filterTimeout = null;
-
-          // Reset sort
-          var state = myDataTable.getState();
-          state.sortedBy = {key:'name', dir:YAHOO.widget.DataTable.CLASS_ASC};
-
-          // Get filtered data
-          myDataSource.sendRequest(YUD.get('q_filter').value,{
-              success : myDataTable.onDataReturnInitializeTable,
-              failure : myDataTable.onDataReturnInitializeTable,
-              scope   : myDataTable,
-              argument: state
-          });
-
-      };
-      $('#q_filter').click(function(){
-          if(!$('#q_filter').hasClass('loaded')){
-              //TODO: load here full list later to do search within groups
-              $('#q_filter').addClass('loaded');
-          }
-      });
-
-      $('#q_filter').keyup(function(){
-          clearTimeout(filterTimeout);
-          filterTimeout = setTimeout(updateFilter,600);
-      });
-
-      if($('#q_filter').val()) {
-          updateFilter();
-      }
-
-    }
-
-table_renderer(${c.data |n});
+  var data = ${c.data|n};
+  var myDataTable = $("#datatable_list_wrap").DataTable({
+        data: data.records,
+        columns: [
+            {data: "raw_name", "visible": false, searchable: false},
+            {data: "name", "orderData": 1, title: "${_('Name')}"},
+            {data: "last_rev_raw", "visible": false, searchable: false},
+            {data: "last_changeset", "orderData": 3, title: "${_('Tip')}", searchable: false},
+            {data: "action", title: "${_('Action')}", sortable: false, searchable: false}
+        ],
+        order: [[2, "asc"]],
+        dom: '<"dataTables_left"f><"dataTables_right"ilp>t',
+        pageLength: 100
+    });
 </script>
--- a/kallithea/templates/admin/my_account/my_account_watched.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/my_account/my_account_watched.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,107 +1,21 @@
 <div style="font-size: 20px; color: #666666; padding: 0px 0px 10px 0px">${_('Repositories You are Watching')}</div>
-<input class="q_filter_box" id="q_filter" size="15" type="text" name="filter"
-       placeholder="${_('quick filter...')}" value=""/>
 
-<div class="table-grid table yui-skin-sam" id="repos_list_wrap"></div>
-<div id="user-paginator" style="padding: 0px 0px 0px 20px"></div>
+<div class="table">
+    <table id="datatable_list_wrap"></table>
+</div>
 
 <script>
-function table_renderer(data){
-    var myDataSource = new YAHOO.util.DataSource(data);
-    myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
-
-    myDataSource.responseSchema = {
-        resultsList: "records",
-        fields: [
-            {key:"menu"},
-            {key:"raw_name"},
-            {key:"name"},
-            {key:"last_changeset"},
-            {key:"last_rev_raw"},
-            {key:"action"}
-            ]
-        };
-    myDataSource.doBeforeCallback = function(req,raw,res,cb) {
-        // This is the filter function
-        var data     = res.results || [],
-            filtered = [],
-            i,l;
-
-        if (req) {
-            req = req.toLowerCase();
-            for (i = 0; i<data.length; i++) {
-                var pos = data[i].raw_name.toLowerCase().indexOf(req);
-                if (pos != -1) {
-                    filtered.push(data[i]);
-                }
-            }
-            res.results = filtered;
-        }
-        return res;
-    }
-
-      // main table sorting
-      var myColumnDefs = [
-          {key:"menu",label:"",sortable:false,className:"quick_repo_menu hidden"},
-          {key:"name",label:"${_('Name')}",sortable:true,
-              sortOptions: { sortFunction: nameSort }},
-          {key:"last_changeset",label:"${_('Tip')}",sortable:true,
-              sortOptions: { sortFunction: revisionSort }},
-          {key:"action",label:"${_('Action')}",sortable:false}
-      ];
-
-      var myDataTable = new YAHOO.widget.DataTable("repos_list_wrap", myColumnDefs, myDataSource,{
-        sortedBy:{key:"name",dir:"asc"},
-        paginator: YUI_paginator(50, ['user-paginator']),
-
-        MSG_SORTASC:"${_('Click to sort ascending')}",
-        MSG_SORTDESC:"${_('Click to sort descending')}",
-        MSG_EMPTY:"${_('No records found.')}",
-        MSG_ERROR:"${_('Data error.')}",
-        MSG_LOADING:"${_('Loading...')}"
-      }
-      );
-      myDataTable.subscribe('postRenderEvent',function(oArgs) {
-          tooltip_activate();
-          quick_repo_menu();
-      });
-
-      var filterTimeout = null;
-
-      updateFilter = function() {
-          // Reset timeout
-          filterTimeout = null;
-
-          // Reset sort
-          var state = myDataTable.getState();
-          state.sortedBy = {key:'name', dir:YAHOO.widget.DataTable.CLASS_ASC};
-
-          // Get filtered data
-          myDataSource.sendRequest(YUD.get('q_filter').value,{
-              success : myDataTable.onDataReturnInitializeTable,
-              failure : myDataTable.onDataReturnInitializeTable,
-              scope   : myDataTable,
-              argument: state
-          });
-
-      };
-      $('#q_filter').click(function(){
-          if(!$('#q_filter').hasClass('loaded')){
-              //TODO: load here full list later to do search within groups
-              $('#q_filter').addClass('loaded');
-          }
-      });
-
-      $('#q_filter').keyup(function(){
-          clearTimeout(filterTimeout);
-          filterTimeout = setTimeout(updateFilter,600);
-      });
-
-      if($('#q_filter').val()) {
-          updateFilter();
-      }
-
-    }
-
-table_renderer(${c.data |n});
+  var data = ${c.data|n};
+  var myDataTable = $("#datatable_list_wrap").DataTable({
+        data: data.records,
+        columns: [
+            {data: "raw_name", "visible": false, searchable: false},
+            {data: "name", "orderData": 1, title: "${_('Name')}"},
+            {data: "last_rev_raw", "visible": false, searchable: false},
+            {data: "last_changeset", "orderData": 3, title: "${_('Tip')}", searchable: false},
+        ],
+        order: [[2, "asc"]],
+        dom: '<"dataTables_left"f><"dataTables_right"ilp>t',
+        pageLength: 100
+    });
 </script>
--- a/kallithea/templates/admin/notifications/notifications.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/notifications/notifications.html	Fri Nov 18 01:11:13 2016 +0100
@@ -14,36 +14,37 @@
 </%block>
 
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading">
         ${self.breadcrumbs()}
     </div>
 
-      <div style="padding:14px 18px;text-align: right;float:left">
-      <span id='all' class="btn btn-small"><a href="${h.url.current()}">${_('All')}</a></span>
-      <span id='comment' class="btn btn-small"><a href="${h.url.current(type=c.comment_type)}">${_('Comments')}</a></span>
-      <span id='pull_request' class="btn btn-small"><a href="${h.url.current(type=c.pull_request_type)}">${_('Pull Requests')}</a></span>
-      </div>
-      %if c.notifications:
-      <div style="padding:14px 18px;text-align: right;float:right">
-      <span id='mark_all_read' class="btn btn-small">${_('Mark All Read')}</span>
-      </div>
-      %endif
-  <div id='notification_data'>
-    <%include file='notifications_data.html'/>
-  </div>
+    <div style="padding:14px 18px;text-align: right;float:left">
+            <span id='all' class="btn btn-default btn-sm"><a href="${h.url.current()}">${_('All')}</a></span>
+            <span id='comment' class="btn btn-default btn-sm"><a href="${h.url.current(type=c.comment_type)}">${_('Comments')}</a></span>
+            <span id='pull_request' class="btn btn-default btn-sm"><a href="${h.url.current(type=c.pull_request_type)}">${_('Pull Requests')}</a></span>
+    </div>
+    %if c.notifications:
+        <div style="padding:14px 18px;text-align: right;float:right">
+            <span id='mark_all_read' class="btn btn-default btn-sm">${_('Mark All Read')}</span>
+        </div>
+    %endif
+    <div id='notification_data'>
+        <%include file='notifications_data.html'/>
+    </div>
 </div>
 <script type="text/javascript">
-var url_action = "${url('notification', notification_id='__NOTIFICATION_ID__')}";
+var url_delete = "${url('notification_delete', notification_id='__NOTIFICATION_ID__')}";
+var url_read = "${url('notification_update', notification_id='__NOTIFICATION_ID__')}";
 var run = function(){
   $('.delete-notification').click(function(e){
     var notification_id = e.currentTarget.id;
-    deleteNotification(url_action,notification_id);
+    deleteNotification(url_delete,notification_id);
   });
   $('.read-notification').click(function(e){
     var notification_id = e.currentTarget.id;
-    readNotification(url_action,notification_id);
+    readNotification(url_read,notification_id);
   });
 }
 run();
--- a/kallithea/templates/admin/notifications/notifications_data.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/notifications/notifications_data.html	Fri Nov 18 01:11:13 2016 +0100
@@ -4,37 +4,31 @@
 unread = lambda n:{False:'unread'}.get(n)
 %>
 
-
-<div class="notification-list  notification-table">
+<div class="notification-list notification-table">
 %for notification in c.notifications:
   <div id="notification_${notification.notification.notification_id}" class="container ${unread(notification.read)}">
     <div class="notification-header">
-      <div class="gravatar">
-        ${h.gravatar(notification.notification.created_by_user.email, size=24)}
-      </div>
-      <div class="desc ${unread(notification.read)}">
-      <a href="${url('notification', notification_id=notification.notification.notification_id)}">${notification.notification.description}</a>
-
-      </div>
-      <div class="delete-notifications">
-        <span id="${notification.notification.notification_id}" class="delete-notification"><i class="icon-minus-circled" id="yui-gen24" style="color: #b94a48; padding: 2px;"></i></span>
-      </div>
+      ${h.gravatar_div(notification.notification.created_by_user.email, size=24)}
+      <span class="desc ${unread(notification.read)}">
+        <a href="${url('notification', notification_id=notification.notification.notification_id)}">${notification.notification.description}</a>
+      </span>
+      <span class="delete-notifications">
+        <span id="${notification.notification.notification_id}" class="delete-notification"><i class="icon-minus-circled" style="color: #b94a48; padding: 2px;"></i></span>
+      </span>
       %if not notification.read:
-      <div class="read-notifications">
-        <span id="${notification.notification.notification_id}" class="read-notification"><i class="icon-ok" id="yui-gen24" style="color: #4CBB17; padding: 2px;"></i></span>
-      </div>
+      <span class="read-notifications">
+        <span id="${notification.notification.notification_id}" class="read-notification"><i class="icon-ok" style="color: #4CBB17; padding: 2px;"></i></span>
+      </span>
       %endif
     </div>
-        <div class="notification-subject"></div>
+    <div class="notification-subject"></div>
   </div>
 %endfor
 </div>
 
-<div class="notification-paginator">
-  <div class="pagination-wh pagination-left">
-  ${c.notifications.pager('$link_previous ~2~ $link_next',controller='admin/notifications',**request.GET.mixed())}
-  </div>
-</div>
+<ul class="pagination">
+    ${c.notifications.pager(controller='admin/notifications', **request.GET.mixed())}
+</ul>
 
 %else:
     <div class="table">${_('No notifications here yet')}</div>
--- a/kallithea/templates/admin/notifications/show_notification.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/notifications/show_notification.html	Fri Nov 18 01:11:13 2016 +0100
@@ -16,35 +16,33 @@
 </%block>
 
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading">
         ${self.breadcrumbs()}
     </div>
     <div class="table">
       <div id="notification_${c.notification.notification_id}">
         <div class="notification-header">
-          <div class="gravatar">
-            ${h.gravatar(c.notification.created_by_user.email, size=24)}
-          </div>
-          <div class="desc">
+          ${h.gravatar_div(c.notification.created_by_user.email, size=24)}
+          <span class="desc">
               ${c.notification.description}
-          </div>
-          <div class="delete-notifications">
-            <span id="${c.notification.notification_id}" class="delete-notification action"><i class="icon-minus-circled" id="yui-gen24"></i></span>
-          </div>
+          </span>
+          <span class="delete-notifications">
+            <span id="${c.notification.notification_id}" class="delete-notification action"><i class="icon-minus-circled"></i></span>
+          </span>
         </div>
         <div class="notification-body">
-        <div class="notification-subject">${h.literal(c.notification.subject)}</div>
-        %if c.notification.body:
-            ${h.rst_w_mentions(c.notification.body)}
-        %endif
+            <div class="notification-subject">${h.literal(c.notification.subject)}</div>
+            %if c.notification.body:
+                ${h.render_w_mentions(c.notification.body)}
+            %endif
         </div>
       </div>
     </div>
 </div>
 <script type="text/javascript">
-var url = "${url('notification', notification_id='__NOTIFICATION_ID__')}";
+var url = "${url('notification_delete', notification_id='__NOTIFICATION_ID__')}";
 var main = "${url('notifications')}";
    $('.delete-notification').click(function(e){
        var notification_id = e.currentTarget.id;
--- a/kallithea/templates/admin/permissions/permissions.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/permissions/permissions.html	Fri Nov 18 01:11:13 2016 +0100
@@ -17,8 +17,8 @@
 
 
 <%def name="main()">
-<div class="box" style="overflow:auto">
-    <div class="title">
+<div class="panel panel-primary" style="overflow:auto">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
 
--- a/kallithea/templates/admin/permissions/permissions_globals.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/permissions/permissions_globals.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,11 +1,9 @@
 ${h.form(url('admin_permissions'), method='post')}
     <div class="form">
         <!-- fields -->
-        <div class="fields">
-            <div class="field">
-                <div class="label label-checkbox">
-                    <label for="anonymous">${_('Anonymous access')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label class="control-label" for="anonymous">${_('Anonymous access')}:</label>
                 <div class="checkboxes">
                     <div class="checkbox">
                         ${h.checkbox('anonymous',True)}
@@ -13,104 +11,88 @@
                      <span class="help-block">${h.literal(_('Allow access to Kallithea without needing to log in. Anonymous users use %s user permissions.' % (h.link_to('*default*',h.url('admin_permissions_perms')))))}</span>
                 </div>
             </div>
-            <div class="field">
-                <div class="label">
-                    <label for="default_repo_perm">${_('Repository')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="default_repo_perm">${_('Repository')}:</label>
                 <div class="select">
                     ${h.select('default_repo_perm','',c.repo_perms_choices)}
                     ${h.checkbox('overwrite_default_repo','true')}
                     <label for="overwrite_default_repo">
-                    <span class="tooltip"
-                    title="${_('All default permissions on each repository will be reset to chosen permission, note that all custom default permission on repositories will be lost')}">
+                    <span data-toggle="tooltip"
+                        title="${_('All default permissions on each repository will be reset to chosen permission, note that all custom default permission on repositories will be lost')}">
                     ${_('Apply to all existing repositories')}</span> </label>
                     <span class="help-block">${_('Permissions for the Default user on new repositories.')}</span>
                 </div>
             </div>
-            <div class="field">
-                <div class="label">
-                    <label for="default_group_perm">${_('Repository group')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="default_group_perm">${_('Repository group')}:</label>
                 <div class="select">
                     ${h.select('default_group_perm','',c.group_perms_choices)}
                     ${h.checkbox('overwrite_default_group','true')}
                     <label for="overwrite_default_group">
-                    <span class="tooltip"
-                    title="${_('All default permissions on each repository group will be reset to chosen permission, note that all custom default permission on repository groups will be lost')}">
+                    <span data-toggle="tooltip"
+                        title="${_('All default permissions on each repository group will be reset to chosen permission, note that all custom default permission on repository groups will be lost')}">
                     ${_('Apply to all existing repository groups')}</span> </label>
                     <span class="help-block">${_('Permissions for the Default user on new repository groups.')}</span>
                 </div>
             </div>
-            <div class="field">
-                <div class="label">
-                    <label for="default_group_perm">${_('User group')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="default_user_group_perm">${_('User group')}:</label>
                 <div class="select">
                     ${h.select('default_user_group_perm','',c.user_group_perms_choices)}
                     ${h.checkbox('overwrite_default_user_group','true')}
                     <label for="overwrite_default_user_group">
-                    <span class="tooltip"
-                    title="${_('All default permissions on each user group will be reset to chosen permission, note that all custom default permission on user groups will be lost')}">
+                    <span data-toggle="tooltip"
+                        title="${_('All default permissions on each user group will be reset to chosen permission, note that all custom default permission on user groups will be lost')}">
                     ${_('Apply to all existing user groups')}</span></label>
                     <span class="help-block">${_('Permissions for the Default user on new user groups.')}</span>
                 </div>
             </div>
-             <div class="field">
-                <div class="label">
-                    <label for="default_repo_create">${_('Top level repository creation')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="default_repo_create">${_('Top level repository creation')}:</label>
                 <div class="select">
                     ${h.select('default_repo_create','',c.repo_create_choices)}
                     <span class="help-block">${_('Enable this to allow non-admins to create repositories at the top level.')}</span>
                     <span class="help-block">${_('Note: This will also give all users API access to create repositories everywhere. That might change in future versions.')}</span>
                 </div>
-             </div>
-            <div class="field">
-                <div class="label label-checkbox">
-                    <label for="create_on_write">${_('Repository creation with group write access')}:</label>
-                </div>
+            </div>
+            <div class="form-group">
+                <label class="control-label" for="create_on_write">${_('Repository creation with group write access')}:</label>
                 <div class="select">
                     ${h.select('create_on_write','',c.repo_create_on_write_choices)}
                     <span class="help-block">${_('With this, write permission to a repository group allows creating repositories inside that group. Without this, group write permissions mean nothing.')}</span>
                 </div>
             </div>
-             <div class="field">
-                <div class="label">
-                    <label for="default_user_group_create">${_('User group creation')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="default_user_group_create">${_('User group creation')}:</label>
                 <div class="select">
                     ${h.select('default_user_group_create','',c.user_group_create_choices)}
                     <span class="help-block">${_('Enable this to allow non-admins to create user groups.')}</span>
                 </div>
-             </div>
-             <div class="field">
-                <div class="label">
-                    <label for="default_fork">${_('Repository forking')}:</label>
-                </div>
+            </div>
+            <div class="form-group">
+                <label class="control-label" for="default_fork">${_('Repository forking')}:</label>
                 <div class="select">
                     ${h.select('default_fork','',c.fork_choices)}
                     <span class="help-block">${_('Enable this to allow non-admins to fork repositories.')}</span>
                 </div>
-             </div>
-             <div class="field">
-                <div class="label">
-                    <label for="default_register">${_('Registration')}:</label>
-                </div>
+            </div>
+            <div class="form-group">
+                <label class="control-label" for="default_register">${_('Registration')}:</label>
                 <div class="select">
                     ${h.select('default_register','',c.register_choices)}
                 </div>
-             </div>
-             <div class="field">
-                <div class="label">
-                    <label for="default_extern_activate">${_('External auth account activation')}:</label>
-                </div>
+            </div>
+            <div class="form-group">
+                <label class="control-label" for="default_extern_activate">${_('External auth account activation')}:</label>
                 <div class="select">
                     ${h.select('default_extern_activate','',c.extern_activate_choices)}
                 </div>
-             </div>
-            <div class="buttons">
-              ${h.submit('save',_('Save'),class_="btn")}
-              ${h.reset('reset',_('Reset'),class_="btn")}
+            </div>
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Save'),class_="btn btn-default")}
+                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/admin/permissions/permissions_ips.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/permissions/permissions_ips.html	Fri Nov 18 01:11:13 2016 +0100
@@ -6,11 +6,11 @@
               <td><div class="ip">${ip.ip_addr}</div></td>
               <td><div class="ip">${h.ip_range(ip.ip_addr)}</div></td>
               <td>
-                ${h.form(url('edit_user_ips', id=c.user.user_id),method='delete')}
+                ${h.form(url('edit_user_ips_delete', id=c.user.user_id))}
                     ${h.hidden('del_ip_id',ip.ip_id)}
                     ${h.hidden('default_user', 'True')}
                     <i class="icon-minus-circled" style="color:#FF4444"></i> ${h.submit('remove_',_('Delete'),id="remove_ip_%s" % ip.ip_id,
-                    class_="action_button", onclick="return confirm('"+_('Confirm to delete this IP address: %s') % ip.ip_addr+"');")}
+                    class_="btn btn-default btn-xs", onclick="return confirm('"+_('Confirm to delete this IP address: %s') % ip.ip_addr+"');")}
                 ${h.end_form()}
               </td>
           </tr>
@@ -21,22 +21,22 @@
       </table>
 </div>
 
-${h.form(url('edit_user_ips', id=c.user.user_id),method='put')}
+${h.form(url('edit_user_ips_update', id=c.user.user_id))}
     <div class="form">
         <!-- fields -->
-        <div class="fields">
-             <div class="field">
-                <div class="label">
-                    <label for="new_ip">${_('New IP address')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label class="control-label" for="new_ip">${_('New IP address')}:</label>
                 <div class="input">
                     ${h.hidden('default_user', 'True')}
                     ${h.text('new_ip', class_='medium')}
                 </div>
-             </div>
-            <div class="buttons">
-              ${h.submit('save',_('Add'),class_="btn")}
-              ${h.reset('reset',_('Reset'),class_="btn")}
+            </div>
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Add'),class_="btn btn-default")}
+                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/admin/repo_groups/repo_group_add.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repo_groups/repo_group_add.html	Fri Nov 18 01:11:13 2016 +0100
@@ -18,55 +18,49 @@
 </%block>
 
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading">
         ${self.breadcrumbs()}
     </div>
     <!-- end box / title -->
     ${h.form(url('repos_groups'))}
     <div class="form">
         <!-- fields -->
-        <div class="fields">
-             <div class="field">
-                <div class="label">
-                    <label for="group_name">${_('Group name')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label class="control-label" for="group_name">${_('Group name')}:</label>
                 <div class="input">
                     ${h.text('group_name',class_='small')}
                 </div>
-             </div>
+            </div>
 
-            <div class="field">
-                <div class="label label-textarea">
-                    <label for="group_description">${_('Description')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="group_description">${_('Description')}:</label>
                 <div class="textarea-repo editor">
                     ${h.textarea('group_description',cols=23,rows=5,class_="medium")}
                 </div>
             </div>
 
-            <div class="field">
-                 <div class="label">
-                     <label for="group_parent_id">${_('Group parent')}:</label>
-                 </div>
-                 <div class="input">
-                     ${h.select('group_parent_id',request.GET.get('parent_group'),c.repo_groups,class_="medium")}
-                 </div>
+            <div class="form-group">
+                <label class="control-label" for="parent_group_id">${_('Group parent')}:</label>
+                <div class="input">
+                    ${h.select('parent_group_id',request.GET.get('parent_group'),c.repo_groups,class_="medium")}
+                </div>
             </div>
 
             <div id="copy_perms" class="field">
-                <div class="label label-checkbox">
-                    <label for="group_copy_permissions">${_('Copy parent group permissions')}:</label>
-                </div>
+                <label class="control-label" for="group_copy_permissions">${_('Copy parent group permissions')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('group_copy_permissions',value="True")}
                     <span class="help-block">${_('Copy permission set from parent repository group.')}</span>
                 </div>
             </div>
 
-            <div class="buttons">
-              ${h.submit('save',_('Save'),class_="btn")}
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Save'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
@@ -82,11 +76,11 @@
                 $('#copy_perms').hide();
             }
         }
-        $("#group_parent_id").select2({
+        $("#parent_group_id").select2({
             'dropdownAutoWidth': true
         });
-        setCopyPermsOption($('#group_parent_id').val());
-        $("#group_parent_id").on("change", function(e) {
+        setCopyPermsOption($('#parent_group_id').val());
+        $("#parent_group_id").on("change", function(e) {
             setCopyPermsOption(e.val);
         });
         $('#group_name').focus();
--- a/kallithea/templates/admin/repo_groups/repo_group_edit.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repo_groups/repo_group_edit.html	Fri Nov 18 01:11:13 2016 +0100
@@ -18,7 +18,7 @@
 <%def name="breadcrumbs_side_links()">
     <ul class="links">
       <li>
-          <a href="${h.url('new_repos_group', parent_group=c.repo_group.group_id)}" class="btn btn-small btn-success"><i class="icon-plus"></i> ${_('Add Child Group')}</a>
+          <a href="${h.url('new_repos_group', parent_group=c.repo_group.group_id)}" class="btn btn-success btn-xs"><i class="icon-plus"></i> ${_('Add Child Group')}</a>
       </li>
     </ul>
 </%def>
@@ -28,8 +28,8 @@
 </%block>
 
 <%def name="main()">
-<div class="box" style="overflow:auto">
-    <div class="title">
+<div class="panel panel-primary" style="overflow:auto">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
         ${self.breadcrumbs_side_links()}
     </div>
--- a/kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repo_groups/repo_group_edit_advanced.html	Fri Nov 18 01:11:13 2016 +0100
@@ -7,7 +7,7 @@
     (_('Total repositories'), c.repo_group.repositories_recursive_count, ''),
     (_('Children groups'), c.repo_group.children.count(), ''),
     (_('Created on'), h.fmt_date(c.repo_group.created_on), ''),
-    (_('Owner'), h.person(c.repo_group.user), ''),
+    (_('Owner'), h.person(c.repo_group.owner), ''),
  ]
 %>
 %for dt, dd, tt in elems:
@@ -16,8 +16,8 @@
 %endfor
 </dl>
 
-${h.form(h.url('repos_group', group_name=c.repo_group.group_name),method='delete')}
-    <button class="btn btn-small btn-danger" type="submit"
+${h.form(h.url('delete_repos_group', group_name=c.repo_group.group_name))}
+    <button class="btn btn-danger btn-sm" type="submit"
             onclick="return confirm('${ungettext('Confirm to delete this group: %s with %s repository',
           'Confirm to delete this group: %s with %s repositories',
  c.repo_group.repositories_recursive_count) % (c.repo_group.group_name, c.repo_group.repositories_recursive_count)}');">
--- a/kallithea/templates/admin/repo_groups/repo_group_edit_perms.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repo_groups/repo_group_edit_perms.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,13 +1,13 @@
-${h.form(url('edit_repo_group_perms', group_name=c.repo_group.group_name),method='put')}
+${h.form(url('edit_repo_group_perms', group_name=c.repo_group.group_name))}
 <div class="form">
-   <div class="fields">
+    <div class="fields">
         <div class="field">
             <table id="permissions_manage" class="noborder">
                 <tr>
-                    <td>${_('None')}</td>
-                    <td>${_('Read')}</td>
-                    <td>${_('Write')}</td>
-                    <td>${_('Admin')}</td>
+                    <td>${_('None')}<br />(${_('Not visible')})</td>
+                    <td>${_('Read')}<br />(${_('Visible')})</td>
+                    <td>${_('Write')}<br />(${_('Add repos')})</td>
+                    <td>${_('Admin')}<br />(${_('Add/Edit groups')})</td>
                     <td>${_('User/User Group')}</td>
                     <td></td>
                 </tr>
@@ -30,7 +30,7 @@
                         </td>
                         <td>
                           %if r2p.user.username !='default':
-                            <span style="color:#da4f49" class="action_button" onclick="ajaxActionRevoke(${r2p.user.user_id}, 'user', '${'id%s'%id(r2p.user.username)}', '${r2p.user.username}')">
+                            <span style="color:#da4f49" class="btn btn-default btn-xs" onclick="ajaxActionRevoke(${r2p.user.user_id}, 'user', '${'id%s'%id(r2p.user.username)}', '${r2p.user.username}')">
                              <i class="icon-minus-circled"></i> ${_('Revoke')}
                             </span>
                           %endif
@@ -67,7 +67,7 @@
                             %endif
                         </td>
                         <td>
-                            <span style="color:#da4f49" class="action_button" onclick="ajaxActionRevoke(${g2p.users_group.users_group_id}, 'user_group', '${'id%s'%id(g2p.users_group.users_group_name)}', '${g2p.users_group.users_group_name}')">
+                            <span style="color:#da4f49" class="btn btn-default btn-xs" onclick="ajaxActionRevoke(${g2p.users_group.users_group_id}, 'user_group', '${'id%s'%id(g2p.users_group.users_group_name)}', '${g2p.users_group.users_group_name}')">
                             <i class="icon-minus-circled"></i> ${_('Revoke')}
                             </span>
                         </td>
@@ -75,7 +75,7 @@
                 %endfor
 
                 <%
-                _tmpl = h.literal("""' \
+                _tmpl = h.literal("""'\
                     <td><input type="radio" value="group.none" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
                     <td><input type="radio" value="group.read" checked="checked" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
                     <td><input type="radio" value="group.write" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
@@ -111,16 +111,16 @@
             </table>
         </div>
         <div class="buttons">
-          ${h.submit('save',_('Save'),class_="btn")}
-          ${h.reset('reset',_('Reset'),class_="btn")}
+            ${h.submit('save',_('Save'),class_="btn btn-default")}
+            ${h.reset('reset',_('Reset'),class_="btn btn-default")}
         </div>
-   </div>
+    </div>
 </div>
 ${h.end_form()}
 
 <script type="text/javascript">
     function ajaxActionRevoke(obj_id, obj_type, field_id, obj_name) {
-        url = "${h.url('edit_repo_group_perms', group_name=c.repo_group.group_name)}";
+        url = "${h.url('edit_repo_group_perms_delete', group_name=c.repo_group.group_name)}";
         var revoke_msg = _TM['Confirm to revoke permission for {0}: {1} ?'].format(obj_type.replace('_', ' '), obj_name);
         if (confirm(revoke_msg)){
             var recursive = $('input[name=recursive]:checked').val();
--- a/kallithea/templates/admin/repo_groups/repo_group_edit_settings.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repo_groups/repo_group_edit_settings.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,56 +1,54 @@
 ## -*- coding: utf-8 -*-
-${h.form(url('repos_group',group_name=c.repo_group.group_name),method='put')}
+${h.form(url('update_repos_group',group_name=c.repo_group.group_name))}
 <div class="form">
     <!-- fields -->
-    <div class="fields">
-        <div class="field">
-            <div class="label">
-                <label for="group_name">${_('Group name')}:</label>
-            </div>
+    <div class="form-horizontal">
+        <div class="form-group">
+            <label class="control-label" for="group_name">${_('Group name')}:</label>
             <div class="input">
                 ${h.text('group_name',class_='medium')}
             </div>
         </div>
 
-        <div class="field">
-            <div class="label label-textarea">
-                <label for="group_description">${_('Description')}:</label>
-            </div>
+        <div class="form-group">
+            <label class="control-label" for="group_description">${_('Description')}:</label>
             <div class="textarea text-area editor">
                 ${h.textarea('group_description',cols=23,rows=5,class_="medium")}
             </div>
         </div>
 
-        <div class="field">
-            <div class="label">
-                <label for="group_parent_id">${_('Group parent')}:</label>
-            </div>
+        <div class="form-group">
+            <label class="control-label" for="parent_group_id">${_('Group parent')}:</label>
             <div class="input">
-                ${h.select('group_parent_id','',c.repo_groups,class_="medium")}
+                ${h.select('parent_group_id','',c.repo_groups,class_="medium")}
             </div>
         </div>
-        <div class="field">
-            <div class="label label-checkbox">
-                <label for="enable_locking">${_('Enable locking')}:</label>
-            </div>
+
+        <div class="form-group">
+            <label class="control-label" for="enable_locking">${_('Enable locking')}:</label>
             <div class="checkboxes">
                 ${h.checkbox('enable_locking',value="True")}
                 <span class="help-block">${_('Enable lock-by-pulling on group. This option will be applied to all other groups and repositories inside')}</span>
             </div>
         </div>
-        <div class="buttons">
-          ${h.submit('save',_('Save'),class_="btn")}
-          ${h.reset('reset',_('Reset'),class_="btn")}
+
+        <div class="form-group">
+            <div class="buttons">
+                ${h.submit('save',_('Save'),class_="btn btn-default")}
+                ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+            </div>
         </div>
     </div>
 </div>
 ${h.end_form()}
 
-${h.form(url('delete_repo_group', group_name=c.repo_group.group_name),method='delete')}
+${h.form(url('delete_repo_group', group_name=c.repo_group.group_name))}
 <div class="form">
-    <div class="fields">
-        <div class="field" style="border:none;color:#888">
-            ${h.submit('remove_%s' % c.repo_group.group_name,_('Remove this group'),class_="btn red",onclick="return confirm('"+_('Confirm to delete this group')+"');")}
+    <div class="form-horizontal">
+        <div class="form-group">
+            <div class="buttons">
+                ${h.submit('remove_%s' % c.repo_group.group_name,_('Remove this group'),class_="btn btn-danger",onclick="return confirm('"+_('Confirm to delete this group')+"');")}
+            </div>
         </div>
     </div>
 </div>
@@ -58,7 +56,7 @@
 
 <script>
     $(document).ready(function(){
-        $("#group_parent_id").select2({
+        $("#parent_group_id").select2({
             'dropdownAutoWidth': true
         });
     });
--- a/kallithea/templates/admin/repo_groups/repo_group_show.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repo_groups/repo_group_show.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,7 +1,7 @@
 ## -*- coding: utf-8 -*-
 <%inherit file="/base/base.html"/>
 <%block name="title">
-    ${_('%s Repository group dashboard') % c.group.group_name}
+    ${_('Repository group %s') % c.group.group_name}
 </%block>
 
 <%def name="breadcrumbs()">
--- a/kallithea/templates/admin/repo_groups/repo_groups.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repo_groups/repo_groups.html	Fri Nov 18 01:11:13 2016 +0100
@@ -6,7 +6,6 @@
 </%block>
 
 <%def name="breadcrumbs_links()">
-    <input class="q_filter_box" id="q_filter" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value=""/>
     ${h.link_to(_('Admin'),h.url('admin_home'))} &raquo; <span id="repo_group_count">0</span> ${_('Repository Groups')}
 </%def>
 
@@ -16,41 +15,39 @@
 </%block>
 
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
         <ul class="links">
             %if h.HasPermissionAny('hg.admin')():
              <li>
-               <a href="${h.url('new_repos_group')}" class="btn btn-small btn-success"><i class="icon-plus"></i> ${_('Add Repository Group')}</a>
+               <a href="${h.url('new_repos_group')}" class="btn btn-success btn-xs"><i class="icon-plus"></i> ${_('Add Repository Group')}</a>
              </li>
             %endif
         </ul>
     </div>
     <!-- end box / title -->
-    <div class="table-grid table yui-skin-sam" id="datatable_list_wrap"></div>
-    <div id="user-paginator" style="padding: 0px 0px 0px 20px"></div>
+    <div class="table">
+        <table id="datatable_list_wrap"></table>
+    </div>
 </div>
 <script>
   var data = ${c.data|n};
-  var fields = [
-    {key: "group_name"},
-    {key: "raw_name"},
-    {key: "desc"},
-    {key: "repos"},
-    {key: "owner"},
-    {key: "action"}
-  ];
-  var column_defs = [
-    {key:"group_name",label:"${_('Name')}",sortable:true, sortOptions: { sortFunction: nameSort }},
-    {key:"desc",label:"${_('Description')}",sortable:true},
-    {key:"repos",label:"${_('Number of Top-level Repositories')}",sortable:true},
-    {key:"owner",label:"${_('Owner')}",sortable:true},
-    {key:"action",label:"${_('Action')}",sortable:false}
-  ];
-  var counter = YUD.get('repo_group_count');
-  var sort_key = "group_name";
-  YUI_datatable(data, fields, column_defs, counter, sort_key, ${c.visual.admin_grid_items});
+  var myDataTable = $("#datatable_list_wrap").DataTable({
+        data: data.records,
+        columns: [
+            {data: "raw_name", visible: false, searchable: false},
+            {data: "group_name", orderData: 0, title: "${_('Name')}"},
+            {data: "desc", title: "${_('Description')}", searchable: false},
+            {data: "repos", title: "${_('Number of Top-level Repositories')}", searchable: false},
+            {data: "owner", title: "${_('Owner')}", searchable: false},
+            {data: "action", title: "${_('Action')}", sortable: false, searchable: false}
+        ],
+        drawCallback: updateRowCountCallback($("#repo_group_count")),
+        dom: '<"dataTables_left"f><"dataTables_right"ilp>t',
+        pageLength: 100
+    });
+
 </script>
 </%def>
--- a/kallithea/templates/admin/repos/repo_add.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repos/repo_add.html	Fri Nov 18 01:11:13 2016 +0100
@@ -24,9 +24,9 @@
 </%block>
 
 <%def name="main()">
-    <div class="box">
+    <div class="panel panel-primary">
         <!-- box / title -->
-        <div class="title">
+        <div class="panel-heading clearfix">
             ${self.breadcrumbs()}
         </div>
         <%include file="repo_add_base.html"/>
--- a/kallithea/templates/admin/repos/repo_add_base.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repos/repo_add_base.html	Fri Nov 18 01:11:13 2016 +0100
@@ -3,19 +3,15 @@
 ${h.form(url('repos'))}
 <div class="form">
     <!-- fields -->
-    <div class="fields">
-        <div class="field">
-            <div class="label">
-                <label for="repo_name">${_('Name')}:</label>
-            </div>
+    <div class="form-horizontal">
+        <div class="form-group">
+            <label class="control-label" for="repo_name">${_('Name')}:</label>
             <div class="input">
                 ${h.text('repo_name',class_="small")}
             </div>
          </div>
         <div id="remote_clone" class="field">
-            <div class="label">
-                <label for="clone_uri">${_('Clone remote repository')}:</label>
-            </div>
+            <label class="control-label" for="clone_uri">${_('Clone remote repository')}:</label>
             <div class="input">
                 ${h.text('clone_uri',class_="small")}
                 <span class="help-block">
@@ -23,62 +19,52 @@
                 </span>
             </div>
         </div>
-        <div class="field">
-            <div class="label label-textarea">
-                <label for="repo_description">${_('Description')}:</label>
-            </div>
+        <div class="form-group">
+            <label class="control-label" for="repo_description">${_('Description')}:</label>
             <div class="textarea-repo editor">
                 ${h.textarea('repo_description')}
                 <span class="help-block">${_('Keep it short and to the point. Use a README file for longer descriptions.')}</span>
             </div>
         </div>
-        <div class="field">
-             <div class="label">
-                 <label for="repo_group">${_('Repository group')}:</label>
-             </div>
-             <div class="input">
-                 ${h.select('repo_group',request.GET.get('parent_group'),c.repo_groups,class_="medium")}
-                 <span class="help-block">${_('Optionally select a group to put this repository into.')}</span>
-             </div>
+        <div class="form-group">
+            <label class="control-label" for="repo_group">${_('Repository group')}:</label>
+            <div class="input">
+                ${h.select('repo_group',request.GET.get('parent_group'),c.repo_groups,class_="medium")}
+                <span class="help-block">${_('Optionally select a group to put this repository into.')}</span>
+            </div>
         </div>
         <div id="copy_perms" class="field">
-            <div class="label label-checkbox">
-                <label for="repo_copy_permissions">${_('Copy parent group permissions')}:</label>
-            </div>
+            <label class="control-label" for="repo_copy_permissions">${_('Copy parent group permissions')}:</label>
             <div class="checkboxes">
                 ${h.checkbox('repo_copy_permissions',value="True")}
                 <span class="help-block">${_('Copy permission set from parent repository group.')}</span>
             </div>
         </div>
-        <div class="field">
-            <div class="label">
-                <label for="repo_type">${_('Type')}:</label>
-            </div>
+        <div class="form-group">
+            <label class="control-label" for="repo_type">${_('Type')}:</label>
             <div class="input">
                 ${h.select('repo_type','hg',c.backends,class_="small")}
                 <span class="help-block">${_('Type of repository to create.')}</span>
             </div>
         </div>
-        <div class="field">
-            <div class="label">
-                <label for="repo_landing_rev">${_('Landing revision')}:</label>
-            </div>
+        <div class="form-group">
+            <label class="control-label" for="repo_landing_rev">${_('Landing revision')}:</label>
             <div class="input">
                 ${h.select('repo_landing_rev','',c.landing_revs,class_="medium")}
                 <span class="help-block">${_('Default revision for files page, downloads, full text search index and readme generation')}</span>
             </div>
         </div>
-        <div class="field">
-            <div class="label label-checkbox">
-                <label for="repo_private">${_('Private repository')}:</label>
-            </div>
+        <div class="form-group">
+            <label class="control-label" for="repo_private">${_('Private repository')}:</label>
             <div class="checkboxes">
                 ${h.checkbox('repo_private',value="True")}
                 <span class="help-block">${_('Private repositories are only visible to people explicitly added as collaborators.')}</span>
             </div>
         </div>
-        <div class="buttons">
-          ${h.submit('add',_('Add'),class_="btn")}
+        <div class="form-group">
+            <div class="buttons">
+                ${h.submit('add',_('Add'),class_="btn btn-default")}
+            </div>
         </div>
     </div>
 </div>
--- a/kallithea/templates/admin/repos/repo_creating.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repos/repo_creating.html	Fri Nov 18 01:11:13 2016 +0100
@@ -17,26 +17,26 @@
     ${self.menu('repositories')}
 </%block>
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
 
     <div style="display:table; padding: 10px 0px; font-size: 14px;font-weight: bold;margin-right: auto;margin-left: auto">
-        ${_('Repository "%(repo_name)s" is being created, you will be redirected when this process is finished.' % {'repo_name':c.repo_name})}
+                ${_('Repository "%(repo_name)s" is being created, you will be redirected when this process is finished.' % {'repo_name':c.repo_name})}
     </div>
 
     <div id="progress" style="width: 500px;margin-left: auto; margin-right: auto">
-        <div class="progress progress-striped active">
-          <div class="progress-bar progress-bar" role="progressbar"
-               aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
-          </div>
-        </div>
+            <div class="progress progress-striped active">
+                <div class="progress-bar progress-bar" role="progressbar"
+                    aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
+                </div>
+            </div>
     </div>
     <div id="progress_error" style="display: none;">
-        <div style="font-weight: bold; color:#aa1111">
-        ${_("We're sorry but error occurred during this operation. Please check your Kallithea server logs, or contact administrator.")}
+        <div class="alert alert-danger">
+                ${_("We're sorry but error occurred during this operation. Please check your Kallithea server logs, or contact administrator.")}
         </div>
     </div>
 </div>
--- a/kallithea/templates/admin/repos/repo_edit.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repos/repo_edit.html	Fri Nov 18 01:11:13 2016 +0100
@@ -18,8 +18,8 @@
 
 <%def name="main()">
 ${self.repo_context_bar('options')}
-<div class="box" style="overflow:auto">
-    <!--<div class="title">-->
+<div class="panel panel-primary" style="overflow:auto">
+    <!--<div class="panel-heading">-->
         <!--${self.breadcrumbs()}-->
     <!--</div>-->
 
--- a/kallithea/templates/admin/repos/repo_edit_advanced.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repos/repo_edit_advanced.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,9 +1,9 @@
 <h3>${_('Parent')}</h3>
-${h.form(url('edit_repo_advanced_fork', repo_name=c.repo_info.repo_name), method='put')}
+${h.form(url('edit_repo_advanced_fork', repo_name=c.repo_info.repo_name))}
 <div class="form">
        ${h.select('id_fork_of','',c.repos_list,class_="medium")}
-       ${h.submit('set_as_fork_%s' % c.repo_info.repo_name,_('Set'),class_="btn btn-small")}
-       <div class="field" style="border:none;color:#888">
+       ${h.submit('set_as_fork_%s' % c.repo_info.repo_name,_('Set'),class_="btn btn-default btn-sm")}
+       <div class="field text-muted" style="border:none">
        <ul>
             <li>${_('''Manually set this repository as a fork of another from the list.''')}</li>
        </ul>
@@ -20,22 +20,22 @@
 </script>
 
 <h3>${_('Public Journal Visibility')}</h3>
-${h.form(url('edit_repo_advanced_journal', repo_name=c.repo_info.repo_name), method='put')}
+${h.form(url('edit_repo_advanced_journal', repo_name=c.repo_info.repo_name))}
 <div class="form">
   <div class="field">
   %if c.in_public_journal:
-    <button class="btn btn-small" type="submit">
+    <button class="btn btn-default btn-sm" type="submit">
         <i class="icon-minus"></i>
         ${_('Remove from public journal')}
     </button>
   %else:
-    <button class="btn btn-small" type="submit">
+    <button class="btn btn-default btn-sm" type="submit">
         <i class="icon-plus"></i>
         ${_('Add to Public Journal')}
     </button>
   %endif
   </div>
- <div class="field" style="border:none;color:#888">
+ <div class="field text-muted" style="border:none">
  <ul>
       <li>${_('All actions done in this repository will be visible to everyone in the public journal.')}</li>
  </ul>
@@ -44,11 +44,11 @@
 ${h.end_form()}
 
 <h3>${_('Change Locking')}</h3>
-${h.form(url('edit_repo_advanced_locking', repo_name=c.repo_info.repo_name), method='put')}
+${h.form(url('edit_repo_advanced_locking', repo_name=c.repo_info.repo_name))}
 <div class="form">
       %if c.repo_info.locked[0]:
         ${h.hidden('set_unlock', '1')}
-        <button class="btn btn-small" type="submit"
+        <button class="btn btn-default btn-sm" type="submit"
                 onclick="return confirm('${_('Confirm to unlock repository.')}');">
             <i class="icon-lock-open-alt"></i>
             ${_('Unlock Repository')}
@@ -56,14 +56,14 @@
        ${_('Locked by %s on %s') % (h.person_by_id(c.repo_info.locked[0]),h.fmt_date(h.time_to_datetime(c.repo_info.locked[1])))}
       %else:
         ${h.hidden('set_lock', '1')}
-        <button class="btn btn-small" type="submit"
+        <button class="btn btn-default btn-sm" type="submit"
                 onclick="return confirm('${_('Confirm to lock repository.')}');">
             <i class="icon-lock"></i>
             ${_('Lock Repository')}
         </button>
         ${_('Repository is not locked')}
       %endif
-   <div class="field" style="border:none;color:#888">
+   <div class="field text-muted" style="border:none">
    <ul>
         <li>${_('Force locking on the repository. Works only when anonymous access is disabled. Triggering a pull locks the repository.  The user who is pulling locks the repository; only the user who pulled and locked it can unlock it by doing a push.')}
         </li>
@@ -73,9 +73,9 @@
 ${h.end_form()}
 
 <h3>${_('Delete')}</h3>
-${h.form(url('delete_repo', repo_name=c.repo_name), method='delete')}
+${h.form(url('delete_repo', repo_name=c.repo_name))}
 <div class="form">
-    <button class="btn btn-small btn-danger" type="submit"
+    <button class="btn btn-danger btn-sm" type="submit"
             onclick="return confirm('${_('Confirm to delete this repository: %s') % c.repo_name}');">
         <i class="icon-minus-circled"></i>
         ${_('Delete this Repository')}
@@ -85,7 +85,7 @@
         <input type="radio" name="forks" value="detach_forks" checked="checked"/> <label for="forks">${_('Detach forks')}</label>
         <input type="radio" name="forks" value="delete_forks" /> <label for="forks">${_('Delete forks')}</label>
     %endif
-    <div class="field" style="border:none;color:#888">
+    <div class="field text-muted" style="border:none">
         <ul>
         <li>${_('The deleted repository will be moved away and hidden until the administrator expires it. The administrator can both permanently delete it or restore it.')}</li>
         </ul>
--- a/kallithea/templates/admin/repos/repo_edit_caches.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repos/repo_edit_caches.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,8 +1,8 @@
-${h.form(url('edit_repo_caches', repo_name=c.repo_name), method='put')}
+${h.form(url('update_repo_caches', repo_name=c.repo_name))}
 <div class="form">
    <div class="fields">
-       ${h.submit('reset_cache_%s' % c.repo_info.repo_name,_('Invalidate Repository Cache'),class_="btn btn-small",onclick="return confirm('"+_('Confirm to invalidate repository cache.')+"');")}
-      <div class="field" style="border:none;color:#888">
+       ${h.submit('reset_cache_%s' % c.repo_info.repo_name,_('Invalidate Repository Cache'),class_="btn btn-default btn-sm")}
+      <div class="field text-muted" style="border:none">
       <ul>
           <li>${_('Manually invalidate cache for this repository. On first access, the repository will be cached again.')}
           </li>
@@ -10,7 +10,7 @@
       </div>
       <div class="field" style="border:none;">
         ${_('List of Cached Values')}
-           <table>
+           <table class="table">
            <tr>
             <th>${_('Prefix')}</th>
             <th>${_('Key')}</th>
--- a/kallithea/templates/admin/repos/repo_edit_fields.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repos/repo_edit_fields.html	Fri Nov 18 01:11:13 2016 +0100
@@ -13,10 +13,10 @@
             <td>${field.field_key}</td>
             <td>${field.field_type}</td>
             <td>
-              ${h.form(url('delete_repo_fields', repo_name=c.repo_info.repo_name, field_id=field.repo_field_id),method='delete')}
+              ${h.form(url('delete_repo_fields', repo_name=c.repo_info.repo_name, field_id=field.repo_field_id))}
                   <i class="icon-minus-circled" style="color:#FF4444"></i>
                   ${h.submit('remove_%s' % field.repo_field_id, _('Delete'), id="remove_field_%s" % field.repo_field_id,
-                  class_="action_button", onclick="return confirm('"+_('Confirm to delete this field: %s') % field.field_key+"');")}
+                  class_="btn btn-default btn-xs", onclick="return confirm('"+_('Confirm to delete this field: %s') % field.field_key+"');")}
               ${h.end_form()}
             </td>
         </tr>
@@ -24,39 +24,36 @@
       </table>
     </div>
     %endif
-    ${h.form(url('create_repo_fields', repo_name=c.repo_name),method='put')}
+    ${h.form(url('create_repo_fields', repo_name=c.repo_name))}
     <div class="form">
         <!-- fields -->
-        <div class="fields">
-             <div class="field">
-                <div class="label">
-                    <label for="new_field_key">${_('New field key')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label class="control-label" for="new_field_key">${_('New field key')}:</label>
                 <div class="input">
                     ${h.text('new_field_key', class_='small')}
                 </div>
-             </div>
-             <div class="field">
-                <div class="label">
-                    <label for="new_field_label">${_('New field label')}:</label>
-                </div>
+            </div>
+
+            <div class="form-group">
+                <label class="control-label" for="new_field_label">${_('New field label')}:</label>
                 <div class="input">
                     ${h.text('new_field_label', class_='small', placeholder=_('Enter short label'))}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label">
-                    <label for="new_field_desc">${_('New field description')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="new_field_desc">${_('New field description')}:</label>
                 <div class="input">
                     ${h.text('new_field_desc', class_='small', placeholder=_('Enter description of a field'))}
                 </div>
-             </div>
+            </div>
 
-            <div class="buttons">
-              ${h.submit('save',_('Add'),class_="btn")}
-              ${h.reset('reset',_('Reset'),class_="btn")}
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Add'),class_="btn btn-default")}
+                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/admin/repos/repo_edit_fork.html	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,21 +0,0 @@
-${h.form(url('repo_as_fork', repo_name=c.repo_info.repo_name),method='put')}
-<div class="form">
-   <div class="fields">
-       ${h.select('id_fork_of','',c.repos_list,class_="medium")}
-       ${h.submit('set_as_fork_%s' % c.repo_info.repo_name,_('Set'),class_="btn btn-small")}
-   </div>
-       <div class="field" style="border:none;color:#888">
-       <ul>
-            <li>${_('''Manually set this repository as a fork of another from the list.''')}</li>
-       </ul>
-       </div>
-</div>
-${h.end_form()}
-
-<script>
-    $(document).ready(function(){
-        $("#id_fork_of").select2({
-            'dropdownAutoWidth': true
-        });
-    });
-</script>
--- a/kallithea/templates/admin/repos/repo_edit_permissions.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repos/repo_edit_permissions.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,7 +1,7 @@
-${h.form(url('edit_repo_perms_update', repo_name=c.repo_name), method='put')}
+${h.form(url('edit_repo_perms_update', repo_name=c.repo_name))}
 <div class="form">
-   <div class="fields">
-        <div class="field">
+    <div class="form-horizontal">
+        <div class="form-group">
             ${h.hidden('repo_private')}
             <table id="permissions_manage" class="noborder">
                 <tr>
@@ -39,7 +39,7 @@
                         </td>
                         <td>
                           %if r2p.user.username !='default':
-                            <span style="color:#da4f49" class="action_button" onclick="ajaxActionRevoke(${r2p.user.user_id}, 'user', '${'id%s'%id(r2p.user.username)}', '${r2p.user.username}')">
+                            <span style="color:#da4f49" class="btn btn-default btn-xs" onclick="ajaxActionRevoke(${r2p.user.user_id}, 'user', '${'id%s'%id(r2p.user.username)}', '${r2p.user.username}')">
                             <i class="icon-minus-circled"></i> ${_('Revoke')}
                             </span>
                           %endif
@@ -64,7 +64,7 @@
                             %endif
                         </td>
                         <td>
-                            <span style="color:#da4f49" class="action_button" onclick="ajaxActionRevoke(${g2p.users_group.users_group_id}, 'user_group', '${'id%s'%id(g2p.users_group.users_group_name)}', '${g2p.users_group.users_group_name}')">
+                            <span style="color:#da4f49" class="btn btn-default btn-xs" onclick="ajaxActionRevoke(${g2p.users_group.users_group_id}, 'user_group', '${'id%s'%id(g2p.users_group.users_group_name)}', '${g2p.users_group.users_group_name}')">
                             <i class="icon-minus-circled"></i> ${_('Revoke')}
                             </span>
                         </td>
@@ -72,7 +72,7 @@
                 %endfor
 
                 <%
-                _tmpl = h.literal("""' \
+                _tmpl = h.literal("""'\
                     <td><input type="radio" value="repository.none" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
                     <td><input type="radio" value="repository.read" checked="checked" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
                     <td><input type="radio" value="repository.write" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
@@ -97,11 +97,11 @@
                 </tr>
             </table>
         </div>
-        <div class="buttons">
-          ${h.submit('save',_('Save'),class_="btn")}
-          ${h.reset('reset',_('Reset'),class_="btn")}
+        <div class="form-group">
+            ${h.submit('save',_('Save'),class_="btn btn-default")}
+            ${h.reset('reset',_('Reset'),class_="btn btn-default")}
         </div>
-   </div>
+    </div>
 </div>
 ${h.end_form()}
 
--- a/kallithea/templates/admin/repos/repo_edit_remote.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repos/repo_edit_remote.html	Fri Nov 18 01:11:13 2016 +0100
@@ -2,12 +2,12 @@
 <div style="font-size: 20px; padding: 0px 0px 10px 0px">
    ${_('Remote repository URL')}: <a href="${c.repo_info.clone_uri}">${c.repo_info.clone_uri_hidden}</a></li>
 </div>
-${h.form(url('edit_repo_remote', repo_name=c.repo_name), method='put')}
+${h.form(url('edit_repo_remote_update', repo_name=c.repo_name))}
 <div class="form">
     <div class="fields">
         ${h.submit('remote_pull_%s' % c.repo_info.repo_name,
             _('Pull Changes from Remote Repository'),
-            class_="btn btn-small",
+            class_="btn btn-default btn-sm",
             onclick="return confirm('"+_('Confirm to pull changes from remote repository.')+"');")}
     </div>
 </div>
--- a/kallithea/templates/admin/repos/repo_edit_settings.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repos/repo_edit_settings.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,11 +1,9 @@
-${h.form(url('put_repo', repo_name=c.repo_info.repo_name), method='put')}
+${h.form(url('update_repo', repo_name=c.repo_info.repo_name))}
     <div class="form">
         <!-- fields -->
-        <div class="fields">
-            <div class="field">
-                <div class="label">
-                    <label for="repo_name">${_('Name')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label class="control-label" for="repo_name">${_('Name')}:</label>
                 <div class="input">
                     ${h.text('repo_name',class_="medium")}
                     <span class="help-block">${_('Permanent Repository ID')}: `_${c.repo_info.repo_id}` <span><a id="show_more_clone_id" href="#">${_('What is that?')}</a></span></span>
@@ -16,10 +14,8 @@
                                This is useful for CI systems, or any other cases that you need to hardcode the URL into a 3rd party service.''')}</span>
                 </div>
             </div>
-            <div class="field">
-                <div class="label">
-                    <label for="clone_uri">${_('Remote repository')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="clone_uri">${_('Remote repository')}:</label>
                 <div class="input">
                   <div id="alter_clone_uri">
                         ${h.text('clone_uri',class_="medium", placeholder=_('Repository URL'))}
@@ -30,77 +26,61 @@
                   </span>
                 </div>
             </div>
-            <div class="field">
-                <div class="label">
-                    <label for="repo_group">${_('Repository group')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="repo_group">${_('Repository group')}:</label>
                 <div class="input">
                     ${h.select('repo_group','',c.repo_groups,class_="medium")}
                     <span class="help-block">${_('Optionally select a group to put this repository into.')}</span>
                 </div>
             </div>
-            <div class="field">
-                <div class="label">
-                    <label for="repo_landing_rev">${_('Landing revision')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="repo_landing_rev">${_('Landing revision')}:</label>
                 <div class="input">
                     ${h.select('repo_landing_rev','',c.landing_revs,class_="medium")}
                     <span class="help-block">${_('Default revision for files page, downloads, whoosh and readme')}</span>
                 </div>
             </div>
-            <div class="field">
-                <div class="label">
-                    <label for="user">${_('Owner')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="owner">${_('Owner')}:</label>
                 <div class="input input-medium ac">
                     <div class="perm_ac">
-                       ${h.text('user',class_='yui-ac-input')}
+                       ${h.text('owner',class_='yui-ac-input')}
                        <span class="help-block">${_('Change owner of this repository.')}</span>
                        <div id="owner_container"></div>
                     </div>
                 </div>
              </div>
-            <div class="field">
-                <div class="label label-textarea">
-                    <label for="repo_description">${_('Description')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="repo_description">${_('Description')}:</label>
                 <div class="textarea text-area editor">
                     ${h.textarea('repo_description', style="height:165px")}
                     <span class="help-block">${_('Keep it short and to the point. Use a README file for longer descriptions.')}</span>
                 </div>
             </div>
 
-            <div class="field">
-                <div class="label label-checkbox">
-                    <label for="repo_private">${_('Private repository')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="repo_private">${_('Private repository')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('repo_private',value="True")}
                     <span class="help-block">${_('Private repositories are only visible to people explicitly added as collaborators.')}</span>
                 </div>
             </div>
-            <div class="field">
-                <div class="label label-checkbox">
-                    <label for="repo_enable_statistics">${_('Enable statistics')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="repo_enable_statistics">${_('Enable statistics')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('repo_enable_statistics',value="True")}
                     <span class="help-block">${_('Enable statistics window on summary page.')}</span>
                 </div>
             </div>
-            <div class="field">
-                <div class="label label-checkbox">
-                    <label for="repo_enable_downloads">${_('Enable downloads')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="repo_enable_downloads">${_('Enable downloads')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('repo_enable_downloads',value="True")}
                     <span class="help-block">${_('Enable download menu on summary page.')}</span>
                 </div>
             </div>
-            <div class="field">
-                <div class="label label-checkbox">
-                    <label for="repo_enable_locking">${_('Enable locking')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="repo_enable_locking">${_('Enable locking')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('repo_enable_locking',value="True")}
                     <span class="help-block">${_('Enable lock-by-pulling on repository.')}</span>
@@ -110,10 +90,8 @@
             %if c.visual.repository_fields:
               ## EXTRA FIELDS
               %for field in c.repo_fields:
-                <div class="field">
-                    <div class="label">
-                        <label for="${field.field_key_prefixed}">${field.field_label} (${field.field_key}):</label>
-                    </div>
+                <div class="form-group">
+                    <label class="control-label" for="${field.field_key_prefixed}">${field.field_label} (${field.field_key}):</label>
                     <div class="input input-medium">
                         ${h.text(field.field_key_prefixed, field.field_value, class_='medium')}
                         %if field.field_desc:
@@ -123,9 +101,11 @@
                  </div>
               %endfor
             %endif
-            <div class="buttons">
-              ${h.submit('save',_('Save'),class_="btn")}
-              ${h.reset('reset',_('Reset'),class_="btn")}
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Save'),class_="btn btn-default")}
+                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
@@ -147,6 +127,6 @@
 
         // autocomplete
         var _USERS_AC_DATA = ${c.users_array|n};
-        SimpleUserAutoComplete($('#user'), $('#owner_container'), _USERS_AC_DATA);
+        SimpleUserAutoComplete($('#owner'), $('#owner_container'), _USERS_AC_DATA);
     });
 </script>
--- a/kallithea/templates/admin/repos/repo_edit_statistics.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repos/repo_edit_statistics.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,13 +1,13 @@
-${h.form(url('edit_repo_statistics', repo_name=c.repo_info.repo_name), method='put')}
+${h.form(url('edit_repo_statistics_update', repo_name=c.repo_info.repo_name))}
 <div class="form">
-    <div class="fields">
-       <div class="field" style="border:none;color:#888">
+    <div class="form-horizontal">
+       <div class="field text-muted" style="border:none;color:#888">
         <ul>
             <li>${_('Processed commits')}: ${c.stats_revision}/${c.repo_last_rev}</li>
             <li>${_('Processed progress')}: ${c.stats_percentage}%</li>
         </ul>
        </div>
-        ${h.submit('reset_stats_%s' % c.repo_info.repo_name,_('Reset Statistics'),class_="btn btn-small",onclick="return confirm('"+_('Confirm to remove current statistics.')+"');")}
+        ${h.submit('reset_stats_%s' % c.repo_info.repo_name,_('Reset Statistics'),class_="btn btn-default btn-sm",onclick="return confirm('"+_('Confirm to remove current statistics.')+"');")}
    </div>
 </div>
 ${h.end_form()}
--- a/kallithea/templates/admin/repos/repos.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/repos/repos.html	Fri Nov 18 01:11:13 2016 +0100
@@ -6,54 +6,47 @@
 </%block>
 
 <%def name="breadcrumbs_links()">
-    <input class="q_filter_box" id="q_filter" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value=""/> ${h.link_to(_('Admin'),h.url('admin_home'))} &raquo; <span id="repo_count">0</span> ${_('Repositories')}
+    <span id="repo_count">0</span> ${_('Repositories')}
 </%def>
 <%block name="header_menu">
     ${self.menu('admin')}
 </%block>
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
 
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
         <ul class="links">
          %if h.HasPermissionAny('hg.admin','hg.create.repository')():
           <li>
-            <a href="${h.url('new_repo')}" class="btn btn-small btn-success"><i class="icon-plus"></i> ${_('Add Repository')}</a>
+            <a href="${h.url('new_repo')}" class="btn btn-success btn-xs"><i class="icon-plus"></i> ${_('Add Repository')}</a>
           </li>
          %endif
         </ul>
     </div>
-    <div class="table-grid table yui-skin-sam" id="datatable_list_wrap"></div>
-    <div id="user-paginator" style="padding: 0px 0px 0px 20px"></div>
-
+    <div class="table">
+        <table id="datatable_list_wrap"></table>
+    </div>
 
 </div>
 <script>
   var data = ${c.data|n};
-  var fields = [
-    {key:"menu"},
-    {key:"raw_name"},
-    {key:"name"},
-    {key:"desc"},
-    {key:"last_changeset"},
-    {key:"last_rev_raw"},
-    {key:"owner"},
-    {key:"state"},
-    {key:"action"}
-  ];
-  var column_defs = [
-    {key:"menu",label:"",sortable:false,className:"quick_repo_menu hidden"},
-    {key:"name",label:"${_('Name')}",sortable:true, sortOptions: { sortFunction: nameSort }},
-    {key:"desc",label:"${_('Description')}",sortable:true},
-    {key:"last_changeset",label:"${_('Tip')}",sortable:true, sortOptions: { sortFunction: revisionSort }},
-    {key:"owner",label:"${_('Owner')}",sortable:true},
-    {key:"state",label:"${_('State')}",sortable:true},
-    {key:"action",label:"${_('Action')}",sortable:false}
-  ];
-  var counter = YUD.get('repo_count');
-  var sort_key = "name";
-  YUI_datatable(data, fields, column_defs, counter, sort_key, ${c.visual.admin_grid_items});
+  var myDataTable = $("#datatable_list_wrap").DataTable({
+        data: data.records,
+        columns: [
+            {data: "raw_name", visible: false, searchable: false},
+            {data: "name", orderData: 1, title: "${_('Name')}"},
+            {data: "desc", title: "${_('Description')}", searchable: false},
+            {data: "last_rev_raw", visible: false, searchable: false},
+            {data: "last_changeset", orderData: 4, title: "${_('Tip')}", searchable: false},
+            {data: "owner", title: "${_('Owner')}", searchable: false},
+            {data: "state", title: "${_('State')}", searchable: false},
+            {data: "action", title: "${_('Action')}", sortable: false, searchable: false}
+        ],
+        drawCallback: updateRowCountCallback($("#repo_count")),
+        dom: '<"dataTables_left"f><"dataTables_right"ilp>t',
+        pageLength: 100
+    });
 </script>
 
 </%def>
--- a/kallithea/templates/admin/settings/settings.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/settings/settings.html	Fri Nov 18 01:11:13 2016 +0100
@@ -16,8 +16,8 @@
 </%block>
 
 <%def name="main()">
-<div class="box" style="overflow:auto">
-    <div class="title">
+<div class="panel panel-primary" style="overflow:auto">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
 
--- a/kallithea/templates/admin/settings/settings_email.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/settings/settings_email.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,18 +1,18 @@
 ${h.form(url('admin_settings_email'), method='post')}
     <div class="form">
 
-        <div class="fields">
-            <div class="field">
-                <div class="label">
-                    <label for="test_email">${_('Send test email to')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label class="control-label" for="test_email">${_('Send test email to')}:</label>
                 <div class="input">
                     ${h.text('test_email',size=30)}
                 </div>
             </div>
 
-            <div class="buttons">
-            ${h.submit('send',_('Send'),class_="btn")}
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('send',_('Send'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/admin/settings/settings_global.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/settings/settings_global.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,60 +1,57 @@
 ${h.form(url('admin_settings_global'), method='post')}
     <div class="form">
 
-        <div class="fields">
+        <div class="form-horizontal">
 
-             <div class="field">
-                <div class="label">
-                    <label for="title">${_('Site branding')}:</label>
-                </div>
+             <div class="form-group">
+                <label class="control-label" for="title">${_('Site branding')}:</label>
                 <div class="input">
                     ${h.text('title',size=30)}
                     <span class="help-block">${_('Set a custom title for your Kallithea Service.')}</span>
                 </div>
              </div>
 
-            <div class="field">
-                <div class="label">
-                    <label for="realm">${_('HTTP authentication realm')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="realm">${_('HTTP authentication realm')}:</label>
                 <div class="input">
                     ${h.text('realm',size=30)}
                 </div>
             </div>
 
-            <div class="field">
-                <div class="label">
-                    <label for="ga_code">${_('Analytics HTML block')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="ga_code">${_('HTML/JavaScript/CSS customization block')}:</label>
                 <div class="input">
                     ${h.textarea('ga_code', cols=80, rows=10)}
-                    <span class="help-block">${_('HTML with JavaScript for web analytics systems like Google Analytics or Piwik. This will be added at the bottom of every page.')}</span>
+                    <span class="help-block">${_('HTML (possibly with \
+                        JavaScript and/or CSS) that will be added to the bottom \
+                        of every page. This can be used for web analytics \
+                        systems like Google Analytics or Piwik, but also to \
+                        perform instance-specific customizations like adding a \
+                        project banner at the top of every page.')}</span>
                 </div>
             </div>
 
-            <div class="field">
-                <div class="label">
-                    <label for="captcha_public_key">${_('ReCaptcha public key')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="captcha_public_key">${_('ReCaptcha public key')}:</label>
                 <div class="input">
                     ${h.text('captcha_public_key',size=60)}
                     <span class="help-block">${_('Public key for reCaptcha system.')}</span>
                 </div>
             </div>
 
-            <div class="field">
-                <div class="label">
-                    <label for="captcha_private_key">${_('ReCaptcha private key')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="captcha_private_key">${_('ReCaptcha private key')}:</label>
                 <div class="input">
                     ${h.text('captcha_private_key',size=60)}
                     <span class="help-block">${_('Private key for reCaptcha system. Setting this value will enable captcha on registration.')}</span>
                 </div>
             </div>
 
-            <div class="buttons">
-                ${h.submit('save',_('Save Settings'),class_="btn")}
-                ${h.reset('reset',_('Reset'),class_="btn")}
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Save Settings'),class_="btn btn-default")}
+                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+                </div>
            </div>
         </div>
     </div>
--- a/kallithea/templates/admin/settings/settings_hooks.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/settings/settings_hooks.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,11 +1,9 @@
 <h4>${_('Built-in Mercurial Hooks (Read-Only)')}</h4>
 <div class="form">
-    <div class="fields">
+    <div class="form-horizontal">
       % for hook in c.hooks:
-        <div class="field">
-            <div class="label label">
-                <label for="${hook.ui_key}">${hook.ui_key}</label>
-            </div>
+        <div class="form-group">
+            <label class="control-label" for="${hook.ui_key}">${hook.ui_key}</label>
             <div class="input" style="margin-left:280px">
               ${h.text(hook.ui_key,hook.ui_value,size=60,readonly="readonly")}
             </div>
@@ -19,39 +17,39 @@
 <h4>${_('Custom Hooks')}</h4>
 ${h.form(url('admin_settings_hooks'), method='post')}
 <div class="form">
-    <div class="fields">
+    <div class="form-horizontal">
 
-      % for hook in c.custom_hooks:
-      <div class="field"  id="${'id%s' % hook.ui_id }">
-        <div class="label label">
-            <label for="${hook.ui_key}">${hook.ui_key}</label>
-        </div>
-        <div class="input" style="margin-left:280px">
-            ${h.hidden('hook_ui_key',hook.ui_key)}
-            ${h.hidden('hook_ui_value',hook.ui_value)}
-            ${h.text('hook_ui_value_new',hook.ui_value,size=60)}
-            <span class="action_button"
-                onclick="delete_hook(${hook.ui_id},'${'id%s' % hook.ui_id }')">
-            <i class="icon-minus-circled" style="color:#FF4444"></i>
-            ${_('Delete')}
-            </span>
+        %for hook in c.custom_hooks:
+            <div class="field"  id="${'id%s' % hook.ui_id }">
+                <label class="control-label" for="${hook.ui_key}">${hook.ui_key}</label>
+                <div class="input" style="margin-left:280px">
+                    ${h.hidden('hook_ui_key',hook.ui_key)}
+                    ${h.hidden('hook_ui_value',hook.ui_value)}
+                    ${h.text('hook_ui_value_new',hook.ui_value,size=60)}
+                    <span class="btn btn-default btn-xs"
+                        onclick="delete_hook(${hook.ui_id},'${'id%s' % hook.ui_id }')">
+                        <i class="icon-minus-circled" style="color:#FF4444"></i>
+                        ${_('Delete')}
+                    </span>
+                </div>
+            </div>
+        %endfor
+
+        <div class="form-group">
+            <div class="input" style="margin-left:-135px;position: absolute;">
+                <div class="input">
+                    ${h.text('new_hook_ui_key',size=20)}
+                </div>
+            </div>
+            <div class="input" style="margin-left:280px">
+                ${h.text('new_hook_ui_value',size=60)}
+            </div>
         </div>
-      </div>
-      % endfor
-
-      <div class="field">
-        <div class="input" style="margin-left:-135px;position: absolute;">
-          <div class="input">
-             ${h.text('new_hook_ui_key',size=20)}
-          </div>
+        <div class="form-group">
+            <div class="buttons" style="margin-left:280px">
+                ${h.submit('save',_('Save'),class_="btn btn-default")}
+            </div>
         </div>
-        <div class="input" style="margin-left:280px">
-            ${h.text('new_hook_ui_value',size=60)}
-        </div>
-      </div>
-      <div class="buttons" style="margin-left:280px">
-         ${h.submit('save',_('Save'),class_="btn")}
-      </div>
     </div>
 </div>
 ${h.end_form()}
@@ -59,14 +57,14 @@
 
 <script type="text/javascript">
 function delete_hook(hook_id, field_id) {
-    var sUrl = "${h.url('admin_settings_hooks')}";
+    var sUrl = "${h.url('admin_settings_hooks_delete')}";
     var success = function (o) {
             $('#' + field_id).remove();
         };
     var failure = function (o) {
             alert("${_('Failed to remove hook')}");
         };
-    var postData = {'_method': 'delete', 'hook_id': hook_id};
+    var postData = {'hook_id': hook_id};
     ajaxPOST(sUrl, postData, success, failure);
 };
 </script>
--- a/kallithea/templates/admin/settings/settings_mapping.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/settings/settings_mapping.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,10 +1,8 @@
 ${h.form(url('admin_settings_mapping'), method='post')}
     <div class="form">
-        <div class="fields">
-            <div class="field">
-                <div class="label label-checkbox">
-                    <label for="destroy">${_('Rescan option')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label class="control-label" for="destroy">${_('Rescan options')}:</label>
                 <div class="checkboxes">
                     <div class="checkbox">
                         ${h.checkbox('destroy',True)}
@@ -31,8 +29,10 @@
                 </div>
             </div>
 
-            <div class="buttons">
-            ${h.submit('rescan',_('Rescan Repositories'),class_="btn")}
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('rescan',_('Rescan Repositories'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/admin/settings/settings_search.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/settings/settings_search.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,24 +1,23 @@
 ${h.form(url('admin_settings_search'), method='post')}
     <div class="form">
 
-        <div class="fields">
-            <div class="field">
-                <div class="label label-checkbox">
-                    <label>${_('Index build option')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label class="control-label">${_('Index build option')}:</label>
                 <div class="checkboxes">
                     <div class="checkbox">
                         ${h.checkbox('full_index',True)}
                         <label for="full_index">${_('Build from scratch')}</label>
-
                     </div>
                     <span class="help-block">${_('This option completely reindexeses all of the repositories for proper fulltext search capabilities.')}</span>
 
                 </div>
             </div>
 
-            <div class="buttons">
-            ${h.submit('reindex',_('Reindex'),class_="btn")}
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('reindex',_('Reindex'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/admin/settings/settings_system.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/settings/settings_system.html	Fri Nov 18 01:11:13 2016 +0100
@@ -7,7 +7,7 @@
     (_('Platform'), c.platform, ''),
     (_('Git version'), c.git_version, ''),
     (_('Git path'), c.ini.get('git_path'), ''),
-    (_('Upgrade info endpoint'), h.literal('%s <br/><span style="color:#999999">%s.</span>' % (c.update_url, _('Note: please make sure this server can access this URL'))), ''),
+    (_('Upgrade info endpoint'), h.literal('%s <br/><span class="text-muted">%s.</span>' % (c.update_url, _('Note: please make sure this server can access this URL'))), ''),
  ]
 %>
 
--- a/kallithea/templates/admin/settings/settings_system_update.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/settings/settings_system_update.html	Fri Nov 18 01:11:13 2016 +0100
@@ -17,11 +17,13 @@
 </p>
 
 % if c.should_upgrade and c.important_notices:
-<div style="color: #5f5f5f; padding: 3px 0px 5px 0px;">Important notes for this release:</div>
+<div class="alert alert-warning">
+    Important notes for this release:
     <ul>
     % for notice in c.important_notices:
         <li>- ${notice}</li>
     % endfor
     </ul>
+</div>
 % endif
 </div>
--- a/kallithea/templates/admin/settings/settings_vcs.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/settings/settings_vcs.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,23 +1,8 @@
 ${h.form(url('admin_settings'), method='post')}
     <div class="form">
-        <div class="fields">
-            <div class="field">
-                <div class="label label-checkbox">
-                    <label>${_('Web')}:</label>
-                </div>
-                <div class="checkboxes">
-                    <div class="checkbox">
-                        ${h.checkbox('web_push_ssl', 'True')}
-                        <label for="web_push_ssl">${_('Require SSL for vcs operations')}</label>
-                    </div>
-                    <span class="help-block">${_('Activate to require SSL both pushing and pulling. If SSL certificate is missing, it will return an HTTP Error 406: Not Acceptable.')}</span>
-                </div>
-             </div>
-
-             <div class="field">
-                <div class="label label-checkbox">
-                    <label>${_('Hooks')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label>${_('Hooks')}:</label>
                 <div class="checkboxes">
                     <div class="checkbox">
                         ${h.checkbox('hooks_changegroup_repo_size','True')}
@@ -36,11 +21,9 @@
                         <label for="hooks_changegroup_update">${_('Update repository after push (hg update)')}</label>
                     </div>
                 </div>
-             </div>
-             <div class="field">
-                <div class="label label-checkbox">
-                    <label>${_('Mercurial extensions')}:</label>
-                </div>
+            </div>
+            <div class="form-group">
+                <label>${_('Mercurial extensions')}:</label>
                 <div class="checkboxes">
                     <div class="checkbox">
                         ${h.checkbox('extensions_largefiles','True')}
@@ -59,15 +42,13 @@
                 </div>
             </div>
             %if c.visual.allow_repo_location_change:
-            <div class="field">
-                <div class="label">
-                    <label for="paths_root_path">${_('Location of repositories')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="paths_root_path">${_('Location of repositories')}:</label>
                 <div class="input">
                     ${h.text('paths_root_path',size=60,readonly="readonly")}
-                    <span id="path_unlock" class="tooltip" style="cursor: pointer"
+                    <span id="path_unlock" data-toggle="tooltip" style="cursor: pointer"
                             title="${_('Click to unlock. You must restart Kallithea in order to make this setting take effect.')}">
-                        <div class="btn btn-small"><i id="path_unlock_icon" class="icon-lock"></i></div>
+                        <div class="btn btn-default btn-sm"><i id="path_unlock_icon" class="icon-lock"></i></div>
                     </span>
                     <span class="help-block">${_('Filesystem location where repositories are stored. After changing this value, a restart and rescan of the repository folder are both required.')}</span>
                 </div>
@@ -76,9 +57,11 @@
             ## form still requires this but we cannot internally change it anyway
             ${h.hidden('paths_root_path',size=30,readonly="readonly")}
             %endif
-            <div class="buttons">
-                ${h.submit('save',_('Save Settings'),class_="btn")}
-                ${h.reset('reset',_('Reset'),class_="btn")}
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Save Settings'),class_="btn btn-default")}
+                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+                </div>
            </div>
         </div>
     </div>
--- a/kallithea/templates/admin/settings/settings_visual.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/settings/settings_visual.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,18 +1,17 @@
 ${h.form(url('admin_settings_visual'), method='post')}
     <div class="form">
 
-        <div class="fields">
+        <div class="form-horizontal">
 
-             <div class="field">
-                <div class="label label-checkbox">
-                    <label>${_('General')}:</label>
-                </div>
+            <div class="form-group">
+                <label>${_('General')}:</label>
                 <div class="checkboxes">
                     <div class="checkbox">
                         ${h.checkbox('repository_fields','True')}
                         <label for="repository_fields">${_('Use repository extra fields')}</label>
                     </div>
                     <span class="help-block">${_('Allows storing additional customized fields per repository.')}</span>
+
                     <div class="checkbox">
                         ${h.checkbox('show_version','True')}
                         <label for="show_version">${_('Show Kallithea version')}</label>
@@ -24,8 +23,7 @@
                         <label for="use_gravatar">${_('Use Gravatars in Kallithea')}</label>
                     </div>
                 </div>
-                <div class="field">
-                    <div class="input">
+                <div class="input">
                         ${h.text('gravatar_url', size=80)}
                         <span class="help-block">${_('''Gravatar URL allows you to use another avatar server application.
                                                         The following variables of the URL will be replaced accordingly.
@@ -34,10 +32,12 @@
                                                         {md5email}  md5 hash of the user email (like at gravatar.com),
                                                         {size}      size of the image that is expected from the server application,
                                                         {netloc}    network location/server host of running Kallithea server''')}</span>
-                    </div>
                 </div>
-                <div class="field">
-                    <div class="input">
+            </div>
+
+            <div class="form-group">
+                <label>${_('Clone URL')}:</label>
+                <div class="input">
                         ${h.text('clone_uri_tmpl', size=80)}
                         <span class="help-block">${_('''Schema of clone URL construction eg. '{scheme}://{user}@{netloc}/{repo}'.
                                                         The following variables are available:
@@ -45,35 +45,28 @@
                                                         {user}   current user username,
                                                         {netloc} network location/server host of running Kallithea server,
                                                         {repo}   full repository name,
-                                                        {repoid} ID of repository, can be used to contruct clone-by-id''')}</span>
-                    </div>
-                </div>
-             </div>
-
-            <div class="field">
-                <div class="label">
-                    <label for="dashboard_items">${_('Dashboard items')}:</label>
-                </div>
-                <div class="input">
-                    ${h.text('dashboard_items',size=5)}
-                    <span class="help-block">${_('Number of items displayed in the main page dashboard before pagination is shown.')}</span>
+                                                        {repoid} ID of repository, can be used to construct clone-by-id''')}</span>
                 </div>
             </div>
 
-            <div class="field">
-                <div class="label">
-                    <label for="admin_grid_items">${_('Admin pages items')}:</label>
+            <div class="form-group">
+                <label class="control-label" for="page_size">${_('Repository page size')}:</label>
+                <div class="input">
+                    ${h.text('page_size',size=5)}
+                    <span class="help-block">${_('Number of items displayed in the repository pages before pagination is shown.')}</span>
                 </div>
+            </div>
+
+            <div class="form-group">
+                <label class="control-label" for="admin_grid_items">${_('Admin page size')}:</label>
                 <div class="input">
                     ${h.text('admin_grid_items',size=5)}
                     <span class="help-block">${_('Number of items displayed in the admin pages grids before pagination is shown.')}</span>
                 </div>
             </div>
 
-             <div class="field">
-                <div class="label label-checkbox">
-                    <label>${_('Icons')}:</label>
-                </div>
+            <div class="form-group">
+                <label>${_('Icons')}:</label>
                 <div class="checkboxes">
                     <div class="checkbox">
                         ${h.checkbox('show_public_icon','True')}
@@ -85,12 +78,10 @@
                     </div>
                     <span class="help-block">${_('Show public/private icons next to repository names.')}</span>
                  </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label label-checkbox">
-                    <label>${_('Meta Tagging')}:</label>
-                </div>
+            <div class="form-group">
+                <label>${_('Meta Tagging')}:</label>
                 <div class="checkboxes">
                     <div class="checkbox">
                         ${h.checkbox('stylify_metatags','True')}
@@ -110,12 +101,14 @@
                     </div>
                     <span class="help-block">${_('Parses meta tags from the repository description field and turns them into colored tags.')}</span>
                  </div>
-             </div>
+            </div>
 
-             <div class="buttons">
-                 ${h.submit('save',_('Save Settings'),class_="btn")}
-                 ${h.reset('reset',_('Reset'),class_="btn")}
-             </div>
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Save Settings'),class_="btn btn-default")}
+                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+                </div>
+            </div>
 
         </div>
     </div>
--- a/kallithea/templates/admin/user_groups/user_group_add.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/user_groups/user_group_add.html	Fri Nov 18 01:11:13 2016 +0100
@@ -17,44 +17,40 @@
 </%block>
 
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
     <!-- end box / title -->
     ${h.form(url('users_groups'))}
     <div class="form">
         <!-- fields -->
-        <div class="fields">
-             <div class="field">
-                <div class="label">
-                    <label for="users_group_name">${_('Group name')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label class="control-label" for="users_group_name">${_('Group name')}:</label>
                 <div class="input">
                     ${h.text('users_group_name',class_='small')}
                 </div>
-             </div>
-            <div class="field">
-                <div class="label label-textarea">
-                    <label for="user_group_description">${_('Description')}:</label>
-                </div>
+            </div>
+            <div class="form-group">
+                <label class="control-label" for="user_group_description">${_('Description')}:</label>
                 <div class="textarea text-area editor">
                     ${h.textarea('user_group_description')}
                     <span class="help-block">${_('Short, optional description for this user group.')}</span>
                 </div>
-             </div>
-             <div class="field">
-                <div class="label label-checkbox">
-                    <label for="users_group_active">${_('Active')}:</label>
-                </div>
+            </div>
+            <div class="form-group">
+                <label class="control-label" for="users_group_active">${_('Active')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('users_group_active',value=True, checked='checked')}
                 </div>
-             </div>
+            </div>
 
-            <div class="buttons">
-              ${h.submit('save',_('Save'),class_="btn")}
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Save'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/admin/user_groups/user_group_edit.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/user_groups/user_group_edit.html	Fri Nov 18 01:11:13 2016 +0100
@@ -18,8 +18,8 @@
 </%block>
 
 <%def name="main()">
-<div class="box" style="overflow:auto">
-    <div class="title">
+<div class="panel panel-primary" style="overflow:auto">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
 
--- a/kallithea/templates/admin/user_groups/user_group_edit_advanced.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/user_groups/user_group_edit_advanced.html	Fri Nov 18 01:11:13 2016 +0100
@@ -5,7 +5,7 @@
  elems = [
     (_('Members'), len(c.group_members_obj), ''),
     (_('Created on'), h.fmt_date(c.user_group.created_on), ''),
-    (_('Owner'), h.person(c.user_group.user), ''),
+    (_('Owner'), h.person(c.user_group.owner), ''),
     ]
 %>
 %for dt, dd, tt in elems:
@@ -14,8 +14,8 @@
 %endfor
 </dl>
 
-${h.form(h.url('users_group', id=c.user_group.users_group_id),method='delete')}
-    <button class="btn btn-small btn-danger" type="submit"
+${h.form(h.url('delete_users_group', id=c.user_group.users_group_id))}
+    <button class="btn btn-danger btn-sm" type="submit"
             onclick="return confirm('${_('Confirm to delete this user group: %s') % c.user_group.users_group_name}');">
         <i class="icon-minus-circled"></i>
         ${_('Delete this user group')}
--- a/kallithea/templates/admin/user_groups/user_group_edit_default_perms.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/user_groups/user_group_edit_default_perms.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,5 +1,5 @@
 <%namespace name="dpb" file="/base/default_perms_box.html"/>
-${dpb.default_perms_box(url('edit_user_group_default_perms', id=c.user_group.users_group_id))}
+${dpb.default_perms_box(url('edit_user_group_default_perms_update', id=c.user_group.users_group_id))}
 
 ## permissions overview
 <%namespace name="p" file="/base/perms_summary.html"/>
--- a/kallithea/templates/admin/user_groups/user_group_edit_members.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/user_groups/user_group_edit_members.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,19 +1,12 @@
-<div class="group_members_wrap">
 % if c.group_members_obj:
-  <ul class="group_members">
+  <ul>
   %for user in c.group_members_obj:
     <li>
-      <div class="group_member">
-        <div class="gravatar">
-          ${h.gravatar(user.email, size=24)}
-        </div>
-        <div>${h.link_to(user.username, h.url('edit_user',id=user.user_id))}</div>
-        <div>${user.full_name}</div>
-      </div>
+        ${h.gravatar_div(user.email, size=24)}
+        <div>${h.link_to(user.full_name_and_username, h.url('edit_user',id=user.user_id))}</div>
     </li>
   %endfor
   </ul>
   %else:
     <span class="empty_data">${_('No members yet')}</span>
   %endif
-</div>
--- a/kallithea/templates/admin/user_groups/user_group_edit_perms.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/user_groups/user_group_edit_perms.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-${h.form(url('edit_user_group_perms', id=c.user_group.users_group_id),method='put')}
+${h.form(url('edit_user_group_perms_update', id=c.user_group.users_group_id))}
 <div class="form">
    <div class="fields">
         <div class="field">
@@ -30,7 +30,7 @@
                         </td>
                         <td>
                           %if r2p.user.username !='default':
-                            <span style="color:#da4f49" class="action_button" onclick="ajaxActionRevoke(${r2p.user.user_id}, 'user', '${'id%s'%id(r2p.user.username)}', '${r2p.user.username}')">
+                            <span style="color:#da4f49" class="btn btn-default btn-xs" onclick="ajaxActionRevoke(${r2p.user.user_id}, 'user', '${'id%s'%id(r2p.user.username)}', '${r2p.user.username}')">
                              <i class="icon-minus-circled"></i> ${_('Revoke')}
                             </span>
                           %endif
@@ -67,7 +67,7 @@
                             %endif
                         </td>
                         <td>
-                            <span style="color:#da4f49" class="action_button" onclick="ajaxActionRevoke(${g2p.user_group.users_group_id}, 'user_group', '${'id%s'%id(g2p.user_group.users_group_name)}', '${g2p.user_group.users_group_name}')">
+                            <span style="color:#da4f49" class="btn btn-default btn-xs" onclick="ajaxActionRevoke(${g2p.user_group.users_group_id}, 'user_group', '${'id%s'%id(g2p.user_group.users_group_name)}', '${g2p.user_group.users_group_name}')">
                             <i class="icon-minus-circled"></i> ${_('Revoke')}
                             </span>
                         </td>
@@ -75,7 +75,7 @@
                 %endfor
 
                 <%
-                _tmpl = h.literal("""' \
+                _tmpl = h.literal("""'\
                     <td><input type="radio" value="usergroup.none" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
                     <td><input type="radio" value="usergroup.read" checked="checked" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
                     <td><input type="radio" value="usergroup.write" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
@@ -93,7 +93,7 @@
                 <tr class="new_members last_new_member" id="add_perm_input"></tr>
                 <tr>
                     <td colspan="6">
-                        <span id="add_perm" style="cursor: pointer;">
+                        <span id="add_perm" class="btn">
                             <i class="icon-plus"></i> ${_('Add new')}
                         </span>
                     </td>
@@ -101,8 +101,8 @@
             </table>
         </div>
         <div class="buttons">
-          ${h.submit('save',_('Save'),class_="btn")}
-          ${h.reset('reset',_('Reset'),class_="btn")}
+            ${h.submit('save',_('Save'),class_="btn btn-default")}
+            ${h.reset('reset',_('Reset'),class_="btn btn-default")}
         </div>
    </div>
 </div>
@@ -110,7 +110,7 @@
 
 <script type="text/javascript">
     function ajaxActionRevoke(obj_id, obj_type, field_id, obj_name) {
-        url = "${h.url('edit_user_group_perms', id=c.user_group.users_group_id)}";
+        url = "${h.url('edit_user_group_perms_delete', id=c.user_group.users_group_id)}";
         var revoke_msg = _TM['Confirm to revoke permission for {0}: {1} ?'].format(obj_type.replace('_', ' '), obj_name);
         if (confirm(revoke_msg)){
             ajaxActionRevokePermission(url, obj_id, obj_type, field_id);
--- a/kallithea/templates/admin/user_groups/user_group_edit_settings.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/user_groups/user_group_edit_settings.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,49 +1,41 @@
-${h.form(url('users_group', id=c.user_group.users_group_id),method='put', id='edit_users_group')}
+${h.form(url('update_users_group', id=c.user_group.users_group_id), id='edit_users_group')}
     <div class="form">
         <!-- fields -->
-            <div class="fields">
-                 <div class="field">
-                    <div class="label">
-                        <label for="users_group_name">${_('Group name')}:</label>
-                    </div>
+            <div class="form-horizontal">
+                <div class="form-group">
+                    <label class="control-label" for="users_group_name">${_('Group name')}:</label>
                     <div class="input">
                         ${h.text('users_group_name',class_='large')}
                     </div>
-                 </div>
-                 <div class="field">
-                    <div class="label label-textarea">
-                        <label for="user_group_description">${_('Description')}:</label>
-                    </div>
+                </div>
+                <div class="form-group">
+                    <label class="control-label" for="user_group_description">${_('Description')}:</label>
                     <div class="textarea-small editor">
                         ${h.textarea('user_group_description')}
                         <span class="help-block">${_('Short, optional description for this user group.')}</span>
                     </div>
-                 </div>
-                 <div class="field">
-                    <div class="label label-checkbox">
-                        <label for="users_group_active">${_('Active')}:</label>
-                    </div>
+                </div>
+                <div class="form-group">
+                    <label class="control-label" for="users_group_active">${_('Active')}:</label>
                     <div class="checkboxes">
                         ${h.checkbox('users_group_active',value=True)}
                     </div>
-                 </div>
-                <div class="field">
-                    <div class="label">
-                        <label for="users_group_active">${_('Members')}:</label>
-                    </div>
+                </div>
+                <div class="form-group">
+                    <label class="control-label">${_('Members')}:</label>
                     <div class="select">
-                        <table>
+                        <table class="table">
                                 <tr>
                                     <td>
                                         <div>
                                             <div style="float:left">
                                                 <div class="text" style="padding: 0px 0px 6px;">${_('Chosen group members')}</div>
-                                                ${h.select('users_group_members',[x[0] for x in c.group_members],c.group_members,multiple=True,size=8,style="min-width:210px")}
+                                                ${h.select('users_group_members',[],c.group_members,multiple=True,size=8,style="min-width:210px")}
                                             </div>
                                             <div style="float:left;width:20px;padding-top:50px">
-                                                <i style="cursor:pointer; font-size: 16px" id="add_element" class="icon-left-open"></i>
-                                                <br />
-                                                <i style="cursor:pointer; font-size: 16px" id="remove_element" class="icon-right-open"></i>
+                                                <i style="cursor:pointer; font-size: 16px" id="add_element" class="icon-left-open" title="Choose selected available"></i>
+                                                <div style="height:50px"></div>
+                                                <i style="cursor:pointer; font-size: 16px" id="remove_element" class="icon-right-open" title="Remove selected chosen"></i>
                                             </div>
                                             <div style="float:left">
                                                  <div class="text" style="padding: 0px 0px 6px;">${_('Available members')}</div>
@@ -54,10 +46,11 @@
                                 </tr>
                         </table>
                     </div>
-
                 </div>
-                <div class="buttons">
-                  ${h.submit('Save',_('Save'),class_="btn")}
+                <div class="form-group">
+                    <div class="buttons">
+                        ${h.submit('Save',_('Save'),class_="btn btn-default")}
+                    </div>
                 </div>
             </div>
     </div>
--- a/kallithea/templates/admin/user_groups/user_groups.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/user_groups/user_groups.html	Fri Nov 18 01:11:13 2016 +0100
@@ -6,8 +6,7 @@
 </%block>
 
 <%def name="breadcrumbs_links()">
-    <input class="q_filter_box" id="q_filter" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value=""/>
-    ${h.link_to(_('Admin'),h.url('admin_home'))} &raquo; <span id="user_group_count">0</span> ${_('User Groups')}
+    ${h.link_to(_('Admin'),h.url('admin_home'))} &raquo; ${_('User Groups')}
 </%def>
 
 <%block name="header_menu">
@@ -15,43 +14,39 @@
 </%block>
 
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
         <ul class="links">
         %if h.HasPermissionAny('hg.admin', 'hg.usergroup.create.true')():
           <li>
-            <a href="${h.url('new_users_group')}" class="btn btn-small btn-success"><i class="icon-plus"></i> ${_('Add User Group')}</a>
+            <a href="${h.url('new_users_group')}" class="btn btn-success btn-sm"><i class="icon-plus"></i> ${_('Add User Group')}</a>
           </li>
         %endif
         </ul>
     </div>
     <!-- end box / title -->
-    <div class="table-grid table yui-skin-sam" id="datatable_list_wrap"></div>
-    <div id="user-paginator" style="padding: 0px 0px 0px 20px"></div>
+    <div class="table">
+        <table id="datatable_list_wrap"></table>
+    </div>
 </div>
 <script>
-  var data = ${c.data|n};
-  var fields = [
-    {key: "group_name"},
-    {key: "raw_name"},
-    {key: "desc"},
-    {key: "members"},
-    {key: "active"},
-    {key: "owner"},
-    {key: "action"}
-  ];
-  var column_defs = [
-    {key:"group_name",label:"${_('Name')}",sortable:true, sortOptions: { sortFunction: nameSort }},
-    {key:"desc",label:"${_('Description')}",sortable:true},
-    {key:"members",label:"${_('Members')}",sortable:false},
-    {key:"active",label:"${_('Active')}",sortable:true},
-    {key:"owner",label:"${_('Owner')}",sortable:true},
-    {key:"action",label:"${_('Action')}",sortable:false}
-  ];
-  var counter = YUD.get('user_group_count');
-  var sort_key = "group_name";
-  YUI_datatable(data, fields, column_defs, counter, sort_key, ${c.visual.admin_grid_items});
+    var data = ${c.data|n};
+    var $dataTable = $("#datatable_list_wrap").DataTable({
+        data: data.records,
+        columns: [
+            {data: "raw_name", visible: false, searchable: false},
+            {data: "group_name", title: "${_('Name')}", orderData: 0},
+            {data: "desc", title: "${_('Description')}", searchable: false},
+            {data: "members", title: "${_('Members')}", searchable: false},
+            {data: "active", title: "${_('Active')}", searchable: false, 'sType': 'str'},
+            {data: "owner", title: "${_('Owner')}", searchable: false},
+            {data: "action", title: "${_('Action')}", searchable: false, sortable: false}
+        ],
+        order: [[1, "asc"]],
+        dom: '<"dataTables_left"f><"dataTables_right"ilp>t',
+        pageLength: 100
+    });
 </script>
 </%def>
--- a/kallithea/templates/admin/users/user_add.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/users/user_add.html	Fri Nov 18 01:11:13 2016 +0100
@@ -17,83 +17,72 @@
 </%block>
 
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
     <!-- end box / title -->
-    ${h.form(url('users'))}
+    ${h.form(url('new_user'))}
     <div class="form">
         <!-- fields -->
-        <div class="fields">
-             <div class="field">
-                <div class="label">
-                    <label for="username">${_('Username')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label class="control-label" for="username">${_('Username')}:</label>
                 <div class="input">
                     ${h.text('username',class_='small')}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label">
-                    <label for="password">${_('Password')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="password">${_('Password')}:</label>
                 <div class="input">
                     ${h.password('password',class_='small')}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label">
-                    <label for="password_confirmation">${_('Password confirmation')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="password_confirmation">${_('Password confirmation')}:</label>
                 <div class="input">
                     ${h.password('password_confirmation',class_="small")}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label">
-                    <label for="firstname">${_('First Name')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="firstname">${_('First Name')}:</label>
                 <div class="input">
                     ${h.text('firstname',class_='small')}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label">
-                    <label for="lastname">${_('Last Name')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="lastname">${_('Last Name')}:</label>
                 <div class="input">
                     ${h.text('lastname',class_='small')}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label">
-                    <label for="email">${_('Email')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="email">${_('Email')}:</label>
                 <div class="input">
                     ${h.text('email',class_='small')}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label label-checkbox">
-                    <label for="active">${_('Active')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="active">${_('Active')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('active',value=True,checked='checked')}
                 </div>
-             </div>
+            </div>
 
             ${h.hidden('extern_type', c.default_extern_type)}
             ${h.hidden('extern_name', c.default_extern_name)}
-            <div class="buttons">
-              ${h.submit('save',_('Save'),class_="btn")}
+
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Save'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/admin/users/user_edit.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/users/user_edit.html	Fri Nov 18 01:11:13 2016 +0100
@@ -18,8 +18,8 @@
 </%block>
 
 <%def name="main()">
-<div class="box" style="overflow:auto">
-    <div class="title">
+<div class="panel panel-primary" style="overflow:auto">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
 
--- a/kallithea/templates/admin/users/user_edit_advanced.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/users/user_edit_advanced.html	Fri Nov 18 01:11:13 2016 +0100
@@ -16,8 +16,8 @@
 %endfor
 </dl>
 
-${h.form(h.url('delete_user', id=c.user.user_id),method='delete')}
-    <button class="btn btn-small btn-danger" type="submit"
+${h.form(h.url('delete_user', id=c.user.user_id))}
+    <button class="btn btn-danger btn-sm" type="submit"
             onclick="return confirm('${_('Confirm to delete this user: %s') % c.user.username}');">
         <i class="icon-minus-circled"></i>
         ${_('Delete this user')}
--- a/kallithea/templates/admin/users/user_edit_api_keys.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/users/user_edit_api_keys.html	Fri Nov 18 01:11:13 2016 +0100
@@ -3,14 +3,14 @@
     <tr>
         <td style="width: 450px"><div class="truncate autoexpand" style="width:120px;font-size:16px;font-family: monospace">${c.user.api_key}</div></td>
         <td>
-            <span class="btn btn-mini btn-success disabled">${_('Built-in')}</span>
+            <span class="label label-success">${_('Built-in')}</span>
         </td>
         <td>${_('Expires')}: ${_('Never')}</td>
         <td>
-            ${h.form(url('edit_user_api_keys', id=c.user.user_id),method='delete')}
+            ${h.form(url('edit_user_api_keys_delete', id=c.user.user_id))}
                 ${h.hidden('del_api_key',c.user.api_key)}
                 ${h.hidden('del_api_key_builtin',1)}
-                <button class="btn btn-mini btn-danger" type="submit"
+                <button class="btn btn-danger btn-xs" type="submit"
                         onclick="return confirm('${_('Confirm to reset this API key: %s') % c.user.api_key}');">
                     ${_('Reset')}
                 </button>
@@ -34,9 +34,9 @@
                  %endif
             </td>
             <td>
-                ${h.form(url('edit_user_api_keys', id=c.user.user_id),method='delete')}
+                ${h.form(url('edit_user_api_keys_delete', id=c.user.user_id))}
                     ${h.hidden('del_api_key',api_key.api_key)}
-                    <button class="btn btn-mini btn-danger" type="submit"
+                    <button class="btn btn-danger btn-xs" type="submit"
                             onclick="return confirm('${_('Confirm to remove this API key: %s') % api_key.api_key}');">
                         <i class="icon-minus-circled"></i>
                         ${_('Remove')}
@@ -52,22 +52,23 @@
 </div>
 
 <div>
-    ${h.form(url('edit_user_api_keys', id=c.user.user_id), method='post')}
+    ${h.form(url('edit_user_api_keys_update', id=c.user.user_id))}
     <div class="form">
         <!-- fields -->
-        <div class="fields">
-             <div class="field">
-                <div class="label">
-                    <label for="description">${_('New API key')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label class="control-label" for="description">${_('New API key')}:</label>
                 <div class="input">
                     ${h.text('description', class_='medium', placeholder=_('Description'))}
                     ${h.select('lifetime', '', c.lifetime_options)}
                 </div>
-             </div>
-            <div class="buttons">
-              ${h.submit('save',_('Add'),class_="btn")}
-              ${h.reset('reset',_('Reset'),class_="btn")}
+            </div>
+
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Add'),class_="btn btn-default")}
+                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/admin/users/user_edit_emails.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/users/user_edit_emails.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,23 +1,27 @@
 <div class="emails_wrap">
   <table class="noborder">
     <tr>
-    <td><div class="gravatar">${h.gravatar(c.user.email, size=16)}</div></td>
+    %if c.visual.use_gravatar:
+    <td>${h.gravatar_div(c.user.email, size=16)}</td>
+    %endif
     <td><div class="email">${c.user.email}</div></td>
     <td>
-        <span class="btn btn-mini btn-success disabled">${_('Primary')}</span>
+        <span class="label label-success">${_('Primary')}</span>
     </td>
     </tr>
     %if c.user_email_map:
         %for em in c.user_email_map:
           <tr>
-            <td><div class="gravatar">${h.gravatar(c.user.email, size=16)}</div></td>
+            %if c.visual.use_gravatar:
+            <td>${h.gravatar_div(c.user.email, size=16)}</td>
+            %endif
             <td><div class="email">${em.email}</div></td>
             <td>
-                ${h.form(url('edit_user_emails', id=c.user.user_id),method='delete')}
+                ${h.form(url('edit_user_emails_delete', id=c.user.user_id))}
                     ${h.hidden('del_email_id',em.email_id)}
                     <i class="icon-minus-circled" style="color:#FF4444"></i>
                     ${h.submit('remove_',_('Delete'),id="remove_email_%s" % em.email_id,
-                    class_="action_button", onclick="return  confirm('"+_('Confirm to delete this email: %s') % em.email+"');")}
+                    class_="btn btn-default btn-xs", onclick="return  confirm('"+_('Confirm to delete this email: %s') % em.email+"');")}
                 ${h.end_form()}
             </td>
           </tr>
@@ -29,21 +33,21 @@
 </div>
 
 <div>
-    ${h.form(url('edit_user_emails', id=c.user.user_id),method='put')}
+    ${h.form(url('edit_user_emails_update', id=c.user.user_id))}
     <div class="form">
         <!-- fields -->
-        <div class="fields">
-             <div class="field">
-                <div class="label">
-                    <label for="new_email">${_('New email address')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label class="control-label" for="new_email">${_('New email address')}:</label>
                 <div class="input">
                     ${h.text('new_email', class_='medium')}
                 </div>
-             </div>
-            <div class="buttons">
-              ${h.submit('save',_('Add'),class_="btn")}
-              ${h.reset('reset',_('Reset'),class_="btn")}
+            </div>
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Add'),class_="btn btn-default")}
+                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/admin/users/user_edit_ips.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/users/user_edit_ips.html	Fri Nov 18 01:11:13 2016 +0100
@@ -16,11 +16,11 @@
             <td><div class="ip">${ip.ip_addr}</div></td>
             <td><div class="ip">${h.ip_range(ip.ip_addr)}</div></td>
             <td>
-                ${h.form(url('edit_user_ips', id=c.user.user_id),method='delete')}
+                ${h.form(url('edit_user_ips_delete', id=c.user.user_id))}
                     ${h.hidden('del_ip_id',ip.ip_id)}
                     <i class="icon-minus-circled" style="color:#FF4444"></i>
                     ${h.submit('remove_',_('Delete'),id="remove_ip_%s" % ip.ip_id,
-                    class_="action_button", onclick="return  confirm('"+_('Confirm to delete this IP address: %s') % ip.ip_addr+"');")}
+                    class_="btn btn-default btn-xs", onclick="return  confirm('"+_('Confirm to delete this IP address: %s') % ip.ip_addr+"');")}
                 ${h.end_form()}
             </td>
           </tr>
@@ -33,21 +33,21 @@
 </div>
 
 <div>
-    ${h.form(url('edit_user_ips', id=c.user.user_id),method='put')}
+    ${h.form(url('edit_user_ips_update', id=c.user.user_id))}
     <div class="form">
         <!-- fields -->
-        <div class="fields">
-             <div class="field">
-                <div class="label">
-                    <label for="new_ip">${_('New IP address')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label class="control-label" for="new_ip">${_('New IP address')}:</label>
                 <div class="input">
                     ${h.text('new_ip', class_='medium')}
                 </div>
-             </div>
-            <div class="buttons">
-              ${h.submit('save',_('Add'),class_="btn")}
-              ${h.reset('reset',_('Reset'),class_="btn")}
+            </div>
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Add'),class_="btn btn-default")}
+                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/admin/users/user_edit_perms.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/users/user_edit_perms.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,5 +1,5 @@
 <%namespace name="dpb" file="/base/default_perms_box.html"/>
-${dpb.default_perms_box(url('edit_user_perms', id=c.user.user_id))}
+${dpb.default_perms_box(url('edit_user_perms_update', id=c.user.user_id))}
 
 ## permissions overview
 <%namespace name="p" file="/base/perms_summary.html"/>
--- a/kallithea/templates/admin/users/user_edit_profile.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/users/user_edit_profile.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,8 +1,8 @@
-${h.form(url('update_user', id=c.user.user_id),method='put')}
-<div class="form">
-        <div class="field">
-           <div class="gravatar_box">
-                <div class="gravatar">${h.gravatar(c.user.email)}</div>
+${h.form(url('update_user', id=c.user.user_id))}
+    <div class="form">
+        <div class="form-group">
+            <div class="gravatar_box">
+                ${h.gravatar_div(c.user.email)}
                 <p>
                 %if c.visual.use_gravatar:
                 <strong>${_('Change avatar at')} <a href="http://gravatar.com">gravatar.com</a></strong>
@@ -15,104 +15,86 @@
                             [${_('Current IP')}: ${c.ip_addr}]
                         %endif
                 %endif
-           </div>
+            </div>
         </div>
-        <div class="fields">
+        <div class="form-horizontal">
 
-             <div class="field">
-                <div class="label">
-                    <label for="username">${_('Username')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="username">${_('Username')}:</label>
                 <div class="input">
-                  ${h.text('username',class_='medium', readonly=c.readonly('username'))}
+                    ${h.text('username',class_='medium', readonly=c.readonly('username'))}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label">
-                    <label for="email">${_('Email')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="email">${_('Email')}:</label>
                 <div class="input">
                     ${h.text('email',class_='medium', readonly=c.readonly('email'))}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label">
-                    <label for="extern_type">${_('Source of Record')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="extern_type">${_('Source of Record')}:</label>
                 <div class="input">
                     ${h.text('extern_type',class_='medium',readonly="readonly")}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label">
-                    <label for="extern_name">${_('Name in Source of Record')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="extern_name">${_('Name in Source of Record')}:</label>
                 <div class="input">
                     ${h.text('extern_name',class_='medium',readonly="readonly")}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label">
-                    <label for="new_password">${_('New password')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="new_password">${_('New password')}:</label>
                 <div class="input">
                     ${h.password('new_password',class_='medium',readonly=c.readonly('password'))}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label">
-                    <label for="password_confirmation">${_('New password confirmation')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="password_confirmation">${_('New password confirmation')}:</label>
                 <div class="input">
                     ${h.password('password_confirmation',class_="medium",readonly=c.readonly('password'))}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label">
-                    <label for="firstname">${_('First Name')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="firstname">${_('First Name')}:</label>
                 <div class="input">
                     ${h.text('firstname',class_='medium', readonly=c.readonly('firstname'))}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label">
-                    <label for="lastname">${_('Last Name')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="lastname">${_('Last Name')}:</label>
                 <div class="input">
                     ${h.text('lastname',class_='medium', readonly=c.readonly('lastname'))}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label label-checkbox">
-                    <label for="active">${_('Active')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="active">${_('Active')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('active',value=True, readonly=c.readonly('active'))}
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label label-checkbox">
-                    <label for="admin">${_('Admin')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="admin">${_('Admin')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('admin',value=True, readonly=c.readonly('admin'))}
                 </div>
-             </div>
+            </div>
 
-            <div class="buttons">
-              ${h.submit('save',_('Save'),class_="btn")}
-              ${h.reset('reset',_('Reset'),class_="btn")}
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Save'),class_="btn btn-default")}
+                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
-</div>
+    </div>
 ${h.end_form()}
--- a/kallithea/templates/admin/users/users.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/admin/users/users.html	Fri Nov 18 01:11:13 2016 +0100
@@ -6,7 +6,6 @@
 </%block>
 
 <%def name="breadcrumbs_links()">
-    <input class="q_filter_box" id="q_filter" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value=""/>
     ${h.link_to(_('Admin'),h.url('admin_home'))} &raquo; <span id="user_count">0</span> ${_('Users')}
 </%def>
 
@@ -15,50 +14,43 @@
 </%block>
 
 <%def name="main()">
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
         <ul class="links">
           <li>
-            <a href="${h.url('new_user')}" class="btn btn-small btn-success"><i class="icon-plus"></i> ${_('Add User')}</a>
+            <a href="${h.url('new_user')}" class="btn btn-success btn-xs"><i class="icon-plus"></i> ${_('Add User')}</a>
           </li>
         </ul>
     </div>
     <!-- end box / title -->
-    <div class="table-grid table yui-skin-sam" id="datatable_list_wrap"></div>
-    <div id="user-paginator" style="padding: 0px 0px 0px 20px"></div>
+    <div class="table">
+        <table id="datatable_list_wrap"></table>
+    </div>
 </div>
 
 <script>
-  var data = ${c.data|n};
-  var fields = [
-    {key: "gravatar"},
-    {key: "raw_name"},
-    {key: "username"},
-    {key: "firstname"},
-    {key: "lastname"},
-    {key: "last_login"},
-    {key: "last_login_raw"},
-    {key: "active"},
-    {key: "admin"},
-    {key: "extern_type"},
-    {key: "action"}
-  ];
-  var column_defs = [
-    {key:"gravatar",label:"",sortable:false},
-    {key:"username",label:"${_('Username')}",sortable:true},
-    {key:"firstname",label:"${_('First Name')}",sortable:true},
-    {key:"lastname",label:"${_('Last Name')}",sortable:true},
-    {key:"last_login",label:"${_('Last Login')}",sortable:true, sortOptions: { sortFunction: lastLoginSort }},
-    {key:"active",label:"${_('Active')}",sortable:true},
-    {key:"admin",label:"${_('Admin')}",sortable:true},
-    {key:"extern_type",label:"${_('Auth Type')}",sortable:true},
-    {key:"action",label:"${_('Action')}",sortable:false}
-  ];
-  var counter = YUD.get('user_count');
-  var sort_key = "username";
-  YUI_datatable(data, fields, column_defs, counter, sort_key, ${c.visual.admin_grid_items});
+    var data = ${c.data|n};
+    var $dataTable = $("#datatable_list_wrap").DataTable({
+        data: data.records,
+        columns: [
+            {data: "gravatar", sortable: false, searchable: false},
+            {data: "username", title: "${_('Username')}"},
+            {data: "firstname", title: "${_('First Name')}"},
+            {data: "lastname", title: "${_('Last Name')}"},
+            {data: "last_login_raw", visible: false, searchable: false},
+            {data: "last_login", title: "${_('Last Login')}", orderData: 4, searchable: false},
+            {data: "active", title: "${_('Active')}", searchable: false, 'sType': 'str'},
+            {data: "admin", title: "${_('Admin')}", searchable: false, 'sType': 'str'},
+            {data: "extern_type", title: "${_('Auth Type')}", searchable: false},
+            {data: "action", title: "${_('Action')}", searchable: false, sortable: false}
+        ],
+        order: [[1, "asc"]],
+        drawCallback: updateRowCountCallback($("#user_count")),
+        dom: '<"dataTables_left"f><"dataTables_right"ilp>t',
+        pageLength: 100
+    });
 </script>
 
 </%def>
--- a/kallithea/templates/base/base.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/base/base.html	Fri Nov 18 01:11:13 2016 +0100
@@ -55,7 +55,7 @@
 </%def>
 
 <%def name="admin_menu()">
-  <ul class="admin_menu">
+  <ul class="dropdown-menu" role="menu">
       <li><a href="${h.url('admin_home')}"><i class="icon-book"></i> ${_('Admin Journal')}</a></li>
       <li><a href="${h.url('repos')}"><i class="icon-database"></i> ${_('Repositories')}</a></li>
       <li><a href="${h.url('repos_groups')}"><i class="icon-folder"></i> ${_('Repository Groups')}</a></li>
@@ -72,7 +72,7 @@
 
 ## admin menu used for people that have some admin resources
 <%def name="admin_menu_simple(repositories=None, repository_groups=None, user_groups=None)">
-  <ul>
+  <ul class="dropdown-menu" role="menu">
    %if repositories:
       <li><a href="${h.url('repos')}"><i class="icon-database"></i> ${_('Repositories')}</a></li>
    %endif
@@ -96,14 +96,8 @@
 
 <%def name="repo_context_bar(current=None, rev=None)">
   <% rev = None if rev == 'tip' else rev %>
-  <%
-    def is_current(selected):
-        if selected == current:
-            return h.literal('class="current"')
-    %>
-
   <!--- CONTEXT BAR -->
-  <div id="context-bar" class="box">
+  <div id="context-bar" class="panel panel-primary">
       <h2>
         ${repotag(c.db_repo)}
 
@@ -113,41 +107,35 @@
         %else:
           <i class="icon-globe"></i>
         %endif
-        ${h.repo_link(c.db_repo.groups_and_repo)}
+        %for group in c.db_repo.groups_with_parents:
+          ${h.link_to(group.name, url('repos_group_home', group_name=group.group_name))}
+          &raquo;
+        %endfor
+        ${h.link_to(c.db_repo.just_name, url('summary_home', repo_name=c.db_repo.repo_name))}
 
         %if current == 'createfork':
          - ${_('Create Fork')}
         %endif
       </h2>
-      <!--
-      <div id="breadcrumbs">
-        ${h.link_to(_('Repositories'),h.url('home'))}
-        &raquo;
-        ${h.repo_link(c.db_repo.groups_and_repo)}
-      </div>
-      -->
       <ul id="context-pages" class="horizontal-list">
-        <li ${is_current('summary')}><a href="${h.url('summary_home', repo_name=c.repo_name)}"><i class="icon-doc-text"></i> ${_('Summary')}</a></li>
+        <li class="${'current' if current == 'summary' else ''}" data-context="summary"><a href="${h.url('summary_home', repo_name=c.repo_name)}"><i class="icon-doc-text"></i> ${_('Summary')}</a></li>
         %if rev:
-        <li ${is_current('changelog')}><a href="${h.url('changelog_file_home', repo_name=c.repo_name, revision=rev, f_path='')}"><i class="icon-clock"></i> ${_('Changelog')}</a></li>
+        <li class="${'current' if current == 'changelog' else ''}" data-context="changelog"><a href="${h.url('changelog_file_home', repo_name=c.repo_name, revision=rev, f_path='')}"><i class="icon-clock"></i> ${_('Changelog')}</a></li>
         %else:
-        <li ${is_current('changelog')}><a href="${h.url('changelog_home', repo_name=c.repo_name)}"><i class="icon-clock"></i> ${_('Changelog')}</a></li>
+        <li class="${'current' if current == 'changelog' else ''}" data-context="changelog"><a href="${h.url('changelog_home', repo_name=c.repo_name)}"><i class="icon-clock"></i> ${_('Changelog')}</a></li>
         %endif
-        <li ${is_current('files')}><a href="${h.url('files_home', repo_name=c.repo_name, revision=rev or 'tip')}"><i class="icon-doc-inv"></i> ${_('Files')}</a></li>
-        <li ${is_current('switch-to')}>
-          <a href="#" id="branch_tag_switcher_2" class="dropdown"><i class="icon-exchange"></i> ${_('Switch To')}</a>
-          <ul id="switch_to_list_2" class="switch_to submenu">
-            <li><a href="#">${_('Loading...')}</a></li>
-          </ul>
+        <li class="${'current' if current == 'files' else ''}" data-context="files"><a href="${h.url('files_home', repo_name=c.repo_name, revision=rev or 'tip')}"><i class="icon-doc-inv"></i> ${_('Files')}</a></li>
+        <li class="${'current' if current == 'switch-to' else ''}" data-context="switch-to">
+          <input id="branch_switcher" name="branch_switcher" type="hidden">
         </li>
-        <li ${is_current('options')}>
-             %if h.HasRepoPermissionAll('repository.admin')(c.repo_name):
-               <a href="${h.url('edit_repo',repo_name=c.repo_name)}" class="dropdown"><i class="icon-wrench"></i> ${_('Options')}</a>
+        <li class="${'current' if current == 'options' else ''} dropdown" data-context="options">
+             %if h.HasRepoPermissionAny('repository.admin')(c.repo_name):
+               <a href="${h.url('edit_repo',repo_name=c.repo_name)}" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true"><i class="icon-wrench"></i> ${_('Options')} <i class="caret"></i></a>
              %else:
-               <a href="#" class="dropdown"><i class="icon-wrench"></i> ${_('Options')}</a>
+               <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true"><i class="icon-wrench"></i> ${_('Options')} <i class="caret"></i></a>
              %endif
-          <ul>
-             %if h.HasRepoPermissionAll('repository.admin')(c.repo_name):
+          <ul class="dropdown-menu" role="menu" aria-hidden="yes">
+             %if h.HasRepoPermissionAny('repository.admin')(c.repo_name):
                    <li><a href="${h.url('edit_repo',repo_name=c.repo_name)}"><i class="icon-gear"></i> ${_('Settings')}</a></li>
              %endif
               %if c.db_repo.fork:
@@ -179,61 +167,142 @@
               %endif
              </ul>
         </li>
-        <li ${is_current('showpullrequest')}>
+        <li class="${'current' if current == 'showpullrequest' else ''}" data-context="showpullrequest">
           <a href="${h.url('pullrequest_show_all',repo_name=c.repo_name)}" title="${_('Show Pull Requests for %s') % c.repo_name}"> <i class="icon-git-pull-request"></i> ${_('Pull Requests')}
             %if c.repository_pull_requests:
-              <span>${c.repository_pull_requests}</span>
+              <span class="badge">${c.repository_pull_requests}</span>
             %endif
           </a>
         </li>
       </ul>
   </div>
   <script type="text/javascript">
-      YUE.on('branch_tag_switcher_2','mouseover',function(){
-         var $branch_tag_switcher_2 = $('#branch_tag_switcher_2');
-         var loaded = $branch_tag_switcher_2.hasClass('loaded');
-         if(!loaded){
-             $branch_tag_switcher_2.addClass('loaded');
-             asynchtml("${h.url('branch_tag_switcher',repo_name=c.repo_name)}", $('#switch_to_list_2'));
-         }
-         return false;
+    $(document).ready(function() {
+      var bcache = {};
+
+      $("#branch_switcher").select2({
+          placeholder: '<i class="icon-exchange"></i> ${_('Switch To')} <span class="caret"></span>',
+          dropdownAutoWidth: true,
+          sortResults: prefixFirstSort,
+          formatResult: function(obj) {
+              return obj.text;
+          },
+          formatSelection: function(obj) {
+              return obj.text;
+          },
+          formatNoMatches: function(term) {
+              return "${_('No matches found')}";
+          },
+          escapeMarkup: function(m) {
+              // don't escape our custom placeholder
+              if (m.substr(0, 29) == '<i class="icon-exchange"></i>') {
+                  return m;
+              }
+
+              return Select2.util.escapeMarkup(m);
+          },
+          containerCssClass: "repo-switcher",
+          dropdownCssClass: "repo-switcher-dropdown",
+          query: function(query) {
+              var key = 'cache';
+              var cached = bcache[key];
+              if (cached) {
+                  var data = {
+                      results: []
+                  };
+                  // filter results
+                  $.each(cached.results, function() {
+                      var section = this.text;
+                      var children = [];
+                      $.each(this.children, function() {
+                          if (query.term.length === 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0) {
+                              children.push({
+                                  'id': this.id,
+                                  'text': this.text,
+                                  'type': this.type,
+                                  'obj': this.obj
+                              });
+                          }
+                      });
+                      if (children.length !== 0) {
+                          data.results.push({
+                              'text': section,
+                              'children': children
+                          });
+                      }
+
+                  });
+                  query.callback(data);
+              } else {
+                  $.ajax({
+                      url: pyroutes.url('repo_refs_data', {
+                          'repo_name': '${c.repo_name}'
+                      }),
+                      data: {},
+                      dataType: 'json',
+                      type: 'GET',
+                      success: function(data) {
+                          bcache[key] = data;
+                          query.callback(data);
+                      }
+                  });
+              }
+          }
       });
+
+      $("#branch_switcher").on('select2-selecting', function(e) {
+          e.preventDefault();
+          var context = $('#context-bar .current').data('context');
+          if (context == 'files') {
+              window.location = pyroutes.url('files_home', {
+                  'repo_name': REPO_NAME,
+                  'revision': e.choice.id,
+                  'f_path': '',
+                  'at': e.choice.text
+              });
+          } else if (context == 'changelog') {
+              if (e.choice.type == 'tag' || e.choice.type == 'book') {
+                  $("#branch_filter").append($('<'+'option/>').val(e.choice.text));
+              }
+              $("#branch_filter").val(e.choice.text).change();
+          } else {
+              window.location = pyroutes.url('changelog_home', {
+                  'repo_name': '${c.repo_name}',
+                  'branch': e.choice.text
+              });
+          }
+      });
+    });
   </script>
   <!--- END CONTEXT BAR -->
 </%def>
 
 <%def name="menu(current=None)">
-  <%
-  def is_current(selected):
-      if selected == current:
-          return h.literal('class="current"')
-  %>
-
   <ul id="quick" class="horizontal-list">
     <!-- repo switcher -->
-    <li ${is_current('repositories')}>
+    <li class="${'current' if current == 'repositories' else ''}">
       <input id="repo_switcher" name="repo_switcher" type="hidden">
     </li>
 
     ##ROOT MENU
     %if c.authuser.username != 'default':
-      <li ${is_current('journal')}>
+      <li class="${'current' if current == 'journal' else ''}">
         <a class="menu_link" title="${_('Show recent activity')}"  href="${h.url('journal')}">
           <i class="icon-book"></i> ${_('Journal')}
         </a>
       </li>
     %else:
-      <li ${is_current('journal')}>
+      <li class="${'current' if current == 'journal' else ''}">
         <a class="menu_link" title="${_('Public journal')}"  href="${h.url('public_journal')}">
           <i class="icon-book"></i> ${_('Public journal')}
         </a>
       </li>
     %endif
-      <li ${is_current('gists')}>
-        <a class="menu_link childs" title="${_('Show public gists')}"  href="${h.url('gists')}">
-          <i class="icon-clippy"></i> ${_('Gists')}
+      <li class="${'current' if current == 'gists' else ''} dropdown">
+        <a class="menu_link dropdown-toggle" data-toggle="dropdown" role="button" title="${_('Show public gists')}"  href="${h.url('gists')}">
+          <i class="icon-clippy"></i> ${_('Gists')} <span class="caret"></span>
         </a>
-          <ul class="admin_menu">
+          <ul class="dropdown-menu" role="menu">
             <li><a href="${h.url('new_gist', public=1)}"><i class="icon-paste"></i> ${_('Create New Gist')}</a></li>
             <li><a href="${h.url('gists')}"><i class="icon-globe"></i> ${_('All Public Gists')}</a></li>
             %if c.authuser.username != 'default':
@@ -242,21 +311,21 @@
             %endif
           </ul>
       </li>
-    <li ${is_current('search')}>
+    <li class="${'current' if current == 'search' else ''}">
         <a class="menu_link" title="${_('Search in repositories')}"  href="${h.url('search')}">
           <i class="icon-search"></i> ${_('Search')}
         </a>
     </li>
-    % if h.HasPermissionAll('hg.admin')('access admin main page'):
-      <li ${is_current('admin')}>
-        <a class="menu_link childs" title="${_('Admin')}" href="${h.url('admin_home')}">
-          <i class="icon-gear"></i> ${_('Admin')}
+    % if h.HasPermissionAny('hg.admin')('access admin main page'):
+      <li class="${'current' if current == 'admin' else ''} dropdown">
+        <a class="menu_link dropdown-toggle" data-toggle="dropdown" role="button" title="${_('Admin')}" href="${h.url('admin_home')}">
+          <i class="icon-gear"></i> ${_('Admin')} <span class="caret"></span>
         </a>
         ${admin_menu()}
       </li>
     % elif c.authuser.repositories_admin or c.authuser.repository_groups_admin or c.authuser.user_groups_admin:
-    <li ${is_current('admin')}>
-        <a class="menu_link childs" title="${_('Admin')}">
+    <li class="${'current' if current == 'admin' else ''} dropdown">
+        <a class="menu_link dropdown-toggle" data-toggle="dropdown" role="button" title="${_('Admin')}">
           <i class="icon-gear"></i> ${_('Admin')}
         </a>
         ${admin_menu_simple(c.authuser.repositories_admin,
@@ -265,51 +334,52 @@
     </li>
     % endif
 
-    <li ${is_current('my_pullrequests')}>
+    <li class="${'current' if current == 'my_pullrequests' else ''}">
       <a class="menu_link" title="${_('My Pull Requests')}" href="${h.url('my_pullrequests')}">
         <i class="icon-git-pull-request"></i> ${_('My Pull Requests')}
         %if c.my_pr_count != 0:
-          <span class="menu_link_notifications">${c.my_pr_count}</span>
+          <span class="badge">${c.my_pr_count}</span>
         %endif
       </a>
     </li>
 
     ## USER MENU
-    <li>
-      <a class="menu_link childs" id="quick_login_link">
-          <span class="icon">
-            ${h.gravatar(c.authuser.email, size=20)}
-          </span>
+    <li class="dropdown">
+      <a class="menu_link dropdown-toggle" data-toggle="dropdown" role="button" id="quick_login_link"
+        aria-expanded="false" aria-controls="quick_login"
+        %if c.authuser.username != 'default':
+          href="${h.url('notifications')}"
+        %else:
+          href="#"
+        %endif
+      >
+          ${h.gravatar_div(c.authuser.email, size=20, div_class="icon", div_style="display:inline", div_aria_hidden="true")}
           %if c.authuser.username != 'default':
             <span class="menu_link_user">${c.authuser.username}</span>
             %if c.unread_notifications != 0:
-              <span class="menu_link_notifications">${c.unread_notifications}</span>
+              <span class="badge">${c.unread_notifications}</span>
             %endif
           %else:
               <span>${_('Not Logged In')}</span>
           %endif
       </a>
 
-      <div class="user-menu">
-        <div id="quick_login">
+      <div class="user-menu" role="menu">
+        <div id="quick_login" role="form" aria-describedby="quick_login_h" aria-hidden="true" class="dropdown-menu">
           %if c.authuser.username == 'default' or c.authuser.user_id is None:
-            <h4>${_('Login to Your Account')}</h4>
+            <h4 id="quick_login_h">${_('Login to Your Account')}</h4>
             ${h.form(h.url('login_home', came_from=request.path_qs))}
             <div class="form">
                 <div class="fields">
                     <div class="field">
-                        <div class="label">
-                            <label for="username">${_('Username')}:</label>
-                        </div>
+                        <label for="username">${_('Username')}:</label>
                         <div class="input">
                             ${h.text('username',class_='focus')}
                         </div>
 
                     </div>
                     <div class="field">
-                        <div class="label">
-                            <label for="password">${_('Password')}:</label>
-                        </div>
+                        <label for="password">${_('Password')}:</label>
                         <div class="input">
                             ${h.password('password',class_='focus')}
                         </div>
@@ -323,7 +393,7 @@
                         %endif
                         </div>
                         <div class="submit">
-                            ${h.submit('sign_in',_('Log In'),class_="btn btn-mini")}
+                            ${h.submit('sign_in',_('Log In'),class_="btn btn-default btn-xs")}
                         </div>
                     </div>
                 </div>
@@ -331,9 +401,7 @@
             ${h.end_form()}
           %else:
             <div class="links_left">
-                <div class="big_gravatar">
-                  ${h.gravatar(c.authuser.email, size=48)}
-                </div>
+                ${h.gravatar_div(c.authuser.email, size=48, div_class="big_gravatar")}
                 <div class="full_name">${c.authuser.full_name_or_username}</div>
                 <div class="email">${c.authuser.email}</div>
             </div>
@@ -353,240 +421,112 @@
     </li>
 
     <script type="text/javascript">
-        var visual_show_public_icon = "${c.visual.show_public_icon}" == "True";
-        var cache = {}
-        /*format the look of items in the list*/
-        var format = function(state){
-            if (!state.id){
-              return state.text; // optgroup
-            }
-            var obj_dict = state.obj;
-            var tmpl = '';
-
-            if(obj_dict && state.type == 'repo'){
-                tmpl += '<span class="repo-icons">';
-                if(obj_dict['repo_type'] === 'hg'){
-                    tmpl += '<span class="repotag">hg</span> ';
+        $(document).ready(function(){
+            var visual_show_public_icon = "${c.visual.show_public_icon}" == "True";
+            var cache = {}
+            /*format the look of items in the list*/
+            var format = function(state){
+                if (!state.id){
+                  return state.text; // optgroup
                 }
-                else if(obj_dict['repo_type'] === 'git'){
-                    tmpl += '<span class="repotag">git</span> ';
-                }
-                if(obj_dict['private']){
-                    tmpl += '<i class="icon-keyhole-circled"></i> ';
-                }
-                else if(visual_show_public_icon){
-                    tmpl += '<i class="icon-globe"></i> ';
-                }
-                tmpl += '</span>';
-            }
-            if(obj_dict && state.type == 'group'){
-                    tmpl += '<i class="icon-folder"></i> ';
-            }
-            tmpl += state.text;
-            return tmpl;
-        }
+                var obj_dict = state.obj;
+                var tmpl = '';
 
-        $("#repo_switcher").select2({
-            placeholder: '<i class="icon-database"></i> ${_('Repositories')}',
-            dropdownAutoWidth: true,
-            formatResult: format,
-            formatSelection: format,
-            formatNoMatches: function(term){
-                return "${_('No matches found')}";
-            },
-            containerCssClass: "repo-switcher",
-            dropdownCssClass: "repo-switcher-dropdown",
-            escapeMarkup: function(m){
-                // don't escape our custom placeholder
-                if(m.substr(0,29) == '<i class="icon-database"></i>'){
-                    return m;
+                if(obj_dict && state.type == 'repo'){
+                    tmpl += '<span class="repo-icons">';
+                    if(obj_dict['repo_type'] === 'hg'){
+                        tmpl += '<span class="repotag">hg</span> ';
+                    }
+                    else if(obj_dict['repo_type'] === 'git'){
+                        tmpl += '<span class="repotag">git</span> ';
+                    }
+                    if(obj_dict['private']){
+                        tmpl += '<i class="icon-keyhole-circled"></i> ';
+                    }
+                    else if(visual_show_public_icon){
+                        tmpl += '<i class="icon-globe"></i> ';
+                    }
+                    tmpl += '</span>';
                 }
+                if(obj_dict && state.type == 'group'){
+                        tmpl += '<i class="icon-folder"></i> ';
+                }
+                tmpl += state.text;
+                return tmpl;
+            }
 
-                return Select2.util.escapeMarkup(m);
-            },
-            query: function(query){
-              var key = 'cache';
-              var cached = cache[key] ;
-              if(cached) {
-                var data = {results: []};
-                //filter results
-                $.each(cached.results, function(){
-                    var section = this.text;
-                    var children = [];
-                    $.each(this.children, function(){
-                        if(query.term.length == 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){
-                            children.push({'id': this.id, 'text': this.text, 'type': this.type, 'obj': this.obj});
-                        }
-                    });
-                    if(children.length !== 0){
-                        data.results.push({'text': section, 'children': children});
+            $("#repo_switcher").select2({
+                placeholder: '<i class="icon-database"></i> ${_('Repositories')} <span class="caret"></span>',
+                dropdownAutoWidth: true,
+                sortResults: prefixFirstSort,
+                formatResult: format,
+                formatSelection: format,
+                formatNoMatches: function(term){
+                    return "${_('No matches found')}";
+                },
+                containerCssClass: "repo-switcher",
+                dropdownCssClass: "repo-switcher-dropdown",
+                escapeMarkup: function(m){
+                    // don't escape our custom placeholder
+                    if(m.substr(0,29) == '<i class="icon-database"></i>'){
+                        return m;
                     }
 
-                });
-                query.callback(data);
-              }else{
-                  $.ajax({
-                    url: "${h.url('repo_switcher_data')}",
-                    data: {},
-                    dataType: 'json',
-                    type: 'GET',
-                    success: function(data) {
-                      cache[key] = data;
-                      query.callback({results: data.results});
-                    }
-                  });
-              }
-            }
-        });
-
-        $("#repo_switcher").on('select2-selecting', function(e){
-            e.preventDefault();
-            window.location = pyroutes.url('summary_home', {'repo_name': e.val});
-        });
-
-        ## Global mouse bindings ##
-
-        // general help "?"
-        Mousetrap.bind(['?'], function(e) {
-            $('#help_kb').modal({});
-        });
-
-        // / open the quick filter
-        Mousetrap.bind(['/'], function(e) {
-            $("#repo_switcher").select2("open");
-
-            // return false to prevent default browser behavior
-            // and stop event from bubbling
-            return false;
-        });
+                    return Select2.util.escapeMarkup(m);
+                },
+                query: function(query){
+                  var key = 'cache';
+                  var cached = cache[key] ;
+                  if(cached) {
+                    var data = {results: []};
+                    //filter results
+                    $.each(cached.results, function(){
+                        var section = this.text;
+                        var children = [];
+                        $.each(this.children, function(){
+                            if(query.term.length == 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){
+                                children.push({'id': this.id, 'text': this.text, 'type': this.type, 'obj': this.obj});
+                            }
+                        });
+                        if(children.length !== 0){
+                            data.results.push({'text': section, 'children': children});
+                        }
 
-        // ctrl/command+b, show the the main bar
-        Mousetrap.bind(['command+b', 'ctrl+b'], function(e) {
-            if($('#header-inner').hasClass('hover') && $('#content').hasClass('hover')){
-                $('#header-inner').removeClass('hover');
-                $('#content').removeClass('hover');
-            }
-            else{
-                $('#header-inner').addClass('hover');
-                $('#content').addClass('hover');
-            }
-            return false;
-        });
+                    });
+                    query.callback(data);
+                  }else{
+                      $.ajax({
+                        url: "${h.url('repo_switcher_data')}",
+                        data: {},
+                        dataType: 'json',
+                        type: 'GET',
+                        success: function(data) {
+                          cache[key] = data;
+                          query.callback({results: data.results});
+                        }
+                      });
+                  }
+                }
+            });
 
-        // general nav g + action
-        Mousetrap.bind(['g h'], function(e) {
-            window.location = pyroutes.url('home');
-        });
-        Mousetrap.bind(['g g'], function(e) {
-            window.location = pyroutes.url('gists', {'private':1});
-        });
-        Mousetrap.bind(['g G'], function(e) {
-            window.location = pyroutes.url('gists', {'public':1});
-        });
-        Mousetrap.bind(['n g'], function(e) {
-            window.location = pyroutes.url('new_gist');
+            $("#repo_switcher").on('select2-selecting', function(e){
+                e.preventDefault();
+                window.location = pyroutes.url('summary_home', {'repo_name': e.val});
+            });
+
+            $(document).on('shown.bs.dropdown', function(event) {
+                var dropdown = $(event.target);
+
+                dropdown.attr('aria-expanded', true);
+                dropdown.find('.dropdown-menu').attr('aria-hidden', false);
+            });
+
+            $(document).on('hidden.bs.dropdown', function(event) {
+                var dropdown = $(event.target);
+
+                dropdown.attr('aria-expanded', false);
+                dropdown.find('.dropdown-menu').attr('aria-hidden', true);
+            });
         });
-        Mousetrap.bind(['n r'], function(e) {
-            window.location = pyroutes.url('new_repo');
-        });
-
-        % if hasattr(c, 'repo_name') and hasattr(c, 'db_repo'):
-            // nav in repo context
-            Mousetrap.bind(['g s'], function(e) {
-                window.location = pyroutes.url('summary_home', {'repo_name': REPO_NAME});
-            });
-            Mousetrap.bind(['g c'], function(e) {
-                window.location = pyroutes.url('changelog_home', {'repo_name': REPO_NAME});
-            });
-            Mousetrap.bind(['g F'], function(e) {
-                window.location = pyroutes.url('files_home', {'repo_name': REPO_NAME, 'revision': '${c.db_repo.landing_rev[1]}', 'f_path': '', 'search': '1'});
-            });
-            Mousetrap.bind(['g f'], function(e) {
-                window.location = pyroutes.url('files_home', {'repo_name': REPO_NAME, 'revision': '${c.db_repo.landing_rev[1]}', 'f_path': ''});
-            });
-            Mousetrap.bind(['g o'], function(e) {
-                window.location = pyroutes.url('edit_repo', {'repo_name': REPO_NAME});
-            });
-            Mousetrap.bind(['g O'], function(e) {
-                window.location = pyroutes.url('edit_repo_perms', {'repo_name': REPO_NAME});
-            });
-        % endif
-
     </script>
 </%def>
-
-%if 0:
-<div class="modal" id="help_kb" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
-    <div class="modal-dialog">
-      <div class="modal-content">
-        <div class="modal-header">
-          <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="icon-cancel-circled"></i></button>
-          <h4 class="modal-title">${_('Keyboard shortcuts')}</h4>
-        </div>
-        <div class="modal-body">
-           <div class="row">
-              <div class="col-md-5">
-                <table class="keyboard-mappings">
-                    <tbody>
-                  <tr>
-                    <th></th>
-                    <th>${_('Site-wide shortcuts')}</th>
-                  </tr>
-                  <%
-                     elems = [
-                         ('/', 'Open quick search box'),
-                         ('ctrl/cmd+b', 'Show main settings bar'),
-                         ('g h', 'Goto home page'),
-                         ('g g', 'Goto my private gists page'),
-                         ('g G', 'Goto my public gists page'),
-                         ('n r', 'New repository page'),
-                         ('n g', 'New gist page'),
-                     ]
-                  %>
-                  %for key, desc in elems:
-                  <tr>
-                    <td class="keys">
-                      <span class="key">${key}</span>
-                    </td>
-                    <td>${desc}</td>
-                  </tr>
-                %endfor
-                </tbody>
-                  </table>
-              </div>
-              <div class="col-md-offset-5">
-                <table class="keyboard-mappings">
-                <tbody>
-                  <tr>
-                    <th></th>
-                    <th>${_('Repositories')}</th>
-                  </tr>
-                  <%
-                     elems = [
-                         ('g s', 'Goto summary page'),
-                         ('g c', 'Goto changelog page'),
-                         ('g f', 'Goto files page'),
-                         ('g F', 'Goto files page with file search activated'),
-                         ('g o', 'Goto repository settings'),
-                         ('g O', 'Goto repository permissions settings'),
-                     ]
-                  %>
-                  %for key, desc in elems:
-                  <tr>
-                    <td class="keys">
-                      <span class="key">${key}</span>
-                    </td>
-                    <td>${desc}</td>
-                  </tr>
-                %endfor
-                </tbody>
-            </table>
-              </div>
-            </div>
-        </div>
-        <div class="modal-footer">
-        </div>
-      </div><!-- /.modal-content -->
-    </div><!-- /.modal-dialog -->
-</div><!-- /.modal -->
-%endif
--- a/kallithea/templates/base/default_perms_box.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/base/default_perms_box.html	Fri Nov 18 01:11:13 2016 +0100
@@ -5,64 +5,59 @@
 
 
 <%def name="default_perms_box(form_url)">
-${h.form(form_url, method='put')}
+${h.form(form_url)}
     <div class="form">
         <!-- fields -->
-        <div class="fields">
-             <div class="field">
-                <div class="label label-checkbox">
-                    <label for="inherit_default_permissions">${_('Inherit defaults')}:</label>
-                </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label class="control-label" for="inherit_default_permissions">${_('Inherit defaults')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('inherit_default_permissions',value=True)}
                     <span class="help-block">
-                    ${h.literal(_('Select to inherit global settings, IP whitelist and permissions from the %s.')
-                                % h.link_to('default permissions', url('admin_permissions')))}
+                        ${h.literal(_('Select to inherit global settings, IP whitelist and permissions from the %s.')
+                                    % h.link_to('default permissions', url('admin_permissions')))}
                     </span>
                 </div>
-             </div>
+            </div>
 
-             <div id="inherit_overlay">
-             <div class="field">
-                <div class="label label-checkbox">
-                    <label for="create_repo_perm">${_('Create repositories')}:</label>
-                </div>
+            <div id="inherit_overlay">
+            <div class="form-group">
+                <label class="control-label" for="create_repo_perm">${_('Create repositories')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('create_repo_perm',value=True)}
                     <span class="help-block">
-                    ${h.literal(_('Select this option to allow repository creation for this user'))}
+                        ${h.literal(_('Select this option to allow repository creation for this user'))}
                     </span>
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label label-checkbox">
-                    <label for="create_user_group_perm">${_('Create user groups')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="create_user_group_perm">${_('Create user groups')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('create_user_group_perm',value=True)}
                     <span class="help-block">
                         ${h.literal(_('Select this option to allow user group creation for this user'))}
                     </span>
                 </div>
-             </div>
+            </div>
 
-             <div class="field">
-                <div class="label label-checkbox">
-                    <label for="fork_repo_perm">${_('Fork repositories')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="fork_repo_perm">${_('Fork repositories')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('fork_repo_perm',value=True)}
                     <span class="help-block">
                         ${h.literal(_('Select this option to allow repository forking for this user'))}
                     </span>
                 </div>
-             </div>
+            </div>
 
             </div>
-            <div class="buttons">
-              ${h.submit('save',_('Save'),class_="btn")}
-              ${h.reset('reset',_('Reset'),class_="btn")}
+
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('save',_('Save'),class_="btn btn-default")}
+                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/base/root.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/base/root.html	Fri Nov 18 01:11:13 2016 +0100
@@ -8,6 +8,7 @@
         <link rel="icon" href="${h.url('/images/favicon.ico')}" type="image/png" />
 
         ## CSS ###
+        <link rel="stylesheet" type="text/css" href="${h.url('/css/jquery.dataTables.css', ver=c.kallithea_version)}"/>
         <link rel="stylesheet" type="text/css" href="${h.url('/js/select2/select2.css', ver=c.kallithea_version)}"/>
         <link rel="stylesheet" type="text/css" href="${h.url('/css/pygments.css', ver=c.kallithea_version)}"/>
         <link rel="stylesheet" type="text/css" href="${h.url('/css/style.css', ver=c.kallithea_version)}" media="screen"/>
@@ -36,8 +37,8 @@
                 'Expand Diff': "${_('Expand Diff')}",
                 'Failed to revoke permission': "${_('Failed to revoke permission')}",
                 'Confirm to revoke permission for {0}: {1} ?': "${_('Confirm to revoke permission for {0}: {1} ?')}",
-                'enabled': "${_('enabled')}",
-                'disabled': "${_('disabled')}",
+                'Enabled': "${_('Enabled')}",
+                'Disabled': "${_('Disabled')}",
                 'Select changeset': "${_('Select changeset')}",
                 'Specify changeset': "${_('Specify changeset')}",
                 'MSG_SORTASC': "${_('Click to sort ascending')}",
@@ -58,10 +59,10 @@
             var _authentication_token = "${h.authentication_token()}";
         </script>
         <script type="text/javascript" src="${h.url('/js/yui.2.9.js', ver=c.kallithea_version)}"></script>
-        <script type="text/javascript" src="${h.url('/js/jquery-1.11.1.min.js', ver=c.kallithea_version)}"></script>
+        <script type="text/javascript" src="${h.url('/js/jquery.min.js', ver=c.kallithea_version)}"></script>
+        <script type="text/javascript" src="${h.url('/js/jquery.dataTables.min.js', ver=c.kallithea_version)}"></script>
         <script type="text/javascript" src="${h.url('/js/bootstrap.js', ver=c.kallithea_version)}"></script>
         <script type="text/javascript" src="${h.url('/js/select2/select2.js', ver=c.kallithea_version)}"></script>
-        <script type="text/javascript" src="${h.url('/js/mousetrap.js', ver=c.kallithea_version)}"></script>
         <script type="text/javascript" src="${h.url('/js/yui.flot.js', ver=c.kallithea_version)}"></script>
         <script type="text/javascript" src="${h.url('/js/native.history.js', ver=c.kallithea_version)}"></script>
         <script type="text/javascript" src="${h.url('/js/base.js', ver=c.kallithea_version)}"></script>
@@ -97,7 +98,6 @@
               pyroutes.register('toggle_following', "${h.url('toggle_following')}");
               pyroutes.register('changeset_info', "${h.url('changeset_info', repo_name='%(repo_name)s', revision='%(revision)s')}", ['repo_name', 'revision']);
               pyroutes.register('repo_size', "${h.url('repo_size', repo_name='%(repo_name)s')}", ['repo_name']);
-              pyroutes.register('changeset_comment_preview', "${h.url('changeset_comment_preview', repo_name='%(repo_name)s')}", ['repo_name']);
               pyroutes.register('repo_refs_data', "${h.url('repo_refs_data', repo_name='%(repo_name)s')}", ['repo_name']);
              });
         </script>
--- a/kallithea/templates/bookmarks/bookmarks.html	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,96 +0,0 @@
-## -*- coding: utf-8 -*-
-<%inherit file="/base/base.html"/>
-
-<%block name="title">
-    ${_('%s Bookmarks') % c.repo_name}
-</%block>
-
-<%def name="breadcrumbs_links()">
-    <input class="q_filter_box" id="q_filter_bookmarks" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value=""/>
-    ${_('Bookmarks')}
-</%def>
-
-<%block name="header_menu">
-    ${self.menu('repositories')}
-</%block>
-
-<%def name="main()">
-${self.repo_context_bar('switch-to')}
-<div class="box">
-    <!-- box / title -->
-    <div class="title">
-        ${self.breadcrumbs()}
-    </div>
-    <!-- end box / title -->
-    %if c.repo_bookmarks:
-    <div class="info_box" id="compare_bookmarks" style="clear: both;padding: 10px 19px;text-align: right;"><a href="#" class="btn btn-small">${_('Compare Bookmarks')}</a></div>
-    %endif
-    <div class="table">
-        <%include file='bookmarks_data.html'/>
-    </div>
-</div>
-
-<script type="text/javascript">
-$('#compare_bookmarks').click(function(e){
-    e.preventDefault();
-    var org = $('input[name=compare_org]:checked')[0];
-    var other = $('input[name=compare_other]:checked')[0];
-
-    if(org && other){
-        var compare_url = "${h.url('compare_url',repo_name=c.repo_name,org_ref_type='book',org_ref_name='__ORG__',other_ref_type='book',other_ref_name='__OTHER__')}";
-        var u = compare_url.replace('__ORG__',org.value)
-                           .replace('__OTHER__',other.value);
-        window.location=u;
-    }
-});
-
-// main table sorting
-var myColumnDefs = [
-    {key:"name",label:"${_('Name')}",sortable:true,
-        sortOptions: { sortFunction: nameSort }},
-    {key:"date",label:"${_('Date')}",sortable:true,
-        sortOptions: { sortFunction: dateSort }},
-    {key:"author",label:"${_('Author')}",sortable:true},
-    {key:"revision",label:"${_('Revision')}",sortable:true,
-        sortOptions: { sortFunction: revisionSort }},
-    {key:"compare",label:"${_('Compare')}",sortable:false}
-];
-
-var myDataSource = new YAHOO.util.DataSource(YUD.get("bookmarks_data"));
-
-myDataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;
-
-myDataSource.responseSchema = {
-    fields: [
-        {key:"raw_name"},
-        {key:"name"},
-        {key:"raw_date"},
-        {key:"date"},
-        {key:"author"},
-        {key:"last_rev_raw"},
-        {key:"revision"},
-        {key:"compare"}
-    ]
-};
-
-var myDataTable = new YAHOO.widget.DataTable("table_wrap", myColumnDefs, myDataSource,
-    {
-         sortedBy:{key:"name",dir:"asc"},
-         MSG_SORTASC:"${_('Click to sort ascending')}",
-         MSG_SORTDESC:"${_('Click to sort descending')}",
-         MSG_EMPTY:"${_('No records found.')}",
-         MSG_ERROR:"${_('Data error.')}",
-         MSG_LOADING:"${_('Loading...')}"
-    }
-);
-myDataTable.subscribe('postRenderEvent',function(oArgs) {
-    tooltip_activate();
-    var func = function(node){
-        return node.parentNode.parentNode.parentNode.parentNode.parentNode;
-    }
-    q_filter('q_filter_bookmarks',$('div.table tr td .logbooks .booktag a'),func);
-});
-
-</script>
-
-</%def>
--- a/kallithea/templates/bookmarks/bookmarks_data.html	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,44 +0,0 @@
-%if c.repo_bookmarks:
-   <div id="table_wrap" class="yui-skin-sam">
-    <table id="bookmarks_data">
-    <thead>
-        <tr>
-            <th class="left">Raw name</th> ##notranslation
-            <th class="left">${_('Name')}</th>
-            <th class="left">Raw date</th> ##notranslation
-            <th class="left">${_('Date')}</th>
-            <th class="left">${_('Author')}</th>
-            <th class="left">Raw rev</th> ##notranslation
-            <th class="left">${_('Revision')}</th>
-            <th class="left">${_('Compare')}</th>
-        </tr>
-    </thead>
-    %for cnt,book in enumerate(c.repo_bookmarks.items()):
-        <tr class="parity${cnt%2}">
-            <td>${book[0]}</td>
-            <td>
-                <span class="logbooks">
-                    <span class="booktag">${h.link_to(book[0],
-                    h.url('changeset_home',repo_name=c.repo_name,revision=book[1].raw_id))}</span>
-                </span>
-            </td>
-            <td>${book[1]._timestamp}</td>
-            <td><span class="tooltip" title="${h.age(book[1].date)}">${h.fmt_date(book[1].date)}</span></td>
-            <td title="${book[1].author}">${h.person(book[1].author)}</td>
-            <td>${book[1].revision}</td>
-            <td>
-              <div>
-                  <a href="${h.url('changeset_home',repo_name=c.repo_name,revision=book[1].raw_id)}" class="revision-link">${h.show_id(book[1])}</a>
-              </div>
-            </td>
-            <td>
-                <input class="branch-compare" type="radio" name="compare_org" value="${book[0]}"/>
-                <input class="branch-compare" type="radio" name="compare_other" value="${book[0]}"/>
-            </td>
-        </tr>
-    %endfor
-    </table>
-    </div>
-%else:
-    ${_('There are no bookmarks yet')}
-%endif
--- a/kallithea/templates/branches/branches.html	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,96 +0,0 @@
-## -*- coding: utf-8 -*-
-<%inherit file="/base/base.html"/>
-
-<%block name="title">
-    ${_('%s Branches') % c.repo_name}
-</%block>
-
-<%def name="breadcrumbs_links()">
-    <input class="q_filter_box" id="q_filter_branches" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value=""/>
-    ${_('Branches')}
-</%def>
-
-<%block name="header_menu">
-    ${self.menu('repositories')}
-</%block>
-
-<%def name="main()">
-${self.repo_context_bar('switch-to')}
-<div class="box">
-    <!-- box / title -->
-    <div class="title">
-        ${self.breadcrumbs()}
-    </div>
-    <!-- end box / title -->
-    %if c.repo_branches:
-    <div class="info_box" id="compare_branches" style="clear: both;padding: 10px 19px;text-align: right;"><a href="#" class="btn btn-small">${_('Compare Branches')}</a></div>
-    %endif
-    <div class="table">
-        <%include file='branches_data.html'/>
-    </div>
-</div>
-
-<script type="text/javascript">
-$('#compare_branches').click(function(e){
-    e.preventDefault();
-    var org = $('input[name=compare_org]:checked')[0];
-    var other = $('input[name=compare_other]:checked')[0];
-
-    if(org && other){
-        var compare_url = "${h.url('compare_url',repo_name=c.repo_name,org_ref_type='branch',org_ref_name='__ORG__',other_ref_type='branch',other_ref_name='__OTHER__')}";
-        var u = compare_url.replace('__ORG__',org.value)
-                           .replace('__OTHER__',other.value);
-        window.location=u;
-    }
-});
-
-// main table sorting
-var myColumnDefs = [
-    {key:"name",label:"${_('Name')}",sortable:true,
-        sortOptions: { sortFunction: nameSort }},
-    {key:"date",label:"${_('Date')}",sortable:true,
-        sortOptions: { sortFunction: dateSort }},
-    {key:"author",label:"${_('Author')}",sortable:true},
-    {key:"revision",label:"${_('Revision')}",sortable:true,
-        sortOptions: { sortFunction: revisionSort }},
-    {key:"compare",label:"${_('Compare')}",sortable:false}
-];
-
-var myDataSource = new YAHOO.util.DataSource(YUD.get("branches_data"));
-
-myDataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;
-
-myDataSource.responseSchema = {
-    fields: [
-        {key:"raw_name"},
-        {key:"name"},
-        {key:"raw_date"},
-        {key:"date"},
-        {key:"author"},
-        {key:"last_rev_raw"},
-        {key:"revision"},
-        {key:"compare"}
-    ]
-};
-
-var myDataTable = new YAHOO.widget.DataTable("table_wrap", myColumnDefs, myDataSource,
-    {
-         sortedBy:{key:"name",dir:"asc"},
-         MSG_SORTASC:"${_('Click to sort ascending')}",
-         MSG_SORTDESC:"${_('Click to sort descending')}",
-         MSG_EMPTY:"${_('No records found.')}",
-         MSG_ERROR:"${_('Data error.')}",
-         MSG_LOADING:"${_('Loading...')}"
-    }
-);
-myDataTable.subscribe('postRenderEvent',function(oArgs) {
-    tooltip_activate();
-    var func = function(node){
-        return node.parentNode.parentNode.parentNode.parentNode.parentNode;
-    }
-    q_filter('q_filter_branches',$('div.table tr td .logtags .branchtag a'),func);
-});
-
-</script>
-
-</%def>
--- a/kallithea/templates/branches/branches_data.html	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,70 +0,0 @@
-%if c.repo_branches:
-   <div id="table_wrap" class="yui-skin-sam">
-    <table id="branches_data">
-      <thead>
-        <tr>
-            <th class="left">Raw name</th> ##notranslation
-            <th class="left">${_('Name')}</th>
-            <th class="left">Raw date</th> ##notranslation
-            <th class="left">${_('Date')}</th>
-            <th class="left">${_('Author')}</th>
-            <th class="left">Raw rev</th> ##notranslation
-            <th class="left">${_('Revision')}</th>
-            <th class="left">${_('Compare')}</th>
-        </tr>
-      </thead>
-        %for cnt,branch in enumerate(c.repo_branches.items()):
-        <tr class="parity${cnt%2}">
-            <td>${branch[0]}</td>
-            <td>
-                <span class="logtags">
-                    <span class="branchtag">
-                    ${h.link_to(branch[0],h.url('changelog_home',repo_name=c.repo_name,branch=branch[0]))}
-                    </span>
-                </span>
-            </td>
-            <td>${branch[1]._timestamp}</td>
-            <td><span class="tooltip" title="${h.age(branch[1].date)}">${h.fmt_date(branch[1].date)}</span></td>
-            <td title="${branch[1].author}">${h.person(branch[1].author)}</td>
-            <td>${branch[1].revision}</td>
-            <td>
-                <div>
-                    <a href="${h.url('changeset_home',repo_name=c.repo_name,revision=branch[1].raw_id)}" class="revision-link">${h.show_id(branch[1])}</a>
-                </div>
-            </td>
-            <td>
-                <input class="branch-compare" type="radio" name="compare_org" value="${branch[0]}"/>
-                <input class="branch-compare" type="radio" name="compare_other" value="${branch[0]}"/>
-            </td>
-        </tr>
-        %endfor
-        ## closed branches if any
-        % if hasattr(c,'repo_closed_branches') and c.repo_closed_branches:
-          %for cnt,branch in enumerate(c.repo_closed_branches.items()):
-          <tr class="parity${cnt%2}">
-              <td>${branch[0]}</td>
-              <td>
-                  <span class="logtags">
-                      <span class="branchtag">
-                      ${h.link_to(branch[0]+' [closed]',h.url('changelog_home',repo_name=c.repo_name,branch=branch[0]))}
-                      </span>
-                  </span>
-              </td>
-              <td>${branch[1]._timestamp}</td>
-              <td><span class="tooltip" title="${h.age(branch[1].date)}">${h.fmt_date(branch[1].date)}</span></td>
-              <td title="${branch[1].author}">${h.person(branch[1].author)}</td>
-              <td>${branch[1].revision}</td>
-              <td>
-                <div>
-                    <a href="${h.url('changeset_home',repo_name=c.repo_name,revision=branch[1].raw_id)}" class="revision-link">${h.show_id(branch[1])}</a>
-                </div>
-              </td>
-              <td></td>
-          </tr>
-          %endfor
-        %endif
-    </table>
-    </div>
-%else:
-    ${_('There are no branches yet')}
-%endif
--- a/kallithea/templates/changelog/changelog.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/changelog/changelog.html	Fri Nov 18 01:11:13 2016 +0100
@@ -27,31 +27,31 @@
 
 <%def name="main()">
 ${self.repo_context_bar('changelog', c.first_revision.raw_id if c.first_revision else None)}
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
     <div class="table">
-        % if c.pagination:
+        %if c.pagination:
             <div>
                 <div style="overflow:auto; ${'display:none' if c.changelog_for_path else ''}">
                     <div class="container_header">
                         <div style="float:left; margin-left:20px;">
-                          ${h.form(h.url.current(),method='get',style="display:inline")}
-                            ${h.submit('set',_('Show'),class_="btn btn-small")}
-                            ${h.text('size',size=3,value=c.size)}
-                            ${_('revisions')}
-                            %if c.branch_name:
-                            ${h.hidden('branch', c.branch_name)}
-                            %endif
-                          ${h.end_form()}
-                          <a href="#" class="btn btn-small" id="rev_range_clear" style="display:none">${_('Clear selection')}</a>
+                            ${h.form(h.url.current(),method='get',style="display:inline")}
+                                ${h.submit('set',_('Show'),class_="btn btn-default btn-sm")}
+                                ${h.text('size',size=3,value=c.size)}
+                                ${_('revisions')}
+                                %if c.branch_name:
+                                    ${h.hidden('branch', c.branch_name)}
+                                %endif
+                            ${h.end_form()}
+                            <a href="#" class="btn btn-default btn-sm" id="rev_range_clear" style="display:none">${_('Clear selection')}</a>
                         </div>
                         <div style="float: right; margin: 0px 0px 0px 4px">
-                            <a href="#" class="btn btn-small" id="rev_range_container" style="display:none"></a>
+                            <a href="#" class="btn btn-default btn-sm" id="rev_range_container" style="display:none"></a>
                             %if c.revision:
-                                <a class="btn btn-small" href="${h.url('changelog_home', repo_name=c.repo_name)}">
+                                <a class="btn btn-default btn-sm" href="${h.url('changelog_home', repo_name=c.repo_name)}">
                                     ${_('Go to tip of repository')}
                                 </a>
                             %endif
@@ -59,10 +59,10 @@
                                 <a id="compare_fork"
                                    title="${_('Compare fork with %s' % c.db_repo.fork.repo_name)}"
                                    href="${h.url('compare_url',repo_name=c.db_repo.fork.repo_name,org_ref_type=c.db_repo.landing_rev[0],org_ref_name=c.db_repo.landing_rev[1],other_repo=c.repo_name,other_ref_type='branch' if request.GET.get('branch') else c.db_repo.landing_rev[0],other_ref_name=request.GET.get('branch') or c.db_repo.landing_rev[1], merge=1)}"
-                                   class="btn btn-small"><i class="icon-git-compare"></i> ${_('Compare fork with parent repository (%s)' % c.db_repo.fork.repo_name)}</a>
+                                   class="btn btn-default btn-sm"><i class="icon-git-compare"></i> ${_('Compare fork with parent repository (%s)' % c.db_repo.fork.repo_name)}</a>
                             %endif
                             ## text and href of open_new_pr is controlled from javascript
-                            <a id="open_new_pr" class="btn btn-small"></a>
+                            <a id="open_new_pr" class="btn btn-default btn-sm"></a>
                             ${_("Branch filter:")} ${h.select('branch_filter',c.branch_name,c.branch_filters)}
                         </div>
                     </div>
@@ -89,11 +89,12 @@
                           %if c.statuses.get(cs.raw_id):
                             <div class="changeset-status-ico">
                             %if c.statuses.get(cs.raw_id)[2]:
-                              <a class="tooltip" title="${_('Changeset status: %s\nClick to open associated pull request %s') % (c.statuses.get(cs.raw_id)[1], c.statuses.get(cs.raw_id)[4])}" href="${h.url('pullrequest_show',repo_name=c.statuses.get(cs.raw_id)[3],pull_request_id=c.statuses.get(cs.raw_id)[2])}">
+                              <a data-toggle="tooltip" title="${_('Changeset status: %s by %s\nClick to open associated pull request %s') % (c.statuses.get(cs.raw_id)[1], c.statuses.get(cs.raw_id)[5].username, c.statuses.get(cs.raw_id)[4])}" href="${h.url('pullrequest_show',repo_name=c.statuses.get(cs.raw_id)[3],pull_request_id=c.statuses.get(cs.raw_id)[2])}">
                                 <i class="icon-circle changeset-status-${c.statuses.get(cs.raw_id)[0]}"></i>
                               </a>
                             %else:
-                              <a class="tooltip" title="${_('Changeset status: %s') % c.statuses.get(cs.raw_id)[1]}" href="${c.comments[cs.raw_id][0].url()}">
+                              <a data-toggle="tooltip" title="${_('Changeset status: %s by %s') % (c.statuses.get(cs.raw_id)[1], c.statuses.get(cs.raw_id)[5].username)}"
+                                 href="${c.comments[cs.raw_id][0].url()}">
                                   <i class="icon-circle changeset-status-${c.statuses.get(cs.raw_id)[0]}"></i>
                               </a>
                             %endif
@@ -102,26 +103,24 @@
                         </td>
                         <td class="author">
                             ${h.gravatar(h.email_or_none(cs.author), size=16)}
-                            <span title="${cs.author}" class="user">${h.shorter(h.person(cs.author),22)}</span>
+                            <span data-toggle="tooltip" title="${cs.author}" class="user">${h.shorter(h.person(cs.author),22)}</span>
                         </td>
                         <td class="hash" style="width:${len(h.show_id(cs))*6.5}px">
-                            <a href="${h.url('changeset_home',repo_name=c.repo_name,revision=cs.raw_id)}">
-                                <span class="changeset_hash">${h.show_id(cs)}</span>
-                            </a>
+                            ${h.link_to(h.show_id(cs),h.url('changeset_home',repo_name=c.repo_name,revision=cs.raw_id), class_='changeset_hash')}
                         </td>
                         <td class="date">
-                            <div class="date tooltip" title="${h.fmt_date(cs.date)}">${h.age(cs.date,True)}</div>
+                            <div class="date" data-toggle="tooltip" title="${h.fmt_date(cs.date)}">${h.age(cs.date,True)}</div>
                         </td>
                         <td class="expand_commit" commit_id="${cs.raw_id}" title="${_('Expand commit message')}">
                             <i class="icon-align-left" style="color:#999"></i>
                         </td>
                         <td class="mid">
                             <div class="log-container">
-                                <div class="message" id="C-${cs.raw_id}">${h.urlify_commit(cs.message, c.repo_name,h.url('changeset_home',repo_name=c.repo_name,revision=cs.raw_id))}</div>
+                                <div class="message" id="C-${cs.raw_id}">${h.urlify_text(cs.message, c.repo_name,h.url('changeset_home',repo_name=c.repo_name,revision=cs.raw_id))}</div>
                                 <div class="extra-container">
                                     %if c.comments.get(cs.raw_id):
                                         <div class="comments-container">
-                                            <div class="comments-cnt" title="${_('Changeset has comments')}">
+                                            <div class="comments-cnt" data-toggle="tooltip" title="${_('Changeset has comments')}">
                                                 <a href="${c.comments[cs.raw_id][0].url()}">
                                                     ${len(c.comments[cs.raw_id])}
                                                     <i class="icon-comment-discussion"></i>
@@ -129,22 +128,47 @@
                                             </div>
                                         </div>
                                     %endif
+                                    %if cs.bumped:
+                                        <span class="bumpedtag" title="Bumped">
+                                            Bumped
+                                        </span>
+                                    %endif
+                                    %if cs.divergent:
+                                        <span class="divergenttag" title="Divergent">
+                                            Divergent
+                                        </span>
+                                    %endif
+                                    %if cs.extinct:
+                                        <span class="extincttag" title="Extinct">
+                                            Extinct
+                                        </span>
+                                    %endif
+                                    %if cs.unstable:
+                                        <span class="unstabletag" title="Unstable">
+                                            Unstable
+                                        </span>
+                                    %endif
+                                    %if cs.phase:
+                                        <span class="phasetag" title="Phase">
+                                            ${cs.phase}
+                                        </span>
+                                    %endif
                                     %if h.is_hg(c.db_repo_scm_instance):
                                         %for book in cs.bookmarks:
-                                            <div class="booktag" title="${_('Bookmark %s') % book}">
+                                            <span class="booktag" title="${_('Bookmark %s') % book}">
                                                 ${h.link_to(book,h.url('changeset_home',repo_name=c.repo_name,revision=cs.raw_id))}
-                                            </div>
+                                            </span>
                                         %endfor
                                     %endif
                                     %for tag in cs.tags:
-                                        <div class="tagtag" title="${_('Tag %s') % tag}">
+                                        <span class="tagtag" title="${_('Tag %s') % tag}">
                                             ${h.link_to(tag,h.url('changeset_home',repo_name=c.repo_name,revision=cs.raw_id))}
-                                        </div>
+                                        </span>
                                     %endfor
                                     %if (not c.branch_name) and cs.branch:
-                                        <div class="branchtag" title="${_('Branch %s' % cs.branch)}">
+                                        <span class="branchtag" title="${_('Branch %s' % cs.branch)}">
                                             ${h.link_to(cs.branch,h.url('changelog_home',repo_name=c.repo_name,branch=cs.branch))}
-                                        </div>
+                                        </span>
                                     %endif
                                 </div>
                             </div>
@@ -158,9 +182,9 @@
 
                 </div>
 
-                <div class="pagination-wh pagination-left">
-                    ${c.pagination.pager('$link_previous ~2~ $link_next')}
-                </div>
+                <ul class="pagination">
+                    ${c.pagination.pager()}
+                </ul>
             </div>
         </div>
 
@@ -248,14 +272,14 @@
                 checkbox_checker();
                 $checkboxes.click(function() {
                     checkbox_checker();
-                    r.render(jsdata,100);
+                    r.render(jsdata);
                 });
                 $('#singlerange').click(checkbox_checker);
 
                 $('#rev_range_clear').click(function(e){
                     $checkboxes.prop('checked', false);
                     checkbox_checker();
-                    r.render(jsdata,100);
+                    r.render(jsdata);
                 });
 
                 var $msgs = $('.message');
@@ -278,13 +302,13 @@
                     $('#C-'+cid).toggleClass('expanded');
 
                     //redraw the graph, r and jsdata are bound outside function
-                    r.render(jsdata,100);
+                    r.render(jsdata);
                 });
 
                 // change branch filter
                 $("#branch_filter").select2({
                     dropdownAutoWidth: true,
-                    minimumInputLength: 1,
+                    maxResults: 50,
                     sortResults: branchSort
                     });
 
@@ -301,7 +325,7 @@
 
                 var jsdata = ${c.jsdata|n};
                 var r = new BranchRenderer('graph_canvas', 'graph_content', 'chg_');
-                r.render(jsdata,100);
+                r.render(jsdata);
             });
 
         </script>
--- a/kallithea/templates/changelog/changelog_details.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/changelog/changelog_details.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,11 +1,11 @@
 ## small box that displays changed/added/removed details fetched by AJAX
 
 % if len(c.cs.affected_files) <= c.affected_files_cut_off:
-<span class="removed tooltip" title="<b>${_('Removed')}</b>${h.changed_tooltip(c.cs.removed)}">${len(c.cs.removed)}</span>
-<span class="changed tooltip" title="<b>${_('Changed')}</b>${h.changed_tooltip(c.cs.changed)}">${len(c.cs.changed)}</span>
-<span class="added tooltip"   title="<b>${_('Added')}</b>${h.changed_tooltip(c.cs.added)}">${len(c.cs.added)}</span>
+<span class="removed" data-toggle="tooltip" title="<b>${_('Removed')}</b>${h.changed_tooltip(c.cs.removed)}">${len(c.cs.removed)}</span>
+<span class="changed" data-toggle="tooltip" title="<b>${_('Changed')}</b>${h.changed_tooltip(c.cs.changed)}">${len(c.cs.changed)}</span>
+<span class="added" data-toggle="tooltip" title="<b>${_('Added')}</b>${h.changed_tooltip(c.cs.added)}">${len(c.cs.added)}</span>
 % else:
- <span class="removed tooltip" title="${_('Affected %s files') % len(c.cs.affected_files)}">!</span>
- <span class="changed tooltip" title="${_('Affected %s files') % len(c.cs.affected_files)}">!</span>
- <span class="added tooltip"   title="${_('Affected %s files') % len(c.cs.affected_files)}">!</span>
+ <span class="removed" data-toggle="tooltip" title="${_('Affected %s files') % len(c.cs.affected_files)}">!</span>
+ <span class="changed" data-toggle="tooltip" title="${_('Affected %s files') % len(c.cs.affected_files)}">!</span>
+ <span class="added" data-toggle="tooltip" title="${_('Affected %s files') % len(c.cs.affected_files)}">!</span>
 % endif
--- a/kallithea/templates/changelog/changelog_summary_data.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/changelog/changelog_summary_data.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,6 +1,6 @@
 ## -*- coding: utf-8 -*-
 %if c.repo_changesets:
-<table>
+<table class="table">
     <tr>
         <th class="left"></th>
         <th class="left"></th>
@@ -11,17 +11,20 @@
         <th class="left">${_('Refs')}</th>
     </tr>
 %for cnt,cs in enumerate(c.repo_changesets):
-    <tr class="parity${cnt%2}">
+    <tr class="parity${cnt%2} ${'mergerow' if len(cs.parents) > 1 else ''}">
         <td class="compact">
             <div class="changeset-status-container">
               %if c.statuses.get(cs.raw_id):
                 <span class="changeset-status-ico shortlog">
                 %if c.statuses.get(cs.raw_id)[2]:
-                  <a class="tooltip" title="${_('Changeset status: %s\nClick to open associated pull request %s') % (c.statuses.get(cs.raw_id)[1], c.statuses.get(cs.raw_id)[4])}" href="${h.url('pullrequest_show',repo_name=c.statuses.get(cs.raw_id)[3],pull_request_id=c.statuses.get(cs.raw_id)[2])}">
+                  <a data-toggle="tooltip" title="${_('Changeset status: %s by %s\nClick to open associated pull request %s') % (c.statuses.get(cs.raw_id)[1], c.statuses.get(cs.raw_id)[5].username, c.statuses.get(cs.raw_id)[4])}" href="${h.url('pullrequest_show',repo_name=c.statuses.get(cs.raw_id)[3],pull_request_id=c.statuses.get(cs.raw_id)[2])}">
                     <i class="icon-circle changeset-status-${c.statuses.get(cs.raw_id)[0]}"></i>
                   </a>
                 %else:
-                  <i class="icon-circle changeset-status-${c.statuses.get(cs.raw_id)[0]}"></i>
+                  <a data-toggle="tooltip" title="${_('Changeset status: %s by %s') % (c.statuses.get(cs.raw_id)[1], c.statuses.get(cs.raw_id)[5].username)}"
+                     href="${c.comments[cs.raw_id][0].url()}">
+                    <i class="icon-circle changeset-status-${c.statuses.get(cs.raw_id)[0]}"></i>
+                  </a>
                 %endif
                 </span>
               %endif
@@ -42,29 +45,29 @@
             <a href="${h.url('changeset_home',repo_name=c.repo_name,revision=cs.raw_id)}" class="revision-link">${h.show_id(cs)}</a>
         </td>
         <td>
-            ${h.urlify_commit(h.chop_at(cs.message,'\n'),c.repo_name, h.url('changeset_home',repo_name=c.repo_name,revision=cs.raw_id))}
+            ${h.urlify_text(h.chop_at(cs.message,'\n'),c.repo_name, h.url('changeset_home',repo_name=c.repo_name,revision=cs.raw_id))}
         </td>
-        <td><span class="tooltip" title="${h.fmt_date(cs.date)}">
+        <td><span data-toggle="tooltip" title="${h.fmt_date(cs.date)}">
                       ${h.age(cs.date)}</span>
         </td>
         <td title="${cs.author}">${h.person(cs.author)}</td>
         <td>
             %if h.is_hg(c.db_repo_scm_instance):
                 %for book in cs.bookmarks:
-                    <div class="booktag" title="${_('Bookmark %s') % book}">
+                    <span class="booktag" title="${_('Bookmark %s') % book}">
                         ${h.link_to(book,h.url('changeset_home',repo_name=c.repo_name,revision=cs.raw_id))}
-                    </div>
+                    </span>
                 %endfor
             %endif
             %for tag in cs.tags:
-             <div class="tagtag" title="${_('Tag %s') % tag}">
+             <span class="tagtag" title="${_('Tag %s') % tag}">
                  ${h.link_to(tag,h.url('changeset_home',repo_name=c.repo_name,revision=cs.raw_id))}
-             </div>
+             </span>
             %endfor
             %if cs.branch:
-             <div class="branchtag" title="${_('Branch %s' % cs.branch)}">
+             <span class="branchtag" title="${_('Branch %s' % cs.branch)}">
                  ${h.link_to(cs.branch,h.url('changelog_home',repo_name=c.repo_name,branch=cs.branch))}
-             </div>
+             </span>
             %endif
         </td>
     </tr>
@@ -72,16 +75,16 @@
 
 </table>
 
-<div class="pagination-wh pagination-left">
-${c.repo_changesets.pager('$link_previous ~2~ $link_next')}
-</div>
+<ul class="pagination">
+    ${c.repo_changesets.pager()}
+</ul>
 %else:
 
 %if h.HasRepoPermissionAny('repository.write','repository.admin')(c.repo_name):
 <h4>${_('Add or upload files directly via Kallithea')}</h4>
 <div style="margin: 20px 30px;">
   <div id="add_node_id" class="add_node">
-      <a class="btn btn-mini" href="${h.url('files_add_home',repo_name=c.repo_name,revision=0,f_path='', anchor='edit')}">${_('Add New File')}</a>
+      <a class="btn btn-default btn-xs" href="${h.url('files_add_home',repo_name=c.repo_name,revision=0,f_path='', anchor='edit')}">${_('Add New File')}</a>
   </div>
 </div>
 %endif
--- a/kallithea/templates/changeset/changeset.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/changeset/changeset.html	Fri Nov 18 01:11:13 2016 +0100
@@ -18,9 +18,9 @@
 
 <%def name="main()">
 ${self.repo_context_bar('changelog', c.changeset.raw_id)}
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
     <script>
@@ -51,13 +51,13 @@
                     %endif
                 </div>
                 <div class="diff-actions">
-                  <a href="${h.url('changeset_raw_home',repo_name=c.repo_name,revision=c.changeset.raw_id)}"  class="tooltip" title="${_('Raw diff')}">
+                  <a href="${h.url('changeset_raw_home',repo_name=c.repo_name,revision=c.changeset.raw_id)}" data-toggle="tooltip" title="${_('Raw diff')}">
                       <i class="icon-diff"></i>
                   </a>
-                  <a href="${h.url('changeset_patch_home',repo_name=c.repo_name,revision=c.changeset.raw_id)}"  class="tooltip" title="${_('Patch diff')}">
+                  <a href="${h.url('changeset_patch_home',repo_name=c.repo_name,revision=c.changeset.raw_id)}" data-toggle="tooltip" title="${_('Patch diff')}">
                       <i class="icon-file-powerpoint"></i>
                   </a>
-                  <a href="${h.url('changeset_download_home',repo_name=c.repo_name,revision=c.changeset.raw_id,diff='download')}" class="tooltip" title="${_('Download diff')}">
+                  <a href="${h.url('changeset_download_home',repo_name=c.repo_name,revision=c.changeset.raw_id,diff='download')}" data-toggle="tooltip" title="${_('Download diff')}">
                       <i class="icon-floppy"></i>
                   </a>
                   ${c.ignorews_url(request.GET)}
@@ -111,22 +111,20 @@
                 </div>
                 <div class="left">
                      <div class="author">
-                         <div class="gravatar">
-                           ${h.gravatar(h.email_or_none(c.changeset.author), size=20)}
-                         </div>
+                         ${h.gravatar_div(h.email_or_none(c.changeset.author), size=20)}
                          <span><b>${h.person(c.changeset.author,'full_name_and_username')}</b> - ${h.age(c.changeset.date,True)} ${h.fmt_date(c.changeset.date)}</span><br/>
                          <span>${h.email_or_none(c.changeset.author)}</span><br/>
                      </div>
                      <% rev = c.changeset.extra.get('source') %>
                      %if rev:
                      <div>
-                       ${_('Grafted from:')} ${h.link_to(h.short_id(rev),h.url('changeset_home',repo_name=c.repo_name,revision=rev))}
+                       ${_('Grafted from:')} ${h.link_to(h.short_id(rev),h.url('changeset_home',repo_name=c.repo_name,revision=rev), class_="changeset_hash")}
                      </div>
                      %endif
                      <% rev = c.changeset.extra.get('transplant_source', '').encode('hex') %>
                      %if rev:
                      <div>
-                       ${_('Transplanted from:')} ${h.link_to(h.short_id(rev),h.url('changeset_home',repo_name=c.repo_name,revision=rev))}
+                       ${_('Transplanted from:')} ${h.link_to(h.short_id(rev),h.url('changeset_home',repo_name=c.repo_name,revision=rev), class_="changeset_hash")}
                      </div>
                      %endif
 
@@ -158,29 +156,30 @@
                      </div>
                      % endif
 
-                     <div class="message">${h.urlify_commit(c.changeset.message, c.repo_name)}</div>
+                     <div class="message">${h.urlify_text(c.changeset.message, c.repo_name)}</div>
                 </div>
             </div>
             <div class="changes_txt">
-            % if c.limited_diff:
-            ${ungettext('%s file changed','%s files changed',len(c.changeset.affected_files)) % (len(c.changeset.affected_files))}:
-            % else:
-            ${ungettext('%s file changed with %s insertions and %s deletions','%s files changed with %s insertions and %s deletions', len(c.changeset.affected_files)) % (len(c.changeset.affected_files),c.lines_added,c.lines_deleted)}:
-            %endif
-            </div>
-            <div class="cs_files">
-              %for FID, (cs1, cs2, change, path, diff, stats) in c.changes[c.changeset.raw_id].iteritems():
-                  <div class="cs_${change}">
-                        <div class="node">
-                            <i class="icon-diff-${change}"></i>
-                            <a href="#${FID}">${h.safe_unicode(path)}</a>
-                        </div>
-                    <div class="changes">${h.fancy_file_stats(stats)}</div>
-                  </div>
-              %endfor
+              <% a_rev, cs_rev, file_diff_data = c.changes[c.changeset.raw_id] %>
               % if c.limited_diff:
-                <h5>${_('Changeset was too big and was cut off...')} <a href="${h.url.current(fulldiff=1, **request.GET.mixed())}">${_('Show full diff anyway')}</a></h5>
-              % endif
+                  ${ungettext('%s file changed', '%s files changed', len(file_diff_data)) % len(file_diff_data)}:
+              % else:
+                  ${ungettext('%s file changed with %s insertions and %s deletions', '%s files changed with %s insertions and %s deletions', len(file_diff_data)) % (len(file_diff_data), c.lines_added, c.lines_deleted)}:
+              %endif
+              </div>
+              <div class="cs_files">
+                %for fid, url_fid, op, a_path, path, diff, stats in file_diff_data:
+                    <div class="cs_${op}">
+                      <div class="node">
+                          <i class="icon-diff-${op}"></i>
+                          ${h.link_to(h.safe_unicode(path), '#%s' % fid)}
+                      </div>
+                      <div class="changes">${h.fancy_file_stats(stats)}</div>
+                    </div>
+                %endfor
+                %if c.limited_diff:
+                  <h5>${_('Changeset was too big and was cut off...')} <a href="${h.url.current(fulldiff=1, **request.GET.mixed())}">${_('Show full diff anyway')}</a></h5>
+                %endif
             </div>
         </div>
 
@@ -190,7 +189,9 @@
     <div class="commentable-diff">
     <%namespace name="diff_block" file="/changeset/diff_block.html"/>
     ${diff_block.diff_block_js()}
-    ${diff_block.diff_block(c.changes[c.changeset.raw_id])}
+    <% a_rev, cs_rev, file_diff_data = c.changes[c.changeset.raw_id] %>
+    ${diff_block.diff_block(c.repo_name, 'rev', a_rev, a_rev,
+                            c.repo_name, 'rev', cs_rev, cs_rev, file_diff_data)}
     % if c.limited_diff:
       <h4>${_('Changeset was too big and was cut off...')} <a href="${h.url.current(fulldiff=1, **request.GET.mixed())}">${_('Show full diff anyway')}</a></h4>
     % endif
@@ -203,27 +204,11 @@
     ${comment.generate_comments()}
 
     ## main comment form and it status
-    ${comment.comments(h.url('changeset_comment', repo_name=c.repo_name, revision=c.changeset.raw_id),
-                       h.changeset_status(c.db_repo, c.changeset.raw_id))}
+    ${comment.comments()}
 
     ## FORM FOR MAKING JS ACTION AS CHANGESET COMMENTS
     <script type="text/javascript">
       $(document).ready(function(){
-          $('.show-inline-comments').change(function(e){
-              var target = e.currentTarget;
-              if(target == null){
-                  target = this;
-              }
-              var boxid = $(target).attr('id_for');
-              if(target.checked){
-                  $('#{0} .inline-comments'.format(boxid)).show();
-                  $('#{0} .inline-comments-button'.format(boxid)).show();
-              }else{
-                  $('#{0} .inline-comments'.format(boxid)).hide();
-                  $('#{0} .inline-comments-button'.format(boxid)).hide();
-              }
-          });
-
           $('.code-difftable').on('click', '.add-bubble', function(e){
               show_comment_form($(this));
           });
--- a/kallithea/templates/changeset/changeset_file_comment.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/changeset/changeset_file_comment.html	Fri Nov 18 01:11:13 2016 +0100
@@ -8,9 +8,7 @@
     <div class="comment-prev-next-links"></div>
     <div class="comment-wrapp">
       <div class="meta">
-          <div style="float:left">
-               ${h.gravatar(co.author.email, size=20)}
-          </div>
+          ${h.gravatar_div(co.author.email, size=20, div_style="float:left")}
           <div class="user">
               ${co.author.full_name_and_username}
           </div>
@@ -26,13 +24,15 @@
               <a class="permalink" href="${co.url()}">&para;</a>
           </span>
 
-          %if h.HasPermissionAny('hg.admin')() or h.HasRepoPermissionAny('repository.admin')(c.repo_name) or co.author.user_id == c.authuser.user_id:
-            <div onClick="confirm('${_("Delete comment?")}') && deleteComment(${co.comment_id})" class="buttons delete-comment btn btn-mini">${_('Delete')}</div>
+          %if co.author_id == c.authuser.user_id or h.HasRepoPermissionAny('repository.admin')(c.repo_name):
+            %if co.deletable():
+              <div onClick="confirm('${_("Delete comment?")}') && deleteComment(${co.comment_id})" class="buttons delete-comment btn btn-default btn-xs" style="margin:0 5px">${_('Delete')}</div>
+            %endif
           %endif
       </div>
       <div class="text">
         %if co.status_change:
-           <div class="rst-block automatic-comment">
+           <div class="automatic-comment">
              <p>
                <span title="${_('Changeset status')}" class="changeset-status-lbl">${_("Status change")}: ${co.status_change[0].status_lbl}</span>
                <span class="changeset-status-ico"><i class="icon-circle changeset-status-${co.status_change[0].status}"></i></span>
@@ -40,7 +40,7 @@
            </div>
         %endif
         %if co.text:
-          ${h.rst_w_mentions(co.text)|n}
+          ${h.render_w_mentions(co.text, c.repo_name)|n}
         %endif
       </div>
     </div>
@@ -48,39 +48,59 @@
 </%def>
 
 
-## expanded with .format(f_path, line_no)
-## TODO: don't assume line_no is globally unique ...
 <%def name="comment_inline_form()">
 <div id='comment-inline-form-template' style="display:none">
   <div class="ac">
   %if c.authuser.username != 'default':
     ${h.form('#', class_='inline-form')}
-      <div id="edit-container_{1}" class="clearfix">
-        <div class="comment-help">${_('Commenting on line {1}.')}
-          ${(_('Comments parsed using %s syntax with %s support.') % (
-                 ('<a href="%s">RST</a>' % h.url('rst_help')),
-                   ('<span style="color:#577632" class="tooltip" title="%s">@mention</span>' % _('Use @username inside this text to notify another user'))
-               )
-            )|n
-           }
+      <div class="clearfix">
+        <div class="comment-help">${_('Commenting on line.')}
+          <span class="text-muted">${_('Comments are in plain text. Use @username inside this text to notify another user.')|n}</span>
         </div>
-        <div class="mentions-container" id="mentions_container_{1}"></div>
-        <textarea id="text_{1}" name="text" class="comment-block-ta yui-ac-input"></textarea>
-      </div>
-      <div id="preview-container_{1}" class="clearfix" style="display:none">
-        <div class="comment-help">
-            ${_('Comment preview')}
+        <div class="mentions-container"></div>
+        <textarea name="text" class="comment-block-ta yui-ac-input"></textarea>
+
+        <div id="status_block_container" class="status-block general-only hidden">
+                %if c.pull_request is None:
+                  ${_('Set changeset status')}:
+                %else:
+                  ${_('Vote for pull request status')}:
+                %endif
+                <span class="general-only cs-only">
+                </span>
+                <label>
+                    <input type="radio" class="status_change_radio" name="changeset_status" id="changeset_status_unchanged" value="" checked="checked" />
+                    ${_('No change')}
+                </label>
+                %for status, lbl in c.changeset_statuses:
+                    <label>
+                        <input type="radio" class="status_change_radio" name="changeset_status" id="${status}" value="${status}">
+                        ${lbl}<i class="icon-circle changeset-status-${status}" /></i>
+                    </label>
+                %endfor
+
+                %if c.pull_request is not None and ( \
+                    h.HasPermissionAny('hg.admin')() or h.HasRepoPermissionAny('repository.admin')(c.repo_name) \
+                    or c.pull_request.owner_id == c.authuser.user_id):
+                <div>
+                  ${_('Finish pull request')}:
+                  <label>
+                    <input id="save_close" type="checkbox" name="save_close">
+                    ${_("Close")}
+                  </label>
+                  <label>
+                    <input id="save_delete" type="checkbox" name="save_delete" value="delete">
+                    ${_("Delete")}
+                  </label>
+                </div>
+                %endif
         </div>
-        <div id="preview-box_{1}" class="preview-box"></div>
+
       </div>
       <div class="comment-button">
         <div class="submitting-overlay">${_('Submitting ...')}</div>
-        <input type="hidden" name="f_path" value="{0}">
-        <input type="hidden" name="line" value="{1}">
-        ${h.submit('save', _('Comment'), class_='btn btn-small save-inline-form')}
-        ${h.reset('hide-inline-form', _('Cancel'), class_='btn btn-small hide-inline-form')}
-        <div id="preview-btn_{1}" class="preview-btn btn btn-small">${_('Preview')}</div>
-        <div id="edit-btn_{1}" class="edit-btn btn btn-small" style="display:none">${_('Edit')}</div>
+        ${h.submit('save', _('Comment'), class_='btn btn-default btn-sm save-inline-form')}
+        ${h.reset('hide-inline-form', _('Cancel'), class_='btn btn-default btn-sm hide-inline-form')}
       </div>
     ${h.end_form()}
   %else:
@@ -91,7 +111,7 @@
           </div>
       </div>
       <div class="comment-button">
-      ${h.reset('hide-inline-form', _('Hide'), class_='btn btn-small hide-inline-form')}
+      ${h.reset('hide-inline-form', _('Hide'), class_='btn btn-default btn-sm hide-inline-form')}
       </div>
       ${h.end_form()}
   %endif
@@ -113,7 +133,8 @@
 
 ## generate inline comments and the main ones
 <%def name="generate_comments()">
-<div class="comments">
+## original location of comments ... but the ones outside diff context remains here
+<div class="comments inline-comments">
   %for f_path, lines in c.inline_comments:
     %for line_no, comments in lines.iteritems():
       <div class="comments-list-chunk" data-f_path="${f_path}" data-line_no="${line_no}" data-target-id="${h.safeid(h.safe_unicode(f_path))}_${line_no}">
@@ -124,126 +145,44 @@
     %endfor
   %endfor
 
-  <div class="comments-number">
-    ${comment_count(c.inline_cnt, len(c.comments))}
-  </div>
-
-      <div class="comments-list-general">
+      <div class="comments-list-chunk" data-f_path="" data-line_no="" data-target-id="general-comments">
         %for co in c.comments:
             ${comment_block(co)}
         %endfor
       </div>
 </div>
+<div class="comments-number">
+    ${comment_count(c.inline_cnt, len(c.comments))}
+</div>
 </%def>
 
 ## MAIN COMMENT FORM
-<%def name="comments(post_url, cur_status, is_pr=False, change_status=True)">
+<%def name="comments(change_status=True)">
+
+## global, shared for all edit boxes
+<div class="mentions-container" id="mentions_container"></div>
 
-<div class="comments">
-    %if c.authuser.username != 'default':
-    <div class="comment-form ac">
-      ${h.form(post_url, id="main_form")}
-        <div id="edit-container" class="clearfix">
-            <div class="comment-help">
-                ${(_('Comments parsed using %s syntax with %s support.') % (('<a href="%s">RST</a>' % h.url('rst_help')),
-                  '<span style="color:#577632" class="tooltip" title="%s">@mention</span>' %
-                  _('Use @username inside this text to notify another user.')))|n}
-            </div>
-            <div class="mentions-container" id="mentions_container"></div>
-            ${h.textarea('text', class_="comment-block-ta")}
-            %if change_status:
-              <div id="status_block_container" class="status-block">
-                %if is_pr:
-                  ${_('Vote for pull request status')}:
-                %else:
-                  ${_('Set changeset status')}:
-                %endif
-                <input type="radio" class="status_change_radio" name="changeset_status" id="changeset_status_unchanged" value="" checked="checked" />
-                <label for="changeset_status_unchanged">
-                  ${_('No change')}
-                </label>
-                %for status,lbl in c.changeset_statuses:
-                    <span>
-                        <input type="radio" class="status_change_radio" name="changeset_status" id="${status}" value="${status}">
-                        <label for="${status}"><i class="icon-circle changeset-status-${status}" /></i>${lbl}</label>
-                    </span>
-                %endfor
-
-                %if is_pr and ( \
-                    h.HasPermissionAny('hg.admin')() or h.HasRepoPermissionAny('repository.admin')(c.repo_name) \
-                    or c.pull_request.owner.user_id == c.authuser.user_id):
-                  <input id="save_close" type="checkbox" name="save_close">
-                  <label id="save_close_label" for="save_close">${_("Close")}</label>
-                %endif
-              </div>
-            %endif
-        </div>
-
-        <div id="preview-container" class="clearfix" style="display:none">
-            <div class="comment-help">
-                ${_('Comment preview')}
-            </div>
-            <div id="preview-box" class="preview-box"></div>
-        </div>
-
-        <div class="comment-button">
-            ${h.submit('save', _('Comment'), class_="btn")}
-            <div id="preview-btn" class="preview-btn btn">${_('Preview')}</div>
-            <div id="edit-btn" class="edit-btn btn" style="display:none">${_('Edit')}</div>
-        </div>
-      ${h.end_form()}
-    </div>
-    %endif
+<div class="inline-comments inline-comments-general
+            ${'show-general-status' if change_status else ''}">
+  <div id="comments-general-comments" class="">
+  ## comment_div for general comments
+  </div>
 </div>
 
 <script>
 
 $(document).ready(function () {
-   MentionsAutoComplete($('#text'), $('#mentions_container'), _USERS_AC_DATA, _GROUPS_AC_DATA);
 
    $(window).on('beforeunload', function(){
-      if($('.comment-inline-form textarea[name=text]').size() ||
-         $('textarea#text').val()) {
+      var $textareas = $('.comment-inline-form textarea[name=text]');
+      if($textareas.size() > 1 ||
+         $textareas.val()) {
          // this message will not be displayed on all browsers
          // (e.g. some versions of Firefox), but the user will still be warned
          return 'There are uncommitted comments.';
       }
    });
 
-   $('form#main_form').submit(function(){
-      // if no open inline forms, disable the beforeunload check - it would
-      // fail in the check for the textarea we are about to submit
-      if(!$('.form-open').size()){
-          $(window).off('beforeunload');
-      }
-   });
-
-   $('#preview-btn').click(function(){
-       var _text = $('#text').val();
-       if(!_text){
-           return;
-       }
-       var post_data = {'text': _text};
-       $('#preview-box').addClass('unloaded');
-       $('#preview-box').html(_TM['Loading ...']);
-       $('#edit-container').hide();
-       $('#edit-btn').show();
-       $('#preview-container').show();
-       $('#preview-btn').hide();
-
-       var url = pyroutes.url('changeset_comment_preview', {'repo_name': '${c.repo_name}'});
-       ajaxPOST(url,post_data,function(html){
-           $('#preview-box').html(html);
-           $('#preview-box').removeClass('unloaded');
-       });
-   });
-   $('#edit-btn').click(function(){
-       $('#edit-container').show();
-       $('#edit-btn').hide();
-       $('#preview-container').hide();
-       $('#preview-btn').show();
-   });
-
 });
 </script>
 </%def>
--- a/kallithea/templates/changeset/changeset_range.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/changeset/changeset_range.html	Fri Nov 18 01:11:13 2016 +0100
@@ -18,9 +18,9 @@
 
 <%def name="main()">
 ${self.repo_context_bar('changelog')}
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
     <div class="table">
@@ -30,44 +30,47 @@
                     ${h.show_id(c.cs_ranges[0])}
                     <i class="icon-right"></i>
                     ${h.show_id(c.cs_ranges[-1])}
-                    <a style="font-weight: bold" href="${h.url('compare_url',repo_name=c.repo_name,org_ref_type='rev',org_ref_name=getattr(c.cs_ranges[0].parents[0] if c.cs_ranges[0].parents else h.EmptyChangeset(),'raw_id'),other_ref_type='rev',other_ref_name=c.cs_ranges[-1].raw_id)}" class="btn btn-small"><i class="icon-git-compare"></i> Compare Revisions</a>
+                    <a style="font-weight: bold" href="${h.url('compare_url',repo_name=c.repo_name,org_ref_type='rev',org_ref_name=getattr(c.cs_ranges[0].parents[0] if c.cs_ranges[0].parents else h.EmptyChangeset(),'raw_id'),other_ref_type='rev',other_ref_name=c.cs_ranges[-1].raw_id)}" class="btn btn-default btn-sm"><i class="icon-git-compare"></i> Compare Revisions</a>
                 </div>
             </div>
         </div>
         <div id="changeset_compare_view_content">
-            <div class="container">
+          <div class="container">
             <table class="compare_view_commits noborder">
             %for cnt,cs in enumerate(c.cs_ranges):
-                <tr>
-                <td><div class="gravatar">${h.gravatar(h.email_or_none(cs.author), size=14)}</div></td>
+              <tr>
+                %if c.visual.use_gravatar:
+                <td>${h.gravatar_div(h.email_or_none(cs.author), size=14)}</td>
+                %endif
                 <td>${h.link_to('r%s:%s' % (cs.revision,h.short_id(cs.raw_id)),h.url('changeset_home',repo_name=c.cs_repo.repo_name,revision=cs.raw_id))}</td>
                 <td><div class="author">${h.person(cs.author)}</div></td>
-                <td><span class="tooltip" title="${h.age(cs.date)}">${cs.date}</span></td>
+                <td><span data-toggle="tooltip" title="${h.age(cs.date)}">${cs.date}</span></td>
                 <td>
                   %if c.statuses:
                     <div title="${_('Changeset status')}" class="changeset-status-ico"><i class="icon-circle changeset-status-${c.statuses[cnt]}"></i></div>
                   %endif
                 </td>
-                <td><div class="message">${h.urlify_commit(h.wrap_paragraphs(cs.message),c.repo_name)}</div></td>
-                </tr>
+                <td><div class="message">${h.urlify_text(h.wrap_paragraphs(cs.message),c.repo_name)}</div></td>
+              </tr>
             %endfor
             </table>
-            </div>
-            <div style="font-size:1.1em;font-weight: bold;clear:both;padding-top:10px">${_('Files affected')}</div>
-            <div class="cs_files">
+          </div>
+          <div style="font-size:1.1em;font-weight: bold;clear:both;padding-top:10px">${_('Files affected')}</div>
+          <div class="cs_files">
                 %for cs in c.cs_ranges:
                     <div class="cur_cs">${h.link_to(h.show_id(cs),h.url('changeset_home',repo_name=c.cs_repo.repo_name,revision=cs.raw_id))}</div>
-                    %for FID, (cs1, cs2, change, path, diff, stats) in c.changes[cs.raw_id].iteritems():
-                        <div class="cs_${change}">
+                    <% a_rev, cs_rev, file_diff_data = c.changes[cs.raw_id] %>
+                    %for fid, url_fid, op, a_path, path, diff, stats in file_diff_data:
+                        <div class="cs_${op}">
                             <div class="node">
-                                <i class="icon-diff-${change}"></i>
-                                ${h.link_to(h.safe_unicode(path),h.url.current(anchor=FID))}
+                                <i class="icon-diff-${op}"></i>
+                                ${h.link_to(h.safe_unicode(path), '#%s' % fid)}
                             </div>
                             <div class="changes">${h.fancy_file_stats(stats)}</div>
                         </div>
                     %endfor
                 %endfor
-            </div>
+          </div>
         </div>
 
     </div>
@@ -75,14 +78,11 @@
     <%namespace name="diff_block" file="/changeset/diff_block.html"/>
     ${diff_block.diff_block_js()}
     %for cs in c.cs_ranges:
-          ##${comment.comment_inline_form(cs)}
           ## diff block
           <div class="h3">
-          <a class="tooltip" title="${cs.message}" href="${h.url('changeset_home',repo_name=c.cs_repo.repo_name,revision=cs.raw_id)}">${h.show_id(cs)}</a>
-             <div class="gravatar">
-               ${h.gravatar(h.email_or_none(cs.author), size=20)}
-             </div>
-             <div class="right">
+          <a data-toggle="tooltip" title="${cs.message}" href="${h.url('changeset_home',repo_name=c.cs_repo.repo_name,revision=cs.raw_id)}">${h.show_id(cs)}</a>
+            ${h.gravatar_div(h.email_or_none(cs.author), size=20)}
+            <div class="right">
               <span class="logtags">
                 %if len(cs.parents)>1:
                 <span class="merge">${_('Merge')}</span>
@@ -105,9 +105,10 @@
                 %endif
               </span>
             </div>
-           </div>
-          ${diff_block.diff_block(c.changes[cs.raw_id])}
-
+          </div>
+          <% a_rev, cs_rev, file_diff_data = c.changes[cs.raw_id] %>
+          ${diff_block.diff_block(c.repo_name, 'rev', a_rev, a_rev,
+                                  c.repo_name, 'rev', cs_rev, cs_rev, file_diff_data)}
     %endfor
 </div>
 </%def>
--- a/kallithea/templates/changeset/diff_block.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/changeset/diff_block.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,129 +1,103 @@
 ## -*- coding: utf-8 -*-
-##usage:
-## <%namespace name="diff_block" file="/changeset/diff_block.html"/>
-## ${diff_block.diff_block(change)}
-##
-<%def name="diff_block(change)">
+
+<%def name="diff_block(a_repo_name, a_ref_type, a_ref_name, a_rev,
+                       cs_repo_name, cs_ref_name, cs_ref_type, cs_rev,
+                       file_diff_data)">
 <div class="diff-collapse">
-    <span target="${'diff-container-%s' % (id(change))}" class="diff-collapse-button">&uarr; ${_('Collapse Diff')} &uarr;</span>
+    <span target="${'diff-container-%s' % (id(file_diff_data))}" class="diff-collapse-button">&uarr; ${_('Collapse Diff')} &uarr;</span>
+</div>
+<div class="diff-container" id="${'diff-container-%s' % (id(file_diff_data))}">
+%for id_fid, url_fid, op, a_filename, cs_filename, diff, stats in file_diff_data:
+    ${diff_block_diffblock(id_fid, url_fid, op, diff,
+        a_repo_name, a_rev, a_ref_type, a_ref_name, a_filename,
+        cs_repo_name, cs_rev, cs_ref_type, cs_ref_name, cs_filename)}
+%endfor
 </div>
-<div class="diff-container" id="${'diff-container-%s' % (id(change))}">
-%for FID,(cs1, cs2, change, path, diff, stats) in change.iteritems():
-    <div id="${FID}_target" style="clear:both;margin-top:25px"></div>
-    <div id="${FID}" class="diffblock  margined comm">
+</%def>
+
+<%def name="diff_block_diffblock(id_fid, url_fid, op, diff,
+    a_repo_name, a_rev, a_ref_type, a_ref_name, a_filename,
+    cs_repo_name, cs_rev, cs_ref_type, cs_ref_name, cs_filename)"
+>
+    <div id="${id_fid}_target" style="clear:both;margin-top:25px"></div>
+    <div id="${id_fid}" class="diffblock margined comm">
         <div class="code-header">
             <div class="changeset_header">
                 <div class="changeset_file">
-                    ${h.link_to_if(change!='D',h.safe_unicode(path),h.url('files_home',repo_name=c.repo_name,
-                    revision=cs2,f_path=h.safe_unicode(path)))}
+                    ${h.safe_unicode(cs_filename)}
                 </div>
                 <div class="diff-actions">
-                  <a href="${h.url('files_diff_home',repo_name=c.repo_name,f_path=h.safe_unicode(path),diff2=cs2,diff1=cs1,diff='diff',fulldiff=1)}" class="tooltip" title="${_('Show full diff for this file')}">
-                      <i class="icon-file-code"></i>
-                  </a>
-                  <a href="${h.url('files_diff_2way_home',repo_name=c.repo_name,f_path=h.safe_unicode(path),diff2=cs2,diff1=cs1,diff='diff',fulldiff=1)}" class="tooltip" title="${_('Show full side-by-side diff for this file')}">
-                      <i class="icon-docs"></i>
-                  </a>
-                  <a href="${h.url('files_diff_home',repo_name=c.repo_name,f_path=h.safe_unicode(path),diff2=cs2,diff1=cs1,diff='raw')}" class="tooltip" title="${_('Raw diff')}">
-                      <i class="icon-diff"></i>
-                  </a>
-                  <a href="${h.url('files_diff_home',repo_name=c.repo_name,f_path=h.safe_unicode(path),diff2=cs2,diff1=cs1,diff='download')}" class="tooltip" title="${_('Download diff')}">
-                      <i class="icon-floppy"></i>
-                  </a>
-                  ${c.ignorews_url(request.GET, h.FID(cs2,path))}
-                  ${c.context_url(request.GET, h.FID(cs2,path))}
+                  <span style="margin: 0 10px">
+                    %if op == 'A':
+                      <span class="no-file" data-toggle="tooltip" title="${_("No file before")}">
+                        <i class="icon-minus-circled"></i></span>
+                    %else:
+                      <a href="${h.url('files_home', repo_name=a_repo_name, f_path=a_filename, revision=a_rev)}" data-toggle="tooltip" title="${_("File before")}">
+                        <i class="icon-doc"></i></a>
+                    %endif
+
+                    %if op == 'A':
+                      <span class="arrow" data-toggle="tooltip" title="${_("Added")}">&#10142;</span>
+                    %elif op == 'M':
+                      <span class="arrow" data-toggle="tooltip" title="${_("Modified")}">&#10142;</span>
+                    %elif op == 'D':
+                      <span class="arrow" data-toggle="tooltip" title="${_("Deleted")}">&#10142;</span>
+                    %elif op == 'R':
+                      <span class="arrow" data-toggle="tooltip" title="${_("Renamed")}">&#10142;</span>
+                    %elif op is None:
+                      <span class="arrow" data-toggle="tooltip" title="${_("No change")}">&#10142;</span>
+                    %else:
+                      <span class="arrow" data-toggle="tooltip" title="${_("Unknown operation: %r") % op}">&#10142;</span>
+                    %endif
+
+                    %if op == 'D':
+                      <span class="no-file" data-toggle="tooltip" title="${_("No file after")}">
+                        <i class="icon-minus-circled"></i></span>
+                    %else:
+                      <a href="${h.url('files_home', repo_name=cs_repo_name, f_path=cs_filename, revision=cs_rev)}" data-toggle="tooltip" title="${_("File after")}">
+                        <i class="icon-doc"></i></a>
+                    %endif
+                  </span>
+
+                  <a href="${h.url('files_diff_home',repo_name=cs_repo_name,f_path=h.safe_unicode(cs_filename),diff2=cs_rev,diff1=a_rev,diff='diff',fulldiff=1)}" data-toggle="tooltip" title="${_('Show full diff for this file')}">
+                      <i class="icon-file-code"></i></a>
+                  <a href="${h.url('files_diff_2way_home',repo_name=cs_repo_name,f_path=h.safe_unicode(cs_filename),diff2=cs_rev,diff1=a_rev,diff='diff',fulldiff=1)}" data-toggle="tooltip" title="${_('Show full side-by-side diff for this file')}">
+                      <i class="icon-docs"></i></a>
+                  <a href="${h.url('files_diff_home',repo_name=cs_repo_name,f_path=h.safe_unicode(cs_filename),diff2=cs_rev,diff1=a_rev,diff='raw')}" data-toggle="tooltip" title="${_('Raw diff')}">
+                      <i class="icon-diff"></i></a>
+                  <a href="${h.url('files_diff_home',repo_name=cs_repo_name,f_path=h.safe_unicode(cs_filename),diff2=cs_rev,diff1=a_rev,diff='download')}" data-toggle="tooltip" title="${_('Download diff')}">
+                      <i class="icon-floppy"></i></a>
+                  ${c.ignorews_url(request.GET, url_fid)}
+                  ${c.context_url(request.GET, url_fid)}
                 </div>
                 <span style="float:right;margin-top:-3px">
-                  <label>
-                  ${_('Show inline comments')}
-                  ${h.checkbox('',checked="checked",class_="show-inline-comments",id_for=h.FID(cs2,path))}
-                  </label>
+                    <label>
+                        ${_('Show inline comments')}
+                        ${h.checkbox('',checked="checked",class_="show-inline-comments",id_for=url_fid)}
+                    </label>
                 </span>
             </div>
         </div>
-        <div class="code-body full_f_path" data-f_path="${h.safe_unicode(path)}">
+        <div class="code-body full_f_path" data-f_path="${h.safe_unicode(cs_filename)}">
             ${diff|n}
-            %if path.rsplit('.')[-1] in ['png', 'gif', 'jpg', 'bmp']:
+            %if cs_filename.rsplit('.')[-1] in ['png', 'gif', 'jpg', 'bmp']:
               <div class="btn btn-image-diff-show">Show images</div>
-              %if change =='M':
-                <div id="${FID}_image-diff" class="btn btn-image-diff-swap" style="display:none">Press to swap images</div>
+              %if op == 'M':
+                <div id="${id_fid}_image-diff" class="btn btn-image-diff-swap" style="display:none">Press to swap images</div>
               %endif
               <div style="font-size: 0">
-                %if change == 'M':
-                  <img id="${FID}_image-diff-img-a" class="img-diff img-diff-swapable" style="display:none"
-                      realsrc="${h.url('files_raw_home',repo_name=c.repo_name,revision=cs1,f_path=path)}" />
+                %if op in 'DM':
+                  <img id="${id_fid}_image-diff-img-a" class="img-diff img-diff-swapable" style="display:none"
+                      realsrc="${h.url('files_raw_home',repo_name=a_repo_name,revision=a_rev,f_path=a_filename)}" />
                 %endif
-                %if change in 'AM':
-                  <img id="${FID}_image-diff-img-b" class="img-diff img-diff-swapable" style="display:none"
-                      realsrc="${h.url('files_raw_home',repo_name=c.repo_name,revision=cs2,f_path=path)}" />
+                %if op in 'AM':
+                  <img id="${id_fid}_image-diff-img-b" class="img-diff img-diff-swapable" style="display:none"
+                      realsrc="${h.url('files_raw_home',repo_name=cs_repo_name,revision=cs_rev,f_path=cs_filename)}" />
                 %endif
               </div>
             %endif
         </div>
     </div>
-%endfor
-</div>
-</%def>
-
-<%def name="diff_block_simple(change)">
-
-  %for op,filenode_path,diff in change:
-    <div id="${h.FID('',filenode_path)}_target" style="clear:both;margin-top:25px"></div>
-    <div id="${h.FID('',filenode_path)}" class="diffblock  margined comm">
-      <div class="code-header">
-          <div class="changeset_header">
-              <div class="changeset_file">
-                  ${h.safe_unicode(filenode_path)} |
-                  ## TODO: link to ancestor and head of other instead of exactly other
-                  %if op == 'A':
-                    ${_('Added')}
-                    <a class="spantag" href="${h.url('files_home', repo_name=c.cs_repo.repo_name, f_path=filenode_path, revision=c.cs_rev)}">${h.short_id(c.cs_ref_name) if c.cs_ref_type=='rev' else c.cs_ref_name}</a>
-                  %elif op == 'M':
-                    <a class="spantag" href="${h.url('files_home', repo_name=c.a_repo.repo_name, f_path=filenode_path, revision=c.a_rev)}">${h.short_id(c.a_ref_name) if c.a_ref_type=='rev' else c.a_ref_name}</a>
-                    <i class="icon-right"></i>
-                    <a class="spantag" href="${h.url('files_home', repo_name=c.cs_repo.repo_name, f_path=filenode_path, revision=c.cs_rev)}">${h.short_id(c.cs_ref_name) if c.cs_ref_type=='rev' else c.cs_ref_name}</a>
-                  %elif op == 'D':
-                    ${_('Deleted')}
-                    <a class="spantag" href="${h.url('files_home', repo_name=c.a_repo.repo_name, f_path=filenode_path, revision=c.a_rev)}">${h.short_id(c.a_ref_name) if c.a_ref_type=='rev' else c.a_ref_name}</a>
-                  %elif op == 'R':
-                    ${_('Renamed')}
-                    <a class="spantag" href="${h.url('files_home', repo_name=c.a_repo.repo_name, f_path=filenode_path, revision=c.a_rev)}">${h.short_id(c.a_ref_name) if c.a_ref_type=='rev' else c.a_ref_name}</a>
-                    <i class="icon-right"></i>
-                    <a class="spantag" href="${h.url('files_home', repo_name=c.cs_repo.repo_name, f_path=filenode_path, revision=c.cs_rev)}">${h.short_id(c.cs_ref_name) if c.cs_ref_type=='rev' else c.cs_ref_name}</a>
-                  %else:
-                    ${op}???
-                  %endif
-              </div>
-              <div class="diff-actions">
-                <a href="${h.url('files_diff_2way_home',repo_name=c.cs_repo.repo_name,f_path=h.safe_unicode(filenode_path),diff1=c.a_rev,diff2=c.cs_rev,diff='diff',fulldiff=1)}" class="tooltip" title="${_('Show full side-by-side diff for this file')}">
-                  <i class="icon-docs"></i>
-                </a>
-                ${c.ignorews_url(request.GET)}
-                ${c.context_url(request.GET)}
-              </div>
-          </div>
-      </div>
-        <div class="code-body full_f_path" data-f_path="${h.safe_unicode(filenode_path)}">
-            ${diff|n}
-            %if filenode_path.rsplit('.')[-1] in ['png', 'gif', 'jpg', 'bmp']:
-              <div class="btn btn-image-diff-show">Show images</div>
-              %if op == 'M':
-                <div id="${h.FID('',filenode_path)}_image-diff" class="btn btn-image-diff-swap" style="display:none">Press to swap images</div>
-              %endif
-              <div style="font-size: 0">
-                %if op == 'M':
-                  <img id="${h.FID('',filenode_path)}_image-diff-img-a" class="img-diff img-diff-swapable" style="display:none"
-                      realsrc="${h.url('files_raw_home',repo_name=c.a_repo.repo_name,revision=c.a_rev,f_path=filenode_path) if op in 'DM' else ''}" />
-                %endif
-                %if op in 'AM':
-                  <img id="${h.FID('',filenode_path)}_image-diff-img-b" class="img-diff img-diff-swapable" style="display:none"
-                      realsrc="${h.url('files_raw_home',repo_name=c.cs_repo.repo_name,revision=c.cs_rev,f_path=filenode_path) if op in 'AM' else ''}" />
-                %endif
-              </div>
-            %endif
-        </div>
-    </div>
-  %endfor
 </%def>
 
 <%def name="diff_block_js()">
@@ -149,6 +123,31 @@
     };
     $('.btn-image-diff-swap').mouseup(reset);
     $('.btn-image-diff-swap').mouseleave(reset);
+
+    $('.diff-collapse-button').click(function(e) {
+        var $button = $(e.currentTarget);
+        var $target = $('#' + $button.attr('target'));
+        if($target.hasClass('hidden')){
+            $target.removeClass('hidden');
+            $button.html("&uarr; {0} &uarr;".format(_TM['Collapse Diff']));
+        }
+        else if(!$target.hasClass('hidden')){
+            $target.addClass('hidden');
+            $button.html("&darr; {0} &darr;".format(_TM['Expand Diff']));
+        }
+    });
+    $('.show-inline-comments').change(function(e){
+        var target = e.currentTarget;
+        if(target == null){
+            target = this;
+        }
+        var boxid = $(target).attr('id_for');
+        if(target.checked){
+            $('#{0} .inline-comments'.format(boxid)).show();
+        }else{
+            $('#{0} .inline-comments'.format(boxid)).hide();
+        }
+    });
 });
 </script>
 </%def>
--- a/kallithea/templates/compare/compare_cs.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/compare/compare_cs.html	Fri Nov 18 01:11:13 2016 +0100
@@ -4,10 +4,23 @@
     <span class="empty_data">${_('No changesets')}</span>
   %else:
 
-    %if c.ancestor:
-    <div class="ancestor">${_('Ancestor')}:
-      ${h.link_to(h.short_id(c.ancestor),h.url('changeset_home',repo_name=c.repo_name,revision=c.ancestor))}
-    </div>
+    %if c.ancestors:
+      <div class="ancestor">
+        %if len(c.ancestors) > 1:
+        <div style="color:red; font-weight: bold">
+          ${_('Criss cross merge situation with multiple merge ancestors detected!')}
+        </div>
+        <div style="color:red">
+          ${_('Please merge the target branch to your branch before creating a pull request.')}
+        </div>
+        %endif
+        <div>
+          ${_('Merge Ancestor')}:
+          %for ancestor in c.ancestors:
+            ${h.link_to(h.short_id(ancestor),h.url('changeset_home',repo_name=c.repo_name,revision=ancestor), class_="changeset_hash")}
+          %endfor
+        </div>
+      </div>
     %endif
 
     <div id="graph_nodes">
@@ -18,7 +31,7 @@
 
     <table class="compare_view_commits noborder">
     %for cnt, cs in enumerate(reversed(c.cs_ranges)):
-        <tr id="chg_${cnt+1}">
+      <tr id="chg_${cnt+1}" class="${'mergerow' if len(cs.parents) > 1 else ''}">
         <td style="width:50px">
           %if cs.raw_id in c.statuses:
             <div title="${_('Changeset status: %s') % c.statuses[cs.raw_id][1]}" class="changeset-status-ico">
@@ -47,14 +60,16 @@
               else:
                   title = _('Position in this list of changesets')
           %>
-          <span class="tooltip" title="${title}">
+          <span data-toggle="tooltip" title="${title}">
             ${index}
           </span>
         </td>
-        <td style="width: 140px"><span class="tooltip" title="${h.age(cs.date)}">${cs.date}</span></td>
-        <td><div class="gravatar" commit_id="${cs.raw_id}">${h.gravatar(h.email_or_none(cs.author), size=14)}</div></td>
+        <td style="width: 140px"><span data-toggle="tooltip" title="${h.age(cs.date)}">${cs.date}</span></td>
+        %if c.visual.use_gravatar:
+        <td>${h.gravatar_div(h.email_or_none(cs.author), size=14, div_commit_id="${cs.raw_id}")}</td>
+        %endif
         <td><div class="author">${h.person(cs.author)}</div></td>
-        <td>${h.link_to(h.show_id(cs),h.url('changeset_home',repo_name=c.cs_repo.repo_name,revision=cs.raw_id))}</td>
+        <td>${h.link_to(h.show_id(cs),h.url('changeset_home',repo_name=c.cs_repo.repo_name,revision=cs.raw_id), class_='changeset_hash')}</td>
         <td>
         %if cs.branch:
         <span class="branchtag">${h.link_to(cs.branch,h.url('changelog_home',repo_name=c.cs_repo.repo_name,branch=cs.branch))}</span>
@@ -63,8 +78,17 @@
         <td class="expand_commit" commit_id="${cs.raw_id}" title="${_('Expand commit message')}">
             <i class="icon-align-left" style="color:#999"></i>
         </td>
-        <td><div id="C-${cs.raw_id}" class="message">${h.urlify_commit(cs.message, c.repo_name)}</div></td>
-        </tr>
+        <td>
+            <div style="float: right; margin-top: -4px;">
+                %for tag in cs.tags:
+                    <span class="tagtag" title="${_('Tag %s') % tag}">
+                        ${h.link_to(tag,h.url('changeset_home',repo_name=c.repo_name,revision=cs.raw_id))}
+                    </span>
+                %endfor
+            </div>
+            <div id="C-${cs.raw_id}" class="message">${h.urlify_text(cs.message, c.repo_name)}</div>
+        </td>
+      </tr>
     %endfor
     </table>
 
@@ -82,14 +106,6 @@
           merge='1')
         )}
       </div>
-      <div style="font-size:1.1em;font-weight: bold;clear:both;padding-top:10px">
-        ${_('Common ancestor')}:
-        %if c.ancestor:
-        ${h.link_to(h.short_id(c.ancestor),h.url('changeset_home',repo_name=c.repo_name,revision=c.ancestor))}
-        %else:
-        ${_('No common ancestor found - repositories are unrelated')}
-        %endif
-      </div>
     %endif
     %if c.cs_ranges_org is not None:
       ## TODO: list actual changesets?
@@ -116,13 +132,13 @@
 %if not c.as_form:
         var jsdata = ${c.jsdata|n};
         var r = new BranchRenderer('graph_canvas', 'graph_content_pr', 'chg_');
-        r.render(jsdata,100);
+        r.render(jsdata);
 %endif
 
         $('.expand_commit').click(function(e){
             var cid = $(this).attr('commit_id');
             $('#C-'+cid).toggleClass('expanded');
-            r.render(jsdata,100);
+            r.render(jsdata);
         });
 
         $('.gravatar').click(function(e){
--- a/kallithea/templates/compare/compare_diff.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/compare/compare_diff.html	Fri Nov 18 01:11:13 2016 +0100
@@ -19,27 +19,33 @@
 
 <%def name="main()">
 ${self.repo_context_bar('changelog')}
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
     <div class="table">
         <div id="body" class="diffblock">
-            <div class="code-header">
+            <div class="compare-revision-selector">
+                ## divs are "inline-block" and cannot have whitespace between them.
                 <div>
-                    ${h.hidden('compare_org')} <i class="icon-right"></i> ${h.hidden('compare_other')}
+                    ${h.hidden('compare_org')}
+                </div><div>
+                    <i class="icon-right"></i>
+                </div><div>
+                    ${h.hidden('compare_other')}
+                </div><div>
                     %if not c.compare_home:
-                        <a class="btn btn-small" href="${c.swap_url}"><i class="icon-arrows-cw"></i> ${_('Swap')}</a>
+                        <a class="btn btn-default btn-sm" href="${c.swap_url}"><i class="icon-arrows-cw"></i> ${_('Swap')}</a>
                     %endif
-                    <div id="compare_revs" class="btn btn-small"><i class="icon-git-compare"></i> ${_('Compare Revisions')}</div>
+                    <div id="compare_revs" class="btn btn-default btn-sm"><i class="icon-git-compare"></i> ${_('Compare Revisions')}</div>
                 </div>
             </div>
         </div>
 
     %if c.compare_home:
         <div id="changeset_compare_view_content">
-         <div style="color:#999;font-size: 18px">${_('Compare revisions, branches, bookmarks, or tags.')}</div>
+         <div class="text-muted" style="font-size: 18px">${_('Compare revisions, branches, bookmarks, or tags.')}</div>
         </div>
     %else:
         <div id="changeset_compare_view_content">
@@ -51,9 +57,9 @@
                 <div style="font-size:1.1em;font-weight: bold;clear:both;padding-top:10px">
 
                 % if c.limited_diff:
-                    ${ungettext('%s file changed', '%s files changed', len(c.files)) % len(c.files)}
+                    ${ungettext('%s file changed', '%s files changed', len(c.file_diff_data)) % len(c.file_diff_data)}:
                 % else:
-                    ${ungettext('%s file changed with %s insertions and %s deletions','%s files changed with %s insertions and %s deletions', len(c.files)) % (len(c.files),c.lines_added,c.lines_deleted)}:
+                    ${ungettext('%s file changed with %s insertions and %s deletions','%s files changed with %s insertions and %s deletions', len(c.file_diff_data)) % (len(c.file_diff_data),c.lines_added,c.lines_deleted)}:
                 %endif
 
                 ${c.ignorews_url(request.GET)}
@@ -61,30 +67,29 @@
 
                 </div>
                 <div class="cs_files">
-                  %if not c.files:
+                  %if not c.file_diff_data:
                      <span class="empty_data">${_('No files')}</span>
                   %endif
-                  %for fid, change, f, stat in c.files:
-                     <div class="cs_${change}">
-                         <div class="node">
-                             <i class="icon-diff-${change}"></i>
-                             ${h.link_to(h.safe_unicode(f), '#' + fid)}
-                         </div>
-                         <div class="changes">${h.fancy_file_stats(stat)}</div>
-                     </div>
+                  %for fid, url_fid, op, a_path, path, diff, stats in c.file_diff_data:
+                    <div class="cs_${op}">
+                      <div class="node">
+                          <i class="icon-diff-${op}"></i>
+                          ${h.link_to(h.safe_unicode(path), '#%s' % fid)}
+                      </div>
+                      <div class="changes">${h.fancy_file_stats(stats)}</div>
+                    </div>
                   %endfor
+                  %if c.limited_diff:
+                    <h5>${_('Changeset was too big and was cut off...')} <a href="${h.url.current(fulldiff=1, **request.GET.mixed())}">${_('Show full diff anyway')}</a></h5>
+                  %endif
                 </div>
-                % if c.limited_diff:
-                  <h5>${_('Changeset was too big and was cut off...')} <a href="${h.url.current(fulldiff=1, **request.GET.mixed())}">${_('Show full diff')}</a></h5>
-                % endif
          </div>
 
         ## diff block
         <%namespace name="diff_block" file="/changeset/diff_block.html"/>
         ${diff_block.diff_block_js()}
-        %for fid, change, f, stat in c.files:
-          ${diff_block.diff_block_simple([c.changes[fid]])}
-        %endfor
+        ${diff_block.diff_block(c.a_repo.repo_name, c.a_ref_type, c.a_ref_name, c.a_rev,
+                                c.cs_repo.repo_name, c.cs_ref_type, c.cs_ref_name, c.cs_rev, c.file_diff_data)}
         % if c.limited_diff:
           <h4>${_('Changeset was too big and was cut off...')} <a href="${h.url.current(fulldiff=1, **request.GET.mixed())}">${_('Show full diff')}</a></h4>
         % endif
@@ -104,20 +109,25 @@
             return '{0}@{1}'.format(repo_name, obj.text);
         },
         dropdownAutoWidth: true,
+        maxResults: 50,
         query: function(query){
           var key = cache_key;
           var cached = cache[key] ;
           if(cached) {
             var data = {results: []};
+            var queryLower = query.term.toLowerCase();
             //filter results
             $.each(cached.results, function(){
                 var section = this.text;
                 var children = [];
                 $.each(this.children, function(){
-                    if(query.term.length == 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){
+                    if(children.length < 50 ?
+                       ((queryLower.length == 0) || (this.text.toLowerCase().indexOf(queryLower) >= 0)) :
+                       ((queryLower.length != 0) && (this.text.toLowerCase().indexOf(queryLower) == 0))) {
                         children.push(this);
                     }
                 });
+                children = branchSort(children, undefined, query)
                 data.results.push({'text': section, 'children': children});
             });
             //push the typed in changeset
--- a/kallithea/templates/data_table/_dt_elements.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/data_table/_dt_elements.html	Fri Nov 18 01:11:13 2016 +0100
@@ -87,13 +87,13 @@
 </%def>
 
 <%def name="last_change(last_change)">
-  <span class="tooltip" date="${last_change}" title="${h.fmt_date(last_change)}">${h.age(last_change)}</span>
+  <span data-toggle="tooltip" title="${h.fmt_date(last_change)}" date="${last_change}">${h.age(last_change)}</span>
 </%def>
 
 <%def name="revision(name,rev,tip,author,last_msg)">
   <div>
   %if rev >= 0:
-      <a title="${'%s:\n\n%s' % (h.escape(author), h.escape(last_msg))}" class="tooltip revision-link safe-html-title" href="${h.url('changeset_home',repo_name=name,revision=tip)}">${'r%s:%s' % (rev,h.short_id(tip))}</a>
+      <a data-toggle="tooltip" title="${'%s:\n\n%s' % (h.escape(author), h.escape(last_msg))}" class="revision-link safe-html-title" href="${h.url('changeset_home',repo_name=name,revision=tip)}">${'r%s:%s' % (rev,h.short_id(tip))}</a>
   %else:
       ${_('No changesets yet')}
   %endif
@@ -120,13 +120,13 @@
   <div>
     <div style="float:left; margin-right:5px;" class="grid_edit">
       <a href="${h.url('edit_repo',repo_name=repo_name)}" title="${_('Edit')}">
-        <i class="icon-pencil"></i> ${h.submit('edit_%s' % repo_name,_('Edit'),class_="action_button")}
+        <i class="icon-pencil"></i> ${h.submit('edit_%s' % repo_name,_('Edit'),class_="btn btn-default btn-xs")}
       </a>
     </div>
     <div style="float:left" class="grid_delete">
-      ${h.form(h.url('delete_repo', repo_name=repo_name), method='delete')}
+      ${h.form(h.url('delete_repo', repo_name=repo_name))}
         <i class="icon-minus-circled" style="color:#FF4444"></i>
-        ${h.submit('remove_%s' % repo_name,_('Delete'),class_="action_button",
+        ${h.submit('remove_%s' % repo_name,_('Delete'),class_="btn btn-default btn-xs",
         onclick="return confirm('"+_('Confirm to delete this repository: %s') % repo_name+"');")}
       ${h.end_form()}
     </div>
@@ -135,12 +135,12 @@
 
 <%def name="repo_state(repo_state)">
   <div>
-    %if repo_state == 'repo_state_pending':
-        <div class="btn btn-mini btn-info disabled">${_('Creating')}</div>
-    %elif repo_state == 'repo_state_created':
-        <div class="btn btn-mini btn-success disabled">${_('Created')}</div>
+    %if repo_state == u'repo_state_pending':
+        <div class="label label-info">${_('Creating')}</div>
+    %elif repo_state == u'repo_state_created':
+        <div class="label label-success">${_('Created')}</div>
     %else:
-        <div class="btn btn-mini btn-danger disabled" title="${repo_state}">invalid</div>
+        <div class="label label-danger" title="${repo_state}">invalid</div>
     %endif
   </div>
 </%def>
@@ -148,13 +148,13 @@
 <%def name="user_actions(user_id, username)">
  <div style="float:left" class="grid_edit">
    <a href="${h.url('edit_user',id=user_id)}" title="${_('Edit')}">
-     <i class="icon-pencil"></i> ${h.submit('edit_%s' % username,_('Edit'),class_="action_button")}
+     <i class="icon-pencil"></i> ${h.submit('edit_%s' % username,_('Edit'),class_="btn btn-default btn-xs")}
    </a>
  </div>
  <div style="float:left" class="grid_delete">
-  ${h.form(h.url('delete_user', id=user_id),method='delete')}
+  ${h.form(h.url('delete_user', id=user_id))}
     <i class="icon-minus-circled" style="color:#FF4444"></i>
-    ${h.submit('remove_',_('Delete'),id="remove_user_%s" % user_id, class_="action_button",
+    ${h.submit('remove_',_('Delete'),id="remove_user_%s" % user_id, class_="btn btn-default btn-xs",
     onclick="return confirm('"+_('Confirm to delete this user: %s') % username+"');")}
   ${h.end_form()}
  </div>
@@ -164,13 +164,13 @@
  <div style="float:left" class="grid_edit">
     <a href="${h.url('edit_users_group', id=user_group_id)}" title="${_('Edit')}">
     <i class="icon-pencil"></i>
-     ${h.submit('edit_%s' % user_group_name,_('Edit'),class_="action_button", id_="submit_user_group_edit")}
+     ${h.submit('edit_%s' % user_group_name,_('Edit'),class_="btn btn-default btn-xs", id_="submit_user_group_edit")}
     </a>
  </div>
  <div style="float:left" class="grid_delete">
-    ${h.form(h.url('users_group', id=user_group_id),method='delete')}
+    ${h.form(h.url('delete_users_group', id=user_group_id))}
       <i class="icon-minus-circled" style="color:#FF4444"></i>
-      ${h.submit('remove_',_('Delete'),id="remove_group_%s" % user_group_id, class_="action_button",
+      ${h.submit('remove_',_('Delete'),id="remove_group_%s" % user_group_id, class_="btn btn-default btn-xs",
       onclick="return confirm('"+_('Confirm to delete this user group: %s') % user_group_name+"');")}
     ${h.end_form()}
  </div>
@@ -180,13 +180,13 @@
  <div style="float:left" class="grid_edit">
     <a href="${h.url('edit_repo_group',group_name=repo_group_name)}" title="${_('Edit')}">
     <i class="icon-pencil"></i>
-     ${h.submit('edit_%s' % repo_group_name, _('Edit'),class_="action_button")}
+     ${h.submit('edit_%s' % repo_group_name, _('Edit'),class_="btn btn-default btn-xs")}
     </a>
  </div>
  <div style="float:left" class="grid_delete">
-    ${h.form(h.url('repos_group', group_name=repo_group_name),method='delete')}
+    ${h.form(h.url('delete_repos_group', group_name=repo_group_name))}
         <i class="icon-minus-circled" style="color:#FF4444"></i>
-        ${h.submit('remove_%s' % repo_group_name,_('Delete'),class_="action_button",
+        ${h.submit('remove_%s' % repo_group_name,_('Delete'),class_="btn btn-default btn-xs",
         onclick="return confirm('"+ungettext('Confirm to delete this group: %s with %s repository','Confirm to delete this group: %s with %s repositories',gr_count) % (repo_group_name, gr_count)+"');")}
     ${h.end_form()}
  </div>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/templates/email_templates/button.html	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,26 @@
+<%page args="url,title='',padding_top=True,padding_bottom=True" />\
+##<!-- button -->
+<table cellspacing="0" cellpadding="0" style="margin-left:auto;margin-right:auto">
+    %if padding_top:
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    %endif
+    <tr>
+        <td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px ${color_button}">
+            <a href="${url}" style="text-decoration:none;display:block" target="_blank">
+                <center style="padding:11px 20px">
+                    <font size="3">
+                        <span style="${sans_style};font-weight:700;font-size:15px;line-height:14px;color:${color_button};white-space:nowrap;vertical-align:middle">${_(title)}</span>
+                    </font>
+                </center>
+            </a>
+        </td>
+    </tr>
+    %if padding_bottom:
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    %endif
+</table>
+##<!-- /button -->
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/templates/email_templates/button.txt	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,3 @@
+<%page args="url,title" />\
+
+${title|n,unicode}: ${url}
--- a/kallithea/templates/email_templates/changeset_comment.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/email_templates/changeset_comment.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,20 +1,39 @@
-## -*- coding: utf-8 -*-
-<%inherit file="main.html"/>
-
-%if is_mention:
-<p>${_('Comment from %s on %s changeset %s mentioned you') % (cs_comment_user, cs_target_repo, h.short_id(raw_id))}:</p>
-%else:
-<p>${_('Comment from %s on %s changeset %s') % (cs_comment_user, cs_target_repo, h.short_id(raw_id))}:</p>
-%endif
-<p>${body}</p>
-
-%if status_change:
-    <p>${_('The changeset status was changed to')}: <b>${status_change}</b></p>
-%endif
-
-<p>${_('URL')}: <a href="${cs_comment_url}">${cs_comment_url}</a></p>
-
-<p>${_('Changeset')}: ${h.short_id(raw_id)}</p>
-<p>${_('Description')}:<br/>
-${h.shorter(message, 256)}
-</p>
+<%inherit file="main.html"/>\
+\
+<%block name="header">\
+<% title = _('Mention in Comment on Changeset "%s"') % h.shorter(message, 200, firstline=True) if is_mention else _('Comment on Changeset "%s"') % h.shorter(message, 200, firstline=True) %>\
+<%include file="header.html" args="title=title,link=cs_comment_url"/>\
+</%block>\
+\
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+<%include file="comment.html" args="text=body,author=cs_comment_user,status=status_change"/>\
+        </td>
+    </tr>
+    <tr>
+        <td height="30px"></td>
+    </tr>
+    <tr>
+        <td>
+            <div>
+                ${_('Changeset on')}
+                <a style="color:${color_link};text-decoration:none"
+                   href="${cs_target_repo}">${cs_target_repo}</a>
+                ${_('branch')}
+                <span style="color:${color_link}">${branch}</span>:
+            </div>
+            <div>
+                "<a style="color:${color_link};text-decoration:none"
+                   href="${cs_url}">${h.shorter(message, 60, firstline=True)}</a>"
+                ${_('by')}
+                <span style="color:${color_link}">${cs_author.full_name_and_username}</span>.
+            </div>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<%include file="button.html" args="url=cs_comment_url,title=_('View Comment'),padding_bottom=False"/>\
+        </td>
+    </tr>
+</table>
--- a/kallithea/templates/email_templates/changeset_comment.txt	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/email_templates/changeset_comment.txt	Fri Nov 18 01:11:13 2016 +0100
@@ -1,19 +1,16 @@
-## -*- coding: utf-8 -*-
-<%inherit file="main.txt"/>
+<%block name="header">\
+<% title = _('Mention in Comment on Changeset "%s"') % h.shorter(message, 200, firstline=True) if is_mention else _('Comment on Changeset "%s"') % h.shorter(message, 200, firstline=True) %>\
+<%include file="header.txt" args="title=title,link=cs_comment_url"/>\
+</%block>\
 
-%if is_mention:
-${_('Comment from %s on %s changeset %s mentioned you') % (cs_comment_user, cs_target_repo, h.short_id(raw_id))|n,unicode}:
-%else:
-${_('Comment from %s on %s changeset %s') % (cs_comment_user, cs_target_repo, h.short_id(raw_id))|n,unicode}:
-%endif
-${body|n,unicode}
+<%include file="comment.txt" args="text=body,author=cs_comment_user,status=status_change"/>\
 
-%if status_change:
-${_('The changeset status was changed to')|n,unicode}: ${status_change|n,unicode}
-%endif
+${_('Changeset on')|n,unicode} \
+${cs_target_repo|n,unicode} \
+${_('branch')|n,unicode} \
+${branch|n,unicode}:
+"${h.shorter(message, 60, firstline=True)|n,unicode}" \
+${_('by')|n,unicode} \
+${cs_author.full_name_and_username|n,unicode}.
 
-${_('URL')|n,unicode}: ${cs_comment_url|n,unicode}
-
-${_('Changeset')|n,unicode}: ${h.short_id(raw_id)|n,unicode}
-${_('Description')|n,unicode}:
-${h.shorter(message, 256)|n,unicode}
+<%include file="button.txt" args="url=cs_comment_url,title=_('View Comment')"/>\
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/templates/email_templates/comment.html	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,57 @@
+<%page args="author,text,status,close=False" />\
+\
+##<!-- comment ->
+<table cellpadding="0" cellspacing="0" width="100%" border="0" bgcolor="${color_background_grey}" style="border:1px solid ${color_border};border-radius:4px">
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-weight:600;color:${color_emph}">${author}</div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3" style="border-bottom:1px solid ${color_border}"></td>
+    </tr>
+    %if status or close:
+        <tr>
+            <td height="10px" colspan="3"></td>
+        </tr>
+        <tr>
+            <td width="20px"></td>
+            <td>
+                %if status:
+                    <div style="font-weight:600">
+                        ${_('Status change:')}
+                        ${status}
+                    </div>
+                %endif
+                %if close:
+                    <div style="font-weight:600">
+                        ${_('The pull request has been closed.')}
+                    </div>
+                %endif
+            </td>
+            <td width="20px"></td>
+        </tr>
+        <tr>
+            <td height="10px" colspan="3" style="border-bottom:1px solid ${color_border}"></td>
+        </tr>
+    %endif
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="${comment_style}">${text}</div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+</table>
+##<!-- /comment ->
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/templates/email_templates/comment.txt	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,15 @@
+<%page args="author,text,status,close=False" />\
+${author|n,unicode}:
+
+%if status:
+${_('Status change:')|n,unicode} \
+${status|n,unicode}
+
+%endif
+%if close:
+${_('The pull request has been closed.')|n,unicode}
+
+%endif
+${text|n,unicode}
+
+## Trailing empty line
--- a/kallithea/templates/email_templates/default.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/email_templates/default.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,11 @@
-## -*- coding: utf-8 -*-
-<%inherit file="main.html"/>
-
-${body}
+<%inherit file="main.html"/>\
+\
+<%block name="header">\
+<%include file="header.html" args="title=_('Message'),link=None"/>\
+</%block>\
+\
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td style="${comment_style}">${body}</td>
+    </tr>
+</table>
--- a/kallithea/templates/email_templates/default.txt	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/email_templates/default.txt	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-## -*- coding: utf-8 -*-
-<%inherit file="main.txt"/>
-
-${body|n,unicode}
+<%block name="header">\
+</%block>\
+\
+${body|n,unicode}\
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/templates/email_templates/header.html	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,25 @@
+<%page args="title,link" />\
+\
+##<!-- header -->
+<table bgcolor="${color_background_grey}" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid ${color_border}">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="${sans_style};font-size:19px;line-height:24px">
+        %if link is not None:
+            <a style="text-decoration:none;color:${color_emph}" href="${link}"
+               target="_blank">${title}</a>
+        %else:
+            <span style="color:${color_emph}">${title}</span>
+        %endif
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+##<!-- /header -->
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/templates/email_templates/header.txt	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,8 @@
+<%page args="title,link" />\
+%if link is not None:
+${link}
+
+%endif
+${title|n,unicode}
+
+## Trailing empty line
--- a/kallithea/templates/email_templates/main.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/email_templates/main.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,6 +1,42 @@
-${self.body()}
-
-<br/>
-<br/>
--- <br/>
-${_("This is an automatic notification. Don't reply to this mail.")}
+<!doctype html>
+<html lang="en">
+<head>
+    <title></title>
+    <meta name="viewport" content="width=device-width">
+    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+</head>
+<body>
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;${default_style}">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;${sans_style};border:1px solid ${color_border}">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<%block name="header"/>\
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+                        ##<!-- body -->
+${self.body()}\
+                        ##<!-- /body -->
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+</body>
+</html>
--- a/kallithea/templates/email_templates/main.txt	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,4 +0,0 @@
-${self.body()|n,unicode}
-
--- 
-${_("This is an automatic notification. Don't reply to this mail.")|n,unicode}
--- a/kallithea/templates/email_templates/password_reset.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/email_templates/password_reset.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,12 +1,47 @@
-## -*- coding: utf-8 -*-
-<%inherit file="main.html"/>
-
-<h4>${_('Hello %s') % user}</h4>
-
-<p>${_('We have received a request to reset the password for your account.')}</p>
-<p>${_('To set a new password, click the following link')}:</p>
-<p><a href="${reset_url}">${reset_url}</a></p>
-
-<p>${_("Should you not be able to use the link above, please type the following code into the password reset form")}: <code>${reset_token}</code></p>
-
-<p>${_("If it weren't you who requested the password reset, just disregard this message.")}</p>
+<%inherit file="main.html"/>\
+\
+<%block name="header">\
+<%include file="header.html" args="title=_('Password Reset Request'),link=None"/>\
+</%block>\
+\
+<table cellpadding="0" cellspacing="0" border="0" width="100%" style="table-layout:fixed;word-wrap:break-word;">
+    <tr>
+        <td>${_('Hello %s') % user},</td>
+    </tr>
+    <tr>
+        <td height="10px"></td>
+    </tr>
+    <tr>
+        <td>
+            ${_('We have received a request to reset the password for your account.')}
+        </td>
+    </tr>
+    <tr>
+        <td height="10px"></td>
+    </tr>
+    <tr>
+        <td>
+            %if reset_token is None:
+                <div>${_('This account is however managed outside this system and the password cannot be changed here.')}</div>
+            %else:
+                <div>
+                    ${_('To set a new password, click the following link')}:
+                    <br/>
+                    <a style="color:${color_link};text-decoration:none" href="${reset_url}"
+                        target="_blank">${reset_url}</a>
+                    <br/>
+                    ${_("Should you not be able to use the link above, please type the following code into the password reset form")}:
+                    <code>${reset_token}</code>
+                </div>
+            %endif
+        </td>
+    </tr>
+    <tr>
+        <td height="10px"></td>
+    </tr>
+    <tr>
+        <td>
+            ${_("If it weren't you who requested the password reset, just disregard this message.")}
+        </td>
+    </tr>
+</table>
--- a/kallithea/templates/email_templates/password_reset.txt	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/email_templates/password_reset.txt	Fri Nov 18 01:11:13 2016 +0100
@@ -1,13 +1,20 @@
-## -*- coding: utf-8 -*-
-<%inherit file="main.txt"/>
+<%block name="header">\
+<%include file="header.txt" args="title=_('Password Reset Request'),link=None"/>\
+</%block>\
+\
+${_('Hello %s') % user|n,unicode},
 
-${_('Hello %s') % user|n,unicode}
+${_('We have received a request to reset the password for your account.')|n,unicode}
 
-${_('We have received a request to reset the password for your account..')|n,unicode}
+%if reset_token is None:
+${_('This account is however managed outside this system and the password cannot be changed here.')|n,unicode}
+%else:
 ${_('To set a new password, click the following link')|n,unicode}:
 
 ${reset_url|n,unicode}
 
-${_("Should you not be able to use the link above, please type the following code into the password reset form")|n,unicode}: ${reset_token|n,unicode}
+${_("Should you not be able to use the link above, please type the following code into the password reset form")|n,unicode}:
+${reset_token|n,unicode}
+%endif
 
 ${_("If it weren't you who requested the password reset, just disregard this message.")|n,unicode}
--- a/kallithea/templates/email_templates/pull_request.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/email_templates/pull_request.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,22 +1,73 @@
-## -*- coding: utf-8 -*-
-<%inherit file="main.html"/>
-
-%if is_mention:
-<p>${_('%s mentioned you on %s pull request "%s"') % (pr_user_created, repo_name, pr_title)}</p>
-%else:
-<p>${_('%s requested your review of %s pull request "%s"') % (pr_user_created, repo_name, pr_title)}</p>
-%endif
-
-<p>${_('URL')}: <a href="${pr_url}">${pr_url}</a></p>
+<%inherit file="main.html"/>\
+\
+<%block name="header">\
+<% title = _('Mention on Pull Request %s "%s" by %s') % (pr_nice_id, pr_title, pr_user_created) if is_mention else _('Added as Reviewer of Pull Request %s "%s" by %s') % (pr_nice_id, pr_title, pr_user_created) %>\
+<%include file="header.html" args="title=title,link=pr_url"/>\
+</%block>\
+\
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+            <div>
+                ${_('Pull request from')}
+                <a style="color:${color_link};text-decoration:none"
+                   href="${pr_source_repo}">${pr_source_repo}</a>
+                ${_('at')}
+                <span style="color:${color_link}">${pr_source_branch}</span>
+                ${_('to')}
+                <a style="color:${color_link};text-decoration:none"
+                   href="${pr_target_repo}">${pr_target_repo}</a>
+                ${_('at')}
+                <span style="color:${color_link}">${pr_target_branch}</span>:
+            </div>
+            <div>
+                <a style="color:${color_link};text-decoration:none"
+                   href="${pr_url}">${pr_nice_id}</a>
+                "<span style="color:${color_link}">${pr_title}</span>"
+                ${_('by')}
+                <span style="color:${color_link}">${pr_owner.full_name_and_username}</span>.
+            </div>
+        </td>
+    </tr>
+    <tr><td height="10px"></td></tr>
+    <tr>
+        <td>
+            <div>
+                ${_('Description')}:
+            </div>
+        </td>
+    </tr>
+    <tr><td height="10px"></td></tr>
+    <tr>
+        <td>
+            <div style="${comment_style};color:${color_link}">${body}</div>
+        </td>
+    </tr>
+    <tr><td height="15px"></td></tr>
+    <tr>
+        <td>
+            <div>${_('Changesets')}:</div>
+        </td>
+    </tr>
+    <tr><td height="10px"></td></tr>
 
-<p>${_('Description')}:</p>
-<p style="white-space: pre-wrap;">${body}</p>
-
-<p>${_('Changesets')}:</p>
-<p style="white-space: pre-wrap;">
-%for r,r_msg in pr_revisions:
-<i>${h.short_id(r)}</i>:
-${h.shorter(r_msg, 256)}
-
-%endfor
-</p>
+    <tr>
+        <td style="${sans_style}">
+            <ul style="color:${color_link};padding-left:15px;margin:0">
+                %for revision, desc in pr_revisions:
+                    <li>
+                        <a style="color:${color_link};text-decoration:none"
+                           href="${h.canonical_url('changeset_home', repo_name=org_repo_name, revision=revision)}">
+                            ${h.shorter(desc, 80, firstline=True)}
+                        </a>
+                    </li>
+                %endfor
+            </ul>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<%include file="button.html" args="url=pr_url,title=_('View Pull Request'),padding_bottom=False"/>\
+        </td>
+    </tr>
+</table>
--- a/kallithea/templates/email_templates/pull_request.txt	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/email_templates/pull_request.txt	Fri Nov 18 01:11:13 2016 +0100
@@ -1,20 +1,31 @@
-## -*- coding: utf-8 -*-
-<%inherit file="main.txt"/>
+<%block name="header">\
+<% title = _('Mention on Pull Request %s "%s" by %s') % (pr_nice_id, pr_title, pr_user_created) if is_mention else _('Added as Reviewer of Pull Request %s "%s" by %s') % (pr_nice_id, pr_title, pr_user_created) %>\
+<%include file="header.txt" args="title=title,link=pr_url"/>\
+</%block>\
 
-%if is_mention:
-${_('%s mentioned you on %s pull request "%s"') % (pr_user_created, repo_name, pr_title)|n,unicode}
-%else:
-${_('%s requested your review of %s pull request "%s"') % (pr_user_created, repo_name, pr_title)|n,unicode}
-%endif
+${_('Pull request from')|n,unicode} \
+${pr_source_repo|n,unicode} \
+${_('at')|n,unicode} \
+${pr_source_branch|n,unicode} \
+${_('to')|n,unicode} \
+${pr_target_repo|n,unicode} \
+${_('at')|n,unicode} \
+${pr_target_branch|n,unicode}:
+${pr_nice_id|n,unicode} \
+"${pr_title|n,unicode}" \
+${_('by')|n,unicode} \
+${pr_owner.full_name_and_username|n,unicode}.
 
-${_('URL')|n,unicode}: ${pr_url|n,unicode}
 
 ${_('Description')|n,unicode}:
+
 ${body|n,unicode}
 
+
 ${_('Changesets')|n,unicode}:
-%for r,r_msg in pr_revisions:
-${h.short_id(r)|n,unicode}:
-${h.shorter(r_msg, 256)|n,unicode}
 
+%for revision, desc in pr_revisions:
+${h.shorter(desc, 80, firstline=True)|n,unicode}
 %endfor
+
+<%include file="button.txt" args="url=pr_url,title='View Pull Request'"/>\
--- a/kallithea/templates/email_templates/pull_request_comment.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/email_templates/pull_request_comment.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,15 +1,45 @@
-## -*- coding: utf-8 -*-
-<%inherit file="main.html"/>
-
-<p>${_('Comment from %s on %s pull request "%s"') % (pr_comment_user, repo_name, pr_title)}:</p>
-<p>${body}</p>
-
-%if status_change:
-    %if closing_pr:
-       <p>${_('The comment closed the pull request with status')}: <b>${status_change}</b></p>
-    %else:
-       <p>${_('The comment was made with status')}: <b>${status_change}</b></p>
-    %endif
-%endif
-
-<p>${_('URL')}: <a href="${pr_comment_url}">${pr_comment_url}</a></p>
+<%inherit file="main.html"/>\
+\
+<%block name="header">\
+<% title = _('Mention in Comment on Pull Request %s "%s"') % (pr_nice_id, pr_title) if is_mention else _('Pull Request %s "%s" Closed') % (pr_nice_id, pr_title) if closing_pr else _('Comment on Pull Request %s "%s"') % (pr_nice_id, pr_title) %>\
+<%include file="header.html" args="title=title,link=pr_comment_url"/>\
+</%block>\
+\
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+<%include file="comment.html" args="text=body,author=pr_comment_user,status=status_change,close=closing_pr"/>\
+        </td>
+    </tr>
+    <tr>
+        <td height="30px"></td>
+    </tr>
+    <tr>
+        <td>
+            <div>
+                ${_('Pull request from')}
+                <a style="color:${color_link};text-decoration:none"
+                   href="${pr_source_repo}">${pr_source_repo}</a>
+                ${_('branch')}
+                <span style="color:${color_link}">${pr_source_branch}</span>
+                ${_('to')}
+                <a style="color:${color_link};text-decoration:none"
+                   href="${pr_target_repo}">${pr_target_repo}</a>
+                ${_('branch')}
+                <span style="color:${color_link}">${pr_target_branch}</span>:
+            </div>
+            <div>
+                <a style="color:${color_link};text-decoration:none"
+                   href="${pr_url}">${pr_nice_id}</a>
+                "<span style="color:${color_link}">${pr_title}</span>"
+                ${_('by')}
+                <span style="color:${color_link}">${pr_owner.full_name_and_username}</span>.
+            </div>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<%include file="button.html" args="url=pr_comment_url,title=_('View Comment'),padding_bottom=False"/>\
+        </td>
+    </tr>
+</table>
--- a/kallithea/templates/email_templates/pull_request_comment.txt	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/email_templates/pull_request_comment.txt	Fri Nov 18 01:11:13 2016 +0100
@@ -1,15 +1,21 @@
-## -*- coding: utf-8 -*-
-<%inherit file="main.txt"/>
+<%block name="header">\
+<% title = _('Mention in Comment on Pull Request %s "%s"') % (pr_nice_id, pr_title) if is_mention else _('Pull Request %s "%s" Closed') % (pr_nice_id, pr_title) if closing_pr else _('Comment on Pull Request %s "%s"') % (pr_nice_id, pr_title) %>\
+<%include file="header.txt" args="title=title,link=pr_comment_url"/>\
+</%block>\
 
-${_('Comment from %s on %s pull request "%s"') % (pr_comment_user, repo_name, pr_title)|n,unicode}:
-${body|n,unicode}
+<%include file="comment.txt" args="text=body,author=pr_comment_user,status=status_change,close=closing_pr"/>\
 
-%if status_change:
-    %if closing_pr:
-${_('The comment closed the pull request with status')|n,unicode}: ${status_change|n,unicode}
-    %else:
-${_('The comment was made with status')|n,unicode}: ${status_change|n,unicode}
-    %endif
-%endif
+${_('Pull request from')|n,unicode} \
+${pr_source_repo|n,unicode} \
+${_('at')|n,unicode} \
+${pr_source_branch|n,unicode} \
+${_('to')|n,unicode} \
+${pr_target_repo|n,unicode} \
+${_('at')|n,unicode} \
+${pr_target_branch|n,unicode}:
+${pr_nice_id|n,unicode} \
+"${pr_title|n,unicode}" \
+${_('by')|n,unicode} \
+${pr_owner.full_name_and_username|n,unicode}.
 
-${_('URL')|n,unicode}: ${pr_comment_url|n,unicode}
+<%include file="button.txt" args="url=pr_comment_url,title=_('View Comment')"/>\
--- a/kallithea/templates/email_templates/registration.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/email_templates/registration.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,6 +1,44 @@
 ## -*- coding: utf-8 -*-
-<%inherit file="main.html"/>
-
-${body}
-
-${_('View this user here')}: <a href="${registered_user_url}">${registered_user_url}</a>
+<%inherit file="main.html"/>\
+\
+<%block name="header">\
+<%include file="header.html" args="title=_('New User Registration'),link=registered_user_url"/>\
+</%block>\
+\
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+            ${_('Username')}:
+        </td>
+        <td style="color:${color_link}">
+            ${new_username}
+        </td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="2"></td>
+    </tr>
+    <tr>
+        <td>
+            ${_('Full Name')}:
+        </td>
+        <td style="color:${color_link}">
+            ${new_full_name}
+        </td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="2"></td>
+    </tr>
+    <tr>
+        <td>
+            ${_('Email')}:
+        </td>
+        <td style="color:${color_link}">
+            ${new_email}
+        </td>
+    </tr>
+    <tr>
+        <td colspan="2">
+<%include file="button.html" args="url=registered_user_url,title=_('View User Profile'),padding_bottom=False"/>\
+        </td>
+    </tr>
+</table>
--- a/kallithea/templates/email_templates/registration.txt	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/email_templates/registration.txt	Fri Nov 18 01:11:13 2016 +0100
@@ -1,6 +1,11 @@
-## -*- coding: utf-8 -*-
-<%inherit file="main.txt"/>
+<%block name="header">\
+<%include file="header.txt" args="title=_('New User Registration'),link=registered_user_url"/>\
+</%block>\
+
+${_('Username')|n,unicode}: ${new_username|n,unicode}
 
-${body|n,unicode}
+${_('Full Name')|n,unicode}: ${new_full_name|n,unicode}
 
-${_('View this user here')|n,unicode}: ${registered_user_url|n,unicode}
+${_('Email')|n,unicode}: ${new_email|n,unicode}
+
+<%include file="button.txt" args="url=registered_user_url,title='View User Profile'"/>\
--- a/kallithea/templates/files/diff_2way.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/files/diff_2way.html	Fri Nov 18 01:11:13 2016 +0100
@@ -25,14 +25,14 @@
 
 <%def name="main()">
 ${self.repo_context_bar('changelog')}
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
 
-    <div class="diff-container" style="overflow-x: hidden">
-        <div class="diffblock comm" style="margin:3px; padding:1px">
+    <div class="diff-container">
+        <div class="diffblock comm twoway">
             <div class="code-header">
                 <div class="changeset_header">
                     <div class="changeset_file">
@@ -40,16 +40,16 @@
                         revision=c.cs2.raw_id,f_path=h.safe_unicode(c.node1.path)))}
                     </div>
                     <div class="diff-actions">
-                      <a href="${h.url('files_diff_home',repo_name=c.repo_name,f_path=h.safe_unicode(c.node1.path),diff2=c.cs2.raw_id,diff1=c.cs1.raw_id,diff='diff',fulldiff=1)}" class="tooltip" title="${_('Show full diff for this file')}">
+                      <a href="${h.url('files_diff_home',repo_name=c.repo_name,f_path=h.safe_unicode(c.node1.path),diff2=c.cs2.raw_id,diff1=c.cs1.raw_id,diff='diff',fulldiff=1)}" data-toggle="tooltip" title="${_('Show full diff for this file')}">
                           <i class="icon-file-code"></i>
                       </a>
-                      <a href="${h.url('files_diff_2way_home',repo_name=c.repo_name,f_path=h.safe_unicode(c.node1.path),diff2=c.cs2.raw_id,diff1=c.cs1.raw_id,diff='diff',fulldiff=1)}" class="tooltip" title="${_('Show full side-by-side diff for this file')}">
+                      <a href="${h.url('files_diff_2way_home',repo_name=c.repo_name,f_path=h.safe_unicode(c.node1.path),diff2=c.cs2.raw_id,diff1=c.cs1.raw_id,diff='diff',fulldiff=1)}" data-toggle="tooltip" title="${_('Show full side-by-side diff for this file')}">
                           <i class="icon-docs"></i>
                       </a>
-                      <a href="${h.url('files_diff_home',repo_name=c.repo_name,f_path=h.safe_unicode(c.node1.path),diff2=c.cs2.raw_id,diff1=c.cs1.raw_id,diff='raw')}" class="tooltip" title="${_('Raw diff')}">
+                      <a href="${h.url('files_diff_home',repo_name=c.repo_name,f_path=h.safe_unicode(c.node1.path),diff2=c.cs2.raw_id,diff1=c.cs1.raw_id,diff='raw')}" data-toggle="tooltip" title="${_('Raw diff')}">
                           <i class="icon-diff"></i>
                       </a>
-                      <a href="${h.url('files_diff_home',repo_name=c.repo_name,f_path=h.safe_unicode(c.node1.path),diff2=c.cs2.raw_id,diff1=c.cs1.raw_id,diff='download')}" class="tooltip" title="${_('Download diff')}">
+                      <a href="${h.url('files_diff_home',repo_name=c.repo_name,f_path=h.safe_unicode(c.node1.path),diff2=c.cs2.raw_id,diff1=c.cs1.raw_id,diff='download')}" data-toggle="tooltip" title="${_('Download diff')}">
                           <i class="icon-floppy"></i>
                       </a>
                       ${h.checkbox('ignorews', label=_('Ignore whitespace'))}
@@ -68,7 +68,7 @@
 $(document).ready(function () {
     $('#compare').mergely({
         width: 'auto',
-        height: '600',
+        height: $(window).height() - $('#compare').offset().top - $('#footer').height() - 35,
         fgcolor: {a:'#ddffdd',c:'#cccccc',d:'#ffdddd'},
         bgcolor: '#fff',
         viewport: true,
@@ -91,6 +91,9 @@
             }
         }
     });
+    // recompute width - avoids overflow and horizontal scrollbar
+    $('#compare').mergely('resize');
+
     $('#ignorews').change(function(e){
         var val = e.currentTarget.checked;
         $('#compare').mergely('options', {ignorews: val});
--- a/kallithea/templates/files/file_diff.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/files/file_diff.html	Fri Nov 18 01:11:13 2016 +0100
@@ -14,16 +14,17 @@
 
 <%def name="main()">
 ${self.repo_context_bar('changelog')}
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
     <div>
     ## diff block
     <%namespace name="diff_block" file="/changeset/diff_block.html"/>
     ${diff_block.diff_block_js()}
-    ${diff_block.diff_block(c.changes)}
+    ${diff_block.diff_block(c.repo_name, 'rev', c.a_rev, c.a_rev,
+                            c.repo_name, 'rev', c.cs_rev, c.cs_rev, c.file_diff_data)}
     </div>
 </div>
 </%def>
--- a/kallithea/templates/files/files.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/files/files.html	Fri Nov 18 01:11:13 2016 +0100
@@ -20,9 +20,9 @@
 
 <%def name="main()">
 ${self.repo_context_bar('files', c.revision)}
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
         <ul class="links">
             <li style="color:white">
@@ -99,7 +99,7 @@
     tooltip_activate();
 
     if(State !== undefined){
-        //inistially loaded stuff
+        //initially loaded stuff
         var _f_path = State.data.f_path;
         var _rev = State.data.rev;
 
@@ -149,22 +149,30 @@
     $("#diff1").select2({
         placeholder: _TM['Select changeset'],
         dropdownAutoWidth: true,
+        maxResults: 50,
         query: function(query){
           var key = 'cache';
           var cached = cache[key] ;
           if(cached) {
             var data = {results: []};
+            var queryLower = query.term.toLowerCase();
             //filter results
             $.each(cached.results, function(){
                 var section = this.text;
                 var children = [];
                 $.each(this.children, function(){
-                    if(query.term.length == 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){
-                        children.push({'id': this.id, 'text': this.text});
+                    if(children.length < 50 ?
+                       ((queryLower.length == 0) || (this.text.toLowerCase().indexOf(queryLower) >= 0)) :
+                       ((queryLower.length != 0) && (this.text.toLowerCase().indexOf(queryLower) == 0))) {
+                        children.push(this);
                     }
                 });
+                children = branchSort(children, undefined, query)
                 data.results.push({'text': section, 'children': children});
             });
+            //push the typed in changeset
+            data.results.push({'text':_TM['Specify changeset'],
+                               'children': [{'id': query.term, 'text': query.term, 'type': 'rev'}]});
             query.callback(data);
           }else{
               $.ajax({
@@ -174,7 +182,7 @@
                 type: 'GET',
                 success: function(data) {
                   cache[key] = data;
-                  query.callback({results: data.results});
+                  query.callback(data);
                 }
               });
           }
@@ -233,7 +241,7 @@
     // change branch filter
     $("#branch_selector").select2({
         dropdownAutoWidth: true,
-        minimumInputLength: 1,
+        maxResults: 50,
         sortResults: branchSort
         });
 
--- a/kallithea/templates/files/files_add.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/files/files_add.html	Fri Nov 18 01:11:13 2016 +0100
@@ -23,9 +23,9 @@
 
 <%def name="main()">
 ${self.repo_context_bar('files')}
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
         <ul class="links">
             <li>
@@ -41,17 +41,17 @@
               <span id="filename_container" class="file reviewer_ac">
                   <input class="input-small" type="text" value="" size="30" name="filename" id="filename" placeholder="${_('Enter filename...')}">
                   <input type="hidden" value="${c.f_path}" size="30" name="location" id="location">
-                  ${_('or')} <div class="btn btn-small" id="upload_file_enable">${_('Upload File')}</div>
+                  ${_('or')} <div class="btn btn-default btn-sm" id="upload_file_enable">${_('Upload File')}</div>
               </span>
               <span id="upload_file_container" class="reviewer_ac" style="display:none">
-                  <input type="file"  size="20" name="upload_file" id="upload_file">
-                  ${_('or')} <div class="btn btn-small" id="file_enable">${_('Create New File')}</div>
+                  <input type="file" size="20" name="upload_file" id="upload_file">
+                  ${_('or')} <div class="btn btn-default btn-sm" id="file_enable">${_('Create New File')}</div>
               </span>
           </h3>
             <div id="body" class="codeblock">
-            <div class="code-header" id="set_mode_header">
-                <label class="commit" for="set_mode">${_('New file mode')}</label>
-                <select id="set_mode" name="set_mode"/>
+            <div class="code-header" id="mimetype_header">
+                <label class="commit" for="mimetype">${_('New file type')}</label>
+                <select id="mimetype" name="mimetype"/>
             </div>
                 <div id="editor_container">
                     <pre id="editor_pre"></pre>
@@ -61,55 +61,58 @@
                 <textarea id="commit" name="message" style="height: 100px;width: 99%;margin-left:4px" placeholder="${c.default_message}"></textarea>
             </div>
             <div style="text-align: left;padding-top: 5px">
-            ${h.submit('commit',_('Commit Changes'),class_="btn btn-small btn-success")}
-            ${h.reset('reset',_('Reset'),class_="btn btn-small")}
+            ${h.submit('commit',_('Commit Changes'),class_="btn btn-success btn-sm")}
+            ${h.reset('reset',_('Reset'),class_="btn btn-default btn-sm")}
             </div>
             ${h.end_form()}
             <script type="text/javascript">
-            var reset_url = "${h.url('files_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.f_path)}";
-            var myCodeMirror = initCodeMirror('editor', "${request.script_name}", reset_url);
+                $(document).ready(function(){
+                    var reset_url = "${h.url('files_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.f_path)}";
+                    var myCodeMirror = initCodeMirror('editor', "${request.script_name}", reset_url);
 
-            //inject new modes, based on codeMirrors modeInfo object
-            $('#set_mode').each(function(){
-                var modes_select = this;
-                var index = 1;
-                for(var i=0;i<CodeMirror.modeInfo.length;i++){
-                    var m = CodeMirror.modeInfo[i];
-                    var opt = new Option(m.name, m.mime);
-                    $(opt).attr('mode', m.mode);
-                    if (m.mime == 'text/plain') {
-                        // default plain text
-                        $(opt).prop('selected', true);
-                        modes_select.options[0] = opt;
-                    } else {
-                        modes_select.options[index++] = opt;
-                    }
-                }
-            });
-            $('#set_mode').change(function(e){
-                var selected = e.currentTarget;
-                var node = selected.options[selected.selectedIndex];
-                var detected_mode = CodeMirror.findModeByMIME(node.value);
-                setCodeMirrorMode(myCodeMirror, detected_mode);
+                    //inject new modes, based on codeMirrors modeInfo object
+                    var $mimetype_select = $('#mimetype');
+                    $mimetype_select.each(function(){
+                        var modes_select = this;
+                        var index = 1;
+                        for(var i=0;i<CodeMirror.modeInfo.length;i++){
+                            var m = CodeMirror.modeInfo[i];
+                            var opt = new Option(m.name, m.mime);
+                            $(opt).attr('mode', m.mode);
+                            if (m.mime == 'text/plain') {
+                                // default plain text
+                                $(opt).prop('selected', true);
+                                modes_select.options[0] = opt;
+                            } else {
+                                modes_select.options[index++] = opt;
+                            }
+                        }
+                    });
+                    var $filename_input = $('#filename');
+                    $mimetype_select.change(function(e){
+                        var selected = e.currentTarget;
+                        var node = selected.options[selected.selectedIndex];
+                        var detected_mode = CodeMirror.findModeByMIME(node.value);
+                        setCodeMirrorMode(myCodeMirror, detected_mode);
 
-                var filenameInput = $('#filename');
-                var proposed_ext = CodeMirror.findExtensionByMode(detected_mode);
-                var file_data = CodeMirror.getFilenameAndExt(filenameInput.val());
-                var filename = file_data['filename'] || 'filename1';
-                filenameInput.val(filename + '.' + proposed_ext);
-            });
+                        var proposed_ext = CodeMirror.findExtensionByMode(detected_mode);
+                        var file_data = CodeMirror.getFilenameAndExt($filename_input.val());
+                        var filename = file_data['filename'] || 'filename1';
+                        $filename_input.val(filename + '.' + proposed_ext);
+                    });
 
-            // on type the new filename set mode
-            $('#filename').keyup(function(e){
-                var file_data = CodeMirror.getFilenameAndExt(this.value);
-                if(file_data['ext'] != null){
-                    var detected_mode = CodeMirror.findModeByExtension(file_data['ext']) || CodeMirror.findModeByMIME('text/plain');
-                    if (detected_mode){
-                        setCodeMirrorMode(myCodeMirror, detected_mode);
-                        $('#set_mode').val(detected_mode.mime);
-                    }
-                }
-            });
+                    // on type the new filename set mode
+                    $filename_input.keyup(function(e){
+                        var file_data = CodeMirror.getFilenameAndExt(this.value);
+                        if(file_data['ext'] != null){
+                            var detected_mode = CodeMirror.findModeByExtension(file_data['ext']) || CodeMirror.findModeByMIME('text/plain');
+                            if (detected_mode){
+                                setCodeMirrorMode(myCodeMirror, detected_mode);
+                                $mimetype_select.val(detected_mode.mime);
+                            }
+                        }
+                    });
+                });
             </script>
         </div>
     </div>
--- a/kallithea/templates/files/files_browser.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/files/files_browser.html	Fri Nov 18 01:11:13 2016 +0100
@@ -30,18 +30,18 @@
             ${h.form(h.url.current())}
             <div class="info_box">
               <div class="info_box_elem rev">${_('Revision')}</div>
-              <div class="info_box_elem"><a class="btn btn-mini ypjax-link" href="${c.url_prev}" title="${_('Previous revision')}"><i class="icon-left-open"></i></a></div>
+              <div class="info_box_elem"><a class="btn btn-default btn-xs ypjax-link" href="${c.url_prev}" title="${_('Previous revision')}"><i class="icon-left-open"></i></a></div>
               <div class="info_box_elem">${h.text('at_rev',value=c.changeset.revision,size=5)}</div>
-              <div class="info_box_elem"><a class="btn btn-mini ypjax-link" href="${c.url_next}" title="${_('Next revision')}"><i class="icon-right-open"></i></a></div>
+              <div class="info_box_elem"><a class="btn btn-default btn-xs ypjax-link" href="${c.url_next}" title="${_('Next revision')}"><i class="icon-right-open"></i></a></div>
             </div>
             ${h.end_form()}
         </div>
         <div class="browser-branch">
-           ${h.checkbox('stay_at_branch',c.changeset.branch,c.changeset.branch==c.branch)}
-           <label>${_('Follow current branch')}</label>
+            ${h.checkbox('stay_at_branch',c.changeset.branch,c.changeset.branch==c.branch)}
+            <label>${_('Follow current branch')}</label>
         </div>
         <div id="search_activate_id" class="search_activate">
-           <a class="btn btn-mini" id="filter_activate" href="#">${_('Search File List')}</a>
+            <a class="btn btn-default btn-xs" id="filter_activate" href="#">${_('Search File List')}</a>
         </div>
         <div class="browser-search">
             <div>
@@ -90,12 +90,12 @@
                      </td>
                      <td>
                          %if node.is_file():
-                             <a title="${node.last_changeset.message}" href="${h.url('changeset_home',repo_name=c.repo_name,revision=node.last_changeset.raw_id)}" class="tooltip revision-link">${h.show_id(node.last_changeset)}</a>
+                             <a data-toggle="tooltip" title="${node.last_changeset.message}" href="${h.url('changeset_home',repo_name=c.repo_name,revision=node.last_changeset.raw_id)}" class="revision-link">${h.show_id(node.last_changeset)}</a>
                          %endif
                      </td>
                      <td>
                          %if node.is_file():
-                             <span class="tooltip" title="${h.fmt_date(node.last_changeset.date)}">
+                             <span data-toggle="tooltip" title="${h.fmt_date(node.last_changeset.date)}">
                             ${h.age(node.last_changeset.date)}</span>
                          %endif
                      </td>
--- a/kallithea/templates/files/files_delete.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/files/files_delete.html	Fri Nov 18 01:11:13 2016 +0100
@@ -14,9 +14,9 @@
 
 <%def name="main()">
 ${self.repo_context_bar('files')}
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
         <ul class="links">
             <li>
@@ -40,8 +40,8 @@
                 <textarea id="commit" name="message" style="height: 100px;width: 99%;margin-left:4px" placeholder="${c.default_message}"></textarea>
             </div>
             <div style="text-align: left;padding-top: 5px">
-                ${h.submit('commit',_('Commit Changes'),class_="btn btn-small btn-success")}
-                ${h.reset('reset',_('Reset'),class_="btn btn-small")}
+                ${h.submit('commit',_('Commit Changes'),class_="btn btn-success btn-sm")}
+                ${h.reset('reset',_('Reset'),class_="btn btn-default btn-sm")}
             </div>
             ${h.end_form()}
         </div>
--- a/kallithea/templates/files/files_edit.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/files/files_edit.html	Fri Nov 18 01:11:13 2016 +0100
@@ -23,9 +23,9 @@
 
 <%def name="main()">
 ${self.repo_context_bar('files')}
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
         <ul class="links">
             <li>
@@ -35,7 +35,7 @@
     </div>
     <div class="table" id="edit">
         <div id="files_data">
-            <h3 class="files_location">${_('Location')}: ${h.files_breadcrumbs(c.repo_name,c.cs.revision,c.file.path)}</h3>
+            <h3 class="files_location">${_('Location')}: ${h.files_breadcrumbs(c.repo_name,c.cs.raw_id,c.file.path)}</h3>
             ${h.form(h.url.current(),method='post',id='eform')}
             <div id="body" class="codeblock">
             <div class="code-header">
@@ -45,27 +45,27 @@
                     <div class="left item">${h.format_byte_size(c.file.size,binary=True)}</div>
                     <div class="left item last">${c.file.mimetype}</div>
                     <div class="buttons">
-                      ${h.link_to(_('Show Annotation'),h.url('files_annotate_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.f_path),class_="btn btn-mini")}
-                      ${h.link_to(_('Show as Raw'),h.url('files_raw_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.f_path),class_="btn btn-mini")}
-                      ${h.link_to(_('Download as Raw'),h.url('files_rawfile_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.f_path),class_="btn btn-mini")}
+                      ${h.link_to(_('Show Annotation'),h.url('files_annotate_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.f_path),class_="btn btn-default btn-xs")}
+                      ${h.link_to(_('Show as Raw'),h.url('files_raw_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.f_path),class_="btn btn-default btn-xs")}
+                      ${h.link_to(_('Download as Raw'),h.url('files_rawfile_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.f_path),class_="btn btn-default btn-xs")}
                       % if h.HasRepoPermissionAny('repository.write','repository.admin')(c.repo_name):
                        % if not c.file.is_binary:
-                        ${h.link_to(_('Source'),h.url('files_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.f_path),class_="btn btn-mini")}
+                        ${h.link_to(_('Source'),h.url('files_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.f_path),class_="btn btn-default btn-xs")}
                        % endif
                       % endif
                     </div>
                 </div>
-                <label class="commit" for="set_mode">${_('Editing file')}: ${c.file.unicode_path}</label>
-                <select id="set_mode" name="set_mode"/>
+                <label class="commit" for="mimetype">${_('Editing file')}: ${c.file.unicode_path}</label>
+                <select id="mimetype" name="mimetype"/>
             </div>
                 <pre id="editor_pre"></pre>
                 <textarea id="editor" name="content" style="display:none">${h.escape(c.file.content)|n}</textarea>
-                <div style="padding: 10px;color:#666666">${_('Commit Message')}</div>
+                <div class="text-muted" style="padding: 10px">${_('Commit Message')}</div>
                 <textarea id="commit" name="message" style="height: 60px;width: 99%;margin-left:4px" placeholder="${c.default_message}"></textarea>
             </div>
             <div style="text-align: left;padding-top: 5px">
-            ${h.submit('commit',_('Commit Changes'),class_="btn btn-small btn-success")}
-            ${h.reset('reset',_('Reset'),class_="btn btn-small")}
+            ${h.submit('commit',_('Commit Changes'),class_="btn btn-success")}
+            ${h.reset('reset',_('Reset'),class_="btn btn-default")}
             </div>
             ${h.end_form()}
         </div>
@@ -73,40 +73,41 @@
 </div>
 
 <script type="text/javascript">
-$(document).ready(function(){
-    var reset_url = "${h.url('files_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.file.path)}";
-    var myCodeMirror = initCodeMirror('editor', "${request.script_name}", reset_url);
+    $(document).ready(function(){
+        var reset_url = "${h.url('files_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.file.path)}";
+        var myCodeMirror = initCodeMirror('editor', "${request.script_name}", reset_url);
 
-   //inject new modes, based on codeMirrors modeInfo object
-    $('#set_mode').each(function(){
-        var modes_select = this;
-        var index = 1;
-        for(var i=0;i<CodeMirror.modeInfo.length;i++){
-            var m = CodeMirror.modeInfo[i];
-            var opt = new Option(m.name, m.mime);
-            $(opt).attr('mode', m.mode);
-            if (m.mime == 'text/plain') {
-                // default plain text
-                $(opt).prop('selected', true);
-                modes_select.options[0] = opt;
-            } else {
-                modes_select.options[index++] = opt;
+       //inject new modes, based on codeMirrors modeInfo object
+        var $mimetype_select = $('#mimetype');
+        $mimetype_select.each(function(){
+            var modes_select = this;
+            var index = 1;
+            for(var i=0;i<CodeMirror.modeInfo.length;i++){
+                var m = CodeMirror.modeInfo[i];
+                var opt = new Option(m.name, m.mime);
+                $(opt).attr('mode', m.mode);
+                if (m.mime == 'text/plain') {
+                    // default plain text
+                    $(opt).prop('selected', true);
+                    modes_select.options[0] = opt;
+                } else {
+                    modes_select.options[index++] = opt;
+                }
             }
+        });
+        // try to detect the mode based on the file we edit
+        var detected_mode = CodeMirror.findModeByExtension("${c.file.extension}");
+        if(detected_mode){
+            setCodeMirrorMode(myCodeMirror, detected_mode);
+            $($mimetype_select.find('option[value="'+detected_mode.mime+'"]')[0]).prop('selected', true);
         }
+
+        $mimetype_select.on('change', function(e){
+            var selected = e.currentTarget;
+            var node = selected.options[selected.selectedIndex];
+            var detected_mode = CodeMirror.findModeByMIME(node.value);
+            setCodeMirrorMode(myCodeMirror, detected_mode);
+        });
     });
-    // try to detect the mode based on the file we edit
-    var detected_mode = CodeMirror.findModeByExtension("${c.file.extension}");
-    if(detected_mode){
-        setCodeMirrorMode(myCodeMirror, detected_mode);
-        $($('#set_mode option[value="'+detected_mode.mime+'"]')[0]).prop('selected', true);
-    }
-
-    $('#set_mode').on('change', function(e){
-        var selected = e.currentTarget;
-        var node = selected.options[selected.selectedIndex];
-        var detected_mode = CodeMirror.findModeByMIME(node.value);
-        setCodeMirrorMode(myCodeMirror, detected_mode);
-    });
-});
 </script>
 </%def>
--- a/kallithea/templates/files/files_history_box.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/files/files_history_box.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,10 +1,8 @@
 <div class="file_author" style="clear:both">
     <div class="item">${h.literal(ungettext(u'%s author',u'%s authors',len(c.authors)) % ('<b>%s</b>' % len(c.authors))) }</div>
     %for email, user in c.authors:
-      <div class="contributor tooltip" style="float:left" title="${user}">
-        <div class="gravatar" style="margin:1px">
-          ${h.gravatar(email, size=20)}
-        </div>
+      <div class="contributor" style="float:left" data-toggle="tooltip" title="${user}">
+        ${h.gravatar_div(email, size=20, div_style="margin:1px")}
       </div>
     %endfor
 </div>
--- a/kallithea/templates/files/files_source.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/files/files_source.html	Fri Nov 18 01:11:13 2016 +0100
@@ -2,13 +2,13 @@
     <div>
         <div style="float:left">
         ${h.form(h.url('files_diff_home',repo_name=c.repo_name,f_path=c.f_path),method='get')}
-        ${h.hidden('diff2',c.file_changeset.raw_id)}
+        ${h.hidden('diff2',c.changeset.raw_id)}
         ${h.hidden('diff1')}
-        ${h.submit('diff',_('Diff to Revision'),class_="btn btn-small")}
-        ${h.submit('show_rev',_('Show at Revision'),class_="btn btn-small")}
+        ${h.submit('diff',_('Diff to Revision'),class_="btn btn-default btn-sm")}
+        ${h.submit('show_rev',_('Show at Revision'),class_="btn btn-default btn-sm")}
         ${h.hidden('annotate', c.annotate)}
-        ${h.link_to(_('Show Full History'),h.url('changelog_file_home',repo_name=c.repo_name, revision=c.file_changeset.raw_id, f_path=c.f_path),class_="btn btn-small")}
-        ${h.link_to(_('Show Authors'),'#',class_="btn btn-small" ,id="show_authors")}
+        ${h.link_to(_('Show Full History'),h.url('changelog_file_home',repo_name=c.repo_name, revision=c.changeset.raw_id, f_path=c.f_path),class_="btn btn-default btn-sm")}
+        ${h.link_to(_('Show Authors'),'#',class_="btn btn-default btn-sm" ,id="show_authors")}
 
         ${h.end_form()}
         </div>
@@ -22,56 +22,60 @@
     <div class="code-header">
         <div class="stats">
             <div class="left img"><i class="icon-doc-inv"></i></div>
-            <div class="left item"><pre class="tooltip" title="${h.fmt_date(c.file_changeset.date)}">${h.link_to(h.show_id(c.file_changeset),h.url('changeset_home',repo_name=c.repo_name,revision=c.file_changeset.raw_id))}</pre></div>
+            <div class="left item"><pre data-toggle="tooltip" title="${h.fmt_date(c.changeset.date)}">${h.link_to(h.show_id(c.changeset),h.url('changeset_home',repo_name=c.repo_name,revision=c.changeset.raw_id))}</pre></div>
             <div class="left item"><pre>${h.format_byte_size(c.file.size,binary=True)}</pre></div>
             <div class="left item last"><pre>${c.file.mimetype}</pre></div>
             <div class="buttons">
               %if c.annotate:
-                ${h.link_to(_('Show Source'),    h.url('files_home',         repo_name=c.repo_name,revision=c.file_changeset.raw_id,f_path=c.f_path),class_="btn btn-mini")}
+                ${h.link_to(_('Show Source'),    h.url('files_home',         repo_name=c.repo_name,revision=c.changeset.raw_id,f_path=c.f_path),class_="btn btn-default btn-xs")}
               %else:
-                ${h.link_to(_('Show Annotation'),h.url('files_annotate_home',repo_name=c.repo_name,revision=c.file_changeset.raw_id,f_path=c.f_path),class_="btn btn-mini")}
+                ${h.link_to(_('Show Annotation'),h.url('files_annotate_home',repo_name=c.repo_name,revision=c.changeset.raw_id,f_path=c.f_path),class_="btn btn-default btn-xs")}
               %endif
-              ${h.link_to(_('Show as Raw'),h.url('files_raw_home',repo_name=c.repo_name,revision=c.file_changeset.raw_id,f_path=c.f_path),class_="btn btn-mini")}
-              ${h.link_to(_('Download as Raw'),h.url('files_rawfile_home',repo_name=c.repo_name,revision=c.file_changeset.raw_id,f_path=c.f_path),class_="btn btn-mini")}
-              % if h.HasRepoPermissionAny('repository.write','repository.admin')(c.repo_name):
-               %if c.on_branch_head and c.changeset.branch and not c.file.is_binary:
-                ${h.link_to(_('Edit on Branch:%s') % c.changeset.branch, h.url('files_edit_home',repo_name=c.repo_name,revision=c.changeset.branch,f_path=c.f_path, anchor='edit'),class_="btn btn-mini")}
-                ${h.link_to(_('Delete'), h.url('files_delete_home',repo_name=c.repo_name,revision=c.changeset.branch,f_path=c.f_path, anchor='edit'),class_="btn btn-mini btn-danger")}
-               %elif c.on_branch_head and c.changeset.branch and c.file.is_binary:
-                ${h.link_to(_('Edit'), '#', class_="btn btn-mini disabled tooltip", title=_('Editing binary files not allowed'))}
-                ${h.link_to(_('Delete'), h.url('files_delete_home',repo_name=c.repo_name,revision=c.changeset.branch,f_path=c.f_path, anchor='edit'),class_="btn btn-mini btn-danger")}
+              ${h.link_to(_('Show as Raw'),h.url('files_raw_home',repo_name=c.repo_name,revision=c.changeset.raw_id,f_path=c.f_path),class_="btn btn-default btn-xs")}
+              ${h.link_to(_('Download as Raw'),h.url('files_rawfile_home',repo_name=c.repo_name,revision=c.changeset.raw_id,f_path=c.f_path),class_="btn btn-default btn-xs")}
+              %if h.HasRepoPermissionAny('repository.write','repository.admin')(c.repo_name):
+               %if c.on_branch_head and not c.file.is_binary:
+                ${h.link_to(_('Edit on Branch: %s') % c.changeset.branch, h.url('files_edit_home',repo_name=c.repo_name,revision=c.changeset.raw_id,f_path=c.f_path, anchor='edit'),class_="btn btn-default btn-xs")}
+                ${h.link_to(_('Delete'), h.url('files_delete_home',repo_name=c.repo_name,revision=c.changeset.raw_id,f_path=c.f_path, anchor='edit'),class_="btn btn-danger btn-xs")}
+               %elif c.on_branch_head and c.file.is_binary:
+                ${h.link_to(_('Edit'), '#', class_="btn btn-default btn-xs disabled tooltip", title=_('Editing binary files not allowed'))}
+                ${h.link_to(_('Delete'), h.url('files_delete_home',repo_name=c.repo_name,revision=c.changeset.raw_id,f_path=c.f_path, anchor='edit'),class_="btn btn-danger btn-xs")}
                %else:
-                ${h.link_to(_('Edit'), '#', class_="btn btn-mini disabled tooltip", title=_('Editing files allowed only when on branch head revision'))}
-                ${h.link_to(_('Delete'), '#', class_="btn btn-mini btn-danger disabled tooltip", title=_('Deleting files allowed only when on branch head revision'))}
-               % endif
-              % endif
+                ${h.link_to(_('Edit'), '#', class_="btn btn-default btn-xs disabled tooltip", title=_('Editing files allowed only when on branch head revision'))}
+                ${h.link_to(_('Delete'), '#', class_="btn btn-danger btn-xs disabled tooltip", title=_('Deleting files allowed only when on branch head revision'))}
+               %endif
+              %endif
             </div>
         </div>
         <div class="author">
-            <div class="gravatar">
-                ${h.gravatar(h.email_or_none(c.file_changeset.author), size=16)}
-            </div>
-            <div title="${c.file_changeset.author}" class="user">${h.person(c.file_changeset.author)}</div>
+            ${h.gravatar_div(h.email_or_none(c.changeset.author), size=16)}
+            <div title="${c.changeset.author}" class="user">${h.person(c.changeset.author)}</div>
         </div>
-        <div class="commit">${h.urlify_commit(c.file_changeset.message,c.repo_name)}</div>
+        <div class="commit">${h.urlify_text(c.changeset.message,c.repo_name)}</div>
     </div>
     <div class="code-body">
       %if c.file.is_browser_compatible_image():
-        <img src="${h.url('files_raw_home',repo_name=c.repo_name,revision=c.file_changeset.raw_id,f_path=c.f_path)}" class="img-preview"/>
+        <img src="${h.url('files_raw_home',repo_name=c.repo_name,revision=c.changeset.raw_id,f_path=c.f_path)}" class="img-preview"/>
       %elif c.file.is_binary:
         <div style="padding:5px">
           ${_('Binary file (%s)') % c.file.mimetype}
         </div>
       %else:
-        %if c.file.size < c.cut_off_limit:
+        %if c.file.size < c.cut_off_limit or c.fulldiff:
             %if c.annotate:
               ${h.pygmentize_annotation(c.repo_name,c.file,linenos=True,anchorlinenos=True,lineanchors='L',cssclass="code-highlight")}
             %else:
               ${h.pygmentize(c.file,linenos=True,anchorlinenos=True,lineanchors='L',cssclass="code-highlight")}
             %endif
         %else:
-            ${_('File is too big to display')} ${h.link_to(_('Show as raw'),
-            h.url('files_raw_home',repo_name=c.repo_name,revision=c.file_changeset.raw_id,f_path=c.f_path))}
+            <h4>
+            ${_('File is too big to display.')}
+            %if c.annotate:
+              ${h.link_to(_('Show full annotation anyway.'), h.url.current(fulldiff=1, **request.GET.mixed()))}
+            %else:
+              ${h.link_to(_('Show as raw.'), h.url('files_raw_home',repo_name=c.repo_name,revision=c.changeset.raw_id,f_path=c.f_path))}
+            %endif
+            </h4>
         %endif
       %endif
     </div>
@@ -89,6 +93,6 @@
              f_path: "${h.safe_unicode(c.file.path)}"
            }
         }
-        callbacks(_State); // defined in files.html, main callbacks. Triggerd in pjax calls
+        callbacks(_State); // defined in files.html, main callbacks. Triggered in pjax calls
     });
 </script>
--- a/kallithea/templates/followers/followers.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/followers/followers.html	Fri Nov 18 01:11:13 2016 +0100
@@ -15,9 +15,9 @@
 
 <%def name="main()">
 ${self.repo_context_bar('followers')}
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
     <!-- end box / title -->
--- a/kallithea/templates/followers/followers_data.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/followers/followers_data.html	Fri Nov 18 01:11:13 2016 +0100
@@ -3,18 +3,16 @@
 % for f in c.followers_pager:
     <div>
         <div class="follower_user">
-            <div class="gravatar">
-              ${h.gravatar(f.user.email, size=24)}
-            </div>
+            ${h.gravatar_div(f.user.email, size=24)}
             <span style="font-size: 20px"> <b>${f.user.username}</b> (${f.user.name} ${f.user.lastname})</span>
         </div>
         <div style="clear:both;padding-top: 10px"></div>
         <div class="follower_date">${_('Started following -')}
-        <span class="tooltip" title="${f.follows_from}"> ${h.age(f.follows_from)}</span></div>
+        <span data-toggle="tooltip" title="${f.follows_from}"> ${h.age(f.follows_from)}</span></div>
         <div style="border-bottom: 1px solid #DDD;margin:10px 0px 10px 0px"></div>
     </div>
 % endfor
 
-<div class="pagination-wh pagination-left">
-${c.followers_pager.pager('$link_previous ~2~ $link_next')}
-</div>
+<ul class="pagination">
+    ${c.followers_pager.pager()}
+</ul>
--- a/kallithea/templates/forks/fork.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/forks/fork.html	Fri Nov 18 01:11:13 2016 +0100
@@ -15,85 +15,76 @@
 
 <%def name="main()">
 ${self.repo_context_bar('createfork')}
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
     ${h.form(url('repo_fork_create_home',repo_name=c.repo_info.repo_name))}
     <div class="form">
         <!-- fields -->
-        <div class="fields">
+        <div class="form-horizontal">
 
-            <div class="field">
-              <div class="label">
-                  <label for="repo_name">${_('Fork name')}:</label>
-              </div>
-              <div class="input">
-                  ${h.text('repo_name',class_="small")}
-                  ${h.hidden('repo_type',c.repo_info.repo_type)}
-                  ${h.hidden('fork_parent_id',c.repo_info.repo_id)}
-              </div>
+            <div class="form-group">
+                <label class="control-label" for="repo_name">${_('Fork name')}:</label>
+                <div class="input">
+                    ${h.text('repo_name',class_="small")}
+                    ${h.hidden('repo_type',c.repo_info.repo_type)}
+                    ${h.hidden('fork_parent_id',c.repo_info.repo_id)}
+                </div>
             </div>
 
-            <div class="field">
-                <div class="label label-textarea">
-                    <label for="description">${_('Description')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="description">${_('Description')}:</label>
                 <div class="textarea editor">
                     ${h.textarea('description')}
                     <span class="help-block">${_('Keep it short and to the point. Use a README file for longer descriptions.')}</span>
                 </div>
             </div>
 
-            <div class="field">
-                 <div class="label">
-                     <label for="repo_group">${_('Repository group')}:</label>
-                 </div>
-                 <div class="input">
-                     ${h.select('repo_group','',c.repo_groups,class_="medium")}
-                     <span class="help-block">${_('Optionally select a group to put this repository into.')}</span>
-                 </div>
+            <div class="form-group">
+                <label class="control-label" for="repo_group">${_('Repository group')}:</label>
+                <div class="input">
+                    ${h.select('repo_group','',c.repo_groups,class_="medium")}
+                    <span class="help-block">${_('Optionally select a group to put this repository into.')}</span>
+                </div>
             </div>
 
-             <div class="field">
-                <div class="label">
-                    <label for="landing_rev">${_('Landing revision')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="landing_rev">${_('Landing revision')}:</label>
                 <div class="input">
                     ${h.select('landing_rev','',c.landing_revs,class_="medium")}
                     <span class="help-block">${_('Default revision for files page, downloads, whoosh, and readme.')}</span>
                 </div>
             </div>
 
-            <div class="field">
-                <div class="label label-checkbox">
-                    <label for="private">${_('Private')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="private">${_('Private')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('private',value="True")}
                     <span class="help-block">${_('Private repositories are only visible to people explicitly added as collaborators.')}</span>
                 </div>
             </div>
-            <div class="field">
-                <div class="label label-checkbox">
-                    <label for="private">${_('Copy permissions')}:</label>
-                </div>
+
+            <div class="form-group">
+                <label class="control-label" for="copy_permissions">${_('Copy permissions')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('copy_permissions',value="True", checked="checked")}
                     <span class="help-block">${_('Copy permissions from forked repository')}</span>
                 </div>
             </div>
+
             %if c.can_update:
-            <div class="field">
-                <div class="label label-checkbox">
-                    <label for="private">${_('Update after clone')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="update_after_clone">${_('Update after clone')}:</label>
                 <div class="checkboxes">
                     ${h.checkbox('update_after_clone',value="True")}
                     <span class="help-block">${_('Checkout source after making a clone')}</span>
                 </div>
             </div>
             %endif
-            <div class="buttons">
-                ${h.submit('',_('Fork this Repository'),class_="btn")}
+
+            <div class="form-group">
+                <div class="buttons">
+                    ${h.submit('',_('Fork this Repository'),class_="btn btn-default")}
+                </div>
             </div>
         </div>
     </div>
--- a/kallithea/templates/forks/forks.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/forks/forks.html	Fri Nov 18 01:11:13 2016 +0100
@@ -15,9 +15,9 @@
 
 <%def name="main()">
 ${self.repo_context_bar('showforks')}
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
     <!-- end box / title -->
--- a/kallithea/templates/forks/forks_data.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/forks/forks_data.html	Fri Nov 18 01:11:13 2016 +0100
@@ -4,28 +4,26 @@
     % for f in c.forks_pager:
         <div>
             <div class="fork_user">
-                <div class="gravatar">
-                  ${h.gravatar(f.user.email, size=24)}
-                </div>
+                ${h.gravatar_div(f.owner.email, size=24)}
                 <span style="font-size: 20px">
-                 <b>${f.user.username}</b> (${f.user.name} ${f.user.lastname}) /
+                 <b>${f.owner.username}</b> (${f.owner.name} ${f.owner.lastname}) /
                   ${h.link_to(f.repo_name,h.url('summary_home',repo_name=f.repo_name))}
                 </span>
                 <div style="padding:5px 3px 3px 42px;">${f.description}</div>
             </div>
             <div style="clear:both;padding-top: 10px"></div>
             <div class="follower_date">${_('Forked')} -
-                <span class="tooltip" title="${h.fmt_date(f.created_on)}"> ${h.age(f.created_on)}</span>
+                <span data-toggle="tooltip" title="${h.fmt_date(f.created_on)}"> ${h.age(f.created_on)}</span>
                 <a title="${_('Compare fork with %s') % c.repo_name}"
                    href="${h.url('compare_url',repo_name=c.repo_name, org_ref_type=c.db_repo.landing_rev[0],org_ref_name=c.db_repo.landing_rev[1],other_repo=f.repo_name,other_ref_type=c.db_repo.landing_rev[0],other_ref_name=c.db_repo.landing_rev[1], merge=1)}"
-                   class="btn btn-small"><i class="icon-git-compare"></i> ${_('Compare Fork')}</a>
+                   class="btn btn-default btn-sm"><i class="icon-git-compare"></i> ${_('Compare Fork')}</a>
             </div>
             <div style="border-bottom: 1px solid #DDD;margin:10px 0px 10px 0px"></div>
         </div>
     % endfor
-  <div class="pagination-wh pagination-left">
-  ${c.forks_pager.pager('$link_previous ~2~ $link_next')}
-  </div>
+    <ul class="pagination">
+        ${c.forks_pager.pager()}
+    </ul>
 % else:
     ${_('There are no forks yet')}
 % endif
--- a/kallithea/templates/index.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/index.html	Fri Nov 18 01:11:13 2016 +0100
@@ -2,12 +2,9 @@
 <%inherit file="base/base.html"/>
 
 <%block name="title">
-    ${_('Dashboard')}
+    ${_('Repositories')}
 </%block>
 
-<%def name="breadcrumbs()">
-</%def>
-
 <%block name="header_menu">
 ${self.menu('repositories')}
 </%block>
--- a/kallithea/templates/index_base.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/index_base.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,10 +1,17 @@
 <%page args="parent,group_name=''" />
-    <div class="box">
+    <div class="panel panel-primary">
         <!-- box / title -->
-        <div class="title">
-            <h5>
-            <input class="q_filter_box" id="q_filter" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value=""/> ${parent.breadcrumbs()} <span id="repo_count">0</span> ${_('repositories')}
-            </h5>
+        <div class="panel-heading clearfix">
+            <div class="breadcrumbs">
+                %if c.group is not None:
+                    %for group in c.group.parents:
+                        ${h.link_to(group.name, url('repos_group_home', group_name=group.group_name))}
+                        &raquo;
+                    %endfor
+                    ${c.group.group_name}
+                %endif
+            </div>
+
             %if c.authuser.username != 'default':
               <ul class="links">
                 <li>
@@ -17,34 +24,34 @@
                 %>
                 %if h.HasPermissionAny('hg.admin','hg.create.repository')() or (group_admin or (group_write and create_on_write)):
                   %if c.group:
-                        <a href="${h.url('new_repo',parent_group=c.group.group_id)}" class="btn btn-small"><i class="icon-plus"></i> ${_('Add Repository')}</a>
+                        <a href="${h.url('new_repo',parent_group=c.group.group_id)}" class="btn btn-default btn-xs"><i class="icon-plus"></i> ${_('Add Repository')}</a>
                         %if h.HasPermissionAny('hg.admin')() or h.HasRepoGroupPermissionAny('group.admin')(c.group.group_name):
-                            <a href="${h.url('new_repos_group', parent_group=c.group.group_id)}" class="btn btn-small"><i class="icon-plus"></i> ${_('Add Repository Group')}</a>
+                            <a href="${h.url('new_repos_group', parent_group=c.group.group_id)}" class="btn btn-default btn-xs"><i class="icon-plus"></i> ${_('Add Repository Group')}</a>
                         %endif
                   %else:
-                    <a href="${h.url('new_repo')}" class="btn btn-small"><i class="icon-plus"></i> ${_('Add Repository')}</a>
+                    <a href="${h.url('new_repo')}" class="btn btn-default btn-xs"><i class="icon-plus"></i> ${_('Add Repository')}</a>
                     %if h.HasPermissionAny('hg.admin')():
-                        <a href="${h.url('new_repos_group')}" class="btn btn-small"><i class="icon-plus"></i> ${_('Add Repository Group')}</a>
+                        <a href="${h.url('new_repos_group')}" class="btn btn-default btn-xs"><i class="icon-plus"></i> ${_('Add Repository Group')}</a>
                     %endif
                   %endif
                 %endif
                 %if c.group and h.HasRepoGroupPermissionAny('group.admin')(c.group.group_name):
-                    <a href="${h.url('edit_repo_group',group_name=c.group.group_name)}" title="${_('You have admin right to this group, and can edit it')}" class="btn btn-small"><i class="icon-pencil"></i> ${_('Edit Repository Group')}</a>
+                    <a href="${h.url('edit_repo_group',group_name=c.group.group_name)}" title="${_('You have admin right to this group, and can edit it')}" class="btn btn-default btn-xs"><i class="icon-pencil"></i> ${_('Edit Repository Group')}</a>
                 %endif
                 </li>
               </ul>
             %endif
         </div>
         <!-- end box / title -->
+        %if c.groups:
         <div class="table">
-           % if c.groups:
-            <div id='groups_list_wrap' class="yui-skin-sam">
+            <div id='groups_list_wrap'>
               <table id="groups_list">
                   <thead>
                       <tr>
-                          <th class="left"><a href="#">${_('Group Name')}</a></th>
-                          <th class="left"><a href="#">${_('Description')}</a></th>
-                          ##<th class="left"><a href="#">${_('Number of Repositories')}</a></th>
+                          <th class="left">${_('Repository Group')}</th>
+                          <th class="left">${_('Description')}</th>
+                          ##<th class="left">${_('Number of Repositories')}</th>
                       </tr>
                   </thead>
 
@@ -67,120 +74,39 @@
                   % endfor
               </table>
             </div>
-            <div id="group-user-paginator" style="padding: 0px 0px 0px 0px"></div>
-            <div style="height: 20px"></div>
-            % endif
-            <div id="welcome" style="display:none;text-align:center">
-                <h1><a href="${h.url('home')}">${c.site_name} ${c.kallithea_version}</a></h1>
-            </div>
-            <%cnt=0%>
-            <%namespace name="dt" file="/data_table/_dt_elements.html"/>
-            <div class="yui-skin-sam" id="repos_list_wrap"></div>
-            <div id="user-paginator" style="padding: 0px 0px 0px 0px"></div>
+        </div>
+        %endif
+        <div class="table">
+            <table id="repos_list_wrap"></table>
         </div>
     </div>
 
       <script>
-        var data = ${c.data|n};
-        var myDataSource = new YAHOO.util.DataSource(data);
-        myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
-
-        myDataSource.responseSchema = {
-            resultsList: "records",
-            fields: [
-               {key:"menu"},
-               {key:"raw_name"},
-               {key:"name"},
-               {key:"desc"},
-               {key:"last_change"},
-               {key:"last_changeset"},
-               {key:"last_rev_raw"},
-               {key:"owner"},
-               {key:"atom"}
-            ]
-         };
-        myDataSource.doBeforeCallback = function(req,raw,res,cb) {
-            // This is the filter function
-            var data     = res.results || [],
-                filtered = [],
-                i,l;
-
-            if (req) {
-                req = req.toLowerCase();
-                for (i = 0; i<data.length; i++) {
-                    var pos = data[i].raw_name.toLowerCase().indexOf(req, ${len(group_name)});
-                    if (pos != -1) {
-                        filtered.push(data[i]);
-                    }
-                }
-                res.results = filtered;
-            }
-            YUD.get('repo_count').innerHTML = res.results.length;
-            return res;
-        }
-
-        // main table sorting
-        var myColumnDefs = [
-            {key:"menu",label:"",sortable:false,className:"quick_repo_menu hidden"},
-            {key:"name",label:"${_('Name')}",sortable:true,
-                sortOptions: { sortFunction: nameSort }},
-            {key:"desc",label:"${_('Description')}",sortable:true},
-            {key:"last_change",label:"${_('Last Change')}",sortable:true,
-                sortOptions: { sortFunction: ageSort }},
-            {key:"last_changeset",label:"${_('Tip')}",sortable:true,
-                sortOptions: { sortFunction: revisionSort }},
-            {key:"owner",label:"${_('Owner')}",sortable:true},
-            {key:"atom",label:"",sortable:false}
-        ];
-
-        var myDataTable = new YAHOO.widget.DataTable("repos_list_wrap", myColumnDefs, myDataSource,{
-          sortedBy:{key:"name",dir:"asc"},
-          paginator: YUI_paginator(${c.visual.dashboard_items},['user-paginator']),
-
-          MSG_SORTASC:"${_('Click to sort ascending')}",
-          MSG_SORTDESC:"${_('Click to sort descending')}",
-          MSG_EMPTY:"${_('No repositories found.')}",
-          MSG_ERROR:"${_('Data error.')}",
-          MSG_LOADING:"${_('Loading...')}"
-        }
-        );
-        myDataTable.subscribe('postRenderEvent',function(oArgs) {
-            tooltip_activate();
-            quick_repo_menu();
+        $('#groups_list').DataTable({
+            dom: '<"dataTables_left"f><"dataTables_right"ilp>t',
+            pageLength: 100
         });
 
-        var filterTimeout = null;
-
-        updateFilter = function () {
-            // Reset timeout
-            filterTimeout = null;
-
-            // Reset sort
-            var state = myDataTable.getState();
-            state.sortedBy = {key:'name', dir:YAHOO.widget.DataTable.CLASS_ASC};
-
-            // Get filtered data
-            myDataSource.sendRequest(YUD.get('q_filter').value,{
-                success : myDataTable.onDataReturnInitializeTable,
-                failure : myDataTable.onDataReturnInitializeTable,
-                scope   : myDataTable,
-                argument: state
+        var data = ${c.data|n},
+            $dataTable = $("#repos_list_wrap").DataTable({
+                data: data.records,
+                columns: [
+                    {data: "raw_name", visible: false, searchable: false},
+                    {title: "${_('Repository')}", data: "name", orderData: 1, render: {
+                        filter: function(data) {
+                            return $(data).find(".dt_repo_name").text();
+                        }
+                    }},
+                    {data: "desc", title: "${_('Description')}", searchable: false},
+                    {data: "last_change_iso", visible: false, searchable: false},
+                    {data: "last_change", title: "${_('Last Change')}", orderData: 4, searchable: false},
+                    {data: "last_rev_raw", visible: false, searchable: false},
+                    {data: "last_changeset", title: "${_('Tip')}", orderData: 6, searchable: false},
+                    {data: "owner", title: "${_('Owner')}", searchable: false},
+                    {data: "atom", sortable: false}
+                ],
+                order: [[1, "asc"]],
+                dom: '<"dataTables_left"f><"dataTables_right"ilp>t',
+                pageLength: 100
             });
-
-        };
-        $('#q_filter').click(function(){
-            if(!$('#q_filter').hasClass('loaded')){
-                //TODO: load here full list later to do search within groups
-                $('#q_filter').addClass('loaded');
-            }
-        });
-
-        $('#q_filter').keyup(function(){
-            clearTimeout(filterTimeout);
-            filterTimeout = setTimeout(updateFilter,600);
-        });
-
-        if($('#q_filter').val()) {
-            updateFilter();
-        }
       </script>
--- a/kallithea/templates/journal/journal.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/journal/journal.html	Fri Nov 18 01:11:13 2016 +0100
@@ -7,8 +7,8 @@
     <h5>
     <form id="filter_form">
     <input class="q_filter_box ${'' if c.search_term else 'initial'}" id="j_filter" size="15" type="text" name="filter" value="${c.search_term or _('quick filter...')}"/>
-    <span class="tooltip" title="${h.journal_filter_help()}">?</span>
-    <input type='submit' value="${_('Filter')}" class="btn btn-small" style="padding:0px 2px 0px 2px;margin:0px"/>
+    <span data-toggle="tooltip" title="${h.journal_filter_help()}">?</span>
+    <input type='submit' value="${_('Filter')}" class="btn btn-default btn-xs"/>
     ${_('Journal')} - ${ungettext('%s Entry', '%s Entries', c.journal_pager.item_count) % (c.journal_pager.item_count)}
     </form>
     ${h.end_form()}
@@ -23,12 +23,18 @@
 </%block>
 
 <%def name="main()">
-    <div class="box box-left">
+    <div class="panel panel-primary">
         <!-- box / title -->
-        <div class="title">
+        <div class="panel-heading clearfix">
          ${self.breadcrumbs()}
          <ul class="links icon-only-links">
            <li>
+             <a href="${h.url('my_account_watched')}"><i class="icon-eye"></i> ${_('Watched Repositories')}</a>
+           </li>
+           <li>
+             <a href="${h.url('my_account_repos')}"><i class="icon-database"></i> ${_('My Repositories')}</a>
+           </li>
+           <li>
              <span><a id="refresh" href="${h.url('journal')}"><i class="icon-arrows-cw"></i></a></span>
            </li>
            <li>
@@ -40,35 +46,6 @@
             <%include file='journal_data.html'/>
         </div>
     </div>
-    <div class="box box-right">
-        <!-- box / title -->
-
-        <div class="title">
-            <h5>
-            <input class="q_filter_box" id="q_filter" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value="" style="display: none"/>
-            <input class="q_filter_box" id="q_filter_watched" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value="" style="display: none"/>
-            </h5>
-            <ul class="links nav nav-tabs">
-                <li class="active" id="show_watched_li">
-                    <a id="show_watched" href="#watched"><i class="icon-eye"></i> ${_('Watched Repositories')}</a>
-                </li>
-                <li id="show_my_li">
-                    <a id="show_my" href="#my"><i class="icon-database"></i> ${_('My Repositories')}</a>
-               </li>
-            </ul>
-        </div>
-
-        <!-- end box / title -->
-        <div id="my_container" style="display:none">
-            <div class="table-grid table yui-skin-sam" id="repos_list_wrap"></div>
-            <div id="user-paginator" style="padding: 0px 0px 0px 20px"></div>
-        </div>
-
-        <div id="watched_container">
-            <div class="table-grid table yui-skin-sam" id="watched_repos_list_wrap"></div>
-            <div id="watched-user-paginator" style="padding: 0px 0px 0px 20px"></div>
-        </div>
-    </div>
 
 <script type="text/javascript">
 
@@ -100,240 +77,6 @@
         e.preventDefault();
     });
 
-    var show_my = function(e){
-        $('#watched_container').hide();
-        $('#my_container').show();
-        $('#q_filter').show();
-        $('#q_filter_watched').hide();
-
-        $('#show_my_li').addClass('active');
-        $('#show_watched_li').removeClass('active');
-        if(!$('#show_my').hasClass('loaded')){
-            table_renderer(${c.data |n});
-            $('#show_my').addClass('loaded');
-        }
-    };
-    $('#show_my').click(function(){
-        show_my();
-    });
-    var show_watched = function(){
-        $('#my_container').hide();
-        $('#watched_container').show();
-        $('#q_filter_watched').show();
-        $('#q_filter').hide();
-
-        $('#show_watched_li').addClass('active');
-        $('#show_my_li').removeClass('active');
-        if(!$('#show_watched').hasClass('loaded')){
-            watched_renderer(${c.watched_data |n});
-            $('#show_watched').addClass('loaded');
-        }
-    };
-    $('#show_watched').click(function(){
-        show_watched();
-    });
-    //init watched
-    show_watched();
-
-    var tabs = {
-        'watched': show_watched,
-        'my': show_my
-    }
-    var url = location.href.split('#');
-    if (url[1]) {
-        //We have a hash
-        var tabHash = url[1];
-        var func = tabs[tabHash]
-        if (func){
-            func();
-        }
-    }
-    function watched_renderer(data){
-        var myDataSource = new YAHOO.util.DataSource(data);
-        myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
-
-        myDataSource.responseSchema = {
-            resultsList: "records",
-            fields: [
-               {key:"menu"},
-               {key:"raw_name"},
-               {key:"name"},
-               {key:"last_changeset"},
-               {key:"last_rev_raw"},
-               {key:"action"}
-            ]
-         };
-        myDataSource.doBeforeCallback = function(req,raw,res,cb) {
-            // This is the filter function
-            var data     = res.results || [],
-                filtered = [],
-                i,l;
-
-            if (req) {
-                req = req.toLowerCase();
-                for (i = 0; i<data.length; i++) {
-                    var pos = data[i].raw_name.toLowerCase().indexOf(req);
-                    if (pos != -1) {
-                        filtered.push(data[i]);
-                    }
-                }
-                res.results = filtered;
-            }
-            return res;
-        }
-        // main table sorting
-        var myColumnDefs = [
-            {key:"menu",label:"",sortable:false,className:"quick_repo_menu hidden"},
-            {key:"name",label:"${_('Name')}",sortable:true,
-                sortOptions: { sortFunction: nameSort }},
-            {key:"last_changeset",label:"${_('Tip')}",sortable:true,
-                sortOptions: { sortFunction: revisionSort }},
-            {key:"action",label:"${_('Action')}",sortable:false}
-        ];
-
-        var myDataTable = new YAHOO.widget.DataTable("watched_repos_list_wrap", myColumnDefs, myDataSource,{
-          sortedBy:{key:"name",dir:"asc"},
-          paginator: YUI_paginator(25, ['watched-user-paginator']),
-
-          MSG_SORTASC:"${_('Click to sort ascending')}",
-          MSG_SORTDESC:"${_('Click to sort descending')}",
-          MSG_EMPTY:"${_('No records found.')}",
-          MSG_ERROR:"${_('Data error.')}",
-          MSG_LOADING:"${_('Loading...')}"
-        }
-        );
-        myDataTable.subscribe('postRenderEvent',function(oArgs) {
-            tooltip_activate();
-            quick_repo_menu();
-        });
-
-        var filterTimeout = null;
-
-        updateFilter  = function () {
-            // Reset timeout
-            filterTimeout = null;
-
-            // Reset sort
-            var state = myDataTable.getState();
-            state.sortedBy = {key:'name', dir:YAHOO.widget.DataTable.CLASS_ASC};
-
-            // Get filtered data
-            myDataSource.sendRequest(YUD.get('q_filter_watched').value,{
-                success : myDataTable.onDataReturnInitializeTable,
-                failure : myDataTable.onDataReturnInitializeTable,
-                scope   : myDataTable,
-                argument: state
-            });
-
-        };
-        $('#q_filter_watched').click(function(){
-            if(!$('#q_filter_watched').hasClass('loaded')) {
-                //TODO: load here full list later to do search within groups
-                $('#q_filter_watched').css('loaded');
-            }
-        });
-
-        $('#q_filter_watched').keyup(function(){
-            clearTimeout(filterTimeout);
-            filterTimeout = setTimeout(updateFilter,600);
-        });
-      }
-
-    function table_renderer(data){
-        var myDataSource = new YAHOO.util.DataSource(data);
-        myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
-
-        myDataSource.responseSchema = {
-            resultsList: "records",
-            fields: [
-               {key:"menu"},
-               {key:"raw_name"},
-               {key:"name"},
-               {key:"last_changeset"},
-               {key:"last_rev_raw"},
-               {key:"action"}
-            ]
-         };
-        myDataSource.doBeforeCallback = function(req,raw,res,cb) {
-            // This is the filter function
-            var data     = res.results || [],
-                filtered = [],
-                i,l;
-
-            if (req) {
-                req = req.toLowerCase();
-                for (i = 0; i<data.length; i++) {
-                    var pos = data[i].raw_name.toLowerCase().indexOf(req);
-                    if (pos != -1) {
-                        filtered.push(data[i]);
-                    }
-                }
-                res.results = filtered;
-            }
-            return res;
-        }
-        // main table sorting
-        var myColumnDefs = [
-            {key:"menu",label:"",sortable:false,className:"quick_repo_menu hidden"},
-            {key:"name",label:"${_('Name')}",sortable:true,
-                sortOptions: { sortFunction: nameSort }},
-            {key:"last_changeset",label:"${_('Tip')}",sortable:true,
-                sortOptions: { sortFunction: revisionSort }},
-            {key:"action",label:"${_('Action')}",sortable:false}
-        ];
-
-        var myDataTable = new YAHOO.widget.DataTable("repos_list_wrap", myColumnDefs, myDataSource,{
-          sortedBy:{key:"name",dir:"asc"},
-          paginator: YUI_paginator(25, ['user-paginator']),
-
-          MSG_SORTASC:"${_('Click to sort ascending')}",
-          MSG_SORTDESC:"${_('Click to sort descending')}",
-          MSG_EMPTY:"${_('No records found.')}",
-          MSG_ERROR:"${_('Data error.')}",
-          MSG_LOADING:"${_('Loading...')}"
-        }
-        );
-        myDataTable.subscribe('postRenderEvent',function(oArgs) {
-            tooltip_activate();
-            quick_repo_menu();
-        });
-
-        var filterTimeout = null;
-
-        updateFilter = function () {
-            // Reset timeout
-            filterTimeout = null;
-
-            // Reset sort
-            var state = myDataTable.getState();
-            state.sortedBy = {key:'name', dir:YAHOO.widget.DataTable.CLASS_ASC};
-
-            // Get filtered data
-            myDataSource.sendRequest(YUD.get('q_filter').value,{
-                success : myDataTable.onDataReturnInitializeTable,
-                failure : myDataTable.onDataReturnInitializeTable,
-                scope   : myDataTable,
-                argument: state
-            });
-
-        };
-        $('#q_filter').click(function(){
-            if(!$('#q_filter').hasClass('loaded')){
-                //TODO: load here full list later to do search within groups
-                $('#q_filter').addClass('loaded');
-            }
-        });
-
-        $('#q_filter').keyup(function(){
-            clearTimeout(filterTimeout);
-            filterTimeout = setTimeout(updateFilter,600);
-        });
-
-        if($('#q_filter').val()) {
-            updateFilter();
-        }
-    }
-
 </script>
 
 <script type="text/javascript">
--- a/kallithea/templates/journal/journal_data.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/journal/journal_data.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,13 +1,11 @@
 ## -*- coding: utf-8 -*-
 
-%if c.journal_day_aggreagate:
-    %for day,items in c.journal_day_aggreagate:
+%if c.journal_day_aggregate:
+    %for day,items in c.journal_day_aggregate:
      <div class="journal_day">${day}</div>
         % for user,entries in items:
             <div class="journal_container">
-                <div class="gravatar">
-                    ${h.gravatar(user.email if user else 'anonymous@kallithea-scm.org', size=24)}
-                </div>
+                ${h.gravatar_div(user.email if user else 'anonymous@kallithea-scm.org', size=24)}
                 %if user:
                     <div class="journal_user">${user.name} ${user.lastname}</div>
                 %else:
@@ -28,16 +26,16 @@
                         </span>
                     </div>
                     <div class="journal_action_params">${h.literal(h.action_parser(entry)[1]())}</div>
-                    <div class="date"><span class="tooltip" title="${h.fmt_date(entry.action_date)}">${h.age(entry.action_date)}</span></div>
+                    <div class="date"><span data-toggle="tooltip" title="${h.fmt_date(entry.action_date)}">${h.age(entry.action_date)}</span></div>
                 %endfor
                 </div>
             </div>
         %endfor
     %endfor
 
-  <div class="pagination-wh pagination-left" style="padding: 0px 0px 0px 10px;">
-  ${c.journal_pager.pager('$link_previous ~2~ $link_next')}
-  </div>
+    <ul class="pagination">
+        ${c.journal_pager.pager()}
+    </ul>
 %else:
   <div style="padding:5px 0px 10px 10px;">
       ${_('No entries yet')}
--- a/kallithea/templates/journal/public_journal.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/journal/public_journal.html	Fri Nov 18 01:11:13 2016 +0100
@@ -15,9 +15,9 @@
 </%block>
 <%def name="main()">
 
-<div class="box">
+<div class="panel panel-primary">
   <!-- box / title -->
-  <div class="title">
+  <div class="panel-heading clearfix">
     <h5>${_('Public Journal')}</h5>
     <ul class="links icon-only-links">
       <li>
--- a/kallithea/templates/login.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/login.html	Fri Nov 18 01:11:13 2016 +0100
@@ -41,7 +41,7 @@
                         <div class="checkbox">
                             <label for="remember">
                                 <input type="checkbox" id="remember" name="remember"/>
-                                ${_('Remember me')}
+                                ${_('Stay logged in after browser restart')}
                             </label>
                         </div>
                     </div>
--- a/kallithea/templates/password_reset.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/password_reset.html	Fri Nov 18 01:11:13 2016 +0100
@@ -7,7 +7,7 @@
 
 <div id="register">
     <%include file="/base/flash_msg.html"/>
-    <div class="title withlogo">
+    <div class="panel-heading withlogo">
         %if c.site_name:
             <h5>${_('Reset Your Password to %s') % c.site_name}</h5>
         %else:
@@ -18,22 +18,18 @@
         ${h.form(url('password_reset'))}
         <div class="form">
             <!-- fields -->
-            <div class="fields">
+            <div class="form-horizontal">
 
-                 <div class="field">
-                    <div class="label">
-                        <label for="email">${_('Email Address')}:</label>
-                    </div>
+                <div class="form-group">
+                    <label class="control-label" for="email">${_('Email Address')}:</label>
                     <div class="input">
                         ${h.text('email')}
                     </div>
-                 </div>
+                </div>
 
                 %if c.captcha_active:
-                <div class="field">
-                    <div class="label">
-                        <label for="email">${_('Captcha')}:</label>
-                    </div>
+                <div class="form-group">
+                    <label class="control-label" for="recaptcha_field">${_('Captcha')}:</label>
                     <div class="input">
                         ${h.hidden('recaptcha_field')}
                         <div id="recaptcha"></div>
@@ -43,10 +39,13 @@
 
                 <div class="buttons">
                     <div class="nohighlight">
-                      ${h.submit('send',_('Send Password Reset Email'),class_="btn")}
-                          <div class="activation_msg">${_('A password reset link will be sent to the specified email address if it is registered in the system.')}</div>
+                      ${h.submit('send',_('Send Password Reset Email'),class_="btn btn-default")}
                     </div>
                 </div>
+
+                <div class="alert alert-info">
+                    ${_('A password reset link will be sent to the specified email address if it is registered in the system.')}
+                </div>
             </div>
         </div>
         ${h.end_form()}
--- a/kallithea/templates/password_reset_confirmation.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/password_reset_confirmation.html	Fri Nov 18 01:11:13 2016 +0100
@@ -7,7 +7,7 @@
 
 <div id="register">
     <%include file="/base/flash_msg.html"/>
-    <div class="title withlogo">
+    <div class="panel-heading withlogo">
         %if c.site_name:
             <h5>${_('Reset Your Password to %s') % c.site_name}</h5>
         %else:
@@ -24,36 +24,33 @@
         </div>
         <div class="form">
             <!-- fields -->
-            <div class="fields">
-                 <div class="field">
-                    <div class="label">
-                        <label for="token">${_('Code you received in the email')}:</label>
-                    </div>
+            <div class="form-horizontal">
+                <div class="form-group">
+                    <label class="control-label" for="token">${_('Code you received in the email')}:</label>
                     <div class="input">
                         ${h.text('token', class_='focus')}
                     </div>
-                 </div>
+                </div>
 
-                 <div class="field">
-                    <div class="label">
-                        <label for="password">${_('New Password')}:</label>
-                    </div>
+                <div class="form-group">
+                    <label class="control-label" for="password">${_('New Password')}:</label>
                     <div class="input">
                         ${h.password('password',class_='focus')}
                     </div>
-                 </div>
+                </div>
 
-                 <div class="field">
-                    <div class="label">
-                        <label for="password_confirm">${_('Confirm New Password')}:</label>
-                    </div>
+                <div class="form-group">
+                    <label class="control-label" for="password_confirm">${_('Confirm New Password')}:</label>
                     <div class="input">
                         ${h.password('password_confirm',class_='focus')}
                     </div>
-                 </div>
-                <div class="buttons">
-                    <div class="nohighlight">
-                      ${h.submit('send',_('Confirm'),class_="btn")}
+                </div>
+
+                <div class="form-group">
+                    <div class="buttons">
+                        <div class="nohighlight">
+                            ${h.submit('send',_('Confirm'),class_="btn btn-default")}
+                        </div>
                     </div>
                 </div>
             </div>
--- a/kallithea/templates/pullrequests/pullrequest.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/pullrequests/pullrequest.html	Fri Nov 18 01:11:13 2016 +0100
@@ -14,9 +14,9 @@
 
 <%def name="main()">
 ${self.repo_context_bar('showpullrequest')}
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
 
@@ -24,30 +24,24 @@
     <div class="form">
         <!-- fields -->
 
-        <div class="fields" style="float:left;width:50%;padding-right:30px;">
+        <div class="form-horizontal" style="float:left;width:50%;padding-right:30px;">
 
-             <div class="field">
-                <div class="label">
-                    <label for="pullrequest_title">${_('Title')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="pullrequest_title">${_('Title')}:</label>
                 <div class="input">
                     ${h.text('pullrequest_title',class_="large",placeholder=_('Summarize the changes - or leave empty'))}
                 </div>
-             </div>
+            </div>
 
-            <div class="field">
-                <div class="label label-textarea">
-                    <label for="pullrequest_desc">${_('Description')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label" for="pullrequest_desc">${_('Description')}:</label>
                 <div class="textarea text-area editor">
                     ${h.textarea('pullrequest_desc',size=30,placeholder=_('Write a short description on this pull request'))}
                 </div>
             </div>
 
-            <div class="field">
-                <div class="label label-textarea">
-                    <label for="pullrequest_desc">${_('Changeset flow')}:</label>
-                </div>
+            <div class="form-group">
+                <label class="control-label">${_('Changeset flow')}:</label>
                 <div class="input">
                     ##ORG
                     <div>
@@ -83,11 +77,11 @@
                 </div>
             </div>
 
-            <div class="field">
+            <div class="form-group">
                 <div class="buttons">
-                    ${h.submit('save',_('Create Pull Request'),class_="btn")}
-                    ${h.reset('reset',_('Reset'),class_="btn")}
-               </div>
+                    ${h.submit('save',_('Create Pull Request'),class_="btn btn-default")}
+                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
+                </div>
             </div>
 
         </div>
@@ -134,13 +128,13 @@
                 var length = options.length;
                 for(var j = 0; j < length; j++)
                 {
-                  $optgroup.append($('<option/>').text(options[j][1]).val(options[j][0]));
+                  $optgroup.append($('<'+'option/>').text(options[j][1]).val(options[j][0]));
                 }
                 $other_ref.append($optgroup);
               }
               $other_ref.val(data.selected_ref);
 
-              // re-populate the select2 thingie
+              // re-populate the select2 thingy
               $("#other_ref").select2({
                   dropdownAutoWidth: true
               });
@@ -188,9 +182,9 @@
       }
       pendingajax = asynchtml(url, $('#pull_request_overview'), function(o){
           pendingajax = undefined;
-          var jsdata = eval('('+YUD.get('jsdata').innerHTML+')'); // TODO: just get json
+          var jsdata = eval('('+$('#jsdata').html()+')'); // TODO: just get json
           var r = new BranchRenderer('graph_canvas', 'graph_content_pr', 'chg_');
-          r.render(jsdata,100);
+          r.render(jsdata);
       });
   }
 
@@ -202,6 +196,7 @@
 
       $("#org_ref").select2({
           dropdownAutoWidth: true,
+          maxResults: 50,
           sortResults: branchSort
       });
       $("#org_ref").on("change", function(e){
@@ -217,6 +212,7 @@
 
       $("#other_ref").select2({
           dropdownAutoWidth: true,
+          maxResults: 50,
           sortResults: branchSort
       });
       $("#other_ref").on("change", function(e){
--- a/kallithea/templates/pullrequests/pullrequest_data.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/pullrequests/pullrequest_data.html	Fri Nov 18 01:11:13 2016 +0100
@@ -8,7 +8,7 @@
 %endif
 
 <div class="table">
-  <table>
+  <table class="table">
     <thead>
       <tr>
         <th class="left">${_('Vote')}</th>
@@ -25,7 +25,7 @@
       <td width="80px">
         <% status = pr.user_review_status(c.authuser.user_id) %>
         %if status:
-          <i class="icon-circle changeset-status-${status}" title="${_("You voted: %s") % status}"></i>
+          <i class="icon-circle changeset-status-${status}" title="${_("You voted: %s") % h.changeset_status_lbl(status)}"></i>
         %else:
           <i class="icon-circle changeset-status-not_reviewed" title="${_("You didn't vote")}"></i>
         %endif
@@ -42,7 +42,7 @@
         ${pr.owner.full_name_and_username}
       </td>
       <td>
-        <span class="tooltip" title="${h.fmt_date(pr.created_on)}">
+        <span data-toggle="tooltip" title="${h.fmt_date(pr.created_on)}">
           ${h.age(pr.created_on)}
         </span>
       </td>
@@ -59,9 +59,9 @@
         </a>
       </td>
       <td style="text-align:right">
-        %if pr.owner.user_id == c.authuser.user_id:
-          ${h.form(url('pullrequest_delete', repo_name=pr.other_repo.repo_name, pull_request_id=pr.pull_request_id),method='delete', style="display:inline-block")}
-          <button class="action_button"
+        %if pr.owner_id == c.authuser.user_id:
+          ${h.form(url('pullrequest_delete', repo_name=pr.other_repo.repo_name, pull_request_id=pr.pull_request_id), style="display:inline-block")}
+          <button class="btn btn-default btn-xs"
                   id="remove_${pr.pull_request_id}"
                   name="remove_${pr.pull_request_id}"
                   title="${_('Delete Pull Request')}"
@@ -80,11 +80,9 @@
 </div>
 
 %if hasattr(pullrequests, 'pager'):
-<div class="notification-paginator">
-  <div class="pagination-wh pagination-left">
-  ${pullrequests.pager('$link_previous ~2~ $link_next', **request.GET.mixed())}
-  </div>
-</div>
+    <ul class="pagination">
+        ${pullrequests.pager(**request.GET.mixed())}
+    </ul>
 %endif
 
 </%def>
--- a/kallithea/templates/pullrequests/pullrequest_show.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/pullrequests/pullrequest_show.html	Fri Nov 18 01:11:13 2016 +0100
@@ -15,11 +15,11 @@
 </%block>
 
 <%def name="main()">
-<% editable = not c.pull_request.is_closed() and (h.HasPermissionAny('hg.admin')() or h.HasRepoPermissionAny('repository.admin')(c.repo_name) or c.pull_request.owner.user_id == c.authuser.user_id) %>
+<% editable = not c.pull_request.is_closed() and (h.HasPermissionAny('hg.admin')() or h.HasRepoPermissionAny('repository.admin')(c.repo_name) or c.pull_request.owner_id == c.authuser.user_id) %>
 ${self.repo_context_bar('showpullrequest')}
-<div class="box">
+<div class="panel panel-primary">
   <!-- box / title -->
-  <div class="title">
+  <div class="panel-heading">
     ${self.breadcrumbs()}
   </div>
 
@@ -34,34 +34,28 @@
       <div id="pr-summary" class="fields">
 
         <div class="field pr-not-edit" style="min-height:37px">
-          <div class="label-summary">
             <label>${_('Description')}:</label>
             %if editable:
-            <div style="margin: 5px">
-              <a class="btn btn-small" onclick="$('.pr-do-edit').show();$('.pr-not-edit').hide()">${_("Edit")}</a>
+            <div style="margin: 25px 5px; position: absolute">
+              <a class="btn btn-default btn-xs" onclick="$('.pr-do-edit').show();$('.pr-not-edit').hide()">${_("Edit")}</a>
             </div>
             %endif
-          </div>
           <div class="input">
-            <div style="white-space:pre-wrap; line-height: 14px">${h.urlify_commit(c.pull_request.description, c.pull_request.org_repo.repo_name)}</div>
+            <div class="formatted-fixed">${h.urlify_text(c.pull_request.description, c.pull_request.org_repo.repo_name)}</div>
           </div>
         </div>
 
         %if editable:
         <div class="pr-do-edit" style="display:none">
           <div class="field">
-              <div class="label-summary">
-                  <label for="pullrequest_title">${_('Title')}:</label>
-              </div>
+              <label for="pullrequest_title">${_('Title')}:</label>
               <div class="input">
                   ${h.text('pullrequest_title',class_="large",value=c.pull_request.title,placeholder=_('Summarize the changes'))}
               </div>
           </div>
 
           <div class="field">
-              <div class="label-summary label-textarea">
-                  <label for="pullrequest_desc">${_('Description')}:</label>
-              </div>
+              <label for="pullrequest_desc">${_('Description')}:</label>
               <div class="textarea text-area editor">
                   ${h.textarea('pullrequest_desc',size=30,content=c.pull_request.description,placeholder=_('Write a short description on this pull request'))}
               </div>
@@ -70,15 +64,13 @@
         %endif
 
         <div class="field">
-          <div class="label-summary">
-              <label>${_('Reviewer voting result')}:</label>
-          </div>
+          <label>${_('Reviewer voting result')}:</label>
           <div class="input">
             <div class="changeset-status-container" style="float:none;clear:both">
             %if c.current_voting_result:
               <span class="changeset-status-ico" style="padding:0px 4px 0px 0px">
                   <i class="icon-circle changeset-status-${c.current_voting_result}" title="${_('Pull request status calculated from votes')}"></i></span>
-              <span class="changeset-status-lbl tooltip" title="${_('Pull request status calculated from votes')}">
+              <span class="changeset-status-lbl" data-toggle="tooltip" title="${_('Pull request status calculated from votes')}">
                 %if c.pull_request.is_closed():
                     ${_('Closed')},
                 %endif
@@ -89,12 +81,10 @@
           </div>
         </div>
         <div class="field">
-          <div class="label-summary">
-              <label>${_('Still not reviewed by')}:</label>
-          </div>
+          <label>${_('Still not reviewed by')}:</label>
           <div class="input">
             % if len(c.pull_request_pending_reviewers) > 0:
-                <div class="tooltip" title="${', '.join([x.username for x in c.pull_request_pending_reviewers])}">${ungettext('%d reviewer', '%d reviewers',len(c.pull_request_pending_reviewers)) % len(c.pull_request_pending_reviewers)}</div>
+                <div data-toggle="tooltip" title="${', '.join([x.username for x in c.pull_request_pending_reviewers])}">${ungettext('%d reviewer', '%d reviewers',len(c.pull_request_pending_reviewers)) % len(c.pull_request_pending_reviewers)}</div>
             % elif len(c.pull_request_reviewers) > 0:
                 <div>${_('Pull request was reviewed by all reviewers')}</div>
             %else:
@@ -103,9 +93,7 @@
           </div>
         </div>
         <div class="field">
-          <div class="label-summary">
-              <label>${_('Origin')}:</label>
-          </div>
+          <label>${_('Origin')}:</label>
           <div class="input">
             <div>
               ${h.link_to_ref(c.pull_request.org_repo.repo_name, c.cs_ref_type, c.cs_ref_name, c.cs_rev)}
@@ -116,9 +104,7 @@
           </div>
         </div>
         <div class="field">
-          <div class="label-summary">
-              <label>${_('Target')}:</label>
-          </div>
+          <label>${_('Target')}:</label>
           <div class="input">
             %if c.is_range:
               ${_("This is just a range of changesets and doesn't have a target or a real merge ancestor.")}
@@ -129,10 +115,9 @@
           </div>
         </div>
         <div class="field">
-          <div class="label-summary">
-              <label>${_('Pull changes')}:</label>
-          </div>
+          <label>${_('Pull changes')}:</label>
           <div class="input">
+            %if c.cs_ranges:
               <div>
                ## TODO: use cs_ranges[-1] or org_ref_parts[1] in both cases?
                %if h.is_hg(c.pull_request.org_repo):
@@ -141,24 +126,19 @@
                  <span style="font-family: monospace">git pull ${c.pull_request.org_repo.clone_url()} ${c.pull_request.org_ref_parts[1]}</span>
                %endif
               </div>
+            %endif
           </div>
         </div>
         <div class="field">
-          <div class="label-summary">
-              <label>${_('Created on')}:</label>
-          </div>
+          <label>${_('Created on')}:</label>
           <div class="input">
               <div>${h.fmt_date(c.pull_request.created_on)}</div>
           </div>
         </div>
         <div class="field">
-          <div class="label-summary">
-              <label>${_('Owner')}:</label>
-          </div>
+          <label>${_('Owner')}:</label>
           <div class="input pr-not-edit">
-                  <div class="gravatar">
-                    ${h.gravatar(c.pull_request.owner.email, size=20)}
-                  </div>
+                  ${h.gravatar_div(c.pull_request.owner.email, size=20)}
                   <span>${c.pull_request.owner.full_name_and_username}</span><br/>
                   <span><a href="mailto:${c.pull_request.owner.email}">${c.pull_request.owner.email}</a></span><br/>
           </div>
@@ -169,39 +149,48 @@
         </div>
 
         <div class="field">
-            <div class="label-summary">
-              <label>${_('Update')}:</label>
-            </div>
+          <label>${_('Next iteration')}:</label>
             <div class="input">
               <div class="msg-div">${c.update_msg}</div>
               %if c.avail_revs:
               <div id="updaterevs" style="max-height:200px; overflow-y:auto; overflow-x:hidden; margin-bottom: 10px; padding: 1px 0">
-                <div style="height:0">
+                <div style="height:0;width:40px">
                   <canvas id="avail_graph_canvas" style="width:0"></canvas>
                 </div>
                 <table id="updaterevs-table" class="noborder" style="padding-left:50px">
                   %for cnt, cs in enumerate(c.avail_cs):
-                    <tr id="chg_available_${cnt+1}">
-                      %if cs.revision == c.cs_ranges[-1].revision:
+                    <tr id="chg_available_${cnt+1}" class="${'mergerow' if len(cs.parents) > 1 and not (editable and cs.revision in c.avail_revs) else ''}">
+                      %if c.cs_ranges and cs.revision == c.cs_ranges[-1].revision:
                         <td>
                           %if editable:
-                            ${h.radio(name='updaterev', value='')}
+                            ${h.radio(name='updaterev', value='', checked=True)}
                           %endif
                         </td>
-                        <td colspan="2">${_("Current revision - no change")}</td>
+                        <td colspan="4">${_("Current revision - no change")}</td>
                       %else:
                         <td>
                           %if editable and cs.revision in c.avail_revs:
                             ${h.radio(name='updaterev', value=cs.raw_id)}
                           %endif
                         </td>
-                        <td>${h.link_to(h.show_id(cs),h.url('changeset_home',repo_name=c.cs_repo.repo_name,revision=cs.raw_id))}</td>
-                        <td><div class="message" style="white-space:normal; height:1.1em; max-width: 500px; padding:0">${h.urlify_commit(cs.message, c.repo_name)}</div></td>
+                        <td style="width: 120px"><span data-toggle="tooltip" title="${h.age(cs.date)}">${cs.date}</span></td>
+                        <td>${h.link_to(h.show_id(cs),h.url('changeset_home',repo_name=c.cs_repo.repo_name,revision=cs.raw_id), class_='changeset_hash')}</td>
+                        <td>
+                          <div style="float: right; margin-top: -4px;">
+                            %for tag in cs.tags:
+                              <span class="tagtag" title="${_('Tag %s') % tag}">
+                                ${h.link_to(tag,h.url('changeset_home',repo_name=c.repo_name,revision=cs.raw_id))}
+                              </span>
+                            %endfor
+                          </div>
+                          <div class="message" style="white-space:normal; height:1.1em; max-width: 500px; padding:0">${h.urlify_text(cs.message, c.repo_name)}</div>
+                        </td>
                       %endif
                     </tr>
                   %endfor
                 </table>
               </div>
+              <div class="msg-div">(${_("Pull request iterations do not change content once created. Select a revision and save to make a new iteration.")})</div>
               %endif
               <div class="msg-div">${c.update_msg_other}</div>
             </div>
@@ -214,32 +203,33 @@
         <div id="reviewers" style="padding:0px 0px 5px 10px">
           ## members goes here !
           <div>
-            <ul id="review_members" class="group_members">
+            %for member,status in c.pull_request_reviewers:
+              <input type="hidden" value="${member.user_id}" name="org_review_members" />
+            %endfor
+            <ul id="review_members">
             %for member,status in c.pull_request_reviewers:
               ## WARNING: the HTML below is duplicate with
               ## kallithea/public/js/base.js
               ## If you change something here it should be reflected in the template too.
               <li id="reviewer_${member.user_id}">
-                <div class="reviewers_member">
-                    <div class="reviewer_status tooltip" title="${h.changeset_status_lbl(status.status if status else 'not_reviewed')}">
-                      <i class="icon-circle changeset-status-${status.status if status else 'not_reviewed'}"></i>
-                    </div>
-                  <div class="reviewer_gravatar gravatar">
-                    ${h.gravatar(member.email, size=14)}
-                  </div>
-                  <div style="float:left;">
+                <span class="reviewers_member">
+                  <span class="reviewer_status" data-toggle="tooltip" title="${h.changeset_status_lbl(status)}">
+                      <i class="icon-circle changeset-status-${status}"></i>
+                  </span>
+                  ${h.gravatar(member.email, size=14)}
+                  <span>
                     ${member.full_name_and_username}
-                    %if c.pull_request.user_id == member.user_id:
+                    %if c.pull_request.owner_id == member.user_id:
                       (${_('Owner')})
                     %endif
-                  </div>
+                  </span>
                   <input type="hidden" value="${member.user_id}" name="review_members" />
                   %if editable:
-                  <div class="reviewer_member_remove action_button" onclick="removeReviewMember(${member.user_id})" title="${_('Remove reviewer')}">
+                  <a href="#" class="reviewer_member_remove" onclick="removeReviewMember(${member.user_id})" title="${_('Remove reviewer')}">
                       <i class="icon-minus-circled"></i>
-                  </div>
+                  </a>
                   %endif
-                </div>
+                </span>
               </li>
             %endfor
             </ul>
@@ -261,14 +251,14 @@
             ${_('Click to add the repository owner as reviewer:')}
           </div>
           <ul style="margin-top: 10px">
-            %for u in [c.pull_request.other_repo.user]:
+            %for u in [c.pull_request.other_repo.owner]:
               <li>
                 <a class="missing_reviewer missing_reviewer_${u.user_id}"
                   user_id="${u.user_id}"
                   fname="${u.name}"
                   lname="${u.lastname}"
                   nname="${u.username}"
-                  gravatar_lnk="${h.gravatar_url(u.email, size=28)}"
+                  gravatar_lnk="${h.gravatar_url(u.email, size=28, default='default')}"
                   gravatar_size="14"
                   title="Click to add reviewer to the list, then Save Changes.">${u.full_name}</a>
               </li>
@@ -281,9 +271,9 @@
       <div class="fields">
         %if editable:
           <div class="buttons">
-            ${h.submit('pr-form-save',_('Save Changes'),class_="btn btn-small")}
-            ${h.submit('pr-form-clone',_('Save as New Pull Request'),class_="btn btn-small",disabled='disabled')}
-            ${h.reset('pr-form-reset',_('Cancel Changes'),class_="btn btn-small")}
+            ${h.submit('pr-form-save',_('Save Changes'),class_="btn btn-default btn-sm")}
+            ${h.submit('pr-form-clone',_('Create New Iteration with Changes'),class_="btn btn-default btn-sm",disabled='disabled')}
+            ${h.reset('pr-form-reset',_('Cancel Changes'),class_="btn btn-default btn-sm")}
           </div>
         %endif
       </div>
@@ -291,8 +281,8 @@
   ${h.end_form()}
 </div>
 
-<div class="box">
-    <div class="title">
+<div class="panel panel-primary">
+    <div class="panel-heading">
       <div class="breadcrumbs">${_('Pull Request Content')}</div>
     </div>
     <div class="table">
@@ -308,36 +298,36 @@
 
               <div style="font-size:1.1em;font-weight: bold;clear:both;padding-top:10px">
               ${_('Common ancestor')}:
-              ${h.link_to(h.short_id(c.a_rev),h.url('changeset_home',repo_name=c.a_repo.repo_name,revision=c.a_rev))}
+              ${h.link_to(h.short_id(c.a_rev),h.url('changeset_home',repo_name=c.a_repo.repo_name,revision=c.a_rev), class_="changeset_hash")}
               </div>
 
               ## FILES
               <div style="font-size:1.1em;font-weight: bold;clear:both;padding-top:10px">
 
               % if c.limited_diff:
-                  ${ungettext('%s file changed', '%s files changed', len(c.files)) % len(c.files)}
+                  ${ungettext('%s file changed', '%s files changed', len(c.file_diff_data)) % len(c.file_diff_data)}:
               % else:
-                  ${ungettext('%s file changed with %s insertions and %s deletions','%s files changed with %s insertions and %s deletions', len(c.files)) % (len(c.files),c.lines_added,c.lines_deleted)}:
+                  ${ungettext('%s file changed with %s insertions and %s deletions','%s files changed with %s insertions and %s deletions', len(c.file_diff_data)) % (len(c.file_diff_data),c.lines_added,c.lines_deleted)}:
               %endif
 
               </div>
               <div class="cs_files">
-                %if not c.files:
+                %if not c.file_diff_data:
                    <span class="empty_data">${_('No files')}</span>
                 %endif
-                %for fid, change, f, stat in c.files:
-                    <div class="cs_${change}">
+                %for fid, url_fid, op, a_path, path, diff, stats in c.file_diff_data:
+                    <div class="cs_${op}">
                       <div class="node">
-                          <i class="icon-diff-${change}"></i>
-                          ${h.link_to(h.safe_unicode(f),'#' + fid)}
+                          <i class="icon-diff-${op}"></i>
+                          ${h.link_to(h.safe_unicode(path), '#%s' % fid)}
                       </div>
-                      <div class="changes">${h.fancy_file_stats(stat)}</div>
+                      <div class="changes">${h.fancy_file_stats(stats)}</div>
                     </div>
                 %endfor
+                %if c.limited_diff:
+                  <h5>${_('Changeset was too big and was cut off...')} <a href="${h.url.current(fulldiff=1, **request.GET.mixed())}">${_('Show full diff anyway')}</a></h5>
+                %endif
               </div>
-              % if c.limited_diff:
-                <h5>${_('Changeset was too big and was cut off...')} <a href="${h.url.current(fulldiff=1, **request.GET.mixed())}">${_('Show full diff anyway')}</a></h5>
-              % endif
           </div>
     </div>
     <script>
@@ -356,9 +346,8 @@
     <div class="commentable-diff">
     <%namespace name="diff_block" file="/changeset/diff_block.html"/>
     ${diff_block.diff_block_js()}
-    %for fid, change, f, stat in c.files:
-      ${diff_block.diff_block_simple([c.changes[fid]])}
-    %endfor
+    ${diff_block.diff_block(c.a_repo.repo_name, c.a_ref_type, c.a_ref_name, c.a_rev,
+                            c.cs_repo.repo_name, c.cs_ref_type, c.cs_ref_name, c.cs_rev, c.file_diff_data)}
     % if c.limited_diff:
       <h4>${_('Changeset was too big and was cut off...')} <a href="${h.url.current(fulldiff=1, **request.GET.mixed())}">${_('Show full diff anyway')}</a></h4>
     % endif
@@ -371,10 +360,7 @@
     ${comment.generate_comments()}
 
     ## main comment form and it status
-    ${comment.comments(h.url('pullrequest_comment', repo_name=c.repo_name,
-                              pull_request_id=c.pull_request.pull_request_id),
-                       c.current_voting_result,
-                       is_pr=True, change_status=c.allowed_to_change_status)}
+    ${comment.comments(change_status=c.allowed_to_change_status)}
 
     <script type="text/javascript">
       $(document).ready(function(){
@@ -387,7 +373,7 @@
 
           var avail_jsdata = ${c.avail_jsdata|n};
           var avail_r = new BranchRenderer('avail_graph_canvas', 'updaterevs-table', 'chg_available_');
-          avail_r.render(avail_jsdata,40);
+          avail_r.render(avail_jsdata);
 
           move_comments($(".comments .comments-list-chunk"));
 
--- a/kallithea/templates/pullrequests/pullrequest_show_all.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/pullrequests/pullrequest_show_all.html	Fri Nov 18 01:11:13 2016 +0100
@@ -21,22 +21,22 @@
 <%def name="main()">
 ${self.repo_context_bar('showpullrequest')}
 
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
         <ul class="links">
           <li>
              %if c.authuser.username != 'default':
               <span>
-                  <a id="open_new_pr" class="btn btn-small btn-success" href="${h.url('pullrequest_home',repo_name=c.repo_name)}"><i class="icon-plus"></i> ${_('Open New Pull Request')}</a>
+                  <a id="open_new_pr" class="btn btn-success btn-xs" href="${h.url('pullrequest_home',repo_name=c.repo_name)}"><i class="icon-plus"></i> ${_('Open New Pull Request')}</a>
               </span>
              %endif
               <span>
                 %if c.from_:
-                    <a class="btn btn-small" href="${h.url('pullrequest_show_all',repo_name=c.repo_name,closed=c.closed)}"><i class="icon-git-compare"></i> ${_('Show Pull Requests to %s') % c.repo_name}</a>
+                    <a class="btn btn-default btn-xs" href="${h.url('pullrequest_show_all',repo_name=c.repo_name,closed=c.closed)}"><i class="icon-git-compare"></i> ${_('Show Pull Requests to %s') % c.repo_name}</a>
                 %else:
-                    <a class="btn btn-small" href="${h.url('pullrequest_show_all',repo_name=c.repo_name,closed=c.closed,from_=1)}"><i class="icon-git-compare"></i> ${_("Show Pull Requests from '%s'") % c.repo_name}</a>
+                    <a class="btn btn-default btn-xs" href="${h.url('pullrequest_show_all',repo_name=c.repo_name,closed=c.closed,from_=1)}"><i class="icon-git-compare"></i> ${_("Show Pull Requests from '%s'") % c.repo_name}</a>
                 %endif
               </span>
           </li>
--- a/kallithea/templates/pullrequests/pullrequest_show_my.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/pullrequests/pullrequest_show_my.html	Fri Nov 18 01:11:13 2016 +0100
@@ -16,9 +16,9 @@
 
 <%def name="main()">
 
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading clearfix">
         ${self.breadcrumbs()}
     </div>
 
@@ -35,6 +35,9 @@
     <div class="pullrequests_section_head">${_('Pull Requests Created by Me')}</div>
     ${pullrequest_data.pullrequest_overview(c.my_pull_requests)}
 
+    <div class="pullrequests_section_head" style="clear:both">${_('Pull Requests Needing My Review')}</div>
+    ${pullrequest_data.pullrequest_overview(c.participate_in_pull_requests_todo)}
+
     <div class="pullrequests_section_head" style="clear:both">${_('Pull Requests I Participate In')}</div>
     ${pullrequest_data.pullrequest_overview(c.participate_in_pull_requests)}
 
--- a/kallithea/templates/register.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/register.html	Fri Nov 18 01:11:13 2016 +0100
@@ -7,7 +7,7 @@
 
 <div id="register">
     <%include file="/base/flash_msg.html"/>
-    <div class="title withlogo">
+    <div class="panel-heading withlogo">
         %if c.site_name:
             <h5>${_('Sign Up to %s') % c.site_name}</h5>
         %else:
@@ -18,66 +18,52 @@
         ${h.form(url('register'))}
         <div class="form">
             <!-- fields -->
-            <div class="fields">
-                <div class="field">
-                    <div class="label">
-                        <label for="username">${_('Username')}:</label>
-                    </div>
+            <div class="form-horizontal">
+                <div class="form-group">
+                    <label class="control-label" for="username">${_('Username')}:</label>
                     <div class="input">
                         ${h.text('username',class_="medium")}
                     </div>
                 </div>
 
-                <div class="field">
-                    <div class="label">
-                        <label for="password">${_('Password')}:</label>
-                    </div>
+                <div class="form-group">
+                    <label class="control-label" for="password">${_('Password')}:</label>
                     <div class="input">
                         ${h.password('password',class_="medium")}
                     </div>
                 </div>
 
-                <div class="field">
-                    <div class="label">
-                        <label for="password_confirmation">${_('Re-enter password')}:</label>
-                    </div>
+                <div class="form-group">
+                    <label class="control-label" for="password_confirmation">${_('Re-enter password')}:</label>
                     <div class="input">
                         ${h.password('password_confirmation',class_="medium")}
                     </div>
                 </div>
 
-                <div class="field">
-                    <div class="label">
-                        <label for="firstname">${_('First Name')}:</label>
-                    </div>
+                <div class="form-group">
+                    <label class="control-label" for="firstname">${_('First Name')}:</label>
                     <div class="input">
                         ${h.text('firstname',class_="medium")}
                     </div>
                 </div>
 
-                <div class="field">
-                    <div class="label">
-                        <label for="lastname">${_('Last Name')}:</label>
-                    </div>
+                <div class="form-group">
+                    <label class="control-label" for="lastname">${_('Last Name')}:</label>
                     <div class="input">
                         ${h.text('lastname',class_="medium")}
                     </div>
                 </div>
 
-                <div class="field">
-                    <div class="label">
-                        <label for="email">${_('Email')}:</label>
-                    </div>
+                <div class="form-group">
+                    <label class="control-label" for="email">${_('Email')}:</label>
                     <div class="input">
                         ${h.text('email',class_="medium")}
                     </div>
                 </div>
 
                 %if c.captcha_active:
-                <div class="field">
-                    <div class="label">
-                        <label for="email">${_('Captcha')}:</label>
-                    </div>
+                <div class="form-group">
+                    <label class="control-label" for="recaptcha_field">${_('Captcha')}:</label>
                     <div class="input">
                         ${h.hidden('recaptcha_field')}
                         <div id="recaptcha"></div>
@@ -87,12 +73,12 @@
 
                 <div class="buttons">
                     <div class="nohighlight">
-                      ${h.submit('sign_up',_('Sign Up'),class_="btn")}
-                      %if c.auto_active:
-                          <div class="activation_msg">${_('Registered accounts are ready to use and need no further action.')}</div>
-                      %else:
-                          <div class="activation_msg">${_('Please wait for an administrator to activate your account.')}</div>
-                      %endif
+                        ${h.submit('sign_up',_('Sign Up'),class_="btn btn-default")}
+                        %if c.auto_active:
+                            <div class="activation_msg">${_('Registered accounts are ready to use and need no further action.')}</div>
+                        %else:
+                            <div class="activation_msg">${_('Please wait for an administrator to activate your account.')}</div>
+                        %endif
                     </div>
                 </div>
             </div>
--- a/kallithea/templates/search/search.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/search/search.html	Fri Nov 18 01:11:13 2016 +0100
@@ -32,9 +32,9 @@
 %if c.repo_name:
 ${self.repo_context_bar('options')}
 %endif
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading">
         ${self.breadcrumbs()}
     </div>
     <!-- end box / title -->
@@ -44,23 +44,16 @@
         ${h.form(h.url('search'),method='get')}
     %endif
     <div class="form">
-        <div class="fields">
-            <div class="field field-first field-noborder">
-             <div class="label">
-                 <label for="q">${_('Search term')}:</label>
-             </div>
-                <div class="input">${h.text('q',c.cur_query,class_="small")}
-                    <div class="button highlight">
-                        <input type="submit" value="${_('Search')}" class="btn"/>
-                    </div>
+        <div class="form-horizontal">
+            <div class="form-group">
+                <label class="control-label" for="q">${_('Search term')}:</label>
+                <div class="input">
+                    ${h.text('q',c.cur_query,class_="small")}
                 </div>
-                <div style="font-weight: bold;clear:both;margin-left:200px">${c.runtime}</div>
             </div>
 
-            <div class="field">
-                <div class="label">
-                    <label for="type">${_('Search in')}:</label>
-                </div>
+            <div class="form-group">
+                <label for="type">${_('Search in')}:</label>
                 <div class="select">
                     ${h.select('type',c.cur_type,[('content',_('File contents')),
                         ('commit',_('Commit messages')),
@@ -68,8 +61,18 @@
                         ##('repository',_('Repository names')),
                         ])}
                 </div>
-             </div>
+            </div>
 
+            <div class="form-group">
+                <div class="buttons">
+                    <input type="submit" value="${_('Search')}" class="btn btn-default"/>
+                </div>
+            </div>
+
+            <div class="form-group">
+                ## <label>${_('Status')}:</label>
+                <div style="font-weight: bold;clear:both">${c.runtime}</div>
+            </div>
         </div>
     </div>
     ${h.end_form()}
--- a/kallithea/templates/search/search_commit.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/search/search_commit.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-##commit highligthing
+##commit highlighting
 
 %for cnt,sr in enumerate(c.formated_results):
     %if h.HasRepoPermissionAny('repository.write','repository.read','repository.admin')(sr['repository'],'search results check'):
@@ -12,9 +12,7 @@
             </div>
             <div class="left">
                 <div class="author">
-                    <div class="gravatar">
-                      ${h.gravatar(h.email_or_none(sr['author']), size=20)}
-                    </div>
+                    ${h.gravatar_div(h.email_or_none(sr['author']), size=20)}
                     <span>${h.person(sr['author'])}</span><br/>
                     <span>${h.email_or_none(sr['author'])}</a></span><br/>
                 </div>
@@ -23,7 +21,7 @@
                     <pre>${h.literal(sr['message_hl'])}</pre>
                 </div>
                 %else:
-                <div class="message">${h.urlify_commit(sr['message'], sr['repository'])}</div>
+                <div class="message">${h.urlify_text(sr['message'], sr['repository'])}</div>
                 %endif
             </div>
         </div>
@@ -39,7 +37,7 @@
     %endif
 %endfor
 %if c.cur_query and c.formated_results:
-<div class="pagination-wh pagination-left">
-    ${c.formated_results.pager('$link_previous ~2~ $link_next')}
-</div>
+    <ul class="pagination">
+        ${c.formated_results.pager()}
+    </ul>
 %endif
--- a/kallithea/templates/search/search_content.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/search/search_content.html	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-##content highligthing
+##content highlighting
 
 %for cnt,sr in enumerate(c.formated_results):
     %if h.HasRepoPermissionAny('repository.write','repository.read','repository.admin')(sr['repository'],'search results check'):
@@ -26,7 +26,7 @@
     %endif
 %endfor
 %if c.cur_query and c.formated_results:
-<div class="pagination-wh pagination-left" style="padding-left:16px">
-    ${c.formated_results.pager('$link_previous ~2~ $link_next')}
-</div>
+    <ul class="pagination">
+        ${c.formated_results.pager()}
+    </ul>
 %endif
--- a/kallithea/templates/search/search_path.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/search/search_path.html	Fri Nov 18 01:11:13 2016 +0100
@@ -20,7 +20,7 @@
     %endif
 %endfor
 %if c.cur_query and c.formated_results:
-<div class="pagination-wh pagination-left">
-    ${c.formated_results.pager('$link_previous ~2~ $link_next')}
-</div>
+    <ul class="pagination">
+        ${c.formated_results.pager()}
+    </ul>
 %endif
--- a/kallithea/templates/summary/statistics.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/summary/statistics.html	Fri Nov 18 01:11:13 2016 +0100
@@ -22,9 +22,9 @@
     <%
     summary = lambda n:{False:'summary-short'}.get(n)
     %>
-    <div class="box">
+    <div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading">
         ${self.breadcrumbs()}
     </div>
 
@@ -32,8 +32,8 @@
          <div style="padding:0 10px 10px 17px;">
          %if c.no_data:
            ${c.no_data_msg}
-           %if h.HasPermissionAll('hg.admin')('enable stats on from summary'):
-                ${h.link_to(_('Enable'),h.url('edit_repo',repo_name=c.repo_name),class_="btn btn-mini")}
+           %if h.HasPermissionAny('hg.admin')('enable stats on from summary'):
+                ${h.link_to(_('Enable'),h.url('edit_repo',repo_name=c.repo_name),class_="btn btn-default btn-xs")}
            %endif
         %else:
             ${_('Stats gathered: ')} ${c.stats_percentage}%
@@ -123,6 +123,9 @@
 
 </script>
 <script type="text/javascript">
+var YUD = YAHOO.util.Dom;
+var YUE = YAHOO.util.Event;
+
 /**
  * Plots summary graph
  *
@@ -192,7 +195,7 @@
     }
 
     /**
-     * generate checkboxes accordindly to data
+     * generate checkboxes accordingly to data
      * @param keys
      * @returns
      */
--- a/kallithea/templates/summary/summary.html	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/templates/summary/summary.html	Fri Nov 18 01:11:13 2016 +0100
@@ -10,9 +10,9 @@
     ## locking icon
     %if c.db_repo.enable_locking:
      %if c.db_repo.locked[0]:
-       <span class="locking_locked tooltip icon-block" title="${_('Repository locked by %s') % h.person_by_id(c.db_repo.locked[0])}"></span>
+       <span class="locking_locked icon-block" data-toggle="tooltip" title="${_('Repository locked by %s') % h.person_by_id(c.db_repo.locked[0])}"></span>
      %else:
-       <span class="locking_unlocked tooltip icon-ok" title="${_('Repository unlocked')}"></span>
+       <span class="locking_unlocked icon-ok" data-toggle="tooltip" title="${_('Repository unlocked')}"></span>
      %endif
     %endif
 
@@ -59,70 +59,62 @@
 <%
 summary = lambda n:{False:'summary-short'}.get(n)
 %>
-<div class="box">
+<div class="panel panel-primary">
     <!-- box / title -->
-    <div class="title">
+    <div class="panel-heading">
         ${self.breadcrumbs()}
     </div>
     <!-- end box / title -->
     <div class="form">
-        <div id="summary" class="fields">
-            <div class="field">
-                <div class="label-summary">
-                  <label>${_('Clone URL')}:</label>
-                </div>
+        <div id="summary" class="form-horizontal">
+            <div class="form-group clearfix">
+              <label>${_('Clone URL')}:</label>
                 <div class="input ${summary(c.show_stats)}">
                   ${self.repotag(c.db_repo)}
                   <input style="width:80%" type="text" id="clone_url" readonly="readonly" value="${c.clone_repo_url}"/>
                   <input style="display:none;width:80%" type="text" id="clone_url_id" readonly="readonly" value="${c.clone_repo_url_id}"/>
-                  <div style="display:none" id="clone_by_name" class="btn btn-small">${_('Show by Name')}</div>
-                  <div id="clone_by_id" class="btn btn-small">${_('Show by ID')}</div>
+                  <div style="display:none" id="clone_by_name" class="btn btn-default btn-sm">${_('Show by Name')}</div>
+                  <div id="clone_by_id" class="btn btn-default btn-sm">${_('Show by ID')}</div>
                 </div>
             </div>
 
-            <div class="field">
-              <div class="label-summary">
-                  <label>${_('Description')}:</label>
-              </div>
+            <div class="form-group clearfix">
+              <label>${_('Description')}:</label>
               <div class="input ${summary(c.show_stats)} desc">${h.urlify_text(c.db_repo.description, stylize=c.visual.stylify_metatags)}</div>
             </div>
 
-            <div class="field">
-              <div class="label-summary">
-                  <label>${_('Trending files')}:</label>
-              </div>
+            <div class="form-group clearfix">
+              <label>${_('Trending files')}:</label>
               <div class="input ${summary(c.show_stats)}">
                 %if c.show_stats:
                 <div id="lang_stats"></div>
                 %else:
                    ${_('Statistics are disabled for this repository')}
-                   %if h.HasPermissionAll('hg.admin')('enable stats on from summary'):
-                        ${h.link_to(_('Enable'),h.url('edit_repo',repo_name=c.repo_name, anchor='repo_enable_statistics'),class_="btn btn-mini")}
+                   %if h.HasPermissionAny('hg.admin')('enable stats on from summary'):
+                        ${h.link_to(_('Enable'),h.url('edit_repo',repo_name=c.repo_name, anchor='repo_enable_statistics'),class_="btn btn-default btn-xs")}
                    %endif
                 %endif
               </div>
             </div>
 
-            <div class="field">
-              <div class="label-summary">
-                  <label>${_('Download')}:</label>
-              </div>
+            <div class="form-group clearfix">
+              <label>${_('Download')}:</label>
               <div class="input ${summary(c.show_stats)}">
                 %if len(c.db_repo_scm_instance.revisions) == 0:
                   ${_('There are no downloads yet')}
                 %elif not c.enable_downloads:
                   ${_('Downloads are disabled for this repository')}
-                    %if h.HasPermissionAll('hg.admin')('enable downloads on from summary'):
-                        ${h.link_to(_('Enable'),h.url('edit_repo',repo_name=c.repo_name, anchor='repo_enable_downloads'),class_="btn btn-mini")}
+                    %if h.HasPermissionAny('hg.admin')('enable downloads on from summary'):
+                        ${h.link_to(_('Enable'),h.url('edit_repo',repo_name=c.repo_name, anchor='repo_enable_downloads'),class_="btn btn-default btn-xs")}
                     %endif
                 %else:
                     <span id="${'zip_link'}">
-                        <a class="btn btn-small" href="${h.url('files_archive_home',repo_name=c.db_repo.repo_name,fname='tip.zip')}"><i class="icon-file-zip"></i> ${_('Download as zip')}</a>
+                        <a class="btn btn-default btn-sm" href="${h.url('files_archive_home',repo_name=c.db_repo.repo_name,fname='tip.zip')}"><i class="icon-file-zip"></i> ${_('Download as zip')}</a>
                     </span>
                     ${h.hidden('download_options')}
                     <span style="vertical-align: bottom">
                       <input id="archive_subrepos" type="checkbox" name="subrepos" />
-                      <label for="archive_subrepos" class="tooltip" title="${_('Check this to download archive with subrepos')}" >${_('With subrepos')}</label>
+                      <label for="archive_subrepos" data-toggle="tooltip" title="${_('Check this to download archive with subrepos')}" >${_('With subrepos')}</label>
                     </span>
                 %endif
               </div>
@@ -131,28 +123,26 @@
         <div id="summary-menu-stats">
           <ul>
             <li>
-               <a title="${_('Owner')} ${c.db_repo.user.email}">
-                <i class="icon-user"></i> ${c.db_repo.user.username}
-                  <div class="gravatar" style="float: right; margin: 0px 0px 0px 0px" title="${c.db_repo.user.name} ${c.db_repo.user.lastname}">
-                    ${h.gravatar(c.db_repo.user.email, size=18)}
-                  </div>
+               <a title="${_('Owner')} ${c.db_repo.owner.email}">
+                <i class="icon-user"></i> ${c.db_repo.owner.username}
+                ${h.gravatar_div(c.db_repo.owner.email, size=18, div_style="float: right; margin: 0px 0px 0px 0px", div_title=c.db_repo.owner.full_name)}
               </a>
             </li>
             <li>
                <a title="${_('Followers')}" href="${h.url('repo_followers_home',repo_name=c.repo_name)}">
                 <i class="icon-heart"></i> ${_('Followers')}
-                <span class="stats-bullet" id="current_followers_count">${c.repository_followers}</span>
+                <span class="badge" id="current_followers_count">${c.repository_followers}</span>
               </a>
             </li>
             <li>
               <a title="${_('Forks')}" href="${h.url('repo_forks_home',repo_name=c.repo_name)}">
                 <i class="icon-fork"></i> ${_('Forks')}
-                <span class="stats-bullet">${c.repository_forks}</span>
+                <span class="badge">${c.repository_forks}</span>
               </a>
             </li>
 
             %if c.authuser.username != 'default':
-            <li class="repo_size">
+            <li class="repo_size clearfix">
               <a href="#" onclick="javascript:showRepoSize('repo_size_2','${c.db_repo.repo_name}')"><i class="icon-ruler"></i> ${_('Repository Size')}</a>
               <span  class="stats-bullet" id="repo_size_2"></span>
             </li>
@@ -179,8 +169,8 @@
 </div>
 
 
-<div class="box">
-    <div class="title">
+<div class="panel panel-primary">
+    <div class="panel-heading">
         <div class="breadcrumbs">
         %if c.repo_changesets:
             ${h.link_to(_('Latest Changes'),h.url('changelog_home',repo_name=c.repo_name))}
@@ -198,8 +188,8 @@
 
 %if c.readme_data:
 <div id="readme" class="anchor">
-<div class="box" style="background-color: #FAFAFA">
-    <div class="title" title="${_('Readme file from revision %s:%s') % (c.db_repo.landing_rev[0], c.db_repo.landing_rev[1])}">
+<div class="panel panel-primary" style="background-color: #FAFAFA">
+    <div class="panel-heading" title="${_('Readme file from revision %s:%s') % (c.db_repo.landing_rev[0], c.db_repo.landing_rev[1])}">
         <div class="breadcrumbs">
             <a href="${h.url('files_home',repo_name=c.repo_name,revision='tip',f_path=c.readme_file)}">${c.readme_file}</a>
         </div>
@@ -306,7 +296,7 @@
 
     var tmpl_links = {};
     %for cnt,archive in enumerate(c.db_repo_scm_instance._get_archives()):
-      tmpl_links["${archive['type']}"] = '${h.link_to('__NAME__', h.url('files_archive_home',repo_name=c.db_repo.repo_name, fname='__CS__'+archive['extension'],subrepos='__SUB__'),class_='btn btn-small')}';
+      tmpl_links["${archive['type']}"] = '${h.link_to('__NAME__', h.url('files_archive_home',repo_name=c.db_repo.repo_name, fname='__CS__'+archive['extension'],subrepos='__SUB__'),class_='btn btn-default btn-sm')}';
     %endfor
 });
 </script>
--- a/kallithea/templates/switch_to_list.html	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,49 +0,0 @@
-## -*- coding: utf-8 -*-
-<li>
-    <a href="${h.url('branches_home',repo_name=c.repo_name)}" class="childs"><i class="icon-fork"></i> ${'%s (%s)' % (_('Branches'),len(c.db_repo_scm_instance.branches.values()))}</a>
-    <ul>
-    %if c.db_repo_scm_instance.branches.values():
-        %for cnt,branch in enumerate(c.db_repo_scm_instance.branches.items()):
-            <li><div><pre>${h.link_to('%s - %s' % (branch[0],h.short_id(branch[1])),h.url('files_home',repo_name=c.repo_name,revision=(branch[0] if '/' not in branch[0] else branch[1]), at=branch[0]))}</pre></div></li>
-        %endfor
-    %else:
-        <li>${h.link_to(_('There are no branches yet'),'#')}</li>
-    %endif
-    </ul>
-</li>
-%if c.db_repo_scm_instance.closed_branches.values():
-<li>
-    <a href="${h.url('branches_home',repo_name=c.repo_name)}" class="childs"><i class="icon-fork"></i> ${'%s (%s)' % (_('Closed Branches'),len(c.db_repo_scm_instance.closed_branches.values()))}</a>
-    <ul>
-        %for cnt,branch in enumerate(c.db_repo_scm_instance.closed_branches.items()):
-            <li><div><pre>${h.link_to('%s - %s' % (branch[0],h.short_id(branch[1])),h.url('files_home',repo_name=c.repo_name,revision=(branch[0] if '/' not in branch[0] else branch[1]), at=branch[0]))}</pre></div></li>
-        %endfor
-    </ul>
-</li>
-%endif
-<li>
-    <a href="${h.url('tags_home',repo_name=c.repo_name)}" class="childs"><i class="icon-tag"></i> ${'%s (%s)' % (_('Tags'),len(c.db_repo_scm_instance.tags.values()))}</a>
-    <ul>
-    %if c.db_repo_scm_instance.tags.values():
-        %for cnt,tag in enumerate(c.db_repo_scm_instance.tags.items()):
-         <li><div><pre>${h.link_to('%s - %s' % (tag[0],h.short_id(tag[1])),h.url('files_home',repo_name=c.repo_name,revision=(tag[0] if '/' not in tag[0] else tag[1]), at=tag[0]))}</pre></div></li>
-        %endfor
-    %else:
-        <li>${h.link_to(_('There are no tags yet'),'#')}</li>
-    %endif
-    </ul>
-</li>
-%if c.db_repo_scm_instance.alias == 'hg':
-<li>
-    <a href="${h.url('bookmarks_home',repo_name=c.repo_name)}" class="childs"><i class="icon-bookmark"></i> ${'%s (%s)' % (_('Bookmarks'),len(c.db_repo_scm_instance.bookmarks.values()))}</a>
-    <ul>
-    %if c.db_repo_scm_instance.bookmarks.values():
-        %for cnt,book in enumerate(c.db_repo_scm_instance.bookmarks.items()):
-         <li><div><pre>${h.link_to('%s - %s' % (book[0],h.short_id(book[1])),h.url('files_home',repo_name=c.repo_name,revision=(book[0] if '/' not in book[0] else book[1]), at=book[0]))}</pre></div></li>
-        %endfor
-    %else:
-        <li>${h.link_to(_('There are no bookmarks yet'),'#')}</li>
-    %endif
-    </ul>
-</li>
-%endif
--- a/kallithea/templates/tags/tags.html	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,96 +0,0 @@
-## -*- coding: utf-8 -*-
-<%inherit file="/base/base.html"/>
-
-<%block name="title">
-    ${_('%s Tags') % c.repo_name}
-</%block>
-
-<%def name="breadcrumbs_links()">
-    <input class="q_filter_box" id="q_filter_tags" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value=""/>
-    ${_('Tags')}
-</%def>
-
-<%block name="header_menu">
-    ${self.menu('repositories')}
-</%block>
-
-<%def name="main()">
-${self.repo_context_bar('switch-to')}
-<div class="box">
-    <!-- box / title -->
-    <div class="title">
-        ${self.breadcrumbs()}
-    </div>
-    <!-- end box / title -->
-    %if c.repo_tags:
-    <div class="info_box" id="compare_tags" style="clear: both;padding: 10px 19px;text-align: right;"><a href="#" class="btn btn-small">${_('Compare Tags')}</a></div>
-    %endif
-    <div class="table">
-        <%include file='tags_data.html'/>
-    </div>
-</div>
-
-<script type="text/javascript">
-$('#compare_tags').click(function(e){
-    e.preventDefault();
-    var org = $('input[name=compare_org]:checked')[0];
-    var other = $('input[name=compare_other]:checked')[0];
-
-    if(org && other){
-        var compare_url = "${h.url('compare_url',repo_name=c.repo_name,org_ref_type='tag',org_ref_name='__ORG__',other_ref_type='tag',other_ref_name='__OTHER__')}";
-        var u = compare_url.replace('__ORG__',org.value)
-                           .replace('__OTHER__',other.value);
-        window.location=u;
-    }
-});
-
-// main table sorting
-var myColumnDefs = [
-    {key:"name",label:"${_('Name')}",sortable:true,
-        sortOptions: { sortFunction: nameSort }},
-    {key:"date",label:"${_('Date')}",sortable:true,
-        sortOptions: { sortFunction: dateSort }},
-    {key:"author",label:"${_('Author')}",sortable:true},
-    {key:"revision",label:"${_('Revision')}",sortable:true,
-        sortOptions: { sortFunction: revisionSort }},
-    {key:"compare",label:"${_('Compare')}",sortable:false}
-];
-
-var myDataSource = new YAHOO.util.DataSource(YUD.get("tags_data"));
-
-myDataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;
-
-myDataSource.responseSchema = {
-    fields: [
-        {key:"raw_name"},
-        {key:"name"},
-        {key:"raw_date"},
-        {key:"date"},
-        {key:"author"},
-        {key:"last_rev_raw"},
-        {key:"revision"},
-        {key:"compare"}
-    ]
-};
-
-var myDataTable = new YAHOO.widget.DataTable("table_wrap", myColumnDefs, myDataSource,
-    {
-         sortedBy:{key:"name",dir:"asc"},
-         MSG_SORTASC:"${_('Click to sort ascending')}",
-         MSG_SORTDESC:"${_('Click to sort descending')}",
-         MSG_EMPTY:"${_('No records found.')}",
-         MSG_ERROR:"${_('Data error.')}",
-         MSG_LOADING:"${_('Loading...')}"
-    }
-);
-myDataTable.subscribe('postRenderEvent',function(oArgs) {
-    tooltip_activate();
-    var func = function(node){
-        return node.parentNode.parentNode.parentNode.parentNode.parentNode;
-    }
-    q_filter('q_filter_tags',$('div.table tr td .logtags .tagtag a'),func);
-});
-
-</script>
-
-</%def>
--- a/kallithea/templates/tags/tags_data.html	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,45 +0,0 @@
-%if c.repo_tags:
-   <div id="table_wrap" class="yui-skin-sam">
-    <table id="tags_data">
-      <thead>
-        <tr>
-            <th class="left">Raw name</th> ##notranslation
-            <th class="left">${_('Name')}</th>
-            <th class="left">Raw date</th> ##notranslation
-            <th class="left">${_('Date')}</th>
-            <th class="left">${_('Author')}</th>
-            <th class="left">Raw rev</th> ##notranslation
-            <th class="left">${_('Revision')}</th>
-            <th class="left">${_('Compare')}</th>
-        </tr>
-      </thead>
-        %for cnt,tag in enumerate(c.repo_tags.items()):
-        <tr class="parity${cnt%2}">
-            <td>${tag[0]}</td>
-            <td>
-                <span class="logtags">
-                    <span class="tagtag">${h.link_to(tag[0],
-                    h.url('changeset_home',repo_name=c.repo_name,revision=tag[1].raw_id))}
-                    </span>
-                </span>
-            </td>
-            <td>${tag[1]._timestamp}</td>
-            <td><span class="tooltip" title="${h.age(tag[1].date)}">${h.fmt_date(tag[1].date)}</span></td>
-            <td title="${tag[1].author}">${h.person(tag[1].author)}</td>
-            <td>${tag[1].revision}</td>
-            <td>
-                <div>
-                    <a href="${h.url('changeset_home',repo_name=c.repo_name,revision=tag[1].raw_id)}" class="revision-link">${h.show_id(tag[1])}</a>
-                </div>
-            </td>
-            <td>
-                <input class="branch-compare" type="radio" name="compare_org" value="${tag[0]}"/>
-                <input class="branch-compare" type="radio" name="compare_other" value="${tag[0]}"/>
-            </td>
-        </tr>
-        %endfor
-    </table>
-   </div>
-%else:
-    ${_('There are no tags yet')}
-%endif
--- a/kallithea/tests/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/__init__.py	Fri Nov 18 01:11:13 2016 +0100
@@ -13,230 +13,14 @@
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 """
-Pylons application test package
-
-This package assumes the Pylons environment is already loaded, such as
-when this script is imported from the `nosetests --with-pylons=test.ini`
-command.
-
-This module initializes the application via ``websetup`` (`paster
-setup-app`) and provides the base testing objects.
-
-nosetests -x - fail on first error
-nosetests kallithea.tests.functional.test_admin_settings:TestSettingsController.test_my_account
-nosetests --pdb --pdb-failures
-nosetests --with-coverage --cover-package=kallithea.model.validators kallithea.tests.test_validators
-
-optional FLAGS:
-    KALLITHEA_WHOOSH_TEST_DISABLE=1 - skip whoosh index building and tests
-    KALLITHEA_NO_TMP_PATH=1 - disable new temp path for tests, used mostly for test_vcs_operations
-
-"""
-import os
-import re
-import time
-import logging
-import datetime
-import hashlib
-import tempfile
-from os.path import join as jn
-
-from tempfile import _RandomNameSequence
-
-import pylons
-import pylons.test
-from pylons import config, url
-from pylons.i18n.translation import _get_translator
-from pylons.util import ContextObj
-
-from routes.util import URLGenerator
-from webtest import TestApp
-from nose.plugins.skip import SkipTest
-
-from kallithea.lib.compat import unittest
-from kallithea import is_windows
-from kallithea.model.db import Notification, User, UserNotification
-from kallithea.model.meta import Session
-from kallithea.tests.parameterized import parameterized
-from kallithea.lib.utils2 import safe_str
-
-
-os.environ['TZ'] = 'UTC'
-if not is_windows:
-    time.tzset()
-
-log = logging.getLogger(__name__)
+Kallithea test package
 
-__all__ = [
-    'parameterized', 'environ', 'url', 'TestController',
-    'SkipTest', 'ldap_lib_installed', 'pam_lib_installed', 'BaseTestCase', 'init_stack',
-    'TESTS_TMP_PATH', 'HG_REPO', 'GIT_REPO', 'NEW_HG_REPO', 'NEW_GIT_REPO',
-    'HG_FORK', 'GIT_FORK', 'TEST_USER_ADMIN_LOGIN', 'TEST_USER_ADMIN_PASS',
-    'TEST_USER_ADMIN_EMAIL', 'TEST_USER_REGULAR_LOGIN', 'TEST_USER_REGULAR_PASS',
-    'TEST_USER_REGULAR_EMAIL', 'TEST_USER_REGULAR2_LOGIN',
-    'TEST_USER_REGULAR2_PASS', 'TEST_USER_REGULAR2_EMAIL', 'TEST_HG_REPO',
-    'TEST_HG_REPO_CLONE', 'TEST_HG_REPO_PULL', 'TEST_GIT_REPO',
-    'TEST_GIT_REPO_CLONE', 'TEST_GIT_REPO_PULL', 'HG_REMOTE_REPO',
-    'GIT_REMOTE_REPO', 'SCM_TESTS',
-]
-
-# Invoke websetup with the current config file
-# SetupCommand('setup-app').run([config_file])
-
-environ = {}
-
-#SOME GLOBALS FOR TESTS
-
-TESTS_TMP_PATH = jn('/', 'tmp', 'rc_test_%s' % _RandomNameSequence().next())
-TEST_USER_ADMIN_LOGIN = 'test_admin'
-TEST_USER_ADMIN_PASS = 'test12'
-TEST_USER_ADMIN_EMAIL = 'test_admin@example.com'
-
-TEST_USER_REGULAR_LOGIN = 'test_regular'
-TEST_USER_REGULAR_PASS = 'test12'
-TEST_USER_REGULAR_EMAIL = 'test_regular@example.com'
-
-TEST_USER_REGULAR2_LOGIN = 'test_regular2'
-TEST_USER_REGULAR2_PASS = 'test12'
-TEST_USER_REGULAR2_EMAIL = 'test_regular2@example.com'
-
-HG_REPO = 'vcs_test_hg'
-GIT_REPO = 'vcs_test_git'
-
-NEW_HG_REPO = 'vcs_test_hg_new'
-NEW_GIT_REPO = 'vcs_test_git_new'
-
-HG_FORK = 'vcs_test_hg_fork'
-GIT_FORK = 'vcs_test_git_fork'
-
-## VCS
-SCM_TESTS = ['hg', 'git']
-uniq_suffix = str(int(time.mktime(datetime.datetime.now().timetuple())))
-
-GIT_REMOTE_REPO = 'git://github.com/codeinn/vcs.git'
-
-TEST_GIT_REPO = jn(TESTS_TMP_PATH, GIT_REPO)
-TEST_GIT_REPO_CLONE = jn(TESTS_TMP_PATH, 'vcsgitclone%s' % uniq_suffix)
-TEST_GIT_REPO_PULL = jn(TESTS_TMP_PATH, 'vcsgitpull%s' % uniq_suffix)
-
-
-HG_REMOTE_REPO = 'http://bitbucket.org/marcinkuzminski/vcs'
-
-TEST_HG_REPO = jn(TESTS_TMP_PATH, HG_REPO)
-TEST_HG_REPO_CLONE = jn(TESTS_TMP_PATH, 'vcshgclone%s' % uniq_suffix)
-TEST_HG_REPO_PULL = jn(TESTS_TMP_PATH, 'vcshgpull%s' % uniq_suffix)
+Refer to docs/contributing.rst for details on running the test suite.
+"""
 
-TEST_DIR = tempfile.gettempdir()
-TEST_REPO_PREFIX = 'vcs-test'
-
-# cached repos if any !
-# comment out to get some other repos from bb or github
-GIT_REMOTE_REPO = jn(TESTS_TMP_PATH, GIT_REPO)
-HG_REMOTE_REPO = jn(TESTS_TMP_PATH, HG_REPO)
-
-#skip ldap tests if LDAP lib is not installed
-ldap_lib_installed = False
-try:
-    import ldap
-    ldap.API_VERSION
-    ldap_lib_installed = True
-except ImportError:
-    # means that python-ldap is not installed
-    pass
-
-try:
-    import pam
-    pam.PAM_TEXT_INFO
-    pam_lib_installed = True
-except ImportError:
-    pam_lib_installed = False
-
-import logging
-
-class NullHandler(logging.Handler):
-    def emit(self, record):
-        pass
-
-def init_stack(config=None):
-    if not config:
-        config = pylons.test.pylonsapp.config
-    url._push_object(URLGenerator(config['routes.map'], environ))
-    pylons.app_globals._push_object(config['pylons.app_globals'])
-    pylons.config._push_object(config)
-    pylons.tmpl_context._push_object(ContextObj())
-    # Initialize a translator for tests that utilize i18n
-    translator = _get_translator(pylons.config.get('lang'))
-    pylons.translator._push_object(translator)
-    h = NullHandler()
-    logging.getLogger("kallithea").addHandler(h)
-
-
-class BaseTestCase(unittest.TestCase):
-    def __init__(self, *args, **kwargs):
-        self.wsgiapp = pylons.test.pylonsapp
-        init_stack(self.wsgiapp.config)
-        unittest.TestCase.__init__(self, *args, **kwargs)
-
-    def remove_all_notifications(self):
-        Notification.query().delete()
+import pytest
 
-        # Because query().delete() does not (by default) trigger cascades.
-        # http://docs.sqlalchemy.org/en/rel_0_7/orm/collections.html#passive-deletes
-        UserNotification.query().delete()
-
-        Session().commit()
-
-
-class TestController(BaseTestCase):
-
-    def __init__(self, *args, **kwargs):
-        BaseTestCase.__init__(self, *args, **kwargs)
-        self.app = TestApp(self.wsgiapp)
-        self.maxDiff = None
-        self.index_location = config['app_conf']['index_dir']
-
-    def log_user(self, username=TEST_USER_ADMIN_LOGIN,
-                 password=TEST_USER_ADMIN_PASS):
-        self._logged_username = username
-        response = self.app.post(url(controller='login', action='index'),
-                                 {'username': username,
-                                  'password': password})
-
-        if 'Invalid username or password' in response.body:
-            self.fail('could not login using %s %s' % (username, password))
-
-        self.assertEqual(response.status, '302 Found')
-        self.assert_authenticated_user(response, username)
-
-        response = response.follow()
-        return response.session['authuser']
-
-    def _get_logged_user(self):
-        return User.get_by_username(self._logged_username)
-
-    def assert_authenticated_user(self, response, expected_username):
-        cookie = response.session.get('authuser')
-        user = cookie and cookie.get('user_id')
-        user = user and User.get(user)
-        user = user and user.username
-        self.assertEqual(user, expected_username)
-        self.assertEqual(cookie.get('is_authenticated'), True)
-
-    def authentication_token(self):
-        return self.app.get(url('authentication_token')).body
-
-    def checkSessionFlash(self, response, msg=None, skip=0, _matcher=lambda msg, m: msg in m):
-        if 'flash' not in response.session:
-            self.fail(safe_str(u'msg `%s` not found - session has no flash:\n%s' % (msg, response)))
-        try:
-            level, m = response.session['flash'][-1 - skip]
-            if _matcher(msg, m):
-                return
-        except IndexError:
-            pass
-        self.fail(safe_str(u'msg `%s` not found in session flash (skipping %s): %s' %
-                           (msg, skip,
-                            ', '.join('`%s`' % m for level, m in response.session['flash']))))
-
-    def checkSessionFlashRegex(self, response, regex, skip=0):
-        self.checkSessionFlash(response, regex, skip=skip, _matcher=re.search)
+if getattr(pytest, 'register_assert_rewrite', None):
+    # make sure that all asserts under kallithea/tests benefit from advanced
+    # assert reporting with pytest-3.0.0+.
+    pytest.register_assert_rewrite('kallithea.tests.')
--- a/kallithea/tests/api/api_base.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/api/api_base.py	Fri Nov 18 01:11:13 2016 +0100
@@ -13,16 +13,14 @@
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 """
-tests for api. run with::
-
-    KALLITHEA_WHOOSH_TEST_DISABLE=1 nosetests --with-coverage --cover-package=kallithea.controllers.api.api -x kallithea/tests/api
+Tests for the JSON-RPC web api.
 """
 
 import os
 import random
 import mock
 
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.tests.fixture import Fixture
 from kallithea.lib.compat import json
 from kallithea.lib.auth import AuthUser
@@ -33,13 +31,13 @@
 from kallithea.model.meta import Session
 from kallithea.model.scm import ScmModel
 from kallithea.model.gist import GistModel
-from kallithea.model.db import Repository, User, Setting
+from kallithea.model.db import Repository, User, Setting, Ui
 from kallithea.lib.utils2 import time_to_datetime
 
 
 API_URL = '/_admin/api'
-TEST_USER_GROUP = 'test_user_group'
-TEST_REPO_GROUP = 'test_repo_group'
+TEST_USER_GROUP = u'test_user_group'
+TEST_REPO_GROUP = u'test_repo_group'
 
 fixture = Fixture()
 
@@ -99,8 +97,8 @@
             username='test-api',
             password='test',
             email='test@example.com',
-            firstname='first',
-            lastname='last'
+            firstname=u'first',
+            lastname=u'last'
         )
         Session().commit()
         cls.TEST_USER_LOGIN = cls.test_user.username
@@ -110,12 +108,12 @@
     def teardown_class(cls):
         pass
 
-    def setUp(self):
+    def setup_method(self, method):
         self.maxDiff = None
         make_user_group()
         make_repo_group()
 
-    def tearDown(self):
+    def teardown_method(self, method):
         fixture.destroy_user_group(TEST_USER_GROUP)
         fixture.destroy_gists()
         fixture.destroy_repo_group(TEST_REPO_GROUP)
@@ -127,7 +125,7 @@
             'result': expected
         })
         given = json.loads(given)
-        self.assertEqual(expected, given)
+        assert expected == given
 
     def _compare_error(self, id_, expected, given):
         expected = jsonify({
@@ -136,30 +134,30 @@
             'result': None
         })
         given = json.loads(given)
-        self.assertEqual(expected, given)
+        assert expected == given
 
     def test_Optional_object(self):
         from kallithea.controllers.api.api import Optional
 
         option1 = Optional(None)
-        self.assertEqual('<Optional:%s>' % None, repr(option1))
-        self.assertEqual(option1(), None)
+        assert '<Optional:%s>' % None == repr(option1)
+        assert option1() == None
 
-        self.assertEqual(1, Optional.extract(Optional(1)))
-        self.assertEqual('trololo', Optional.extract('trololo'))
+        assert 1 == Optional.extract(Optional(1))
+        assert 'trololo' == Optional.extract('trololo')
 
     def test_Optional_OAttr(self):
         from kallithea.controllers.api.api import Optional, OAttr
 
         option1 = Optional(OAttr('apiuser'))
-        self.assertEqual('apiuser', Optional.extract(option1))
+        assert 'apiuser' == Optional.extract(option1)
 
     def test_OAttr_object(self):
         from kallithea.controllers.api.api import OAttr
 
         oattr1 = OAttr('apiuser')
-        self.assertEqual('<OptionalAttr:apiuser>', repr(oattr1))
-        self.assertEqual(oattr1(), oattr1)
+        assert '<OptionalAttr:apiuser>' == repr(oattr1)
+        assert oattr1() == oattr1
 
     def test_api_wrong_key(self):
         id_, params = _build_data('trololo', 'get_user')
@@ -195,13 +193,13 @@
         id_, params = _build_data(self.apikey, 'get_users', )
         params = params.replace('"args": {}', '"args": null')
         response = api_call(self, params)
-        self.assertEqual(response.status, '200 OK')
+        assert response.status == '200 OK'
 
     def test_api_args_is_bad(self):
         id_, params = _build_data(self.apikey, 'get_users', )
         params = params.replace('"args": {}', '"args": 1')
         response = api_call(self, params)
-        self.assertEqual(response.status, '200 OK')
+        assert response.status == '200 OK'
 
     def test_api_args_different_args(self):
         import string
@@ -212,7 +210,7 @@
         }
         id_, params = _build_data(self.apikey, 'test', args=expected)
         response = api_call(self, params)
-        self.assertEqual(response.status, '200 OK')
+        assert response.status == '200 OK'
         self._compare_ok(id_, expected, response.body)
 
     def test_api_get_users(self):
@@ -278,10 +276,9 @@
         self._compare_error(id_, expected, given=response.body)
 
     def test_api_pull(self):
-        repo_name = 'test_pull'
+        repo_name = u'test_pull'
         r = fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
-        r.clone_uri = os.path.join(TESTS_TMP_PATH, self.REPO)
-        Session.add(r)
+        r.clone_uri = os.path.join(Ui.get_by_key('paths', '/').ui_value, self.REPO)
         Session.commit()
 
         id_, params = _build_data(self.apikey, 'pull',
@@ -351,7 +348,7 @@
         expected = "repository `%s` does not exist" % (self.REPO,)
         self._compare_error(id_, expected, given=response.body)
 
-    def test_api_lock_repo_lock_aquire(self):
+    def test_api_lock_repo_lock_acquire(self):
         id_, params = _build_data(self.apikey, 'lock',
                                   userid=TEST_USER_ADMIN_LOGIN,
                                   repoid=self.REPO,
@@ -367,8 +364,8 @@
         }
         self._compare_ok(id_, expected, given=response.body)
 
-    def test_api_lock_repo_lock_aquire_by_non_admin(self):
-        repo_name = 'api_delete_me'
+    def test_api_lock_repo_lock_acquire_by_non_admin(self):
+        repo_name = u'api_delete_me'
         fixture.create_repo(repo_name, repo_type=self.REPO_TYPE,
                             cur_user=self.TEST_USER_LOGIN)
         try:
@@ -389,8 +386,8 @@
         finally:
             fixture.destroy_repo(repo_name)
 
-    def test_api_lock_repo_lock_aquire_non_admin_with_userid(self):
-        repo_name = 'api_delete_me'
+    def test_api_lock_repo_lock_acquire_non_admin_with_userid(self):
+        repo_name = u'api_delete_me'
         fixture.create_repo(repo_name, repo_type=self.REPO_TYPE,
                             cur_user=self.TEST_USER_LOGIN)
         try:
@@ -404,7 +401,7 @@
         finally:
             fixture.destroy_repo(repo_name)
 
-    def test_api_lock_repo_lock_aquire_non_admin_not_his_repo(self):
+    def test_api_lock_repo_lock_acquire_non_admin_not_his_repo(self):
         id_, params = _build_data(self.apikey_regular, 'lock',
                                   repoid=self.REPO,
                                   locked=True)
@@ -429,7 +426,7 @@
         }
         self._compare_ok(id_, expected, given=response.body)
 
-    def test_api_lock_repo_lock_aquire_optional_userid(self):
+    def test_api_lock_repo_lock_acquire_optional_userid(self):
         id_, params = _build_data(self.apikey, 'lock',
                                   repoid=self.REPO,
                                   locked=True)
@@ -448,27 +445,31 @@
         self._compare_ok(id_, expected, given=response.body)
 
     def test_api_lock_repo_lock_optional_locked(self):
-        id_, params = _build_data(self.apikey, 'lock',
-                                  repoid=self.REPO)
-        response = api_call(self, params)
-        time_ = response.json['result']['locked_since']
-        expected = {
-            'repo': self.REPO,
-            'locked': True,
-            'locked_since': time_,
-            'locked_by': TEST_USER_ADMIN_LOGIN,
-            'lock_state_changed': False,
-            'msg': ('Repo `%s` locked by `%s` on `%s`.'
-                    % (self.REPO, TEST_USER_ADMIN_LOGIN,
-                       json.dumps(time_to_datetime(time_))))
-        }
-        self._compare_ok(id_, expected, given=response.body)
+        try:
+            id_, params = _build_data(self.apikey, 'lock',
+                                      repoid=self.REPO)
+            response = api_call(self, params)
+            time_ = response.json['result']['locked_since']
+            expected = {
+                'repo': self.REPO,
+                'locked': True,
+                'locked_since': time_,
+                'locked_by': TEST_USER_ADMIN_LOGIN,
+                'lock_state_changed': False,
+                'msg': ('Repo `%s` locked by `%s` on `%s`.'
+                        % (self.REPO, TEST_USER_ADMIN_LOGIN,
+                           json.dumps(time_to_datetime(time_))))
+            }
+            self._compare_ok(id_, expected, given=response.body)
+        finally:
+            # cleanup
+            Repository.unlock(RepoModel().get_by_repo_name(self.REPO))
 
     def test_api_lock_repo_lock_optional_not_locked(self):
-        repo_name = 'api_not_locked'
+        repo_name = u'api_not_locked'
         repo = fixture.create_repo(repo_name, repo_type=self.REPO_TYPE,
                             cur_user=self.TEST_USER_LOGIN)
-        self.assertEqual(repo.locked, [None, None])
+        assert repo.locked == [None, None]
         try:
             id_, params = _build_data(self.apikey, 'lock',
                                       repoid=repo.repo_id)
@@ -516,7 +517,7 @@
         self._compare_ok(id_, expected, given=response.body)
 
     def test_api_get_locks_with_one_locked_repo(self):
-        repo_name = 'api_delete_me'
+        repo_name = u'api_delete_me'
         repo = fixture.create_repo(repo_name, repo_type=self.REPO_TYPE,
                                    cur_user=self.TEST_USER_LOGIN)
         Repository.lock(repo, User.get_by_username(self.TEST_USER_LOGIN).user_id)
@@ -529,7 +530,7 @@
             fixture.destroy_repo(repo_name)
 
     def test_api_get_locks_with_one_locked_repo_for_specific_user(self):
-        repo_name = 'api_delete_me'
+        repo_name = u'api_delete_me'
         repo = fixture.create_repo(repo_name, repo_type=self.REPO_TYPE,
                                    cur_user=self.TEST_USER_LOGIN)
         Repository.lock(repo, User.get_by_username(self.TEST_USER_LOGIN).user_id)
@@ -682,18 +683,19 @@
         expected = ret
         self._compare_error(id_, expected, given=response.body)
 
-    @parameterized.expand([('firstname', 'new_username'),
-                           ('lastname', 'new_username'),
-                           ('email', 'new_username'),
-                           ('admin', True),
-                           ('admin', False),
-                           ('extern_type', 'ldap'),
-                           ('extern_type', None),
-                           ('extern_name', 'test'),
-                           ('extern_name', None),
-                           ('active', False),
-                           ('active', True),
-                           ('password', 'newpass')
+    @parametrize('name,expected', [
+        ('firstname', 'new_username'),
+        ('lastname', 'new_username'),
+        ('email', 'new_username'),
+        ('admin', True),
+        ('admin', False),
+        ('extern_type', 'ldap'),
+        ('extern_type', None),
+        ('extern_name', 'test'),
+        ('extern_name', None),
+        ('active', False),
+        ('active', True),
+        ('password', 'newpass'),
     ])
     def test_api_update_user(self, name, expected):
         usr = User.get_by_username(self.TEST_USER_LOGIN)
@@ -766,7 +768,7 @@
         self._compare_error(id_, expected, given=response.body)
 
     def test_api_get_repo(self):
-        new_group = 'some_new_group'
+        new_group = u'some_new_group'
         make_user_group(new_group)
         RepoModel().grant_user_group_permission(repo=self.REPO,
                                                 group_name=new_group,
@@ -805,10 +807,10 @@
         self._compare_ok(id_, expected, given=response.body)
         fixture.destroy_user_group(new_group)
 
-    @parameterized.expand([
-        ('repository.admin',),
-        ('repository.write',),
-        ('repository.read',),
+    @parametrize('grant_perm', [
+        ('repository.admin'),
+        ('repository.write'),
+        ('repository.read'),
     ])
     def test_api_get_repo_by_non_admin(self, grant_perm):
         RepoModel().grant_user_permission(repo=self.REPO,
@@ -824,7 +826,7 @@
 
         members = []
         followers = []
-        self.assertEqual(2, len(repo.repo_to_perm))
+        assert 2 == len(repo.repo_to_perm)
         for user in repo.repo_to_perm:
             perm = user.permission.permission_name
             user_obj = user.user
@@ -877,7 +879,7 @@
         response = api_call(self, params)
 
         result = []
-        for repo in RepoModel().get_all():
+        for repo in Repository.query():
             result.append(repo.get_api_data())
         ret = jsonify(result)
 
@@ -896,9 +898,11 @@
         expected = ret
         self._compare_ok(id_, expected, given=response.body)
 
-    @parameterized.expand([('all', 'all'),
-                           ('dirs', 'dirs'),
-                           ('files', 'files'), ])
+    @parametrize('name,ret_type', [
+        ('all', 'all'),
+        ('dirs', 'dirs'),
+        ('files', 'files'),
+    ])
     def test_api_get_repo_nodes(self, name, ret_type):
         rev = 'tip'
         path = '/'
@@ -949,9 +953,11 @@
                     % (','.join(['files', 'dirs', 'all'])))
         self._compare_error(id_, expected, given=response.body)
 
-    @parameterized.expand([('all', 'all', 'repository.write'),
-                           ('dirs', 'dirs', 'repository.admin'),
-                           ('files', 'files', 'repository.read'), ])
+    @parametrize('name,ret_type,grant_perm', [
+        ('all', 'all', 'repository.write'),
+        ('dirs', 'dirs', 'repository.admin'),
+        ('files', 'files', 'repository.read'),
+    ])
     def test_api_get_repo_nodes_by_regular_user(self, name, ret_type, grant_perm):
         RepoModel().grant_user_permission(repo=self.REPO,
                                           user=self.TEST_USER_LOGIN,
@@ -975,7 +981,7 @@
             RepoModel().revoke_user_permission(self.REPO, self.TEST_USER_LOGIN)
 
     def test_api_create_repo(self):
-        repo_name = 'api-repo'
+        repo_name = u'api-repo'
         id_, params = _build_data(self.apikey, 'create_repo',
                                   repo_name=repo_name,
                                   owner=TEST_USER_ADMIN_LOGIN,
@@ -984,7 +990,7 @@
         response = api_call(self, params)
 
         repo = RepoModel().get_by_repo_name(repo_name)
-        self.assertNotEqual(repo, None)
+        assert repo != None
         ret = {
             'msg': 'Created new repository `%s`' % repo_name,
             'success': True,
@@ -995,7 +1001,7 @@
         fixture.destroy_repo(repo_name)
 
     def test_api_create_repo_and_repo_group(self):
-        repo_name = 'my_gr/api-repo'
+        repo_name = u'my_gr/api-repo'
         id_, params = _build_data(self.apikey, 'create_repo',
                                   repo_name=repo_name,
                                   owner=TEST_USER_ADMIN_LOGIN,
@@ -1003,7 +1009,7 @@
         response = api_call(self, params)
         print params
         repo = RepoModel().get_by_repo_name(repo_name)
-        self.assertNotEqual(repo, None)
+        assert repo != None
         ret = {
             'msg': 'Created new repository `%s`' % repo_name,
             'success': True,
@@ -1012,11 +1018,11 @@
         expected = ret
         self._compare_ok(id_, expected, given=response.body)
         fixture.destroy_repo(repo_name)
-        fixture.destroy_repo_group('my_gr')
+        fixture.destroy_repo_group(u'my_gr')
 
     def test_api_create_repo_in_repo_group_without_permission(self):
-        repo_group_name = '%s/api-repo-repo' % TEST_REPO_GROUP
-        repo_name = '%s/api-repo' % repo_group_name
+        repo_group_name = u'%s/api-repo-repo' % TEST_REPO_GROUP
+        repo_name = u'%s/api-repo' % repo_group_name
 
         rg = fixture.create_repo_group(repo_group_name)
         Session().commit()
@@ -1048,7 +1054,7 @@
         fixture.destroy_repo_group(repo_group_name)
 
     def test_api_create_repo_unknown_owner(self):
-        repo_name = 'api-repo'
+        repo_name = u'api-repo'
         owner = 'i-dont-exist'
         id_, params = _build_data(self.apikey, 'create_repo',
                                   repo_name=repo_name,
@@ -1060,7 +1066,7 @@
         self._compare_error(id_, expected, given=response.body)
 
     def test_api_create_repo_dont_specify_owner(self):
-        repo_name = 'api-repo'
+        repo_name = u'api-repo'
         owner = 'i-dont-exist'
         id_, params = _build_data(self.apikey, 'create_repo',
                                   repo_name=repo_name,
@@ -1069,7 +1075,7 @@
         response = api_call(self, params)
 
         repo = RepoModel().get_by_repo_name(repo_name)
-        self.assertNotEqual(repo, None)
+        assert repo != None
         ret = {
             'msg': 'Created new repository `%s`' % repo_name,
             'success': True,
@@ -1080,7 +1086,7 @@
         fixture.destroy_repo(repo_name)
 
     def test_api_create_repo_by_non_admin(self):
-        repo_name = 'api-repo'
+        repo_name = u'api-repo'
         owner = 'i-dont-exist'
         id_, params = _build_data(self.apikey_regular, 'create_repo',
                                   repo_name=repo_name,
@@ -1089,7 +1095,7 @@
         response = api_call(self, params)
 
         repo = RepoModel().get_by_repo_name(repo_name)
-        self.assertNotEqual(repo, None)
+        assert repo != None
         ret = {
             'msg': 'Created new repository `%s`' % repo_name,
             'success': True,
@@ -1100,7 +1106,7 @@
         fixture.destroy_repo(repo_name)
 
     def test_api_create_repo_by_non_admin_specify_owner(self):
-        repo_name = 'api-repo'
+        repo_name = u'api-repo'
         owner = 'i-dont-exist'
         id_, params = _build_data(self.apikey_regular, 'create_repo',
                                   repo_name=repo_name,
@@ -1124,7 +1130,7 @@
 
     @mock.patch.object(RepoModel, 'create', crash)
     def test_api_create_repo_exception_occurred(self):
-        repo_name = 'api-repo'
+        repo_name = u'api-repo'
         id_, params = _build_data(self.apikey, 'create_repo',
                                   repo_name=repo_name,
                                   owner=TEST_USER_ADMIN_LOGIN,
@@ -1133,22 +1139,20 @@
         expected = 'failed to create repository `%s`' % repo_name
         self._compare_error(id_, expected, given=response.body)
 
-    @parameterized.expand([
+    @parametrize('changing_attr,updates', [
         ('owner', {'owner': TEST_USER_REGULAR_LOGIN}),
-        ('description', {'description': 'new description'}),
-        ('active', {'active': True}),
-        ('active', {'active': False}),
+        ('description', {'description': u'new description'}),
         ('clone_uri', {'clone_uri': 'http://example.com/repo'}),
         ('clone_uri', {'clone_uri': None}),
         ('landing_rev', {'landing_rev': 'branch:master'}),
         ('enable_statistics', {'enable_statistics': True}),
         ('enable_locking', {'enable_locking': True}),
         ('enable_downloads', {'enable_downloads': True}),
-        ('name', {'name': 'new_repo_name'}),
-        ('repo_group', {'group': 'test_group_for_update'}),
+        ('name', {'name': u'new_repo_name'}),
+        ('repo_group', {'group': u'test_group_for_update'}),
     ])
     def test_api_update_repo(self, changing_attr, updates):
-        repo_name = 'api_update_me'
+        repo_name = u'api_update_me'
         repo = fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
         if changing_attr == 'repo_group':
             fixture.create_repo_group(updates['group'])
@@ -1159,7 +1163,7 @@
         if changing_attr == 'name':
             repo_name = updates['name']
         if changing_attr == 'repo_group':
-            repo_name = '/'.join([updates['group'], repo_name])
+            repo_name = u'/'.join([updates['group'], repo_name])
         try:
             expected = {
                 'msg': 'updated repo ID:%s %s' % (repo.repo_id, repo_name),
@@ -1171,11 +1175,9 @@
             if changing_attr == 'repo_group':
                 fixture.destroy_repo_group(updates['group'])
 
-    @parameterized.expand([
+    @parametrize('changing_attr,updates', [
         ('owner', {'owner': TEST_USER_REGULAR_LOGIN}),
         ('description', {'description': u'new description'}),
-        ('active', {'active': True}),
-        ('active', {'active': False}),
         ('clone_uri', {'clone_uri': 'http://example.com/repo'}),
         ('clone_uri', {'clone_uri': None}),
         ('landing_rev', {'landing_rev': 'branch:master'}),
@@ -1213,7 +1215,7 @@
         fixture.destroy_repo_group(group_name)
 
     def test_api_update_repo_repo_group_does_not_exist(self):
-        repo_name = 'admin_owned'
+        repo_name = u'admin_owned'
         fixture.create_repo(repo_name)
         updates = {'group': 'test_group_for_update'}
         id_, params = _build_data(self.apikey, 'update_repo',
@@ -1226,9 +1228,9 @@
             fixture.destroy_repo(repo_name)
 
     def test_api_update_repo_regular_user_not_allowed(self):
-        repo_name = 'admin_owned'
+        repo_name = u'admin_owned'
         fixture.create_repo(repo_name)
-        updates = {'active': False}
+        updates = {'description': 'something else'}
         id_, params = _build_data(self.apikey_regular, 'update_repo',
                                   repoid=repo_name, **updates)
         response = api_call(self, params)
@@ -1240,7 +1242,7 @@
 
     @mock.patch.object(RepoModel, 'update', crash)
     def test_api_update_repo_exception_occurred(self):
-        repo_name = 'api_update_me'
+        repo_name = u'api_update_me'
         fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
         id_, params = _build_data(self.apikey, 'update_repo',
                                   repoid=repo_name, owner=TEST_USER_ADMIN_LOGIN,)
@@ -1252,8 +1254,8 @@
             fixture.destroy_repo(repo_name)
 
     def test_api_update_repo_regular_user_change_repo_name(self):
-        repo_name = 'admin_owned'
-        new_repo_name = 'new_repo_name'
+        repo_name = u'admin_owned'
+        new_repo_name = u'new_repo_name'
         fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
         RepoModel().grant_user_permission(repo=repo_name,
                                           user=self.TEST_USER_LOGIN,
@@ -1272,8 +1274,8 @@
             fixture.destroy_repo(new_repo_name)
 
     def test_api_update_repo_regular_user_change_repo_name_allowed(self):
-        repo_name = 'admin_owned'
-        new_repo_name = 'new_repo_name'
+        repo_name = u'admin_owned'
+        new_repo_name = u'new_repo_name'
         repo = fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
         RepoModel().grant_user_permission(repo=repo_name,
                                           user=self.TEST_USER_LOGIN,
@@ -1295,7 +1297,7 @@
             fixture.destroy_repo(new_repo_name)
 
     def test_api_update_repo_regular_user_change_owner(self):
-        repo_name = 'admin_owned'
+        repo_name = u'admin_owned'
         fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
         RepoModel().grant_user_permission(repo=repo_name,
                                           user=self.TEST_USER_LOGIN,
@@ -1311,7 +1313,7 @@
             fixture.destroy_repo(repo_name)
 
     def test_api_delete_repo(self):
-        repo_name = 'api_delete_me'
+        repo_name = u'api_delete_me'
         fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
 
         id_, params = _build_data(self.apikey, 'delete_repo',
@@ -1329,7 +1331,7 @@
             fixture.destroy_repo(repo_name)
 
     def test_api_delete_repo_by_non_admin(self):
-        repo_name = 'api_delete_me'
+        repo_name = u'api_delete_me'
         fixture.create_repo(repo_name, repo_type=self.REPO_TYPE,
                             cur_user=self.TEST_USER_LOGIN)
         id_, params = _build_data(self.apikey_regular, 'delete_repo',
@@ -1347,7 +1349,7 @@
             fixture.destroy_repo(repo_name)
 
     def test_api_delete_repo_by_non_admin_no_permission(self):
-        repo_name = 'api_delete_me'
+        repo_name = u'api_delete_me'
         fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
         try:
             id_, params = _build_data(self.apikey_regular, 'delete_repo',
@@ -1359,7 +1361,7 @@
             fixture.destroy_repo(repo_name)
 
     def test_api_delete_repo_exception_occurred(self):
-        repo_name = 'api_delete_me'
+        repo_name = u'api_delete_me'
         fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
         try:
             with mock.patch.object(RepoModel, 'delete', crash):
@@ -1373,7 +1375,7 @@
             fixture.destroy_repo(repo_name)
 
     def test_api_fork_repo(self):
-        fork_name = 'api-repo-fork'
+        fork_name = u'api-repo-fork'
         id_, params = _build_data(self.apikey, 'fork_repo',
                                   repoid=self.REPO,
                                   fork_name=fork_name,
@@ -1391,9 +1393,9 @@
         self._compare_ok(id_, expected, given=response.body)
         fixture.destroy_repo(fork_name)
 
-    @parameterized.expand([
-        (u'api-repo-fork',),
-        (u'%s/api-repo-fork' % TEST_REPO_GROUP,),
+    @parametrize('fork_name', [
+        u'api-repo-fork',
+        u'%s/api-repo-fork' % TEST_REPO_GROUP,
     ])
     def test_api_fork_repo_non_admin(self, fork_name):
         id_, params = _build_data(self.apikey_regular, 'fork_repo',
@@ -1413,7 +1415,7 @@
         fixture.destroy_repo(fork_name)
 
     def test_api_fork_repo_non_admin_specify_owner(self):
-        fork_name = 'api-repo-fork'
+        fork_name = u'api-repo-fork'
         id_, params = _build_data(self.apikey_regular, 'fork_repo',
                                   repoid=self.REPO,
                                   fork_name=fork_name,
@@ -1428,7 +1430,7 @@
         RepoModel().grant_user_permission(repo=self.REPO,
                                           user=self.TEST_USER_LOGIN,
                                           perm='repository.none')
-        fork_name = 'api-repo-fork'
+        fork_name = u'api-repo-fork'
         id_, params = _build_data(self.apikey_regular, 'fork_repo',
                                   repoid=self.REPO,
                                   fork_name=fork_name,
@@ -1438,11 +1440,13 @@
         self._compare_error(id_, expected, given=response.body)
         fixture.destroy_repo(fork_name)
 
-    @parameterized.expand([('read', 'repository.read'),
-                           ('write', 'repository.write'),
-                           ('admin', 'repository.admin')])
+    @parametrize('name,perm', [
+        ('read', 'repository.read'),
+        ('write', 'repository.write'),
+        ('admin', 'repository.admin'),
+    ])
     def test_api_fork_repo_non_admin_no_create_repo_permission(self, name, perm):
-        fork_name = 'api-repo-fork'
+        fork_name = u'api-repo-fork'
         # regardless of base repository permission, forking is disallowed
         # when repository creation is disabled
         RepoModel().grant_user_permission(repo=self.REPO,
@@ -1460,7 +1464,7 @@
         fixture.destroy_repo(fork_name)
 
     def test_api_fork_repo_unknown_owner(self):
-        fork_name = 'api-repo-fork'
+        fork_name = u'api-repo-fork'
         owner = 'i-dont-exist'
         id_, params = _build_data(self.apikey, 'fork_repo',
                                   repoid=self.REPO,
@@ -1472,11 +1476,11 @@
         self._compare_error(id_, expected, given=response.body)
 
     def test_api_fork_repo_fork_exists(self):
-        fork_name = 'api-repo-fork'
+        fork_name = u'api-repo-fork'
         fixture.create_fork(self.REPO, fork_name)
 
         try:
-            fork_name = 'api-repo-fork'
+            fork_name = u'api-repo-fork'
 
             id_, params = _build_data(self.apikey, 'fork_repo',
                                       repoid=self.REPO,
@@ -1505,7 +1509,7 @@
 
     @mock.patch.object(RepoModel, 'create_fork', crash)
     def test_api_fork_repo_exception_occurred(self):
-        fork_name = 'api-repo-fork'
+        fork_name = u'api-repo-fork'
         id_, params = _build_data(self.apikey, 'fork_repo',
                                   repoid=self.REPO,
                                   fork_name=fork_name,
@@ -1534,15 +1538,15 @@
         self._compare_ok(id_, expected, given=response.body)
 
     def test_api_get_user_groups(self):
-        gr_name = 'test_user_group2'
+        gr_name = u'test_user_group2'
         make_user_group(gr_name)
 
-        id_, params = _build_data(self.apikey, 'get_user_groups', )
-        response = api_call(self, params)
+        try:
+            id_, params = _build_data(self.apikey, 'get_user_groups', )
+            response = api_call(self, params)
 
-        try:
             expected = []
-            for gr_name in [TEST_USER_GROUP, 'test_user_group2']:
+            for gr_name in [TEST_USER_GROUP, u'test_user_group2']:
                 user_group = UserGroupModel().get_group(gr_name)
                 ret = user_group.get_api_data()
                 expected.append(ret)
@@ -1551,7 +1555,7 @@
             fixture.destroy_user_group(gr_name)
 
     def test_api_create_user_group(self):
-        group_name = 'some_new_group'
+        group_name = u'some_new_group'
         id_, params = _build_data(self.apikey, 'create_user_group',
                                   group_name=group_name)
         response = api_call(self, params)
@@ -1577,7 +1581,7 @@
 
     @mock.patch.object(UserGroupModel, 'create', crash)
     def test_api_get_user_group_exception_occurred(self):
-        group_name = 'exception_happens'
+        group_name = u'exception_happens'
         id_, params = _build_data(self.apikey, 'create_user_group',
                                   group_name=group_name)
         response = api_call(self, params)
@@ -1585,18 +1589,20 @@
         expected = 'failed to create group `%s`' % group_name
         self._compare_error(id_, expected, given=response.body)
 
-    @parameterized.expand([('group_name', {'group_name': 'new_group_name'}),
-                           ('group_name', {'group_name': 'test_group_for_update'}),
-                           ('owner', {'owner': TEST_USER_REGULAR_LOGIN}),
-                           ('active', {'active': False}),
-                           ('active', {'active': True})])
+    @parametrize('changing_attr,updates', [
+        ('group_name', {'group_name': u'new_group_name'}),
+        ('group_name', {'group_name': u'test_group_for_update'}),
+        ('owner', {'owner': TEST_USER_REGULAR_LOGIN}),
+        ('active', {'active': False}),
+        ('active', {'active': True}),
+    ])
     def test_api_update_user_group(self, changing_attr, updates):
-        gr_name = 'test_group_for_update'
+        gr_name = u'test_group_for_update'
         user_group = fixture.create_user_group(gr_name)
-        id_, params = _build_data(self.apikey, 'update_user_group',
-                                  usergroupid=gr_name, **updates)
-        response = api_call(self, params)
         try:
+            id_, params = _build_data(self.apikey, 'update_user_group',
+                                      usergroupid=gr_name, **updates)
+            response = api_call(self, params)
             expected = {
                'msg': 'updated user group ID:%s %s' % (user_group.users_group_id,
                                                      user_group.users_group_name),
@@ -1611,25 +1617,25 @@
 
     @mock.patch.object(UserGroupModel, 'update', crash)
     def test_api_update_user_group_exception_occurred(self):
-        gr_name = 'test_group'
+        gr_name = u'test_group'
         fixture.create_user_group(gr_name)
-        id_, params = _build_data(self.apikey, 'update_user_group',
-                                  usergroupid=gr_name)
-        response = api_call(self, params)
         try:
+            id_, params = _build_data(self.apikey, 'update_user_group',
+                                      usergroupid=gr_name)
+            response = api_call(self, params)
             expected = 'failed to update user group `%s`' % gr_name
             self._compare_error(id_, expected, given=response.body)
         finally:
             fixture.destroy_user_group(gr_name)
 
     def test_api_add_user_to_user_group(self):
-        gr_name = 'test_group'
+        gr_name = u'test_group'
         fixture.create_user_group(gr_name)
-        id_, params = _build_data(self.apikey, 'add_user_to_user_group',
-                                  usergroupid=gr_name,
-                                  userid=TEST_USER_ADMIN_LOGIN)
-        response = api_call(self, params)
         try:
+            id_, params = _build_data(self.apikey, 'add_user_to_user_group',
+                                      usergroupid=gr_name,
+                                      userid=TEST_USER_ADMIN_LOGIN)
+            response = api_call(self, params)
             expected = {
             'msg': 'added member `%s` to user group `%s`' % (
                     TEST_USER_ADMIN_LOGIN, gr_name),
@@ -1650,30 +1656,28 @@
 
     @mock.patch.object(UserGroupModel, 'add_user_to_group', crash)
     def test_api_add_user_to_user_group_exception_occurred(self):
-        gr_name = 'test_group'
+        gr_name = u'test_group'
         fixture.create_user_group(gr_name)
-        id_, params = _build_data(self.apikey, 'add_user_to_user_group',
-                                  usergroupid=gr_name,
-                                  userid=TEST_USER_ADMIN_LOGIN)
-        response = api_call(self, params)
-
         try:
+            id_, params = _build_data(self.apikey, 'add_user_to_user_group',
+                                      usergroupid=gr_name,
+                                      userid=TEST_USER_ADMIN_LOGIN)
+            response = api_call(self, params)
             expected = 'failed to add member to user group `%s`' % gr_name
             self._compare_error(id_, expected, given=response.body)
         finally:
             fixture.destroy_user_group(gr_name)
 
     def test_api_remove_user_from_user_group(self):
-        gr_name = 'test_group_3'
+        gr_name = u'test_group_3'
         gr = fixture.create_user_group(gr_name)
         UserGroupModel().add_user_to_group(gr, user=TEST_USER_ADMIN_LOGIN)
         Session().commit()
-        id_, params = _build_data(self.apikey, 'remove_user_from_user_group',
-                                  usergroupid=gr_name,
-                                  userid=TEST_USER_ADMIN_LOGIN)
-        response = api_call(self, params)
-
         try:
+            id_, params = _build_data(self.apikey, 'remove_user_from_user_group',
+                                      usergroupid=gr_name,
+                                      userid=TEST_USER_ADMIN_LOGIN)
+            response = api_call(self, params)
             expected = {
                 'msg': 'removed member `%s` from user group `%s`' % (
                     TEST_USER_ADMIN_LOGIN, gr_name
@@ -1685,30 +1689,28 @@
 
     @mock.patch.object(UserGroupModel, 'remove_user_from_group', crash)
     def test_api_remove_user_from_user_group_exception_occurred(self):
-        gr_name = 'test_group_3'
+        gr_name = u'test_group_3'
         gr = fixture.create_user_group(gr_name)
         UserGroupModel().add_user_to_group(gr, user=TEST_USER_ADMIN_LOGIN)
         Session().commit()
-        id_, params = _build_data(self.apikey, 'remove_user_from_user_group',
-                                  usergroupid=gr_name,
-                                  userid=TEST_USER_ADMIN_LOGIN)
-        response = api_call(self, params)
         try:
+            id_, params = _build_data(self.apikey, 'remove_user_from_user_group',
+                                      usergroupid=gr_name,
+                                      userid=TEST_USER_ADMIN_LOGIN)
+            response = api_call(self, params)
             expected = 'failed to remove member from user group `%s`' % gr_name
             self._compare_error(id_, expected, given=response.body)
         finally:
             fixture.destroy_user_group(gr_name)
 
     def test_api_delete_user_group(self):
-        gr_name = 'test_group'
+        gr_name = u'test_group'
         ugroup = fixture.create_user_group(gr_name)
         gr_id = ugroup.users_group_id
-        id_, params = _build_data(self.apikey, 'delete_user_group',
-                                  usergroupid=gr_name,
-                                  userid=TEST_USER_ADMIN_LOGIN)
-        response = api_call(self, params)
-
         try:
+            id_, params = _build_data(self.apikey, 'delete_user_group',
+                                      usergroupid=gr_name)
+            response = api_call(self, params)
             expected = {
                 'user_group': None,
                 'msg': 'deleted user group ID:%s %s' % (gr_id, gr_name)
@@ -1719,19 +1721,17 @@
                 fixture.destroy_user_group(gr_name)
 
     def test_api_delete_user_group_that_is_assigned(self):
-        gr_name = 'test_group'
+        gr_name = u'test_group'
         ugroup = fixture.create_user_group(gr_name)
         gr_id = ugroup.users_group_id
 
         ugr_to_perm = RepoModel().grant_user_group_permission(self.REPO, gr_name, 'repository.write')
         msg = 'User Group assigned to %s' % ugr_to_perm.repository.repo_name
 
-        id_, params = _build_data(self.apikey, 'delete_user_group',
-                                  usergroupid=gr_name,
-                                  userid=TEST_USER_ADMIN_LOGIN)
-        response = api_call(self, params)
-
         try:
+            id_, params = _build_data(self.apikey, 'delete_user_group',
+                                      usergroupid=gr_name)
+            response = api_call(self, params)
             expected = msg
             self._compare_error(id_, expected, given=response.body)
         finally:
@@ -1739,12 +1739,11 @@
                 fixture.destroy_user_group(gr_name)
 
     def test_api_delete_user_group_exception_occurred(self):
-        gr_name = 'test_group'
+        gr_name = u'test_group'
         ugroup = fixture.create_user_group(gr_name)
         gr_id = ugroup.users_group_id
         id_, params = _build_data(self.apikey, 'delete_user_group',
-                                  usergroupid=gr_name,
-                                  userid=TEST_USER_ADMIN_LOGIN)
+                                  usergroupid=gr_name)
 
         try:
             with mock.patch.object(UserGroupModel, 'delete', crash):
@@ -1754,10 +1753,12 @@
         finally:
             fixture.destroy_user_group(gr_name)
 
-    @parameterized.expand([('none', 'repository.none'),
-                           ('read', 'repository.read'),
-                           ('write', 'repository.write'),
-                           ('admin', 'repository.admin')])
+    @parametrize('name,perm', [
+        ('none', 'repository.none'),
+        ('read', 'repository.read'),
+        ('write', 'repository.write'),
+        ('admin', 'repository.admin'),
+    ])
     def test_api_grant_user_permission(self, name, perm):
         id_, params = _build_data(self.apikey,
                                   'grant_user_permission',
@@ -1830,10 +1831,12 @@
         )
         self._compare_error(id_, expected, given=response.body)
 
-    @parameterized.expand([('none', 'repository.none'),
-                           ('read', 'repository.read'),
-                           ('write', 'repository.write'),
-                           ('admin', 'repository.admin')])
+    @parametrize('name,perm', [
+        ('none', 'repository.none'),
+        ('read', 'repository.read'),
+        ('write', 'repository.write'),
+        ('admin', 'repository.admin'),
+    ])
     def test_api_grant_user_group_permission(self, name, perm):
         id_, params = _build_data(self.apikey,
                                   'grant_user_group_permission',
@@ -1910,7 +1913,7 @@
         )
         self._compare_error(id_, expected, given=response.body)
 
-    @parameterized.expand([
+    @parametrize('name,perm,apply_to_children', [
         ('none', 'group.none', 'none'),
         ('read', 'group.read', 'none'),
         ('write', 'group.write', 'none'),
@@ -1948,7 +1951,7 @@
         expected = ret
         self._compare_ok(id_, expected, given=response.body)
 
-    @parameterized.expand([
+    @parametrize('name,perm,apply_to_children,grant_admin,access_ok', [
         ('none_fails', 'group.none', 'none', False, False),
         ('read_fails', 'group.read', 'none', False, False),
         ('write_fails', 'group.write', 'none', False, False),
@@ -2014,7 +2017,7 @@
         )
         self._compare_error(id_, expected, given=response.body)
 
-    @parameterized.expand([
+    @parametrize('name,apply_to_children', [
         ('none', 'none'),
         ('all', 'all'),
         ('repos', 'repos'),
@@ -2041,7 +2044,7 @@
         }
         self._compare_ok(id_, expected, given=response.body)
 
-    @parameterized.expand([
+    @parametrize('name,apply_to_children,grant_admin,access_ok', [
         ('none', 'none', False, False),
         ('all', 'all', False, False),
         ('repos', 'repos', False, False),
@@ -2097,7 +2100,7 @@
         )
         self._compare_error(id_, expected, given=response.body)
 
-    @parameterized.expand([
+    @parametrize('name,perm,apply_to_children', [
         ('none', 'group.none', 'none'),
         ('read', 'group.read', 'none'),
         ('write', 'group.write', 'none'),
@@ -2136,7 +2139,7 @@
         expected = ret
         self._compare_ok(id_, expected, given=response.body)
 
-    @parameterized.expand([
+    @parametrize('name,perm,apply_to_children,grant_admin,access_ok', [
         ('none_fails', 'group.none', 'none', False, False),
         ('read_fails', 'group.read', 'none', False, False),
         ('write_fails', 'group.write', 'none', False, False),
@@ -2203,7 +2206,7 @@
         )
         self._compare_error(id_, expected, given=response.body)
 
-    @parameterized.expand([
+    @parametrize('name,apply_to_children', [
         ('none', 'none'),
         ('all', 'all'),
         ('repos', 'repos'),
@@ -2229,7 +2232,7 @@
         }
         self._compare_ok(id_, expected, given=response.body)
 
-    @parameterized.expand([
+    @parametrize('name,apply_to_children,grant_admin,access_ok', [
         ('none', 'none', False, False),
         ('all', 'all', False, False),
         ('repos', 'repos', False, False),
@@ -2329,7 +2332,7 @@
         id_, params = _build_data(self.apikey, 'get_gists')
         response = api_call(self, params)
         expected = response.json
-        self.assertEqual(len(response.json['result']), 2)
+        assert len(response.json['result']) == 2
         #self._compare_ok(id_, expected, given=response.body)
 
     def test_api_get_gists_regular_user(self):
@@ -2345,7 +2348,7 @@
         id_, params = _build_data(self.apikey_regular, 'get_gists')
         response = api_call(self, params)
         expected = response.json
-        self.assertEqual(len(response.json['result']), 3)
+        assert len(response.json['result']) == 3
         #self._compare_ok(id_, expected, given=response.body)
 
     def test_api_get_gists_only_for_regular_user(self):
@@ -2362,7 +2365,7 @@
                                   userid=self.TEST_USER_LOGIN)
         response = api_call(self, params)
         expected = response.json
-        self.assertEqual(len(response.json['result']), 3)
+        assert len(response.json['result']) == 3
         #self._compare_ok(id_, expected, given=response.body)
 
     def test_api_get_gists_regular_user_with_different_userid(self):
--- a/kallithea/tests/api/test_api_git.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/api/test_api_git.py	Fri Nov 18 01:11:13 2016 +0100
@@ -12,7 +12,7 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-from kallithea.tests import TestController, GIT_REPO
+from kallithea.tests.base import TestController, GIT_REPO
 from kallithea.tests.api.api_base import _BaseTestApi
 
 
--- a/kallithea/tests/api/test_api_hg.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/api/test_api_hg.py	Fri Nov 18 01:11:13 2016 +0100
@@ -12,7 +12,7 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-from kallithea.tests import TestController, HG_REPO
+from kallithea.tests.base import TestController, HG_REPO
 from kallithea.tests.api.api_base import _BaseTestApi
 
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/tests/base.py	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,221 @@
+# -*- coding: utf-8 -*-
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+import datetime
+import logging
+import os
+import pytest
+import re
+import tempfile
+import time
+
+import pylons
+from pylons import config, url
+from pylons.i18n.translation import _get_translator
+from pylons.util import ContextObj
+from routes.util import URLGenerator
+from webtest import TestApp
+
+from kallithea import is_windows
+from kallithea.model.db import Notification, User, UserNotification
+from kallithea.model.meta import Session
+from kallithea.lib.utils2 import safe_str
+
+os.environ['TZ'] = 'UTC'
+if not is_windows:
+    time.tzset()
+
+log = logging.getLogger(__name__)
+
+skipif = pytest.mark.skipif
+parametrize = pytest.mark.parametrize
+
+__all__ = [
+    'skipif', 'parametrize', 'environ', 'url', 'TestController',
+    'ldap_lib_installed', 'pam_lib_installed', 'invalidate_all_caches',
+    'TESTS_TMP_PATH', 'HG_REPO', 'GIT_REPO', 'NEW_HG_REPO', 'NEW_GIT_REPO',
+    'HG_FORK', 'GIT_FORK', 'TEST_USER_ADMIN_LOGIN', 'TEST_USER_ADMIN_PASS',
+    'TEST_USER_ADMIN_EMAIL', 'TEST_USER_REGULAR_LOGIN', 'TEST_USER_REGULAR_PASS',
+    'TEST_USER_REGULAR_EMAIL', 'TEST_USER_REGULAR2_LOGIN',
+    'TEST_USER_REGULAR2_PASS', 'TEST_USER_REGULAR2_EMAIL', 'TEST_HG_REPO',
+    'TEST_HG_REPO_CLONE', 'TEST_HG_REPO_PULL', 'TEST_GIT_REPO',
+    'TEST_GIT_REPO_CLONE', 'TEST_GIT_REPO_PULL', 'HG_REMOTE_REPO',
+    'GIT_REMOTE_REPO', 'SCM_TESTS',
+]
+
+# Invoke websetup with the current config file
+# SetupCommand('setup-app').run([config_file])
+
+environ = {}
+
+#SOME GLOBALS FOR TESTS
+
+TESTS_TMP_PATH = os.path.join(tempfile.gettempdir(), 'rc_test_%s' % tempfile._RandomNameSequence().next())
+TEST_USER_ADMIN_LOGIN = 'test_admin'
+TEST_USER_ADMIN_PASS = 'test12'
+TEST_USER_ADMIN_EMAIL = 'test_admin@example.com'
+
+TEST_USER_REGULAR_LOGIN = 'test_regular'
+TEST_USER_REGULAR_PASS = 'test12'
+TEST_USER_REGULAR_EMAIL = 'test_regular@example.com'
+
+TEST_USER_REGULAR2_LOGIN = 'test_regular2'
+TEST_USER_REGULAR2_PASS = 'test12'
+TEST_USER_REGULAR2_EMAIL = 'test_regular2@example.com'
+
+HG_REPO = u'vcs_test_hg'
+GIT_REPO = u'vcs_test_git'
+
+NEW_HG_REPO = u'vcs_test_hg_new'
+NEW_GIT_REPO = u'vcs_test_git_new'
+
+HG_FORK = u'vcs_test_hg_fork'
+GIT_FORK = u'vcs_test_git_fork'
+
+## VCS
+SCM_TESTS = ['hg', 'git']
+uniq_suffix = str(int(time.mktime(datetime.datetime.now().timetuple())))
+
+GIT_REMOTE_REPO = 'git://github.com/codeinn/vcs.git'
+
+TEST_GIT_REPO = os.path.join(TESTS_TMP_PATH, GIT_REPO)
+TEST_GIT_REPO_CLONE = os.path.join(TESTS_TMP_PATH, 'vcsgitclone%s' % uniq_suffix)
+TEST_GIT_REPO_PULL = os.path.join(TESTS_TMP_PATH, 'vcsgitpull%s' % uniq_suffix)
+
+
+HG_REMOTE_REPO = 'http://bitbucket.org/marcinkuzminski/vcs'
+
+TEST_HG_REPO = os.path.join(TESTS_TMP_PATH, HG_REPO)
+TEST_HG_REPO_CLONE = os.path.join(TESTS_TMP_PATH, 'vcshgclone%s' % uniq_suffix)
+TEST_HG_REPO_PULL = os.path.join(TESTS_TMP_PATH, 'vcshgpull%s' % uniq_suffix)
+
+TEST_DIR = tempfile.gettempdir()
+TEST_REPO_PREFIX = 'vcs-test'
+
+# cached repos if any !
+# comment out to get some other repos from bb or github
+GIT_REMOTE_REPO = os.path.join(TESTS_TMP_PATH, GIT_REPO)
+HG_REMOTE_REPO = os.path.join(TESTS_TMP_PATH, HG_REPO)
+
+#skip ldap tests if LDAP lib is not installed
+ldap_lib_installed = False
+try:
+    import ldap
+    ldap.API_VERSION
+    ldap_lib_installed = True
+except ImportError:
+    # means that python-ldap is not installed
+    pass
+
+try:
+    import pam
+    pam.PAM_TEXT_INFO
+    pam_lib_installed = True
+except ImportError:
+    pam_lib_installed = False
+
+def invalidate_all_caches():
+    """Invalidate all beaker caches currently configured.
+    Useful when manipulating IP permissions in a test and changes need to take
+    effect immediately.
+    Note: Any use of this function is probably a workaround - it should be
+    replaced with a more specific cache invalidation in code or test."""
+    from beaker.cache import cache_managers
+    for cache in cache_managers.values():
+        cache.clear()
+
+class NullHandler(logging.Handler):
+    def emit(self, record):
+        pass
+
+class TestController(object):
+    """Pytest-style test controller"""
+
+    # Note: pytest base classes cannot have an __init__ method
+
+    @pytest.fixture(autouse=True)
+    def app_fixture(self):
+        self.wsgiapp = pylons.test.pylonsapp
+        self.init_stack(self.wsgiapp.config)
+        self.app = TestApp(self.wsgiapp)
+        self.maxDiff = None
+        self.index_location = config['app_conf']['index_dir']
+        return self.app
+
+    def init_stack(self, config=None):
+        if not config:
+            config = pylons.test.pylonsapp.config
+        url._push_object(URLGenerator(config['routes.map'], environ))
+        pylons.app_globals._push_object(config['pylons.app_globals'])
+        pylons.config._push_object(config)
+        pylons.tmpl_context._push_object(ContextObj())
+        # Initialize a translator for tests that utilize i18n
+        translator = _get_translator(pylons.config.get('lang'))
+        pylons.translator._push_object(translator)
+        h = NullHandler()
+        logging.getLogger("kallithea").addHandler(h)
+
+    def remove_all_notifications(self):
+        # query().delete() does not (by default) trigger cascades
+        # ( http://docs.sqlalchemy.org/en/rel_0_7/orm/collections.html#passive-deletes )
+        # so delete the UserNotification first to ensure referential integrity.
+        UserNotification.query().delete()
+
+        Notification.query().delete()
+        Session().commit()
+
+    def log_user(self, username=TEST_USER_ADMIN_LOGIN,
+                 password=TEST_USER_ADMIN_PASS):
+        self._logged_username = username
+        response = self.app.post(url(controller='login', action='index'),
+                                 {'username': username,
+                                  'password': password})
+
+        if 'Invalid username or password' in response.body:
+            pytest.fail('could not login using %s %s' % (username, password))
+
+        assert response.status == '302 Found'
+        self.assert_authenticated_user(response, username)
+
+        response = response.follow()
+        return response.session['authuser']
+
+    def _get_logged_user(self):
+        return User.get_by_username(self._logged_username)
+
+    def assert_authenticated_user(self, response, expected_username):
+        cookie = response.session.get('authuser')
+        user = cookie and cookie.get('user_id')
+        user = user and User.get(user)
+        user = user and user.username
+        assert user == expected_username
+
+    def authentication_token(self):
+        return self.app.get(url('authentication_token')).body
+
+    def checkSessionFlash(self, response, msg=None, skip=0, _matcher=lambda msg, m: msg in m):
+        if 'flash' not in response.session:
+            pytest.fail(safe_str(u'msg `%s` not found - session has no flash:\n%s' % (msg, response)))
+        try:
+            level, m = response.session['flash'][-1 - skip]
+            if _matcher(msg, m):
+                return
+        except IndexError:
+            pass
+        pytest.fail(safe_str(u'msg `%s` not found in session flash (skipping %s): %s' %
+                           (msg, skip,
+                            ', '.join('`%s`' % m for level, m in response.session['flash']))))
+
+    def checkSessionFlashRegex(self, response, regex, skip=0):
+        self.checkSessionFlash(response, regex, skip=skip, _matcher=re.search)
--- a/kallithea/tests/conftest.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/conftest.py	Fri Nov 18 01:11:13 2016 +0100
@@ -6,6 +6,11 @@
 from paste.deploy import loadapp
 import pylons.test
 from pylons.i18n.translation import _get_translator
+import pytest
+from kallithea.model.user import UserModel
+from kallithea.model.meta import Session
+from kallithea.model.db import Setting, User, UserIpMap
+from kallithea.tests.base import invalidate_all_caches, TEST_USER_REGULAR_LOGIN
 
 
 def pytest_configure():
@@ -32,3 +37,69 @@
     pylons.translator._push_object(translator)
 
     return pylons.test.pylonsapp
+
+
+@pytest.yield_fixture
+def create_test_user():
+    """Provide users that automatically disappear after test is over."""
+    test_user_ids = []
+    def _create_test_user(user_form):
+        user = UserModel().create(user_form)
+        test_user_ids.append(user.user_id)
+        return user
+    yield _create_test_user
+    for user_id in test_user_ids:
+        UserModel().delete(user_id)
+    Session().commit()
+
+
+def _set_settings(*kvtseq):
+    session = Session()
+    for kvt in kvtseq:
+        assert len(kvt) in (2, 3)
+        k = kvt[0]
+        v = kvt[1]
+        t = kvt[2] if len(kvt) == 3 else 'unicode'
+        Setting.create_or_update(k, v, t)
+    session.commit()
+
+
+@pytest.yield_fixture
+def set_test_settings():
+    """Restore settings after test is over."""
+    # Save settings.
+    settings_snapshot = [
+        (s.app_settings_name, s.app_settings_value, s.app_settings_type)
+        for s in Setting.query().all()]
+    yield _set_settings
+    # Restore settings.
+    session = Session()
+    keys = frozenset(k for (k, v, t) in settings_snapshot)
+    for s in Setting.query().all():
+        if s.app_settings_name not in keys:
+            session.delete(s)
+    for k, v, t in settings_snapshot:
+        if t == 'list' and hasattr(v, '__iter__'):
+            v = ','.join(v) # Quirk: must format list value manually.
+        Setting.create_or_update(k, v, t)
+    session.commit()
+
+@pytest.yield_fixture
+def auto_clear_ip_permissions():
+    """Fixture that provides nothing but clearing IP permissions upon test
+    exit. This clearing is needed to avoid other test failing to make fake http
+    accesses."""
+    yield
+    # cleanup
+    user_model = UserModel()
+
+    user_ids = []
+    user_ids.append(User.get_default_user().user_id)
+    user_ids.append(User.get_by_username(TEST_USER_REGULAR_LOGIN).user_id)
+
+    for user_id in user_ids:
+        for ip in UserIpMap.query().filter(UserIpMap.user_id == user_id):
+            user_model.delete_extra_ip(user_id, ip.ip_id)
+
+    # IP permissions are cached, need to invalidate this cache explicitly
+    invalidate_all_caches()
--- a/kallithea/tests/fixture.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/fixture.py	Fri Nov 18 01:11:13 2016 +0100
@@ -17,8 +17,8 @@
 """
 import os
 import time
-from kallithea.tests import *
-from kallithea.model.db import Repository, User, RepoGroup, UserGroup
+from kallithea.tests.base import *
+from kallithea.model.db import Repository, User, RepoGroup, UserGroup, Gist
 from kallithea.model.meta import Session
 from kallithea.model.repo import RepoModel
 from kallithea.model.user import UserModel
@@ -27,9 +27,9 @@
 from kallithea.model.gist import GistModel
 from kallithea.model.scm import ScmModel
 from kallithea.lib.vcs.backends.base import EmptyChangeset
+from os.path import dirname
 
-dn = os.path.dirname
-FIXTURES = os.path.join(dn(dn(os.path.abspath(__file__))), 'tests', 'fixtures')
+FIXTURES = os.path.join(dirname(dirname(os.path.abspath(__file__))), 'tests', 'fixtures')
 
 
 def error_function(*args, **kwargs):
@@ -58,14 +58,12 @@
                 anon = User.get_default_user()
                 self._before = anon.active
                 anon.active = status
-                Session().add(anon)
                 Session().commit()
-                time.sleep(1.5)  # hack: wait for beaker sql_cache_short to expire
+                invalidate_all_caches()
 
             def __exit__(self, exc_type, exc_val, exc_tb):
                 anon = User.get_default_user()
                 anon.active = self._before
-                Session().add(anon)
                 Session().commit()
 
         return context()
@@ -76,7 +74,7 @@
             repo_type='hg',
             clone_uri='',
             repo_group=u'-1',
-            repo_description='DESC',
+            repo_description=u'DESC',
             repo_private=False,
             repo_landing_rev='rev:tip',
             repo_copy_permissions=False,
@@ -95,8 +93,8 @@
     def _get_group_create_params(self, **custom):
         defs = dict(
             group_name=None,
-            group_description='DESC',
-            group_parent_id=None,
+            group_description=u'DESC',
+            parent_group_id=None,
             perms_updates=[],
             perms_new=[],
             enable_locking=False,
@@ -111,8 +109,8 @@
             username=name,
             password='qweqwe',
             email='%s+test@example.com' % name,
-            firstname='TestUser',
-            lastname='Test',
+            firstname=u'TestUser',
+            lastname=u'Test',
             active=True,
             admin=False,
             extern_type='internal',
@@ -125,7 +123,7 @@
     def _get_user_group_create_params(self, name, **custom):
         defs = dict(
             users_group_name=name,
-            user_group_description='DESC',
+            user_group_description=u'DESC',
             users_group_active=True,
             user_group_data={},
         )
@@ -147,6 +145,7 @@
         cur_user = kwargs.get('cur_user', TEST_USER_ADMIN_LOGIN)
         RepoModel().create(form_data, cur_user)
         Session().commit()
+        ScmModel().mark_for_invalidation(name)
         return Repository.get_by_repo_name(name)
 
     def create_fork(self, repo_to_fork, fork_name, **kwargs):
@@ -166,6 +165,7 @@
         owner = kwargs.get('cur_user', TEST_USER_ADMIN_LOGIN)
         RepoModel().create_fork(form_data, cur_user=owner)
         Session().commit()
+        ScmModel().mark_for_invalidation(fork_name)
         r = Repository.get_by_repo_name(fork_name)
         assert r
         return r
@@ -185,7 +185,7 @@
         gr = RepoGroupModel().create(
             group_name=form_data['group_name'],
             group_description=form_data['group_name'],
-            owner=owner, parent=form_data['group_parent_id'])
+            owner=owner, parent=form_data['parent_group_id'])
         Session().commit()
         gr = RepoGroup.get_by_group_name(gr.group_name)
         return gr
@@ -235,7 +235,7 @@
         form_data = {
             'description': u'new-gist',
             'owner': TEST_USER_ADMIN_LOGIN,
-            'gist_type': GistModel.cls.GIST_PUBLIC,
+            'gist_type': Gist.GIST_PUBLIC,
             'lifetime': -1,
             'gist_mapping': {'filename1.txt':{'content':'hello world'},}
         }
@@ -250,7 +250,7 @@
         return gist
 
     def destroy_gists(self, gistid=None):
-        for g in GistModel.cls.get_all():
+        for g in Gist.query():
             if gistid:
                 if gistid == g.gist_access_id:
                     GistModel().delete(g)
@@ -259,7 +259,7 @@
         Session().commit()
 
     def load_resource(self, resource_name, strip=True):
-        with open(os.path.join(FIXTURES, resource_name)) as f:
+        with open(os.path.join(FIXTURES, resource_name), 'rb') as f:
             source = f.read()
             if strip:
                 source = source.strip()
--- a/kallithea/tests/fixtures/markuptest.diff	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/fixtures/markuptest.diff	Fri Nov 18 01:11:13 2016 +0100
@@ -1,7 +1,7 @@
 diff --git a/f b/f
 --- a/f	
 +++ b/f	
-@@ -51,5 +51,12 @@
+@@ -51,6 +51,13 @@
  	begin();
  	
 +	int foo;
@@ -15,3 +15,5 @@
 +	
 +	#define MAX_STEPS (64)
  
+-	#define MIN_STEPS (48)
++	#define MIN_STEPS (42)
--- a/kallithea/tests/functional/test_admin.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_admin.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,13 +1,13 @@
 import os
 import csv
 import datetime
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.model.db import UserLog
 from kallithea.model.meta import Session
 from kallithea.lib.utils2 import safe_unicode
+from os.path import dirname
 
-dn = os.path.dirname
-FIXTURES = os.path.join(dn(dn(os.path.abspath(__file__))), 'fixtures')
+FIXTURES = os.path.join(dirname(dirname(os.path.abspath(__file__))), 'fixtures')
 
 
 class TestAdminController(TestController):
--- a/kallithea/tests/functional/test_admin_auth_settings.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_admin_auth_settings.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.model.db import Setting
 
 
@@ -21,16 +21,16 @@
                                     action='index'))
         response.mustcontain('Authentication Plugins')
 
+    @skipif(not ldap_lib_installed, reason='skipping due to missing ldap lib')
     def test_ldap_save_settings(self):
         self.log_user()
-        if not ldap_lib_installed:
-            raise SkipTest('skipping due to missing ldap lib')
 
         params = self._enable_plugins('kallithea.lib.auth_modules.auth_internal,kallithea.lib.auth_modules.auth_ldap')
         params.update({'auth_ldap_host': u'dc.example.com',
                        'auth_ldap_port': '999',
                        'auth_ldap_tls_kind': 'PLAIN',
                        'auth_ldap_tls_reqcert': 'NEVER',
+                       'auth_ldap_cacertdir': '',
                        'auth_ldap_dn_user': 'test_user',
                        'auth_ldap_dn_pass': 'test_pass',
                        'auth_ldap_base_dn': 'test_base_dn',
@@ -48,13 +48,11 @@
         self.checkSessionFlash(response, 'Auth settings updated successfully')
 
         new_settings = Setting.get_auth_settings()
-        self.assertEqual(new_settings['auth_ldap_host'], u'dc.example.com',
-                         'fail db write compare')
+        assert new_settings['auth_ldap_host'] == u'dc.example.com', 'fail db write compare'
 
+    @skipif(not ldap_lib_installed, reason='skipping due to missing ldap lib')
     def test_ldap_error_form_wrong_port_number(self):
         self.log_user()
-        if not ldap_lib_installed:
-            raise SkipTest('skipping due to missing ldap lib')
 
         params = self._enable_plugins('kallithea.lib.auth_modules.auth_internal,kallithea.lib.auth_modules.auth_ldap')
         params.update({'auth_ldap_host': '',
@@ -78,10 +76,9 @@
         response.mustcontain("""<span class="error-message">"""
                              """Please enter a number</span>""")
 
+    @skipif(not ldap_lib_installed, reason='skipping due to missing ldap lib')
     def test_ldap_error_form(self):
         self.log_user()
-        if not ldap_lib_installed:
-            raise SkipTest('skipping due to missing ldap lib')
 
         params = self._enable_plugins('kallithea.lib.auth_modules.auth_internal,kallithea.lib.auth_modules.auth_ldap')
         params.update({'auth_ldap_host': 'Host',
@@ -135,6 +132,9 @@
     def test_container_auth_login_header(self):
         self._container_auth_setup(
             auth_container_header='THE_USER_NAME',
+            auth_container_email_header='',
+            auth_container_firstname_header='',
+            auth_container_lastname_header='',
             auth_container_fallback_header='',
             auth_container_clean_username='False',
         )
@@ -143,9 +143,34 @@
             resulting_username='john@example.org',
         )
 
+    def test_container_auth_login_header_attr(self):
+        self._container_auth_setup(
+            auth_container_header='THE_USER_NAME',
+            auth_container_email_header='THE_USER_EMAIL',
+            auth_container_firstname_header='THE_USER_FIRSTNAME',
+            auth_container_lastname_header='THE_USER_LASTNAME',
+            auth_container_fallback_header='',
+            auth_container_clean_username='False',
+        )
+        response = self.app.get(
+            url=url(controller='admin/my_account', action='my_account'),
+            extra_environ={'THE_USER_NAME': 'johnd',
+                           'THE_USER_EMAIL': 'john@example.org',
+                           'THE_USER_FIRSTNAME': 'John',
+                           'THE_USER_LASTNAME': 'Doe',
+                           }
+        )
+        assert response.form['email'].value == 'john@example.org'
+        assert response.form['firstname'].value == 'John'
+        assert response.form['lastname'].value == 'Doe'
+
+
     def test_container_auth_login_fallback_header(self):
         self._container_auth_setup(
             auth_container_header='THE_USER_NAME',
+            auth_container_email_header='',
+            auth_container_firstname_header='',
+            auth_container_lastname_header='',
             auth_container_fallback_header='HTTP_X_YZZY',
             auth_container_clean_username='False',
         )
@@ -157,6 +182,9 @@
     def test_container_auth_clean_username_at(self):
         self._container_auth_setup(
             auth_container_header='REMOTE_USER',
+            auth_container_email_header='',
+            auth_container_firstname_header='',
+            auth_container_lastname_header='',
             auth_container_fallback_header='',
             auth_container_clean_username='True',
         )
@@ -168,6 +196,9 @@
     def test_container_auth_clean_username_backslash(self):
         self._container_auth_setup(
             auth_container_header='REMOTE_USER',
+            auth_container_email_header='',
+            auth_container_firstname_header='',
+            auth_container_lastname_header='',
             auth_container_fallback_header='',
             auth_container_clean_username='True',
         )
@@ -179,6 +210,9 @@
     def test_container_auth_no_logout(self):
         self._container_auth_setup(
             auth_container_header='REMOTE_USER',
+            auth_container_email_header='',
+            auth_container_firstname_header='',
+            auth_container_lastname_header='',
             auth_container_fallback_header='',
             auth_container_clean_username='True',
         )
@@ -186,7 +220,7 @@
             url=url(controller='admin/my_account', action='my_account'),
             extra_environ={'REMOTE_USER': 'john'},
         )
-        self.assertNotIn('Log Out', response.normal_body)
+        assert 'Log Out' not in response.normal_body
 
     def test_crowd_save_settings(self):
         self.log_user()
@@ -205,15 +239,12 @@
         self.checkSessionFlash(response, 'Auth settings updated successfully')
 
         new_settings = Setting.get_auth_settings()
-        self.assertEqual(new_settings['auth_crowd_host'], u'hostname',
-                         'fail db write compare')
+        assert new_settings['auth_crowd_host'] == u'hostname', 'fail db write compare'
 
+    @skipif(not pam_lib_installed, reason='skipping due to missing pam lib')
     def test_pam_save_settings(self):
         self.log_user()
 
-        if not pam_lib_installed:
-            raise SkipTest('skipping due to missing pam lib')
-
         params = self._enable_plugins('kallithea.lib.auth_modules.auth_internal,kallithea.lib.auth_modules.auth_pam')
         params.update({'auth_pam_service': 'kallithea',
                        'auth_pam_gecos': '^foo-.*'})
@@ -225,5 +256,4 @@
         self.checkSessionFlash(response, 'Auth settings updated successfully')
 
         new_settings = Setting.get_auth_settings()
-        self.assertEqual(new_settings['auth_pam_service'], u'kallithea',
-                         'fail db write compare')
+        assert new_settings['auth_pam_service'] == u'kallithea', 'fail db write compare'
--- a/kallithea/tests/functional/test_admin_defaults.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_admin_defaults.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.model.db import Setting
 
 
@@ -12,19 +12,6 @@
         response.mustcontain('default_repo_enable_downloads')
         response.mustcontain('default_repo_enable_locking')
 
-    def test_index_as_xml(self):
-        response = self.app.get(url('formatted_defaults', format='xml'))
-
-    def test_create(self):
-        response = self.app.post(url('defaults'),
-            {'_authentication_token': self.authentication_token()})
-
-    def test_new(self):
-        response = self.app.get(url('new_default'))
-
-    def test_new_as_xml(self):
-        response = self.app.get(url('formatted_new_default', format='xml'))
-
     def test_update_params_true_hg(self):
         self.log_user()
         params = {
@@ -35,12 +22,12 @@
             'default_repo_type': 'hg',
             '_authentication_token': self.authentication_token(),
         }
-        response = self.app.put(url('default', id='default'), params=params)
+        response = self.app.post(url('defaults_update', id='default'), params=params)
         self.checkSessionFlash(response, 'Default settings updated successfully')
 
         params.pop('_authentication_token')
         defs = Setting.get_default_repo_settings()
-        self.assertEqual(params, defs)
+        assert params == defs
 
     def test_update_params_false_git(self):
         self.log_user()
@@ -52,31 +39,9 @@
             'default_repo_type': 'git',
             '_authentication_token': self.authentication_token(),
         }
-        response = self.app.put(url('default', id='default'), params=params)
+        response = self.app.post(url('defaults_update', id='default'), params=params)
         self.checkSessionFlash(response, 'Default settings updated successfully')
 
         params.pop('_authentication_token')
         defs = Setting.get_default_repo_settings()
-        self.assertEqual(params, defs)
-
-    def test_update_browser_fakeout(self):
-        response = self.app.post(url('default', id=1), params=dict(_method='put', _authentication_token=self.authentication_token()))
-
-    def test_delete(self):
-        # Not possible due to CSRF protection.
-        response = self.app.delete(url('default', id=1), status=405)
-
-    def test_delete_browser_fakeout(self):
-        response = self.app.post(url('default', id=1), params=dict(_method='delete', _authentication_token=self.authentication_token()))
-
-    def test_show(self):
-        response = self.app.get(url('default', id=1))
-
-    def test_show_as_xml(self):
-        response = self.app.get(url('formatted_default', id=1, format='xml'))
-
-    def test_edit(self):
-        response = self.app.get(url('edit_default', id=1))
-
-    def test_edit_as_xml(self):
-        response = self.app.get(url('formatted_edit_default', id=1, format='xml'))
+        assert params == defs
--- a/kallithea/tests/functional/test_admin_gists.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_admin_gists.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.model.gist import GistModel
 from kallithea.model.meta import Session
 from kallithea.model.db import User, Gist
@@ -10,8 +10,8 @@
     gist_mapping = {
         f_name: {'content': content}
     }
-    user = User.get_by_username(owner)
-    gist = GistModel().create(description, owner=user,
+    owner = User.get_by_username(owner)
+    gist = GistModel().create(description, owner=owner,
                        gist_mapping=gist_mapping, gist_type=gist_type,
                        lifetime=lifetime)
     Session().commit()
@@ -20,8 +20,8 @@
 
 class TestGistsController(TestController):
 
-    def tearDown(self):
-        for g in Gist.get_all():
+    def teardown_method(self, method):
+        for g in Gist.query():
             GistModel().delete(g)
         Session().commit()
 
@@ -73,7 +73,7 @@
         response = response.follow()
         response.mustcontain('added file: foo')
         response.mustcontain('gist test')
-        response.mustcontain('<div class="btn btn-mini btn-success disabled">Public Gist</div>')
+        response.mustcontain('<div class="label label-success">Public Gist</div>')
 
     def test_create_with_path_with_dirs(self):
         self.log_user()
@@ -90,7 +90,6 @@
         self.log_user()
         gist = _create_gist('never-see-me')
         gist.gist_expires = 0  # 1970
-        Session().add(gist)
         Session().commit()
 
         response = self.app.get(url('gist', gist_id=gist.gist_access_id), status=404)
@@ -107,7 +106,7 @@
         response = response.follow()
         response.mustcontain('added file: private-foo<')
         response.mustcontain('private gist test')
-        response.mustcontain('<div class="btn btn-mini btn-warning disabled">Private Gist</div>')
+        response.mustcontain('<div class="label label-warning">Private Gist</div>')
 
     def test_create_with_description(self):
         self.log_user()
@@ -123,33 +122,29 @@
         response.mustcontain('added file: foo-desc')
         response.mustcontain('gist test')
         response.mustcontain('gist-desc')
-        response.mustcontain('<div class="btn btn-mini btn-success disabled">Public Gist</div>')
+        response.mustcontain('<div class="label label-success">Public Gist</div>')
 
     def test_new(self):
         self.log_user()
         response = self.app.get(url('new_gist'))
 
-    def test_update(self):
-        self.skipTest('not implemented')
-        response = self.app.put(url('gist', gist_id=1))
-
     def test_delete(self):
         self.log_user()
         gist = _create_gist('delete-me')
-        response = self.app.post(url('gist', gist_id=gist.gist_id),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('gist_delete', gist_id=gist.gist_id),
+            params={'_authentication_token': self.authentication_token()})
 
     def test_delete_normal_user_his_gist(self):
         self.log_user(TEST_USER_REGULAR_LOGIN, TEST_USER_REGULAR_PASS)
         gist = _create_gist('delete-me', owner=TEST_USER_REGULAR_LOGIN)
-        response = self.app.post(url('gist', gist_id=gist.gist_id),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('gist_delete', gist_id=gist.gist_id),
+            params={'_authentication_token': self.authentication_token()})
 
     def test_delete_normal_user_not_his_own_gist(self):
         self.log_user(TEST_USER_REGULAR_LOGIN, TEST_USER_REGULAR_PASS)
         gist = _create_gist('delete-me')
-        response = self.app.post(url('gist', gist_id=gist.gist_id), status=403,
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('gist_delete', gist_id=gist.gist_id), status=403,
+            params={'_authentication_token': self.authentication_token()})
 
     def test_show(self):
         gist = _create_gist('gist-show-me')
@@ -157,20 +152,20 @@
         response.mustcontain('added file: gist-show-me<')
         response.mustcontain('%s - created' % TEST_USER_ADMIN_LOGIN)
         response.mustcontain('gist-desc')
-        response.mustcontain('<div class="btn btn-mini btn-success disabled">Public Gist</div>')
+        response.mustcontain('<div class="label label-success">Public Gist</div>')
 
     def test_show_as_raw(self):
         gist = _create_gist('gist-show-me', content='GIST CONTENT')
         response = self.app.get(url('formatted_gist',
                                     gist_id=gist.gist_access_id, format='raw'))
-        self.assertEqual(response.body, 'GIST CONTENT')
+        assert response.body == 'GIST CONTENT'
 
     def test_show_as_raw_individual_file(self):
         gist = _create_gist('gist-show-me-raw', content='GIST BODY')
         response = self.app.get(url('formatted_gist_file',
                                     gist_id=gist.gist_access_id, format='raw',
                                     revision='tip', f_path='gist-show-me-raw'))
-        self.assertEqual(response.body, 'GIST BODY')
+        assert response.body == 'GIST BODY'
 
     def test_edit(self):
         response = self.app.get(url('edit_gist', gist_id=1))
--- a/kallithea/tests/functional/test_admin_notifications.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_admin_notifications.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.model.db import User
 
 from kallithea.model.user import UserModel
@@ -8,16 +8,18 @@
 
 
 class TestNotificationsController(TestController):
-    def setUp(self):
+    def setup_method(self, method):
         self.remove_all_notifications()
 
-    def test_index(self):
+    def test_index(self, create_test_user):
         self.log_user()
 
-        u1 = UserModel().create_or_update(username='u1', password='qweqwe',
-                                          email='u1@example.com',
-                                          firstname='u1', lastname='u1')
+        u1 = create_test_user(dict(username='u1', password='qweqwe',
+                                   email='u1@example.com',
+                                   firstname=u'u1', lastname=u'u1',
+                                   active=True))
         u1 = u1.user_id
+        Session().commit()
 
         response = self.app.get(url('notifications'))
         response.mustcontain('<div class="table">No notifications here yet</div>')
@@ -29,16 +31,18 @@
         response = self.app.get(url('notifications'))
         response.mustcontain('id="notification_%s"' % notif.notification_id)
 
-    def test_delete(self):
+    def test_delete(self, create_test_user):
         self.log_user()
         cur_user = self._get_logged_user()
 
-        u1 = UserModel().create_or_update(username='u1', password='qweqwe',
-                                               email='u1@example.com',
-                                               firstname='u1', lastname='u1')
-        u2 = UserModel().create_or_update(username='u2', password='qweqwe',
-                                               email='u2@example.com',
-                                               firstname='u2', lastname='u2')
+        u1 = create_test_user(dict(username='u1', password='qweqwe',
+                                   email='u1@example.com',
+                                   firstname=u'u1', lastname=u'u1',
+                                   active=True))
+        u2 = create_test_user(dict(username='u2', password='qweqwe',
+                                   email='u2@example.com',
+                                   firstname=u'u2', lastname=u'u2',
+                                   active=True))
 
         # make notifications
         notification = NotificationModel().create(created_by=cur_user,
@@ -51,28 +55,31 @@
 
         # check DB
         get_notif = lambda un: [x.notification for x in un]
-        self.assertEqual(get_notif(cur_user.notifications), [notification])
-        self.assertEqual(get_notif(u1.notifications), [notification])
-        self.assertEqual(get_notif(u2.notifications), [notification])
+        assert get_notif(cur_user.notifications) == [notification]
+        assert get_notif(u1.notifications) == [notification]
+        assert get_notif(u2.notifications) == [notification]
         cur_usr_id = cur_user.user_id
 
         response = self.app.post(
-            url('notification', notification_id=notification.notification_id),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
-        self.assertEqual(response.body, 'ok')
+            url('notification_delete', notification_id=notification.notification_id),
+            params={'_authentication_token': self.authentication_token()})
+        assert response.body == 'ok'
 
         cur_user = User.get(cur_usr_id)
-        self.assertEqual(cur_user.notifications, [])
+        assert cur_user.notifications == []
 
-    def test_show(self):
+    def test_show(self, create_test_user):
         self.log_user()
         cur_user = self._get_logged_user()
-        u1 = UserModel().create_or_update(username='u1', password='qweqwe',
-                                          email='u1@example.com',
-                                          firstname='u1', lastname='u1')
-        u2 = UserModel().create_or_update(username='u2', password='qweqwe',
-                                          email='u2@example.com',
-                                          firstname='u2', lastname='u2')
+        u1 = create_test_user(dict(username='u1', password='qweqwe',
+                                   email='u1@example.com',
+                                   firstname=u'u1', lastname=u'u1',
+                                   active=True))
+        u2 = create_test_user(dict(username='u2', password='qweqwe',
+                                   email='u2@example.com',
+                                   firstname=u'u2', lastname=u'u2',
+                                   active=True))
+        Session().commit()
 
         subject = u'test'
         notif_body = u'hi there'
@@ -97,13 +104,10 @@
                                                   body       = notify_body)
 
         description = NotificationModel().make_description(notification)
-        self.assertEqual(
-            description,
-            "{0} sent message {1}".format(
+        assert description == "{0} sent message {1}".format(
                 cur_user.username,
                 h.age(notification.created_on)
                 )
-            )
 
     def test_description_with_datetime(self):
         self.log_user()
@@ -115,10 +119,44 @@
                                                   body       = notify_body)
 
         description = NotificationModel().make_description(notification, False)
-        self.assertEqual(
-            description,
-            "{0} sent message at {1}".format(
+        assert description == "{0} sent message at {1}".format(
                 cur_user.username,
                 h.fmt_date(notification.created_on)
                 )
-            )
+
+    def test_mark_all_read(self, create_test_user):
+        self.log_user()
+        u0 = self._get_logged_user()
+        u1 = create_test_user(dict(username='u1', password='qweqwe',
+                                   email='u1@example.com',
+                                   firstname=u'u1', lastname=u'u1',
+                                   active=True))
+        u2 = create_test_user(dict(username='u2', password='qweqwe',
+                                   email='u2@example.com',
+                                   firstname=u'u2', lastname=u'u2',
+                                   active=True))
+        notif = NotificationModel().create(created_by=u1,
+                                           subject=u'subject',
+                                           body=u'body',
+                                           recipients=[u0, u2])
+        u0_id, u1_id, u2_id = u0.user_id, u1.user_id, u2.user_id
+
+        assert [n.read for n in u0.notifications] == [False]
+        assert u1.notifications == []
+        assert [n.read for n in u2.notifications] == [False]
+
+        # Mark all read for current user.
+
+        response = self.app.get(url('notifications_mark_all_read'), # TODO: should be POST
+                                extra_environ=dict(HTTP_X_PARTIAL_XHR='1'))
+
+        assert response.status_int == 200
+        response.mustcontain('id="notification_%s"' % notif.notification_id)
+
+        u0 = User.get(u0_id)
+        u1 = User.get(u1_id)
+        u2 = User.get(u2_id)
+
+        assert [n.read for n in u0.notifications] == [True]
+        assert u1.notifications == []
+        assert [n.read for n in u2.notifications] == [False]
--- a/kallithea/tests/functional/test_admin_permissions.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_admin_permissions.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,5 +1,9 @@
+import time
+
 from kallithea.model.db import User, UserIpMap
-from kallithea.tests import *
+from kallithea.model.user import UserModel
+from kallithea.model.meta import Session
+from kallithea.tests.base import *
 
 class TestAdminPermissionsController(TestController):
 
@@ -14,26 +18,52 @@
         # Test response...
         response.mustcontain('All IP addresses are allowed')
 
-    def test_add_ips(self):
+    def test_add_ips(self, auto_clear_ip_permissions):
         self.log_user()
         default_user_id = User.get_default_user().user_id
-        response = self.app.put(url('edit_user_ips', id=default_user_id),
+        response = self.app.post(url('edit_user_ips_update', id=default_user_id),
                                  params=dict(new_ip='127.0.0.0/24',
                                  _authentication_token=self.authentication_token()))
 
-        response = self.app.get(url('admin_permissions_ips'))
+        # IP permissions are cached, need to invalidate this cache explicitly
+        invalidate_all_caches()
+
+        self.app.get(url('admin_permissions_ips'), status=302)
+
+        # REMOTE_ADDR must match 127.0.0.0/24
+        response = self.app.get(url('admin_permissions_ips'),
+                                extra_environ={'REMOTE_ADDR': '127.0.0.1'})
         response.mustcontain('127.0.0.0/24')
         response.mustcontain('127.0.0.0 - 127.0.0.255')
 
-        ## delete
+    def test_delete_ips(self, auto_clear_ip_permissions):
+        self.log_user()
         default_user_id = User.get_default_user().user_id
-        del_ip_id = UserIpMap.query().filter(UserIpMap.user_id ==
-                                             default_user_id).first().ip_id
+
+        ## first add
+        new_ip = '127.0.0.0/24'
+        user_model = UserModel()
+        ip_obj = user_model.add_extra_ip(default_user_id, new_ip)
+        Session().commit()
 
-        response = self.app.post(url('edit_user_ips', id=default_user_id),
-                                 params=dict(_method='delete',
-                                             del_ip_id=del_ip_id,
-                                             _authentication_token=self.authentication_token()))
+        ## double check that add worked
+        # IP permissions are cached, need to invalidate this cache explicitly
+        invalidate_all_caches()
+        self.app.get(url('admin_permissions_ips'), status=302)
+        # REMOTE_ADDR must match 127.0.0.0/24
+        response = self.app.get(url('admin_permissions_ips'),
+                                extra_environ={'REMOTE_ADDR': '127.0.0.1'})
+        response.mustcontain('127.0.0.0/24')
+        response.mustcontain('127.0.0.0 - 127.0.0.255')
+
+        ## now delete
+        response = self.app.post(url('edit_user_ips_delete', id=default_user_id),
+                                 params=dict(del_ip_id=ip_obj.ip_id,
+                                             _authentication_token=self.authentication_token()),
+                                 extra_environ={'REMOTE_ADDR': '127.0.0.1'})
+
+        # IP permissions are cached, need to invalidate this cache explicitly
+        invalidate_all_caches()
 
         response = self.app.get(url('admin_permissions_ips'))
         response.mustcontain('All IP addresses are allowed')
--- a/kallithea/tests/functional/test_admin_repo_groups.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_admin_repo_groups.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 
 class TestRepoGroupsController(TestController):
     pass
--- a/kallithea/tests/functional/test_admin_repos.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_admin_repos.py	Fri Nov 18 01:11:13 2016 +0100
@@ -7,10 +7,11 @@
 import pytest
 
 from kallithea.lib import vcs
-from kallithea.model.db import Repository, RepoGroup, UserRepoToPerm, User,\
-    Permission
+from kallithea.lib.utils2 import safe_str, safe_unicode
+from kallithea.model.db import Repository, RepoGroup, UserRepoToPerm, User, \
+    Permission, Ui
 from kallithea.model.user import UserModel
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.model.repo_group import RepoGroupModel
 from kallithea.model.repo import RepoModel
 from kallithea.model.meta import Session
@@ -20,15 +21,15 @@
 
 
 def _get_permission_for_user(user, repo):
-    perm = UserRepoToPerm.query()\
+    perm = UserRepoToPerm.query() \
                 .filter(UserRepoToPerm.repository ==
-                        Repository.get_by_repo_name(repo))\
-                .filter(UserRepoToPerm.user == User.get_by_username(user))\
+                        Repository.get_by_repo_name(repo)) \
+                .filter(UserRepoToPerm.user == User.get_by_username(user)) \
                 .all()
     return perm
 
 
-class _BaseTest(object):
+class _BaseTestCase(TestController):
     """
     Write all tests here
     """
@@ -38,14 +39,6 @@
     OTHER_TYPE_REPO = None
     OTHER_TYPE = None
 
-    @classmethod
-    def setup_class(cls):
-        pass
-
-    @classmethod
-    def teardown_class(cls):
-        pass
-
     def test_index(self):
         self.log_user()
         response = self.app.get(url('repos'))
@@ -53,7 +46,7 @@
     def test_create(self):
         self.log_user()
         repo_name = self.NEW_REPO
-        description = 'description for newly created repo'
+        description = u'description for newly created repo'
         response = self.app.post(url('repos'),
                         fixture._get_repo_create_params(repo_private=False,
                                                 repo_name=repo_name,
@@ -62,17 +55,17 @@
                                                 _authentication_token=self.authentication_token()))
         ## run the check page that triggers the flash message
         response = self.app.get(url('repo_check_home', repo_name=repo_name))
-        self.assertEqual(response.json, {u'result': True})
+        assert response.json == {u'result': True}
         self.checkSessionFlash(response,
                                'Created repository <a href="/%s">%s</a>'
                                % (repo_name, repo_name))
 
         # test if the repo was created in the database
-        new_repo = Session().query(Repository)\
+        new_repo = Session().query(Repository) \
             .filter(Repository.repo_name == repo_name).one()
 
-        self.assertEqual(new_repo.repo_name, repo_name)
-        self.assertEqual(new_repo.description, description)
+        assert new_repo.repo_name == repo_name
+        assert new_repo.description == description
 
         # test if the repository is visible in the list ?
         response = self.app.get(url('summary_home', repo_name=repo_name))
@@ -81,63 +74,26 @@
 
         # test if the repository was created on filesystem
         try:
-            vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
+            vcs.get_repo(safe_str(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name)))
         except vcs.exceptions.VCSError:
-            self.fail('no repo %s in filesystem' % repo_name)
+            pytest.fail('no repo %s in filesystem' % repo_name)
 
         RepoModel().delete(repo_name)
         Session().commit()
 
-    def test_create_non_ascii(self):
-        self.log_user()
-        non_ascii = "ąęł"
-        repo_name = "%s%s" % (self.NEW_REPO, non_ascii)
-        repo_name_unicode = repo_name.decode('utf8')
-        description = 'description for newly created repo' + non_ascii
-        description_unicode = description.decode('utf8')
-        response = self.app.post(url('repos'),
-                        fixture._get_repo_create_params(repo_private=False,
-                                                repo_name=repo_name,
-                                                repo_type=self.REPO_TYPE,
-                                                repo_description=description,
-                                                _authentication_token=self.authentication_token()))
-        ## run the check page that triggers the flash message
-        response = self.app.get(url('repo_check_home', repo_name=repo_name))
-        self.assertEqual(response.json, {u'result': True})
-        self.checkSessionFlash(response,
-                               u'Created repository <a href="/%s">%s</a>'
-                               % (urllib.quote(repo_name), repo_name_unicode))
-        # test if the repo was created in the database
-        new_repo = Session().query(Repository)\
-            .filter(Repository.repo_name == repo_name_unicode).one()
-
-        self.assertEqual(new_repo.repo_name, repo_name_unicode)
-        self.assertEqual(new_repo.description, description_unicode)
-
-        # test if the repository is visible in the list ?
-        response = self.app.get(url('summary_home', repo_name=repo_name))
-        response.mustcontain(repo_name)
-        response.mustcontain(self.REPO_TYPE)
-
-        # test if the repository was created on filesystem
-        try:
-            vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
-        except vcs.exceptions.VCSError:
-            self.fail('no repo %s in filesystem' % repo_name)
-
     def test_create_in_group(self):
         self.log_user()
 
         ## create GROUP
-        group_name = 'sometest_%s' % self.REPO_TYPE
+        group_name = u'sometest_%s' % self.REPO_TYPE
         gr = RepoGroupModel().create(group_name=group_name,
-                                     group_description='test',
+                                     group_description=u'test',
                                      owner=TEST_USER_ADMIN_LOGIN)
         Session().commit()
 
-        repo_name = 'ingroup'
+        repo_name = u'ingroup'
         repo_name_full = RepoGroup.url_sep().join([group_name, repo_name])
-        description = 'description for newly created repo'
+        description = u'description for newly created repo'
         response = self.app.post(url('repos'),
                         fixture._get_repo_create_params(repo_private=False,
                                                 repo_name=repo_name,
@@ -147,34 +103,34 @@
                                                 _authentication_token=self.authentication_token()))
         ## run the check page that triggers the flash message
         response = self.app.get(url('repo_check_home', repo_name=repo_name_full))
-        self.assertEqual(response.json, {u'result': True})
+        assert response.json == {u'result': True}
         self.checkSessionFlash(response,
                                'Created repository <a href="/%s">%s</a>'
                                % (repo_name_full, repo_name_full))
         # test if the repo was created in the database
-        new_repo = Session().query(Repository)\
+        new_repo = Session().query(Repository) \
             .filter(Repository.repo_name == repo_name_full).one()
         new_repo_id = new_repo.repo_id
 
-        self.assertEqual(new_repo.repo_name, repo_name_full)
-        self.assertEqual(new_repo.description, description)
+        assert new_repo.repo_name == repo_name_full
+        assert new_repo.description == description
 
         # test if the repository is visible in the list ?
         response = self.app.get(url('summary_home', repo_name=repo_name_full))
         response.mustcontain(repo_name_full)
         response.mustcontain(self.REPO_TYPE)
 
-        inherited_perms = UserRepoToPerm.query()\
+        inherited_perms = UserRepoToPerm.query() \
             .filter(UserRepoToPerm.repository_id == new_repo_id).all()
-        self.assertEqual(len(inherited_perms), 1)
+        assert len(inherited_perms) == 1
 
         # test if the repository was created on filesystem
         try:
-            vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name_full))
+            vcs.get_repo(safe_str(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name_full)))
         except vcs.exceptions.VCSError:
             RepoGroupModel().delete(group_name)
             Session().commit()
-            self.fail('no repo %s in filesystem' % repo_name)
+            pytest.fail('no repo %s in filesystem' % repo_name)
 
         RepoModel().delete(repo_name_full)
         RepoGroupModel().delete(group_name)
@@ -200,21 +156,21 @@
         Session().commit()
 
         ## create GROUP
-        group_name = 'reg_sometest_%s' % self.REPO_TYPE
+        group_name = u'reg_sometest_%s' % self.REPO_TYPE
         gr = RepoGroupModel().create(group_name=group_name,
-                                     group_description='test',
+                                     group_description=u'test',
                                      owner=TEST_USER_ADMIN_LOGIN)
         Session().commit()
 
-        group_name_allowed = 'reg_sometest_allowed_%s' % self.REPO_TYPE
+        group_name_allowed = u'reg_sometest_allowed_%s' % self.REPO_TYPE
         gr_allowed = RepoGroupModel().create(group_name=group_name_allowed,
-                                     group_description='test',
+                                     group_description=u'test',
                                      owner=TEST_USER_REGULAR_LOGIN)
         Session().commit()
 
-        repo_name = 'ingroup'
+        repo_name = u'ingroup'
         repo_name_full = RepoGroup.url_sep().join([group_name, repo_name])
-        description = 'description for newly created repo'
+        description = u'description for newly created repo'
         response = self.app.post(url('repos'),
                         fixture._get_repo_create_params(repo_private=False,
                                                 repo_name=repo_name,
@@ -226,9 +182,9 @@
         response.mustcontain('Invalid value')
 
         # user is allowed to create in this group
-        repo_name = 'ingroup'
+        repo_name = u'ingroup'
         repo_name_full = RepoGroup.url_sep().join([group_name_allowed, repo_name])
-        description = 'description for newly created repo'
+        description = u'description for newly created repo'
         response = self.app.post(url('repos'),
                         fixture._get_repo_create_params(repo_private=False,
                                                 repo_name=repo_name,
@@ -239,34 +195,34 @@
 
         ## run the check page that triggers the flash message
         response = self.app.get(url('repo_check_home', repo_name=repo_name_full))
-        self.assertEqual(response.json, {u'result': True})
+        assert response.json == {u'result': True}
         self.checkSessionFlash(response,
                                'Created repository <a href="/%s">%s</a>'
                                % (repo_name_full, repo_name_full))
         # test if the repo was created in the database
-        new_repo = Session().query(Repository)\
+        new_repo = Session().query(Repository) \
             .filter(Repository.repo_name == repo_name_full).one()
         new_repo_id = new_repo.repo_id
 
-        self.assertEqual(new_repo.repo_name, repo_name_full)
-        self.assertEqual(new_repo.description, description)
+        assert new_repo.repo_name == repo_name_full
+        assert new_repo.description == description
 
         # test if the repository is visible in the list ?
         response = self.app.get(url('summary_home', repo_name=repo_name_full))
         response.mustcontain(repo_name_full)
         response.mustcontain(self.REPO_TYPE)
 
-        inherited_perms = UserRepoToPerm.query()\
+        inherited_perms = UserRepoToPerm.query() \
             .filter(UserRepoToPerm.repository_id == new_repo_id).all()
-        self.assertEqual(len(inherited_perms), 1)
+        assert len(inherited_perms) == 1
 
         # test if the repository was created on filesystem
         try:
-            vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name_full))
+            vcs.get_repo(safe_str(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name_full)))
         except vcs.exceptions.VCSError:
             RepoGroupModel().delete(group_name)
             Session().commit()
-            self.fail('no repo %s in filesystem' % repo_name)
+            pytest.fail('no repo %s in filesystem' % repo_name)
 
         RepoModel().delete(repo_name_full)
         RepoGroupModel().delete(group_name)
@@ -277,9 +233,9 @@
         self.log_user()
 
         ## create GROUP
-        group_name = 'sometest_%s' % self.REPO_TYPE
+        group_name = u'sometest_%s' % self.REPO_TYPE
         gr = RepoGroupModel().create(group_name=group_name,
-                                     group_description='test',
+                                     group_description=u'test',
                                      owner=TEST_USER_ADMIN_LOGIN)
         perm = Permission.get_by_key('repository.write')
         RepoGroupModel().grant_user_permission(gr, TEST_USER_REGULAR_LOGIN, perm)
@@ -287,9 +243,9 @@
         ## add repo permissions
         Session().commit()
 
-        repo_name = 'ingroup_inherited_%s' % self.REPO_TYPE
+        repo_name = u'ingroup_inherited_%s' % self.REPO_TYPE
         repo_name_full = RepoGroup.url_sep().join([group_name, repo_name])
-        description = 'description for newly created repo'
+        description = u'description for newly created repo'
         response = self.app.post(url('repos'),
                         fixture._get_repo_create_params(repo_private=False,
                                                 repo_name=repo_name,
@@ -305,12 +261,12 @@
                                'Created repository <a href="/%s">%s</a>'
                                % (repo_name_full, repo_name_full))
         # test if the repo was created in the database
-        new_repo = Session().query(Repository)\
+        new_repo = Session().query(Repository) \
             .filter(Repository.repo_name == repo_name_full).one()
         new_repo_id = new_repo.repo_id
 
-        self.assertEqual(new_repo.repo_name, repo_name_full)
-        self.assertEqual(new_repo.description, description)
+        assert new_repo.repo_name == repo_name_full
+        assert new_repo.description == description
 
         # test if the repository is visible in the list ?
         response = self.app.get(url('summary_home', repo_name=repo_name_full))
@@ -319,21 +275,21 @@
 
         # test if the repository was created on filesystem
         try:
-            vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name_full))
+            vcs.get_repo(safe_str(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name_full)))
         except vcs.exceptions.VCSError:
             RepoGroupModel().delete(group_name)
             Session().commit()
-            self.fail('no repo %s in filesystem' % repo_name)
+            pytest.fail('no repo %s in filesystem' % repo_name)
 
         #check if inherited permissiona are applied
-        inherited_perms = UserRepoToPerm.query()\
+        inherited_perms = UserRepoToPerm.query() \
             .filter(UserRepoToPerm.repository_id == new_repo_id).all()
-        self.assertEqual(len(inherited_perms), 2)
+        assert len(inherited_perms) == 2
 
-        self.assertTrue(TEST_USER_REGULAR_LOGIN in [x.user.username
-                                                    for x in inherited_perms])
-        self.assertTrue('repository.write' in [x.permission.permission_name
-                                               for x in inherited_perms])
+        assert TEST_USER_REGULAR_LOGIN in [x.user.username
+                                                    for x in inherited_perms]
+        assert 'repository.write' in [x.permission.permission_name
+                                               for x in inherited_perms]
 
         RepoModel().delete(repo_name_full)
         RepoGroupModel().delete(group_name)
@@ -342,7 +298,7 @@
     def test_create_remote_repo_wrong_clone_uri(self):
         self.log_user()
         repo_name = self.NEW_REPO
-        description = 'description for newly created repo'
+        description = u'description for newly created repo'
         response = self.app.post(url('repos'),
                         fixture._get_repo_create_params(repo_private=False,
                                                 repo_name=repo_name,
@@ -356,7 +312,7 @@
     def test_create_remote_repo_wrong_clone_uri_hg_svn(self):
         self.log_user()
         repo_name = self.NEW_REPO
-        description = 'description for newly created repo'
+        description = u'description for newly created repo'
         response = self.app.post(url('repos'),
                         fixture._get_repo_create_params(repo_private=False,
                                                 repo_name=repo_name,
@@ -369,8 +325,8 @@
 
     def test_delete(self):
         self.log_user()
-        repo_name = 'vcs_test_new_to_delete_%s' % self.REPO_TYPE
-        description = 'description for newly created repo'
+        repo_name = u'vcs_test_new_to_delete_%s' % self.REPO_TYPE
+        description = u'description for newly created repo'
         response = self.app.post(url('repos'),
                         fixture._get_repo_create_params(repo_private=False,
                                                 repo_type=self.REPO_TYPE,
@@ -383,11 +339,11 @@
                                'Created repository <a href="/%s">%s</a>'
                                % (repo_name, repo_name))
         # test if the repo was created in the database
-        new_repo = Session().query(Repository)\
+        new_repo = Session().query(Repository) \
             .filter(Repository.repo_name == repo_name).one()
 
-        self.assertEqual(new_repo.repo_name, repo_name)
-        self.assertEqual(new_repo.description, description)
+        assert new_repo.repo_name == repo_name
+        assert new_repo.description == description
 
         # test if the repository is visible in the list ?
         response = self.app.get(url('summary_home', repo_name=repo_name))
@@ -396,33 +352,32 @@
 
         # test if the repository was created on filesystem
         try:
-            vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
+            vcs.get_repo(safe_str(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name)))
         except vcs.exceptions.VCSError:
-            self.fail('no repo %s in filesystem' % repo_name)
+            pytest.fail('no repo %s in filesystem' % repo_name)
 
         response = self.app.post(url('delete_repo', repo_name=repo_name),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+            params={'_authentication_token': self.authentication_token()})
 
         self.checkSessionFlash(response, 'Deleted repository %s' % (repo_name))
 
         response.follow()
 
         #check if repo was deleted from db
-        deleted_repo = Session().query(Repository)\
+        deleted_repo = Session().query(Repository) \
             .filter(Repository.repo_name == repo_name).scalar()
 
-        self.assertEqual(deleted_repo, None)
+        assert deleted_repo == None
 
-        self.assertEqual(os.path.isdir(os.path.join(TESTS_TMP_PATH, repo_name)),
-                                  False)
+        assert os.path.isdir(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name)) == False
 
     def test_delete_non_ascii(self):
         self.log_user()
         non_ascii = "ąęł"
-        repo_name = "%s%s" % (self.NEW_REPO, non_ascii)
-        repo_name_unicode = repo_name.decode('utf8')
+        repo_name = "%s%s" % (safe_str(self.NEW_REPO), non_ascii)
+        repo_name_unicode = safe_unicode(repo_name)
         description = 'description for newly created repo' + non_ascii
-        description_unicode = description.decode('utf8')
+        description_unicode = safe_unicode(description)
         response = self.app.post(url('repos'),
                         fixture._get_repo_create_params(repo_private=False,
                                                 repo_name=repo_name,
@@ -431,16 +386,16 @@
                                                 _authentication_token=self.authentication_token()))
         ## run the check page that triggers the flash message
         response = self.app.get(url('repo_check_home', repo_name=repo_name))
-        self.assertEqual(response.json, {u'result': True})
+        assert response.json == {u'result': True}
         self.checkSessionFlash(response,
                                u'Created repository <a href="/%s">%s</a>'
                                % (urllib.quote(repo_name), repo_name_unicode))
         # test if the repo was created in the database
-        new_repo = Session().query(Repository)\
+        new_repo = Session().query(Repository) \
             .filter(Repository.repo_name == repo_name_unicode).one()
 
-        self.assertEqual(new_repo.repo_name, repo_name_unicode)
-        self.assertEqual(new_repo.description, description_unicode)
+        assert new_repo.repo_name == repo_name_unicode
+        assert new_repo.description == description_unicode
 
         # test if the repository is visible in the list ?
         response = self.app.get(url('summary_home', repo_name=repo_name))
@@ -449,23 +404,22 @@
 
         # test if the repository was created on filesystem
         try:
-            vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
+            vcs.get_repo(safe_str(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name_unicode)))
         except vcs.exceptions.VCSError:
-            self.fail('no repo %s in filesystem' % repo_name)
+            pytest.fail('no repo %s in filesystem' % repo_name)
 
         response = self.app.post(url('delete_repo', repo_name=repo_name),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+            params={'_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'Deleted repository %s' % (repo_name_unicode))
         response.follow()
 
         #check if repo was deleted from db
-        deleted_repo = Session().query(Repository)\
+        deleted_repo = Session().query(Repository) \
             .filter(Repository.repo_name == repo_name_unicode).scalar()
 
-        self.assertEqual(deleted_repo, None)
+        assert deleted_repo == None
 
-        self.assertEqual(os.path.isdir(os.path.join(TESTS_TMP_PATH, repo_name)),
-                                  False)
+        assert os.path.isdir(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name_unicode)) == False
 
     def test_delete_repo_with_group(self):
         #TODO:
@@ -473,7 +427,7 @@
 
     def test_delete_browser_fakeout(self):
         response = self.app.post(url('delete_repo', repo_name=self.REPO),
-                                 params=dict(_method='delete', _authentication_token=self.authentication_token()))
+                                 params=dict(_authentication_token=self.authentication_token()))
 
     def test_show(self):
         self.log_user()
@@ -486,43 +440,42 @@
         self.log_user()
         #initially repository perm should be read
         perm = _get_permission_for_user(user='default', repo=self.REPO)
-        self.assertTrue(len(perm), 1)
-        self.assertEqual(perm[0].permission.permission_name, 'repository.read')
-        self.assertEqual(Repository.get_by_repo_name(self.REPO).private, False)
+        assert len(perm), 1
+        assert perm[0].permission.permission_name == 'repository.read'
+        assert Repository.get_by_repo_name(self.REPO).private == False
 
-        response = self.app.put(url('put_repo', repo_name=self.REPO),
+        response = self.app.post(url('update_repo', repo_name=self.REPO),
                         fixture._get_repo_create_params(repo_private=1,
                                                 repo_name=self.REPO,
                                                 repo_type=self.REPO_TYPE,
-                                                user=TEST_USER_ADMIN_LOGIN,
+                                                owner=TEST_USER_ADMIN_LOGIN,
                                                 _authentication_token=self.authentication_token()))
         self.checkSessionFlash(response,
                                msg='Repository %s updated successfully' % (self.REPO))
-        self.assertEqual(Repository.get_by_repo_name(self.REPO).private, True)
+        assert Repository.get_by_repo_name(self.REPO).private == True
 
         #now the repo default permission should be None
         perm = _get_permission_for_user(user='default', repo=self.REPO)
-        self.assertTrue(len(perm), 1)
-        self.assertEqual(perm[0].permission.permission_name, 'repository.none')
+        assert len(perm), 1
+        assert perm[0].permission.permission_name == 'repository.none'
 
-        response = self.app.put(url('put_repo', repo_name=self.REPO),
+        response = self.app.post(url('update_repo', repo_name=self.REPO),
                         fixture._get_repo_create_params(repo_private=False,
                                                 repo_name=self.REPO,
                                                 repo_type=self.REPO_TYPE,
-                                                user=TEST_USER_ADMIN_LOGIN,
+                                                owner=TEST_USER_ADMIN_LOGIN,
                                                 _authentication_token=self.authentication_token()))
         self.checkSessionFlash(response,
                                msg='Repository %s updated successfully' % (self.REPO))
-        self.assertEqual(Repository.get_by_repo_name(self.REPO).private, False)
+        assert Repository.get_by_repo_name(self.REPO).private == False
 
         #we turn off private now the repo default permission should stay None
         perm = _get_permission_for_user(user='default', repo=self.REPO)
-        self.assertTrue(len(perm), 1)
-        self.assertEqual(perm[0].permission.permission_name, 'repository.none')
+        assert len(perm), 1
+        assert perm[0].permission.permission_name == 'repository.none'
 
         #update this permission back
         perm[0].permission = Permission.get_by_key('repository.read')
-        Session().add(perm[0])
         Session().commit()
 
     def test_set_repo_fork_has_no_self_id(self):
@@ -534,11 +487,11 @@
 
     def test_set_fork_of_other_repo(self):
         self.log_user()
-        other_repo = 'other_%s' % self.REPO_TYPE
+        other_repo = u'other_%s' % self.REPO_TYPE
         fixture.create_repo(other_repo, repo_type=self.REPO_TYPE)
         repo = Repository.get_by_repo_name(self.REPO)
         repo2 = Repository.get_by_repo_name(other_repo)
-        response = self.app.put(url('edit_repo_advanced_fork', repo_name=self.REPO),
+        response = self.app.post(url('edit_repo_advanced_fork', repo_name=self.REPO),
                                 params=dict(id_fork_of=repo2.repo_id, _authentication_token=self.authentication_token()))
         repo = Repository.get_by_repo_name(self.REPO)
         repo2 = Repository.get_by_repo_name(other_repo)
@@ -559,7 +512,7 @@
         self.log_user()
         repo = Repository.get_by_repo_name(self.REPO)
         repo2 = Repository.get_by_repo_name(self.OTHER_TYPE_REPO)
-        response = self.app.put(url('edit_repo_advanced_fork', repo_name=self.REPO),
+        response = self.app.post(url('edit_repo_advanced_fork', repo_name=self.REPO),
                                 params=dict(id_fork_of=repo2.repo_id, _authentication_token=self.authentication_token()))
         repo = Repository.get_by_repo_name(self.REPO)
         repo2 = Repository.get_by_repo_name(self.OTHER_TYPE_REPO)
@@ -569,7 +522,7 @@
     def test_set_fork_of_none(self):
         self.log_user()
         ## mark it as None
-        response = self.app.put(url('edit_repo_advanced_fork', repo_name=self.REPO),
+        response = self.app.post(url('edit_repo_advanced_fork', repo_name=self.REPO),
                                 params=dict(id_fork_of=None, _authentication_token=self.authentication_token()))
         repo = Repository.get_by_repo_name(self.REPO)
         repo2 = Repository.get_by_repo_name(self.OTHER_TYPE_REPO)
@@ -581,7 +534,7 @@
     def test_set_fork_of_same_repo(self):
         self.log_user()
         repo = Repository.get_by_repo_name(self.REPO)
-        response = self.app.put(url('edit_repo_advanced_fork', repo_name=self.REPO),
+        response = self.app.post(url('edit_repo_advanced_fork', repo_name=self.REPO),
                                 params=dict(id_fork_of=repo.repo_id, _authentication_token=self.authentication_token()))
         self.checkSessionFlash(response,
                                'An error occurred during this operation')
@@ -606,7 +559,7 @@
 
         user = User.get(usr['user_id'])
 
-        repo_name = self.NEW_REPO+'no_perms'
+        repo_name = self.NEW_REPO + u'no_perms'
         description = 'description for newly created repo'
         response = self.app.post(url('repos'),
                         fixture._get_repo_create_params(repo_private=False,
@@ -637,12 +590,13 @@
                                'Error creating repository %s' % repo_name)
         # repo must not be in db
         repo = Repository.get_by_repo_name(repo_name)
-        self.assertEqual(repo, None)
+        assert repo == None
 
         # repo must not be in filesystem !
-        self.assertFalse(os.path.isdir(os.path.join(TESTS_TMP_PATH, repo_name)))
+        assert not os.path.isdir(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name))
 
-class TestAdminReposControllerGIT(TestController, _BaseTest):
+
+class TestAdminReposControllerGIT(_BaseTestCase):
     REPO = GIT_REPO
     REPO_TYPE = 'git'
     NEW_REPO = NEW_GIT_REPO
@@ -650,7 +604,7 @@
     OTHER_TYPE = 'hg'
 
 
-class TestAdminReposControllerHG(TestController, _BaseTest):
+class TestAdminReposControllerHG(_BaseTestCase):
     REPO = HG_REPO
     REPO_TYPE = 'hg'
     NEW_REPO = NEW_HG_REPO
--- a/kallithea/tests/functional/test_admin_settings.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_admin_settings.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,7 +1,9 @@
 # -*- coding: utf-8 -*-
 
+import tempfile
+
 from kallithea.model.db import Setting, Ui
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.tests.fixture import Fixture
 
 fixture = Fixture()
@@ -37,31 +39,31 @@
         self.log_user()
         response = self.app.post(url('admin_settings_hooks'),
                                 params=dict(new_hook_ui_key='test_hooks_1',
-                                            new_hook_ui_value='cd /tmp',
+                                            new_hook_ui_value='cd %s' % tempfile.gettempdir(),
                                             _authentication_token=self.authentication_token()))
 
         response = response.follow()
         response.mustcontain('test_hooks_1')
-        response.mustcontain('cd /tmp')
+        response.mustcontain('cd %s' % tempfile.gettempdir())
 
     def test_create_custom_hook_delete(self):
         self.log_user()
         response = self.app.post(url('admin_settings_hooks'),
                                 params=dict(new_hook_ui_key='test_hooks_2',
-                                            new_hook_ui_value='cd /tmp2',
+                                            new_hook_ui_value='cd %s2' % tempfile.gettempdir(),
                                             _authentication_token=self.authentication_token()))
 
         response = response.follow()
         response.mustcontain('test_hooks_2')
-        response.mustcontain('cd /tmp2')
+        response.mustcontain('cd %s2' % tempfile.gettempdir())
 
-        hook_id = Ui.get_by_key('test_hooks_2').ui_id
+        hook_id = Ui.get_by_key('hooks', 'test_hooks_2').ui_id
         ## delete
         self.app.post(url('admin_settings_hooks'),
                         params=dict(hook_id=hook_id, _authentication_token=self.authentication_token()))
         response = self.app.get(url('admin_settings_hooks'))
         response.mustcontain(no=['test_hooks_2'])
-        response.mustcontain(no=['cd /tmp2'])
+        response.mustcontain(no=['cd %s2' % tempfile.gettempdir()])
 
     def test_index_search(self):
         self.log_user()
@@ -87,8 +89,7 @@
 
         self.checkSessionFlash(response, 'Updated application settings')
 
-        self.assertEqual(Setting
-                         .get_app_settings()['ga_code'], new_ga_code)
+        assert Setting.get_app_settings()['ga_code'] == new_ga_code
 
         response = response.follow()
         response.mustcontain("""_gaq.push(['_setAccount', '%s']);""" % new_ga_code)
@@ -108,8 +109,7 @@
                                  ))
 
         self.checkSessionFlash(response, 'Updated application settings')
-        self.assertEqual(Setting
-                        .get_app_settings()['ga_code'], new_ga_code)
+        assert Setting.get_app_settings()['ga_code'] == new_ga_code
 
         response = response.follow()
         response.mustcontain(no=["_gaq.push(['_setAccount', '%s']);" % new_ga_code])
@@ -129,8 +129,7 @@
                                  ))
 
         self.checkSessionFlash(response, 'Updated application settings')
-        self.assertEqual(Setting
-                        .get_app_settings()['captcha_private_key'], '1234567890')
+        assert Setting.get_app_settings()['captcha_private_key'] == '1234567890'
 
         response = self.app.get(url('register'))
         response.mustcontain('captcha')
@@ -150,8 +149,7 @@
                                  ))
 
         self.checkSessionFlash(response, 'Updated application settings')
-        self.assertEqual(Setting
-                        .get_app_settings()['captcha_private_key'], '')
+        assert Setting.get_app_settings()['captcha_private_key'] == ''
 
         response = self.app.get(url('register'))
         response.mustcontain(no=['captcha'])
@@ -173,9 +171,7 @@
                                 ))
 
             self.checkSessionFlash(response, 'Updated application settings')
-            self.assertEqual(Setting
-                             .get_app_settings()['title'],
-                             new_title.decode('utf-8'))
+            assert Setting.get_app_settings()['title'] == new_title.decode('utf-8')
 
             response = response.follow()
             response.mustcontain("""<div class="branding">%s</div>""" % new_title)
--- a/kallithea/tests/functional/test_admin_user_groups.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_admin_user_groups.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,9 +1,9 @@
 # -*- coding: utf-8 -*-
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.model.db import UserGroup, UserGroupToPerm, Permission
 from kallithea.model.meta import Session
 
-TEST_USER_GROUP = 'admins_test'
+TEST_USER_GROUP = u'admins_test'
 
 
 class TestAdminUsersGroupsController(TestController):
@@ -18,7 +18,7 @@
         users_group_name = TEST_USER_GROUP
         response = self.app.post(url('users_groups'),
                                  {'users_group_name': users_group_name,
-                                  'user_group_description': 'DESC',
+                                  'user_group_description': u'DESC',
                                   'active': True,
                                   '_authentication_token': self.authentication_token()})
         response.follow()
@@ -32,18 +32,18 @@
         response = self.app.get(url('new_users_group'))
 
     def test_update(self):
-        response = self.app.put(url('users_group', id=1), status=403)
+        response = self.app.post(url('update_users_group', id=1), status=403)
 
     def test_update_browser_fakeout(self):
-        response = self.app.post(url('users_group', id=1),
-                                 params=dict(_method='put', _authentication_token=self.authentication_token()))
+        response = self.app.post(url('update_users_group', id=1),
+                                 params=dict(_authentication_token=self.authentication_token()))
 
     def test_delete(self):
         self.log_user()
         users_group_name = TEST_USER_GROUP + 'another'
         response = self.app.post(url('users_groups'),
                                  {'users_group_name':users_group_name,
-                                  'user_group_description': 'DESC',
+                                  'user_group_description': u'DESC',
                                   'active': True,
                                   '_authentication_token': self.authentication_token()})
         response.follow()
@@ -51,23 +51,23 @@
         self.checkSessionFlash(response,
                                'Created user group ')
 
-        gr = Session().query(UserGroup)\
+        gr = Session().query(UserGroup) \
             .filter(UserGroup.users_group_name == users_group_name).one()
 
-        response = self.app.post(url('users_group', id=gr.users_group_id),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('delete_users_group', id=gr.users_group_id),
+            params={'_authentication_token': self.authentication_token()})
 
-        gr = Session().query(UserGroup)\
+        gr = Session().query(UserGroup) \
             .filter(UserGroup.users_group_name == users_group_name).scalar()
 
-        self.assertEqual(gr, None)
+        assert gr == None
 
     def test_default_perms_enable_repository_read_on_group(self):
         self.log_user()
         users_group_name = TEST_USER_GROUP + 'another2'
         response = self.app.post(url('users_groups'),
                                  {'users_group_name': users_group_name,
-                                  'user_group_description': 'DESC',
+                                  'user_group_description': u'DESC',
                                   'active': True,
                                   '_authentication_token': self.authentication_token()})
         response.follow()
@@ -76,8 +76,8 @@
         self.checkSessionFlash(response,
                                'Created user group ')
         ## ENABLE REPO CREATE ON A GROUP
-        response = self.app.put(url('edit_user_group_default_perms',
-                                    id=ug.users_group_id),
+        response = self.app.post(url('edit_user_group_default_perms_update',
+                                     id=ug.users_group_id),
                                  {'create_repo_perm': True,
                                   '_authentication_token': self.authentication_token()})
         response.follow()
@@ -87,18 +87,16 @@
         p3 = Permission.get_by_key('hg.fork.none')
         # check if user has this perms, they should be here since
         # defaults are on
-        perms = UserGroupToPerm.query()\
+        perms = UserGroupToPerm.query() \
             .filter(UserGroupToPerm.users_group == ug).all()
 
-        self.assertEqual(
-            sorted([[x.users_group_id, x.permission_id, ] for x in perms]),
-            sorted([[ug.users_group_id, p.permission_id],
+        assert sorted([[x.users_group_id, x.permission_id, ] for x in perms]) == sorted([[ug.users_group_id, p.permission_id],
                     [ug.users_group_id, p2.permission_id],
-                    [ug.users_group_id, p3.permission_id]]))
+                    [ug.users_group_id, p3.permission_id]])
 
         ## DISABLE REPO CREATE ON A GROUP
-        response = self.app.put(
-            url('edit_user_group_default_perms', id=ug.users_group_id),
+        response = self.app.post(
+            url('edit_user_group_default_perms_update', id=ug.users_group_id),
             params={'_authentication_token': self.authentication_token()})
 
         response.follow()
@@ -109,38 +107,36 @@
 
         # check if user has this perms, they should be here since
         # defaults are on
-        perms = UserGroupToPerm.query()\
+        perms = UserGroupToPerm.query() \
             .filter(UserGroupToPerm.users_group == ug).all()
 
-        self.assertEqual(
-            sorted([[x.users_group_id, x.permission_id, ] for x in perms]),
-            sorted([[ug.users_group_id, p.permission_id],
+        assert sorted([[x.users_group_id, x.permission_id, ] for x in perms]) == sorted([[ug.users_group_id, p.permission_id],
                     [ug.users_group_id, p2.permission_id],
-                    [ug.users_group_id, p3.permission_id]]))
+                    [ug.users_group_id, p3.permission_id]])
 
         # DELETE !
         ug = UserGroup.get_by_group_name(users_group_name)
         ugid = ug.users_group_id
-        response = self.app.post(url('users_group', id=ug.users_group_id),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('delete_users_group', id=ug.users_group_id),
+            params={'_authentication_token': self.authentication_token()})
         response = response.follow()
-        gr = Session().query(UserGroup)\
+        gr = Session().query(UserGroup) \
             .filter(UserGroup.users_group_name == users_group_name).scalar()
 
-        self.assertEqual(gr, None)
+        assert gr == None
         p = Permission.get_by_key('hg.create.repository')
-        perms = UserGroupToPerm.query()\
+        perms = UserGroupToPerm.query() \
             .filter(UserGroupToPerm.users_group_id == ugid).all()
         perms = [[x.users_group_id,
                   x.permission_id, ] for x in perms]
-        self.assertEqual(perms, [])
+        assert perms == []
 
     def test_default_perms_enable_repository_fork_on_group(self):
         self.log_user()
         users_group_name = TEST_USER_GROUP + 'another2'
         response = self.app.post(url('users_groups'),
                                  {'users_group_name': users_group_name,
-                                  'user_group_description': 'DESC',
+                                  'user_group_description': u'DESC',
                                   'active': True,
                                   '_authentication_token': self.authentication_token()})
         response.follow()
@@ -149,9 +145,9 @@
         self.checkSessionFlash(response,
                                'Created user group ')
         ## ENABLE REPO CREATE ON A GROUP
-        response = self.app.put(url('edit_user_group_default_perms',
-                                    id=ug.users_group_id),
-                                {'fork_repo_perm': True, '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('edit_user_group_default_perms_update',
+                                     id=ug.users_group_id),
+                                 {'fork_repo_perm': True, '_authentication_token': self.authentication_token()})
 
         response.follow()
         ug = UserGroup.get_by_group_name(users_group_name)
@@ -160,17 +156,15 @@
         p3 = Permission.get_by_key('hg.fork.repository')
         # check if user has this perms, they should be here since
         # defaults are on
-        perms = UserGroupToPerm.query()\
+        perms = UserGroupToPerm.query() \
             .filter(UserGroupToPerm.users_group == ug).all()
 
-        self.assertEqual(
-            sorted([[x.users_group_id, x.permission_id, ] for x in perms]),
-            sorted([[ug.users_group_id, p.permission_id],
+        assert sorted([[x.users_group_id, x.permission_id, ] for x in perms]) == sorted([[ug.users_group_id, p.permission_id],
                     [ug.users_group_id, p2.permission_id],
-                    [ug.users_group_id, p3.permission_id]]))
+                    [ug.users_group_id, p3.permission_id]])
 
         ## DISABLE REPO CREATE ON A GROUP
-        response = self.app.put(url('edit_user_group_default_perms', id=ug.users_group_id),
+        response = self.app.post(url('edit_user_group_default_perms_update', id=ug.users_group_id),
             params={'_authentication_token': self.authentication_token()})
 
         response.follow()
@@ -180,51 +174,31 @@
         p3 = Permission.get_by_key('hg.fork.none')
         # check if user has this perms, they should be here since
         # defaults are on
-        perms = UserGroupToPerm.query()\
+        perms = UserGroupToPerm.query() \
             .filter(UserGroupToPerm.users_group == ug).all()
 
-        self.assertEqual(
-            sorted([[x.users_group_id, x.permission_id, ] for x in perms]),
-            sorted([[ug.users_group_id, p.permission_id],
+        assert sorted([[x.users_group_id, x.permission_id, ] for x in perms]) == sorted([[ug.users_group_id, p.permission_id],
                     [ug.users_group_id, p2.permission_id],
-                    [ug.users_group_id, p3.permission_id]]))
+                    [ug.users_group_id, p3.permission_id]])
 
         # DELETE !
         ug = UserGroup.get_by_group_name(users_group_name)
         ugid = ug.users_group_id
-        response = self.app.post(url('users_group', id=ug.users_group_id),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('delete_users_group', id=ug.users_group_id),
+            params={'_authentication_token': self.authentication_token()})
         response = response.follow()
-        gr = Session().query(UserGroup)\
+        gr = Session().query(UserGroup) \
                            .filter(UserGroup.users_group_name ==
                                    users_group_name).scalar()
 
-        self.assertEqual(gr, None)
+        assert gr == None
         p = Permission.get_by_key('hg.fork.repository')
-        perms = UserGroupToPerm.query()\
+        perms = UserGroupToPerm.query() \
             .filter(UserGroupToPerm.users_group_id == ugid).all()
         perms = [[x.users_group_id,
                   x.permission_id, ] for x in perms]
-        self.assertEqual(
-            perms,
-            []
-        )
+        assert perms == []
 
     def test_delete_browser_fakeout(self):
-        response = self.app.post(url('users_group', id=1),
-                                 params=dict(_method='delete', _authentication_token=self.authentication_token()))
-
-    def test_show(self):
-        response = self.app.get(url('users_group', id=1))
-
-    def test_edit(self):
-        response = self.app.get(url('edit_users_group', id=1))
-
-    def test_assign_members(self):
-        pass
-
-    def test_add_create_permission(self):
-        pass
-
-    def test_revoke_members(self):
-        pass
+        response = self.app.post(url('delete_users_group', id=1),
+                                 params=dict(_authentication_token=self.authentication_token()))
--- a/kallithea/tests/functional/test_admin_users.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_admin_users.py	Fri Nov 18 01:11:13 2016 +0100
@@ -12,19 +12,35 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-from sqlalchemy.orm.exc import NoResultFound
+from sqlalchemy.orm.exc import NoResultFound, ObjectDeletedError
 
-from kallithea.tests import *
+import pytest
+from kallithea.tests.base import *
 from kallithea.tests.fixture import Fixture
+from kallithea.controllers.admin.users import UsersController
 from kallithea.model.db import User, Permission, UserIpMap, UserApiKeys
 from kallithea.lib.auth import check_password
 from kallithea.model.user import UserModel
 from kallithea.model import validators
 from kallithea.lib import helpers as h
 from kallithea.model.meta import Session
+from webob.exc import HTTPNotFound
 
 fixture = Fixture()
 
+@pytest.yield_fixture
+def user_and_repo_group_fail():
+    username = 'repogrouperr'
+    groupname = u'repogroup_fail'
+    user = fixture.create_user(name=username)
+    repo_group = fixture.create_repo_group(name=groupname, cur_user=username)
+    yield user, repo_group
+    # cleanup
+    try:
+        fixture.destroy_repo_group(repo_group)
+    except ObjectDeletedError:
+        # delete already succeeded in test body
+        pass
 
 class TestAdminUsersController(TestController):
     test_user_1 = 'testme'
@@ -38,18 +54,18 @@
     def test_index(self):
         self.log_user()
         response = self.app.get(url('users'))
-        # Test response...
+        # TODO: Test response...
 
     def test_create(self):
         self.log_user()
         username = 'newtestuser'
         password = 'test12'
         password_confirmation = password
-        name = 'name'
-        lastname = 'lastname'
+        name = u'name'
+        lastname = u'lastname'
         email = 'mail@example.com'
 
-        response = self.app.post(url('users'),
+        response = self.app.post(url('new_user'),
             {'username': username,
              'password': password,
              'password_confirmation': password_confirmation,
@@ -60,38 +76,39 @@
              'extern_type': 'internal',
              'email': email,
              '_authentication_token': self.authentication_token()})
+        # 302 Found
+        # The resource was found at http://localhost/_admin/users/5/edit; you should be redirected automatically.
 
-        self.checkSessionFlash(response, '''Created user <a href="/_admin/users/''')
-        self.checkSessionFlash(response, '''/edit">%s</a>''' % (username))
+        self.checkSessionFlash(response, '''Created user %s''' % username)
 
-        new_user = Session().query(User).\
+        response = response.follow()
+        response.mustcontain("""%s user settings""" % username) # in <title>
+
+        new_user = Session().query(User). \
             filter(User.username == username).one()
 
-        self.assertEqual(new_user.username, username)
-        self.assertEqual(check_password(password, new_user.password), True)
-        self.assertEqual(new_user.name, name)
-        self.assertEqual(new_user.lastname, lastname)
-        self.assertEqual(new_user.email, email)
-
-        response.follow()
-        response = response.follow()
-        response.mustcontain("""newtestuser""")
+        assert new_user.username == username
+        assert check_password(password, new_user.password) == True
+        assert new_user.name == name
+        assert new_user.lastname == lastname
+        assert new_user.email == email
 
     def test_create_err(self):
         self.log_user()
         username = 'new_user'
         password = ''
-        name = 'name'
-        lastname = 'lastname'
+        name = u'name'
+        lastname = u'lastname'
         email = 'errmail.example.com'
 
-        response = self.app.post(url('users'), {'username': username,
-                                               'password': password,
-                                               'name': name,
-                                               'active': False,
-                                               'lastname': lastname,
-                                               'email': email,
-                                               '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('new_user'),
+            {'username': username,
+             'password': password,
+             'name': name,
+             'active': False,
+             'lastname': lastname,
+             'email': email,
+             '_authentication_token': self.authentication_token()})
 
         msg = validators.ValidUsername(False, {})._messages['system_invalid_username']
         msg = h.html_escape(msg % {'username': 'new_user'})
@@ -102,13 +119,14 @@
         def get_user():
             Session().query(User).filter(User.username == username).one()
 
-        self.assertRaises(NoResultFound, get_user), 'found user in database'
+        with pytest.raises(NoResultFound):
+            get_user(), 'found user in database'
 
     def test_new(self):
         self.log_user()
         response = self.app.get(url('new_user'))
 
-    @parameterized.expand(
+    @parametrize('name,attrs',
         [('firstname', {'firstname': 'new_username'}),
          ('lastname', {'lastname': 'new_username'}),
          ('admin', {'admin': True}),
@@ -148,7 +166,7 @@
                                           # so we use creation data
 
         params.update({'_authentication_token': self.authentication_token()})
-        response = self.app.put(url('user', id=usr.user_id), params)
+        response = self.app.post(url('update_user', id=usr.user_id), params)
         self.checkSessionFlash(response, 'User updated successfully')
         params.pop('_authentication_token')
 
@@ -157,7 +175,7 @@
         updated_params.update({'password_confirmation': ''})
         updated_params.update({'new_password': ''})
 
-        self.assertEqual(params, updated_params)
+        assert params == updated_params
 
     def test_delete(self):
         self.log_user()
@@ -165,50 +183,47 @@
 
         fixture.create_user(name=username)
 
-        new_user = Session().query(User)\
+        new_user = Session().query(User) \
             .filter(User.username == username).one()
-        response = self.app.post(url('user', id=new_user.user_id),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('delete_user', id=new_user.user_id),
+            params={'_authentication_token': self.authentication_token()})
 
         self.checkSessionFlash(response, 'Successfully deleted user')
 
     def test_delete_repo_err(self):
         self.log_user()
         username = 'repoerr'
-        reponame = 'repoerr_fail'
+        reponame = u'repoerr_fail'
 
         fixture.create_user(name=username)
         fixture.create_repo(name=reponame, cur_user=username)
 
-        new_user = Session().query(User)\
+        new_user = Session().query(User) \
             .filter(User.username == username).one()
-        response = self.app.post(url('user', id=new_user.user_id),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('delete_user', id=new_user.user_id),
+            params={'_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'User "%s" still '
                                'owns 1 repositories and cannot be removed. '
                                'Switch owners or remove those repositories: '
                                '%s' % (username, reponame))
 
         response = self.app.post(url('delete_repo', repo_name=reponame),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+            params={'_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'Deleted repository %s' % reponame)
 
-        response = self.app.post(url('user', id=new_user.user_id),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('delete_user', id=new_user.user_id),
+            params={'_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'Successfully deleted user')
 
-    def test_delete_repo_group_err(self):
+    def test_delete_repo_group_err(self, user_and_repo_group_fail):
         self.log_user()
         username = 'repogrouperr'
-        groupname = 'repogroup_fail'
-
-        fixture.create_user(name=username)
-        fixture.create_repo_group(name=groupname, cur_user=username)
+        groupname = u'repogroup_fail'
 
-        new_user = Session().query(User)\
+        new_user = Session().query(User) \
             .filter(User.username == username).one()
-        response = self.app.post(url('user', id=new_user.user_id),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('delete_user', id=new_user.user_id),
+            params={'_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'User "%s" still '
                                'owns 1 repository groups and cannot be removed. '
                                'Switch owners or remove those repository groups: '
@@ -219,25 +234,25 @@
         # response = self.app.get(url('repos_groups', id=rg.group_id))
 
         response = self.app.post(url('delete_repo_group', group_name=groupname),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+            params={'_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'Removed repository group %s' % groupname)
 
-        response = self.app.post(url('user', id=new_user.user_id),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('delete_user', id=new_user.user_id),
+            params={'_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'Successfully deleted user')
 
     def test_delete_user_group_err(self):
         self.log_user()
         username = 'usergrouperr'
-        groupname = 'usergroup_fail'
+        groupname = u'usergroup_fail'
 
         fixture.create_user(name=username)
         ug = fixture.create_user_group(name=groupname, cur_user=username)
 
-        new_user = Session().query(User)\
+        new_user = Session().query(User) \
             .filter(User.username == username).one()
-        response = self.app.post(url('user', id=new_user.user_id),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('delete_user', id=new_user.user_id),
+            params={'_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'User "%s" still '
                                'owns 1 user groups and cannot be removed. '
                                'Switch owners or remove those user groups: '
@@ -249,13 +264,10 @@
 
         fixture.destroy_user_group(ug.users_group_id)
 
-        response = self.app.post(url('user', id=new_user.user_id),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('delete_user', id=new_user.user_id),
+            params={'_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'Successfully deleted user')
 
-    def test_show(self):
-        response = self.app.get(url('user', id=1))
-
     def test_edit(self):
         self.log_user()
         user = User.get_by_username(TEST_USER_ADMIN_LOGIN)
@@ -267,27 +279,26 @@
         perm_create = Permission.get_by_key('hg.create.repository')
 
         user = UserModel().create_or_update(username='dummy', password='qwe',
-                                            email='dummy', firstname='a',
-                                            lastname='b')
+                                            email='dummy', firstname=u'a',
+                                            lastname=u'b')
         Session().commit()
         uid = user.user_id
 
         try:
             #User should have None permission on creation repository
-            self.assertEqual(UserModel().has_perm(user, perm_none), False)
-            self.assertEqual(UserModel().has_perm(user, perm_create), False)
+            assert UserModel().has_perm(user, perm_none) == False
+            assert UserModel().has_perm(user, perm_create) == False
 
-            response = self.app.post(url('edit_user_perms', id=uid),
-                                     params=dict(_method='put',
-                                                 create_repo_perm=True,
+            response = self.app.post(url('edit_user_perms_update', id=uid),
+                                     params=dict(create_repo_perm=True,
                                                  _authentication_token=self.authentication_token()))
 
             perm_none = Permission.get_by_key('hg.create.none')
             perm_create = Permission.get_by_key('hg.create.repository')
 
             #User should have None permission on creation repository
-            self.assertEqual(UserModel().has_perm(uid, perm_none), False)
-            self.assertEqual(UserModel().has_perm(uid, perm_create), True)
+            assert UserModel().has_perm(uid, perm_none) == False
+            assert UserModel().has_perm(uid, perm_create) == True
         finally:
             UserModel().delete(uid)
             Session().commit()
@@ -298,25 +309,25 @@
         perm_create = Permission.get_by_key('hg.create.repository')
 
         user = UserModel().create_or_update(username='dummy', password='qwe',
-                                            email='dummy', firstname='a',
-                                            lastname='b')
+                                            email='dummy', firstname=u'a',
+                                            lastname=u'b')
         Session().commit()
         uid = user.user_id
 
         try:
             #User should have None permission on creation repository
-            self.assertEqual(UserModel().has_perm(user, perm_none), False)
-            self.assertEqual(UserModel().has_perm(user, perm_create), False)
+            assert UserModel().has_perm(user, perm_none) == False
+            assert UserModel().has_perm(user, perm_create) == False
 
-            response = self.app.post(url('edit_user_perms', id=uid),
-                                     params=dict(_method='put', _authentication_token=self.authentication_token()))
+            response = self.app.post(url('edit_user_perms_update', id=uid),
+                                     params=dict(_authentication_token=self.authentication_token()))
 
             perm_none = Permission.get_by_key('hg.create.none')
             perm_create = Permission.get_by_key('hg.create.repository')
 
             #User should have None permission on creation repository
-            self.assertEqual(UserModel().has_perm(uid, perm_none), True)
-            self.assertEqual(UserModel().has_perm(uid, perm_create), False)
+            assert UserModel().has_perm(uid, perm_none) == True
+            assert UserModel().has_perm(uid, perm_create) == False
         finally:
             UserModel().delete(uid)
             Session().commit()
@@ -327,27 +338,26 @@
         perm_fork = Permission.get_by_key('hg.fork.repository')
 
         user = UserModel().create_or_update(username='dummy', password='qwe',
-                                            email='dummy', firstname='a',
-                                            lastname='b')
+                                            email='dummy', firstname=u'a',
+                                            lastname=u'b')
         Session().commit()
         uid = user.user_id
 
         try:
             #User should have None permission on creation repository
-            self.assertEqual(UserModel().has_perm(user, perm_none), False)
-            self.assertEqual(UserModel().has_perm(user, perm_fork), False)
+            assert UserModel().has_perm(user, perm_none) == False
+            assert UserModel().has_perm(user, perm_fork) == False
 
-            response = self.app.post(url('edit_user_perms', id=uid),
-                                     params=dict(_method='put',
-                                                 create_repo_perm=True,
+            response = self.app.post(url('edit_user_perms_update', id=uid),
+                                     params=dict(create_repo_perm=True,
                                                  _authentication_token=self.authentication_token()))
 
             perm_none = Permission.get_by_key('hg.create.none')
             perm_create = Permission.get_by_key('hg.create.repository')
 
             #User should have None permission on creation repository
-            self.assertEqual(UserModel().has_perm(uid, perm_none), False)
-            self.assertEqual(UserModel().has_perm(uid, perm_create), True)
+            assert UserModel().has_perm(uid, perm_none) == False
+            assert UserModel().has_perm(uid, perm_create) == True
         finally:
             UserModel().delete(uid)
             Session().commit()
@@ -358,25 +368,25 @@
         perm_fork = Permission.get_by_key('hg.fork.repository')
 
         user = UserModel().create_or_update(username='dummy', password='qwe',
-                                            email='dummy', firstname='a',
-                                            lastname='b')
+                                            email='dummy', firstname=u'a',
+                                            lastname=u'b')
         Session().commit()
         uid = user.user_id
 
         try:
             #User should have None permission on creation repository
-            self.assertEqual(UserModel().has_perm(user, perm_none), False)
-            self.assertEqual(UserModel().has_perm(user, perm_fork), False)
+            assert UserModel().has_perm(user, perm_none) == False
+            assert UserModel().has_perm(user, perm_fork) == False
 
-            response = self.app.post(url('edit_user_perms', id=uid),
-                                     params=dict(_method='put', _authentication_token=self.authentication_token()))
+            response = self.app.post(url('edit_user_perms_update', id=uid),
+                                     params=dict(_authentication_token=self.authentication_token()))
 
             perm_none = Permission.get_by_key('hg.create.none')
             perm_create = Permission.get_by_key('hg.create.repository')
 
             #User should have None permission on creation repository
-            self.assertEqual(UserModel().has_perm(uid, perm_none), True)
-            self.assertEqual(UserModel().has_perm(uid, perm_create), False)
+            assert UserModel().has_perm(uid, perm_none) == True
+            assert UserModel().has_perm(uid, perm_create) == False
         finally:
             UserModel().delete(uid)
             Session().commit()
@@ -387,7 +397,7 @@
         response = self.app.get(url('edit_user_ips', id=user.user_id))
         response.mustcontain('All IP addresses are allowed')
 
-    @parameterized.expand([
+    @parametrize('test_name,ip,ip_range,failure', [
         ('127/24', '127.0.0.1/24', '127.0.0.0 - 127.0.0.255', False),
         ('10/32', '10.0.0.10/32', '10.0.0.10 - 10.0.0.10', False),
         ('0/16', '0.0.0.0/16', '0.0.0.0 - 0.0.255.255', False),
@@ -395,13 +405,13 @@
         ('127_bad_mask', '127.0.0.1/99', '127.0.0.1 - 127.0.0.1', True),
         ('127_bad_ip', 'foobar', 'foobar', True),
     ])
-    def test_add_ip(self, test_name, ip, ip_range, failure):
+    def test_add_ip(self, test_name, ip, ip_range, failure, auto_clear_ip_permissions):
         self.log_user()
         user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
         user_id = user.user_id
 
-        response = self.app.put(url('edit_user_ips', id=user_id),
-                                params=dict(new_ip=ip, _authentication_token=self.authentication_token()))
+        response = self.app.post(url('edit_user_ips_update', id=user_id),
+                                 params=dict(new_ip=ip, _authentication_token=self.authentication_token()))
 
         if failure:
             self.checkSessionFlash(response, 'Please enter a valid IPv4 or IPv6 address')
@@ -414,12 +424,7 @@
             response.mustcontain(ip)
             response.mustcontain(ip_range)
 
-        ## cleanup
-        for del_ip in UserIpMap.query().filter(UserIpMap.user_id == user_id).all():
-            Session().delete(del_ip)
-            Session().commit()
-
-    def test_delete_ip(self):
+    def test_delete_ip(self, auto_clear_ip_permissions):
         self.log_user()
         user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
         user_id = user.user_id
@@ -433,8 +438,8 @@
         response.mustcontain(ip)
         response.mustcontain(ip_range)
 
-        self.app.post(url('edit_user_ips', id=user_id),
-                      params=dict(_method='delete', del_ip_id=new_ip_id, _authentication_token=self.authentication_token()))
+        self.app.post(url('edit_user_ips_delete', id=user_id),
+                      params=dict(del_ip_id=new_ip_id, _authentication_token=self.authentication_token()))
 
         response = self.app.get(url('edit_user_ips', id=user_id))
         response.mustcontain('All IP addresses are allowed')
@@ -449,7 +454,7 @@
         response.mustcontain(user.api_key)
         response.mustcontain('Expires: Never')
 
-    @parameterized.expand([
+    @parametrize('desc,lifetime', [
         ('forever', -1),
         ('5mins', 60*5),
         ('30days', 60*60*24*30),
@@ -459,7 +464,7 @@
         user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
         user_id = user.user_id
 
-        response = self.app.post(url('edit_user_api_keys', id=user_id),
+        response = self.app.post(url('edit_user_api_keys_update', id=user_id),
                  {'description': desc, 'lifetime': lifetime, '_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'API key successfully created')
         try:
@@ -477,20 +482,20 @@
         user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
         user_id = user.user_id
 
-        response = self.app.post(url('edit_user_api_keys', id=user_id),
+        response = self.app.post(url('edit_user_api_keys_update', id=user_id),
                 {'description': 'desc', 'lifetime': -1, '_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'API key successfully created')
         response = response.follow()
 
         #now delete our key
         keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all()
-        self.assertEqual(1, len(keys))
+        assert 1 == len(keys)
 
-        response = self.app.post(url('edit_user_api_keys', id=user_id),
-                 {'_method': 'delete', 'del_api_key': keys[0].api_key, '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('edit_user_api_keys_delete', id=user_id),
+                 {'del_api_key': keys[0].api_key, '_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'API key successfully deleted')
         keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all()
-        self.assertEqual(0, len(keys))
+        assert 0 == len(keys)
 
     def test_reset_main_api_key(self):
         self.log_user()
@@ -501,35 +506,29 @@
         response.mustcontain(api_key)
         response.mustcontain('Expires: Never')
 
-        response = self.app.post(url('edit_user_api_keys', id=user_id),
-                 {'_method': 'delete', 'del_api_key_builtin': api_key, '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('edit_user_api_keys_delete', id=user_id),
+                 {'del_api_key_builtin': api_key, '_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'API key successfully reset')
         response = response.follow()
         response.mustcontain(no=[api_key])
 
-# TODO To be uncommented when pytest is the test runner
-#import pytest
-#from kallithea.controllers.admin.users import UsersController
-#class TestAdminUsersController_unittest(object):
-#    """
-#    Unit tests for the users controller
-#    These are in a separate class, not deriving from TestController (and thus
-#    unittest.TestCase), to be able to benefit from pytest features like
-#    monkeypatch.
-#    """
-#    def test_get_user_or_raise_if_default(self, monkeypatch):
-#        # flash complains about an unexisting session
-#        def flash_mock(*args, **kwargs):
-#            pass
-#        monkeypatch.setattr(h, 'flash', flash_mock)
-#
-#        u = UsersController()
-#        # a regular user should work correctly
-#        user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
-#        assert u._get_user_or_raise_if_default(user.user_id) == user
-#        # the default user should raise
-#        with pytest.raises(HTTPNotFound):
-#            u._get_user_or_raise_if_default(User.get_default_user().user_id)
+
+class TestAdminUsersController_unittest(object):
+    """ Unit tests for the users controller """
+
+    def test_get_user_or_raise_if_default(self, monkeypatch):
+        # flash complains about an non-existing session
+        def flash_mock(*args, **kwargs):
+            pass
+        monkeypatch.setattr(h, 'flash', flash_mock)
+
+        u = UsersController()
+        # a regular user should work correctly
+        user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
+        assert u._get_user_or_raise_if_default(user.user_id) == user
+        # the default user should raise
+        with pytest.raises(HTTPNotFound):
+            u._get_user_or_raise_if_default(User.get_default_user().user_id)
 
 
 class TestAdminUsersControllerForDefaultUser(TestController):
@@ -556,14 +555,14 @@
     def test_add_api_keys_default_user(self):
         self.log_user()
         user = User.get_default_user()
-        response = self.app.post(url('edit_user_api_keys', id=user.user_id),
-                 {'_method': 'put', '_authentication_token': self.authentication_token()}, status=404)
+        response = self.app.post(url('edit_user_api_keys_update', id=user.user_id),
+                 {'_authentication_token': self.authentication_token()}, status=404)
 
     def test_delete_api_keys_default_user(self):
         self.log_user()
         user = User.get_default_user()
-        response = self.app.post(url('edit_user_api_keys', id=user.user_id),
-                 {'_method': 'delete', '_authentication_token': self.authentication_token()}, status=404)
+        response = self.app.post(url('edit_user_api_keys_delete', id=user.user_id),
+                 {'_authentication_token': self.authentication_token()}, status=404)
 
     # Permissions
     def test_edit_perms_default_user(self):
@@ -574,8 +573,8 @@
     def test_update_perms_default_user(self):
         self.log_user()
         user = User.get_default_user()
-        response = self.app.post(url('edit_user_perms', id=user.user_id),
-                 {'_method': 'put', '_authentication_token': self.authentication_token()}, status=404)
+        response = self.app.post(url('edit_user_perms_update', id=user.user_id),
+                 {'_authentication_token': self.authentication_token()}, status=404)
 
     # Emails
     def test_edit_emails_default_user(self):
@@ -586,14 +585,14 @@
     def test_add_emails_default_user(self):
         self.log_user()
         user = User.get_default_user()
-        response = self.app.post(url('edit_user_emails', id=user.user_id),
-                 {'_method': 'put', '_authentication_token': self.authentication_token()}, status=404)
+        response = self.app.post(url('edit_user_emails_update', id=user.user_id),
+                 {'_authentication_token': self.authentication_token()}, status=404)
 
     def test_delete_emails_default_user(self):
         self.log_user()
         user = User.get_default_user()
-        response = self.app.post(url('edit_user_emails', id=user.user_id),
-                 {'_method': 'delete', '_authentication_token': self.authentication_token()}, status=404)
+        response = self.app.post(url('edit_user_emails_delete', id=user.user_id),
+                 {'_authentication_token': self.authentication_token()}, status=404)
 
     # IP addresses
     # Add/delete of IP addresses for the default user is used to maintain
--- a/kallithea/tests/functional/test_branches.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,20 +0,0 @@
-from kallithea.tests import *
-
-
-class TestBranchesController(TestController):
-
-    def test_index_hg(self):
-        self.log_user()
-        response = self.app.get(url(controller='branches',
-                                    action='index', repo_name=HG_REPO))
-        response.mustcontain("""<a href="/%s/changelog?branch=default">default</a>""" % HG_REPO)
-
-        # closed branches
-        response.mustcontain("""<a href="/%s/changelog?branch=git">git [closed]</a>""" % HG_REPO)
-        response.mustcontain("""<a href="/%s/changelog?branch=web">web [closed]</a>""" % HG_REPO)
-
-    def test_index_git(self):
-        self.log_user()
-        response = self.app.get(url(controller='branches',
-                                    action='index', repo_name=GIT_REPO))
-        response.mustcontain("""<a href="/%s/changelog?branch=master">master</a>""" % GIT_REPO)
--- a/kallithea/tests/functional/test_changelog.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_changelog.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 
 
 class TestChangelogController(TestController):
@@ -17,10 +17,12 @@
         )
         #rev 640: code garden
         response.mustcontain(
-            """<span class="changeset_hash">r640:0a4e54a44604</span>"""
+            """<a class="changeset_hash" href="/%s/changeset/0a4e54a4460401d6dbbd6a3604b17cd2b3606b82">r640:0a4e54a44604</a>""" % HG_REPO
         )
         response.mustcontain("""code garden""")
 
+        response.mustcontain("""var jsdata = [[[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 1, 2, 0], [0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0], [1, 1, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 2, 0], [1, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 1, 3, 0], [0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 3, 0]], 0, 0, 0, 0, 0, 0], [[1, 3], [[0, 0, 2, 0], [1, 1, 3, 0]], 0, 0, 0, 0, 0, 0], [[1, 3], [[0, 0, 2, 0], [1, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 1, 4, 0], [0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[1, 4], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[1, 4], [[0, 0, 2, 0], [1, 1, 4, 0], [1, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[1, 4], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[1, 4], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[1, 4], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[1, 4], [[0, 0, 2, 0], [1, 1, 4, 0], [1, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[1, 4], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[1, 4], [[0, 0, 2, 0], [1, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 1, 5, 0], [0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 5, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 5, 0]], 0, 0, 0, 0, 0, 0], [[1, 5], [[0, 0, 2, 0], [1, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 1, 6, 0], [0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 6, 0]], 0, 0, 0, 0, 0, 0], [[1, 6], [[0, 0, 2, 0], [1, 1, 6, 0]], 0, 0, 0, 0, 0, 0], [[1, 6], [[0, 0, 2, 0], [1, 1, 6, 0], [1, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 6, 0]], 0, 0, 0, 0, 0, 0], [[1, 6], [[0, 0, 2, 0], [1, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 1, 7, 0], [0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 7, 0]], 0, 0, 0, 0, 0, 0], [[1, 7], [[0, 0, 2, 0], [1, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 1, 8, 0], [0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 8, 0]], 0, 0, 0, 0, 0, 0], [[1, 8], [[0, 0, 2, 0], [1, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 1, 9, 0], [0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 1, 10, 0], [0, 0, 2, 0], [1, 2, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 10, 0], [2, 2, 9, 0]], 0, 0, 0, 0, 0, 0], [[2, 9], [[0, 0, 2, 0], [1, 1, 10, 0], [2, 1, 10, 0]], 0, 0, 0, 0, 0, 0], [[1, 10], [[0, 0, 2, 0], [1, 1, 10, 0]], 0, 0, 0, 0, 0, 0], [[1, 10], [[0, 0, 2, 0], [1, 1, 10, 0]], 0, 0, 0, 0, 0, 0], [[1, 10], [[0, 0, 2, 0], [1, 1, 10, 0]], 0, 0, 0, 0, 0, 0], [[1, 10], [[0, 0, 2, 0], [1, 1, 10, 0]], 0, 0, 0, 0, 0, 0], [[1, 10], [[0, 0, 2, 0], [1, 1, 10, 0]], 0, 0, 0, 0, 0, 0], [[1, 10], [[0, 0, 2, 0], [1, 1, 10, 0]], 0, 0, 0, 0, 0, 0], [[1, 10], [[0, 0, 2, 0], [1, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[1, 11], [[0, 0, 2, 0], [1, 1, 11, 0]], 1, 0, 0, 0, 0, 0], [[2, 12], [[0, 0, 2, 0], [2, 1, 12, 0]], 1, 0, 0, 0, 0, 0], [[0, 2], [[0, 1, 13, 0], [0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 13, 0]], 0, 0, 0, 0, 0, 0], [[1, 13], [[0, 0, 2, 0], [1, 1, 13, 0], [1, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 13, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 13, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 13, 0]], 0, 0, 0, 0, 0, 0], [[1, 13], [[0, 0, 2, 0], [1, 1, 13, 0], [1, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 1, 14, 0], [0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0]], 0, 0, 0, 0, 0, 0]];""")
+
     def test_index_pagination_hg(self):
         self.log_user()
         #pagination
@@ -46,7 +48,7 @@
         )
 
         response.mustcontain(
-            """<span class="changeset_hash">r539:22baf968d547</span>"""
+            """<a class="changeset_hash" href="/vcs_test_hg/changeset/22baf968d547386b9516965ce89d189665003a31">r539:22baf968d547</a>"""
         )
 
     def test_index_git(self):
@@ -63,14 +65,16 @@
         )
 
         response.mustcontain(
-            """<span class="changeset_hash">r613:95f9a91d775b</span>"""
+            """<a class="changeset_hash" href="/vcs_test_git/changeset/95f9a91d775b0084b2368ae7779e44931c849c0e">r613:95f9a91d775b</a>"""
         )
 
         response.mustcontain("""fixing stupid typo in context for mercurial""")
 
+        response.mustcontain("""var jsdata = [[[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 1, 2, 0], [0, 0, 1, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 1, 0], [1, 1, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 1], [[0, 0, 2, 0], [1, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 1, 3, 0], [0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 3, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 3, 0]], 0, 0, 0, 0, 0, 0], [[1, 3], [[0, 0, 2, 0], [1, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 1, 4, 0], [0, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[1, 4], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[1, 4], [[0, 0, 2, 0], [1, 1, 4, 0], [1, 0, 2, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[1, 4], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[1, 4], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[1, 4], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[1, 4], [[0, 0, 2, 0], [1, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[1, 4], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[1, 4], [[0, 0, 2, 0], [1, 1, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 2], [[0, 0, 4, 0], [1, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 1, 5, 0], [0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0], [1, 1, 5, 0]], 0, 0, 0, 0, 0, 0], [[1, 5], [[0, 0, 4, 0], [1, 1, 5, 0]], 0, 0, 0, 0, 0, 0], [[1, 5], [[0, 0, 4, 0], [1, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 1, 6, 0], [0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0], [1, 1, 6, 0]], 0, 0, 0, 0, 0, 0], [[1, 6], [[0, 0, 4, 0], [1, 1, 6, 0]], 0, 0, 0, 0, 0, 0], [[1, 6], [[0, 0, 4, 0], [1, 1, 6, 0], [1, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0], [1, 1, 6, 0]], 0, 0, 0, 0, 0, 0], [[1, 6], [[0, 0, 4, 0], [1, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 1, 7, 0], [0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0], [1, 1, 7, 0]], 0, 0, 0, 0, 0, 0], [[1, 7], [[0, 0, 4, 0], [1, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 1, 8, 0], [0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0], [1, 1, 8, 0]], 0, 0, 0, 0, 0, 0], [[1, 8], [[0, 0, 4, 0], [1, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 1, 9, 0], [0, 0, 4, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0], [1, 1, 9, 0]], 0, 0, 0, 0, 0, 0], [[1, 9], [[0, 0, 4, 0], [1, 0, 4, 0], [1, 1, 9, 0]], 0, 0, 0, 0, 0, 0], [[1, 9], [[0, 0, 4, 0], [1, 1, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0], [1, 1, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0], [1, 1, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0], [1, 1, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0], [1, 1, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0], [1, 1, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 4, 0], [1, 1, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 4], [[0, 0, 9, 0], [1, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 1, 10, 0], [0, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 1, 11, 0], [0, 0, 9, 0], [1, 2, 10, 0]], 0, 0, 0, 0, 0, 0], [[2, 10], [[0, 0, 9, 0], [1, 1, 11, 0], [2, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0], [1, 1, 11, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0], [1, 1, 11, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0], [1, 1, 11, 0]], 0, 0, 0, 0, 0, 0], [[1, 11], [[0, 0, 9, 0], [1, 0, 9, 0], [1, 1, 11, 0]], 0, 0, 0, 0, 0, 0], [[1, 11], [[0, 0, 9, 0], [1, 1, 11, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0], [1, 1, 11, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0], [1, 1, 11, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0], [1, 1, 11, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0], [1, 1, 11, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 1, 11, 0], [0, 0, 9, 0], [1, 1, 11, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0], [1, 1, 11, 0]], 0, 0, 0, 0, 0, 0], [[1, 11], [[0, 0, 9, 0], [1, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0]], 0, 0, 0, 0, 0, 0], [[0, 9], [[0, 0, 9, 0]], 0, 0, 0, 0, 0, 0]];""")
+
 #        response.mustcontain(
 #            """<div id="changed_total_5e204e7583b9c8e7b93a020bd036564b1e731dae" """
-#            """style="float:right;" class="changed_total tooltip" """
+#            """style="float:right;" class="changed_total" data-toggle="tooltip" """
 #            """title="Affected number of files, click to show """
 #            """more details">3</div>"""
 #        )
@@ -100,7 +104,7 @@
         )
 
         response.mustcontain(
-            """<span class="changeset_hash">r515:636ed213f2f1</span>"""
+            """<a class="changeset_hash" href="/vcs_test_git/changeset/636ed213f2f11ef91071b9c24f2d5e6bd01a6ed5">r515:636ed213f2f1</a>"""
         )
 
     def test_index_hg_with_filenode(self):
@@ -129,25 +133,25 @@
         response = self.app.get(url(controller='changelog', action='index',
                                     revision='tip', f_path='/tests',
                                     repo_name=HG_REPO))
-        self.assertEqual(response.status, '302 Found')
+        assert response.status == '302 Found'
 
     def test_index_git_with_filenode_that_is_dirnode(self):
         self.log_user()
         response = self.app.get(url(controller='changelog', action='index',
                                     revision='tip', f_path='/tests',
                                     repo_name=GIT_REPO))
-        self.assertEqual(response.status, '302 Found')
+        assert response.status == '302 Found'
 
     def test_index_hg_with_filenode_not_existing(self):
         self.log_user()
         response = self.app.get(url(controller='changelog', action='index',
                                     revision='tip', f_path='/wrong_path',
                                     repo_name=HG_REPO))
-        self.assertEqual(response.status, '302 Found')
+        assert response.status == '302 Found'
 
     def test_index_git_with_filenode_not_existing(self):
         self.log_user()
         response = self.app.get(url(controller='changelog', action='index',
                                     revision='tip', f_path='/wrong_path',
                                     repo_name=GIT_REPO))
-        self.assertEqual(response.status, '302 Found')
+        assert response.status == '302 Found'
--- a/kallithea/tests/functional/test_changeset.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_changeset.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 
 class TestChangesetController(TestController):
 
--- a/kallithea/tests/functional/test_changeset_comments.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_changeset_comments.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.model.db import ChangesetComment, Notification, \
     UserNotification
 from kallithea.model.meta import Session
@@ -6,7 +6,7 @@
 
 class TestChangeSetCommentsController(TestController):
 
-    def setUp(self):
+    def setup_method(self, method):
         for x in ChangesetComment.query().all():
             Session().delete(x)
         Session().commit()
@@ -21,32 +21,30 @@
         params = {'text': text, '_authentication_token': self.authentication_token()}
         response = self.app.post(url(controller='changeset', action='comment',
                                      repo_name=HG_REPO, revision=rev),
-                                     params=params)
+                                     params=params, extra_environ={'HTTP_X_PARTIAL_XHR': '1'})
         # Test response...
-        self.assertEqual(response.status, '302 Found')
-        response.follow()
+        assert response.status == '200 OK'
 
         response = self.app.get(url(controller='changeset', action='index',
                                 repo_name=HG_REPO, revision=rev))
         # test DB
-        self.assertEqual(ChangesetComment.query().count(), 1)
+        assert ChangesetComment.query().count() == 1
         response.mustcontain(
             '''<div class="comments-number">'''
             ''' 1 comment (0 inline, 1 general)'''
         )
 
-        self.assertEqual(Notification.query().count(), 1)
-        self.assertEqual(ChangesetComment.query().count(), 1)
+        assert Notification.query().count() == 1
+        assert ChangesetComment.query().count() == 1
 
         notification = Notification.query().all()[0]
 
         ID = ChangesetComment.query().first().comment_id
-        self.assertEqual(notification.type_,
-                         Notification.TYPE_CHANGESET_COMMENT)
+        assert notification.type_ == Notification.TYPE_CHANGESET_COMMENT
         sbj = (u'/%s/changeset/'
                '27cd5cce30c96924232dffcd24178a07ffeb5dfc#comment-%s' % (HG_REPO, ID))
         print "%s vs %s" % (sbj, notification.subject)
-        self.assertTrue(sbj in notification.subject)
+        assert sbj in notification.subject
 
     def test_create_inline(self):
         self.log_user()
@@ -58,15 +56,14 @@
         params = {'text': text, 'f_path': f_path, 'line': line, '_authentication_token': self.authentication_token()}
         response = self.app.post(url(controller='changeset', action='comment',
                                      repo_name=HG_REPO, revision=rev),
-                                     params=params)
+                                     params=params, extra_environ={'HTTP_X_PARTIAL_XHR': '1'})
         # Test response...
-        self.assertEqual(response.status, '302 Found')
-        response.follow()
+        assert response.status == '200 OK'
 
         response = self.app.get(url(controller='changeset', action='index',
                                 repo_name=HG_REPO, revision=rev))
         #test DB
-        self.assertEqual(ChangesetComment.query().count(), 1)
+        assert ChangesetComment.query().count() == 1
         response.mustcontain(
             '''<div class="comments-number">'''
             ''' 1 comment (1 inline, 0 general)'''
@@ -77,17 +74,16 @@
             '''data-line_no="n1" data-target-id="vcswebsimplevcsviewsrepositorypy_n1">'''
         )
 
-        self.assertEqual(Notification.query().count(), 1)
-        self.assertEqual(ChangesetComment.query().count(), 1)
+        assert Notification.query().count() == 1
+        assert ChangesetComment.query().count() == 1
 
         notification = Notification.query().all()[0]
         ID = ChangesetComment.query().first().comment_id
-        self.assertEqual(notification.type_,
-                         Notification.TYPE_CHANGESET_COMMENT)
+        assert notification.type_ == Notification.TYPE_CHANGESET_COMMENT
         sbj = (u'/%s/changeset/'
                '27cd5cce30c96924232dffcd24178a07ffeb5dfc#comment-%s' % (HG_REPO, ID))
         print "%s vs %s" % (sbj, notification.subject)
-        self.assertTrue(sbj in notification.subject)
+        assert sbj in notification.subject
 
     def test_create_with_mention(self):
         self.log_user()
@@ -98,25 +94,24 @@
         params = {'text': text, '_authentication_token': self.authentication_token()}
         response = self.app.post(url(controller='changeset', action='comment',
                                      repo_name=HG_REPO, revision=rev),
-                                     params=params)
+                                     params=params, extra_environ={'HTTP_X_PARTIAL_XHR': '1'})
         # Test response...
-        self.assertEqual(response.status, '302 Found')
-        response.follow()
+        assert response.status == '200 OK'
 
         response = self.app.get(url(controller='changeset', action='index',
                                 repo_name=HG_REPO, revision=rev))
         # test DB
-        self.assertEqual(ChangesetComment.query().count(), 1)
+        assert ChangesetComment.query().count() == 1
         response.mustcontain(
             '''<div class="comments-number">'''
             ''' 1 comment (0 inline, 1 general)'''
         )
 
-        self.assertEqual(Notification.query().count(), 2)
+        assert Notification.query().count() == 2
         users = [x.user.username for x in UserNotification.query().all()]
 
         # test_regular gets notification by @mention
-        self.assertEqual(sorted(users), [TEST_USER_ADMIN_LOGIN, TEST_USER_REGULAR_LOGIN])
+        assert sorted(users) == [TEST_USER_ADMIN_LOGIN, TEST_USER_REGULAR_LOGIN]
 
     def test_delete(self):
         self.log_user()
@@ -126,20 +121,19 @@
         params = {'text': text, '_authentication_token': self.authentication_token()}
         response = self.app.post(url(controller='changeset', action='comment',
                                      repo_name=HG_REPO, revision=rev),
-                                     params=params)
+                                     params=params, extra_environ={'HTTP_X_PARTIAL_XHR': '1'})
 
         comments = ChangesetComment.query().all()
-        self.assertEqual(len(comments), 1)
+        assert len(comments) == 1
         comment_id = comments[0].comment_id
 
-        self.app.post(url(controller='changeset',
-                                    action='delete_comment',
+        self.app.post(url("changeset_comment_delete",
                                     repo_name=HG_REPO,
                                     comment_id=comment_id),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+            params={'_authentication_token': self.authentication_token()})
 
         comments = ChangesetComment.query().all()
-        self.assertEqual(len(comments), 0)
+        assert len(comments) == 0
 
         response = self.app.get(url(controller='changeset', action='index',
                                 repo_name=HG_REPO, revision=rev))
--- a/kallithea/tests/functional/test_compare.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_compare.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,5 +1,5 @@
 # -*- coding: utf-8 -*-
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.model.repo import RepoModel
 from kallithea.model.meta import Session
 from kallithea.tests.fixture import Fixture
@@ -12,11 +12,11 @@
 
 class TestCompareController(TestController):
 
-    def setUp(self):
+    def setup_method(self, method):
         self.r1_id = None
         self.r2_id = None
 
-    def tearDown(self):
+    def teardown_method(self, method):
         if self.r2_id:
             RepoModel().delete(self.r2_id)
         if self.r1_id:
@@ -26,7 +26,7 @@
 
     def test_compare_forks_on_branch_extra_commits_hg(self):
         self.log_user()
-        repo1 = fixture.create_repo('one', repo_type='hg',
+        repo1 = fixture.create_repo(u'one', repo_type='hg',
                                     repo_description='diff-test',
                                     cur_user=TEST_USER_ADMIN_LOGIN)
         self.r1_id = repo1.repo_id
@@ -36,7 +36,7 @@
                 parent=None, newfile=True)
 
         #fork this repo
-        repo2 = fixture.create_fork('one', 'one-fork')
+        repo2 = fixture.create_fork(u'one', u'one-fork')
         self.r2_id = repo2.repo_id
 
         #add two extra commit into fork
@@ -68,16 +68,16 @@
         response.mustcontain(_commit_div(cs1.raw_id, 'commit2'))
         response.mustcontain(_commit_div(cs2.raw_id, 'commit3'))
 
-        response.mustcontain("""<a href="/%s/changeset/%s">r1:%s</a>""" % (repo2.repo_name, cs1.raw_id, cs1.short_id))
-        response.mustcontain("""<a href="/%s/changeset/%s">r2:%s</a>""" % (repo2.repo_name, cs2.raw_id, cs2.short_id))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/%s">r1:%s</a>""" % (repo2.repo_name, cs1.raw_id, cs1.short_id))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/%s">r2:%s</a>""" % (repo2.repo_name, cs2.raw_id, cs2.short_id))
         ## files
         response.mustcontain("""<a href="#C--826e8142e6ba">file1</a>""")
         #swap
-        response.mustcontain("""<a class="btn btn-small" href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=True"><i class="icon-arrows-cw"></i> Swap</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
+        response.mustcontain("""<a class="btn btn-default btn-sm" href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=True"><i class="icon-arrows-cw"></i> Swap</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
 
     def test_compare_forks_on_branch_extra_commits_git(self):
         self.log_user()
-        repo1 = fixture.create_repo('one-git', repo_type='git',
+        repo1 = fixture.create_repo(u'one-git', repo_type='git',
                                     repo_description='diff-test',
                                     cur_user=TEST_USER_ADMIN_LOGIN)
         self.r1_id = repo1.repo_id
@@ -87,7 +87,7 @@
                 parent=None, newfile=True)
 
         #fork this repo
-        repo2 = fixture.create_fork('one-git', 'one-git-fork')
+        repo2 = fixture.create_fork(u'one-git', u'one-git-fork')
         self.r2_id = repo2.repo_id
 
         #add two extra commit into fork
@@ -119,17 +119,17 @@
         response.mustcontain(_commit_div(cs1.raw_id, 'commit2'))
         response.mustcontain(_commit_div(cs2.raw_id, 'commit3'))
 
-        response.mustcontain("""<a href="/%s/changeset/%s">r1:%s</a>""" % (repo2.repo_name, cs1.raw_id, cs1.short_id))
-        response.mustcontain("""<a href="/%s/changeset/%s">r2:%s</a>""" % (repo2.repo_name, cs2.raw_id, cs2.short_id))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/%s">r1:%s</a>""" % (repo2.repo_name, cs1.raw_id, cs1.short_id))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/%s">r2:%s</a>""" % (repo2.repo_name, cs2.raw_id, cs2.short_id))
         ## files
         response.mustcontain("""<a href="#C--826e8142e6ba">file1</a>""")
         #swap
-        response.mustcontain("""<a class="btn btn-small" href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=True"><i class="icon-arrows-cw"></i> Swap</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
+        response.mustcontain("""<a class="btn btn-default btn-sm" href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=True"><i class="icon-arrows-cw"></i> Swap</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
 
-    def test_compare_forks_on_branch_extra_commits_origin_has_incomming_hg(self):
+    def test_compare_forks_on_branch_extra_commits_origin_has_incoming_hg(self):
         self.log_user()
 
-        repo1 = fixture.create_repo('one', repo_type='hg',
+        repo1 = fixture.create_repo(u'one', repo_type='hg',
                                     repo_description='diff-test',
                                     cur_user=TEST_USER_ADMIN_LOGIN)
 
@@ -141,7 +141,7 @@
                 parent=None, newfile=True)
 
         #fork this repo
-        repo2 = fixture.create_fork('one', 'one-fork')
+        repo2 = fixture.create_fork(u'one', u'one-fork')
         self.r2_id = repo2.repo_id
 
         #now commit something to origin repo
@@ -178,17 +178,17 @@
         response.mustcontain(_commit_div(cs1.raw_id, 'commit2'))
         response.mustcontain(_commit_div(cs2.raw_id, 'commit3'))
 
-        response.mustcontain("""<a href="/%s/changeset/%s">r1:%s</a>""" % (repo2.repo_name, cs1.raw_id, cs1.short_id))
-        response.mustcontain("""<a href="/%s/changeset/%s">r2:%s</a>""" % (repo2.repo_name, cs2.raw_id, cs2.short_id))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/%s">r1:%s</a>""" % (repo2.repo_name, cs1.raw_id, cs1.short_id))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/%s">r2:%s</a>""" % (repo2.repo_name, cs2.raw_id, cs2.short_id))
         ## files
         response.mustcontain("""<a href="#C--826e8142e6ba">file1</a>""")
         #swap
-        response.mustcontain("""<a class="btn btn-small" href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=True"><i class="icon-arrows-cw"></i> Swap</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
+        response.mustcontain("""<a class="btn btn-default btn-sm" href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=True"><i class="icon-arrows-cw"></i> Swap</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
 
-    def test_compare_forks_on_branch_extra_commits_origin_has_incomming_git(self):
+    def test_compare_forks_on_branch_extra_commits_origin_has_incoming_git(self):
         self.log_user()
 
-        repo1 = fixture.create_repo('one-git', repo_type='git',
+        repo1 = fixture.create_repo(u'one-git', repo_type='git',
                                     repo_description='diff-test',
                                     cur_user=TEST_USER_ADMIN_LOGIN)
 
@@ -200,7 +200,7 @@
                 parent=None, newfile=True)
 
         #fork this repo
-        repo2 = fixture.create_fork('one-git', 'one-git-fork')
+        repo2 = fixture.create_fork(u'one-git', u'one-git-fork')
         self.r2_id = repo2.repo_id
 
         #now commit something to origin repo
@@ -237,12 +237,12 @@
         response.mustcontain(_commit_div(cs1.raw_id, 'commit2'))
         response.mustcontain(_commit_div(cs2.raw_id, 'commit3'))
 
-        response.mustcontain("""<a href="/%s/changeset/%s">r1:%s</a>""" % (repo2.repo_name, cs1.raw_id, cs1.short_id))
-        response.mustcontain("""<a href="/%s/changeset/%s">r2:%s</a>""" % (repo2.repo_name, cs2.raw_id, cs2.short_id))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/%s">r1:%s</a>""" % (repo2.repo_name, cs1.raw_id, cs1.short_id))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/%s">r2:%s</a>""" % (repo2.repo_name, cs2.raw_id, cs2.short_id))
         ## files
         response.mustcontain("""<a href="#C--826e8142e6ba">file1</a>""")
         #swap
-        response.mustcontain("""<a class="btn btn-small" href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=True"><i class="icon-arrows-cw"></i> Swap</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
+        response.mustcontain("""<a class="btn btn-default btn-sm" href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=True"><i class="icon-arrows-cw"></i> Swap</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
 
     def test_compare_cherry_pick_changesets_from_bottom(self):
 
@@ -259,7 +259,7 @@
         #make repo1, and cs1+cs2
         self.log_user()
 
-        repo1 = fixture.create_repo('repo1', repo_type='hg',
+        repo1 = fixture.create_repo(u'repo1', repo_type='hg',
                                     repo_description='diff-test',
                                     cur_user=TEST_USER_ADMIN_LOGIN)
         self.r1_id = repo1.repo_id
@@ -272,7 +272,7 @@
                 content='line1\nline2\n', message='commit2', vcs_type='hg',
                 parent=cs0)
         #fork this repo
-        repo2 = fixture.create_fork('repo1', 'repo1-fork')
+        repo2 = fixture.create_fork(u'repo1', u'repo1-fork')
         self.r2_id = repo2.repo_id
         #now make cs3-6
         cs2 = fixture.commit_change(repo1.repo_name, filename='file1',
@@ -306,9 +306,9 @@
         response.mustcontain(_commit_div(cs3.raw_id, 'commit4'))
         response.mustcontain(_commit_div(cs4.raw_id, 'commit5'))
 
-        response.mustcontain("""<a href="/%s/changeset/%s">r2:%s</a>""" % (repo1.repo_name, cs2.raw_id, cs2.short_id))
-        response.mustcontain("""<a href="/%s/changeset/%s">r3:%s</a>""" % (repo1.repo_name, cs3.raw_id, cs3.short_id))
-        response.mustcontain("""<a href="/%s/changeset/%s">r4:%s</a>""" % (repo1.repo_name, cs4.raw_id, cs4.short_id))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/%s">r2:%s</a>""" % (repo1.repo_name, cs2.raw_id, cs2.short_id))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/%s">r3:%s</a>""" % (repo1.repo_name, cs3.raw_id, cs3.short_id))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/%s">r4:%s</a>""" % (repo1.repo_name, cs4.raw_id, cs4.short_id))
         ## files
         response.mustcontain("""#C--826e8142e6ba">file1</a>""")
 
@@ -326,7 +326,7 @@
 #
         #make repo1, and cs1+cs2
         self.log_user()
-        repo1 = fixture.create_repo('repo1', repo_type='hg',
+        repo1 = fixture.create_repo(u'repo1', repo_type='hg',
                                     repo_description='diff-test',
                                     cur_user=TEST_USER_ADMIN_LOGIN)
         self.r1_id = repo1.repo_id
@@ -339,7 +339,7 @@
                 content='line1\nline2\n', message='commit2', vcs_type='hg',
                 parent=cs0)
         #fork this repo
-        repo2 = fixture.create_fork('repo1', 'repo1-fork')
+        repo2 = fixture.create_fork(u'repo1', u'repo1-fork')
         self.r2_id = repo2.repo_id
         #now make cs3-6
         cs2 = fixture.commit_change(repo1.repo_name, filename='file1',
@@ -372,9 +372,9 @@
         response.mustcontain(_commit_div(cs4.raw_id, 'commit5'))
         response.mustcontain(_commit_div(cs5.raw_id, 'commit6'))
 
-        response.mustcontain("""<a href="/%s/changeset/%s">r3:%s</a>""" % (repo1.repo_name, cs3.raw_id, cs3.short_id))
-        response.mustcontain("""<a href="/%s/changeset/%s">r4:%s</a>""" % (repo1.repo_name, cs4.raw_id, cs4.short_id))
-        response.mustcontain("""<a href="/%s/changeset/%s">r5:%s</a>""" % (repo1.repo_name, cs5.raw_id, cs5.short_id))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/%s">r3:%s</a>""" % (repo1.repo_name, cs3.raw_id, cs3.short_id))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/%s">r4:%s</a>""" % (repo1.repo_name, cs4.raw_id, cs4.short_id))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/%s">r5:%s</a>""" % (repo1.repo_name, cs5.raw_id, cs5.short_id))
         ## files
         response.mustcontain("""#C--826e8142e6ba">file1</a>""")
 
@@ -403,9 +403,9 @@
         response.mustcontain('%s@%s' % (HG_FORK, rev2))
         ## outgoing changesets between those revisions
 
-        response.mustcontain("""<a href="/%s/changeset/2dda4e345facb0ccff1a191052dd1606dba6781d">r4:2dda4e345fac</a>""" % (HG_FORK))
-        response.mustcontain("""<a href="/%s/changeset/6fff84722075f1607a30f436523403845f84cd9e">r5:6fff84722075</a>""" % (HG_FORK))
-        response.mustcontain("""<a href="/%s/changeset/7d4bc8ec6be56c0f10425afb40b6fc315a4c25e7">r6:%s</a>""" % (HG_FORK, rev2))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/2dda4e345facb0ccff1a191052dd1606dba6781d">r4:2dda4e345fac</a>""" % (HG_FORK))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/6fff84722075f1607a30f436523403845f84cd9e">r5:6fff84722075</a>""" % (HG_FORK))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/7d4bc8ec6be56c0f10425afb40b6fc315a4c25e7">r6:%s</a>""" % (HG_FORK, rev2))
 
         ## files
         response.mustcontain("""<a href="#C--9c390eb52cd6">vcs/backends/hg.py</a>""")
@@ -433,9 +433,9 @@
         response.mustcontain('%s@%s' % (GIT_FORK, rev2))
         ## outgoing changesets between those revisions
 
-        response.mustcontain("""<a href="/%s/changeset/49d3fd156b6f7db46313fac355dca1a0b94a0017">r4:49d3fd156b6f</a>""" % (GIT_FORK))
-        response.mustcontain("""<a href="/%s/changeset/2d1028c054665b962fa3d307adfc923ddd528038">r5:2d1028c05466</a>""" % (GIT_FORK))
-        response.mustcontain("""<a href="/%s/changeset/d7e0d30fbcae12c90680eb095a4f5f02505ce501">r6:%s</a>""" % (GIT_FORK, rev2[:12]))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/49d3fd156b6f7db46313fac355dca1a0b94a0017">r4:49d3fd156b6f</a>""" % (GIT_FORK))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/2d1028c054665b962fa3d307adfc923ddd528038">r5:2d1028c05466</a>""" % (GIT_FORK))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/d7e0d30fbcae12c90680eb095a4f5f02505ce501">r6:%s</a>""" % (GIT_FORK, rev2[:12]))
 
         ## files
         response.mustcontain("""<a href="#C--9c390eb52cd6">vcs/backends/hg.py</a>""")
@@ -445,7 +445,7 @@
     def test_org_repo_new_commits_after_forking_simple_diff_hg(self):
         self.log_user()
 
-        repo1 = fixture.create_repo('one', repo_type='hg',
+        repo1 = fixture.create_repo(u'one', repo_type='hg',
                                     repo_description='diff-test',
                                     cur_user=TEST_USER_ADMIN_LOGIN)
 
@@ -455,19 +455,18 @@
         cs0 = fixture.commit_change(repo=r1_name, filename='file1',
                 content='line1', message='commit1', vcs_type='hg', newfile=True)
         Session().commit()
-        self.assertEqual(repo1.scm_instance.revisions, [cs0.raw_id])
+        assert repo1.scm_instance.revisions == [cs0.raw_id]
         #fork the repo1
-        repo2 = fixture.create_repo('one-fork', repo_type='hg',
+        repo2 = fixture.create_repo(u'one-fork', repo_type='hg',
                                     repo_description='diff-test',
                                     cur_user=TEST_USER_ADMIN_LOGIN,
                                     clone_uri=repo1.repo_full_path,
                                     fork_of='one')
         Session().commit()
-        self.assertEqual(repo2.scm_instance.revisions, [cs0.raw_id])
+        assert repo2.scm_instance.revisions == [cs0.raw_id]
         self.r2_id = repo2.repo_id
         r2_name = repo2.repo_name
 
-
         cs1 = fixture.commit_change(repo=r2_name, filename='file1-fork',
                 content='file1-line1-from-fork', message='commit1-fork',
                 vcs_type='hg', parent=repo2.scm_instance[-1], newfile=True)
@@ -486,16 +485,13 @@
         response = self.app.get(url('compare_url',
                                     repo_name=r2_name,
                                     org_ref_type="branch",
-                                    org_ref_name=rev1,
+                                    org_ref_name=rev2,
                                     other_ref_type="branch",
-                                    other_ref_name=rev2,
+                                    other_ref_name=rev1,
                                     other_repo=r1_name,
-                                    merge='1',))
+                                    merge='1',), status=404)
 
-        response.mustcontain('%s@%s' % (r2_name, rev1))
-        response.mustcontain('%s@%s' % (r1_name, rev2))
-        response.mustcontain('No files')
-        response.mustcontain('No changesets')
+        response.mustcontain('Cannot show empty diff')
 
         cs0 = fixture.commit_change(repo=r1_name, filename='file2',
                 content='line1-added-after-fork', message='commit2-parent',
@@ -507,9 +503,9 @@
         response = self.app.get(url('compare_url',
                                     repo_name=r2_name,
                                     org_ref_type="branch",
-                                    org_ref_name=rev1,
+                                    org_ref_name=rev2,
                                     other_ref_type="branch",
-                                    other_ref_name=rev2,
+                                    other_ref_name=rev1,
                                     other_repo=r1_name,
                                     merge='1',
                                     ))
@@ -524,7 +520,7 @@
     def test_org_repo_new_commits_after_forking_simple_diff_git(self):
         self.log_user()
 
-        repo1 = fixture.create_repo('one-git', repo_type='git',
+        repo1 = fixture.create_repo(u'one-git', repo_type='git',
                                     repo_description='diff-test',
                                     cur_user=TEST_USER_ADMIN_LOGIN)
 
@@ -535,15 +531,15 @@
                 content='line1', message='commit1', vcs_type='git',
                 newfile=True)
         Session().commit()
-        self.assertEqual(repo1.scm_instance.revisions, [cs0.raw_id])
+        assert repo1.scm_instance.revisions == [cs0.raw_id]
         #fork the repo1
-        repo2 = fixture.create_repo('one-git-fork', repo_type='git',
+        repo2 = fixture.create_repo(u'one-git-fork', repo_type='git',
                                     repo_description='diff-test',
                                     cur_user=TEST_USER_ADMIN_LOGIN,
                                     clone_uri=repo1.repo_full_path,
                                     fork_of='one-git')
         Session().commit()
-        self.assertEqual(repo2.scm_instance.revisions, [cs0.raw_id])
+        assert repo2.scm_instance.revisions == [cs0.raw_id]
         self.r2_id = repo2.repo_id
         r2_name = repo2.repo_name
 
@@ -570,12 +566,9 @@
                                     other_ref_type="branch",
                                     other_ref_name=rev2,
                                     other_repo=r1_name,
-                                    merge='1',))
+                                    merge='1',), status=404)
 
-        response.mustcontain('%s@%s' % (r2_name, rev1))
-        response.mustcontain('%s@%s' % (r1_name, rev2))
-        response.mustcontain('No files')
-        response.mustcontain('No changesets')
+        response.mustcontain('Cannot show empty diff')
 
         cs0 = fixture.commit_change(repo=r1_name, filename='file2',
                 content='line1-added-after-fork', message='commit2-parent',
--- a/kallithea/tests/functional/test_compare_local.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_compare_local.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,5 +1,5 @@
 # -*- coding: utf-8 -*-
-from kallithea.tests import *
+from kallithea.tests.base import *
 
 class TestCompareController(TestController):
 
@@ -18,50 +18,62 @@
         response.mustcontain('%s@%s' % (HG_REPO, tag2))
 
         ## outgoing changesets between tags
-        response.mustcontain('''<a href="/%s/changeset/c5ddebc06eaaba3010c2d66ea6ec9d074eb0f678">r112:c5ddebc06eaa</a>''' % HG_REPO)
-        response.mustcontain('''<a href="/%s/changeset/70d4cef8a37657ee4cf5aabb3bd9f68879769816">r115:70d4cef8a376</a>''' % HG_REPO)
-        response.mustcontain('''<a href="/%s/changeset/9749bfbfc0d2eba208d7947de266303b67c87cda">r116:9749bfbfc0d2</a>''' % HG_REPO)
-        response.mustcontain('''<a href="/%s/changeset/41fda979f02fda216374bf8edac4e83f69e7581c">r117:41fda979f02f</a>''' % HG_REPO)
-        response.mustcontain('''<a href="/%s/changeset/bb1a3ab98cc45cb934a77dcabf87a5a598b59e97">r118:bb1a3ab98cc4</a>''' % HG_REPO)
-        response.mustcontain('''<a href="/%s/changeset/36e0fc9d2808c5022a24f49d6658330383ed8666">r119:36e0fc9d2808</a>''' % HG_REPO)
-        response.mustcontain('''<a href="/%s/changeset/17544fbfcd33ffb439e2b728b5d526b1ef30bfcf">r120:17544fbfcd33</a>''' % HG_REPO)
+        response.mustcontain('''<a class="changeset_hash" href="/%s/changeset/c5ddebc06eaaba3010c2d66ea6ec9d074eb0f678">r112:c5ddebc06eaa</a>''' % HG_REPO)
+        response.mustcontain('''<a class="changeset_hash" href="/%s/changeset/70d4cef8a37657ee4cf5aabb3bd9f68879769816">r115:70d4cef8a376</a>''' % HG_REPO)
+        response.mustcontain('''<a class="changeset_hash" href="/%s/changeset/9749bfbfc0d2eba208d7947de266303b67c87cda">r116:9749bfbfc0d2</a>''' % HG_REPO)
+        response.mustcontain('''<a class="changeset_hash" href="/%s/changeset/41fda979f02fda216374bf8edac4e83f69e7581c">r117:41fda979f02f</a>''' % HG_REPO)
+        response.mustcontain('''<a class="changeset_hash" href="/%s/changeset/bb1a3ab98cc45cb934a77dcabf87a5a598b59e97">r118:bb1a3ab98cc4</a>''' % HG_REPO)
+        response.mustcontain('''<a class="changeset_hash" href="/%s/changeset/36e0fc9d2808c5022a24f49d6658330383ed8666">r119:36e0fc9d2808</a>''' % HG_REPO)
+        response.mustcontain('''<a class="changeset_hash" href="/%s/changeset/17544fbfcd33ffb439e2b728b5d526b1ef30bfcf">r120:17544fbfcd33</a>''' % HG_REPO)
 
         response.mustcontain('11 files changed with 94 insertions and 64 deletions')
 
         ## files diff
-        response.mustcontain('''<div class="node">
-                             <i class="icon-diff-A"></i>
-                             <a href="#C--1c5cf9e91c12">docs/api/utils/index.rst</a>''')
-        response.mustcontain('''<div class="node">
-                             <i class="icon-diff-A"></i>
-                             <a href="#C--e3305437df55">test_and_report.sh</a>''')
-        response.mustcontain('''<div class="node">
-                             <i class="icon-diff-M"></i>
-                             <a href="#C--c8e92ef85cd1">.hgignore</a>''')
-        response.mustcontain('''<div class="node">
-                             <i class="icon-diff-M"></i>
-                             <a href="#C--6e08b694d687">.hgtags</a>''')
-        response.mustcontain('''<div class="node">
-                             <i class="icon-diff-M"></i>
-                             <a href="#C--2c14b00f3393">docs/api/index.rst</a>''')
-        response.mustcontain('''<div class="node">
-                             <i class="icon-diff-M"></i>
-                             <a href="#C--430ccbc82bdf">vcs/__init__.py</a>''')
-        response.mustcontain('''<div class="node">
-                             <i class="icon-diff-M"></i>
-                             <a href="#C--9c390eb52cd6">vcs/backends/hg.py</a>''')
-        response.mustcontain('''<div class="node">
-                             <i class="icon-diff-M"></i>
-                             <a href="#C--ebb592c595c0">vcs/utils/__init__.py</a>''')
-        response.mustcontain('''<div class="node">
-                             <i class="icon-diff-M"></i>
-                             <a href="#C--7abc741b5052">vcs/utils/annotate.py</a>''')
-        response.mustcontain('''<div class="node">
-                             <i class="icon-diff-M"></i>
-                             <a href="#C--2ef0ef106c56">vcs/utils/diffs.py</a>''')
-        response.mustcontain('''<div class="node">
-                             <i class="icon-diff-M"></i>
-                             <a href="#C--3150cb87d4b7">vcs/utils/lazy.py</a>''')
+        response.mustcontain(
+                   '''<div class="node">
+                          <i class="icon-diff-A"></i>
+                          <a href="#C--1c5cf9e91c12">docs/api/utils/index.rst</a>
+                      </div>''')
+        response.mustcontain(
+                   '''<div class="node">
+                          <i class="icon-diff-A"></i>
+                          <a href="#C--e3305437df55">test_and_report.sh</a>''')
+        response.mustcontain(
+                   '''<div class="node">
+                          <i class="icon-diff-M"></i>
+                          <a href="#C--c8e92ef85cd1">.hgignore</a>''')
+        response.mustcontain(
+                   '''<div class="node">
+                          <i class="icon-diff-M"></i>
+                          <a href="#C--6e08b694d687">.hgtags</a>''')
+        response.mustcontain(
+                   '''<div class="node">
+                          <i class="icon-diff-M"></i>
+                          <a href="#C--2c14b00f3393">docs/api/index.rst</a>''')
+        response.mustcontain(
+                   '''<div class="node">
+                          <i class="icon-diff-M"></i>
+                          <a href="#C--430ccbc82bdf">vcs/__init__.py</a>''')
+        response.mustcontain(
+                   '''<div class="node">
+                          <i class="icon-diff-M"></i>
+                          <a href="#C--9c390eb52cd6">vcs/backends/hg.py</a>''')
+        response.mustcontain(
+                   '''<div class="node">
+                          <i class="icon-diff-M"></i>
+                          <a href="#C--ebb592c595c0">vcs/utils/__init__.py</a>''')
+        response.mustcontain(
+                   '''<div class="node">
+                          <i class="icon-diff-M"></i>
+                          <a href="#C--7abc741b5052">vcs/utils/annotate.py</a>''')
+        response.mustcontain(
+                   '''<div class="node">
+                          <i class="icon-diff-M"></i>
+                          <a href="#C--2ef0ef106c56">vcs/utils/diffs.py</a>''')
+        response.mustcontain(
+                   '''<div class="node">
+                          <i class="icon-diff-M"></i>
+                          <a href="#C--3150cb87d4b7">vcs/utils/lazy.py</a>''')
 
     def test_compare_tag_git(self):
         self.log_user()
@@ -78,13 +90,13 @@
         response.mustcontain('%s@%s' % (GIT_REPO, tag2))
 
         ## outgoing changesets between tags
-        response.mustcontain('''<a href="/%s/changeset/794bbdd31545c199f74912709ea350dedcd189a2">r113:794bbdd31545</a>''' % GIT_REPO)
-        response.mustcontain('''<a href="/%s/changeset/e36d8c5025329bdd4212bd53d4ed8a70ff44985f">r115:e36d8c502532</a>''' % GIT_REPO)
-        response.mustcontain('''<a href="/%s/changeset/5c9ff4f6d7508db0e72b1d2991c357d0d8e07af2">r116:5c9ff4f6d750</a>''' % GIT_REPO)
-        response.mustcontain('''<a href="/%s/changeset/b7187fa2b8c1d773ec35e9dee12f01f74808c879">r117:b7187fa2b8c1</a>''' % GIT_REPO)
-        response.mustcontain('''<a href="/%s/changeset/5f3b74262014a8de2dc7dade1152de9fd0c8efef">r118:5f3b74262014</a>''' % GIT_REPO)
-        response.mustcontain('''<a href="/%s/changeset/17438a11f72b93f56d0e08e7d1fa79a378578a82">r119:17438a11f72b</a>''' % GIT_REPO)
-        response.mustcontain('''<a href="/%s/changeset/5a3a8fb005554692b16e21dee62bf02667d8dc3e">r120:5a3a8fb00555</a>''' % GIT_REPO)
+        response.mustcontain('''<a class="changeset_hash" href="/%s/changeset/794bbdd31545c199f74912709ea350dedcd189a2">r113:794bbdd31545</a>''' % GIT_REPO)
+        response.mustcontain('''<a class="changeset_hash" href="/%s/changeset/e36d8c5025329bdd4212bd53d4ed8a70ff44985f">r115:e36d8c502532</a>''' % GIT_REPO)
+        response.mustcontain('''<a class="changeset_hash" href="/%s/changeset/5c9ff4f6d7508db0e72b1d2991c357d0d8e07af2">r116:5c9ff4f6d750</a>''' % GIT_REPO)
+        response.mustcontain('''<a class="changeset_hash" href="/%s/changeset/b7187fa2b8c1d773ec35e9dee12f01f74808c879">r117:b7187fa2b8c1</a>''' % GIT_REPO)
+        response.mustcontain('''<a class="changeset_hash" href="/%s/changeset/5f3b74262014a8de2dc7dade1152de9fd0c8efef">r118:5f3b74262014</a>''' % GIT_REPO)
+        response.mustcontain('''<a class="changeset_hash" href="/%s/changeset/17438a11f72b93f56d0e08e7d1fa79a378578a82">r119:17438a11f72b</a>''' % GIT_REPO)
+        response.mustcontain('''<a class="changeset_hash" href="/%s/changeset/5a3a8fb005554692b16e21dee62bf02667d8dc3e">r120:5a3a8fb00555</a>''' % GIT_REPO)
 
         response.mustcontain('11 files changed with 94 insertions and 64 deletions')
 
@@ -149,7 +161,7 @@
         response.mustcontain('%s@%s' % (HG_REPO, rev2))
 
         ## outgoing changesets between those revisions
-        response.mustcontain("""<a href="/%s/changeset/3d8f361e72ab303da48d799ff1ac40d5ac37c67e">r1:%s</a>""" % (HG_REPO, rev2))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/3d8f361e72ab303da48d799ff1ac40d5ac37c67e">r1:%s</a>""" % (HG_REPO, rev2))
 
         response.mustcontain('1 file changed with 7 insertions and 0 deletions')
         ## files
@@ -171,7 +183,7 @@
         response.mustcontain('%s@%s' % (GIT_REPO, rev2))
 
         ## outgoing changesets between those revisions
-        response.mustcontain("""<a href="/%s/changeset/38b5fe81f109cb111f549bfe9bb6b267e10bc557">r1:%s</a>""" % (GIT_REPO, rev2[:12]))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/38b5fe81f109cb111f549bfe9bb6b267e10bc557">r1:%s</a>""" % (GIT_REPO, rev2[:12]))
         response.mustcontain('1 file changed with 7 insertions and 0 deletions')
 
         ## files
@@ -193,10 +205,10 @@
                                 extra_environ={'HTTP_X_PARTIAL_XHR': '1'},)
 
         ## outgoing changesets between those revisions
-        response.mustcontain("""<a href="/%s/changeset/3d8f361e72ab303da48d799ff1ac40d5ac37c67e">r1:%s</a>""" % (HG_REPO, rev2))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/3d8f361e72ab303da48d799ff1ac40d5ac37c67e">r1:%s</a>""" % (HG_REPO, rev2))
 
-        response.mustcontain('Common ancestor')
-        response.mustcontain("""<a href="/%s/changeset/b986218ba1c9b0d6a259fac9b050b1724ed8e545">%s</a>""" % (HG_REPO, rev1))
+        response.mustcontain('Merge Ancestor')
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/b986218ba1c9b0d6a259fac9b050b1724ed8e545">%s</a>""" % (HG_REPO, rev1))
 
     def test_compare_revisions_git_as_form(self):
         self.log_user()
@@ -213,7 +225,7 @@
                                     ),
                                 extra_environ={'HTTP_X_PARTIAL_XHR': '1'},)
         ## outgoing changesets between those revisions
-        response.mustcontain("""<a href="/%s/changeset/38b5fe81f109cb111f549bfe9bb6b267e10bc557">r1:%s</a>""" % (GIT_REPO, rev2[:12]))
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/38b5fe81f109cb111f549bfe9bb6b267e10bc557">r1:%s</a>""" % (GIT_REPO, rev2[:12]))
 
-        response.mustcontain('Common ancestor')
-        response.mustcontain("""<a href="/%s/changeset/c1214f7e79e02fc37156ff215cd71275450cffc3">%s</a>""" % (GIT_REPO, rev1[:12]))
+        response.mustcontain('Merge Ancestor')
+        response.mustcontain("""<a class="changeset_hash" href="/%s/changeset/c1214f7e79e02fc37156ff215cd71275450cffc3">%s</a>""" % (GIT_REPO, rev1[:12]))
--- a/kallithea/tests/functional/test_feed.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_feed.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 
 class TestFeedController(TestController):
 
--- a/kallithea/tests/functional/test_files.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_files.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,6 +1,8 @@
 # -*- coding: utf-8 -*-
 import os
-from kallithea.tests import *
+import posixpath
+import mimetypes
+from kallithea.tests.base import *
 from kallithea.model.db import Repository
 from kallithea.model.meta import Session
 from kallithea.tests.fixture import Fixture
@@ -20,7 +22,6 @@
 def _set_downloads(repo_name, set_to):
     repo = Repository.get_by_repo_name(repo_name)
     repo.enable_downloads = set_to
-    Session().add(repo)
     Session().commit()
 
 
@@ -91,17 +92,21 @@
             response.mustcontain("""@ r%s:%s""" % (r[0], r[1][:12]))
 
     def test_file_source(self):
+        # Force the global cache to be populated now when we know the right .ini has been loaded.
+        # (Without this, the test would fail.)
+        import kallithea.lib.helpers
+        kallithea.lib.helpers._urlify_issues_f = None
         self.log_user()
         response = self.app.get(url(controller='files', action='index',
                                     repo_name=HG_REPO,
                                     revision='8911406ad776fdd3d0b9932a2e89677e57405a48',
                                     f_path='vcs/nodes.py'))
 
-        response.mustcontain("""<div class="commit">Partially implemented <a class="issue-tracker-link" href="https://issues.example.com/vcs_test_hg/issue/16">#16</a>. filecontent/commit message/author/node name are safe_unicode now.
-In addition some other __str__ are unicode as well
-Added test for unicode
-Improved test to clone into uniq repository.
-removed extra unicode conversion in diff.</div>
+        response.mustcontain("""<div class="commit">Partially implemented <a class="issue-tracker-link" href="https://issues.example.com/vcs_test_hg/issue/16">#16</a>. filecontent/commit message/author/node name are safe_unicode now.<br/>"""
+"""In addition some other __str__ are unicode as well<br/>"""
+"""Added test for unicode<br/>"""
+"""Improved test to clone into uniq repository.<br/>"""
+"""removed extra unicode conversion in diff.</div>
 """)
 
         response.mustcontain("""<option selected="selected" value="8911406ad776fdd3d0b9932a2e89677e57405a48">default at 8911406ad776</option>""")
@@ -113,7 +118,7 @@
                                     revision='tip',
                                     f_path='vcs/nodes.py'),
                                 extra_environ={'HTTP_X_PARTIAL_XHR': '1'},)
-        self.assertEqual(response.body, HG_NODE_HISTORY)
+        assert response.body == HG_NODE_HISTORY
 
     def test_file_source_history_git(self):
         self.log_user()
@@ -122,7 +127,7 @@
                                     revision='master',
                                     f_path='vcs/nodes.py'),
                                 extra_environ={'HTTP_X_PARTIAL_XHR': '1'},)
-        self.assertEqual(response.body, GIT_NODE_HISTORY)
+        assert response.body == GIT_NODE_HISTORY
 
     def test_file_annotation(self):
         self.log_user()
@@ -152,7 +157,7 @@
                                     annotate=True),
                                 extra_environ={'HTTP_X_PARTIAL_XHR': '1'})
 
-        self.assertEqual(response.body, HG_NODE_HISTORY)
+        assert response.body == HG_NODE_HISTORY
 
     def test_file_annotation_history_git(self):
         self.log_user()
@@ -163,7 +168,7 @@
                                     annotate=True),
                                 extra_environ={'HTTP_X_PARTIAL_XHR': '1'})
 
-        self.assertEqual(response.body, GIT_NODE_HISTORY)
+        assert response.body == GIT_NODE_HISTORY
 
     def test_file_authors(self):
         self.log_user()
@@ -197,14 +202,14 @@
                                         repo_name=HG_REPO,
                                         fname=fname))
 
-            self.assertEqual(response.status, '200 OK')
+            assert response.status == '200 OK'
             heads = [
                 ('Pragma', 'no-cache'),
                 ('Cache-Control', 'no-cache'),
                 ('Content-Disposition', 'attachment; filename=%s' % filename),
                 ('Content-Type', '%s; charset=utf-8' % info[0]),
             ]
-            self.assertEqual(response.response._headers.items(), heads)
+            assert response.response._headers.items() == heads
 
     def test_archival_wrong_ext(self):
         self.log_user()
@@ -240,8 +245,8 @@
                                     revision='27cd5cce30c96924232dffcd24178a07ffeb5dfc',
                                     f_path='vcs/nodes.py'))
 
-        self.assertEqual(response.content_disposition, "attachment; filename=nodes.py")
-        self.assertEqual(response.content_type, "text/x-python")
+        assert response.content_disposition == "attachment; filename=nodes.py"
+        assert response.content_type == mimetypes.guess_type("nodes.py")[0]
 
     def test_raw_file_wrong_cs(self):
         self.log_user()
@@ -278,7 +283,7 @@
                                     revision='27cd5cce30c96924232dffcd24178a07ffeb5dfc',
                                     f_path='vcs/nodes.py'))
 
-        self.assertEqual(response.content_type, "text/plain")
+        assert response.content_type == "text/plain"
 
     def test_raw_wrong_cs(self):
         self.log_user()
@@ -347,7 +352,7 @@
 
         self.checkSessionFlash(response, 'No filename')
 
-    @parameterized.expand([
+    @parametrize('location,filename', [
         ('/abs', 'foo'),
         ('../rel', 'foo'),
         ('file/../foo', 'foo'),
@@ -367,14 +372,14 @@
 
         self.checkSessionFlash(response, 'Location must be relative path and must not contain .. in path')
 
-    @parameterized.expand([
+    @parametrize('cnt,location,filename', [
         (1, '', 'foo.txt'),
         (2, 'dir', 'foo.rst'),
         (3, 'rel/dir', 'foo.bar'),
     ])
     def test_add_file_into_hg(self, cnt, location, filename):
         self.log_user()
-        repo = fixture.create_repo('commit-test-%s' % cnt, repo_type='hg')
+        repo = fixture.create_repo(u'commit-test-%s' % cnt, repo_type='hg')
         response = self.app.post(url('files_add_home',
                                       repo_name=repo.repo_name,
                                       revision='tip', f_path='/'),
@@ -387,7 +392,7 @@
                                  status=302)
         try:
             self.checkSessionFlash(response, 'Successfully committed to %s'
-                                   % os.path.join(location, filename))
+                                   % posixpath.join(location, filename))
         finally:
             fixture.destroy_repo(repo.repo_name)
 
@@ -423,7 +428,7 @@
 
         self.checkSessionFlash(response, 'No filename')
 
-    @parameterized.expand([
+    @parametrize('location,filename', [
         ('/abs', 'foo'),
         ('../rel', 'foo'),
         ('file/../foo', 'foo'),
@@ -443,14 +448,14 @@
 
         self.checkSessionFlash(response, 'Location must be relative path and must not contain .. in path')
 
-    @parameterized.expand([
+    @parametrize('cnt,location,filename', [
         (1, '', 'foo.txt'),
         (2, 'dir', 'foo.rst'),
         (3, 'rel/dir', 'foo.bar'),
     ])
     def test_add_file_into_git(self, cnt, location, filename):
         self.log_user()
-        repo = fixture.create_repo('commit-test-%s' % cnt, repo_type='git')
+        repo = fixture.create_repo(u'commit-test-%s' % cnt, repo_type='git')
         response = self.app.post(url('files_add_home',
                                       repo_name=repo.repo_name,
                                       revision='tip', f_path='/'),
@@ -463,7 +468,7 @@
                                  status=302)
         try:
             self.checkSessionFlash(response, 'Successfully committed to %s'
-                                   % os.path.join(location, filename))
+                                   % posixpath.join(location, filename))
         finally:
             fixture.destroy_repo(repo.repo_name)
 
@@ -476,7 +481,7 @@
 
     def test_edit_file_view_not_on_branch_hg(self):
         self.log_user()
-        repo = fixture.create_repo('test-edit-repo', repo_type='hg')
+        repo = fixture.create_repo(u'test-edit-repo', repo_type='hg')
 
         ## add file
         location = 'vcs'
@@ -494,10 +499,10 @@
         response.follow()
         try:
             self.checkSessionFlash(response, 'Successfully committed to %s'
-                                   % os.path.join(location, filename))
+                                   % posixpath.join(location, filename))
             response = self.app.get(url('files_edit_home',
                                           repo_name=repo.repo_name,
-                                          revision='tip', f_path='vcs/nodes.py'),
+                                          revision='tip', f_path=posixpath.join(location, filename)),
                                     status=302)
             self.checkSessionFlash(response,
                 'You can only edit files with revision being a valid branch')
@@ -506,7 +511,7 @@
 
     def test_edit_file_view_commit_changes_hg(self):
         self.log_user()
-        repo = fixture.create_repo('test-edit-repo', repo_type='hg')
+        repo = fixture.create_repo(u'test-edit-repo', repo_type='hg')
 
         ## add file
         location = 'vcs'
@@ -525,19 +530,19 @@
         response.follow()
         try:
             self.checkSessionFlash(response, 'Successfully committed to %s'
-                                   % os.path.join(location, filename))
+                                   % posixpath.join(location, filename))
             response = self.app.post(url('files_edit_home',
                                           repo_name=repo.repo_name,
                                           revision=repo.scm_instance.DEFAULT_BRANCH_NAME,
-                                          f_path='vcs/nodes.py'),
+                                          f_path=posixpath.join(location, filename)),
                                      params={
                                         'content': "def py():\n print 'hello world'\n",
-                                        'message': 'i commited',
+                                        'message': 'i committed',
                                         '_authentication_token': self.authentication_token(),
                                      },
                                     status=302)
-            self.checkSessionFlash(response,
-                                   'Successfully committed to vcs/nodes.py')
+            self.checkSessionFlash(response, 'Successfully committed to %s'
+                                   % posixpath.join(location, filename))
         finally:
             fixture.destroy_repo(repo.repo_name)
 
@@ -550,7 +555,7 @@
 
     def test_edit_file_view_not_on_branch_git(self):
         self.log_user()
-        repo = fixture.create_repo('test-edit-repo', repo_type='git')
+        repo = fixture.create_repo(u'test-edit-repo', repo_type='git')
 
         ## add file
         location = 'vcs'
@@ -568,10 +573,10 @@
         response.follow()
         try:
             self.checkSessionFlash(response, 'Successfully committed to %s'
-                                   % os.path.join(location, filename))
+                                   % posixpath.join(location, filename))
             response = self.app.get(url('files_edit_home',
                                           repo_name=repo.repo_name,
-                                          revision='tip', f_path='vcs/nodes.py'),
+                                          revision='tip', f_path=posixpath.join(location, filename)),
                                     status=302)
             self.checkSessionFlash(response,
                 'You can only edit files with revision being a valid branch')
@@ -580,7 +585,7 @@
 
     def test_edit_file_view_commit_changes_git(self):
         self.log_user()
-        repo = fixture.create_repo('test-edit-repo', repo_type='git')
+        repo = fixture.create_repo(u'test-edit-repo', repo_type='git')
 
         ## add file
         location = 'vcs'
@@ -599,19 +604,19 @@
         response.follow()
         try:
             self.checkSessionFlash(response, 'Successfully committed to %s'
-                                   % os.path.join(location, filename))
+                                   % posixpath.join(location, filename))
             response = self.app.post(url('files_edit_home',
                                           repo_name=repo.repo_name,
                                           revision=repo.scm_instance.DEFAULT_BRANCH_NAME,
-                                          f_path='vcs/nodes.py'),
+                                          f_path=posixpath.join(location, filename)),
                                      params={
                                         'content': "def py():\n print 'hello world'\n",
-                                        'message': 'i commited',
+                                        'message': 'i committed',
                                         '_authentication_token': self.authentication_token(),
                                      },
                                     status=302)
-            self.checkSessionFlash(response,
-                                   'Successfully committed to vcs/nodes.py')
+            self.checkSessionFlash(response, 'Successfully committed to %s'
+                                   % posixpath.join(location, filename))
         finally:
             fixture.destroy_repo(repo.repo_name)
 
@@ -624,7 +629,7 @@
 
     def test_delete_file_view_not_on_branch_hg(self):
         self.log_user()
-        repo = fixture.create_repo('test-delete-repo', repo_type='hg')
+        repo = fixture.create_repo(u'test-delete-repo', repo_type='hg')
 
         ## add file
         location = 'vcs'
@@ -642,10 +647,10 @@
         response.follow()
         try:
             self.checkSessionFlash(response, 'Successfully committed to %s'
-                                   % os.path.join(location, filename))
+                                   % posixpath.join(location, filename))
             response = self.app.get(url('files_delete_home',
                                           repo_name=repo.repo_name,
-                                          revision='tip', f_path='vcs/nodes.py'),
+                                          revision='tip', f_path=posixpath.join(location, filename)),
                                     status=302)
             self.checkSessionFlash(response,
                 'You can only delete files with revision being a valid branch')
@@ -654,7 +659,7 @@
 
     def test_delete_file_view_commit_changes_hg(self):
         self.log_user()
-        repo = fixture.create_repo('test-delete-repo', repo_type='hg')
+        repo = fixture.create_repo(u'test-delete-repo', repo_type='hg')
 
         ## add file
         location = 'vcs'
@@ -673,18 +678,18 @@
         response.follow()
         try:
             self.checkSessionFlash(response, 'Successfully committed to %s'
-                                   % os.path.join(location, filename))
+                                   % posixpath.join(location, filename))
             response = self.app.post(url('files_delete_home',
                                           repo_name=repo.repo_name,
                                           revision=repo.scm_instance.DEFAULT_BRANCH_NAME,
-                                          f_path='vcs/nodes.py'),
+                                          f_path=posixpath.join(location, filename)),
                                      params={
-                                        'message': 'i commited',
+                                        'message': 'i committed',
                                         '_authentication_token': self.authentication_token(),
                                      },
                                     status=302)
             self.checkSessionFlash(response,
-                                   'Successfully deleted file vcs/nodes.py')
+                                   'Successfully deleted file %s' % posixpath.join(location, filename))
         finally:
             fixture.destroy_repo(repo.repo_name)
 
@@ -697,7 +702,7 @@
 
     def test_delete_file_view_not_on_branch_git(self):
         self.log_user()
-        repo = fixture.create_repo('test-delete-repo', repo_type='git')
+        repo = fixture.create_repo(u'test-delete-repo', repo_type='git')
 
         ## add file
         location = 'vcs'
@@ -715,10 +720,10 @@
         response.follow()
         try:
             self.checkSessionFlash(response, 'Successfully committed to %s'
-                                   % os.path.join(location, filename))
+                                   % posixpath.join(location, filename))
             response = self.app.get(url('files_delete_home',
                                           repo_name=repo.repo_name,
-                                          revision='tip', f_path='vcs/nodes.py'),
+                                          revision='tip', f_path=posixpath.join(location, filename)),
                                     status=302)
             self.checkSessionFlash(response,
                 'You can only delete files with revision being a valid branch')
@@ -727,7 +732,7 @@
 
     def test_delete_file_view_commit_changes_git(self):
         self.log_user()
-        repo = fixture.create_repo('test-delete-repo', repo_type='git')
+        repo = fixture.create_repo(u'test-delete-repo', repo_type='git')
 
         ## add file
         location = 'vcs'
@@ -746,17 +751,17 @@
         response.follow()
         try:
             self.checkSessionFlash(response, 'Successfully committed to %s'
-                                   % os.path.join(location, filename))
+                                   % posixpath.join(location, filename))
             response = self.app.post(url('files_delete_home',
                                           repo_name=repo.repo_name,
                                           revision=repo.scm_instance.DEFAULT_BRANCH_NAME,
-                                          f_path='vcs/nodes.py'),
+                                          f_path=posixpath.join(location, filename)),
                                      params={
-                                        'message': 'i commited',
+                                        'message': 'i committed',
                                         '_authentication_token': self.authentication_token(),
                                      },
                                     status=302)
             self.checkSessionFlash(response,
-                                   'Successfully deleted file vcs/nodes.py')
+                                   'Successfully deleted file %s' % posixpath.join(location, filename))
         finally:
             fixture.destroy_repo(repo.repo_name)
--- a/kallithea/tests/functional/test_followers.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_followers.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 
 
 class TestFollowersController(TestController):
--- a/kallithea/tests/functional/test_forks.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_forks.py	Fri Nov 18 01:11:13 2016 +0100
@@ -2,7 +2,7 @@
 
 import unittest
 
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.tests.fixture import Fixture
 
 from kallithea.model.db import Repository
@@ -12,31 +12,7 @@
 
 fixture = Fixture()
 
-from kallithea.tests import *
-
-
-class _BaseFixture(unittest.TestCase):
-    @classmethod
-    def setup_class(cls):
-        pass
-
-    @classmethod
-    def teardown_class(cls):
-        pass
-
-    def setUp(self):
-        self.username = u'forkuser'
-        self.password = u'qweqwe'
-        self.u1 = fixture.create_user(self.username, password=self.password,
-                                      email=u'fork_king@example.com')
-        Session().commit()
-
-    def tearDown(self):
-        Session().delete(self.u1)
-        Session().commit()
-
-
-class _BaseTestCase(object):
+class _BaseTestCase(TestController):
     """
     Write all tests here
     """
@@ -45,6 +21,18 @@
     NEW_REPO = None
     REPO_FORK = None
 
+    def setup_method(self, method):
+        self.username = u'forkuser'
+        self.password = u'qweqwe'
+        self.u1 = fixture.create_user(self.username, password=self.password,
+                                      email=u'fork_king@example.com')
+        Session().commit()
+
+    def teardown_method(self, method):
+        Session().delete(self.u1)
+        Session().commit()
+
+
     def test_index(self):
         self.log_user()
         repo_name = self.REPO
@@ -97,11 +85,11 @@
 
         # remove this fork
         response = self.app.post(url('delete_repo', repo_name=fork_name),
-            params={'_method': 'delete', '_authentication_token': self.authentication_token()})
+            params={'_authentication_token': self.authentication_token()})
 
     def test_fork_create_into_group(self):
         self.log_user()
-        group = fixture.create_repo_group('vc')
+        group = fixture.create_repo_group(u'vc')
         group_id = group.group_id
         fork_name = self.REPO_FORK
         fork_name_full = 'vc/%s' % fork_name
@@ -130,11 +118,11 @@
                 % (repo_name, fork_name_full, fork_name_full))
 
         #test if the fork was created in the database
-        fork_repo = Session().query(Repository)\
+        fork_repo = Session().query(Repository) \
             .filter(Repository.repo_name == fork_name_full).one()
 
-        self.assertEqual(fork_repo.repo_name, fork_name_full)
-        self.assertEqual(fork_repo.fork.repo_name, repo_name)
+        assert fork_repo.repo_name == fork_name_full
+        assert fork_repo.fork.repo_name == repo_name
 
         # test if the repository is visible in the list ?
         response = self.app.get(url('summary_home', repo_name=fork_name_full))
@@ -173,11 +161,11 @@
                 % (repo_name, fork_name, fork_name))
 
         #test if the fork was created in the database
-        fork_repo = Session().query(Repository)\
+        fork_repo = Session().query(Repository) \
             .filter(Repository.repo_name == fork_name).one()
 
-        self.assertEqual(fork_repo.repo_name, fork_name)
-        self.assertEqual(fork_repo.fork.repo_name, repo_name)
+        assert fork_repo.repo_name == fork_name
+        assert fork_repo.fork.repo_name == repo_name
 
         # test if the repository is visible in the list ?
         response = self.app.get(url('summary_home', repo_name=fork_name))
@@ -189,10 +177,10 @@
         usr = self.log_user(self.username, self.password)['user_id']
         repo_name = self.REPO
 
-        forks = Repository.query()\
-            .filter(Repository.repo_type == self.REPO_TYPE)\
+        forks = Repository.query() \
+            .filter(Repository.repo_type == self.REPO_TYPE) \
             .filter(Repository.fork_id != None).all()
-        self.assertEqual(1, len(forks))
+        assert 1 == len(forks)
 
         # set read permissions for this
         RepoModel().grant_user_permission(repo=forks[0],
@@ -209,10 +197,10 @@
         usr = self.log_user(self.username, self.password)['user_id']
         repo_name = self.REPO
 
-        forks = Repository.query()\
-            .filter(Repository.repo_type == self.REPO_TYPE)\
+        forks = Repository.query() \
+            .filter(Repository.repo_type == self.REPO_TYPE) \
             .filter(Repository.fork_id != None).all()
-        self.assertEqual(1, len(forks))
+        assert 1 == len(forks)
 
         # set none
         RepoModel().grant_user_permission(repo=forks[0],
@@ -224,14 +212,14 @@
         response.mustcontain('There are no forks yet')
 
 
-class TestGIT(TestController, _BaseTestCase, _BaseFixture):
+class TestGIT(_BaseTestCase):
     REPO = GIT_REPO
     NEW_REPO = NEW_GIT_REPO
     REPO_TYPE = 'git'
     REPO_FORK = GIT_FORK
 
 
-class TestHG(TestController, _BaseTestCase, _BaseFixture):
+class TestHG(_BaseTestCase):
     REPO = HG_REPO
     NEW_REPO = NEW_HG_REPO
     REPO_TYPE = 'hg'
--- a/kallithea/tests/functional/test_home.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_home.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.tests.fixture import Fixture
 from kallithea.model.meta import Session
 from kallithea.model.db import Repository
@@ -17,7 +17,7 @@
         #if global permission is set
         response.mustcontain('Add Repository')
         # html in javascript variable:
-        response.mustcontain('var data = {"totalRecords": %s' % len(Repository.getAll()))
+        response.mustcontain('var data = {"totalRecords": %s' % Repository.query().count())
         response.mustcontain(r'href=\"/%s\"' % HG_REPO)
 
         response.mustcontain(r'<span class="repotag">git')
@@ -44,13 +44,13 @@
 
     def test_index_page_on_groups(self):
         self.log_user()
-        gr = fixture.create_repo_group('gr1')
-        fixture.create_repo(name='gr1/repo_in_group', repo_group=gr)
-        response = self.app.get(url('repos_group_home', group_name='gr1'))
+        gr = fixture.create_repo_group(u'gr1')
+        fixture.create_repo(name=u'gr1/repo_in_group', repo_group=gr)
+        response = self.app.get(url('repos_group_home', group_name=u'gr1'))
 
         try:
-            response.mustcontain("gr1/repo_in_group")
+            response.mustcontain(u"gr1/repo_in_group")
         finally:
-            RepoModel().delete('gr1/repo_in_group')
-            RepoGroupModel().delete(repo_group='gr1', force_delete=True)
+            RepoModel().delete(u'gr1/repo_in_group')
+            RepoGroupModel().delete(repo_group=u'gr1', force_delete=True)
             Session().commit()
--- a/kallithea/tests/functional/test_journal.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_journal.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 import datetime
 
 
@@ -15,15 +15,15 @@
 #        usr = Session().query(User).filter(User.username == TEST_USER_ADMIN_LOGIN).one()
 #        repo = Session().query(Repository).filter(Repository.repo_name == HG_REPO).one()
 #
-#        followings = Session().query(UserFollowing)\
-#            .filter(UserFollowing.user == usr)\
+#        followings = Session().query(UserFollowing) \
+#            .filter(UserFollowing.user == usr) \
 #            .filter(UserFollowing.follows_repository == repo).all()
 #
 #        assert len(followings) == 1, 'Not following any repository'
 #
 #        response = self.app.post(url(controller='journal',
 #                                     action='toggle_following'),
-#                                     {'follows_repo_id':repo.repo_id})
+#                                     {'follows_repository_id':repo.repo_id})
 
     def test_start_following_repository(self):
         self.log_user()
--- a/kallithea/tests/functional/test_login.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_login.py	Fri Nov 18 01:11:13 2016 +0100
@@ -5,7 +5,7 @@
 
 import mock
 
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.tests.fixture import Fixture
 from kallithea.lib.utils2 import generate_api_key
 from kallithea.lib.auth import check_password
@@ -20,20 +20,20 @@
 
 
 class TestLoginController(TestController):
-    def setUp(self):
+    def setup_method(self, method):
         self.remove_all_notifications()
-        self.assertEqual(Notification.query().all(), [])
+        assert Notification.query().all() == []
 
     def test_index(self):
         response = self.app.get(url(controller='login', action='index'))
-        self.assertEqual(response.status, '200 OK')
+        assert response.status == '200 OK'
         # Test response...
 
     def test_login_admin_ok(self):
         response = self.app.post(url(controller='login', action='index'),
                                  {'username': TEST_USER_ADMIN_LOGIN,
                                   'password': TEST_USER_ADMIN_PASS})
-        self.assertEqual(response.status, '302 Found')
+        assert response.status == '302 Found'
         self.assert_authenticated_user(response, TEST_USER_ADMIN_LOGIN)
 
         response = response.follow()
@@ -44,7 +44,18 @@
                                  {'username': TEST_USER_REGULAR_LOGIN,
                                   'password': TEST_USER_REGULAR_PASS})
 
-        self.assertEqual(response.status, '302 Found')
+        assert response.status == '302 Found'
+        self.assert_authenticated_user(response, TEST_USER_REGULAR_LOGIN)
+
+        response = response.follow()
+        response.mustcontain('/%s' % HG_REPO)
+
+    def test_login_regular_email_ok(self):
+        response = self.app.post(url(controller='login', action='index'),
+                                 {'username': TEST_USER_REGULAR_EMAIL,
+                                  'password': TEST_USER_REGULAR_PASS})
+
+        assert response.status == '302 Found'
         self.assert_authenticated_user(response, TEST_USER_REGULAR_LOGIN)
 
         response = response.follow()
@@ -56,10 +67,10 @@
                                      came_from=test_came_from),
                                  {'username': TEST_USER_ADMIN_LOGIN,
                                   'password': TEST_USER_ADMIN_PASS})
-        self.assertEqual(response.status, '302 Found')
+        assert response.status == '302 Found'
         response = response.follow()
 
-        self.assertEqual(response.status, '200 OK')
+        assert response.status == '200 OK'
         response.mustcontain('Users Administration')
 
     def test_login_do_not_remember(self):
@@ -68,10 +79,9 @@
                                   'password': TEST_USER_REGULAR_PASS,
                                   'remember': False})
 
-        self.assertIn('Set-Cookie', response.headers)
+        assert 'Set-Cookie' in response.headers
         for cookie in response.headers.getall('Set-Cookie'):
-            self.assertFalse(re.search(r';\s+(Max-Age|Expires)=', cookie, re.IGNORECASE),
-                'Cookie %r has expiration date, but should be a session cookie' % cookie)
+            assert not re.search(r';\s+(Max-Age|Expires)=', cookie, re.IGNORECASE), 'Cookie %r has expiration date, but should be a session cookie' % cookie
 
     def test_login_remember(self):
         response = self.app.post(url(controller='login', action='index'),
@@ -79,10 +89,9 @@
                                   'password': TEST_USER_REGULAR_PASS,
                                   'remember': True})
 
-        self.assertIn('Set-Cookie', response.headers)
+        assert 'Set-Cookie' in response.headers
         for cookie in response.headers.getall('Set-Cookie'):
-            self.assertTrue(re.search(r';\s+(Max-Age|Expires)=', cookie, re.IGNORECASE),
-                'Cookie %r should have expiration date, but is a session cookie' % cookie)
+            assert re.search(r';\s+(Max-Age|Expires)=', cookie, re.IGNORECASE), 'Cookie %r should have expiration date, but is a session cookie' % cookie
 
     def test_logout(self):
         response = self.app.post(url(controller='login', action='index'),
@@ -92,15 +101,15 @@
         # Verify that a login session has been established.
         response = self.app.get(url(controller='login', action='index'))
         response = response.follow()
-        self.assertIn('authuser', response.session)
+        assert 'authuser' in response.session
 
         response.click('Log Out')
 
         # Verify that the login session has been terminated.
         response = self.app.get(url(controller='login', action='index'))
-        self.assertNotIn('authuser', response.session)
+        assert 'authuser' not in response.session
 
-    @parameterized.expand([
+    @parametrize('url_came_from', [
           ('data:text/html,<script>window.alert("xss")</script>',),
           ('mailto:test@example.com',),
           ('file:///etc/passwd',),
@@ -122,7 +131,7 @@
         response = self.app.post(url(controller='login', action='index'),
                                  {'username': TEST_USER_ADMIN_LOGIN,
                                   'password': 'as'})
-        self.assertEqual(response.status, '200 OK')
+        assert response.status == '200 OK'
 
         response.mustcontain('Enter 3 characters or more')
 
@@ -135,7 +144,7 @@
 
     # verify that get arguments are correctly passed along login redirection
 
-    @parameterized.expand([
+    @parametrize('args,args_encoded', [
         ({'foo':'one', 'bar':'two'}, (('foo', 'one'), ('bar', 'two'))),
         ({'blue': u'blå'.encode('utf-8'), 'green':u'grøn'},
              (('blue', u'blå'.encode('utf-8')), ('green', u'grøn'.encode('utf-8')))),
@@ -145,13 +154,13 @@
             response = self.app.get(url(controller='summary', action='index',
                                         repo_name=HG_REPO,
                                         **args))
-            self.assertEqual(response.status, '302 Found')
+            assert response.status == '302 Found'
             came_from = urlparse.parse_qs(urlparse.urlparse(response.location).query)['came_from'][0]
             came_from_qs = urlparse.parse_qsl(urlparse.urlparse(came_from).query)
             for encoded in args_encoded:
-                self.assertIn(encoded, came_from_qs)
+                assert encoded in came_from_qs
 
-    @parameterized.expand([
+    @parametrize('args,args_encoded', [
         ({'foo':'one', 'bar':'two'}, ('foo=one', 'bar=two')),
         ({'blue': u'blå', 'green':u'grøn'},
              ('blue=bl%C3%A5', 'green=gr%C3%B8n')),
@@ -161,9 +170,9 @@
                                     came_from=url('/_admin/users', **args)))
         came_from = urlparse.parse_qs(urlparse.urlparse(response.form.action).query)['came_from'][0]
         for encoded in args_encoded:
-            self.assertIn(encoded, came_from)
+            assert encoded in came_from
 
-    @parameterized.expand([
+    @parametrize('args,args_encoded', [
         ({'foo':'one', 'bar':'two'}, ('foo=one', 'bar=two')),
         ({'blue': u'blå', 'green':u'grøn'},
              ('blue=bl%C3%A5', 'green=gr%C3%B8n')),
@@ -173,11 +182,11 @@
                                      came_from = url('/_admin/users', **args)),
                                  {'username': TEST_USER_ADMIN_LOGIN,
                                   'password': TEST_USER_ADMIN_PASS})
-        self.assertEqual(response.status, '302 Found')
+        assert response.status == '302 Found'
         for encoded in args_encoded:
-            self.assertIn(encoded, response.location)
+            assert encoded in response.location
 
-    @parameterized.expand([
+    @parametrize('args,args_encoded', [
         ({'foo':'one', 'bar':'two'}, ('foo=one', 'bar=two')),
         ({'blue': u'blå', 'green':u'grøn'},
              ('blue=bl%C3%A5', 'green=gr%C3%B8n')),
@@ -191,7 +200,7 @@
         response.mustcontain('Invalid username or password')
         came_from = urlparse.parse_qs(urlparse.urlparse(response.form.action).query)['came_from'][0]
         for encoded in args_encoded:
-            self.assertIn(encoded, came_from)
+            assert encoded in came_from
 
     #==========================================================================
     # REGISTRATIONS
@@ -245,7 +254,7 @@
                                              'email': 'goodmailm',
                                              'firstname': 'test',
                                              'lastname': 'test'})
-        self.assertEqual(response.status, '200 OK')
+        assert response.status == '200 OK'
         response.mustcontain('An email address must contain a single @')
         response.mustcontain('Enter a value 6 characters long or more')
 
@@ -316,18 +325,18 @@
                                              'email': email,
                                              'firstname': name,
                                              'lastname': lastname,
-                                             'admin': True})  # This should be overriden
-        self.assertEqual(response.status, '302 Found')
-        self.checkSessionFlash(response, 'You have successfully registered into Kallithea')
+                                             'admin': True})  # This should be overridden
+        assert response.status == '302 Found'
+        self.checkSessionFlash(response, 'You have successfully registered with Kallithea')
 
         ret = Session().query(User).filter(User.username == 'test_regular4').one()
-        self.assertEqual(ret.username, username)
-        self.assertEqual(check_password(password, ret.password), True)
-        self.assertEqual(ret.email, email)
-        self.assertEqual(ret.name, name)
-        self.assertEqual(ret.lastname, lastname)
-        self.assertNotEqual(ret.api_key, None)
-        self.assertEqual(ret.admin, False)
+        assert ret.username == username
+        assert check_password(password, ret.password) == True
+        assert ret.email == email
+        assert ret.name == name
+        assert ret.lastname == lastname
+        assert ret.api_key != None
+        assert ret.admin == False
 
     #==========================================================================
     # PASSWORD RESET
@@ -345,13 +354,13 @@
     def test_forgot_password(self):
         response = self.app.get(url(controller='login',
                                     action='password_reset'))
-        self.assertEqual(response.status, '200 OK')
+        assert response.status == '200 OK'
 
         username = 'test_password_reset_1'
         password = 'qweqwe'
         email = 'username@example.com'
-        name = 'passwd'
-        lastname = 'reset'
+        name = u'passwd'
+        lastname = u'reset'
         timestamp = int(time.time())
 
         new = User()
@@ -384,7 +393,7 @@
                                   'password_confirm': "p@ssw0rd",
                                   'token': token,
                                  })
-        self.assertEqual(response.status, '200 OK')
+        assert response.status == '200 OK'
         response.mustcontain('Invalid password reset token')
 
         # GOOD TOKEN
@@ -400,7 +409,7 @@
                                     email=email,
                                     timestamp=timestamp,
                                     token=token))
-        self.assertEqual(response.status, '200 OK')
+        assert response.status == '200 OK'
         response.mustcontain("You are about to set a new password for the email address %s" % email)
 
         response = self.app.post(url(controller='login',
@@ -411,7 +420,7 @@
                                   'password_confirm': "p@ssw0rd",
                                   'token': token,
                                  })
-        self.assertEqual(response.status, '302 Found')
+        assert response.status == '302 Found'
         self.checkSessionFlash(response, 'Successfully updated password')
 
         response = response.follow()
@@ -424,78 +433,67 @@
         config = {'api_access_controllers_whitelist': values or []}
         return config
 
-    @parameterized.expand([
-        ('none', None),
-        ('empty_string', ''),
-        ('fake_number', '123456'),
-        ('proper_api_key', None)
+    def _api_key_test(self, api_key, status):
+        """Verifies HTTP status code for accessing an auth-requiring page,
+        using the given api_key URL parameter. If api_key is None, no api_key
+        parameter is passed at all. If api_key is True, a real, working API key
+        is used.
+        """
+        with fixture.anon_access(False):
+            if api_key is None:
+                params = {}
+            else:
+                if api_key is True:
+                    api_key = User.get_first_admin().api_key
+                params = {'api_key': api_key}
+
+            self.app.get(url(controller='changeset', action='changeset_raw',
+                             repo_name=HG_REPO, revision='tip', **params),
+                         status=status)
+
+    @parametrize('test_name,api_key,code', [
+        ('none', None, 302),
+        ('empty_string', '', 403),
+        ('fake_number', '123456', 403),
+        ('proper_api_key', True, 403)
     ])
-    def test_access_not_whitelisted_page_via_api_key(self, test_name, api_key):
+    def test_access_not_whitelisted_page_via_api_key(self, test_name, api_key, code):
         whitelist = self._get_api_whitelist([])
         with mock.patch('kallithea.CONFIG', whitelist):
-            self.assertEqual([],
-                             whitelist['api_access_controllers_whitelist'])
-            if test_name == 'proper_api_key':
-                #use builtin if api_key is None
-                api_key = User.get_first_admin().api_key
+            assert [] == whitelist['api_access_controllers_whitelist']
+            self._api_key_test(api_key, code)
 
-            with fixture.anon_access(False):
-                self.app.get(url(controller='changeset',
-                                 action='changeset_raw',
-                                 repo_name=HG_REPO, revision='tip', api_key=api_key),
-                             status=403)
-
-    @parameterized.expand([
+    @parametrize('test_name,api_key,code', [
         ('none', None, 302),
         ('empty_string', '', 302),
         ('fake_number', '123456', 302),
         ('fake_not_alnum', 'a-z', 302),
         ('fake_api_key', '0123456789abcdef0123456789ABCDEF01234567', 302),
-        ('proper_api_key', None, 200)
+        ('proper_api_key', True, 200)
     ])
     def test_access_whitelisted_page_via_api_key(self, test_name, api_key, code):
         whitelist = self._get_api_whitelist(['ChangesetController:changeset_raw'])
         with mock.patch('kallithea.CONFIG', whitelist):
-            self.assertEqual(['ChangesetController:changeset_raw'],
-                             whitelist['api_access_controllers_whitelist'])
-            if test_name == 'proper_api_key':
-                api_key = User.get_first_admin().api_key
-
-            with fixture.anon_access(False):
-                self.app.get(url(controller='changeset',
-                                 action='changeset_raw',
-                                 repo_name=HG_REPO, revision='tip', api_key=api_key),
-                             status=code)
+            assert ['ChangesetController:changeset_raw'] == whitelist['api_access_controllers_whitelist']
+            self._api_key_test(api_key, code)
 
     def test_access_page_via_extra_api_key(self):
         whitelist = self._get_api_whitelist(['ChangesetController:changeset_raw'])
         with mock.patch('kallithea.CONFIG', whitelist):
-            self.assertEqual(['ChangesetController:changeset_raw'],
-                             whitelist['api_access_controllers_whitelist'])
+            assert ['ChangesetController:changeset_raw'] == whitelist['api_access_controllers_whitelist']
 
             new_api_key = ApiKeyModel().create(TEST_USER_ADMIN_LOGIN, u'test')
             Session().commit()
-            with fixture.anon_access(False):
-                self.app.get(url(controller='changeset',
-                                 action='changeset_raw',
-                                 repo_name=HG_REPO, revision='tip', api_key=new_api_key.api_key),
-                             status=200)
+            self._api_key_test(new_api_key.api_key, status=200)
 
     def test_access_page_via_expired_api_key(self):
         whitelist = self._get_api_whitelist(['ChangesetController:changeset_raw'])
         with mock.patch('kallithea.CONFIG', whitelist):
-            self.assertEqual(['ChangesetController:changeset_raw'],
-                             whitelist['api_access_controllers_whitelist'])
+            assert ['ChangesetController:changeset_raw'] == whitelist['api_access_controllers_whitelist']
 
             new_api_key = ApiKeyModel().create(TEST_USER_ADMIN_LOGIN, u'test')
             Session().commit()
             #patch the API key and make it expired
             new_api_key.expires = 0
-            Session().add(new_api_key)
             Session().commit()
-            with fixture.anon_access(False):
-                self.app.get(url(controller='changeset',
-                                 action='changeset_raw',
-                                 repo_name=HG_REPO, revision='tip',
-                                 api_key=new_api_key.api_key),
-                             status=302)
+            self._api_key_test(new_api_key.api_key, status=302)
--- a/kallithea/tests/functional/test_my_account.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_my_account.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,7 +1,7 @@
 # -*- coding: utf-8 -*-
 
 from kallithea.model.db import User, UserFollowing, Repository, UserApiKeys
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.tests.fixture import Fixture
 from kallithea.lib import helpers as h
 from kallithea.model.user import UserModel
@@ -28,7 +28,7 @@
     def test_my_account_my_repos(self):
         self.log_user()
         response = self.app.get(url('my_account_repos'))
-        cnt = Repository.query().filter(Repository.user ==
+        cnt = Repository.query().filter(Repository.owner ==
                            User.get_by_username(TEST_USER_ADMIN_LOGIN)).count()
         response.mustcontain('"totalRecords": %s' % cnt)
 
@@ -53,7 +53,7 @@
                                  {'new_email': TEST_USER_REGULAR_EMAIL, '_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'This email address is already in use')
 
-    def test_my_account_my_emails_add_mising_email_in_form(self):
+    def test_my_account_my_emails_add_missing_email_in_form(self):
         self.log_user()
         response = self.app.get(url('my_account_emails'))
         response.mustcontain('No additional emails specified')
@@ -72,21 +72,21 @@
         response = self.app.get(url('my_account_emails'))
 
         from kallithea.model.db import UserEmailMap
-        email_id = UserEmailMap.query()\
-            .filter(UserEmailMap.user == User.get_by_username(TEST_USER_ADMIN_LOGIN))\
+        email_id = UserEmailMap.query() \
+            .filter(UserEmailMap.user == User.get_by_username(TEST_USER_ADMIN_LOGIN)) \
             .filter(UserEmailMap.email == 'barz@example.com').one().email_id
 
         response.mustcontain('barz@example.com')
         response.mustcontain('<input id="del_email_id" name="del_email_id" type="hidden" value="%s" />' % email_id)
 
-        response = self.app.post(url('my_account_emails'),
-                                 {'del_email_id': email_id, '_method': 'delete', '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('my_account_emails_delete'),
+                                 {'del_email_id': email_id, '_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'Removed email from user')
         response = self.app.get(url('my_account_emails'))
         response.mustcontain('No additional emails specified')
 
 
-    @parameterized.expand(
+    @parametrize('name,attrs',
         [('firstname', {'firstname': 'new_username'}),
          ('lastname', {'lastname': 'new_username'}),
          ('admin', {'admin': True}),
@@ -145,7 +145,7 @@
             params['admin'] = False
 
         params.pop('_authentication_token')
-        self.assertEqual(params, updated_params)
+        assert params == updated_params
 
     def test_my_account_update_err_email_exists(self):
         self.log_user()
@@ -156,8 +156,8 @@
                                     username=TEST_USER_ADMIN_LOGIN,
                                     new_password=TEST_USER_ADMIN_PASS,
                                     password_confirmation='test122',
-                                    firstname='NewName',
-                                    lastname='NewLastname',
+                                    firstname=u'NewName',
+                                    lastname=u'NewLastname',
                                     email=new_email,
                                     _authentication_token=self.authentication_token())
                                 )
@@ -173,14 +173,14 @@
                                             username=TEST_USER_ADMIN_LOGIN,
                                             new_password=TEST_USER_ADMIN_PASS,
                                             password_confirmation='test122',
-                                            firstname='NewName',
-                                            lastname='NewLastname',
+                                            firstname=u'NewName',
+                                            lastname=u'NewLastname',
                                             email=new_email,
                                             _authentication_token=self.authentication_token()))
 
         response.mustcontain('An email address must contain a single @')
         from kallithea.model import validators
-        msg = validators.ValidUsername(edit=False, old_data={})\
+        msg = validators.ValidUsername(edit=False, old_data={}) \
                 ._messages['username_exists']
         msg = h.html_escape(msg % {'username': TEST_USER_ADMIN_LOGIN})
         response.mustcontain(msg)
@@ -192,7 +192,7 @@
         response.mustcontain(user.api_key)
         response.mustcontain('Expires: Never')
 
-    @parameterized.expand([
+    @parametrize('desc,lifetime', [
         ('forever', -1),
         ('5mins', 60*5),
         ('30days', 60*60*24*30),
@@ -223,13 +223,13 @@
 
         #now delete our key
         keys = UserApiKeys.query().all()
-        self.assertEqual(1, len(keys))
+        assert 1 == len(keys)
 
-        response = self.app.post(url('my_account_api_keys'),
-                 {'_method': 'delete', 'del_api_key': keys[0].api_key, '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('my_account_api_keys_delete'),
+                 {'del_api_key': keys[0].api_key, '_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'API key successfully deleted')
         keys = UserApiKeys.query().all()
-        self.assertEqual(0, len(keys))
+        assert 0 == len(keys)
 
 
     def test_my_account_reset_main_api_key(self):
@@ -240,8 +240,8 @@
         response.mustcontain(api_key)
         response.mustcontain('Expires: Never')
 
-        response = self.app.post(url('my_account_api_keys'),
-                 {'_method': 'delete', 'del_api_key_builtin': api_key, '_authentication_token': self.authentication_token()})
+        response = self.app.post(url('my_account_api_keys_delete'),
+                 {'del_api_key_builtin': api_key, '_authentication_token': self.authentication_token()})
         self.checkSessionFlash(response, 'API key successfully reset')
         response = response.follow()
         response.mustcontain(no=[api_key])
--- a/kallithea/tests/functional/test_pullrequests.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_pullrequests.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,7 +1,8 @@
 import re
 
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.tests.fixture import Fixture
+from kallithea.model.db import User
 from kallithea.model.meta import Session
 
 from kallithea.controllers.pullrequests import PullrequestsController
@@ -20,55 +21,118 @@
         response = self.app.post(url(controller='pullrequests', action='create',
                                      repo_name=HG_REPO),
                                  {'org_repo': HG_REPO,
-                                  'org_ref': 'branch:default:default',
+                                  'org_ref': 'branch:stable:4f7e2131323e0749a740c0a56ab68ae9269c562a',
                                   'other_repo': HG_REPO,
-                                  'other_ref': 'branch:default:default',
+                                  'other_ref': 'branch:default:96507bd11ecc815ebc6270fdf6db110928c09c1e',
                                   'pullrequest_title': 'title',
                                   'pullrequest_desc': 'description',
                                   '_authentication_token': self.authentication_token(),
-                                 }
-                                )
-        self.assertEqual(response.status, '302 Found')
+                                 },
+                                 status=302)
         response = response.follow()
-        self.assertEqual(response.status, '200 OK')
-        response.mustcontain('This pull request has already been merged to default.')
+        assert response.status == '200 OK'
+        response.mustcontain('Successfully opened new pull request')
+        response.mustcontain('No additional changesets found for iterating on this pull request')
+        response.mustcontain('href="/vcs_test_hg/changeset/4f7e2131323e0749a740c0a56ab68ae9269c562a"')
 
-    def test_create_with_existing_reviewer(self):
+    def test_available(self):
+        self.log_user()
+        response = self.app.post(url(controller='pullrequests', action='create',
+                                     repo_name=HG_REPO),
+                                 {'org_repo': HG_REPO,
+                                  'org_ref': 'rev:94f45ed825a1:94f45ed825a113e61af7e141f44ca578374abef0',
+                                  'other_repo': HG_REPO,
+                                  'other_ref': 'branch:default:96507bd11ecc815ebc6270fdf6db110928c09c1e',
+                                  'pullrequest_title': 'title',
+                                  'pullrequest_desc': 'description',
+                                  '_authentication_token': self.authentication_token(),
+                                 },
+                                 status=302)
+        response = response.follow()
+        assert response.status == '200 OK'
+        response.mustcontain(no='No additional changesets found for iterating on this pull request')
+        response.mustcontain('The following additional changes are available on stable:')
+        response.mustcontain('<input id="updaterev_4f7e2131323e0749a740c0a56ab68ae9269c562a" name="updaterev" type="radio" value="4f7e2131323e0749a740c0a56ab68ae9269c562a" />')
+        response.mustcontain('href="/vcs_test_hg/changeset/4f7e2131323e0749a740c0a56ab68ae9269c562a"') # as update
+
+    def test_range(self):
         self.log_user()
         response = self.app.post(url(controller='pullrequests', action='create',
                                      repo_name=HG_REPO),
                                  {'org_repo': HG_REPO,
-                                  'org_ref': 'branch:default:default',
+                                  'org_ref': 'branch:stable:4f7e2131323e0749a740c0a56ab68ae9269c562a',
                                   'other_repo': HG_REPO,
-                                  'other_ref': 'branch:default:default',
+                                  'other_ref': 'rev:94f45ed825a1:94f45ed825a113e61af7e141f44ca578374abef0',
+                                  'pullrequest_title': 'title',
+                                  'pullrequest_desc': 'description',
+                                  '_authentication_token': self.authentication_token(),
+                                 },
+                                 status=302)
+        response = response.follow()
+        assert response.status == '200 OK'
+        response.mustcontain('No additional changesets found for iterating on this pull request')
+        response.mustcontain('href="/vcs_test_hg/changeset/4f7e2131323e0749a740c0a56ab68ae9269c562a"')
+
+    def test_update_reviewers(self):
+        self.log_user()
+        regular_user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
+        regular_user2 = User.get_by_username(TEST_USER_REGULAR2_LOGIN)
+        admin_user = User.get_by_username(TEST_USER_ADMIN_LOGIN)
+
+        # create initial PR
+        response = self.app.post(url(controller='pullrequests', action='create',
+                                     repo_name=HG_REPO),
+                                 {'org_repo': HG_REPO,
+                                  'org_ref': 'rev:94f45ed825a1:94f45ed825a113e61af7e141f44ca578374abef0',
+                                  'other_repo': HG_REPO,
+                                  'other_ref': 'branch:default:96507bd11ecc815ebc6270fdf6db110928c09c1e',
                                   'pullrequest_title': 'title',
                                   'pullrequest_desc': 'description',
                                   '_authentication_token': self.authentication_token(),
-                                  'review_members': TEST_USER_ADMIN_LOGIN,
-                                 }
-                                )
-        self.assertEqual(response.status, '302 Found')
-        response = response.follow()
-        self.assertEqual(response.status, '200 OK')
-        response.mustcontain('This pull request has already been merged to default.')
+                                 },
+                                 status=302)
+        pull_request1_id = re.search('/pull-request/(\d+)/', response.location).group(1)
+        assert response.location == 'http://localhost/%s/pull-request/%s/_/stable' % (HG_REPO, pull_request1_id)
 
-    def test_create_with_invalid_reviewer(self):
-        invalid_user_name = 'invalid_user'
-        self.log_user()
-        response = self.app.post(url(controller='pullrequests', action='create',
-                                     repo_name=HG_REPO),
+        # create new iteration
+        response = self.app.post(url(controller='pullrequests', action='post',
+                                     repo_name=HG_REPO, pull_request_id=pull_request1_id),
                                  {
-                                  'org_repo': HG_REPO,
-                                  'org_ref': 'branch:default:default',
-                                  'other_repo': HG_REPO,
-                                  'other_ref': 'branch:default:default',
+                                  'updaterev': '4f7e2131323e0749a740c0a56ab68ae9269c562a',
                                   'pullrequest_title': 'title',
                                   'pullrequest_desc': 'description',
+                                  'owner': TEST_USER_ADMIN_LOGIN,
                                   '_authentication_token': self.authentication_token(),
-                                  'review_members': invalid_user_name,
+                                  'review_members': [regular_user.user_id],
                                  },
-                                 status=400)
-        response.mustcontain('Invalid reviewer &#34;%s&#34; specified' % invalid_user_name)
+                                 status=302)
+        pull_request2_id = re.search('/pull-request/(\d+)/', response.location).group(1)
+        assert pull_request2_id != pull_request1_id
+        assert response.location == 'http://localhost/%s/pull-request/%s/_/stable' % (HG_REPO, pull_request2_id)
+        response = response.follow()
+        # verify reviewer was added
+        response.mustcontain('<input type="hidden" value="%s" name="review_members" />' % regular_user.user_id)
+
+        # update without creating new iteration
+        response = self.app.post(url(controller='pullrequests', action='post',
+                                     repo_name=HG_REPO, pull_request_id=pull_request2_id),
+                                 {
+                                  'pullrequest_title': 'Title',
+                                  'pullrequest_desc': 'description',
+                                  'owner': TEST_USER_ADMIN_LOGIN,
+                                  '_authentication_token': self.authentication_token(),
+                                  'org_review_members': [admin_user.user_id], # fake - just to get some 'meanwhile' warning ... but it is also added ...
+                                  'review_members': [regular_user2.user_id, admin_user.user_id],
+                                 },
+                                 status=302)
+        assert response.location == 'http://localhost/%s/pull-request/%s/_/stable' % (HG_REPO, pull_request2_id)
+        response = response.follow()
+        # verify reviewers were added / removed
+        response.mustcontain('Meanwhile, the following reviewers have been added: test_regular')
+        response.mustcontain('Meanwhile, the following reviewers have been removed: test_admin')
+        response.mustcontain('<input type="hidden" value="%s" name="review_members" />' % regular_user.user_id)
+        response.mustcontain('<input type="hidden" value="%s" name="review_members" />' % regular_user2.user_id)
+        response.mustcontain(no='<input type="hidden" value="%s" name="review_members" />' % admin_user.user_id)
 
     def test_update_with_invalid_reviewer(self):
         invalid_user_id = 99999
@@ -78,31 +142,30 @@
                                      repo_name=HG_REPO),
                                  {
                                   'org_repo': HG_REPO,
-                                  'org_ref': 'branch:default:default',
+                                  'org_ref': 'rev:94f45ed825a1:94f45ed825a113e61af7e141f44ca578374abef0',
                                   'other_repo': HG_REPO,
-                                  'other_ref': 'branch:default:default',
+                                  'other_ref': 'branch:default:96507bd11ecc815ebc6270fdf6db110928c09c1e',
                                   'pullrequest_title': 'title',
                                   'pullrequest_desc': 'description',
                                   '_authentication_token': self.authentication_token(),
-                                 }
-                                )
-        self.assertEqual(response.status, '302 Found')
+                                 },
+                                status=302)
         # location is of the form:
         # http://localhost/vcs_test_hg/pull-request/54/_/title
         m = re.search('/pull-request/(\d+)/', response.location)
-        self.assertNotEqual(m, None)
+        assert m != None
         pull_request_id = m.group(1)
 
         # update it
         response = self.app.post(url(controller='pullrequests', action='post',
                                      repo_name=HG_REPO, pull_request_id=pull_request_id),
                                  {
-                                  'updaterev': 'default',
+                                  'updaterev': '4f7e2131323e0749a740c0a56ab68ae9269c562a',
                                   'pullrequest_title': 'title',
                                   'pullrequest_desc': 'description',
                                   'owner': TEST_USER_ADMIN_LOGIN,
                                   '_authentication_token': self.authentication_token(),
-                                  'review_members': invalid_user_id,
+                                  'review_members': [str(invalid_user_id)],
                                  },
                                  status=400)
         response.mustcontain('Invalid reviewer &#34;%s&#34; specified' % invalid_user_id)
@@ -115,19 +178,18 @@
                                      repo_name=HG_REPO),
                                  {
                                   'org_repo': HG_REPO,
-                                  'org_ref': 'branch:default:default',
+                                  'org_ref': 'branch:stable:4f7e2131323e0749a740c0a56ab68ae9269c562a',
                                   'other_repo': HG_REPO,
-                                  'other_ref': 'branch:default:default',
+                                  'other_ref': 'branch:default:96507bd11ecc815ebc6270fdf6db110928c09c1e',
                                   'pullrequest_title': 'title',
                                   'pullrequest_desc': 'description',
                                   '_authentication_token': self.authentication_token(),
-                                 }
-                                )
-        self.assertEqual(response.status, '302 Found')
+                                 },
+                                status=302)
         # location is of the form:
         # http://localhost/vcs_test_hg/pull-request/54/_/title
         m = re.search('/pull-request/(\d+)/', response.location)
-        self.assertNotEqual(m, None)
+        assert m != None
         pull_request_id = m.group(1)
 
         # edit it
@@ -138,28 +200,27 @@
                                   'pullrequest_desc': 'description',
                                   'owner': TEST_USER_ADMIN_LOGIN,
                                   '_authentication_token': self.authentication_token(),
-                                  'review_members': invalid_user_id,
+                                  'review_members': [str(invalid_user_id)],
                                  },
                                  status=400)
         response.mustcontain('Invalid reviewer &#34;%s&#34; specified' % invalid_user_id)
 
 class TestPullrequestsGetRepoRefs(TestController):
 
-    def setUp(self):
-        self.main = fixture.create_repo('main', repo_type='hg')
-        Session.add(self.main)
+    def setup_method(self, method):
+        self.main = fixture.create_repo(u'main', repo_type='hg')
         Session.commit()
         self.c = PullrequestsController()
 
-    def tearDown(self):
-        fixture.destroy_repo('main')
+    def teardown_method(self, method):
+        fixture.destroy_repo(u'main')
         Session.commit()
         Session.remove()
 
     def test_repo_refs_empty_repo(self):
         # empty repo with no commits, no branches, no bookmarks, just one tag
         refs, default = self.c._get_repo_refs(self.main.scm_instance)
-        self.assertEqual(default, 'tag:null:0000000000000000000000000000000000000000')
+        assert default == 'tag:null:0000000000000000000000000000000000000000'
 
     def test_repo_refs_one_commit_no_hints(self):
         cs0 = fixture.commit_change(self.main.repo_name, filename='file1',
@@ -167,9 +228,9 @@
                 parent=None, newfile=True)
 
         refs, default = self.c._get_repo_refs(self.main.scm_instance)
-        self.assertEqual(default, 'branch:default:%s' % cs0.raw_id)
-        self.assertIn(([('branch:default:%s' % cs0.raw_id, 'default (current tip)')],
-                'Branches'), refs)
+        assert default == 'branch:default:%s' % cs0.raw_id
+        assert ([('branch:default:%s' % cs0.raw_id, 'default (current tip)')],
+                'Branches') in refs
 
     def test_repo_refs_one_commit_rev_hint(self):
         cs0 = fixture.commit_change(self.main.repo_name, filename='file1',
@@ -178,8 +239,8 @@
 
         refs, default = self.c._get_repo_refs(self.main.scm_instance, rev=cs0.raw_id)
         expected = 'branch:default:%s' % cs0.raw_id
-        self.assertEqual(default, expected)
-        self.assertIn(([(expected, 'default (current tip)')], 'Branches'), refs)
+        assert default == expected
+        assert ([(expected, 'default (current tip)')], 'Branches') in refs
 
     def test_repo_refs_two_commits_no_hints(self):
         cs0 = fixture.commit_change(self.main.repo_name, filename='file1',
@@ -191,8 +252,8 @@
 
         refs, default = self.c._get_repo_refs(self.main.scm_instance)
         expected = 'branch:default:%s' % cs1.raw_id
-        self.assertEqual(default, expected)
-        self.assertIn(([(expected, 'default (current tip)')], 'Branches'), refs)
+        assert default == expected
+        assert ([(expected, 'default (current tip)')], 'Branches') in refs
 
     def test_repo_refs_two_commits_rev_hints(self):
         cs0 = fixture.commit_change(self.main.repo_name, filename='file1',
@@ -204,14 +265,14 @@
 
         refs, default = self.c._get_repo_refs(self.main.scm_instance, rev=cs0.raw_id)
         expected = 'rev:%s:%s' % (cs0.raw_id, cs0.raw_id)
-        self.assertEqual(default, expected)
-        self.assertIn(([(expected, 'Changeset: %s' % cs0.raw_id[0:12])], 'Special'), refs)
-        self.assertIn(([('branch:default:%s' % cs1.raw_id, 'default (current tip)')], 'Branches'), refs)
+        assert default == expected
+        assert ([(expected, 'Changeset: %s' % cs0.raw_id[0:12])], 'Special') in refs
+        assert ([('branch:default:%s' % cs1.raw_id, 'default (current tip)')], 'Branches') in refs
 
         refs, default = self.c._get_repo_refs(self.main.scm_instance, rev=cs1.raw_id)
         expected = 'branch:default:%s' % cs1.raw_id
-        self.assertEqual(default, expected)
-        self.assertIn(([(expected, 'default (current tip)')], 'Branches'), refs)
+        assert default == expected
+        assert ([(expected, 'default (current tip)')], 'Branches') in refs
 
     def test_repo_refs_two_commits_branch_hint(self):
         cs0 = fixture.commit_change(self.main.repo_name, filename='file1',
@@ -223,8 +284,8 @@
 
         refs, default = self.c._get_repo_refs(self.main.scm_instance, branch='default')
         expected = 'branch:default:%s' % cs1.raw_id
-        self.assertEqual(default, expected)
-        self.assertIn(([(expected, 'default (current tip)')], 'Branches'), refs)
+        assert default == expected
+        assert ([(expected, 'default (current tip)')], 'Branches') in refs
 
     def test_repo_refs_one_branch_no_hints(self):
         cs0 = fixture.commit_change(self.main.repo_name, filename='file1',
--- a/kallithea/tests/functional/test_repo_groups.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_repo_groups.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 
 
 class TestRepoGroupsController(TestController):
@@ -8,26 +8,71 @@
         response = self.app.get(url('repos_groups'))
         response.mustcontain('{"totalRecords": 0, "sort": null, "startIndex": 0, "dir": "asc", "records": []};')
 
-#    def test_create(self):
-#        response = self.app.post(url('repos_groups'))
-
     def test_new(self):
         self.log_user()
         response = self.app.get(url('new_repos_group'))
 
+    def test_create(self):
+        self.log_user()
+
+        group_name = 'foo'
+
+        # creation with form error
+        response = self.app.post(url('repos_groups'),
+                                         {'group_name': group_name,
+                                          '_authentication_token': self.authentication_token()})
+        response.mustcontain('name="group_name" type="text" value="%s"' % group_name)
+        response.mustcontain('<!-- for: group_description -->')
+
+        # creation
+        response = self.app.post(url('repos_groups'),
+                                         {'group_name': group_name,
+                                         'group_description': 'lala',
+                                         'parent_group_id': '-1',
+                                         'group_copy_permissions': 'True',
+                                          '_authentication_token': self.authentication_token()})
+        self.checkSessionFlash(response, 'Created repository group %s' % group_name)
+
+        # edit form
+        response = self.app.get(url('edit_repo_group', group_name=group_name))
+        response.mustcontain('>lala<')
+
+        # edit with form error
+        response = self.app.post(url('update_repos_group', group_name=group_name),
+                                         {'group_name': group_name,
+                                          '_authentication_token': self.authentication_token()})
+        response.mustcontain('name="group_name" type="text" value="%s"' % group_name)
+        response.mustcontain('<!-- for: group_description -->')
+
+        # edit
+        response = self.app.post(url('update_repos_group', group_name=group_name),
+                                         {'group_name': group_name,
+                                         'group_description': 'lolo',
+                                          '_authentication_token': self.authentication_token()})
+        self.checkSessionFlash(response, 'Updated repository group %s' % group_name)
+        response = response.follow()
+        response.mustcontain('name="group_name" type="text" value="%s"' % group_name)
+        response.mustcontain(no='<!-- for: group_description -->')
+        response.mustcontain('>lolo<')
+
+        # listing
+        response = self.app.get(url('repos_groups'))
+        response.mustcontain('"totalRecords": 1')
+        response.mustcontain('raw_name": "%s"' % group_name)
+
+        # show
+        response = self.app.get(url('repos_group', group_name=group_name))
+        response.mustcontain('href="/_admin/repo_groups/%s/edit"' % group_name)
+
+        # show ignores extra trailing slashes in the URL
+        response = self.app.get(url('repos_group', group_name='%s//' % group_name))
+        response.mustcontain('href="/_admin/repo_groups/%s/edit"' % group_name)
+
+        # delete
+        response = self.app.post(url('delete_repo_group', group_name=group_name),
+                                 {'_authentication_token': self.authentication_token()})
+        self.checkSessionFlash(response, 'Removed repository group %s' % group_name)
+
     def test_new_by_regular_user(self):
         self.log_user(TEST_USER_REGULAR_LOGIN, TEST_USER_REGULAR_PASS)
         response = self.app.get(url('new_repos_group'), status=403)
-#
-#    def test_update(self):
-#        response = self.app.put(url('repos_group', group_name=1))
-#
-#    def test_delete(self):
-#        self.log_user()
-#        response = self.app.delete(url('repos_group', group_name=1))
-#
-#    def test_show(self):
-#        response = self.app.get(url('repos_group', group_name=1))
-#
-#    def test_edit(self):
-#        response = self.app.get(url('edit_repo_group', group_name=1))
--- a/kallithea/tests/functional/test_search.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_search.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,5 +1,6 @@
+import mock
 import os
-from kallithea.tests import *
+from kallithea.tests.base import *
 
 
 class TestSearchController(TestController):
@@ -11,11 +12,16 @@
         response.mustcontain('class="small" id="q" name="q" type="text"')
         # Test response...
 
-    def test_empty_search(self):
-        if os.path.isdir(self.index_location):
-            raise SkipTest('skipped due to existing index')
-        else:
-            self.log_user()
+    def test_empty_search(self, tmpdir):
+        self.log_user()
+
+        config_mock = {
+            'app_conf': {
+                # can be any existing dir that does not contain an actual index
+                'index_dir': str(tmpdir),
+            }
+        }
+        with mock.patch('kallithea.controllers.search.config', config_mock):
             response = self.app.get(url(controller='search', action='index'),
                                     {'q': HG_REPO})
             response.mustcontain('There is no index to search in. '
--- a/kallithea/tests/functional/test_summary.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/functional/test_summary.py	Fri Nov 18 01:11:13 2016 +0100
@@ -12,7 +12,7 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.tests.fixture import Fixture
 from kallithea.model.db import Repository
 from kallithea.model.repo import RepoModel
@@ -82,7 +82,7 @@
 
     def test_index_by_repo_having_id_path_in_name_hg(self):
         self.log_user()
-        fixture.create_repo(name='repo_1')
+        fixture.create_repo(name=u'repo_1')
         response = self.app.get(url(controller='summary',
                                     action='index',
                                     repo_name='repo_1'))
@@ -90,7 +90,7 @@
         try:
             response.mustcontain("repo_1")
         finally:
-            RepoModel().delete(Repository.get_by_repo_name('repo_1'))
+            RepoModel().delete(Repository.get_by_repo_name(u'repo_1'))
             Session().commit()
 
     def test_index_by_id_git(self):
@@ -112,7 +112,6 @@
     def _enable_stats(self, repo):
         r = Repository.get_by_repo_name(repo)
         r.enable_statistics = True
-        Session().add(r)
         Session().commit()
 
     def test_index_trending(self):
@@ -121,6 +120,9 @@
         self._enable_stats(HG_REPO)
 
         ScmModel().mark_for_invalidation(HG_REPO)
+        # generate statistics first
+        response = self.app.get(url(controller='summary', action='statistics',
+                                    repo_name=HG_REPO))
         response = self.app.get(url(controller='summary', action='index',
                                     repo_name=HG_REPO))
         response.mustcontain(
@@ -151,6 +153,9 @@
         self._enable_stats(GIT_REPO)
 
         ScmModel().mark_for_invalidation(GIT_REPO)
+        # generate statistics first
+        response = self.app.get(url(controller='summary', action='statistics',
+                                    repo_name=GIT_REPO))
         response = self.app.get(url(controller='summary', action='index',
                                     repo_name=GIT_REPO))
         response.mustcontain(
--- a/kallithea/tests/functional/test_tags.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,40 +0,0 @@
-from kallithea.tests import *
-
-
-class TestTagsController(TestController):
-
-    def test_index_hg(self):
-        self.log_user()
-        response = self.app.get(url(controller='tags', action='index', repo_name=HG_REPO))
-        response.mustcontain("""<a href="/%s/changeset/96507bd11ecc815ebc6270fdf6db110928c09c1e">tip</a>""" % HG_REPO)
-        response.mustcontain("""<a href="/%s/changeset/2c96c02def9a7c997f33047761a53943e6254396">v0.2.0</a>""" % HG_REPO)
-        response.mustcontain("""<a href="/%s/changeset/fef5bfe1dc17611d5fb59a7f6f95c55c3606f933">v0.1.11</a>""" % HG_REPO)
-        response.mustcontain("""<a href="/%s/changeset/92831aebf2f8dd4879e897024b89d09af214df1c">v0.1.10</a>""" % HG_REPO)
-        response.mustcontain("""<a href="/%s/changeset/8680b1d1cee3aa3c1ab3734b76ee164bbedbc5c9">v0.1.9</a>""" % HG_REPO)
-        response.mustcontain("""<a href="/%s/changeset/ecb25ba9c96faf1e65a0bc3fd914918420a2f116">v0.1.8</a>""" % HG_REPO)
-        response.mustcontain("""<a href="/%s/changeset/f67633a2894edaf28513706d558205fa93df9209">v0.1.7</a>""" % HG_REPO)
-        response.mustcontain("""<a href="/%s/changeset/02b38c0eb6f982174750c0e309ff9faddc0c7e12">v0.1.6</a>""" % HG_REPO)
-        response.mustcontain("""<a href="/%s/changeset/a6664e18181c6fc81b751a8d01474e7e1a3fe7fc">v0.1.5</a>""" % HG_REPO)
-        response.mustcontain("""<a href="/%s/changeset/fd4bdb5e9b2a29b4393a4ac6caef48c17ee1a200">v0.1.4</a>""" % HG_REPO)
-        response.mustcontain("""<a href="/%s/changeset/17544fbfcd33ffb439e2b728b5d526b1ef30bfcf">v0.1.3</a>""" % HG_REPO)
-        response.mustcontain("""<a href="/%s/changeset/a7e60bff65d57ac3a1a1ce3b12a70f8a9e8a7720">v0.1.2</a>""" % HG_REPO)
-        response.mustcontain("""<a href="/%s/changeset/eb3a60fc964309c1a318b8dfe26aa2d1586c85ae">v0.1.1</a>""" % HG_REPO)
-
-    def test_index_git(self):
-        self.log_user()
-        response = self.app.get(url(controller='tags', action='index', repo_name=GIT_REPO))
-
-        response.mustcontain("""<a href="/%s/changeset/137fea89f304a42321d40488091ee2ed419a3686">v0.2.2</a>""" % GIT_REPO)
-        response.mustcontain("""<a href="/%s/changeset/5051d0fa344d4408a2659d9a0348eb2d41868ecf">v0.2.1</a>""" % GIT_REPO)
-        response.mustcontain("""<a href="/%s/changeset/599ba911aa24d2981225f3966eb659dfae9e9f30">v0.2.0</a>""" % GIT_REPO)
-        response.mustcontain("""<a href="/%s/changeset/c60f01b77c42dce653d6b1d3b04689862c261929">v0.1.11</a>""" % GIT_REPO)
-        response.mustcontain("""<a href="/%s/changeset/10cddef6b794696066fb346434014f0a56810218">v0.1.10</a>""" % GIT_REPO)
-        response.mustcontain("""<a href="/%s/changeset/341d28f0eec5ddf0b6b77871e13c2bbd6bec685c">v0.1.9</a>""" % GIT_REPO)
-        response.mustcontain("""<a href="/%s/changeset/74ebce002c088b8a5ecf40073db09375515ecd68">v0.1.8</a>""" % GIT_REPO)
-        response.mustcontain("""<a href="/%s/changeset/4d78bf73b5c22c82b68f902f138f7881b4fffa2c">v0.1.7</a>""" % GIT_REPO)
-        response.mustcontain("""<a href="/%s/changeset/0205cb3f44223fb3099d12a77a69c81b798772d9">v0.1.6</a>""" % GIT_REPO)
-        response.mustcontain("""<a href="/%s/changeset/6c0ce52b229aa978889e91b38777f800e85f330b">v0.1.5</a>""" % GIT_REPO)
-        response.mustcontain("""<a href="/%s/changeset/7d735150934cd7645ac3051903add952390324a5">v0.1.4</a>""" % GIT_REPO)
-        response.mustcontain("""<a href="/%s/changeset/5a3a8fb005554692b16e21dee62bf02667d8dc3e">v0.1.3</a>""" % GIT_REPO)
-        response.mustcontain("""<a href="/%s/changeset/0ba5f8a4660034ff25c0cac2a5baabf5d2791d63">v0.1.2</a>""" % GIT_REPO)
-        response.mustcontain("""<a href="/%s/changeset/e6ea6d16e2f26250124a1f4b4fe37a912f9d86a0">v0.1.1</a>""" % GIT_REPO)
--- a/kallithea/tests/models/common.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/models/common.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.tests.fixture import Fixture
 
 from kallithea.model.repo_group import RepoGroupModel
@@ -15,7 +15,7 @@
 
 def _destroy_project_tree(test_u1_id):
     Session.remove()
-    repo_group = RepoGroup.get_by_group_name(group_name='g0')
+    repo_group = RepoGroup.get_by_group_name(group_name=u'g0')
     for el in reversed(repo_group.recursive_groups_and_repos()):
         if isinstance(el, Repository):
             RepoModel().delete(el)
@@ -56,18 +56,18 @@
         username=u'test_u1', password=u'qweqwe',
         email=u'test_u1@example.com', firstname=u'test_u1', lastname=u'test_u1'
     )
-    g0 = fixture.create_repo_group('g0')
-    g0_1 = fixture.create_repo_group('g0_1', group_parent_id=g0)
-    g0_1_1 = fixture.create_repo_group('g0_1_1', group_parent_id=g0_1)
-    g0_1_1_r1 = fixture.create_repo('g0/g0_1/g0_1_1/g0_1_1_r1', repo_group=g0_1_1)
-    g0_1_1_r2 = fixture.create_repo('g0/g0_1/g0_1_1/g0_1_1_r2', repo_group=g0_1_1)
-    g0_1_r1 = fixture.create_repo('g0/g0_1/g0_1_r1', repo_group=g0_1)
-    g0_2 = fixture.create_repo_group('g0_2', group_parent_id=g0)
-    g0_2_r1 = fixture.create_repo('g0/g0_2/g0_2_r1', repo_group=g0_2)
-    g0_2_r2 = fixture.create_repo('g0/g0_2/g0_2_r2', repo_group=g0_2)
-    g0_3 = fixture.create_repo_group('g0_3', group_parent_id=g0)
-    g0_3_r1 = fixture.create_repo('g0/g0_3/g0_3_r1', repo_group=g0_3)
-    g0_3_r2_private = fixture.create_repo('g0/g0_3/g0_3_r1_private',
+    g0 = fixture.create_repo_group(u'g0')
+    g0_1 = fixture.create_repo_group(u'g0_1', parent_group_id=g0)
+    g0_1_1 = fixture.create_repo_group(u'g0_1_1', parent_group_id=g0_1)
+    g0_1_1_r1 = fixture.create_repo(u'g0/g0_1/g0_1_1/g0_1_1_r1', repo_group=g0_1_1)
+    g0_1_1_r2 = fixture.create_repo(u'g0/g0_1/g0_1_1/g0_1_1_r2', repo_group=g0_1_1)
+    g0_1_r1 = fixture.create_repo(u'g0/g0_1/g0_1_r1', repo_group=g0_1)
+    g0_2 = fixture.create_repo_group(u'g0_2', parent_group_id=g0)
+    g0_2_r1 = fixture.create_repo(u'g0/g0_2/g0_2_r1', repo_group=g0_2)
+    g0_2_r2 = fixture.create_repo(u'g0/g0_2/g0_2_r2', repo_group=g0_2)
+    g0_3 = fixture.create_repo_group(u'g0_3', parent_group_id=g0)
+    g0_3_r1 = fixture.create_repo(u'g0/g0_3/g0_3_r1', repo_group=g0_3)
+    g0_3_r2_private = fixture.create_repo(u'g0/g0_3/g0_3_r1_private',
                                           repo_group=g0_3, repo_private=True)
     return test_u1
 
--- a/kallithea/tests/models/test_changeset_status.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/models/test_changeset_status.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.model.changeset_status import ChangesetStatusModel
 from kallithea.model.db import ChangesetStatus as CS
 
@@ -7,12 +7,12 @@
     def __init__(self, status):
         self.status = status
 
-class TestChangesetStatusCalculation(BaseTestCase):
+class TestChangesetStatusCalculation(TestController):
 
-    def setUp(self):
+    def setup_method(self, method):
         self.m = ChangesetStatusModel()
 
-    @parameterized.expand([
+    @parametrize('name,expected_result,statuses', [
         ('empty list', CS.STATUS_UNDER_REVIEW, []),
         ('approve', CS.STATUS_APPROVED, [CSM(CS.STATUS_APPROVED)]),
         ('approve2', CS.STATUS_APPROVED, [CSM(CS.STATUS_APPROVED), CSM(CS.STATUS_APPROVED)]),
@@ -37,4 +37,4 @@
     ])
     def test_result(self, name, expected_result, statuses):
         result = self.m._calculate_status(statuses)
-        self.assertEqual(result, expected_result)
+        assert result == expected_result
--- a/kallithea/tests/models/test_diff_parsers.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/models/test_diff_parsers.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,4 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.lib.diffs import DiffProcessor, NEW_FILENODE, DEL_FILENODE, \
     MOD_FILENODE, RENAMED_FILENODE, CHMOD_FILENODE, BIN_FILENODE, COPIED_FILENODE
 from kallithea.tests.fixture import Fixture
@@ -271,31 +271,34 @@
 }
 
 
-class DiffLibTest(BaseTestCase):
+class TestDiffLib(TestController):
 
-    @parameterized.expand([(x,) for x in DIFF_FIXTURES])
+    @parametrize('diff_fixture', DIFF_FIXTURES)
     def test_diff(self, diff_fixture):
         diff = fixture.load_resource(diff_fixture, strip=False)
-        diff_proc = DiffProcessor(diff)
+        vcs = 'hg'
+        if diff_fixture.startswith('git_'):
+            vcs = 'git'
+        diff_proc = DiffProcessor(diff, vcs=vcs)
         diff_proc_d = diff_proc.prepare()
         data = [(x['filename'], x['operation'], x['stats']) for x in diff_proc_d]
         expected_data = DIFF_FIXTURES[diff_fixture]
-        self.assertListEqual(expected_data, data)
+        assert expected_data == data
 
     def test_diff_markup(self):
         diff = fixture.load_resource('markuptest.diff', strip=False)
         diff_proc = DiffProcessor(diff)
         diff_proc_d = diff_proc.prepare()
         chunks = diff_proc_d[0]['chunks']
-        self.assertFalse(chunks[0])
+        assert not chunks[0]
         #from pprint import pprint; pprint(chunks[1])
         l = ['\n']
         for d in chunks[1]:
             l.append('%(action)-7s %(new_lineno)3s %(old_lineno)3s %(line)r\n' % d)
         s = ''.join(l)
         print s
-        self.assertEqual(s, r'''
-context ... ... u'@@ -51,5 +51,12 @@\n'
+        assert s == r'''
+context ... ... u'@@ -51,6 +51,13 @@\n'
 unmod    51  51 u'<u>\t</u>begin();\n'
 unmod    52  52 u'<u>\t</u>\n'
 add      53     u'<u>\t</u>int foo;<u class="cr"></u>\n'
@@ -305,8 +308,10 @@
 add      57     u'<u>\t</u>int tab;<u>\t</u>\n'
 add      58     u'<u>\t</u>\n'
 unmod    59  53 u' <i></i>'
-del          54 u'<u>\t</u><del>#define MAX_STEPS (48)</del>\n'
-add      60     u'<u>\t</u><ins><u class="cr"></u></ins>\n'
+del          54 u'<u>\t</u>#define MAX_STEPS (48)\n'
+add      60     u'<u>\t</u><u class="cr"></u>\n'
 add      61     u'<u>\t</u>#define MAX_STEPS (64)<u class="cr"></u>\n'
 unmod    62  55 u'\n'
-''')
+del          56 u'<u>\t</u>#define MIN_STEPS (<del>48</del>)\n'
+add      63     u'<u>\t</u>#define MIN_STEPS (<ins>42</ins>)\n'
+'''
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/tests/models/test_dump_html_mails.ref.html	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,2755 @@
+<!doctype html>
+<html lang="en">
+<head><title>Notifications</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>
+<body>
+<hr/>
+<h1>cs_comment, is_mention=False, status_change=None</h1>
+<pre>
+From: u1
+To: u2@example.com
+Subject: [Comment] repo/name changeset cafe1234 "This changeset did something cl..." on brunch
+</pre>
+<hr/>
+<pre>http://comment.org
+
+Comment on Changeset "This changeset did something clever which is hard to explain"
+
+
+Opinionated User (jsmith):
+
+This is the new comment.
+
+ - and here it ends indented.
+
+
+Changeset on repo_target branch brunch:
+"This changeset did something clever which is hard to explain" by u2 u3 (u2).
+
+
+View Comment: http://comment.org
+</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <a style="text-decoration:none;color:#395fa0" href="http://comment.org"
+               target="_blank">Comment on Changeset &#34;This changeset did something clever which is hard to explain&#34;</a>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+<table cellpadding="0" cellspacing="0" width="100%" border="0" bgcolor="#f9f9f9" style="border:1px solid #ddd;border-radius:4px">
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-weight:600;color:#395fa0">Opinionated User (jsmith)</div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-family:Lucida Console,Consolas,Monaco,Inconsolata,Liberation Mono,monospace;white-space:pre-wrap"><div class="formatted-fixed">This is the new comment.<br/><br/> - and here it ends indented.</div></div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+</table>
+        </td>
+    </tr>
+    <tr>
+        <td height="30px"></td>
+    </tr>
+    <tr>
+        <td>
+            <div>
+                Changeset on
+                <a style="color:#395fa0;text-decoration:none"
+                   href="repo_target">repo_target</a>
+                branch
+                <span style="color:#395fa0">brunch</span>:
+            </div>
+            <div>
+                "<a style="color:#395fa0;text-decoration:none"
+                   href="http://changeset.com">This changeset did something clever which is hard to explain</a>"
+                by
+                <span style="color:#395fa0">u2 u3 (u2)</span>.
+            </div>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<table cellspacing="0" cellpadding="0" style="margin-left:auto;margin-right:auto">
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    <tr>
+        <td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #395fa0">
+            <a href="http://comment.org" style="text-decoration:none;display:block" target="_blank">
+                <center style="padding:11px 20px">
+                    <font size="3">
+                        <span style="font-family:Helvetica,Arial,sans-serif;font-weight:700;font-size:15px;line-height:14px;color:#395fa0;white-space:nowrap;vertical-align:middle">View Comment</span>
+                    </font>
+                </center>
+            </a>
+        </td>
+    </tr>
+</table>
+        </td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+<hr/>
+<h1>cs_comment, is_mention=True, status_change=None</h1>
+<pre>
+From: u1
+To: u2@example.com
+Subject: [Comment] repo/name changeset cafe1234 "This changeset did something cl..." on brunch
+</pre>
+<hr/>
+<pre>http://comment.org
+
+Mention in Comment on Changeset "This changeset did something clever which is hard to explain"
+
+
+Opinionated User (jsmith):
+
+This is the new comment.
+
+ - and here it ends indented.
+
+
+Changeset on repo_target branch brunch:
+"This changeset did something clever which is hard to explain" by u2 u3 (u2).
+
+
+View Comment: http://comment.org
+</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <a style="text-decoration:none;color:#395fa0" href="http://comment.org"
+               target="_blank">Mention in Comment on Changeset &#34;This changeset did something clever which is hard to explain&#34;</a>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+<table cellpadding="0" cellspacing="0" width="100%" border="0" bgcolor="#f9f9f9" style="border:1px solid #ddd;border-radius:4px">
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-weight:600;color:#395fa0">Opinionated User (jsmith)</div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-family:Lucida Console,Consolas,Monaco,Inconsolata,Liberation Mono,monospace;white-space:pre-wrap"><div class="formatted-fixed">This is the new comment.<br/><br/> - and here it ends indented.</div></div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+</table>
+        </td>
+    </tr>
+    <tr>
+        <td height="30px"></td>
+    </tr>
+    <tr>
+        <td>
+            <div>
+                Changeset on
+                <a style="color:#395fa0;text-decoration:none"
+                   href="repo_target">repo_target</a>
+                branch
+                <span style="color:#395fa0">brunch</span>:
+            </div>
+            <div>
+                "<a style="color:#395fa0;text-decoration:none"
+                   href="http://changeset.com">This changeset did something clever which is hard to explain</a>"
+                by
+                <span style="color:#395fa0">u2 u3 (u2)</span>.
+            </div>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<table cellspacing="0" cellpadding="0" style="margin-left:auto;margin-right:auto">
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    <tr>
+        <td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #395fa0">
+            <a href="http://comment.org" style="text-decoration:none;display:block" target="_blank">
+                <center style="padding:11px 20px">
+                    <font size="3">
+                        <span style="font-family:Helvetica,Arial,sans-serif;font-weight:700;font-size:15px;line-height:14px;color:#395fa0;white-space:nowrap;vertical-align:middle">View Comment</span>
+                    </font>
+                </center>
+            </a>
+        </td>
+    </tr>
+</table>
+        </td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+<hr/>
+<h1>cs_comment, is_mention=False, status_change='Approved'</h1>
+<pre>
+From: u1
+To: u2@example.com
+Subject: [Approved: Comment] repo/name changeset cafe1234 "This changeset did something cl..." on brunch
+</pre>
+<hr/>
+<pre>http://comment.org
+
+Comment on Changeset "This changeset did something clever which is hard to explain"
+
+
+Opinionated User (jsmith):
+
+Status change: Approved
+
+This is the new comment.
+
+ - and here it ends indented.
+
+
+Changeset on repo_target branch brunch:
+"This changeset did something clever which is hard to explain" by u2 u3 (u2).
+
+
+View Comment: http://comment.org
+</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <a style="text-decoration:none;color:#395fa0" href="http://comment.org"
+               target="_blank">Comment on Changeset &#34;This changeset did something clever which is hard to explain&#34;</a>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+<table cellpadding="0" cellspacing="0" width="100%" border="0" bgcolor="#f9f9f9" style="border:1px solid #ddd;border-radius:4px">
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-weight:600;color:#395fa0">Opinionated User (jsmith)</div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+    </tr>
+        <tr>
+            <td height="10px" colspan="3"></td>
+        </tr>
+        <tr>
+            <td width="20px"></td>
+            <td>
+                    <div style="font-weight:600">
+                        Status change:
+                        Approved
+                    </div>
+            </td>
+            <td width="20px"></td>
+        </tr>
+        <tr>
+            <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+        </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-family:Lucida Console,Consolas,Monaco,Inconsolata,Liberation Mono,monospace;white-space:pre-wrap"><div class="formatted-fixed">This is the new comment.<br/><br/> - and here it ends indented.</div></div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+</table>
+        </td>
+    </tr>
+    <tr>
+        <td height="30px"></td>
+    </tr>
+    <tr>
+        <td>
+            <div>
+                Changeset on
+                <a style="color:#395fa0;text-decoration:none"
+                   href="repo_target">repo_target</a>
+                branch
+                <span style="color:#395fa0">brunch</span>:
+            </div>
+            <div>
+                "<a style="color:#395fa0;text-decoration:none"
+                   href="http://changeset.com">This changeset did something clever which is hard to explain</a>"
+                by
+                <span style="color:#395fa0">u2 u3 (u2)</span>.
+            </div>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<table cellspacing="0" cellpadding="0" style="margin-left:auto;margin-right:auto">
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    <tr>
+        <td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #395fa0">
+            <a href="http://comment.org" style="text-decoration:none;display:block" target="_blank">
+                <center style="padding:11px 20px">
+                    <font size="3">
+                        <span style="font-family:Helvetica,Arial,sans-serif;font-weight:700;font-size:15px;line-height:14px;color:#395fa0;white-space:nowrap;vertical-align:middle">View Comment</span>
+                    </font>
+                </center>
+            </a>
+        </td>
+    </tr>
+</table>
+        </td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+<hr/>
+<h1>cs_comment, is_mention=True, status_change='Approved'</h1>
+<pre>
+From: u1
+To: u2@example.com
+Subject: [Approved: Comment] repo/name changeset cafe1234 "This changeset did something cl..." on brunch
+</pre>
+<hr/>
+<pre>http://comment.org
+
+Mention in Comment on Changeset "This changeset did something clever which is hard to explain"
+
+
+Opinionated User (jsmith):
+
+Status change: Approved
+
+This is the new comment.
+
+ - and here it ends indented.
+
+
+Changeset on repo_target branch brunch:
+"This changeset did something clever which is hard to explain" by u2 u3 (u2).
+
+
+View Comment: http://comment.org
+</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <a style="text-decoration:none;color:#395fa0" href="http://comment.org"
+               target="_blank">Mention in Comment on Changeset &#34;This changeset did something clever which is hard to explain&#34;</a>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+<table cellpadding="0" cellspacing="0" width="100%" border="0" bgcolor="#f9f9f9" style="border:1px solid #ddd;border-radius:4px">
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-weight:600;color:#395fa0">Opinionated User (jsmith)</div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+    </tr>
+        <tr>
+            <td height="10px" colspan="3"></td>
+        </tr>
+        <tr>
+            <td width="20px"></td>
+            <td>
+                    <div style="font-weight:600">
+                        Status change:
+                        Approved
+                    </div>
+            </td>
+            <td width="20px"></td>
+        </tr>
+        <tr>
+            <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+        </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-family:Lucida Console,Consolas,Monaco,Inconsolata,Liberation Mono,monospace;white-space:pre-wrap"><div class="formatted-fixed">This is the new comment.<br/><br/> - and here it ends indented.</div></div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+</table>
+        </td>
+    </tr>
+    <tr>
+        <td height="30px"></td>
+    </tr>
+    <tr>
+        <td>
+            <div>
+                Changeset on
+                <a style="color:#395fa0;text-decoration:none"
+                   href="repo_target">repo_target</a>
+                branch
+                <span style="color:#395fa0">brunch</span>:
+            </div>
+            <div>
+                "<a style="color:#395fa0;text-decoration:none"
+                   href="http://changeset.com">This changeset did something clever which is hard to explain</a>"
+                by
+                <span style="color:#395fa0">u2 u3 (u2)</span>.
+            </div>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<table cellspacing="0" cellpadding="0" style="margin-left:auto;margin-right:auto">
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    <tr>
+        <td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #395fa0">
+            <a href="http://comment.org" style="text-decoration:none;display:block" target="_blank">
+                <center style="padding:11px 20px">
+                    <font size="3">
+                        <span style="font-family:Helvetica,Arial,sans-serif;font-weight:700;font-size:15px;line-height:14px;color:#395fa0;white-space:nowrap;vertical-align:middle">View Comment</span>
+                    </font>
+                </center>
+            </a>
+        </td>
+    </tr>
+</table>
+        </td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+<hr/>
+<h1>message</h1>
+<pre>
+From: u1
+To: u2@example.com
+Subject: Test Message
+</pre>
+<hr/>
+<pre>This is the body of the test message
+ - nothing interesting here except indentation.</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <span style="color:#395fa0">Message</span>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td style="font-family:Lucida Console,Consolas,Monaco,Inconsolata,Liberation Mono,monospace;white-space:pre-wrap"><div class="formatted-fixed">This is the body of the test message<br/> - nothing interesting here except indentation.</div></td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+<hr/>
+<h1>registration</h1>
+<pre>
+From: u1
+To: u2@example.com
+Subject: New user newbie registered
+</pre>
+<hr/>
+<pre>http://newbie.org
+
+New User Registration
+
+
+Username: newbie
+
+Full Name: New Full Name
+
+Email: new@email.com
+
+
+View User Profile: http://newbie.org
+</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <a style="text-decoration:none;color:#395fa0" href="http://newbie.org"
+               target="_blank">New User Registration</a>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+            Username:
+        </td>
+        <td style="color:#395fa0">
+            newbie
+        </td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="2"></td>
+    </tr>
+    <tr>
+        <td>
+            Full Name:
+        </td>
+        <td style="color:#395fa0">
+            New Full Name
+        </td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="2"></td>
+    </tr>
+    <tr>
+        <td>
+            Email:
+        </td>
+        <td style="color:#395fa0">
+            new@email.com
+        </td>
+    </tr>
+    <tr>
+        <td colspan="2">
+<table cellspacing="0" cellpadding="0" style="margin-left:auto;margin-right:auto">
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    <tr>
+        <td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #395fa0">
+            <a href="http://newbie.org" style="text-decoration:none;display:block" target="_blank">
+                <center style="padding:11px 20px">
+                    <font size="3">
+                        <span style="font-family:Helvetica,Arial,sans-serif;font-weight:700;font-size:15px;line-height:14px;color:#395fa0;white-space:nowrap;vertical-align:middle">View User Profile</span>
+                    </font>
+                </center>
+            </a>
+        </td>
+    </tr>
+</table>
+        </td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+<hr/>
+<h1>pull_request, is_mention=False</h1>
+<pre>
+From: u1
+To: u2@example.com
+Subject: [Review] repo/name PR #7 "The Title" from devbranch by u2
+</pre>
+<hr/>
+<pre>http://pr.org/7
+
+Added as Reviewer of Pull Request #7 "The Title" by Requesting User (root)
+
+
+Pull request from https://dev.org/repo at devbranch to http://mainline.com/repo at trunk:
+#7 "The Title" by u2 u3 (u2).
+
+
+Description:
+
+This PR is awesome because it does stuff
+ - please approve indented!
+
+
+Changesets:
+
+Introduce one and two
+Make one plus two equal tree
+
+
+View Pull Request: http://pr.org/7
+</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <a style="text-decoration:none;color:#395fa0" href="http://pr.org/7"
+               target="_blank">Added as Reviewer of Pull Request #7 &#34;The Title&#34; by Requesting User (root)</a>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+            <div>
+                Pull request from
+                <a style="color:#395fa0;text-decoration:none"
+                   href="https://dev.org/repo">https://dev.org/repo</a>
+                at
+                <span style="color:#395fa0">devbranch</span>
+                to
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://mainline.com/repo">http://mainline.com/repo</a>
+                at
+                <span style="color:#395fa0">trunk</span>:
+            </div>
+            <div>
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://pr.org/7">#7</a>
+                "<span style="color:#395fa0">The Title</span>"
+                by
+                <span style="color:#395fa0">u2 u3 (u2)</span>.
+            </div>
+        </td>
+    </tr>
+    <tr><td height="10px"></td></tr>
+    <tr>
+        <td>
+            <div>
+                Description:
+            </div>
+        </td>
+    </tr>
+    <tr><td height="10px"></td></tr>
+    <tr>
+        <td>
+            <div style="font-family:Lucida Console,Consolas,Monaco,Inconsolata,Liberation Mono,monospace;white-space:pre-wrap;color:#395fa0"><div class="formatted-fixed">This PR is awesome because it does stuff<br/> - please approve indented!</div></div>
+        </td>
+    </tr>
+    <tr><td height="15px"></td></tr>
+    <tr>
+        <td>
+            <div>Changesets:</div>
+        </td>
+    </tr>
+    <tr><td height="10px"></td></tr>
+
+    <tr>
+        <td style="font-family:Helvetica,Arial,sans-serif">
+            <ul style="color:#395fa0;padding-left:15px;margin:0">
+                    <li>
+                        <a style="color:#395fa0;text-decoration:none"
+                           href="http://changeset_home/?repo_name=repo_org&amp;revision=123abc123abc123abc123abc123abc123abc123abc">
+                            Introduce one and two
+                        </a>
+                    </li>
+                    <li>
+                        <a style="color:#395fa0;text-decoration:none"
+                           href="http://changeset_home/?repo_name=repo_org&amp;revision=567fed567fed567fed567fed567fed567fed567fed">
+                            Make one plus two equal tree
+                        </a>
+                    </li>
+            </ul>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<table cellspacing="0" cellpadding="0" style="margin-left:auto;margin-right:auto">
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    <tr>
+        <td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #395fa0">
+            <a href="http://pr.org/7" style="text-decoration:none;display:block" target="_blank">
+                <center style="padding:11px 20px">
+                    <font size="3">
+                        <span style="font-family:Helvetica,Arial,sans-serif;font-weight:700;font-size:15px;line-height:14px;color:#395fa0;white-space:nowrap;vertical-align:middle">View Pull Request</span>
+                    </font>
+                </center>
+            </a>
+        </td>
+    </tr>
+</table>
+        </td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+<hr/>
+<h1>pull_request, is_mention=True</h1>
+<pre>
+From: u1
+To: u2@example.com
+Subject: [Review] repo/name PR #7 "The Title" from devbranch by u2
+</pre>
+<hr/>
+<pre>http://pr.org/7
+
+Mention on Pull Request #7 "The Title" by Requesting User (root)
+
+
+Pull request from https://dev.org/repo at devbranch to http://mainline.com/repo at trunk:
+#7 "The Title" by u2 u3 (u2).
+
+
+Description:
+
+This PR is awesome because it does stuff
+ - please approve indented!
+
+
+Changesets:
+
+Introduce one and two
+Make one plus two equal tree
+
+
+View Pull Request: http://pr.org/7
+</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <a style="text-decoration:none;color:#395fa0" href="http://pr.org/7"
+               target="_blank">Mention on Pull Request #7 &#34;The Title&#34; by Requesting User (root)</a>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+            <div>
+                Pull request from
+                <a style="color:#395fa0;text-decoration:none"
+                   href="https://dev.org/repo">https://dev.org/repo</a>
+                at
+                <span style="color:#395fa0">devbranch</span>
+                to
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://mainline.com/repo">http://mainline.com/repo</a>
+                at
+                <span style="color:#395fa0">trunk</span>:
+            </div>
+            <div>
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://pr.org/7">#7</a>
+                "<span style="color:#395fa0">The Title</span>"
+                by
+                <span style="color:#395fa0">u2 u3 (u2)</span>.
+            </div>
+        </td>
+    </tr>
+    <tr><td height="10px"></td></tr>
+    <tr>
+        <td>
+            <div>
+                Description:
+            </div>
+        </td>
+    </tr>
+    <tr><td height="10px"></td></tr>
+    <tr>
+        <td>
+            <div style="font-family:Lucida Console,Consolas,Monaco,Inconsolata,Liberation Mono,monospace;white-space:pre-wrap;color:#395fa0"><div class="formatted-fixed">This PR is awesome because it does stuff<br/> - please approve indented!</div></div>
+        </td>
+    </tr>
+    <tr><td height="15px"></td></tr>
+    <tr>
+        <td>
+            <div>Changesets:</div>
+        </td>
+    </tr>
+    <tr><td height="10px"></td></tr>
+
+    <tr>
+        <td style="font-family:Helvetica,Arial,sans-serif">
+            <ul style="color:#395fa0;padding-left:15px;margin:0">
+                    <li>
+                        <a style="color:#395fa0;text-decoration:none"
+                           href="http://changeset_home/?repo_name=repo_org&amp;revision=123abc123abc123abc123abc123abc123abc123abc">
+                            Introduce one and two
+                        </a>
+                    </li>
+                    <li>
+                        <a style="color:#395fa0;text-decoration:none"
+                           href="http://changeset_home/?repo_name=repo_org&amp;revision=567fed567fed567fed567fed567fed567fed567fed">
+                            Make one plus two equal tree
+                        </a>
+                    </li>
+            </ul>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<table cellspacing="0" cellpadding="0" style="margin-left:auto;margin-right:auto">
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    <tr>
+        <td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #395fa0">
+            <a href="http://pr.org/7" style="text-decoration:none;display:block" target="_blank">
+                <center style="padding:11px 20px">
+                    <font size="3">
+                        <span style="font-family:Helvetica,Arial,sans-serif;font-weight:700;font-size:15px;line-height:14px;color:#395fa0;white-space:nowrap;vertical-align:middle">View Pull Request</span>
+                    </font>
+                </center>
+            </a>
+        </td>
+    </tr>
+</table>
+        </td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+<hr/>
+<h1>pull_request_comment, is_mention=False, status_change=None, closing_pr=False</h1>
+<pre>
+From: u1
+To: u2@example.com
+Subject: [Comment] repo/name PR #7 "The Title" from devbranch by u2
+</pre>
+<hr/>
+<pre>http://pr.org/comment
+
+Comment on Pull Request #7 "The Title"
+
+
+Opinionated User (jsmith):
+
+Me too!
+
+ - and indented on second line
+
+
+Pull request from https://dev.org/repo at devbranch to http://mainline.com/repo at trunk:
+#7 "The Title" by u2 u3 (u2).
+
+
+View Comment: http://pr.org/comment
+</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <a style="text-decoration:none;color:#395fa0" href="http://pr.org/comment"
+               target="_blank">Comment on Pull Request #7 &#34;The Title&#34;</a>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+<table cellpadding="0" cellspacing="0" width="100%" border="0" bgcolor="#f9f9f9" style="border:1px solid #ddd;border-radius:4px">
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-weight:600;color:#395fa0">Opinionated User (jsmith)</div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-family:Lucida Console,Consolas,Monaco,Inconsolata,Liberation Mono,monospace;white-space:pre-wrap"><div class="formatted-fixed">Me too!<br/><br/> - and indented on second line</div></div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+</table>
+        </td>
+    </tr>
+    <tr>
+        <td height="30px"></td>
+    </tr>
+    <tr>
+        <td>
+            <div>
+                Pull request from
+                <a style="color:#395fa0;text-decoration:none"
+                   href="https://dev.org/repo">https://dev.org/repo</a>
+                branch
+                <span style="color:#395fa0">devbranch</span>
+                to
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://mainline.com/repo">http://mainline.com/repo</a>
+                branch
+                <span style="color:#395fa0">trunk</span>:
+            </div>
+            <div>
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://pr.org/7">#7</a>
+                "<span style="color:#395fa0">The Title</span>"
+                by
+                <span style="color:#395fa0">u2 u3 (u2)</span>.
+            </div>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<table cellspacing="0" cellpadding="0" style="margin-left:auto;margin-right:auto">
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    <tr>
+        <td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #395fa0">
+            <a href="http://pr.org/comment" style="text-decoration:none;display:block" target="_blank">
+                <center style="padding:11px 20px">
+                    <font size="3">
+                        <span style="font-family:Helvetica,Arial,sans-serif;font-weight:700;font-size:15px;line-height:14px;color:#395fa0;white-space:nowrap;vertical-align:middle">View Comment</span>
+                    </font>
+                </center>
+            </a>
+        </td>
+    </tr>
+</table>
+        </td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+<hr/>
+<h1>pull_request_comment, is_mention=True, status_change=None, closing_pr=False</h1>
+<pre>
+From: u1
+To: u2@example.com
+Subject: [Comment] repo/name PR #7 "The Title" from devbranch by u2
+</pre>
+<hr/>
+<pre>http://pr.org/comment
+
+Mention in Comment on Pull Request #7 "The Title"
+
+
+Opinionated User (jsmith):
+
+Me too!
+
+ - and indented on second line
+
+
+Pull request from https://dev.org/repo at devbranch to http://mainline.com/repo at trunk:
+#7 "The Title" by u2 u3 (u2).
+
+
+View Comment: http://pr.org/comment
+</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <a style="text-decoration:none;color:#395fa0" href="http://pr.org/comment"
+               target="_blank">Mention in Comment on Pull Request #7 &#34;The Title&#34;</a>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+<table cellpadding="0" cellspacing="0" width="100%" border="0" bgcolor="#f9f9f9" style="border:1px solid #ddd;border-radius:4px">
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-weight:600;color:#395fa0">Opinionated User (jsmith)</div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-family:Lucida Console,Consolas,Monaco,Inconsolata,Liberation Mono,monospace;white-space:pre-wrap"><div class="formatted-fixed">Me too!<br/><br/> - and indented on second line</div></div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+</table>
+        </td>
+    </tr>
+    <tr>
+        <td height="30px"></td>
+    </tr>
+    <tr>
+        <td>
+            <div>
+                Pull request from
+                <a style="color:#395fa0;text-decoration:none"
+                   href="https://dev.org/repo">https://dev.org/repo</a>
+                branch
+                <span style="color:#395fa0">devbranch</span>
+                to
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://mainline.com/repo">http://mainline.com/repo</a>
+                branch
+                <span style="color:#395fa0">trunk</span>:
+            </div>
+            <div>
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://pr.org/7">#7</a>
+                "<span style="color:#395fa0">The Title</span>"
+                by
+                <span style="color:#395fa0">u2 u3 (u2)</span>.
+            </div>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<table cellspacing="0" cellpadding="0" style="margin-left:auto;margin-right:auto">
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    <tr>
+        <td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #395fa0">
+            <a href="http://pr.org/comment" style="text-decoration:none;display:block" target="_blank">
+                <center style="padding:11px 20px">
+                    <font size="3">
+                        <span style="font-family:Helvetica,Arial,sans-serif;font-weight:700;font-size:15px;line-height:14px;color:#395fa0;white-space:nowrap;vertical-align:middle">View Comment</span>
+                    </font>
+                </center>
+            </a>
+        </td>
+    </tr>
+</table>
+        </td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+<hr/>
+<h1>pull_request_comment, is_mention=False, status_change='Under Review', closing_pr=False</h1>
+<pre>
+From: u1
+To: u2@example.com
+Subject: [Under Review: Comment] repo/name PR #7 "The Title" from devbranch by u2
+</pre>
+<hr/>
+<pre>http://pr.org/comment
+
+Comment on Pull Request #7 "The Title"
+
+
+Opinionated User (jsmith):
+
+Status change: Under Review
+
+Me too!
+
+ - and indented on second line
+
+
+Pull request from https://dev.org/repo at devbranch to http://mainline.com/repo at trunk:
+#7 "The Title" by u2 u3 (u2).
+
+
+View Comment: http://pr.org/comment
+</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <a style="text-decoration:none;color:#395fa0" href="http://pr.org/comment"
+               target="_blank">Comment on Pull Request #7 &#34;The Title&#34;</a>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+<table cellpadding="0" cellspacing="0" width="100%" border="0" bgcolor="#f9f9f9" style="border:1px solid #ddd;border-radius:4px">
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-weight:600;color:#395fa0">Opinionated User (jsmith)</div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+    </tr>
+        <tr>
+            <td height="10px" colspan="3"></td>
+        </tr>
+        <tr>
+            <td width="20px"></td>
+            <td>
+                    <div style="font-weight:600">
+                        Status change:
+                        Under Review
+                    </div>
+            </td>
+            <td width="20px"></td>
+        </tr>
+        <tr>
+            <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+        </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-family:Lucida Console,Consolas,Monaco,Inconsolata,Liberation Mono,monospace;white-space:pre-wrap"><div class="formatted-fixed">Me too!<br/><br/> - and indented on second line</div></div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+</table>
+        </td>
+    </tr>
+    <tr>
+        <td height="30px"></td>
+    </tr>
+    <tr>
+        <td>
+            <div>
+                Pull request from
+                <a style="color:#395fa0;text-decoration:none"
+                   href="https://dev.org/repo">https://dev.org/repo</a>
+                branch
+                <span style="color:#395fa0">devbranch</span>
+                to
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://mainline.com/repo">http://mainline.com/repo</a>
+                branch
+                <span style="color:#395fa0">trunk</span>:
+            </div>
+            <div>
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://pr.org/7">#7</a>
+                "<span style="color:#395fa0">The Title</span>"
+                by
+                <span style="color:#395fa0">u2 u3 (u2)</span>.
+            </div>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<table cellspacing="0" cellpadding="0" style="margin-left:auto;margin-right:auto">
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    <tr>
+        <td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #395fa0">
+            <a href="http://pr.org/comment" style="text-decoration:none;display:block" target="_blank">
+                <center style="padding:11px 20px">
+                    <font size="3">
+                        <span style="font-family:Helvetica,Arial,sans-serif;font-weight:700;font-size:15px;line-height:14px;color:#395fa0;white-space:nowrap;vertical-align:middle">View Comment</span>
+                    </font>
+                </center>
+            </a>
+        </td>
+    </tr>
+</table>
+        </td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+<hr/>
+<h1>pull_request_comment, is_mention=True, status_change='Under Review', closing_pr=False</h1>
+<pre>
+From: u1
+To: u2@example.com
+Subject: [Under Review: Comment] repo/name PR #7 "The Title" from devbranch by u2
+</pre>
+<hr/>
+<pre>http://pr.org/comment
+
+Mention in Comment on Pull Request #7 "The Title"
+
+
+Opinionated User (jsmith):
+
+Status change: Under Review
+
+Me too!
+
+ - and indented on second line
+
+
+Pull request from https://dev.org/repo at devbranch to http://mainline.com/repo at trunk:
+#7 "The Title" by u2 u3 (u2).
+
+
+View Comment: http://pr.org/comment
+</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <a style="text-decoration:none;color:#395fa0" href="http://pr.org/comment"
+               target="_blank">Mention in Comment on Pull Request #7 &#34;The Title&#34;</a>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+<table cellpadding="0" cellspacing="0" width="100%" border="0" bgcolor="#f9f9f9" style="border:1px solid #ddd;border-radius:4px">
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-weight:600;color:#395fa0">Opinionated User (jsmith)</div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+    </tr>
+        <tr>
+            <td height="10px" colspan="3"></td>
+        </tr>
+        <tr>
+            <td width="20px"></td>
+            <td>
+                    <div style="font-weight:600">
+                        Status change:
+                        Under Review
+                    </div>
+            </td>
+            <td width="20px"></td>
+        </tr>
+        <tr>
+            <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+        </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-family:Lucida Console,Consolas,Monaco,Inconsolata,Liberation Mono,monospace;white-space:pre-wrap"><div class="formatted-fixed">Me too!<br/><br/> - and indented on second line</div></div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+</table>
+        </td>
+    </tr>
+    <tr>
+        <td height="30px"></td>
+    </tr>
+    <tr>
+        <td>
+            <div>
+                Pull request from
+                <a style="color:#395fa0;text-decoration:none"
+                   href="https://dev.org/repo">https://dev.org/repo</a>
+                branch
+                <span style="color:#395fa0">devbranch</span>
+                to
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://mainline.com/repo">http://mainline.com/repo</a>
+                branch
+                <span style="color:#395fa0">trunk</span>:
+            </div>
+            <div>
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://pr.org/7">#7</a>
+                "<span style="color:#395fa0">The Title</span>"
+                by
+                <span style="color:#395fa0">u2 u3 (u2)</span>.
+            </div>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<table cellspacing="0" cellpadding="0" style="margin-left:auto;margin-right:auto">
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    <tr>
+        <td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #395fa0">
+            <a href="http://pr.org/comment" style="text-decoration:none;display:block" target="_blank">
+                <center style="padding:11px 20px">
+                    <font size="3">
+                        <span style="font-family:Helvetica,Arial,sans-serif;font-weight:700;font-size:15px;line-height:14px;color:#395fa0;white-space:nowrap;vertical-align:middle">View Comment</span>
+                    </font>
+                </center>
+            </a>
+        </td>
+    </tr>
+</table>
+        </td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+<hr/>
+<h1>pull_request_comment, is_mention=False, status_change=None, closing_pr=True</h1>
+<pre>
+From: u1
+To: u2@example.com
+Subject: [Closing: Comment] repo/name PR #7 "The Title" from devbranch by u2
+</pre>
+<hr/>
+<pre>http://pr.org/comment
+
+Pull Request #7 "The Title" Closed
+
+
+Opinionated User (jsmith):
+
+The pull request has been closed.
+
+Me too!
+
+ - and indented on second line
+
+
+Pull request from https://dev.org/repo at devbranch to http://mainline.com/repo at trunk:
+#7 "The Title" by u2 u3 (u2).
+
+
+View Comment: http://pr.org/comment
+</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <a style="text-decoration:none;color:#395fa0" href="http://pr.org/comment"
+               target="_blank">Pull Request #7 &#34;The Title&#34; Closed</a>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+<table cellpadding="0" cellspacing="0" width="100%" border="0" bgcolor="#f9f9f9" style="border:1px solid #ddd;border-radius:4px">
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-weight:600;color:#395fa0">Opinionated User (jsmith)</div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+    </tr>
+        <tr>
+            <td height="10px" colspan="3"></td>
+        </tr>
+        <tr>
+            <td width="20px"></td>
+            <td>
+                    <div style="font-weight:600">
+                        The pull request has been closed.
+                    </div>
+            </td>
+            <td width="20px"></td>
+        </tr>
+        <tr>
+            <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+        </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-family:Lucida Console,Consolas,Monaco,Inconsolata,Liberation Mono,monospace;white-space:pre-wrap"><div class="formatted-fixed">Me too!<br/><br/> - and indented on second line</div></div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+</table>
+        </td>
+    </tr>
+    <tr>
+        <td height="30px"></td>
+    </tr>
+    <tr>
+        <td>
+            <div>
+                Pull request from
+                <a style="color:#395fa0;text-decoration:none"
+                   href="https://dev.org/repo">https://dev.org/repo</a>
+                branch
+                <span style="color:#395fa0">devbranch</span>
+                to
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://mainline.com/repo">http://mainline.com/repo</a>
+                branch
+                <span style="color:#395fa0">trunk</span>:
+            </div>
+            <div>
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://pr.org/7">#7</a>
+                "<span style="color:#395fa0">The Title</span>"
+                by
+                <span style="color:#395fa0">u2 u3 (u2)</span>.
+            </div>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<table cellspacing="0" cellpadding="0" style="margin-left:auto;margin-right:auto">
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    <tr>
+        <td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #395fa0">
+            <a href="http://pr.org/comment" style="text-decoration:none;display:block" target="_blank">
+                <center style="padding:11px 20px">
+                    <font size="3">
+                        <span style="font-family:Helvetica,Arial,sans-serif;font-weight:700;font-size:15px;line-height:14px;color:#395fa0;white-space:nowrap;vertical-align:middle">View Comment</span>
+                    </font>
+                </center>
+            </a>
+        </td>
+    </tr>
+</table>
+        </td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+<hr/>
+<h1>pull_request_comment, is_mention=True, status_change=None, closing_pr=True</h1>
+<pre>
+From: u1
+To: u2@example.com
+Subject: [Closing: Comment] repo/name PR #7 "The Title" from devbranch by u2
+</pre>
+<hr/>
+<pre>http://pr.org/comment
+
+Mention in Comment on Pull Request #7 "The Title"
+
+
+Opinionated User (jsmith):
+
+The pull request has been closed.
+
+Me too!
+
+ - and indented on second line
+
+
+Pull request from https://dev.org/repo at devbranch to http://mainline.com/repo at trunk:
+#7 "The Title" by u2 u3 (u2).
+
+
+View Comment: http://pr.org/comment
+</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <a style="text-decoration:none;color:#395fa0" href="http://pr.org/comment"
+               target="_blank">Mention in Comment on Pull Request #7 &#34;The Title&#34;</a>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+<table cellpadding="0" cellspacing="0" width="100%" border="0" bgcolor="#f9f9f9" style="border:1px solid #ddd;border-radius:4px">
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-weight:600;color:#395fa0">Opinionated User (jsmith)</div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+    </tr>
+        <tr>
+            <td height="10px" colspan="3"></td>
+        </tr>
+        <tr>
+            <td width="20px"></td>
+            <td>
+                    <div style="font-weight:600">
+                        The pull request has been closed.
+                    </div>
+            </td>
+            <td width="20px"></td>
+        </tr>
+        <tr>
+            <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+        </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-family:Lucida Console,Consolas,Monaco,Inconsolata,Liberation Mono,monospace;white-space:pre-wrap"><div class="formatted-fixed">Me too!<br/><br/> - and indented on second line</div></div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+</table>
+        </td>
+    </tr>
+    <tr>
+        <td height="30px"></td>
+    </tr>
+    <tr>
+        <td>
+            <div>
+                Pull request from
+                <a style="color:#395fa0;text-decoration:none"
+                   href="https://dev.org/repo">https://dev.org/repo</a>
+                branch
+                <span style="color:#395fa0">devbranch</span>
+                to
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://mainline.com/repo">http://mainline.com/repo</a>
+                branch
+                <span style="color:#395fa0">trunk</span>:
+            </div>
+            <div>
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://pr.org/7">#7</a>
+                "<span style="color:#395fa0">The Title</span>"
+                by
+                <span style="color:#395fa0">u2 u3 (u2)</span>.
+            </div>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<table cellspacing="0" cellpadding="0" style="margin-left:auto;margin-right:auto">
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    <tr>
+        <td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #395fa0">
+            <a href="http://pr.org/comment" style="text-decoration:none;display:block" target="_blank">
+                <center style="padding:11px 20px">
+                    <font size="3">
+                        <span style="font-family:Helvetica,Arial,sans-serif;font-weight:700;font-size:15px;line-height:14px;color:#395fa0;white-space:nowrap;vertical-align:middle">View Comment</span>
+                    </font>
+                </center>
+            </a>
+        </td>
+    </tr>
+</table>
+        </td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+<hr/>
+<h1>pull_request_comment, is_mention=False, status_change='Under Review', closing_pr=True</h1>
+<pre>
+From: u1
+To: u2@example.com
+Subject: [Under Review, Closing: Comment] repo/name PR #7 "The Title" from devbranch by u2
+</pre>
+<hr/>
+<pre>http://pr.org/comment
+
+Pull Request #7 "The Title" Closed
+
+
+Opinionated User (jsmith):
+
+Status change: Under Review
+
+The pull request has been closed.
+
+Me too!
+
+ - and indented on second line
+
+
+Pull request from https://dev.org/repo at devbranch to http://mainline.com/repo at trunk:
+#7 "The Title" by u2 u3 (u2).
+
+
+View Comment: http://pr.org/comment
+</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <a style="text-decoration:none;color:#395fa0" href="http://pr.org/comment"
+               target="_blank">Pull Request #7 &#34;The Title&#34; Closed</a>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+<table cellpadding="0" cellspacing="0" width="100%" border="0" bgcolor="#f9f9f9" style="border:1px solid #ddd;border-radius:4px">
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-weight:600;color:#395fa0">Opinionated User (jsmith)</div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+    </tr>
+        <tr>
+            <td height="10px" colspan="3"></td>
+        </tr>
+        <tr>
+            <td width="20px"></td>
+            <td>
+                    <div style="font-weight:600">
+                        Status change:
+                        Under Review
+                    </div>
+                    <div style="font-weight:600">
+                        The pull request has been closed.
+                    </div>
+            </td>
+            <td width="20px"></td>
+        </tr>
+        <tr>
+            <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+        </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-family:Lucida Console,Consolas,Monaco,Inconsolata,Liberation Mono,monospace;white-space:pre-wrap"><div class="formatted-fixed">Me too!<br/><br/> - and indented on second line</div></div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+</table>
+        </td>
+    </tr>
+    <tr>
+        <td height="30px"></td>
+    </tr>
+    <tr>
+        <td>
+            <div>
+                Pull request from
+                <a style="color:#395fa0;text-decoration:none"
+                   href="https://dev.org/repo">https://dev.org/repo</a>
+                branch
+                <span style="color:#395fa0">devbranch</span>
+                to
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://mainline.com/repo">http://mainline.com/repo</a>
+                branch
+                <span style="color:#395fa0">trunk</span>:
+            </div>
+            <div>
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://pr.org/7">#7</a>
+                "<span style="color:#395fa0">The Title</span>"
+                by
+                <span style="color:#395fa0">u2 u3 (u2)</span>.
+            </div>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<table cellspacing="0" cellpadding="0" style="margin-left:auto;margin-right:auto">
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    <tr>
+        <td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #395fa0">
+            <a href="http://pr.org/comment" style="text-decoration:none;display:block" target="_blank">
+                <center style="padding:11px 20px">
+                    <font size="3">
+                        <span style="font-family:Helvetica,Arial,sans-serif;font-weight:700;font-size:15px;line-height:14px;color:#395fa0;white-space:nowrap;vertical-align:middle">View Comment</span>
+                    </font>
+                </center>
+            </a>
+        </td>
+    </tr>
+</table>
+        </td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+<hr/>
+<h1>pull_request_comment, is_mention=True, status_change='Under Review', closing_pr=True</h1>
+<pre>
+From: u1
+To: u2@example.com
+Subject: [Under Review, Closing: Comment] repo/name PR #7 "The Title" from devbranch by u2
+</pre>
+<hr/>
+<pre>http://pr.org/comment
+
+Mention in Comment on Pull Request #7 "The Title"
+
+
+Opinionated User (jsmith):
+
+Status change: Under Review
+
+The pull request has been closed.
+
+Me too!
+
+ - and indented on second line
+
+
+Pull request from https://dev.org/repo at devbranch to http://mainline.com/repo at trunk:
+#7 "The Title" by u2 u3 (u2).
+
+
+View Comment: http://pr.org/comment
+</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <a style="text-decoration:none;color:#395fa0" href="http://pr.org/comment"
+               target="_blank">Mention in Comment on Pull Request #7 &#34;The Title&#34;</a>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%">
+    <tr>
+        <td>
+<table cellpadding="0" cellspacing="0" width="100%" border="0" bgcolor="#f9f9f9" style="border:1px solid #ddd;border-radius:4px">
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-weight:600;color:#395fa0">Opinionated User (jsmith)</div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+    </tr>
+        <tr>
+            <td height="10px" colspan="3"></td>
+        </tr>
+        <tr>
+            <td width="20px"></td>
+            <td>
+                    <div style="font-weight:600">
+                        Status change:
+                        Under Review
+                    </div>
+                    <div style="font-weight:600">
+                        The pull request has been closed.
+                    </div>
+            </td>
+            <td width="20px"></td>
+        </tr>
+        <tr>
+            <td height="10px" colspan="3" style="border-bottom:1px solid #ddd"></td>
+        </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="20px"></td>
+        <td>
+            <div style="font-family:Lucida Console,Consolas,Monaco,Inconsolata,Liberation Mono,monospace;white-space:pre-wrap"><div class="formatted-fixed">Me too!<br/><br/> - and indented on second line</div></div>
+        </td>
+        <td width="20px"></td>
+    </tr>
+    <tr>
+        <td height="10px" colspan="3"></td>
+    </tr>
+</table>
+        </td>
+    </tr>
+    <tr>
+        <td height="30px"></td>
+    </tr>
+    <tr>
+        <td>
+            <div>
+                Pull request from
+                <a style="color:#395fa0;text-decoration:none"
+                   href="https://dev.org/repo">https://dev.org/repo</a>
+                branch
+                <span style="color:#395fa0">devbranch</span>
+                to
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://mainline.com/repo">http://mainline.com/repo</a>
+                branch
+                <span style="color:#395fa0">trunk</span>:
+            </div>
+            <div>
+                <a style="color:#395fa0;text-decoration:none"
+                   href="http://pr.org/7">#7</a>
+                "<span style="color:#395fa0">The Title</span>"
+                by
+                <span style="color:#395fa0">u2 u3 (u2)</span>.
+            </div>
+        </td>
+    </tr>
+    <tr>
+        <td>
+<table cellspacing="0" cellpadding="0" style="margin-left:auto;margin-right:auto">
+    <tr>
+        <td height="25px"></td>
+    </tr>
+    <tr>
+        <td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #395fa0">
+            <a href="http://pr.org/comment" style="text-decoration:none;display:block" target="_blank">
+                <center style="padding:11px 20px">
+                    <font size="3">
+                        <span style="font-family:Helvetica,Arial,sans-serif;font-weight:700;font-size:15px;line-height:14px;color:#395fa0;white-space:nowrap;vertical-align:middle">View Comment</span>
+                    </font>
+                </center>
+            </a>
+        </td>
+    </tr>
+</table>
+        </td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+<hr/>
+<h1>TYPE_PASSWORD_RESET</h1>
+<pre>
+From: u1
+To: john@doe.com
+Subject: Password reset link
+</pre>
+<hr/>
+<pre>Password Reset Request
+
+Hello John Doe,
+
+We have received a request to reset the password for your account.
+
+To set a new password, click the following link:
+
+http://reset.com/decbf64715098db5b0bd23eab44bd792670ab746
+
+Should you not be able to use the link above, please type the following code into the password reset form:
+decbf64715098db5b0bd23eab44bd792670ab746
+
+If it weren't you who requested the password reset, just disregard this message.
+</pre>
+<hr/>
+<!--!doctype html-->
+<!--html lang="en"-->
+<!--head-->
+    <!--title--><!--/title-->
+    <!--meta name="viewport" content="width=device-width"-->
+    <!--meta http-equiv="Content-Type" content="text/html; charset=UTF-8"-->
+<!--/head-->
+<!--body-->
+<table align="center" cellpadding="0" cellspacing="0" border="0" style="min-width:348px;max-width:800px;font-family:Helvetica,Arial,sans-serif;font-weight:200;font-size:14px;line-height:17px;color:#202020">
+    <tr>
+        <td width="30px"></td>
+        <td>
+            <table width="100%" cellpadding="0" cellspacing="0" border="0"
+                   style="table-layout:fixed;font-family:Helvetica,Arial,sans-serif;border:1px solid #ddd">
+                <tr><td width="30px"></td><td></td><td width="30px"></td></tr>
+                <tr>
+                    <td colspan="3">
+<table bgcolor="#f9f9f9" width="100%" cellpadding="0" cellspacing="0"
+       style="border-bottom:1px solid #ddd">
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+    <tr>
+        <td width="30px"></td>
+        <td style="font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:24px">
+            <span style="color:#395fa0">Password Reset Request</span>
+        </td>
+        <td width="30px"></td>
+    </tr>
+    <tr>
+        <td height="20px" colspan="3"></td>
+    </tr>
+</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td>
+<table cellpadding="0" cellspacing="0" border="0" width="100%" style="table-layout:fixed;word-wrap:break-word;">
+    <tr>
+        <td>Hello John Doe,</td>
+    </tr>
+    <tr>
+        <td height="10px"></td>
+    </tr>
+    <tr>
+        <td>
+            We have received a request to reset the password for your account.
+        </td>
+    </tr>
+    <tr>
+        <td height="10px"></td>
+    </tr>
+    <tr>
+        <td>
+                <div>
+                    To set a new password, click the following link:
+                    <br/>
+                    <a style="color:#395fa0;text-decoration:none" href="http://reset.com/decbf64715098db5b0bd23eab44bd792670ab746"
+                        target="_blank">http://reset.com/decbf64715098db5b0bd23eab44bd792670ab746</a>
+                    <br/>
+                    Should you not be able to use the link above, please type the following code into the password reset form:
+                    <code>decbf64715098db5b0bd23eab44bd792670ab746</code>
+                </div>
+        </td>
+    </tr>
+    <tr>
+        <td height="10px"></td>
+    </tr>
+    <tr>
+        <td>
+            If it weren&#39;t you who requested the password reset, just disregard this message.
+        </td>
+    </tr>
+</table>
+                    </td>
+                    <td></td>
+                </tr>
+                <tr>
+                    <td height="30px" colspan="3"></td>
+                </tr>
+            </table>
+        </td>
+        <td width="30px"></td>
+    </tr>
+</table>
+<!--/body-->
+<!--/html-->
+<hr/>
+
+</body>
+</html>
--- a/kallithea/tests/models/test_notifications.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/models/test_notifications.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,66 +1,76 @@
-from kallithea.tests import *
+import os
+import re
 
+import mock
+import routes.util
+
+from kallithea.tests.base import *
+from kallithea.lib import helpers as h
 from kallithea.model.db import User, Notification, UserNotification
 from kallithea.model.user import UserModel
+from kallithea.model.meta import Session
+from kallithea.model.notification import NotificationModel, EmailNotificationModel
 
-from kallithea.model.meta import Session
-from kallithea.model.notification import NotificationModel
+import kallithea.lib.celerylib
+import kallithea.lib.celerylib.tasks
 
 
-class TestNotifications(BaseTestCase):
+class TestNotifications(TestController):
 
-    def __init__(self, methodName='runTest'):
+    def setup_method(self, method):
         Session.remove()
-        self.u1 = UserModel().create_or_update(username=u'u1',
+        u1 = UserModel().create_or_update(username=u'u1',
                                         password=u'qweqwe',
                                         email=u'u1@example.com',
                                         firstname=u'u1', lastname=u'u1')
         Session().commit()
-        self.u1 = self.u1.user_id
+        self.u1 = u1.user_id
 
-        self.u2 = UserModel().create_or_update(username=u'u2',
+        u2 = UserModel().create_or_update(username=u'u2',
                                         password=u'qweqwe',
                                         email=u'u2@example.com',
                                         firstname=u'u2', lastname=u'u3')
         Session().commit()
-        self.u2 = self.u2.user_id
+        self.u2 = u2.user_id
 
-        self.u3 = UserModel().create_or_update(username=u'u3',
+        u3 = UserModel().create_or_update(username=u'u3',
                                         password=u'qweqwe',
                                         email=u'u3@example.com',
                                         firstname=u'u3', lastname=u'u3')
         Session().commit()
-        self.u3 = self.u3.user_id
-
-        super(TestNotifications, self).__init__(methodName=methodName)
+        self.u3 = u3.user_id
 
-    def setUp(self):
         self.remove_all_notifications()
-        self.assertEqual([], Notification.query().all())
-        self.assertEqual([], UserNotification.query().all())
+        assert [] == Notification.query().all()
+        assert [] == UserNotification.query().all()
 
     def test_create_notification(self):
         usrs = [self.u1, self.u2]
-        notification = NotificationModel().create(created_by=self.u1,
-                                           subject=u'subj', body=u'hi there',
-                                           recipients=usrs)
+        def send_email(recipients, subject, body='', html_body='', headers=None, author=None):
+            assert recipients == ['u2@example.com']
+            assert subject == 'Test Message'
+            assert body == u"hi there"
+            assert '>hi there<' in html_body
+            assert author.username == 'u1'
+        with mock.patch.object(kallithea.lib.celerylib.tasks, 'send_email', send_email):
+            notification = NotificationModel().create(created_by=self.u1,
+                                               subject=u'subj', body=u'hi there',
+                                               recipients=usrs)
         Session().commit()
         u1 = User.get(self.u1)
         u2 = User.get(self.u2)
         u3 = User.get(self.u3)
         notifications = Notification.query().all()
-        self.assertEqual(len(notifications), 1)
+        assert len(notifications) == 1
 
-        self.assertEqual(notifications[0].recipients, [u1, u2])
-        self.assertEqual(notification.notification_id,
-                         notifications[0].notification_id)
+        assert notifications[0].recipients == [u1, u2]
+        assert notification.notification_id == notifications[0].notification_id
 
-        unotification = UserNotification.query()\
+        unotification = UserNotification.query() \
             .filter(UserNotification.notification == notification).all()
 
-        self.assertEqual(len(unotification), len(usrs))
-        self.assertEqual(set([x.user.user_id for x in unotification]),
-                         set(usrs))
+        assert len(unotification) == len(usrs)
+        assert set([x.user_id for x in unotification]) == set(usrs)
 
     def test_user_notifications(self):
         notification1 = NotificationModel().create(created_by=self.u1,
@@ -73,8 +83,7 @@
         Session().commit()
         u3 = Session().query(User).get(self.u3)
 
-        self.assertEqual(sorted([x.notification for x in u3.notifications]),
-                         sorted([notification2, notification1]))
+        assert sorted([x.notification for x in u3.notifications]) == sorted([notification2, notification1])
 
     def test_delete_notifications(self):
         notification = NotificationModel().create(created_by=self.u1,
@@ -82,17 +91,17 @@
                                     recipients=[self.u3, self.u1, self.u2])
         Session().commit()
         notifications = Notification.query().all()
-        self.assertTrue(notification in notifications)
+        assert notification in notifications
 
         Notification.delete(notification.notification_id)
         Session().commit()
 
         notifications = Notification.query().all()
-        self.assertFalse(notification in notifications)
+        assert not notification in notifications
 
         un = UserNotification.query().filter(UserNotification.notification
                                              == notification).all()
-        self.assertEqual(un, [])
+        assert un == []
 
     def test_delete_association(self):
         notification = NotificationModel().create(created_by=self.u1,
@@ -100,42 +109,42 @@
                                     recipients=[self.u3, self.u1, self.u2])
         Session().commit()
 
-        unotification = UserNotification.query()\
+        unotification = UserNotification.query() \
                             .filter(UserNotification.notification ==
-                                    notification)\
-                            .filter(UserNotification.user_id == self.u3)\
+                                    notification) \
+                            .filter(UserNotification.user_id == self.u3) \
                             .scalar()
 
-        self.assertEqual(unotification.user_id, self.u3)
+        assert unotification.user_id == self.u3
 
         NotificationModel().delete(self.u3,
                                    notification.notification_id)
         Session().commit()
 
-        u3notification = UserNotification.query()\
+        u3notification = UserNotification.query() \
                             .filter(UserNotification.notification ==
-                                    notification)\
-                            .filter(UserNotification.user_id == self.u3)\
+                                    notification) \
+                            .filter(UserNotification.user_id == self.u3) \
                             .scalar()
 
-        self.assertEqual(u3notification, None)
+        assert u3notification == None
 
         # notification object is still there
-        self.assertEqual(Notification.query().all(), [notification])
+        assert Notification.query().all() == [notification]
 
         #u1 and u2 still have assignments
-        u1notification = UserNotification.query()\
+        u1notification = UserNotification.query() \
                             .filter(UserNotification.notification ==
-                                    notification)\
-                            .filter(UserNotification.user_id == self.u1)\
+                                    notification) \
+                            .filter(UserNotification.user_id == self.u1) \
                             .scalar()
-        self.assertNotEqual(u1notification, None)
-        u2notification = UserNotification.query()\
+        assert u1notification != None
+        u2notification = UserNotification.query() \
                             .filter(UserNotification.notification ==
-                                    notification)\
-                            .filter(UserNotification.user_id == self.u2)\
+                                    notification) \
+                            .filter(UserNotification.user_id == self.u2) \
                             .scalar()
-        self.assertNotEqual(u2notification, None)
+        assert u2notification != None
 
     def test_notification_counter(self):
         NotificationModel().create(created_by=self.u1,
@@ -143,21 +152,133 @@
                             recipients=[self.u3, self.u1])
         Session().commit()
 
-        self.assertEqual(NotificationModel()
-                         .get_unread_cnt_for_user(self.u1), 1)
-        self.assertEqual(NotificationModel()
-                         .get_unread_cnt_for_user(self.u2), 0)
-        self.assertEqual(NotificationModel()
-                         .get_unread_cnt_for_user(self.u3), 1)
+        assert NotificationModel().get_unread_cnt_for_user(self.u1) == 0
+        assert NotificationModel().get_unread_cnt_for_user(self.u2) == 0
+        assert NotificationModel().get_unread_cnt_for_user(self.u3) == 1
 
         notification = NotificationModel().create(created_by=self.u1,
                                            subject=u'title', body=u'hi there3',
                                     recipients=[self.u3, self.u1, self.u2])
         Session().commit()
 
-        self.assertEqual(NotificationModel()
-                         .get_unread_cnt_for_user(self.u1), 2)
-        self.assertEqual(NotificationModel()
-                         .get_unread_cnt_for_user(self.u2), 1)
-        self.assertEqual(NotificationModel()
-                         .get_unread_cnt_for_user(self.u3), 2)
+        assert NotificationModel().get_unread_cnt_for_user(self.u1) == 0
+        assert NotificationModel().get_unread_cnt_for_user(self.u2) == 1
+        assert NotificationModel().get_unread_cnt_for_user(self.u3) == 2
+
+    @mock.patch.object(h, 'canonical_url', (lambda arg, **kwargs: 'http://%s/?%s' % (arg, '&'.join('%s=%s' % (k, v) for (k, v) in sorted(kwargs.items())))))
+    def test_dump_html_mails(self):
+        # Exercise all notification types and dump them to one big html file
+        l = []
+
+        def send_email(recipients, subject, body='', html_body='', headers=None, author=None):
+            l.append('<hr/>\n')
+            l.append('<h1>%s</h1>\n' % desc) # desc is from outer scope
+            l.append('<pre>\n')
+            l.append('From: %s\n' % author.username)
+            l.append('To: %s\n' % ' '.join(recipients))
+            l.append('Subject: %s\n' % subject)
+            l.append('</pre>\n')
+            l.append('<hr/>\n')
+            l.append('<pre>%s</pre>\n' % body)
+            l.append('<hr/>\n')
+            l.append(html_body)
+            l.append('<hr/>\n')
+
+        with mock.patch.object(kallithea.lib.celerylib.tasks, 'send_email', send_email):
+            pr_kwargs = dict(
+                pr_nice_id='#7',
+                pr_title='The Title',
+                pr_title_short='The Title',
+                pr_url='http://pr.org/7',
+                pr_target_repo='http://mainline.com/repo',
+                pr_target_branch='trunk',
+                pr_source_repo='https://dev.org/repo',
+                pr_source_branch='devbranch',
+                pr_owner=User.get(self.u2),
+                pr_owner_username='u2'
+                )
+
+            for type_, body, kwargs in [
+                (Notification.TYPE_CHANGESET_COMMENT,
+                 u'This is the new comment.\n\n - and here it ends indented.',
+                 dict(
+                    short_id='cafe1234',
+                    raw_id='cafe1234c0ffeecafe',
+                    branch='brunch',
+                    cs_comment_user='Opinionated User (jsmith)',
+                    cs_comment_url='http://comment.org',
+                    is_mention=[False, True],
+                    message='This changeset did something clever which is hard to explain',
+                    message_short='This changeset did something cl...',
+                    status_change=[None, 'Approved'],
+                    cs_target_repo='repo_target',
+                    cs_url='http://changeset.com',
+                    cs_author=User.get(self.u2))),
+                (Notification.TYPE_MESSAGE,
+                 u'This is the body of the test message\n - nothing interesting here except indentation.',
+                 dict()),
+                #(Notification.TYPE_MENTION, '$body', None), # not used
+                (Notification.TYPE_REGISTRATION,
+                 u'Registration body',
+                 dict(
+                    new_username='newbie',
+                    registered_user_url='http://newbie.org',
+                    new_email='new@email.com',
+                    new_full_name='New Full Name')),
+                (Notification.TYPE_PULL_REQUEST,
+                 u'This PR is awesome because it does stuff\n - please approve indented!',
+                 dict(
+                    pr_user_created='Requesting User (root)', # pr_owner should perhaps be used for @mention in description ...
+                    is_mention=[False, True],
+                    pr_revisions=[('123abc'*7, "Introduce one and two\n\nand that's it"), ('567fed'*7, 'Make one plus two equal tree')],
+                    org_repo_name='repo_org',
+                    **pr_kwargs)),
+                (Notification.TYPE_PULL_REQUEST_COMMENT,
+                 u'Me too!\n\n - and indented on second line',
+                 dict(
+                    closing_pr=[False, True],
+                    is_mention=[False, True],
+                    pr_comment_user='Opinionated User (jsmith)',
+                    pr_comment_url='http://pr.org/comment',
+                    status_change=[None, 'Under Review'],
+                    **pr_kwargs)),
+                ]:
+                kwargs['repo_name'] = u'repo/name'
+                params = [(type_, type_, body, kwargs)]
+                for param_name in ['is_mention', 'status_change', 'closing_pr']: # TODO: inline/general
+                    if not isinstance(kwargs.get(param_name), list):
+                        continue
+                    new_params = []
+                    for v in kwargs[param_name]:
+                        for desc, type_, body, kwargs in params:
+                            kwargs = dict(kwargs)
+                            kwargs[param_name] = v
+                            new_params.append(('%s, %s=%r' % (desc, param_name, v), type_, body, kwargs))
+                    params = new_params
+
+                for desc, type_, body, kwargs in params:
+                    # desc is used as "global" variable
+                    notification = NotificationModel().create(created_by=self.u1,
+                                                       subject=u'unused', body=body, email_kwargs=kwargs,
+                                                       recipients=[self.u2], type_=type_)
+
+            # Email type TYPE_PASSWORD_RESET has no corresponding notification type - test it directly:
+            desc = 'TYPE_PASSWORD_RESET'
+            kwargs = dict(user='John Doe', reset_token='decbf64715098db5b0bd23eab44bd792670ab746', reset_url='http://reset.com/decbf64715098db5b0bd23eab44bd792670ab746')
+            kallithea.lib.celerylib.tasks.send_email(['john@doe.com'],
+                "Password reset link",
+                EmailNotificationModel().get_email_tmpl(EmailNotificationModel.TYPE_PASSWORD_RESET, 'txt', **kwargs),
+                EmailNotificationModel().get_email_tmpl(EmailNotificationModel.TYPE_PASSWORD_RESET, 'html', **kwargs),
+                author=User.get(self.u1))
+
+        out = '<!doctype html>\n<html lang="en">\n<head><title>Notifications</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>\n<body>\n%s\n</body>\n</html>\n' % \
+            re.sub(r'<(/?(?:!doctype|html|head|title|meta|body)\b[^>]*)>', r'<!--\1-->', ''.join(l))
+
+        outfn = os.path.join(os.path.dirname(__file__), 'test_dump_html_mails.out.html')
+        reffn = os.path.join(os.path.dirname(__file__), 'test_dump_html_mails.ref.html')
+        with file(outfn, 'w') as f:
+            f.write(out)
+        with file(reffn) as f:
+            ref = f.read()
+        assert ref == out # copy test_dump_html_mails.out.html to test_dump_html_mails.ref.html to update expectations
+        os.unlink(outfn)
--- a/kallithea/tests/models/test_permissions.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/models/test_permissions.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,8 +1,8 @@
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.tests.fixture import Fixture
 from kallithea.model.repo_group import RepoGroupModel
 from kallithea.model.repo import RepoModel
-from kallithea.model.db import RepoGroup, User, UserGroupRepoGroupToPerm,\
+from kallithea.model.db import RepoGroup, User, UserGroupRepoGroupToPerm, \
     Permission, UserToPerm
 from kallithea.model.user import UserModel
 
@@ -15,18 +15,16 @@
 fixture = Fixture()
 
 
-class TestPermissions(BaseTestCase):
-    def __init__(self, methodName='runTest'):
-        super(TestPermissions, self).__init__(methodName=methodName)
+class TestPermissions(TestController):
 
     @classmethod
-    def setUpClass(cls):
+    def setup_class(cls):
         #recreate default user to get a clean start
         PermissionModel().create_default_permissions(user=User.DEFAULT_USER,
                                                      force=True)
         Session().commit()
 
-    def setUp(self):
+    def setup_method(self, method):
         self.u1 = UserModel().create_or_update(
             username=u'u1', password=u'qweqwe',
             email=u'u1@example.com', firstname=u'u1', lastname=u'u1'
@@ -46,7 +44,7 @@
         )
         Session().commit()
 
-    def tearDown(self):
+    def teardown_method(self, method):
         if hasattr(self, 'test_repo'):
             RepoModel().delete(repo=self.test_repo)
 
@@ -59,10 +57,10 @@
         if hasattr(self, 'g2'):
             RepoGroupModel().delete(self.g2.group_id)
 
+        if hasattr(self, 'ug2'):
+            UserGroupModel().delete(self.ug2, force=True)
         if hasattr(self, 'ug1'):
             UserGroupModel().delete(self.ug1, force=True)
-        if hasattr(self, 'ug2'):
-            UserGroupModel().delete(self.ug2, force=True)
 
         Session().commit()
 
@@ -70,30 +68,27 @@
         u1_auth = AuthUser(user_id=self.u1.user_id)
         perms = {
             'repositories_groups': {},
-            'global': set([u'hg.create.repository', u'repository.read',
-                           u'hg.register.manual_activate']),
-            'repositories': {HG_REPO: u'repository.read'}
+            'global': set(['hg.create.repository', 'repository.read',
+                           'hg.register.manual_activate']),
+            'repositories': {HG_REPO: 'repository.read'}
         }
-        self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
-                         perms['repositories'][HG_REPO])
+        assert u1_auth.permissions['repositories'][HG_REPO] == perms['repositories'][HG_REPO]
         new_perm = 'repository.write'
         RepoModel().grant_user_permission(repo=HG_REPO, user=self.u1,
                                           perm=new_perm)
         Session().commit()
 
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
-                         new_perm)
+        assert u1_auth.permissions['repositories'][HG_REPO] == new_perm
 
     def test_default_admin_perms_set(self):
         a1_auth = AuthUser(user_id=self.a1.user_id)
         perms = {
             'repositories_groups': {},
-            'global': set([u'hg.admin', 'hg.create.write_on_repogroup.true']),
-            'repositories': {HG_REPO: u'repository.admin'}
+            'global': set(['hg.admin', 'hg.create.write_on_repogroup.true']),
+            'repositories': {HG_REPO: 'repository.admin'}
         }
-        self.assertEqual(a1_auth.permissions['repositories'][HG_REPO],
-                         perms['repositories'][HG_REPO])
+        assert a1_auth.permissions['repositories'][HG_REPO] == perms['repositories'][HG_REPO]
         new_perm = 'repository.write'
         RepoModel().grant_user_permission(repo=HG_REPO, user=self.a1,
                                           perm=new_perm)
@@ -101,28 +96,24 @@
         # cannot really downgrade admins permissions !? they still gets set as
         # admin !
         u1_auth = AuthUser(user_id=self.a1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
-                         perms['repositories'][HG_REPO])
+        assert u1_auth.permissions['repositories'][HG_REPO] == perms['repositories'][HG_REPO]
 
     def test_default_group_perms(self):
-        self.g1 = fixture.create_repo_group('test1', skip_if_exists=True)
-        self.g2 = fixture.create_repo_group('test2', skip_if_exists=True)
+        self.g1 = fixture.create_repo_group(u'test1', skip_if_exists=True)
+        self.g2 = fixture.create_repo_group(u'test2', skip_if_exists=True)
         u1_auth = AuthUser(user_id=self.u1.user_id)
         perms = {
             'repositories_groups': {u'test1': 'group.read', u'test2': 'group.read'},
             'global': set(Permission.DEFAULT_USER_PERMISSIONS),
-            'repositories': {HG_REPO: u'repository.read'}
+            'repositories': {HG_REPO: 'repository.read'}
         }
-        self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
-                         perms['repositories'][HG_REPO])
-        self.assertEqual(u1_auth.permissions['repositories_groups'],
-                         perms['repositories_groups'])
-        self.assertEqual(u1_auth.permissions['global'],
-                         perms['global'])
+        assert u1_auth.permissions['repositories'][HG_REPO] == perms['repositories'][HG_REPO]
+        assert u1_auth.permissions['repositories_groups'] == perms['repositories_groups']
+        assert u1_auth.permissions['global'] == perms['global']
 
     def test_default_admin_group_perms(self):
-        self.g1 = fixture.create_repo_group('test1', skip_if_exists=True)
-        self.g2 = fixture.create_repo_group('test2', skip_if_exists=True)
+        self.g1 = fixture.create_repo_group(u'test1', skip_if_exists=True)
+        self.g2 = fixture.create_repo_group(u'test2', skip_if_exists=True)
         a1_auth = AuthUser(user_id=self.a1.user_id)
         perms = {
             'repositories_groups': {u'test1': 'group.admin', u'test2': 'group.admin'},
@@ -130,14 +121,12 @@
             'repositories': {HG_REPO: 'repository.admin'}
         }
 
-        self.assertEqual(a1_auth.permissions['repositories'][HG_REPO],
-                         perms['repositories'][HG_REPO])
-        self.assertEqual(a1_auth.permissions['repositories_groups'],
-                         perms['repositories_groups'])
+        assert a1_auth.permissions['repositories'][HG_REPO] == perms['repositories'][HG_REPO]
+        assert a1_auth.permissions['repositories_groups'] == perms['repositories_groups']
 
     def test_propagated_permission_from_users_group_by_explicit_perms_exist(self):
         # make group
-        self.ug1 = fixture.create_user_group('G1')
+        self.ug1 = fixture.create_user_group(u'G1')
         UserGroupModel().add_user_to_group(self.ug1, self.u1)
 
         # set permission to lower
@@ -145,8 +134,7 @@
         RepoModel().grant_user_permission(repo=HG_REPO, user=self.u1, perm=new_perm)
         Session().commit()
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
-                         new_perm)
+        assert u1_auth.permissions['repositories'][HG_REPO] == new_perm
 
         # grant perm for group this should not override permission from user
         # since it has explicitly set
@@ -158,18 +146,16 @@
         u1_auth = AuthUser(user_id=self.u1.user_id)
         perms = {
             'repositories_groups': {},
-            'global': set([u'hg.create.repository', u'repository.read',
-                           u'hg.register.manual_activate']),
-            'repositories': {HG_REPO: u'repository.read'}
+            'global': set(['hg.create.repository', 'repository.read',
+                           'hg.register.manual_activate']),
+            'repositories': {HG_REPO: 'repository.read'}
         }
-        self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
-                         new_perm)
-        self.assertEqual(u1_auth.permissions['repositories_groups'],
-                         perms['repositories_groups'])
+        assert u1_auth.permissions['repositories'][HG_REPO] == new_perm
+        assert u1_auth.permissions['repositories_groups'] == perms['repositories_groups']
 
     def test_propagated_permission_from_users_group(self):
         # make group
-        self.ug1 = fixture.create_user_group('G1')
+        self.ug1 = fixture.create_user_group(u'G1')
         UserGroupModel().add_user_to_group(self.ug1, self.u3)
 
         # grant perm for group this should override default permission from user
@@ -181,18 +167,16 @@
         u3_auth = AuthUser(user_id=self.u3.user_id)
         perms = {
             'repositories_groups': {},
-            'global': set([u'hg.create.repository', u'repository.read',
-                           u'hg.register.manual_activate']),
-            'repositories': {HG_REPO: u'repository.read'}
+            'global': set(['hg.create.repository', 'repository.read',
+                           'hg.register.manual_activate']),
+            'repositories': {HG_REPO: 'repository.read'}
         }
-        self.assertEqual(u3_auth.permissions['repositories'][HG_REPO],
-                         new_perm_gr)
-        self.assertEqual(u3_auth.permissions['repositories_groups'],
-                         perms['repositories_groups'])
+        assert u3_auth.permissions['repositories'][HG_REPO] == new_perm_gr
+        assert u3_auth.permissions['repositories_groups'] == perms['repositories_groups']
 
     def test_propagated_permission_from_users_group_lower_weight(self):
         # make group
-        self.ug1 = fixture.create_user_group('G1')
+        self.ug1 = fixture.create_user_group(u'G1')
         # add user to group
         UserGroupModel().add_user_to_group(self.ug1, self.u1)
 
@@ -202,8 +186,7 @@
                                           perm=new_perm_h)
         Session().commit()
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
-                         new_perm_h)
+        assert u1_auth.permissions['repositories'][HG_REPO] == new_perm_h
 
         # grant perm for group this should NOT override permission from user
         # since it's lower than granted
@@ -215,26 +198,22 @@
         u1_auth = AuthUser(user_id=self.u1.user_id)
         perms = {
             'repositories_groups': {},
-            'global': set([u'hg.create.repository', u'repository.read',
-                           u'hg.register.manual_activate']),
-            'repositories': {HG_REPO: u'repository.write'}
+            'global': set(['hg.create.repository', 'repository.read',
+                           'hg.register.manual_activate']),
+            'repositories': {HG_REPO: 'repository.write'}
         }
-        self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
-                         new_perm_h)
-        self.assertEqual(u1_auth.permissions['repositories_groups'],
-                         perms['repositories_groups'])
+        assert u1_auth.permissions['repositories'][HG_REPO] == new_perm_h
+        assert u1_auth.permissions['repositories_groups'] == perms['repositories_groups']
 
     def test_repo_in_group_permissions(self):
-        self.g1 = fixture.create_repo_group('group1', skip_if_exists=True)
-        self.g2 = fixture.create_repo_group('group2', skip_if_exists=True)
+        self.g1 = fixture.create_repo_group(u'group1', skip_if_exists=True)
+        self.g2 = fixture.create_repo_group(u'group2', skip_if_exists=True)
         # both perms should be read !
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories_groups'],
-                         {u'group1': u'group.read', u'group2': u'group.read'})
+        assert u1_auth.permissions['repositories_groups'] == {u'group1': u'group.read', u'group2': u'group.read'}
 
         a1_auth = AuthUser(user_id=self.anon.user_id)
-        self.assertEqual(a1_auth.permissions['repositories_groups'],
-                 {u'group1': u'group.read', u'group2': u'group.read'})
+        assert a1_auth.permissions['repositories_groups'] == {u'group1': u'group.read', u'group2': u'group.read'}
 
         #Change perms to none for both groups
         RepoGroupModel().grant_user_permission(repo_group=self.g1,
@@ -245,12 +224,10 @@
                                                perm='group.none')
 
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories_groups'],
-                 {u'group1': u'group.none', u'group2': u'group.none'})
+        assert u1_auth.permissions['repositories_groups'] == {u'group1': u'group.none', u'group2': u'group.none'}
 
         a1_auth = AuthUser(user_id=self.anon.user_id)
-        self.assertEqual(a1_auth.permissions['repositories_groups'],
-                 {u'group1': u'group.none', u'group2': u'group.none'})
+        assert a1_auth.permissions['repositories_groups'] == {u'group1': u'group.none', u'group2': u'group.none'}
 
         # add repo to group
         name = RepoGroup.url_sep().join([self.g1.group_name, 'test_perm'])
@@ -260,12 +237,10 @@
                                              cur_user=self.u1,)
 
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories_groups'],
-                 {u'group1': u'group.none', u'group2': u'group.none'})
+        assert u1_auth.permissions['repositories_groups'] == {u'group1': u'group.none', u'group2': u'group.none'}
 
         a1_auth = AuthUser(user_id=self.anon.user_id)
-        self.assertEqual(a1_auth.permissions['repositories_groups'],
-                 {u'group1': u'group.none', u'group2': u'group.none'})
+        assert a1_auth.permissions['repositories_groups'] == {u'group1': u'group.none', u'group2': u'group.none'}
 
         #grant permission for u2 !
         RepoGroupModel().grant_user_permission(repo_group=self.g1, user=self.u2,
@@ -273,51 +248,45 @@
         RepoGroupModel().grant_user_permission(repo_group=self.g2, user=self.u2,
                                                perm='group.read')
         Session().commit()
-        self.assertNotEqual(self.u1, self.u2)
+        assert self.u1 != self.u2
         #u1 and anon should have not change perms while u2 should !
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories_groups'],
-                 {u'group1': u'group.none', u'group2': u'group.none'})
+        assert u1_auth.permissions['repositories_groups'] == {u'group1': u'group.none', u'group2': u'group.none'}
 
         u2_auth = AuthUser(user_id=self.u2.user_id)
-        self.assertEqual(u2_auth.permissions['repositories_groups'],
-                 {u'group1': u'group.read', u'group2': u'group.read'})
+        assert u2_auth.permissions['repositories_groups'] == {u'group1': u'group.read', u'group2': u'group.read'}
 
         a1_auth = AuthUser(user_id=self.anon.user_id)
-        self.assertEqual(a1_auth.permissions['repositories_groups'],
-                 {u'group1': u'group.none', u'group2': u'group.none'})
+        assert a1_auth.permissions['repositories_groups'] == {u'group1': u'group.none', u'group2': u'group.none'}
 
     def test_repo_group_user_as_user_group_member(self):
         # create Group1
-        self.g1 = fixture.create_repo_group('group1', skip_if_exists=True)
+        self.g1 = fixture.create_repo_group(u'group1', skip_if_exists=True)
         a1_auth = AuthUser(user_id=self.anon.user_id)
 
-        self.assertEqual(a1_auth.permissions['repositories_groups'],
-                         {u'group1': u'group.read'})
+        assert a1_auth.permissions['repositories_groups'] == {u'group1': u'group.read'}
 
         # set default permission to none
         RepoGroupModel().grant_user_permission(repo_group=self.g1,
                                                user=self.anon,
                                                perm='group.none')
         # make group
-        self.ug1 = fixture.create_user_group('G1')
+        self.ug1 = fixture.create_user_group(u'G1')
         # add user to group
         UserGroupModel().add_user_to_group(self.ug1, self.u1)
         Session().commit()
 
         # check if user is in the group
-        membrs = [x.user_id for x in UserGroupModel().get(self.ug1.users_group_id).members]
-        self.assertEqual(membrs, [self.u1.user_id])
+        members = [x.user_id for x in UserGroupModel().get(self.ug1.users_group_id).members]
+        assert members == [self.u1.user_id]
         # add some user to that group
 
         # check his permissions
         a1_auth = AuthUser(user_id=self.anon.user_id)
-        self.assertEqual(a1_auth.permissions['repositories_groups'],
-                         {u'group1': u'group.none'})
+        assert a1_auth.permissions['repositories_groups'] == {u'group1': u'group.none'}
 
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories_groups'],
-                         {u'group1': u'group.none'})
+        assert u1_auth.permissions['repositories_groups'] == {u'group1': u'group.none'}
 
         # grant ug1 read permissions for
         RepoGroupModel().grant_user_group_permission(repo_group=self.g1,
@@ -325,20 +294,18 @@
                                                       perm='group.read')
         Session().commit()
         # check if the
-        obj = Session().query(UserGroupRepoGroupToPerm)\
-            .filter(UserGroupRepoGroupToPerm.group == self.g1)\
-            .filter(UserGroupRepoGroupToPerm.users_group == self.ug1)\
+        obj = Session().query(UserGroupRepoGroupToPerm) \
+            .filter(UserGroupRepoGroupToPerm.group == self.g1) \
+            .filter(UserGroupRepoGroupToPerm.users_group == self.ug1) \
             .scalar()
-        self.assertEqual(obj.permission.permission_name, 'group.read')
+        assert obj.permission.permission_name == 'group.read'
 
         a1_auth = AuthUser(user_id=self.anon.user_id)
 
-        self.assertEqual(a1_auth.permissions['repositories_groups'],
-                         {u'group1': u'group.none'})
+        assert a1_auth.permissions['repositories_groups'] == {u'group1': u'group.none'}
 
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories_groups'],
-                         {u'group1': u'group.read'})
+        assert u1_auth.permissions['repositories_groups'] == {u'group1': u'group.read'}
 
     def test_inherited_permissions_from_default_on_user_enabled(self):
         user_model = UserModel()
@@ -353,12 +320,11 @@
         Session().commit()
         u1_auth = AuthUser(user_id=self.u1.user_id)
         # this user will have inherited permissions from default user
-        self.assertEqual(u1_auth.permissions['global'],
-                         set(['hg.create.repository', 'hg.fork.repository',
+        assert u1_auth.permissions['global'] == set(['hg.create.repository', 'hg.fork.repository',
                               'hg.register.manual_activate',
                               'hg.extern_activate.auto',
                               'repository.read', 'group.read',
-                              'usergroup.read', 'hg.create.write_on_repogroup.true']))
+                              'usergroup.read', 'hg.create.write_on_repogroup.true'])
 
     def test_inherited_permissions_from_default_on_user_disabled(self):
         user_model = UserModel()
@@ -373,12 +339,11 @@
         Session().commit()
         u1_auth = AuthUser(user_id=self.u1.user_id)
         # this user will have inherited permissions from default user
-        self.assertEqual(u1_auth.permissions['global'],
-                         set(['hg.create.none', 'hg.fork.none',
+        assert u1_auth.permissions['global'] == set(['hg.create.none', 'hg.fork.none',
                               'hg.register.manual_activate',
                               'hg.extern_activate.auto',
                               'repository.read', 'group.read',
-                              'usergroup.read', 'hg.create.write_on_repogroup.true']))
+                              'usergroup.read', 'hg.create.write_on_repogroup.true'])
 
     def test_non_inherited_permissions_from_default_on_user_enabled(self):
         user_model = UserModel()
@@ -401,12 +366,11 @@
         u1_auth = AuthUser(user_id=self.u1.user_id)
         # this user will have non inherited permissions from he's
         # explicitly set permissions
-        self.assertEqual(u1_auth.permissions['global'],
-                         set(['hg.create.none', 'hg.fork.none',
+        assert u1_auth.permissions['global'] == set(['hg.create.none', 'hg.fork.none',
                               'hg.register.manual_activate',
                               'hg.extern_activate.auto',
                               'repository.read', 'group.read',
-                              'usergroup.read', 'hg.create.write_on_repogroup.true']))
+                              'usergroup.read', 'hg.create.write_on_repogroup.true'])
 
     def test_non_inherited_permissions_from_default_on_user_disabled(self):
         user_model = UserModel()
@@ -429,19 +393,18 @@
         u1_auth = AuthUser(user_id=self.u1.user_id)
         # this user will have non inherited permissions from he's
         # explicitly set permissions
-        self.assertEqual(u1_auth.permissions['global'],
-                         set(['hg.create.repository', 'hg.fork.repository',
+        assert u1_auth.permissions['global'] == set(['hg.create.repository', 'hg.fork.repository',
                               'hg.register.manual_activate',
                               'hg.extern_activate.auto',
                               'repository.read', 'group.read',
-                              'usergroup.read', 'hg.create.write_on_repogroup.true']))
+                              'usergroup.read', 'hg.create.write_on_repogroup.true'])
 
     def test_inactive_user_group_does_not_affect_global_permissions(self):
         # Issue #138: Inactive User Groups affecting permissions
         # Add user to inactive user group, set specific permissions on user
         # group and disable inherit-from-default. User permissions should still
         # inherit from default.
-        self.ug1 = fixture.create_user_group('G1')
+        self.ug1 = fixture.create_user_group(u'G1')
         self.ug1.inherit_default_permissions = False
         user_group_model = UserGroupModel()
         user_group_model.add_user_to_group(self.ug1, self.u1)
@@ -464,20 +427,19 @@
         Session().commit()
         u1_auth = AuthUser(user_id=self.u1.user_id)
 
-        self.assertEqual(u1_auth.permissions['global'],
-                         set(['hg.create.none', 'hg.fork.none',
+        assert u1_auth.permissions['global'] == set(['hg.create.none', 'hg.fork.none',
                               'hg.register.manual_activate',
                               'hg.extern_activate.auto',
                               'repository.read', 'group.read',
                               'usergroup.read',
-                              'hg.create.write_on_repogroup.true']))
+                              'hg.create.write_on_repogroup.true'])
 
     def test_inactive_user_group_does_not_affect_global_permissions_inverse(self):
         # Issue #138: Inactive User Groups affecting permissions
         # Add user to inactive user group, set specific permissions on user
         # group and disable inherit-from-default. User permissions should still
         # inherit from default.
-        self.ug1 = fixture.create_user_group('G1')
+        self.ug1 = fixture.create_user_group(u'G1')
         self.ug1.inherit_default_permissions = False
         user_group_model = UserGroupModel()
         user_group_model.add_user_to_group(self.ug1, self.u1)
@@ -500,16 +462,15 @@
         Session().commit()
         u1_auth = AuthUser(user_id=self.u1.user_id)
 
-        self.assertEqual(u1_auth.permissions['global'],
-                         set(['hg.create.repository', 'hg.fork.repository',
+        assert u1_auth.permissions['global'] == set(['hg.create.repository', 'hg.fork.repository',
                               'hg.register.manual_activate',
                               'hg.extern_activate.auto',
                               'repository.read', 'group.read',
                               'usergroup.read',
-                              'hg.create.write_on_repogroup.true']))
+                              'hg.create.write_on_repogroup.true'])
 
     def test_inactive_user_group_does_not_affect_repo_permissions(self):
-        self.ug1 = fixture.create_user_group('G1')
+        self.ug1 = fixture.create_user_group(u'G1')
         self.ug1.inherit_default_permissions = False
         user_group_model = UserGroupModel()
         user_group_model.add_user_to_group(self.ug1, self.u1)
@@ -517,7 +478,7 @@
 
         # note: make u2 repo owner rather than u1, because the owner always has
         # admin permissions
-        self.test_repo = fixture.create_repo(name='myownrepo',
+        self.test_repo = fixture.create_repo(name=u'myownrepo',
                                              repo_type='hg',
                                              cur_user=self.u2)
 
@@ -531,11 +492,10 @@
                                           perm='repository.write')
         Session().commit()
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories']['myownrepo'],
-                         'repository.write')
+        assert u1_auth.permissions['repositories']['myownrepo'] == 'repository.write'
 
     def test_inactive_user_group_does_not_affect_repo_permissions_inverse(self):
-        self.ug1 = fixture.create_user_group('G1')
+        self.ug1 = fixture.create_user_group(u'G1')
         self.ug1.inherit_default_permissions = False
         user_group_model = UserGroupModel()
         user_group_model.add_user_to_group(self.ug1, self.u1)
@@ -543,7 +503,7 @@
 
         # note: make u2 repo owner rather than u1, because the owner always has
         # admin permissions
-        self.test_repo = fixture.create_repo(name='myownrepo',
+        self.test_repo = fixture.create_repo(name=u'myownrepo',
                                              repo_type='hg',
                                              cur_user=self.u2)
 
@@ -557,17 +517,16 @@
                                           perm='repository.admin')
         Session().commit()
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories']['myownrepo'],
-                         'repository.admin')
+        assert u1_auth.permissions['repositories']['myownrepo'] == 'repository.admin'
 
     def test_inactive_user_group_does_not_affect_repo_group_permissions(self):
-        self.ug1 = fixture.create_user_group('G1')
+        self.ug1 = fixture.create_user_group(u'G1')
         self.ug1.inherit_default_permissions = False
         user_group_model = UserGroupModel()
         user_group_model.add_user_to_group(self.ug1, self.u1)
         user_group_model.update(self.ug1, {'users_group_active': False})
 
-        self.g1 = fixture.create_repo_group('group1', skip_if_exists=True)
+        self.g1 = fixture.create_repo_group(u'group1', skip_if_exists=True)
 
         # enable admin access for user group on repo group
         RepoGroupModel().grant_user_group_permission(self.g1,
@@ -579,17 +538,16 @@
                                                perm='group.write')
         Session().commit()
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories_groups'],
-                         {u'group1': u'group.write'})
+        assert u1_auth.permissions['repositories_groups'] == {u'group1': u'group.write'}
 
     def test_inactive_user_group_does_not_affect_repo_group_permissions_inverse(self):
-        self.ug1 = fixture.create_user_group('G1')
+        self.ug1 = fixture.create_user_group(u'G1')
         self.ug1.inherit_default_permissions = False
         user_group_model = UserGroupModel()
         user_group_model.add_user_to_group(self.ug1, self.u1)
         user_group_model.update(self.ug1, {'users_group_active': False})
 
-        self.g1 = fixture.create_repo_group('group1', skip_if_exists=True)
+        self.g1 = fixture.create_repo_group(u'group1', skip_if_exists=True)
 
         # enable only write access for user group on repo group
         RepoGroupModel().grant_user_group_permission(self.g1,
@@ -601,17 +559,16 @@
                                                perm='group.admin')
         Session().commit()
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories_groups'],
-                         {u'group1': u'group.admin'})
+        assert u1_auth.permissions['repositories_groups'] == {u'group1': u'group.admin'}
 
     def test_inactive_user_group_does_not_affect_user_group_permissions(self):
-        self.ug1 = fixture.create_user_group('G1')
+        self.ug1 = fixture.create_user_group(u'G1')
         self.ug1.inherit_default_permissions = False
         user_group_model = UserGroupModel()
         user_group_model.add_user_to_group(self.ug1, self.u1)
         user_group_model.update(self.ug1, {'users_group_active': False})
 
-        self.ug2 = fixture.create_user_group('G2')
+        self.ug2 = fixture.create_user_group(u'G2')
 
         # enable admin access for user group on user group
         UserGroupModel().grant_user_group_permission(self.ug2,
@@ -623,17 +580,17 @@
                                                perm='usergroup.write')
         Session().commit()
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['user_groups'][u'G1'], u'usergroup.read')
-        self.assertEqual(u1_auth.permissions['user_groups'][u'G2'], u'usergroup.write')
+        assert u1_auth.permissions['user_groups'][u'G1'] == u'usergroup.read'
+        assert u1_auth.permissions['user_groups'][u'G2'] == u'usergroup.write'
 
     def test_inactive_user_group_does_not_affect_user_group_permissions_inverse(self):
-        self.ug1 = fixture.create_user_group('G1')
+        self.ug1 = fixture.create_user_group(u'G1')
         self.ug1.inherit_default_permissions = False
         user_group_model = UserGroupModel()
         user_group_model.add_user_to_group(self.ug1, self.u1)
         user_group_model.update(self.ug1, {'users_group_active': False})
 
-        self.ug2 = fixture.create_user_group('G2')
+        self.ug2 = fixture.create_user_group(u'G2')
 
         # enable only write access for user group on user group
         UserGroupModel().grant_user_group_permission(self.ug2,
@@ -645,21 +602,20 @@
                                                perm='usergroup.admin')
         Session().commit()
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['user_groups'][u'G1'], u'usergroup.read')
-        self.assertEqual(u1_auth.permissions['user_groups'][u'G2'], u'usergroup.admin')
+        assert u1_auth.permissions['user_groups'][u'G1'] == u'usergroup.read'
+        assert u1_auth.permissions['user_groups'][u'G2'] == u'usergroup.admin'
 
     def test_owner_permissions_doesnot_get_overwritten_by_group(self):
         #create repo as USER,
-        self.test_repo = fixture.create_repo(name='myownrepo',
+        self.test_repo = fixture.create_repo(name=u'myownrepo',
                                              repo_type='hg',
                                              cur_user=self.u1)
 
         #he has permissions of admin as owner
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories']['myownrepo'],
-                         'repository.admin')
+        assert u1_auth.permissions['repositories']['myownrepo'] == 'repository.admin'
         #set his permission as user group, he should still be admin
-        self.ug1 = fixture.create_user_group('G1')
+        self.ug1 = fixture.create_user_group(u'G1')
         UserGroupModel().add_user_to_group(self.ug1, self.u1)
         RepoModel().grant_user_group_permission(self.test_repo,
                                                  group_name=self.ug1,
@@ -667,34 +623,29 @@
 
         Session().commit()
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories']['myownrepo'],
-                         'repository.admin')
+        assert u1_auth.permissions['repositories']['myownrepo'] == 'repository.admin'
 
     def test_owner_permissions_doesnot_get_overwritten_by_others(self):
         #create repo as USER,
-        self.test_repo = fixture.create_repo(name='myownrepo',
+        self.test_repo = fixture.create_repo(name=u'myownrepo',
                                              repo_type='hg',
                                              cur_user=self.u1)
 
         #he has permissions of admin as owner
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories']['myownrepo'],
-                         'repository.admin')
+        assert u1_auth.permissions['repositories']['myownrepo'] == 'repository.admin'
         #set his permission as user, he should still be admin
         RepoModel().grant_user_permission(self.test_repo, user=self.u1,
                                           perm='repository.none')
         Session().commit()
         u1_auth = AuthUser(user_id=self.u1.user_id)
-        self.assertEqual(u1_auth.permissions['repositories']['myownrepo'],
-                         'repository.admin')
+        assert u1_auth.permissions['repositories']['myownrepo'] == 'repository.admin'
 
     def _test_def_perm_equal(self, user, change_factor=0):
-        perms = UserToPerm.query()\
-                .filter(UserToPerm.user == user)\
+        perms = UserToPerm.query() \
+                .filter(UserToPerm.user == user) \
                 .all()
-        self.assertEqual(len(perms),
-                         len(Permission.DEFAULT_USER_PERMISSIONS,)+change_factor,
-                         msg=perms)
+        assert len(perms) == len(Permission.DEFAULT_USER_PERMISSIONS,)+change_factor, perms
 
     def test_set_default_permissions(self):
         PermissionModel().create_default_permissions(user=self.u1)
@@ -704,8 +655,8 @@
         PermissionModel().create_default_permissions(user=self.u1)
         self._test_def_perm_equal(user=self.u1)
         #now we delete one, it should be re-created after another call
-        perms = UserToPerm.query()\
-                .filter(UserToPerm.user == self.u1)\
+        perms = UserToPerm.query() \
+                .filter(UserToPerm.user == self.u1) \
                 .all()
         Session().delete(perms[0])
         Session().commit()
@@ -716,7 +667,7 @@
         PermissionModel().create_default_permissions(user=self.u1)
         self._test_def_perm_equal(user=self.u1)
 
-    @parameterized.expand([
+    @parametrize('perm,modify_to', [
         ('repository.read', 'repository.none'),
         ('group.read', 'group.none'),
         ('usergroup.read', 'usergroup.none'),
@@ -730,16 +681,15 @@
 
         old = Permission.get_by_key(perm)
         new = Permission.get_by_key(modify_to)
-        self.assertNotEqual(old, None)
-        self.assertNotEqual(new, None)
+        assert old != None
+        assert new != None
 
         #now modify permissions
-        p = UserToPerm.query()\
-                .filter(UserToPerm.user == self.u1)\
-                .filter(UserToPerm.permission == old)\
+        p = UserToPerm.query() \
+                .filter(UserToPerm.user == self.u1) \
+                .filter(UserToPerm.permission == old) \
                 .one()
         p.permission = new
-        Session().add(p)
         Session().commit()
 
         PermissionModel().create_default_permissions(user=self.u1)
--- a/kallithea/tests/models/test_repo_groups.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/models/test_repo_groups.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,7 +1,8 @@
 import os
+import pytest
 from sqlalchemy.exc import IntegrityError
 
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.tests.fixture import Fixture
 
 from kallithea.model.repo_group import RepoGroupModel
@@ -13,10 +14,10 @@
 fixture = Fixture()
 
 
-def _update_group(id_, group_name, desc='desc', parent_id=None):
+def _update_group(id_, group_name, desc=u'desc', parent_id=None):
     form_data = fixture._get_group_create_params(group_name=group_name,
                                                  group_desc=desc,
-                                                 group_parent_id=parent_id)
+                                                 parent_group_id=parent_id)
     gr = RepoGroupModel().update(id_, form_data)
     return gr
 
@@ -33,19 +34,19 @@
     return r
 
 
-class TestRepoGroups(BaseTestCase):
+class TestRepoGroups(TestController):
 
-    def setUp(self):
-        self.g1 = fixture.create_repo_group('test1', skip_if_exists=True)
-        self.g2 = fixture.create_repo_group('test2', skip_if_exists=True)
-        self.g3 = fixture.create_repo_group('test3', skip_if_exists=True)
+    def setup_method(self, method):
+        self.g1 = fixture.create_repo_group(u'test1', skip_if_exists=True)
+        self.g2 = fixture.create_repo_group(u'test2', skip_if_exists=True)
+        self.g3 = fixture.create_repo_group(u'test3', skip_if_exists=True)
 
-    def tearDown(self):
+    def teardown_method(self, method):
         Session.remove()
 
     def __check_path(self, *path):
         """
-        Checks the path for existance !
+        Checks the path for existence !
         """
         path = [TESTS_TMP_PATH] + list(path)
         path = os.path.join(*path)
@@ -58,142 +59,143 @@
         RepoGroupModel().delete(id_)
 
     def test_create_group(self):
-        g = fixture.create_repo_group('newGroup')
+        g = fixture.create_repo_group(u'newGroup')
         Session().commit()
-        self.assertEqual(g.full_path, 'newGroup')
+        assert g.full_path == 'newGroup'
 
-        self.assertTrue(self.__check_path('newGroup'))
+        assert self.__check_path('newGroup')
 
     def test_create_same_name_group(self):
-        self.assertRaises(IntegrityError, lambda: fixture.create_repo_group('newGroup'))
+        with pytest.raises(IntegrityError):
+            fixture.create_repo_group(u'newGroup')
         Session().rollback()
 
     def test_same_subgroup(self):
-        sg1 = fixture.create_repo_group('sub1', group_parent_id=self.g1.group_id)
-        self.assertEqual(sg1.parent_group, self.g1)
-        self.assertEqual(sg1.full_path, 'test1/sub1')
-        self.assertTrue(self.__check_path('test1', 'sub1'))
+        sg1 = fixture.create_repo_group(u'sub1', parent_group_id=self.g1.group_id)
+        assert sg1.parent_group == self.g1
+        assert sg1.full_path == 'test1/sub1'
+        assert self.__check_path('test1', 'sub1')
 
-        ssg1 = fixture.create_repo_group('subsub1', group_parent_id=sg1.group_id)
-        self.assertEqual(ssg1.parent_group, sg1)
-        self.assertEqual(ssg1.full_path, 'test1/sub1/subsub1')
-        self.assertTrue(self.__check_path('test1', 'sub1', 'subsub1'))
+        ssg1 = fixture.create_repo_group(u'subsub1', parent_group_id=sg1.group_id)
+        assert ssg1.parent_group == sg1
+        assert ssg1.full_path == 'test1/sub1/subsub1'
+        assert self.__check_path('test1', 'sub1', 'subsub1')
 
     def test_remove_group(self):
-        sg1 = fixture.create_repo_group('deleteme')
+        sg1 = fixture.create_repo_group(u'deleteme')
         self.__delete_group(sg1.group_id)
 
-        self.assertEqual(RepoGroup.get(sg1.group_id), None)
-        self.assertFalse(self.__check_path('deteteme'))
+        assert RepoGroup.get(sg1.group_id) == None
+        assert not self.__check_path('deteteme')
 
-        sg1 = fixture.create_repo_group('deleteme', group_parent_id=self.g1.group_id)
+        sg1 = fixture.create_repo_group(u'deleteme', parent_group_id=self.g1.group_id)
         self.__delete_group(sg1.group_id)
 
-        self.assertEqual(RepoGroup.get(sg1.group_id), None)
-        self.assertFalse(self.__check_path('test1', 'deteteme'))
+        assert RepoGroup.get(sg1.group_id) == None
+        assert not self.__check_path('test1', 'deteteme')
 
     def test_rename_single_group(self):
-        sg1 = fixture.create_repo_group('initial')
+        sg1 = fixture.create_repo_group(u'initial')
 
-        new_sg1 = _update_group(sg1.group_id, 'after')
-        self.assertTrue(self.__check_path('after'))
-        self.assertEqual(RepoGroup.get_by_group_name('initial'), None)
+        new_sg1 = _update_group(sg1.group_id, u'after')
+        assert self.__check_path('after')
+        assert RepoGroup.get_by_group_name(u'initial') == None
 
     def test_update_group_parent(self):
 
-        sg1 = fixture.create_repo_group('initial', group_parent_id=self.g1.group_id)
+        sg1 = fixture.create_repo_group(u'initial', parent_group_id=self.g1.group_id)
 
-        new_sg1 = _update_group(sg1.group_id, 'after', parent_id=self.g1.group_id)
-        self.assertTrue(self.__check_path('test1', 'after'))
-        self.assertEqual(RepoGroup.get_by_group_name('test1/initial'), None)
+        new_sg1 = _update_group(sg1.group_id, u'after', parent_id=self.g1.group_id)
+        assert self.__check_path('test1', 'after')
+        assert RepoGroup.get_by_group_name(u'test1/initial') == None
 
-        new_sg1 = _update_group(sg1.group_id, 'after', parent_id=self.g3.group_id)
-        self.assertTrue(self.__check_path('test3', 'after'))
-        self.assertEqual(RepoGroup.get_by_group_name('test3/initial'), None)
+        new_sg1 = _update_group(sg1.group_id, u'after', parent_id=self.g3.group_id)
+        assert self.__check_path('test3', 'after')
+        assert RepoGroup.get_by_group_name(u'test3/initial') == None
 
-        new_sg1 = _update_group(sg1.group_id, 'hello')
-        self.assertTrue(self.__check_path('hello'))
+        new_sg1 = _update_group(sg1.group_id, u'hello')
+        assert self.__check_path('hello')
 
-        self.assertEqual(RepoGroup.get_by_group_name('hello'), new_sg1)
+        assert RepoGroup.get_by_group_name(u'hello') == new_sg1
 
     def test_subgrouping_with_repo(self):
 
-        g1 = fixture.create_repo_group('g1')
-        g2 = fixture.create_repo_group('g2')
+        g1 = fixture.create_repo_group(u'g1')
+        g2 = fixture.create_repo_group(u'g2')
         # create new repo
-        r = fixture.create_repo('john')
+        r = fixture.create_repo(u'john')
 
-        self.assertEqual(r.repo_name, 'john')
+        assert r.repo_name == 'john'
         # put repo into group
-        r = _update_repo('john', repo_group=g1.group_id)
+        r = _update_repo(u'john', repo_group=g1.group_id)
         Session().commit()
-        self.assertEqual(r.repo_name, 'g1/john')
+        assert r.repo_name == 'g1/john'
 
-        _update_group(g1.group_id, 'g1', parent_id=g2.group_id)
-        self.assertTrue(self.__check_path('g2', 'g1'))
+        _update_group(g1.group_id, u'g1', parent_id=g2.group_id)
+        assert self.__check_path('g2', 'g1')
 
         # test repo
-        self.assertEqual(r.repo_name, RepoGroup.url_sep().join(['g2', 'g1',
-                                                                r.just_name]))
+        assert r.repo_name == RepoGroup.url_sep().join(['g2', 'g1',
+                                                                r.just_name])
 
     def test_move_to_root(self):
-        g1 = fixture.create_repo_group('t11')
-        g2 = fixture.create_repo_group('t22', group_parent_id=g1.group_id)
+        g1 = fixture.create_repo_group(u't11')
+        g2 = fixture.create_repo_group(u't22', parent_group_id=g1.group_id)
 
-        self.assertEqual(g2.full_path, 't11/t22')
-        self.assertTrue(self.__check_path('t11', 't22'))
+        assert g2.full_path == 't11/t22'
+        assert self.__check_path('t11', 't22')
 
-        g2 = _update_group(g2.group_id, 'g22', parent_id=None)
+        g2 = _update_group(g2.group_id, u'g22', parent_id=None)
         Session().commit()
 
-        self.assertEqual(g2.group_name, 'g22')
+        assert g2.group_name == 'g22'
         # we moved out group from t1 to '' so it's full path should be 'g2'
-        self.assertEqual(g2.full_path, 'g22')
-        self.assertFalse(self.__check_path('t11', 't22'))
-        self.assertTrue(self.__check_path('g22'))
+        assert g2.full_path == 'g22'
+        assert not self.__check_path('t11', 't22')
+        assert self.__check_path('g22')
 
     def test_rename_top_level_group_in_nested_setup(self):
-        g1 = fixture.create_repo_group('L1')
-        g2 = fixture.create_repo_group('L2', group_parent_id=g1.group_id)
-        g3 = fixture.create_repo_group('L3', group_parent_id=g2.group_id)
+        g1 = fixture.create_repo_group(u'L1')
+        g2 = fixture.create_repo_group(u'L2', parent_group_id=g1.group_id)
+        g3 = fixture.create_repo_group(u'L3', parent_group_id=g2.group_id)
 
-        r = fixture.create_repo('L1/L2/L3/L3_REPO', repo_group=g3.group_id)
+        r = fixture.create_repo(u'L1/L2/L3/L3_REPO', repo_group=g3.group_id)
 
         ##rename L1 all groups should be now changed
-        _update_group(g1.group_id, 'L1_NEW')
+        _update_group(g1.group_id, u'L1_NEW')
         Session().commit()
-        self.assertEqual(g1.full_path, 'L1_NEW')
-        self.assertEqual(g2.full_path, 'L1_NEW/L2')
-        self.assertEqual(g3.full_path, 'L1_NEW/L2/L3')
-        self.assertEqual(r.repo_name,  'L1_NEW/L2/L3/L3_REPO')
+        assert g1.full_path == 'L1_NEW'
+        assert g2.full_path == 'L1_NEW/L2'
+        assert g3.full_path == 'L1_NEW/L2/L3'
+        assert r.repo_name == 'L1_NEW/L2/L3/L3_REPO'
 
     def test_change_parent_of_top_level_group_in_nested_setup(self):
-        g1 = fixture.create_repo_group('R1')
-        g2 = fixture.create_repo_group('R2', group_parent_id=g1.group_id)
-        g3 = fixture.create_repo_group('R3', group_parent_id=g2.group_id)
-        g4 = fixture.create_repo_group('R1_NEW')
+        g1 = fixture.create_repo_group(u'R1')
+        g2 = fixture.create_repo_group(u'R2', parent_group_id=g1.group_id)
+        g3 = fixture.create_repo_group(u'R3', parent_group_id=g2.group_id)
+        g4 = fixture.create_repo_group(u'R1_NEW')
 
-        r = fixture.create_repo('R1/R2/R3/R3_REPO', repo_group=g3.group_id)
+        r = fixture.create_repo(u'R1/R2/R3/R3_REPO', repo_group=g3.group_id)
         ##rename L1 all groups should be now changed
-        _update_group(g1.group_id, 'R1', parent_id=g4.group_id)
+        _update_group(g1.group_id, u'R1', parent_id=g4.group_id)
         Session().commit()
-        self.assertEqual(g1.full_path, 'R1_NEW/R1')
-        self.assertEqual(g2.full_path, 'R1_NEW/R1/R2')
-        self.assertEqual(g3.full_path, 'R1_NEW/R1/R2/R3')
-        self.assertEqual(r.repo_name,  'R1_NEW/R1/R2/R3/R3_REPO')
+        assert g1.full_path == 'R1_NEW/R1'
+        assert g2.full_path == 'R1_NEW/R1/R2'
+        assert g3.full_path == 'R1_NEW/R1/R2/R3'
+        assert r.repo_name == 'R1_NEW/R1/R2/R3/R3_REPO'
 
     def test_change_parent_of_top_level_group_in_nested_setup_with_rename(self):
-        g1 = fixture.create_repo_group('X1')
-        g2 = fixture.create_repo_group('X2', group_parent_id=g1.group_id)
-        g3 = fixture.create_repo_group('X3', group_parent_id=g2.group_id)
-        g4 = fixture.create_repo_group('X1_NEW')
+        g1 = fixture.create_repo_group(u'X1')
+        g2 = fixture.create_repo_group(u'X2', parent_group_id=g1.group_id)
+        g3 = fixture.create_repo_group(u'X3', parent_group_id=g2.group_id)
+        g4 = fixture.create_repo_group(u'X1_NEW')
 
-        r = fixture.create_repo('X1/X2/X3/X3_REPO', repo_group=g3.group_id)
+        r = fixture.create_repo(u'X1/X2/X3/X3_REPO', repo_group=g3.group_id)
 
         ##rename L1 all groups should be now changed
-        _update_group(g1.group_id, 'X1_PRIM', parent_id=g4.group_id)
+        _update_group(g1.group_id, u'X1_PRIM', parent_id=g4.group_id)
         Session().commit()
-        self.assertEqual(g1.full_path, 'X1_NEW/X1_PRIM')
-        self.assertEqual(g2.full_path, 'X1_NEW/X1_PRIM/X2')
-        self.assertEqual(g3.full_path, 'X1_NEW/X1_PRIM/X2/X3')
-        self.assertEqual(r.repo_name,  'X1_NEW/X1_PRIM/X2/X3/X3_REPO')
+        assert g1.full_path == 'X1_NEW/X1_PRIM'
+        assert g2.full_path == 'X1_NEW/X1_PRIM/X2'
+        assert g3.full_path == 'X1_NEW/X1_PRIM/X2/X3'
+        assert r.repo_name == 'X1_NEW/X1_PRIM/X2/X3/X3_REPO'
--- a/kallithea/tests/models/test_repos.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/models/test_repos.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,4 +1,5 @@
-from kallithea.tests import *
+import pytest
+from kallithea.tests.base import *
 
 from kallithea.model.meta import Session
 from kallithea.tests.fixture import Fixture
@@ -9,69 +10,71 @@
 fixture = Fixture()
 
 
-class TestRepos(BaseTestCase):
+class TestRepos(TestController):
 
-    def setUp(self):
-        pass
-
-    def tearDown(self):
+    def teardown_method(self, method):
         Session.remove()
 
     def test_remove_repo(self):
-        repo = fixture.create_repo(name='test-repo-1')
+        repo = fixture.create_repo(name=u'test-repo-1')
         Session().commit()
 
         RepoModel().delete(repo=repo)
         Session().commit()
 
-        self.assertEqual(None, Repository.get_by_repo_name(repo_name='test-repo-1'))
+        assert None == Repository.get_by_repo_name(repo_name=u'test-repo-1')
 
     def test_remove_repo_repo_raises_exc_when_attached_forks(self):
-        repo = fixture.create_repo(name='test-repo-1')
+        repo = fixture.create_repo(name=u'test-repo-1')
+        Session().commit()
+
+        fixture.create_fork(repo.repo_name, u'test-repo-fork-1')
         Session().commit()
 
-        fixture.create_fork(repo.repo_name, 'test-repo-fork-1')
+        with pytest.raises(AttachedForksError):
+            RepoModel().delete(repo=repo)
+        # cleanup
+        RepoModel().delete(repo=u'test-repo-fork-1')
+        RepoModel().delete(repo=u'test-repo-1')
         Session().commit()
 
-        self.assertRaises(AttachedForksError, lambda: RepoModel().delete(repo=repo))
-
     def test_remove_repo_delete_forks(self):
-        repo = fixture.create_repo(name='test-repo-1')
+        repo = fixture.create_repo(name=u'test-repo-1')
         Session().commit()
 
-        fork = fixture.create_fork(repo.repo_name, 'test-repo-fork-1')
+        fork = fixture.create_fork(repo.repo_name, u'test-repo-fork-1')
         Session().commit()
 
         #fork of fork
-        fixture.create_fork(fork.repo_name, 'test-repo-fork-fork-1')
+        fixture.create_fork(fork.repo_name, u'test-repo-fork-fork-1')
         Session().commit()
 
         RepoModel().delete(repo=repo, forks='delete')
         Session().commit()
 
-        self.assertEqual(None, Repository.get_by_repo_name(repo_name='test-repo-1'))
-        self.assertEqual(None, Repository.get_by_repo_name(repo_name='test-repo-fork-1'))
-        self.assertEqual(None, Repository.get_by_repo_name(repo_name='test-repo-fork-fork-1'))
+        assert None == Repository.get_by_repo_name(repo_name=u'test-repo-1')
+        assert None == Repository.get_by_repo_name(repo_name=u'test-repo-fork-1')
+        assert None == Repository.get_by_repo_name(repo_name=u'test-repo-fork-fork-1')
 
     def test_remove_repo_detach_forks(self):
-        repo = fixture.create_repo(name='test-repo-1')
+        repo = fixture.create_repo(name=u'test-repo-1')
         Session().commit()
 
-        fork = fixture.create_fork(repo.repo_name, 'test-repo-fork-1')
+        fork = fixture.create_fork(repo.repo_name, u'test-repo-fork-1')
         Session().commit()
 
         #fork of fork
-        fixture.create_fork(fork.repo_name, 'test-repo-fork-fork-1')
+        fixture.create_fork(fork.repo_name, u'test-repo-fork-fork-1')
         Session().commit()
 
         RepoModel().delete(repo=repo, forks='detach')
         Session().commit()
 
         try:
-            self.assertEqual(None, Repository.get_by_repo_name(repo_name='test-repo-1'))
-            self.assertNotEqual(None, Repository.get_by_repo_name(repo_name='test-repo-fork-1'))
-            self.assertNotEqual(None, Repository.get_by_repo_name(repo_name='test-repo-fork-fork-1'))
+            assert None == Repository.get_by_repo_name(repo_name=u'test-repo-1')
+            assert None != Repository.get_by_repo_name(repo_name=u'test-repo-fork-1')
+            assert None != Repository.get_by_repo_name(repo_name=u'test-repo-fork-fork-1')
         finally:
-            RepoModel().delete(repo='test-repo-fork-fork-1')
-            RepoModel().delete(repo='test-repo-fork-1')
+            RepoModel().delete(repo=u'test-repo-fork-fork-1')
+            RepoModel().delete(repo=u'test-repo-fork-1')
             Session().commit()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/tests/models/test_settings.py	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,43 @@
+from kallithea.model.meta import Session
+from kallithea.model.db import Setting
+
+
+name = 'spam-setting-name'
+
+def test_passing_list_setting_value_results_in_string_valued_setting():
+    assert Setting.get_by_name(name) is None
+    setting = Setting.create_or_update(name, ['spam', 'eggs'])
+    Session().flush() # must flush so we can delete it below
+    try:
+        assert Setting.get_by_name(name) is not None
+        # Quirk: list value is stringified.
+        assert Setting.get_by_name(name).app_settings_value \
+               == "['spam', 'eggs']"
+        assert Setting.get_by_name(name).app_settings_type == 'unicode'
+    finally:
+        Session().delete(setting)
+
+def test_list_valued_setting_creation_requires_manual_value_formatting():
+    assert Setting.get_by_name(name) is None
+    # Quirk: need manual formatting of list setting value.
+    setting = Setting.create_or_update(name, 'spam,eggs', type='list')
+    Session().flush() # must flush so we can delete it below
+    try:
+        assert setting.app_settings_value == ['spam', 'eggs']
+    finally:
+        Session().delete(setting)
+
+def test_list_valued_setting_update():
+    assert Setting.get_by_name(name) is None
+    setting = Setting.create_or_update(name, 'spam', type='list')
+    Session().flush() # must flush so we can delete it below
+    try:
+        assert setting.app_settings_value == [u'spam']
+        # Assign back setting value.
+        setting.app_settings_value = setting.app_settings_value
+        # Quirk: value is stringified on write and listified on read.
+        assert setting.app_settings_value == ["[u'spam']"]
+        setting.app_settings_value = setting.app_settings_value
+        assert setting.app_settings_value == ["[u\"[u'spam']\"]"]
+    finally:
+        Session().delete(setting)
--- a/kallithea/tests/models/test_user_group_permissions_on_repo_groups.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/models/test_user_group_permissions_on_repo_groups.py	Fri Nov 18 01:11:13 2016 +0100
@@ -17,7 +17,7 @@
 _get_group_perms = None
 
 
-def permissions_setup_func(group_name='g0', perm='group.read', recursive='all'):
+def permissions_setup_func(group_name=u'g0', perm='group.read', recursive='all'):
     """
     Resets all permissions to perm attribute
     """
@@ -44,7 +44,7 @@
     Session().commit()
     test_u2_id = test_u2.user_id
 
-    gr1 = fixture.create_user_group('perms_group_1')
+    gr1 = fixture.create_user_group(u'perms_group_1')
     Session().commit()
     test_u2_gr_id = gr1.users_group_id
     UserGroupModel().add_user_to_group(gr1, user=test_u2_id)
@@ -58,45 +58,45 @@
 
 def teardown_module():
     _destroy_project_tree(test_u2_id)
-    fixture.destroy_user_group('perms_group_1')
+    fixture.destroy_user_group(u'perms_group_1')
 
 
 def test_user_permissions_on_group_without_recursive_mode():
     # set permission to g0 non-recursive mode
     recursive = 'none'
-    group = 'g0'
+    group = u'g0'
     permissions_setup_func(group, 'group.write', recursive=recursive)
 
     items = [x for x in _get_repo_perms(group, recursive)]
     expected = 0
     assert len(items) == expected, ' %s != %s' % (len(items), expected)
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'repository.read'
+        check_tree_perms(name, perm, group, 'repository.read')
 
     items = [x for x in _get_group_perms(group, recursive)]
     expected = 1
     assert len(items) == expected, ' %s != %s' % (len(items), expected)
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'group.write'
+        check_tree_perms(name, perm, group, 'group.write')
 
 
 def test_user_permissions_on_group_without_recursive_mode_subgroup():
     # set permission to g0 non-recursive mode
     recursive = 'none'
-    group = 'g0/g0_1'
+    group = u'g0/g0_1'
     permissions_setup_func(group, 'group.write', recursive=recursive)
 
     items = [x for x in _get_repo_perms(group, recursive)]
     expected = 0
     assert len(items) == expected, ' %s != %s' % (len(items), expected)
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'repository.read'
+        check_tree_perms(name, perm, group, 'repository.read')
 
     items = [x for x in _get_group_perms(group, recursive)]
     expected = 1
     assert len(items) == expected, ' %s != %s' % (len(items), expected)
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'group.write'
+        check_tree_perms(name, perm, group, 'group.write')
 
 
 def test_user_permissions_on_group_with_recursive_mode():
@@ -104,7 +104,7 @@
     # set permission to g0 recursive mode, all children including
     # other repos and groups should have this permission now set !
     recursive = 'all'
-    group = 'g0'
+    group = u'g0'
     permissions_setup_func(group, 'group.write', recursive=recursive)
 
     repo_items = [x for x in _get_repo_perms(group, recursive)]
@@ -112,16 +112,16 @@
     _check_expected_count(items, repo_items, expected_count(group, True))
 
     for name, perm in repo_items:
-        yield check_tree_perms, name, perm, group, 'repository.write'
+        check_tree_perms(name, perm, group, 'repository.write')
 
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'group.write'
+        check_tree_perms(name, perm, group, 'group.write')
 
 
 def test_user_permissions_on_group_with_recursive_mode_inner_group():
     ## set permission to g0_3 group to none
     recursive = 'all'
-    group = 'g0/g0_3'
+    group = u'g0/g0_3'
     permissions_setup_func(group, 'group.none', recursive=recursive)
 
     repo_items = [x for x in _get_repo_perms(group, recursive)]
@@ -129,16 +129,16 @@
     _check_expected_count(items, repo_items, expected_count(group, True))
 
     for name, perm in repo_items:
-        yield check_tree_perms, name, perm, group, 'repository.none'
+        check_tree_perms(name, perm, group, 'repository.none')
 
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'group.none'
+        check_tree_perms(name, perm, group, 'group.none')
 
 
 def test_user_permissions_on_group_with_recursive_mode_deepest():
     ## set permission to g0_3 group to none
     recursive = 'all'
-    group = 'g0/g0_1/g0_1_1'
+    group = u'g0/g0_1/g0_1_1'
     permissions_setup_func(group, 'group.write', recursive=recursive)
 
     repo_items = [x for x in _get_repo_perms(group, recursive)]
@@ -146,16 +146,16 @@
     _check_expected_count(items, repo_items, expected_count(group, True))
 
     for name, perm in repo_items:
-        yield check_tree_perms, name, perm, group, 'repository.write'
+        check_tree_perms(name, perm, group, 'repository.write')
 
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'group.write'
+        check_tree_perms(name, perm, group, 'group.write')
 
 
 def test_user_permissions_on_group_with_recursive_mode_only_with_repos():
     ## set permission to g0_3 group to none
     recursive = 'all'
-    group = 'g0/g0_2'
+    group = u'g0/g0_2'
     permissions_setup_func(group, 'group.admin', recursive=recursive)
 
     repo_items = [x for x in _get_repo_perms(group, recursive)]
@@ -163,16 +163,16 @@
     _check_expected_count(items, repo_items, expected_count(group, True))
 
     for name, perm in repo_items:
-        yield check_tree_perms, name, perm, group, 'repository.admin'
+        check_tree_perms(name, perm, group, 'repository.admin')
 
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'group.admin'
+        check_tree_perms(name, perm, group, 'group.admin')
 
 
 def test_user_permissions_on_group_with_recursive_mode_on_repos():
     # set permission to g0/g0_1 with recursive mode on just repositories
     recursive = 'repos'
-    group = 'g0/g0_1'
+    group = u'g0/g0_1'
     perm = 'group.write'
     permissions_setup_func(group, perm, recursive=recursive)
 
@@ -181,7 +181,7 @@
     _check_expected_count(items, repo_items, expected_count(group, True))
 
     for name, perm in repo_items:
-        yield check_tree_perms, name, perm, group, 'repository.write'
+        check_tree_perms(name, perm, group, 'repository.write')
 
     for name, perm in items:
         # permission is set with repos only mode, but we also change the permission
@@ -190,13 +190,13 @@
         old_perm = 'group.read'
         if name == group:
             old_perm = perm
-        yield check_tree_perms, name, perm, group, old_perm
+        check_tree_perms(name, perm, group, old_perm)
 
 
 def test_user_permissions_on_group_with_recursive_mode_on_repo_groups():
     # set permission to g0/g0_1 with recursive mode on just repository groups
     recursive = 'groups'
-    group = 'g0/g0_1'
+    group = u'g0/g0_1'
     perm = 'group.none'
     permissions_setup_func(group, perm, recursive=recursive)
 
@@ -205,7 +205,7 @@
     _check_expected_count(items, repo_items, expected_count(group, True))
 
     for name, perm in repo_items:
-        yield check_tree_perms, name, perm, group, 'repository.read'
+        check_tree_perms(name, perm, group, 'repository.read')
 
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'group.none'
+        check_tree_perms(name, perm, group, 'group.none')
--- a/kallithea/tests/models/test_user_groups.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/models/test_user_groups.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,6 +1,6 @@
-from kallithea.model.db import User
+from kallithea.model.db import User, UserGroup
 
-from kallithea.tests import BaseTestCase, parameterized, TEST_USER_REGULAR_LOGIN
+from kallithea.tests.base import *
 from kallithea.tests.fixture import Fixture
 
 from kallithea.model.user_group import UserGroupModel
@@ -10,27 +10,27 @@
 fixture = Fixture()
 
 
-class TestUserGroups(BaseTestCase):
+class TestUserGroups(TestController):
 
-    def tearDown(self):
+    def teardown_method(self, method):
         # delete all groups
-        for gr in UserGroupModel.get_all():
+        for gr in UserGroup.query():
             fixture.destroy_user_group(gr)
         Session().commit()
 
-    @parameterized.expand([
+    @parametrize('pre_existing,regular_should_be,external_should_be,groups,expected', [
         ([], [], [], [], []),
-        ([], ['regular'], [], [], ['regular']),  # no changes of regular
-        (['some_other'], [], [], ['some_other'], []),   # not added to regular group
-        ([], ['regular'], ['container'], ['container'], ['regular', 'container']),
-        ([], ['regular'], [], ['container', 'container2'], ['regular', 'container', 'container2']),
-        ([], ['regular'], ['other'], [], ['regular']),  # remove not used
-        (['some_other'], ['regular'], ['other', 'container'], ['container', 'container2'], ['regular', 'container', 'container2']),
+        ([], [u'regular'], [], [], [u'regular']),  # no changes of regular
+        ([u'some_other'], [], [], [u'some_other'], []),   # not added to regular group
+        ([], [u'regular'], [u'container'], [u'container'], [u'regular', u'container']),
+        ([], [u'regular'], [], [u'container', u'container2'], [u'regular', u'container', u'container2']),
+        ([], [u'regular'], [u'other'], [], [u'regular']),  # remove not used
+        ([u'some_other'], [u'regular'], [u'other', u'container'], [u'container', u'container2'], [u'regular', u'container', u'container2']),
     ])
     def test_enforce_groups(self, pre_existing, regular_should_be,
                             external_should_be, groups, expected):
         # delete all groups
-        for gr in UserGroupModel.get_all():
+        for gr in UserGroup.query():
             fixture.destroy_user_group(gr)
         Session().commit()
 
@@ -58,4 +58,4 @@
 
         user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
         in_groups = user.group_member
-        self.assertEqual(expected, [x.users_group.users_group_name for x in in_groups])
+        assert expected == [x.users_group.users_group_name for x in in_groups]
--- a/kallithea/tests/models/test_user_permissions_on_repo_groups.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/models/test_user_permissions_on_repo_groups.py	Fri Nov 18 01:11:13 2016 +0100
@@ -13,7 +13,7 @@
 _get_group_perms = None
 
 
-def permissions_setup_func(group_name='g0', perm='group.read', recursive='all',
+def permissions_setup_func(group_name=u'g0', perm='group.read', recursive='all',
                            user_id=None):
     """
     Resets all permissions to perm attribute
@@ -58,39 +58,39 @@
 def test_user_permissions_on_group_without_recursive_mode():
     # set permission to g0 non-recursive mode
     recursive = 'none'
-    group = 'g0'
+    group = u'g0'
     permissions_setup_func(group, 'group.write', recursive=recursive)
 
     items = [x for x in _get_repo_perms(group, recursive)]
     expected = 0
     assert len(items) == expected, ' %s != %s' % (len(items), expected)
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'repository.read'
+        check_tree_perms(name, perm, group, 'repository.read')
 
     items = [x for x in _get_group_perms(group, recursive)]
     expected = 1
     assert len(items) == expected, ' %s != %s' % (len(items), expected)
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'group.write'
+        check_tree_perms(name, perm, group, 'group.write')
 
 
 def test_user_permissions_on_group_without_recursive_mode_subgroup():
     # set permission to g0 non-recursive mode
     recursive = 'none'
-    group = 'g0/g0_1'
+    group = u'g0/g0_1'
     permissions_setup_func(group, 'group.write', recursive=recursive)
 
     items = [x for x in _get_repo_perms(group, recursive)]
     expected = 0
     assert len(items) == expected, ' %s != %s' % (len(items), expected)
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'repository.read'
+        check_tree_perms(name, perm, group, 'repository.read')
 
     items = [x for x in _get_group_perms(group, recursive)]
     expected = 1
     assert len(items) == expected, ' %s != %s' % (len(items), expected)
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'group.write'
+        check_tree_perms(name, perm, group, 'group.write')
 
 
 def test_user_permissions_on_group_with_recursive_mode():
@@ -98,7 +98,7 @@
     # set permission to g0 recursive mode, all children including
     # other repos and groups should have this permission now set !
     recursive = 'all'
-    group = 'g0'
+    group = u'g0'
     permissions_setup_func(group, 'group.write', recursive=recursive)
 
     repo_items = [x for x in _get_repo_perms(group, recursive)]
@@ -106,10 +106,10 @@
     _check_expected_count(items, repo_items, expected_count(group, True))
 
     for name, perm in repo_items:
-        yield check_tree_perms, name, perm, group, 'repository.write'
+        check_tree_perms(name, perm, group, 'repository.write')
 
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'group.write'
+        check_tree_perms(name, perm, group, 'group.write')
 
 
 def test_user_permissions_on_group_with_recursive_mode_for_default_user():
@@ -117,7 +117,7 @@
     # set permission to g0 recursive mode, all children including
     # other repos and groups should have this permission now set !
     recursive = 'all'
-    group = 'g0'
+    group = u'g0'
     default_user_id = User.get_default_user().user_id
     permissions_setup_func(group, 'group.write', recursive=recursive,
                            user_id=default_user_id)
@@ -133,16 +133,16 @@
     _check_expected_count(items, repo_items, expected_count(group, True))
 
     for name, perm in repo_items:
-        yield check_tree_perms, name, perm, group, 'repository.write'
+        check_tree_perms(name, perm, group, 'repository.write')
 
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'group.write'
+        check_tree_perms(name, perm, group, 'group.write')
 
 
 def test_user_permissions_on_group_with_recursive_mode_inner_group():
     ## set permission to g0_3 group to none
     recursive = 'all'
-    group = 'g0/g0_3'
+    group = u'g0/g0_3'
     permissions_setup_func(group, 'group.none', recursive=recursive)
 
     repo_items = [x for x in _get_repo_perms(group, recursive)]
@@ -150,16 +150,16 @@
     _check_expected_count(items, repo_items, expected_count(group, True))
 
     for name, perm in repo_items:
-        yield check_tree_perms, name, perm, group, 'repository.none'
+        check_tree_perms(name, perm, group, 'repository.none')
 
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'group.none'
+        check_tree_perms(name, perm, group, 'group.none')
 
 
 def test_user_permissions_on_group_with_recursive_mode_deepest():
     ## set permission to g0_3 group to none
     recursive = 'all'
-    group = 'g0/g0_1/g0_1_1'
+    group = u'g0/g0_1/g0_1_1'
     permissions_setup_func(group, 'group.write', recursive=recursive)
 
     repo_items = [x for x in _get_repo_perms(group, recursive)]
@@ -167,16 +167,16 @@
     _check_expected_count(items, repo_items, expected_count(group, True))
 
     for name, perm in repo_items:
-        yield check_tree_perms, name, perm, group, 'repository.write'
+        check_tree_perms(name, perm, group, 'repository.write')
 
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'group.write'
+        check_tree_perms(name, perm, group, 'group.write')
 
 
 def test_user_permissions_on_group_with_recursive_mode_only_with_repos():
     ## set permission to g0_3 group to none
     recursive = 'all'
-    group = 'g0/g0_2'
+    group = u'g0/g0_2'
     permissions_setup_func(group, 'group.admin', recursive=recursive)
 
     repo_items = [x for x in _get_repo_perms(group, recursive)]
@@ -184,17 +184,17 @@
     _check_expected_count(items, repo_items, expected_count(group, True))
 
     for name, perm in repo_items:
-        yield check_tree_perms, name, perm, group, 'repository.admin'
+        check_tree_perms(name, perm, group, 'repository.admin')
 
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'group.admin'
+        check_tree_perms(name, perm, group, 'group.admin')
 
 
 def test_user_permissions_on_group_with_recursive_repo_mode_for_default_user():
     # set permission to g0/g0_1 recursive repos only mode, all children including
     # other repos should have this permission now set, inner groups are excluded!
     recursive = 'repos'
-    group = 'g0/g0_1'
+    group = u'g0/g0_1'
     perm = 'group.none'
     default_user_id = User.get_default_user().user_id
 
@@ -212,7 +212,7 @@
     _check_expected_count(items, repo_items, expected_count(group, True))
 
     for name, perm in repo_items:
-        yield check_tree_perms, name, perm, group, 'repository.none'
+        check_tree_perms(name, perm, group, 'repository.none')
 
     for name, perm in items:
         # permission is set with repos only mode, but we also change the permission
@@ -221,13 +221,13 @@
         old_perm = 'group.read'
         if name == group:
             old_perm = perm
-        yield check_tree_perms, name, perm, group, old_perm
+        check_tree_perms(name, perm, group, old_perm)
 
 
 def test_user_permissions_on_group_with_recursive_repo_mode_inner_group():
     ## set permission to g0_3 group to none, with recursive repos only
     recursive = 'repos'
-    group = 'g0/g0_3'
+    group = u'g0/g0_3'
     perm = 'group.none'
     permissions_setup_func(group, perm, recursive=recursive)
 
@@ -236,7 +236,7 @@
     _check_expected_count(items, repo_items, expected_count(group, True))
 
     for name, perm in repo_items:
-        yield check_tree_perms, name, perm, group, 'repository.none'
+        check_tree_perms(name, perm, group, 'repository.none')
 
     for name, perm in items:
         # permission is set with repos only mode, but we also change the permission
@@ -245,7 +245,7 @@
         old_perm = 'group.read'
         if name == group:
             old_perm = perm
-        yield check_tree_perms, name, perm, group, old_perm
+        check_tree_perms(name, perm, group, old_perm)
 
 
 def test_user_permissions_on_group_with_recursive_group_mode_for_default_user():
@@ -253,7 +253,7 @@
     # other groups should have this permission now set. repositories should
     # remain intact as we use groups only mode !
     recursive = 'groups'
-    group = 'g0/g0_1'
+    group = u'g0/g0_1'
     default_user_id = User.get_default_user().user_id
     permissions_setup_func(group, 'group.write', recursive=recursive,
                            user_id=default_user_id)
@@ -269,16 +269,16 @@
     _check_expected_count(items, repo_items, expected_count(group, True))
 
     for name, perm in repo_items:
-        yield check_tree_perms, name, perm, group, 'repository.read'
+        check_tree_perms(name, perm, group, 'repository.read')
 
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'group.write'
+        check_tree_perms(name, perm, group, 'group.write')
 
 
 def test_user_permissions_on_group_with_recursive_group_mode_inner_group():
     ## set permission to g0_3 group to none, with recursive mode for groups only
     recursive = 'groups'
-    group = 'g0/g0_3'
+    group = u'g0/g0_3'
     permissions_setup_func(group, 'group.none', recursive=recursive)
 
     repo_items = [x for x in _get_repo_perms(group, recursive)]
@@ -286,7 +286,7 @@
     _check_expected_count(items, repo_items, expected_count(group, True))
 
     for name, perm in repo_items:
-        yield check_tree_perms, name, perm, group, 'repository.read'
+        check_tree_perms(name, perm, group, 'repository.read')
 
     for name, perm in items:
-        yield check_tree_perms, name, perm, group, 'group.none'
+        check_tree_perms(name, perm, group, 'group.none')
--- a/kallithea/tests/models/test_users.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/models/test_users.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,6 +1,7 @@
-from kallithea.tests import *
+import pytest
+from kallithea.tests.base import *
 
-from kallithea.model.db import User, UserGroup, UserGroupMember, UserEmailMap,\
+from kallithea.model.db import User, UserGroup, UserGroupMember, UserEmailMap, \
     Permission
 from kallithea.model.user import UserModel
 
@@ -11,12 +12,13 @@
 fixture = Fixture()
 
 
-class TestUser(BaseTestCase):
-    def __init__(self, methodName='runTest'):
+class TestUser(TestController):
+
+    @classmethod
+    def setup_class(cls):
         Session.remove()
-        super(TestUser, self).__init__(methodName=methodName)
 
-    def tearDown(self):
+    def teardown_method(self, method):
         Session.remove()
 
     def test_create_and_remove(self):
@@ -25,36 +27,37 @@
                                            email=u'u232@example.com',
                                            firstname=u'u1', lastname=u'u1')
         Session().commit()
-        self.assertEqual(User.get_by_username(u'test_user'), usr)
+        assert User.get_by_username(u'test_user') == usr
+        assert User.get_by_username(u'test_USER', case_insensitive=True) == usr
+        assert User.get_by_username(u'test_USER', case_insensitive=False) == None
 
         # make user group
-        user_group = fixture.create_user_group('some_example_group')
+        user_group = fixture.create_user_group(u'some_example_group')
         Session().commit()
 
         UserGroupModel().add_user_to_group(user_group, usr)
         Session().commit()
 
-        self.assertEqual(UserGroup.get(user_group.users_group_id), user_group)
-        self.assertEqual(UserGroupMember.query().count(), 1)
+        assert UserGroup.get(user_group.users_group_id) == user_group
+        assert UserGroupMember.query().count() == 1
         UserModel().delete(usr.user_id)
         Session().commit()
 
-        self.assertEqual(UserGroupMember.query().all(), [])
+        assert UserGroupMember.query().all() == []
 
-    def test_additonal_email_as_main(self):
+    def test_additional_email_as_main(self):
         usr = UserModel().create_or_update(username=u'test_user',
                                            password=u'qweqwe',
                                      email=u'main_email@example.com',
                                      firstname=u'u1', lastname=u'u1')
         Session().commit()
 
-        def do():
+        with pytest.raises(AttributeError):
             m = UserEmailMap()
             m.email = u'main_email@example.com'
             m.user = usr
             Session().add(m)
             Session().commit()
-        self.assertRaises(AttributeError, do)
 
         UserModel().delete(usr.user_id)
         Session().commit()
@@ -72,32 +75,39 @@
         Session().add(m)
         Session().commit()
 
+        u = User.get_by_email(email='MAIN_email@example.com')
+        assert usr.user_id == u.user_id
+        assert usr.username == u.username
+
         u = User.get_by_email(email='main_email@example.com')
-        self.assertEqual(usr.user_id, u.user_id)
-        self.assertEqual(usr.username, u.username)
+        assert usr.user_id == u.user_id
+        assert usr.username == u.username
 
         u = User.get_by_email(email='main_email2@example.com')
-        self.assertEqual(usr.user_id, u.user_id)
-        self.assertEqual(usr.username, u.username)
+        assert usr.user_id == u.user_id
+        assert usr.username == u.username
         u = User.get_by_email(email='main_email3@example.com')
-        self.assertEqual(None, u)
+        assert None == u
+
+        u = User.get_by_email(email='main_e%ail@example.com')
+        assert None == u
+        u = User.get_by_email(email='main_emai_@example.com')
+        assert None == u
+
 
         UserModel().delete(usr.user_id)
         Session().commit()
 
 
-class TestUsers(BaseTestCase):
+class TestUsers(TestController):
 
-    def __init__(self, methodName='runTest'):
-        super(TestUsers, self).__init__(methodName=methodName)
-
-    def setUp(self):
+    def setup_method(self, method):
         self.u1 = UserModel().create_or_update(username=u'u1',
                                         password=u'qweqwe',
                                         email=u'u1@example.com',
                                         firstname=u'u1', lastname=u'u1')
 
-    def tearDown(self):
+    def teardown_method(self, method):
         perm = Permission.query().all()
         for p in perm:
             UserModel().revoke_perm(self.u1, p)
@@ -110,21 +120,21 @@
         perm = Permission.query().all()[0]
         UserModel().grant_perm(self.u1, perm)
         Session().commit()
-        self.assertEqual(UserModel().has_perm(self.u1, perm), True)
+        assert UserModel().has_perm(self.u1, perm) == True
 
     def test_has_perm(self):
         perm = Permission.query().all()
         for p in perm:
             has_p = UserModel().has_perm(self.u1, p)
-            self.assertEqual(False, has_p)
+            assert False == has_p
 
     def test_revoke_perm(self):
         perm = Permission.query().all()[0]
         UserModel().grant_perm(self.u1, perm)
         Session().commit()
-        self.assertEqual(UserModel().has_perm(self.u1, perm), True)
+        assert UserModel().has_perm(self.u1, perm) == True
 
         #revoke
         UserModel().revoke_perm(self.u1, perm)
         Session().commit()
-        self.assertEqual(UserModel().has_perm(self.u1, perm), False)
+        assert UserModel().has_perm(self.u1, perm) == False
--- a/kallithea/tests/other/manual_test_vcs_operations.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/other/manual_test_vcs_operations.py	Fri Nov 18 01:11:13 2016 +0100
@@ -19,7 +19,7 @@
 
 Run it in two terminals::
  paster serve kallithea/tests/test.ini
- KALLITHEA_WHOOSH_TEST_DISABLE=1 KALLITHEA_NO_TMP_PATH=1 nosetests kallithea/tests/other/manual_test_vcs_operations.py
+ KALLITHEA_WHOOSH_TEST_DISABLE=1 KALLITHEA_NO_TMP_PATH=1 py.test kallithea/tests/other/manual_test_vcs_operations.py
 
 You must have git > 1.8.1 for tests to work fine
 
@@ -32,15 +32,16 @@
 
 """
 
+import os
 import re
 import tempfile
 import time
-from os.path import join as jn
 
 from tempfile import _RandomNameSequence
 from subprocess import Popen, PIPE
 
-from kallithea.tests import *
+from kallithea.tests.base import *
+from kallithea.tests.fixture import Fixture
 from kallithea.model.db import User, Repository, UserIpMap, CacheInvalidation
 from kallithea.model.meta import Session
 from kallithea.model.repo import RepoModel
@@ -49,13 +50,15 @@
 DEBUG = True
 HOST = '127.0.0.1:4999'  # test host
 
+fixture = Fixture()
+
 
 class Command(object):
 
     def __init__(self, cwd):
         self.cwd = cwd
 
-    def execute(self, cmd, *args):
+    def execute(self, cmd, *args, **environ):
         """
         Runs command on the system with given ``args``.
         """
@@ -63,11 +66,17 @@
         command = cmd + ' ' + ' '.join(args)
         if DEBUG:
             print '*** CMD %s ***' % command
-        p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE, cwd=self.cwd)
+        testenv = dict(os.environ)
+        testenv['LANG'] = 'en_US.UTF-8'
+        testenv['LANGUAGE'] = 'en_US:en'
+        testenv.update(environ)
+        p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE, cwd=self.cwd, env=testenv)
         stdout, stderr = p.communicate()
         if DEBUG:
-            print 'stdout:', repr(stdout)
-            print 'stderr:', repr(stderr)
+            if stdout:
+                print 'stdout:', repr(stdout)
+            if stderr:
+                print 'stderr:', repr(stderr)
         return stdout, stderr
 
 
@@ -103,25 +112,30 @@
     :param DEST:
     """
     # commit some stuff into this repo
-    cwd = path = jn(DEST)
-    #added_file = jn(path, '%ssetupążźć.py' % _RandomNameSequence().next())
-    added_file = jn(path, '%ssetup.py' % _RandomNameSequence().next())
+    cwd = path = os.path.join(DEST)
+    #added_file = os.path.join(path, '%ssetupążźć.py' % _RandomNameSequence().next())
+    added_file = os.path.join(path, '%ssetup.py' % _RandomNameSequence().next())
     Command(cwd).execute('touch %s' % added_file)
     Command(cwd).execute('%s add %s' % (vcs, added_file))
 
+    email = 'me@example.com'
+    if os.name == 'nt':
+        author_str = 'User <%s>' % email
+    else:
+        author_str = 'User ǝɯɐᴎ <%s>' % email
     for i in xrange(kwargs.get('files_no', 3)):
-        cmd = """echo 'added_line%s' >> %s""" % (i, added_file)
+        cmd = """echo "added_line%s" >> %s""" % (i, added_file)
         Command(cwd).execute(cmd)
-        author_str = 'User ǝɯɐᴎ <me@example.com>'
         if vcs == 'hg':
-            cmd = """hg commit -m 'commited new %s' -u '%s' %s """ % (
+            cmd = """hg commit -m "committed new %s" -u "%s" "%s" """ % (
                 i, author_str, added_file
             )
         elif vcs == 'git':
-            cmd = """EMAIL="me@example.com" git commit -m 'commited new %s' --author '%s' %s """ % (
+            cmd = """git commit -m "committed new %s" --author "%s" "%s" """ % (
                 i, author_str, added_file
             )
-        Command(cwd).execute(cmd)
+        # git commit needs EMAIL on some machines
+        Command(cwd).execute(cmd, EMAIL=email)
 
     # PUSH it back
     _REPO = None
@@ -146,7 +160,6 @@
 def set_anonymous_access(enable=True):
     user = User.get_by_username(User.DEFAULT_USER)
     user.active = enable
-    Session().add(user)
     Session().commit()
     print '\tanonymous access is now:', enable
     if enable != User.get_by_username(User.DEFAULT_USER).active:
@@ -166,29 +179,27 @@
     assert 'master -> master' in stderr
 
 
-class TestVCSOperations(BaseTestCase):
+class TestVCSOperations(TestController):
 
     @classmethod
     def setup_class(cls):
         #DISABLE ANONYMOUS ACCESS
         set_anonymous_access(False)
 
-    def setUp(self):
+    def setup_method(self, method):
         r = Repository.get_by_repo_name(GIT_REPO)
         Repository.unlock(r)
         r.enable_locking = False
-        Session().add(r)
         Session().commit()
 
         r = Repository.get_by_repo_name(HG_REPO)
         Repository.unlock(r)
         r.enable_locking = False
-        Session().add(r)
         Session().commit()
 
     def test_clone_hg_repo_by_admin(self):
         clone_url = _construct_url(HG_REPO)
-        stdout, stderr = Command('/tmp').execute('hg clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('hg clone', clone_url)
 
         assert 'requesting all changes' in stdout
         assert 'adding changesets' in stdout
@@ -199,47 +210,50 @@
 
     def test_clone_git_repo_by_admin(self):
         clone_url = _construct_url(GIT_REPO)
-        stdout, stderr = Command('/tmp').execute('git clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('git clone', clone_url)
 
         assert 'Cloning into' in stdout + stderr
         assert stderr == '' or stdout == ''
 
     def test_clone_wrong_credentials_hg(self):
         clone_url = _construct_url(HG_REPO, passwd='bad!')
-        stdout, stderr = Command('/tmp').execute('hg clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('hg clone', clone_url)
         assert 'abort: authorization failed' in stderr
 
     def test_clone_wrong_credentials_git(self):
         clone_url = _construct_url(GIT_REPO, passwd='bad!')
-        stdout, stderr = Command('/tmp').execute('git clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('git clone', clone_url)
         assert 'fatal: Authentication failed' in stderr
 
     def test_clone_git_dir_as_hg(self):
         clone_url = _construct_url(GIT_REPO)
-        stdout, stderr = Command('/tmp').execute('hg clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('hg clone', clone_url)
         assert 'HTTP Error 404: Not Found' in stderr
 
     def test_clone_hg_repo_as_git(self):
         clone_url = _construct_url(HG_REPO)
-        stdout, stderr = Command('/tmp').execute('git clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('git clone', clone_url)
         assert 'not found' in stderr
 
     def test_clone_non_existing_path_hg(self):
         clone_url = _construct_url('trololo')
-        stdout, stderr = Command('/tmp').execute('hg clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('hg clone', clone_url)
         assert 'HTTP Error 404: Not Found' in stderr
 
     def test_clone_non_existing_path_git(self):
         clone_url = _construct_url('trololo')
-        stdout, stderr = Command('/tmp').execute('git clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('git clone', clone_url)
         assert 'not found' in stderr
 
     def test_push_new_file_hg(self):
         DEST = _get_tmp_dir()
         clone_url = _construct_url(HG_REPO, dest=DEST)
-        stdout, stderr = Command('/tmp').execute('hg clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('hg clone', clone_url)
 
-        stdout, stderr = _add_files_and_push('hg', DEST)
+        fork_name = '%s_fork%s' % (HG_REPO, _RandomNameSequence().next())
+        fixture.create_fork(HG_REPO, fork_name)
+        clone_url = _construct_url(fork_name).split()[0]
+        stdout, stderr = _add_files_and_push('hg', DEST, clone_url=clone_url)
 
         assert 'pushing to' in stdout
         assert 'Repository size' in stdout
@@ -248,12 +262,14 @@
     def test_push_new_file_git(self):
         DEST = _get_tmp_dir()
         clone_url = _construct_url(GIT_REPO, dest=DEST)
-        stdout, stderr = Command('/tmp').execute('git clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('git clone', clone_url)
 
         # commit some stuff into this repo
-        stdout, stderr = _add_files_and_push('git', DEST)
-
-        print [(x.repo_full_path,x.repo_path) for x in Repository.get_all()]
+        fork_name = '%s_fork%s' % (GIT_REPO, _RandomNameSequence().next())
+        fixture.create_fork(GIT_REPO, fork_name)
+        clone_url = _construct_url(fork_name).split()[0]
+        stdout, stderr = _add_files_and_push('git', DEST, clone_url=clone_url)
+        print [(x.repo_full_path,x.repo_path) for x in Repository.query()] # TODO: what is this for
         _check_proper_git_push(stdout, stderr)
 
     def test_push_invalidates_cache_hg(self):
@@ -261,48 +277,53 @@
                                                ==HG_REPO).scalar()
         if not key:
             key = CacheInvalidation(HG_REPO, HG_REPO)
+            Session().add(key)
 
         key.cache_active = True
-        Session().add(key)
         Session().commit()
 
         DEST = _get_tmp_dir()
         clone_url = _construct_url(HG_REPO, dest=DEST)
-        stdout, stderr = Command('/tmp').execute('hg clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('hg clone', clone_url)
 
-        stdout, stderr = _add_files_and_push('hg', DEST, files_no=1)
+        fork_name = '%s_fork%s' % (HG_REPO, _RandomNameSequence().next())
+        fixture.create_fork(HG_REPO, fork_name)
+        clone_url = _construct_url(fork_name).split()[0]
+        stdout, stderr = _add_files_and_push('hg', DEST, files_no=1, clone_url=clone_url)
 
         key = CacheInvalidation.query().filter(CacheInvalidation.cache_key
-                                               ==HG_REPO).one()
-        self.assertEqual(key.cache_active, False)
+                                               ==fork_name).all()
+        assert key == []
 
     def test_push_invalidates_cache_git(self):
         key = CacheInvalidation.query().filter(CacheInvalidation.cache_key
                                                ==GIT_REPO).scalar()
         if not key:
             key = CacheInvalidation(GIT_REPO, GIT_REPO)
+            Session().add(key)
 
         key.cache_active = True
-        Session().add(key)
         Session().commit()
 
         DEST = _get_tmp_dir()
         clone_url = _construct_url(GIT_REPO, dest=DEST)
-        stdout, stderr = Command('/tmp').execute('git clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('git clone', clone_url)
 
         # commit some stuff into this repo
-        stdout, stderr = _add_files_and_push('git', DEST, files_no=1)
+        fork_name = '%s_fork%s' % (GIT_REPO, _RandomNameSequence().next())
+        fixture.create_fork(GIT_REPO, fork_name)
+        clone_url = _construct_url(fork_name).split()[0]
+        stdout, stderr = _add_files_and_push('git', DEST, files_no=1, clone_url=clone_url)
         _check_proper_git_push(stdout, stderr)
 
         key = CacheInvalidation.query().filter(CacheInvalidation.cache_key
-                                               ==GIT_REPO).one()
-        print CacheInvalidation.get_all()
-        self.assertEqual(key.cache_active, False)
+                                               ==fork_name).all()
+        assert key == []
 
     def test_push_wrong_credentials_hg(self):
         DEST = _get_tmp_dir()
         clone_url = _construct_url(HG_REPO, dest=DEST)
-        stdout, stderr = Command('/tmp').execute('hg clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('hg clone', clone_url)
 
         stdout, stderr = _add_files_and_push('hg', DEST, user='bad',
                                              passwd='name')
@@ -312,7 +333,7 @@
     def test_push_wrong_credentials_git(self):
         DEST = _get_tmp_dir()
         clone_url = _construct_url(GIT_REPO, dest=DEST)
-        stdout, stderr = Command('/tmp').execute('git clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('git clone', clone_url)
 
         stdout, stderr = _add_files_and_push('git', DEST, user='bad',
                                              passwd='name')
@@ -322,7 +343,7 @@
     def test_push_back_to_wrong_url_hg(self):
         DEST = _get_tmp_dir()
         clone_url = _construct_url(HG_REPO, dest=DEST)
-        stdout, stderr = Command('/tmp').execute('hg clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('hg clone', clone_url)
 
         stdout, stderr = _add_files_and_push('hg', DEST,
                                     clone_url='http://%s/tmp' % HOST)
@@ -332,7 +353,7 @@
     def test_push_back_to_wrong_url_git(self):
         DEST = _get_tmp_dir()
         clone_url = _construct_url(GIT_REPO, dest=DEST)
-        stdout, stderr = Command('/tmp').execute('git clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('git clone', clone_url)
 
         stdout, stderr = _add_files_and_push('git', DEST,
                                     clone_url='http://%s/tmp' % HOST)
@@ -343,11 +364,10 @@
         # enable locking
         r = Repository.get_by_repo_name(HG_REPO)
         r.enable_locking = True
-        Session().add(r)
         Session().commit()
         # clone
         clone_url = _construct_url(HG_REPO)
-        stdout, stderr = Command('/tmp').execute('hg clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('hg clone', clone_url)
 
         #check if lock was made
         r = Repository.get_by_repo_name(HG_REPO)
@@ -357,11 +377,10 @@
         # enable locking
         r = Repository.get_by_repo_name(GIT_REPO)
         r.enable_locking = True
-        Session().add(r)
         Session().commit()
         # clone
         clone_url = _construct_url(GIT_REPO)
-        stdout, stderr = Command('/tmp').execute('git clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('git clone', clone_url)
 
         #check if lock was made
         r = Repository.get_by_repo_name(GIT_REPO)
@@ -373,7 +392,7 @@
         Repository.lock(r, User.get_by_username(TEST_USER_ADMIN_LOGIN).user_id)
         #pull fails since repo is locked
         clone_url = _construct_url(HG_REPO)
-        stdout, stderr = Command('/tmp').execute('hg clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('hg clone', clone_url)
         msg = ("""abort: HTTP Error 423: Repository `%s` locked by user `%s`"""
                 % (HG_REPO, TEST_USER_ADMIN_LOGIN))
         assert msg in stderr
@@ -384,7 +403,7 @@
         Repository.lock(r, User.get_by_username(TEST_USER_ADMIN_LOGIN).user_id)
         #pull fails since repo is locked
         clone_url = _construct_url(GIT_REPO)
-        stdout, stderr = Command('/tmp').execute('git clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('git clone', clone_url)
         msg = ("""The requested URL returned error: 423""")
         assert msg in stderr
 
@@ -392,7 +411,7 @@
         #clone some temp
         DEST = _get_tmp_dir()
         clone_url = _construct_url(HG_REPO, dest=DEST)
-        stdout, stderr = Command('/tmp').execute('hg clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('hg clone', clone_url)
 
         #lock repo
         r = Repository.get_by_repo_name(HG_REPO)
@@ -414,7 +433,7 @@
         #clone some temp
         DEST = _get_tmp_dir()
         clone_url = _construct_url(GIT_REPO, dest=DEST)
-        stdout, stderr = Command('/tmp').execute('git clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('git clone', clone_url)
 
         #lock repo
         r = Repository.get_by_repo_name(GIT_REPO)
@@ -441,52 +460,54 @@
 
     def test_push_unlocks_repository_hg(self):
         # enable locking
-        r = Repository.get_by_repo_name(HG_REPO)
+        fork_name = '%s_fork%s' % (HG_REPO, _RandomNameSequence().next())
+        fixture.create_fork(HG_REPO, fork_name)
+        r = Repository.get_by_repo_name(fork_name)
         r.enable_locking = True
-        Session().add(r)
         Session().commit()
         #clone some temp
         DEST = _get_tmp_dir()
-        clone_url = _construct_url(HG_REPO, dest=DEST)
-        stdout, stderr = Command('/tmp').execute('hg clone', clone_url)
+        clone_url = _construct_url(fork_name, dest=DEST)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('hg clone', clone_url)
 
         #check for lock repo after clone
-        r = Repository.get_by_repo_name(HG_REPO)
+        r = Repository.get_by_repo_name(fork_name)
         uid = User.get_by_username(TEST_USER_ADMIN_LOGIN).user_id
         assert r.locked[0] == uid
 
         #push is ok and repo is now unlocked
-        stdout, stderr = _add_files_and_push('hg', DEST)
-        assert ('remote: Released lock on repo `%s`' % HG_REPO) in stdout
+        stdout, stderr = _add_files_and_push('hg', DEST, clone_url=clone_url.split()[0])
+        assert str('remote: Released lock on repo `%s`' % fork_name) in stdout
         #we need to cleanup the Session Here !
         Session.remove()
-        r = Repository.get_by_repo_name(HG_REPO)
+        r = Repository.get_by_repo_name(fork_name)
         assert r.locked == [None, None]
 
     #TODO: fix me ! somehow during tests hooks don't get called on Git
     def test_push_unlocks_repository_git(self):
         # enable locking
-        r = Repository.get_by_repo_name(GIT_REPO)
+        fork_name = '%s_fork%s' % (GIT_REPO, _RandomNameSequence().next())
+        fixture.create_fork(GIT_REPO, fork_name)
+        r = Repository.get_by_repo_name(fork_name)
         r.enable_locking = True
-        Session().add(r)
         Session().commit()
         #clone some temp
         DEST = _get_tmp_dir()
-        clone_url = _construct_url(GIT_REPO, dest=DEST)
-        stdout, stderr = Command('/tmp').execute('git clone', clone_url)
+        clone_url = _construct_url(fork_name, dest=DEST)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('git clone', clone_url)
 
         #check for lock repo after clone
-        r = Repository.get_by_repo_name(GIT_REPO)
+        r = Repository.get_by_repo_name(fork_name)
         assert r.locked[0] == User.get_by_username(TEST_USER_ADMIN_LOGIN).user_id
 
         #push is ok and repo is now unlocked
-        stdout, stderr = _add_files_and_push('git', DEST)
+        stdout, stderr = _add_files_and_push('git', DEST, clone_url=clone_url.split()[0])
         _check_proper_git_push(stdout, stderr)
 
-        #assert ('remote: Released lock on repo `%s`' % GIT_REPO) in stdout
+        assert ('remote: Released lock on repo `%s`' % fork_name) in stderr
         #we need to cleanup the Session Here !
         Session.remove()
-        r = Repository.get_by_repo_name(GIT_REPO)
+        r = Repository.get_by_repo_name(fork_name)
         assert r.locked == [None, None]
 
     def test_ip_restriction_hg(self):
@@ -495,17 +516,19 @@
             user_model.add_extra_ip(TEST_USER_ADMIN_LOGIN, '10.10.10.10/32')
             Session().commit()
             clone_url = _construct_url(HG_REPO)
-            stdout, stderr = Command('/tmp').execute('hg clone', clone_url)
+            stdout, stderr = Command(tempfile.gettempdir()).execute('hg clone', clone_url)
             assert 'abort: HTTP Error 403: Forbidden' in stderr
         finally:
             #release IP restrictions
-            for ip in UserIpMap.getAll():
+            for ip in UserIpMap.query():
                 UserIpMap.delete(ip.ip_id)
             Session().commit()
 
-        time.sleep(2)
+        # IP permissions are cached, need to invalidate this cache explicitly
+        invalidate_all_caches()
+
         clone_url = _construct_url(HG_REPO)
-        stdout, stderr = Command('/tmp').execute('hg clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('hg clone', clone_url)
 
         assert 'requesting all changes' in stdout
         assert 'adding changesets' in stdout
@@ -520,18 +543,20 @@
             user_model.add_extra_ip(TEST_USER_ADMIN_LOGIN, '10.10.10.10/32')
             Session().commit()
             clone_url = _construct_url(GIT_REPO)
-            stdout, stderr = Command('/tmp').execute('git clone', clone_url)
+            stdout, stderr = Command(tempfile.gettempdir()).execute('git clone', clone_url)
             # The message apparently changed in Git 1.8.3, so match it loosely.
             assert re.search(r'\b403\b', stderr)
         finally:
             #release IP restrictions
-            for ip in UserIpMap.getAll():
+            for ip in UserIpMap.query():
                 UserIpMap.delete(ip.ip_id)
             Session().commit()
 
-        time.sleep(2)
+        # IP permissions are cached, need to invalidate this cache explicitly
+        invalidate_all_caches()
+
         clone_url = _construct_url(GIT_REPO)
-        stdout, stderr = Command('/tmp').execute('git clone', clone_url)
+        stdout, stderr = Command(tempfile.gettempdir()).execute('git clone', clone_url)
 
         assert 'Cloning into' in stdout + stderr
         assert stderr == '' or stdout == ''
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/tests/other/test_auth_ldap.py	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,138 @@
+from kallithea.lib.auth_modules import auth_ldap, authenticate
+from kallithea.model.db import Setting, User
+from kallithea.model.meta import Session
+import uuid
+import pytest
+
+
+@pytest.fixture
+def arrange_ldap_auth(set_test_settings):
+    set_test_settings(
+        ('auth_plugins', 'kallithea.lib.auth_modules.auth_ldap', 'list'),
+        ('auth_ldap_enabled', True, 'bool'),
+        ('auth_ldap_attr_firstname', 'test_ldap_firstname'),
+        ('auth_ldap_attr_lastname', 'test_ldap_lastname'),
+        ('auth_ldap_attr_email', 'test_ldap_email'))
+
+
+class _AuthLdapMock():
+
+    def __init__(self, **kwargs):
+        pass
+
+    def authenticate_ldap(self, username, password):
+        return 'spam dn', dict(test_ldap_firstname=['spam ldap first name'],
+                               test_ldap_lastname=['spam ldap last name'],
+                               test_ldap_email=['spam ldap email'])
+
+
+def test_update_user_attributes_from_ldap(monkeypatch, create_test_user,
+                                          arrange_ldap_auth):
+    """Authenticate user with mocked LDAP, verify attributes are updated.
+    """
+
+    # Arrange test user.
+    uniqifier = uuid.uuid4()
+    username = 'test-user-{0}'.format(uniqifier)
+    assert User.get_by_username(username) is None
+    user_input = dict(username='test-user-{0}'.format(uniqifier),
+                      password='spam password',
+                      email='spam-email-{0}'.format(uniqifier),
+                      firstname='spam first name',
+                      lastname='spam last name',
+                      active=True,
+                      admin=False)
+    user = create_test_user(user_input)
+
+    # Arrange LDAP auth.
+    monkeypatch.setattr(auth_ldap, 'AuthLdap', _AuthLdapMock)
+
+    # Authenticate with LDAP.
+    user_data = authenticate(username, 'password')
+
+    # Verify that authenication succeeded and retrieved correct attributes
+    # from LDAP.
+    assert user_data is not None
+    assert user_data.get('firstname') == 'spam ldap first name'
+    assert user_data.get('lastname') == 'spam ldap last name'
+    assert user_data.get('email') == 'spam ldap email'
+
+    # Verify that authentication overwrote user attributes with the ones
+    # retrieved from LDAP.
+    assert user.firstname == 'spam ldap first name'
+    assert user.lastname == 'spam ldap last name'
+    assert user.email == 'spam ldap email'
+
+
+def test_init_user_attributes_from_ldap(monkeypatch, arrange_ldap_auth):
+    """Authenticate unknown user with mocked LDAP, verify user is created.
+    """
+
+    # Arrange test user.
+    uniqifier = uuid.uuid4()
+    username = 'test-user-{0}'.format(uniqifier)
+    assert User.get_by_username(username) is None
+
+    # Arrange LDAP auth.
+    monkeypatch.setattr(auth_ldap, 'AuthLdap', _AuthLdapMock)
+
+    # Authenticate with LDAP.
+    user_data = authenticate(username, 'password')
+
+    # Verify that authenication succeeded and retrieved correct attributes
+    # from LDAP.
+    assert user_data is not None
+    assert user_data.get('firstname') == 'spam ldap first name'
+    assert user_data.get('lastname') == 'spam ldap last name'
+    assert user_data.get('email') == 'spam ldap email'
+
+    # Verify that authentication created new user with attributes
+    # retrieved from LDAP.
+    new_user = User.get_by_username(username)
+    assert new_user is not None
+    assert new_user.firstname == 'spam ldap first name'
+    assert new_user.lastname == 'spam ldap last name'
+    assert new_user.email == 'spam ldap email'
+
+
+class _AuthLdapNoEmailMock():
+
+    def __init__(self, **kwargs):
+        pass
+
+    def authenticate_ldap(self, username, password):
+        return 'spam dn', dict(test_ldap_firstname=['spam ldap first name'],
+                               test_ldap_lastname=['spam ldap last name'],
+                               test_ldap_email=[''])
+
+
+def test_init_user_attributes_from_ldap_with_missing_email(monkeypatch,
+                                                           arrange_ldap_auth):
+    """Authenticate unknown user with mocked LDAP where email is missing.
+    """
+
+    # Arrange test user.
+    uniqifier = uuid.uuid4()
+    username = 'test-user-{0}'.format(uniqifier)
+    assert User.get_by_username(username) is None
+
+    # Arrange LDAP auth.
+    monkeypatch.setattr(auth_ldap, 'AuthLdap', _AuthLdapNoEmailMock)
+
+    # Authenticate with LDAP.
+    user_data = authenticate(username, 'password')
+
+    # Verify that authenication succeeded and retrieved correct attributes
+    # from LDAP, with empty email.
+    assert user_data is not None
+    assert user_data.get('firstname') == 'spam ldap first name'
+    assert user_data.get('lastname') == 'spam ldap last name'
+    assert user_data.get('email') == ''
+
+    # Verify that authentication created new user with attributes
+    # retrieved from LDAP, with email == None.
+    new_user = User.get_by_username(username)
+    assert new_user is not None
+    assert new_user.firstname == 'spam ldap first name'
+    assert new_user.lastname == 'spam ldap last name'
+    assert new_user.email is None
--- a/kallithea/tests/other/test_libs.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/other/test_libs.py	Fri Nov 18 01:11:13 2016 +0100
@@ -28,7 +28,7 @@
 import datetime
 import hashlib
 import mock
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.lib.utils2 import AttributeDict
 from kallithea.model.db import Repository
 
@@ -66,20 +66,39 @@
      '%s://example.com:8080' % proto),
 ]
 
+class FakeUrlGenerator(object):
 
-class TestLibs(BaseTestCase):
+    def __init__(self, current_url=None, default_route=None, **routes):
+        """Initialize using specified 'current' URL template,
+        default route template, and all other aguments describing known
+        routes (format: route=template)"""
+        self.current_url = current_url
+        self.default_route = default_route
+        self.routes = routes
 
-    @parameterized.expand(TEST_URLS)
+    def __call__(self, route_name, *args, **kwargs):
+        if route_name in self.routes:
+            return self.routes[route_name] % kwargs
+
+        return self.default_route % kwargs
+
+    def current(self, *args, **kwargs):
+        return self.current_url % kwargs
+
+class TestLibs(TestController):
+
+    @parametrize('test_url,expected,expected_creds', TEST_URLS)
     def test_uri_filter(self, test_url, expected, expected_creds):
         from kallithea.lib.utils2 import uri_filter
-        self.assertEqual(uri_filter(test_url), expected)
+        assert uri_filter(test_url) == expected
 
-    @parameterized.expand(TEST_URLS)
+    @parametrize('test_url,expected,expected_creds', TEST_URLS)
     def test_credentials_filter(self, test_url, expected, expected_creds):
         from kallithea.lib.utils2 import credentials_filter
-        self.assertEqual(credentials_filter(test_url), expected_creds)
+        assert credentials_filter(test_url) == expected_creds
 
-    @parameterized.expand([('t', True),
+    @parametrize('str_bool,expected', [
+                           ('t', True),
                            ('true', True),
                            ('y', True),
                            ('yes', True),
@@ -99,10 +118,10 @@
     ])
     def test_str2bool(self, str_bool, expected):
         from kallithea.lib.utils2 import str2bool
-        self.assertEqual(str2bool(str_bool), expected)
+        assert str2bool(str_bool) == expected
 
     def test_mention_extractor(self):
-        from kallithea.lib.utils2 import extract_mentioned_users
+        from kallithea.lib.utils2 import extract_mentioned_usernames
         sample = (
             "@first hi there @world here's my email username@example.com "
             "@lukaszb check @one_more22 it pls @ ttwelve @D[] @one@two@three "
@@ -111,12 +130,12 @@
             "user.dot  hej ! not-needed maril@example.com"
         )
 
-        s = sorted([
+        expected = set([
             '2one_more22', 'first', 'lukaszb', 'one', 'one_more22', 'UPPER', 'cAmEL', 'john',
-            'marian.user', 'marco-polo', 'marco_polo', 'world'], key=lambda k: k.lower())
-        self.assertEqual(s, extract_mentioned_users(sample))
+            'marian.user', 'marco-polo', 'marco_polo', 'world'])
+        assert expected == set(extract_mentioned_usernames(sample))
 
-    @parameterized.expand([
+    @parametrize('age_args,expected', [
         (dict(), u'just now'),
         (dict(seconds= -1), u'1 second ago'),
         (dict(seconds= -60 * 2), u'2 minutes ago'),
@@ -137,9 +156,9 @@
         from dateutil import relativedelta
         n = datetime.datetime(year=2012, month=5, day=17)
         delt = lambda *args, **kwargs: relativedelta.relativedelta(*args, **kwargs)
-        self.assertEqual(age(n + delt(**age_args), now=n), expected)
+        assert age(n + delt(**age_args), now=n) == expected
 
-    @parameterized.expand([
+    @parametrize('age_args,expected', [
         (dict(), u'just now'),
         (dict(seconds= -1), u'1 second ago'),
         (dict(seconds= -60 * 2), u'2 minutes ago'),
@@ -161,9 +180,9 @@
         from dateutil import relativedelta
         n = datetime.datetime(year=2012, month=5, day=17)
         delt = lambda *args, **kwargs: relativedelta.relativedelta(*args, **kwargs)
-        self.assertEqual(age(n + delt(**age_args), show_short_version=True, now=n), expected)
+        assert age(n + delt(**age_args), show_short_version=True, now=n) == expected
 
-    @parameterized.expand([
+    @parametrize('age_args,expected', [
         (dict(), u'just now'),
         (dict(seconds=1), u'in 1 second'),
         (dict(seconds=60 * 2), u'in 2 minutes'),
@@ -179,9 +198,9 @@
         from dateutil import relativedelta
         n = datetime.datetime(year=2012, month=5, day=17)
         delt = lambda *args, **kwargs: relativedelta.relativedelta(*args, **kwargs)
-        self.assertEqual(age(n + delt(**age_args), now=n), expected)
+        assert age(n + delt(**age_args), now=n) == expected
 
-    def test_tag_exctrator(self):
+    def test_tag_extractor(self):
         sample = (
             "hello pta[tag] gog [[]] [[] sda ero[or]d [me =>>< sa]"
             "[requires] [stale] [see<>=>] [see => http://example.com]"
@@ -190,23 +209,17 @@
         )
         from kallithea.lib.helpers import urlify_text
         res = urlify_text(sample, stylize=True)
-        self.assertIn('<div class="metatag" tag="tag">tag</div>', res)
-        self.assertIn('<div class="metatag" tag="obsolete">obsolete</div>', res)
-        self.assertIn('<div class="metatag" tag="stale">stale</div>', res)
-        self.assertIn('<div class="metatag" tag="lang">python</div>', res)
-        self.assertIn('<div class="metatag" tag="requires">requires =&gt; <a href="/url">url</a></div>', res)
-        self.assertIn('<div class="metatag" tag="tag">tag</div>', res)
+        assert '<div class="metatag" tag="tag">tag</div>' in res
+        assert '<div class="metatag" tag="obsolete">obsolete</div>' in res
+        assert '<div class="metatag" tag="stale">stale</div>' in res
+        assert '<div class="metatag" tag="lang">python</div>' in res
+        assert '<div class="metatag" tag="requires">requires =&gt; <a href="/url">url</a></div>' in res
+        assert '<div class="metatag" tag="tag">tag</div>' in res
 
     def test_alternative_gravatar(self):
         from kallithea.lib.helpers import gravatar_url
         _md5 = lambda s: hashlib.md5(s).hexdigest()
 
-        #mock pylons.url
-        class fake_url(object):
-            @classmethod
-            def current(cls, *args, **kwargs):
-                return 'https://example.com'
-
         #mock pylons.tmpl_context
         def fake_tmpl_context(_url):
             _c = AttributeDict()
@@ -216,11 +229,11 @@
 
             return _c
 
-
-        with mock.patch('pylons.url', fake_url):
+        fake_url = FakeUrlGenerator(current_url='https://example.com')
+        with mock.patch('kallithea.config.routing.url', fake_url):
             fake = fake_tmpl_context(_url='http://example.com/{email}')
             with mock.patch('pylons.tmpl_context', fake):
-                    from pylons import url
+                    from kallithea.config.routing import url
                     assert url.current() == 'https://example.com'
                     grav = gravatar_url(email_address='test@example.com', size=24)
                     assert grav == 'http://example.com/test@example.com'
@@ -248,7 +261,7 @@
                 grav = gravatar_url(email_address=em, size=24)
                 assert grav == 'https://example.com/%s/%s' % (_md5(em), 24)
 
-    @parameterized.expand([
+    @parametrize('tmpl,repo_name,overrides,prefix,expected', [
         (Repository.DEFAULT_CLONE_URI, 'group/repo1', {}, '', 'http://vps1:8000/group/repo1'),
         (Repository.DEFAULT_CLONE_URI, 'group/repo1', {'user': 'username'}, '', 'http://username@vps1:8000/group/repo1'),
         (Repository.DEFAULT_CLONE_URI, 'group/repo1', {}, '/prefix', 'http://vps1:8000/prefix/group/repo1'),
@@ -268,7 +281,7 @@
         from kallithea.lib.utils2 import get_clone_url
         clone_url = get_clone_url(uri_tmpl=tmpl, qualified_home_url='http://vps1:8000'+prefix,
                                   repo_name=repo_name, repo_id=23, **overrides)
-        self.assertEqual(clone_url, expected)
+        assert clone_url == expected
 
     def _quick_url(self, text, tmpl="""<a class="revision-link" href="%s">%s</a>""", url_=None):
         """
@@ -282,75 +295,109 @@
 
         def url_func(match_obj):
             _url = match_obj.groups()[0]
-            return tmpl % (url_ or '/some-url', _url)
+            return tmpl % (url_ or '/repo_name/changeset/%s' % _url, _url)
         return URL_PAT.sub(url_func, text)
 
-    @parameterized.expand([
+    @parametrize('sample,expected', [
       ("",
        ""),
       ("git-svn-id: https://svn.apache.org/repos/asf/libcloud/trunk@1441655 13f79535-47bb-0310-9956-ffa450edef68",
-       "git-svn-id: https://svn.apache.org/repos/asf/libcloud/trunk@1441655 13f79535-47bb-0310-9956-ffa450edef68"),
+       """git-svn-id: <a href="https://svn.apache.org/repos/asf/libcloud/trunk@1441655">https://svn.apache.org/repos/asf/libcloud/trunk@1441655</a> 13f79535-47bb-0310-9956-ffa450edef68"""),
       ("from rev 000000000000",
-       "from rev url[000000000000]"),
+       """from rev url[000000000000]"""),
       ("from rev 000000000000123123 also rev 000000000000",
-       "from rev url[000000000000123123] also rev url[000000000000]"),
+       """from rev url[000000000000123123] also rev url[000000000000]"""),
       ("this should-000 00",
-       "this should-000 00"),
+       """this should-000 00"""),
       ("longtextffffffffff rev 123123123123",
-       "longtextffffffffff rev url[123123123123]"),
+       """longtextffffffffff rev url[123123123123]"""),
       ("rev ffffffffffffffffffffffffffffffffffffffffffffffffff",
-       "rev ffffffffffffffffffffffffffffffffffffffffffffffffff"),
+       """rev ffffffffffffffffffffffffffffffffffffffffffffffffff"""),
       ("ffffffffffff some text traalaa",
-       "url[ffffffffffff] some text traalaa"),
+       """url[ffffffffffff] some text traalaa"""),
        ("""Multi line
        123123123123
        some text 123123123123
        sometimes !
        """,
-       """Multi line
-       url[123123123123]
-       some text url[123123123123]
-       sometimes !
-       """)
+       """Multi line<br/>"""
+       """       url[123123123123]<br/>"""
+       """       some text url[123123123123]<br/>"""
+       """       sometimes !"""),
     ])
-    def test_urlify_changesets(self, sample, expected):
-        def fake_url(self, *args, **kwargs):
-            return '/some-url'
-
+    def test_urlify_text(self, sample, expected):
         expected = self._quick_url(expected)
+        fake_url = FakeUrlGenerator(changeset_home='/%(repo_name)s/changeset/%(revision)s')
+        with mock.patch('kallithea.config.routing.url', fake_url):
+            from kallithea.lib.helpers import urlify_text
+            assert urlify_text(sample, 'repo_name') == expected
 
-        with mock.patch('pylons.url', fake_url):
-            from kallithea.lib.helpers import urlify_changesets
-            self.assertEqual(urlify_changesets(sample, 'repo_name'), expected)
-
-    @parameterized.expand([
+    @parametrize('sample,expected,url_', [
       ("",
        "",
        ""),
       ("https://svn.apache.org/repos",
-       "url[https://svn.apache.org/repos]",
+       """url[https://svn.apache.org/repos]""",
        "https://svn.apache.org/repos"),
       ("http://svn.apache.org/repos",
-       "url[http://svn.apache.org/repos]",
+       """url[http://svn.apache.org/repos]""",
        "http://svn.apache.org/repos"),
       ("from rev a also rev http://google.com",
-       "from rev a also rev url[http://google.com]",
+       """from rev a also rev url[http://google.com]""",
        "http://google.com"),
-       ("""Multi line
+      ("http://imgur.com/foo.gif inline http://imgur.com/foo.gif ending http://imgur.com/foo.gif",
+       """url[http://imgur.com/foo.gif] inline url[http://imgur.com/foo.gif] ending url[http://imgur.com/foo.gif]""",
+       "http://imgur.com/foo.gif"),
+      ("""Multi line
        https://foo.bar.example.com
        some text lalala""",
-       """Multi line
-       url[https://foo.bar.example.com]
-       some text lalala""",
-       "https://foo.bar.example.com")
+       """Multi line<br/>"""
+       """       url[https://foo.bar.example.com]<br/>"""
+       """       some text lalala""",
+       "https://foo.bar.example.com"),
+      ("@mention @someone",
+       """<b>@mention</b> <b>@someone</b>""",
+       ""),
+      ("deadbeefcafe 123412341234",
+       """<a class="revision-link" href="/repo_name/changeset/deadbeefcafe">deadbeefcafe</a> <a class="revision-link" href="/repo_name/changeset/123412341234">123412341234</a>""",
+       ""),
+      ("We support * markup for *bold* markup of *single or multiple* words, "
+       "*a bit @like http://slack.com*. "
+       "The first * must come after whitespace and not be followed by whitespace, "
+       "contain anything but * and newline until the next *, "
+       "which must not come after whitespace "
+       "and not be followed by * or alphanumerical *characters*.",
+       """We support * markup for <b>*bold*</b> markup of <b>*single or multiple*</b> words, """
+       """<b>*a bit <b>@like</b> <a href="http://slack.com">http://slack.com</a>*</b>. """
+       """The first * must come after whitespace and not be followed by whitespace, """
+       """contain anything but * and newline until the next *, """
+       """which must not come after whitespace """
+       """and not be followed by * or alphanumerical <b>*characters*</b>.""",
+       "-"),
+      # tags are covered by test_tag_extractor
     ])
     def test_urlify_test(self, sample, expected, url_):
-        from kallithea.lib.helpers import urlify_text
         expected = self._quick_url(expected,
                                    tmpl="""<a href="%s">%s</a>""", url_=url_)
-        self.assertEqual(urlify_text(sample), expected)
+        fake_url = FakeUrlGenerator(changeset_home='/%(repo_name)s/changeset/%(revision)s')
+        with mock.patch('kallithea.config.routing.url', fake_url):
+            from kallithea.lib.helpers import urlify_text
+            assert urlify_text(sample, 'repo_name', stylize=True) == expected
 
-    @parameterized.expand([
+    @parametrize('sample,expected', [
+      ("deadbeefcafe @mention, and http://foo.bar/ yo",
+       """<a class="revision-link" href="/repo_name/changeset/deadbeefcafe">deadbeefcafe</a>"""
+       """<a class="message-link" href="#the-link"> <b>@mention</b>, and </a>"""
+       """<a href="http://foo.bar/">http://foo.bar/</a>"""
+       """<a class="message-link" href="#the-link"> yo</a>"""),
+    ])
+    def test_urlify_link(self, sample, expected):
+        fake_url = FakeUrlGenerator(changeset_home='/%(repo_name)s/changeset/%(revision)s')
+        with mock.patch('kallithea.config.routing.url', fake_url):
+            from kallithea.lib.helpers import urlify_text
+            assert urlify_text(sample, 'repo_name', link_='#the-link') == expected
+
+    @parametrize('test,expected', [
       ("", None),
       ("/_2", '2'),
       ("_2", '2'),
@@ -370,5 +417,4 @@
     def test_get_repo_by_id(self, test, expected):
         from kallithea.lib.utils import _extract_id_from_repo_name
         _test = _extract_id_from_repo_name(test)
-        self.assertEqual(_test, expected, msg='url:%s, got:`%s` expected: `%s`'
-                                              % (test, _test, expected))
+        assert _test == expected, 'url:%s, got:`%s` expected: `%s`' % (test, _test, expected)
--- a/kallithea/tests/other/test_mail.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/other/test_mail.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,7 +1,7 @@
 import mock
 
 import kallithea
-from kallithea.tests import *
+from kallithea.tests.base import *
 from kallithea.model.db import User
 
 class smtplib_mock(object):
@@ -21,7 +21,7 @@
         pass
 
 @mock.patch('kallithea.lib.rcmail.smtp_mailer.smtplib', smtplib_mock)
-class TestMail(BaseTestCase):
+class TestMail(TestController):
 
     def test_send_mail_trivial(self):
         mailserver = 'smtp.mailserver.org'
@@ -38,12 +38,12 @@
         with mock.patch('kallithea.lib.celerylib.tasks.config', config_mock):
             kallithea.lib.celerylib.tasks.send_email(recipients, subject, body, html_body)
 
-        self.assertSetEqual(smtplib_mock.lastdest, set(recipients))
-        self.assertEqual(smtplib_mock.lastsender, envelope_from)
-        self.assertIn('From: %s' % envelope_from, smtplib_mock.lastmsg)
-        self.assertIn('Subject: %s' % subject, smtplib_mock.lastmsg)
-        self.assertIn(body, smtplib_mock.lastmsg)
-        self.assertIn(html_body, smtplib_mock.lastmsg)
+        assert smtplib_mock.lastdest == set(recipients)
+        assert smtplib_mock.lastsender == envelope_from
+        assert 'From: %s' % envelope_from in smtplib_mock.lastmsg
+        assert 'Subject: %s' % subject in smtplib_mock.lastmsg
+        assert body in smtplib_mock.lastmsg
+        assert html_body in smtplib_mock.lastmsg
 
     def test_send_mail_no_recipients(self):
         mailserver = 'smtp.mailserver.org'
@@ -62,12 +62,12 @@
         with mock.patch('kallithea.lib.celerylib.tasks.config', config_mock):
             kallithea.lib.celerylib.tasks.send_email(recipients, subject, body, html_body)
 
-        self.assertSetEqual(smtplib_mock.lastdest, set([TEST_USER_ADMIN_EMAIL, email_to]))
-        self.assertEqual(smtplib_mock.lastsender, envelope_from)
-        self.assertIn('From: %s' % envelope_from, smtplib_mock.lastmsg)
-        self.assertIn('Subject: %s' % subject, smtplib_mock.lastmsg)
-        self.assertIn(body, smtplib_mock.lastmsg)
-        self.assertIn(html_body, smtplib_mock.lastmsg)
+        assert smtplib_mock.lastdest == set([TEST_USER_ADMIN_EMAIL, email_to])
+        assert smtplib_mock.lastsender == envelope_from
+        assert 'From: %s' % envelope_from in smtplib_mock.lastmsg
+        assert 'Subject: %s' % subject in smtplib_mock.lastmsg
+        assert body in smtplib_mock.lastmsg
+        assert html_body in smtplib_mock.lastmsg
 
     def test_send_mail_no_recipients_no_email_to(self):
         mailserver = 'smtp.mailserver.org'
@@ -84,12 +84,12 @@
         with mock.patch('kallithea.lib.celerylib.tasks.config', config_mock):
             kallithea.lib.celerylib.tasks.send_email(recipients, subject, body, html_body)
 
-        self.assertSetEqual(smtplib_mock.lastdest, set([TEST_USER_ADMIN_EMAIL]))
-        self.assertEqual(smtplib_mock.lastsender, envelope_from)
-        self.assertIn('From: %s' % envelope_from, smtplib_mock.lastmsg)
-        self.assertIn('Subject: %s' % subject, smtplib_mock.lastmsg)
-        self.assertIn(body, smtplib_mock.lastmsg)
-        self.assertIn(html_body, smtplib_mock.lastmsg)
+        assert smtplib_mock.lastdest == set([TEST_USER_ADMIN_EMAIL])
+        assert smtplib_mock.lastsender == envelope_from
+        assert 'From: %s' % envelope_from in smtplib_mock.lastmsg
+        assert 'Subject: %s' % subject in smtplib_mock.lastmsg
+        assert body in smtplib_mock.lastmsg
+        assert html_body in smtplib_mock.lastmsg
 
     def test_send_mail_with_author(self):
         mailserver = 'smtp.mailserver.org'
@@ -107,12 +107,12 @@
         with mock.patch('kallithea.lib.celerylib.tasks.config', config_mock):
             kallithea.lib.celerylib.tasks.send_email(recipients, subject, body, html_body, author=author)
 
-        self.assertSetEqual(smtplib_mock.lastdest, set(recipients))
-        self.assertEqual(smtplib_mock.lastsender, envelope_from)
-        self.assertIn('From: "Kallithea Admin (no-reply)" <%s>' % envelope_from, smtplib_mock.lastmsg)
-        self.assertIn('Subject: %s' % subject, smtplib_mock.lastmsg)
-        self.assertIn(body, smtplib_mock.lastmsg)
-        self.assertIn(html_body, smtplib_mock.lastmsg)
+        assert smtplib_mock.lastdest == set(recipients)
+        assert smtplib_mock.lastsender == envelope_from
+        assert 'From: "Kallithea Admin (no-reply)" <%s>' % envelope_from in smtplib_mock.lastmsg
+        assert 'Subject: %s' % subject in smtplib_mock.lastmsg
+        assert body in smtplib_mock.lastmsg
+        assert html_body in smtplib_mock.lastmsg
 
     def test_send_mail_with_author_full_mail_from(self):
         mailserver = 'smtp.mailserver.org'
@@ -131,12 +131,12 @@
         with mock.patch('kallithea.lib.celerylib.tasks.config', config_mock):
             kallithea.lib.celerylib.tasks.send_email(recipients, subject, body, html_body, author=author)
 
-        self.assertSetEqual(smtplib_mock.lastdest, set(recipients))
-        self.assertEqual(smtplib_mock.lastsender, envelope_from)
-        self.assertIn('From: "Kallithea Admin (no-reply)" <%s>' % envelope_addr, smtplib_mock.lastmsg)
-        self.assertIn('Subject: %s' % subject, smtplib_mock.lastmsg)
-        self.assertIn(body, smtplib_mock.lastmsg)
-        self.assertIn(html_body, smtplib_mock.lastmsg)
+        assert smtplib_mock.lastdest == set(recipients)
+        assert smtplib_mock.lastsender == envelope_from
+        assert 'From: "Kallithea Admin (no-reply)" <%s>' % envelope_addr in smtplib_mock.lastmsg
+        assert 'Subject: %s' % subject in smtplib_mock.lastmsg
+        assert body in smtplib_mock.lastmsg
+        assert html_body in smtplib_mock.lastmsg
 
     def test_send_mail_extra_headers(self):
         mailserver = 'smtp.mailserver.org'
@@ -145,7 +145,7 @@
         subject = 'subject'
         body = 'body'
         html_body = 'html_body'
-        author = User(name='foo', lastname='(fubar) "baz"')
+        author = User(name='foo', lastname=u'(fubar) "baz"')
         headers = {'extra': 'yes'}
 
         config_mock = {
@@ -156,12 +156,12 @@
             kallithea.lib.celerylib.tasks.send_email(recipients, subject, body, html_body,
                                                      author=author, headers=headers)
 
-        self.assertSetEqual(smtplib_mock.lastdest, set(recipients))
-        self.assertEqual(smtplib_mock.lastsender, envelope_from)
-        self.assertIn(r'From: "foo (fubar) \"baz\" (no-reply)" <%s>' % envelope_from, smtplib_mock.lastmsg)
-        self.assertIn('Subject: %s' % subject, smtplib_mock.lastmsg)
-        self.assertIn(body, smtplib_mock.lastmsg)
-        self.assertIn(html_body, smtplib_mock.lastmsg)
-        self.assertIn('Extra: yes', smtplib_mock.lastmsg)
+        assert smtplib_mock.lastdest == set(recipients)
+        assert smtplib_mock.lastsender == envelope_from
+        assert r'From: "foo (fubar) \"baz\" (no-reply)" <%s>' % envelope_from in smtplib_mock.lastmsg
+        assert 'Subject: %s' % subject in smtplib_mock.lastmsg
+        assert body in smtplib_mock.lastmsg
+        assert html_body in smtplib_mock.lastmsg
+        assert 'Extra: yes' in smtplib_mock.lastmsg
         # verify that headers dict hasn't mutated by send_email
-        self.assertDictEqual(headers, {'extra': 'yes'})
+        assert headers == {'extra': 'yes'}
--- a/kallithea/tests/other/test_validators.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/other/test_validators.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,7 +1,9 @@
 # -*- coding: utf-8 -*-
 import formencode
+import pytest
+import tempfile
 
-from kallithea.tests import *
+from kallithea.tests.base import *
 
 from kallithea.model import validators as v
 from kallithea.model.user_group import UserGroupModel
@@ -13,59 +15,66 @@
 fixture = Fixture()
 
 
-class TestRepoGroups(BaseTestCase):
+class TestRepoGroups(TestController):
 
-    def setUp(self):
-        pass
-
-    def tearDown(self):
+    def teardown_method(self, method):
         Session.remove()
 
     def test_Message_extractor(self):
         validator = v.ValidUsername()
-        self.assertRaises(formencode.Invalid, validator.to_python, 'default')
+        with pytest.raises(formencode.Invalid):
+            validator.to_python('default')
 
         class StateObj(object):
             pass
 
-        self.assertRaises(formencode.Invalid,
-                          validator.to_python, 'default', StateObj)
+        with pytest.raises(formencode.Invalid):
+            validator.to_python('default', StateObj)
 
     def test_ValidUsername(self):
         validator = v.ValidUsername()
 
-        self.assertRaises(formencode.Invalid, validator.to_python, 'default')
-        self.assertRaises(formencode.Invalid, validator.to_python, 'new_user')
-        self.assertRaises(formencode.Invalid, validator.to_python, '.,')
-        self.assertRaises(formencode.Invalid, validator.to_python,
-                          TEST_USER_ADMIN_LOGIN)
-        self.assertEqual('test', validator.to_python('test'))
+        with pytest.raises(formencode.Invalid):
+            validator.to_python('default')
+        with pytest.raises(formencode.Invalid):
+            validator.to_python('new_user')
+        with pytest.raises(formencode.Invalid):
+            validator.to_python('.,')
+        with pytest.raises(formencode.Invalid):
+            validator.to_python(TEST_USER_ADMIN_LOGIN)
+        assert 'test' == validator.to_python('test')
 
         validator = v.ValidUsername(edit=True, old_data={'user_id': 1})
 
     def test_ValidRepoUser(self):
         validator = v.ValidRepoUser()
-        self.assertRaises(formencode.Invalid, validator.to_python, 'nouser')
-        self.assertEqual(TEST_USER_ADMIN_LOGIN,
-                         validator.to_python(TEST_USER_ADMIN_LOGIN))
+        with pytest.raises(formencode.Invalid):
+            validator.to_python('nouser')
+        assert TEST_USER_ADMIN_LOGIN == validator.to_python(TEST_USER_ADMIN_LOGIN)
 
     def test_ValidUserGroup(self):
         validator = v.ValidUserGroup()
-        self.assertRaises(formencode.Invalid, validator.to_python, 'default')
-        self.assertRaises(formencode.Invalid, validator.to_python, '.,')
+        with pytest.raises(formencode.Invalid):
+            validator.to_python(u'default')
+        with pytest.raises(formencode.Invalid):
+            validator.to_python(u'.,')
 
-        gr = fixture.create_user_group('test')
-        gr2 = fixture.create_user_group('tes2')
+        gr = fixture.create_user_group(u'test')
+        gr2 = fixture.create_user_group(u'tes2')
         Session().commit()
-        self.assertRaises(formencode.Invalid, validator.to_python, 'test')
+        with pytest.raises(formencode.Invalid):
+            validator.to_python(u'test')
         assert gr.users_group_id is not None
         validator = v.ValidUserGroup(edit=True,
                                     old_data={'users_group_id':
                                               gr2.users_group_id})
 
-        self.assertRaises(formencode.Invalid, validator.to_python, 'test')
-        self.assertRaises(formencode.Invalid, validator.to_python, 'TesT')
-        self.assertRaises(formencode.Invalid, validator.to_python, 'TEST')
+        with pytest.raises(formencode.Invalid):
+            validator.to_python(u'test')
+        with pytest.raises(formencode.Invalid):
+            validator.to_python(u'TesT')
+        with pytest.raises(formencode.Invalid):
+            validator.to_python(u'TEST')
         UserGroupModel().delete(gr)
         UserGroupModel().delete(gr2)
         Session().commit()
@@ -73,49 +82,48 @@
     def test_ValidRepoGroup(self):
         validator = v.ValidRepoGroup()
         model = RepoGroupModel()
-        self.assertRaises(formencode.Invalid, validator.to_python,
-                          {'group_name': HG_REPO, })
-        gr = model.create(group_name='test_gr', group_description='desc',
+        with pytest.raises(formencode.Invalid):
+            validator.to_python({'group_name': HG_REPO, })
+        gr = model.create(group_name=u'test_gr', group_description=u'desc',
                           parent=None,
                           just_db=True,
                           owner=TEST_USER_ADMIN_LOGIN)
-        self.assertRaises(formencode.Invalid,
-                          validator.to_python, {'group_name': gr.group_name, })
+        with pytest.raises(formencode.Invalid):
+            validator.to_python({'group_name': gr.group_name, })
 
         validator = v.ValidRepoGroup(edit=True,
                                       old_data={'group_id':  gr.group_id})
-        self.assertRaises(formencode.Invalid,
-                          validator.to_python, {
+        with pytest.raises(formencode.Invalid):
+            validator.to_python({
                                         'group_name': gr.group_name + 'n',
-                                        'group_parent_id': gr.group_id
+                                        'parent_group_id': gr.group_id
                                         })
         model.delete(gr)
 
     def test_ValidPassword(self):
         validator = v.ValidPassword()
-        self.assertEqual('lol', validator.to_python('lol'))
-        self.assertEqual(None, validator.to_python(None))
-        self.assertRaises(formencode.Invalid, validator.to_python, 'ąćżź')
+        assert 'lol' == validator.to_python('lol')
+        assert None == validator.to_python(None)
+        with pytest.raises(formencode.Invalid):
+            validator.to_python('ąćżź')
 
     def test_ValidPasswordsMatch(self):
         validator = v.ValidPasswordsMatch('new_password', 'password_confirmation')
-        self.assertRaises(formencode.Invalid,
-                    validator.to_python, {'new_password': 'pass',
+        with pytest.raises(formencode.Invalid):
+            validator.to_python({'new_password': 'pass',
                                           'password_confirmation': 'pass2'})
 
-        self.assertRaises(formencode.Invalid,
-                    validator.to_python, {'new_password': 'pass',
+        with pytest.raises(formencode.Invalid):
+            validator.to_python({'new_password': 'pass',
                                           'password_confirmation': 'pass2'})
 
-        self.assertEqual({'new_password': 'pass',
-                          'password_confirmation': 'pass'},
-                    validator.to_python({'new_password': 'pass',
-                                         'password_confirmation': 'pass'}))
+        assert {'new_password': 'pass',
+                          'password_confirmation': 'pass'} == validator.to_python({'new_password': 'pass',
+                                         'password_confirmation': 'pass'})
 
-        self.assertEqual({'new_password': 'pass',
-                          'password_confirmation': 'pass'},
-                    validator.to_python({'new_password': 'pass',
-                                         'password_confirmation': 'pass'}))
+        assert {'new_password': 'pass',
+                          'password_confirmation': 'pass'} == validator.to_python({'new_password': 'pass',
+                                         'password_confirmation': 'pass'})
 
     def test_ValidAuth(self):
         validator = v.ValidAuth()
@@ -127,9 +135,9 @@
             'username': 'err',
             'password': 'err',
         }
-        self.assertEqual(valid_creds, validator.to_python(valid_creds))
-        self.assertRaises(formencode.Invalid,
-                          validator.to_python, invalid_creds)
+        assert valid_creds == validator.to_python(valid_creds)
+        with pytest.raises(formencode.Invalid):
+            validator.to_python(invalid_creds)
 
     def test_ValidAuthToken(self):
         validator = v.ValidAuthToken()
@@ -141,18 +149,18 @@
     def test_ValidRepoName(self):
         validator = v.ValidRepoName()
 
-        self.assertRaises(formencode.Invalid,
-                          validator.to_python, {'repo_name': ''})
+        with pytest.raises(formencode.Invalid):
+            validator.to_python({'repo_name': ''})
 
-        self.assertRaises(formencode.Invalid,
-                          validator.to_python, {'repo_name': HG_REPO})
+        with pytest.raises(formencode.Invalid):
+            validator.to_python({'repo_name': HG_REPO})
 
-        gr = RepoGroupModel().create(group_name='group_test',
-                                      group_description='desc',
+        gr = RepoGroupModel().create(group_name=u'group_test',
+                                      group_description=u'desc',
                                       parent=None,
                                       owner=TEST_USER_ADMIN_LOGIN)
-        self.assertRaises(formencode.Invalid,
-                          validator.to_python, {'repo_name': gr.group_name})
+        with pytest.raises(formencode.Invalid):
+            validator.to_python({'repo_name': gr.group_name})
 
         #TODO: write an error case for that ie. create a repo withinh a group
 #        self.assertRaises(formencode.Invalid,
@@ -163,14 +171,14 @@
         # this uses ValidRepoName validator
         assert True
 
-    @parameterized.expand([
+    @parametrize('name,expected', [
         ('test', 'test'), ('lolz!', 'lolz'), ('  aavv', 'aavv'),
         ('ala ma kota', 'ala-ma-kota'), ('@nooo', 'nooo'),
         ('$!haha lolz !', 'haha-lolz'), ('$$$$$', ''), ('{}OK!', 'OK'),
         ('/]re po', 're-po')])
     def test_SlugifyName(self, name, expected):
         validator = v.SlugifyName()
-        self.assertEqual(expected, validator.to_python(name))
+        assert expected == validator.to_python(name)
 
     def test_ValidCloneUri(self):
             #TODO: write this one
@@ -178,8 +186,9 @@
 
     def test_ValidForkType(self):
             validator = v.ValidForkType(old_data={'repo_type': 'hg'})
-            self.assertEqual('hg', validator.to_python('hg'))
-            self.assertRaises(formencode.Invalid, validator.to_python, 'git')
+            assert 'hg' == validator.to_python('hg')
+            with pytest.raises(formencode.Invalid):
+                validator.to_python('git')
 
     def test_ValidPerms(self):
             #TODO: write this one
@@ -187,45 +196,44 @@
 
     def test_ValidSettings(self):
         validator = v.ValidSettings()
-        self.assertEqual({'pass': 'pass'},
-                         validator.to_python(value={'user': 'test',
-                                                    'pass': 'pass'}))
+        assert {'pass': 'pass'} == validator.to_python(value={'user': 'test',
+                                                    'pass': 'pass'})
 
-        self.assertEqual({'user2': 'test', 'pass': 'pass'},
-                         validator.to_python(value={'user2': 'test',
-                                                    'pass': 'pass'}))
+        assert {'user2': 'test', 'pass': 'pass'} == validator.to_python(value={'user2': 'test',
+                                                    'pass': 'pass'})
 
     def test_ValidPath(self):
             validator = v.ValidPath()
-            self.assertEqual(TESTS_TMP_PATH,
-                             validator.to_python(TESTS_TMP_PATH))
-            self.assertRaises(formencode.Invalid, validator.to_python,
-                              '/no_such_dir')
+            assert tempfile.gettempdir() == validator.to_python(tempfile.gettempdir())
+            with pytest.raises(formencode.Invalid):
+                validator.to_python('/no_such_dir')
 
     def test_UniqSystemEmail(self):
         validator = v.UniqSystemEmail(old_data={})
 
-        self.assertEqual('mail@python.org',
-                         validator.to_python('MaiL@Python.org'))
+        assert 'mail@python.org' == validator.to_python('MaiL@Python.org')
 
         email = TEST_USER_REGULAR2_EMAIL
-        self.assertRaises(formencode.Invalid, validator.to_python, email)
+        with pytest.raises(formencode.Invalid):
+            validator.to_python(email)
 
     def test_ValidSystemEmail(self):
         validator = v.ValidSystemEmail()
         email = TEST_USER_REGULAR2_EMAIL
 
-        self.assertEqual(email, validator.to_python(email))
-        self.assertRaises(formencode.Invalid, validator.to_python, 'err')
+        assert email == validator.to_python(email)
+        with pytest.raises(formencode.Invalid):
+            validator.to_python('err')
 
     def test_LdapLibValidator(self):
         if ldap_lib_installed:
             validator = v.LdapLibValidator()
-            self.assertEqual("DN", validator.to_python('DN'))
+            assert "DN" == validator.to_python('DN')
         else:
             validator = v.LdapLibValidator()
-            self.assertRaises(v.LdapImportError, validator.to_python, 'err')
+            with pytest.raises(v.LdapImportError):
+                validator.to_python('err')
 
     def test_AttrLoginValidator(self):
         validator = v.AttrLoginValidator()
-        self.assertEqual('DN_attr', validator.to_python('DN_attr'))
+        assert 'DN_attr' == validator.to_python('DN_attr')
--- a/kallithea/tests/parameterized.py	Thu Nov 17 13:09:43 2016 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,241 +0,0 @@
-import re
-import new
-import inspect
-import logging
-import logging.handlers
-from functools import wraps
-
-from unittest import TestCase
-
-
-def skip_test(func):
-    try:
-        from nose.tools import nottest
-    except ImportError:
-        pass
-    else:
-        func = nottest(func)
-
-    try:
-        import pytest
-    except ImportError:
-        pass
-    else:
-        func = pytest.mark.skipIf(True, func)
-
-    return func
-
-
-def _terrible_magic_get_defining_classes():
-    """ Returns the set of parent classes of the class currently being defined.
-        Will likely only work if called from the ``parameterized`` decorator.
-        This function is entirely @brandon_rhodes's fault, as he suggested
-        the implementation: http://stackoverflow.com/a/8793684/71522
-        """
-    stack = inspect.stack()
-    if len(stack) <= 4:
-        return []
-    frame = stack[3]
-    code_context = frame[4][0].strip()
-    if not code_context.startswith("class "):
-        return []
-    _, parents = code_context.split("(", 1)
-    parents, _ = parents.rsplit(")", 1)
-    return eval("[" + parents + "]", frame[0].f_globals, frame[0].f_locals)
-
-
-def parameterized(input):
-    """ Parameterize a test case:
-        >>> add1_tests = [(1, 2), (2, 3)]
-        >>> class TestFoo(object):
-        ...     @parameterized(add1_tests)
-        ...     def test_add1(self, input, expected):
-        ...         assert_equal(add1(input), expected)
-        >>> @parameterized(add1_tests)
-        ... def test_add1(input, expected):
-        ...     assert_equal(add1(input), expected)
-        >>>
-        """
-
-    if not hasattr(input, "__iter__"):
-        raise ValueError("expected iterable input; got %r" % (input,))
-
-    def parameterized_helper(f):
-        attached_instance_method = [False]
-
-        parent_classes = _terrible_magic_get_defining_classes()
-        if any(issubclass(cls, TestCase) for cls in parent_classes):
-            raise Exception("Warning: '@parameterized' tests won't work "
-                            "inside subclasses of 'TestCase' - use "
-                            "'@parameterized.expand' instead")
-
-        @wraps(f)
-        def parameterized_helper_method(self=None):
-            if self is not None and not attached_instance_method[0]:
-                # confusingly, we need to create a named instance method and
-                # attach that to the class...
-                cls = self.__class__
-                im_f = new.instancemethod(f, None, cls)
-                setattr(cls, f.__name__, im_f)
-                attached_instance_method[0] = True
-            for args in input:
-                if isinstance(args, basestring):
-                    args = [args]
-                # ... then pull that named instance method off, turning it into
-                # a bound method ...
-                if self is not None:
-                    args = [getattr(self, f.__name__)] + list(args)
-                else:
-                    args = [f] + list(args)
-                # ... then yield that as a tuple. If those steps aren't
-                # followed precicely, Nose gets upset and doesn't run the test
-                # or doesn't run setup methods.
-                yield tuple(args)
-
-        f.__name__ = "_helper_for_%s" % (f.__name__,)
-        parameterized_helper_method.parameterized_input = input
-        parameterized_helper_method.parameterized_func = f
-        return parameterized_helper_method
-
-    return parameterized_helper
-
-
-def to_safe_name(s):
-    return re.sub("[^a-zA-Z0-9_]", "", s)
-
-
-def parameterized_expand_helper(func_name, func, args):
-    def parameterized_expand_helper_helper(self=()):
-        if self != ():
-            self = (self,)
-        return func(*(self + args))
-    parameterized_expand_helper_helper.__name__ = str(func_name)
-    return parameterized_expand_helper_helper
-
-
-def parameterized_expand(input):
-    """ A "brute force" method of parameterizing test cases. Creates new test
-        cases and injects them into the namespace that the wrapped function
-        is being defined in. Useful for parameterizing tests in subclasses
-        of 'UnitTest', where Nose test generators don't work.
-
-        >>> @parameterized.expand([("foo", 1, 2)])
-        ... def test_add1(name, input, expected):
-        ...     actual = add1(input)
-        ...     assert_equal(actual, expected)
-        ...
-        >>> locals()
-        ... 'test_add1_foo_0': <function ...> ...
-        >>>
-        """
-
-    def parameterized_expand_wrapper(f):
-        stack = inspect.stack()
-        frame = stack[1]
-        frame_locals = frame[0].f_locals
-
-        base_name = f.__name__
-        for num, args in enumerate(input):
-            name_suffix = "_%s" % (num,)
-            if len(args) > 0 and isinstance(args[0], basestring):
-                name_suffix += "_" + to_safe_name(args[0])
-            name = base_name + name_suffix
-            new_func = parameterized_expand_helper(name, f, args)
-            frame_locals[name] = new_func
-        return skip_test(f)
-    return parameterized_expand_wrapper
-
-parameterized.expand = parameterized_expand
-
-
-def assert_contains(haystack, needle):
-    if needle not in haystack:
-        raise AssertionError("%r not in %r" % (needle, haystack))
-
-
-def assert_not_contains(haystack, needle):
-    if needle in haystack:
-        raise AssertionError("%r in %r" % (needle, haystack))
-
-
-def assert_raises(func, exc_type, str_contains=None, repr_contains=None):
-    try:
-        func()
-    except exc_type as e:
-        if str_contains is not None and str_contains not in str(e):
-            raise AssertionError("%s raised, but %r does not contain %r"
-                                 % (exc_type, str(e), str_contains))
-        if repr_contains is not None and repr_contains not in repr(e):
-            raise AssertionError("%s raised, but %r does not contain %r"
-                                 % (exc_type, repr(e), repr_contains))
-        return e
-    else:
-        raise AssertionError("%s not raised" % (exc_type,))
-
-
-log_handler = None
-
-
-def setup_logging():
-    """ Configures a log handler which will capure log messages during a test.
-        The ``logged_messages`` and ``assert_no_errors_logged`` functions can be
-        used to make assertions about these logged messages.
-
-        For example::
-
-            from ensi_common.testing import (
-                setup_logging, teardown_logging, assert_no_errors_logged,
-                assert_logged,
-            )
-
-            class TestWidget(object):
-                def setup(self):
-                    setup_logging()
-
-                def teardown(self):
-                    assert_no_errors_logged()
-                    teardown_logging()
-
-                def test_that_will_fail(self):
-                    log.warning("this warning message will trigger a failure")
-
-                def test_that_will_pass(self):
-                    log.info("but info messages are ok")
-                    assert_logged("info messages are ok")
-        """
-
-    global log_handler
-    if log_handler is not None:
-        logging.getLogger().removeHandler(log_handler)
-    log_handler = logging.handlers.BufferingHandler(1000)
-    formatter = logging.Formatter("%(name)s: %(levelname)s: %(message)s")
-    log_handler.setFormatter(formatter)
-    logging.getLogger().addHandler(log_handler)
-
-
-def teardown_logging():
-    global log_handler
-    if log_handler is not None:
-        logging.getLogger().removeHandler(log_handler)
-        log_handler = None
-
-
-def logged_messages():
-    assert log_handler, "setup_logging not called"
-    return [(log_handler.format(record), record) for record in log_handler.buffer]
-
-
-def assert_no_errors_logged():
-    for _, record in logged_messages():
-        if record.levelno >= logging.WARNING:
-            # Assume that the nose log capture plugin is being used, so it will
-            # show the exception.
-            raise AssertionError("an unexpected error was logged")
-
-
-def assert_logged(expected_msg_contents):
-    for msg, _ in logged_messages():
-        if expected_msg_contents in msg:
-            return
-    raise AssertionError("no logged message contains %r"
-                         % (expected_msg_contents,))
--- a/kallithea/tests/scripts/manual_test_concurrency.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/scripts/manual_test_concurrency.py	Fri Nov 18 01:11:13 2016 +0100
@@ -30,8 +30,7 @@
 import sys
 import shutil
 import logging
-from os.path import join as jn
-from os.path import dirname as dn
+from os.path import dirname
 
 from tempfile import _RandomNameSequence
 from subprocess import Popen, PIPE
@@ -39,20 +38,20 @@
 from paste.deploy import appconfig
 from sqlalchemy import engine_from_config
 
-from kallithea.lib.utils import add_cache
-from kallithea.model import init_model
+from kallithea.lib.utils import setup_cache_regions
+from kallithea.model.base import init_model
 from kallithea.model import meta
-from kallithea.model.db import User, Repository
+from kallithea.model.db import User, Repository, Ui
 from kallithea.lib.auth import get_crypt_password
 
-from kallithea.tests import TESTS_TMP_PATH, HG_REPO
+from kallithea.tests.base import HG_REPO
 from kallithea.config.environment import load_environment
 
-rel_path = dn(dn(dn(dn(os.path.abspath(__file__)))))
+rel_path = dirname(dirname(dirname(dirname(os.path.abspath(__file__)))))
 conf = appconfig('config:development.ini', relative_to=rel_path)
 load_environment(conf.global_conf, conf.local_conf)
 
-add_cache(conf)
+setup_cache_regions(conf)
 
 USER = TEST_USER_ADMIN_LOGIN
 PASS = TEST_USER_ADMIN_PASS
@@ -83,7 +82,7 @@
 
 
 def get_session():
-    engine = engine_from_config(conf, 'sqlalchemy.db1.')
+    engine = engine_from_config(conf, 'sqlalchemy.')
     init_model(engine)
     sa = meta.Session
     return sa
@@ -161,7 +160,7 @@
 #==============================================================================
 def test_clone_with_credentials(no_errors=False, repo=HG_REPO, method=METHOD,
                                 seq=None, backend='hg'):
-    cwd = path = jn(TESTS_TMP_PATH, repo)
+    cwd = path = os.path.join(Ui.get_by_key('paths', '/').ui_value, repo)
 
     if seq is None:
         seq = _RandomNameSequence().next()
@@ -169,7 +168,7 @@
     try:
         shutil.rmtree(path, ignore_errors=True)
         os.makedirs(path)
-        #print 'made dirs %s' % jn(path)
+        #print 'made dirs %s' % os.path.join(path)
     except OSError:
         raise
 
--- a/kallithea/tests/scripts/manual_test_crawler.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/scripts/manual_test_crawler.py	Fri Nov 18 01:11:13 2016 +0100
@@ -37,11 +37,11 @@
 import time
 import os
 import sys
-from os.path import join as jn
-from os.path import dirname as dn
+import tempfile
+from os.path import dirname
 
 __here__ = os.path.abspath(__file__)
-__root__ = dn(dn(dn(__here__)))
+__root__ = dirname(dirname(dirname(__here__)))
 sys.path.append(__root__)
 
 from kallithea.lib import vcs
@@ -61,7 +61,7 @@
 
 print 'Crawling @ %s' % BASE_URI
 BASE_URI += '%s'
-PROJECT_PATH = jn('/', 'home', 'username', 'repos')
+PROJECT_PATH = os.path.join('/', 'home', 'username', 'repos')
 PROJECTS = [
     #'linux-magx-pbranch',
     'CPython',
@@ -69,7 +69,7 @@
 ]
 
 
-cj = cookielib.FileCookieJar('/tmp/rc_test_cookie.txt')
+cj = cookielib.FileCookieJar(os.path.join(tempfile.gettempdir(), 'rc_test_cookie.txt'))
 o = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
 o.addheaders = [
     ('User-agent', 'kallithea-crawler'),
@@ -81,7 +81,7 @@
 
 def _get_repo(proj):
     if isinstance(proj, basestring):
-        repo = vcs.get_repo(jn(PROJECT_PATH, proj))
+        repo = vcs.get_repo(os.path.join(PROJECT_PATH, proj))
         proj = proj
     else:
         repo = proj
@@ -116,7 +116,7 @@
 def test_changeset_walk(proj, limit=None):
     repo, proj = _get_repo(proj)
 
-    print 'processing', jn(PROJECT_PATH, proj)
+    print 'processing', os.path.join(PROJECT_PATH, proj)
     total_time = 0
 
     cnt = 0
@@ -142,7 +142,7 @@
 def test_files_walk(proj, limit=100):
     repo, proj = _get_repo(proj)
 
-    print 'processing', jn(PROJECT_PATH, proj)
+    print 'processing', os.path.join(PROJECT_PATH, proj)
     total_time = 0
 
     paths_ = OrderedSet([''])
@@ -182,7 +182,7 @@
 
 if __name__ == '__main__':
     for path in PROJECTS:
-        repo = vcs.get_repo(jn(PROJECT_PATH, path))
+        repo = vcs.get_repo(os.path.join(PROJECT_PATH, path))
         for i in range(PASES):
             print 'PASS %s/%s' % (i, PASES)
             test_changelog_walk(repo, pages=80)
--- a/kallithea/tests/test.ini	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/test.ini	Fri Nov 18 01:11:13 2016 +0100
@@ -2,7 +2,6 @@
 ################################################################################
 # Kallithea - config for tests:                                                #
 # initial_repo_scan = true                                                     #
-# vcs_full_cache = false                                                       #
 # sqlalchemy and kallithea_test.sqlite                                         #
 # custom logging                                                               #
 #                                                                              #
@@ -54,32 +53,31 @@
 #error_email_from = paste_error@example.com
 
 ## SMTP server settings
-## Only smtp_server is mandatory. All other settings take the specified default
-## values.
+## If specifying credentials, make sure to use secure connections.
+## Default: Send unencrypted unauthenticated mails to the specified smtp_server.
+## For "SSL", use smtp_use_ssl = true and smtp_port = 465.
+## For "STARTTLS", use smtp_use_tls = true and smtp_port = 587.
 #smtp_server = smtp.example.com
 #smtp_username =
 #smtp_password =
 #smtp_port = 25
+#smtp_use_ssl = false
 #smtp_use_tls = false
-#smtp_use_ssl = false
-## SMTP authentication parameters to use (e.g. LOGIN PLAIN CRAM-MD5, etc.).
-## If empty, use any of the authentication parameters supported by the server.
-#smtp_auth =
 
 [server:main]
 ## PASTE ##
 #use = egg:Paste#http
 ## nr of worker threads to spawn
-#threadpool_workers = 5
+#threadpool_workers = 1
 ## max request before thread respawn
-#threadpool_max_requests = 10
+#threadpool_max_requests = 100
 ## option to use threads of process
 #use_threadpool = true
 
 ## WAITRESS ##
 use = egg:waitress#main
 ## number of worker threads
-threads = 5
+threads = 1
 ## MAX BODY SIZE 100GB
 max_request_body_size = 107374182400
 ## use poll instead of select, fixes fd limits, may not work on old
@@ -97,7 +95,7 @@
 ## recommended for bigger setup is using of of other than sync one
 #worker_class = sync
 #max_requests = 1000
-## ammount of time a worker can handle request before it gets killed and
+## amount of time a worker can handle request before it gets killed and
 ## restarted
 #timeout = 3600
 
@@ -163,6 +161,7 @@
 
 ## COMMON ##
 host = 127.0.0.1
+#port = 5000
 port = 4999
 
 ## middleware for hosting the WSGI application under a URL prefix
@@ -180,8 +179,10 @@
 ## Available Languages:
 ## cs de fr hu ja nl_BE pl pt_BR ru sk zh_CN zh_TW
 lang =
-cache_dir = %(here)s/data
-index_dir = %(here)s/data/index
+#cache_dir = %(here)s/data
+cache_dir = %(here)s/../../data/test/cache
+#index_dir = %(here)s/data/index
+index_dir = %(here)s/../../data/test/index
 
 ## perform a full repository scan on each server start, this should be
 ## set to false after first startup, to allow faster server restarts.
@@ -189,7 +190,8 @@
 initial_repo_scan = true
 
 ## uncomment and set this path to use archive download cache
-archive_cache_dir = %(here)s/tarballcache
+#archive_cache_dir = %(here)s/tarballcache
+archive_cache_dir = %(here)s/../../data/test/tarballcache
 
 ## change this to unique ID for security
 app_instance_uuid = test
@@ -197,10 +199,6 @@
 ## cut off limit for large diffs (size in bytes)
 cut_off_limit = 256000
 
-## use cache version of scm repo everywhere
-#vcs_full_cache = true
-vcs_full_cache = false
-
 ## force https in Kallithea, fixes https redirects, assumes it's always https
 force_https = false
 
@@ -224,8 +222,14 @@
 
 ## options for showing and identifying changesets
 show_sha_length = 12
+#show_revision_number = false
 show_revision_number = true
 
+## Canonical URL to use when creating full URLs in UI and texts.
+## Useful when the site is available under different names or protocols.
+## Defaults to what is provided in the WSGI environment.
+#canonical_url = https://kallithea.example.com/repos
+
 ## gist URL alias, used to create nicer urls for gist. This should be an
 ## url that does rewrites to _admin/gists/<gistid>.
 ## example: http://gist.example.com/{gistid}. Empty means use the internal
@@ -245,7 +249,7 @@
 #    FilesController:archivefile
 
 ## default encoding used to convert from and to unicode
-## can be also a comma seperated list of encoding in case of mixed encodings
+## can be also a comma separated list of encoding in case of mixed encodings
 default_encoding = utf8
 
 ## issue tracker for Kallithea (leave blank to disable, absent for default)
@@ -280,12 +284,6 @@
 #issue_server_link_wiki = https://wiki.example.com/{id}
 #issue_prefix_wiki = WIKI-
 
-## instance-id prefix
-## a prefix key for this instance used for cache invalidation when running
-## multiple instances of kallithea, make sure it's globally unique for
-## all running kallithea instances. Leave empty if you don't use it
-instance_id =
-
 ## alternative return HTTP header for failed authentication. Default HTTP
 ## response is 401 HTTPUnauthorized. Currently Mercurial clients have trouble with
 ## handling that. Set this variable to 403 to return HTTPForbidden
@@ -301,19 +299,29 @@
 ## allows to setup custom hooks in settings page
 allow_custom_hooks_settings = True
 
+## extra extensions for indexing, space separated and without the leading '.'.
+# index.extensions =
+#    gemfile
+#    lock
+
+## extra filenames for indexing, space separated
+# index.filenames =
+#    .dockerignore
+#    .editorconfig
+#    INSTALL
+#    CHANGELOG
+
 ####################################
 ###        CELERY CONFIG        ####
 ####################################
 
 use_celery = false
-broker.host = localhost
-broker.vhost = rabbitmqhost
-broker.port = 5672
-broker.user = rabbitmq
-broker.password = qweqwe
+
+## Example: connect to the virtual host 'rabbitmqhost' on localhost as rabbitmq:
+broker.url = amqp://rabbitmq:qewqew@localhost:5672/rabbitmqhost
 
 celery.imports = kallithea.lib.celerylib.tasks
-
+celery.accept.content = pickle
 celery.result.backend = amqp
 celery.result.dburi = amqp://
 celery.result.serialier = json
@@ -322,19 +330,19 @@
 #celery.amqp.task.result.expires = 18000
 
 celeryd.concurrency = 2
-#celeryd.log.file = celeryd.log
-celeryd.log.level = DEBUG
 celeryd.max.tasks.per.child = 1
 
-## tasks will never be sent to the queue, but executed locally instead.
+## If true, tasks will never be sent to the queue, but executed locally instead.
 celery.always.eager = false
 
 ####################################
 ###         BEAKER CACHE        ####
 ####################################
 
-beaker.cache.data_dir = %(here)s/data/cache/data
-beaker.cache.lock_dir = %(here)s/data/cache/lock
+#beaker.cache.data_dir = %(here)s/data/cache/data
+beaker.cache.data_dir = %(here)s/../../data/test/cache/data
+#beaker.cache.lock_dir = %(here)s/data/cache/lock
+beaker.cache.lock_dir = %(here)s/../../data/test/cache/lock
 
 beaker.cache.regions = short_term,long_term,sql_cache_short
 
@@ -347,6 +355,7 @@
 beaker.cache.long_term.key_length = 256
 
 beaker.cache.sql_cache_short.type = memory
+#beaker.cache.sql_cache_short.expire = 10
 beaker.cache.sql_cache_short.expire = 1
 beaker.cache.sql_cache_short.key_length = 256
 
@@ -422,7 +431,7 @@
 ## (saves API quota for intensive logging)
 errormator.logging_on_error = false
 
-## list of additonal keywords that should be grabbed from environ object
+## list of additional keywords that should be grabbed from environ object
 ## can be string with comma separated list of words in lowercase
 ## (by default client will always send following info:
 ## 'REMOTE_USER', 'REMOTE_ADDR', 'SERVER_NAME', 'CONTENT_TYPE' + all keys that
@@ -479,20 +488,26 @@
 #########################################################
 
 # SQLITE [default]
-#sqlalchemy.db1.url = sqlite:///%(here)s/kallithea.db?timeout=60
-sqlalchemy.db1.url = sqlite:///%(here)s/kallithea_test.sqlite
+#sqlalchemy.url = sqlite:///%(here)s/kallithea.db?timeout=60
+sqlalchemy.url = sqlite:///%(here)s/kallithea_test.sqlite
 
 # POSTGRESQL
-#sqlalchemy.db1.url = postgresql://user:pass@localhost/kallithea
+#sqlalchemy.url = postgresql://user:pass@localhost/kallithea
 
 # MySQL
-#sqlalchemy.db1.url = mysql://user:pass@localhost/kallithea
+#sqlalchemy.url = mysql://user:pass@localhost/kallithea?charset=utf8
 
 # see sqlalchemy docs for others
 
-sqlalchemy.db1.echo = false
-sqlalchemy.db1.pool_recycle = 3600
-sqlalchemy.db1.convert_unicode = true
+sqlalchemy.echo = false
+sqlalchemy.pool_recycle = 3600
+
+################################
+### ALEMBIC CONFIGURATION   ####
+################################
+
+[alembic]
+script_location = kallithea:alembic
 
 ################################
 ### LOGGING CONFIGURATION   ####
@@ -512,8 +527,7 @@
 #############
 
 [logger_root]
-#level = NOTSET
-level = DEBUG
+level = NOTSET
 handlers = console
 
 [logger_routes]
@@ -542,10 +556,8 @@
 propagate = 1
 
 [logger_sqlalchemy]
-#level = INFO
-#handlers = console_sql
-level = ERROR
-handlers = console
+level = INFO
+handlers = console_sql
 qualname = sqlalchemy.engine
 propagate = 0
 
@@ -563,14 +575,16 @@
 class = StreamHandler
 args = (sys.stderr,)
 #level = INFO
-level = NOTSET
-formatter = generic
+level = DEBUG
+#formatter = generic
+formatter = color_formatter
 
 [handler_console_sql]
 class = StreamHandler
 args = (sys.stderr,)
 level = WARN
-formatter = generic
+#formatter = generic
+formatter = color_formatter_sql
 
 ################
 ## FORMATTERS ##
--- a/kallithea/tests/vcs/__init__.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/vcs/__init__.py	Fri Nov 18 01:11:13 2016 +0100
@@ -23,7 +23,7 @@
 from kallithea.tests.vcs.conf import *
 from kallithea.tests.vcs.utils import SCMFetcher
 
-from kallithea.tests import *
+from kallithea.tests.base import *
 
 
 def setup_package():
--- a/kallithea/tests/vcs/conf.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/vcs/conf.py	Fri Nov 18 01:11:13 2016 +0100
@@ -8,7 +8,6 @@
 import datetime
 import shutil
 import uuid
-from os.path import join as jn
 
 __all__ = (
     'TEST_HG_REPO', 'TEST_GIT_REPO', 'HG_REMOTE_REPO', 'GIT_REMOTE_REPO',
@@ -22,21 +21,21 @@
 
 GIT_REMOTE_REPO = 'git://github.com/codeinn/vcs.git'
 
-TEST_TMP_PATH = os.environ.get('VCS_TEST_ROOT', '/tmp')
+TEST_TMP_PATH = os.environ.get('VCS_TEST_ROOT', tempfile.gettempdir())
 TEST_GIT_REPO = os.environ.get('VCS_TEST_GIT_REPO',
-                              jn(TEST_TMP_PATH, 'vcs-git'))
+                               os.path.join(TEST_TMP_PATH, 'vcs-git'))
 TEST_GIT_REPO_CLONE = os.environ.get('VCS_TEST_GIT_REPO_CLONE',
-                            jn(TEST_TMP_PATH, 'vcsgitclone%s' % uniq_suffix))
+                                     os.path.join(TEST_TMP_PATH, 'vcsgitclone%s' % uniq_suffix))
 TEST_GIT_REPO_PULL = os.environ.get('VCS_TEST_GIT_REPO_PULL',
-                            jn(TEST_TMP_PATH, 'vcsgitpull%s' % uniq_suffix))
+                                    os.path.join(TEST_TMP_PATH, 'vcsgitpull%s' % uniq_suffix))
 
 HG_REMOTE_REPO = 'http://bitbucket.org/marcinkuzminski/vcs'
 TEST_HG_REPO = os.environ.get('VCS_TEST_HG_REPO',
-                              jn(TEST_TMP_PATH, 'vcs-hg'))
+                              os.path.join(TEST_TMP_PATH, 'vcs-hg'))
 TEST_HG_REPO_CLONE = os.environ.get('VCS_TEST_HG_REPO_CLONE',
-                              jn(TEST_TMP_PATH, 'vcshgclone%s' % uniq_suffix))
+                                    os.path.join(TEST_TMP_PATH, 'vcshgclone%s' % uniq_suffix))
 TEST_HG_REPO_PULL = os.environ.get('VCS_TEST_HG_REPO_PULL',
-                              jn(TEST_TMP_PATH, 'vcshgpull%s' % uniq_suffix))
+                                   os.path.join(TEST_TMP_PATH, 'vcshgpull%s' % uniq_suffix))
 
 TEST_DIR = os.environ.get('VCS_TEST_ROOT', tempfile.gettempdir())
 TEST_REPO_PREFIX = 'vcs-test'
@@ -80,9 +79,9 @@
 
 PACKAGE_DIR = os.path.abspath(os.path.join(
     os.path.dirname(__file__), '..'))
-_dest = jn(TEST_TMP_PATH, 'aconfig')
-shutil.copy(jn(THIS, 'aconfig'), _dest)
+_dest = os.path.join(TEST_TMP_PATH, 'aconfig')
+shutil.copy(os.path.join(THIS, 'aconfig'), _dest)
 TEST_USER_CONFIG_FILE = _dest
 
 #overide default configurations with kallithea ones
-from kallithea.tests import *
+from kallithea.tests.base import *
--- a/kallithea/tests/vcs/test_archives.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/vcs/test_archives.py	Fri Nov 18 01:11:13 2016 +0100
@@ -74,12 +74,12 @@
 
     def test_archive_default_stream(self):
         tmppath = tempfile.mkstemp()[1]
-        with open(tmppath, 'w') as stream:
+        with open(tmppath, 'wb') as stream:
             self.tip.fill_archive(stream=stream)
         mystream = StringIO.StringIO()
         self.tip.fill_archive(stream=mystream)
         mystream.seek(0)
-        with open(tmppath, 'r') as f:
+        with open(tmppath, 'rb') as f:
             self.assertEqual(f.read(), mystream.read())
 
     def test_archive_wrong_kind(self):
--- a/kallithea/tests/vcs/test_git.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/vcs/test_git.py	Fri Nov 18 01:11:13 2016 +0100
@@ -4,6 +4,10 @@
 import mock
 import datetime
 import urllib2
+import tempfile
+
+import pytest
+
 from kallithea.lib.vcs.backends.git import GitRepository, GitChangeset
 from kallithea.lib.vcs.exceptions import RepositoryError, VCSError, NodeDoesNotExistError
 from kallithea.lib.vcs.nodes import NodeKind, FileNode, DirNode, NodeState
@@ -17,7 +21,7 @@
 
     def __check_for_existing_repo(self):
         if os.path.exists(TEST_GIT_REPO_CLONE):
-            self.fail('Cannot test git clone repo as location %s already '
+            pytest.fail('Cannot test git clone repo as location %s already '
                       'exists. You should manually remove it first.'
                       % TEST_GIT_REPO_CLONE)
 
@@ -25,7 +29,7 @@
         self.repo = GitRepository(TEST_GIT_REPO)
 
     def test_wrong_repo_path(self):
-        wrong_repo_path = '/tmp/errorrepo'
+        wrong_repo_path = os.path.join(tempfile.gettempdir(), 'errorrepo')
         self.assertRaises(RepositoryError, GitRepository, wrong_repo_path)
 
     def test_git_cmd_injection(self):
@@ -42,7 +46,8 @@
         # Verify correct quoting of evil characters that should work on posix file systems
         if sys.platform == 'win32':
             # windows does not allow '"' in dir names
-            tricky_path = get_new_dir("tricky-path-repo-$'`")
+            # and some versions of the git client don't like ` and '
+            tricky_path = get_new_dir("tricky-path-repo-$")
         else:
             tricky_path = get_new_dir("tricky-path-repo-$'\"`")
         successfully_cloned = GitRepository(tricky_path, src_url=TEST_GIT_REPO, update_after_clone=True, create=True)
@@ -51,7 +56,8 @@
 
         if sys.platform == 'win32':
             # windows does not allow '"' in dir names
-            tricky_path_2 = get_new_dir("tricky-path-2-repo-$'`")
+            # and some versions of the git client don't like ` and '
+            tricky_path_2 = get_new_dir("tricky-path-2-repo-$")
         else:
             tricky_path_2 = get_new_dir("tricky-path-2-repo-$'\"`")
         successfully_cloned2 = GitRepository(tricky_path_2, src_url=tricky_path, bare=True, create=True)
@@ -303,8 +309,8 @@
         self.assertTrue(api is chset.get_node('docs/api'))
         index = api.get_node('index.rst')
         self.assertTrue(index is chset.get_node('docs/api/index.rst'))
-        self.assertTrue(index is chset.get_node('docs')\
-            .get_node('api')\
+        self.assertTrue(index is chset.get_node('docs') \
+            .get_node('api') \
             .get_node('index.rst'))
 
     def test_branch_and_tags(self):
@@ -339,7 +345,7 @@
             idx += 1
             rev_id = self.repo.revisions[rev]
             if idx > limit:
-                self.fail("Exceeded limit already (getting revision %s, "
+                pytest.fail("Exceeded limit already (getting revision %s, "
                     "there are %s total revisions, offset=%s, limit=%s)"
                     % (rev_id, count, offset, limit))
             self.assertEqual(changeset, self.repo.get_changeset(rev_id))
@@ -347,7 +353,7 @@
         start = offset
         end = limit and offset + limit or None
         sliced = list(self.repo[start:end])
-        self.failUnlessEqual(result, sliced,
+        pytest.failUnlessEqual(result, sliced,
             msg="Comparison failed for limit=%s, offset=%s"
             "(get_changeset returned: %s and sliced: %s"
             % (limit, offset, result, sliced))
@@ -551,8 +557,8 @@
         """
         Tests state of FileNodes.
         """
-        node = self.repo\
-            .get_changeset('e6ea6d16e2f26250124a1f4b4fe37a912f9d86a0')\
+        node = self.repo \
+            .get_changeset('e6ea6d16e2f26250124a1f4b4fe37a912f9d86a0') \
             .get_node('vcs/utils/diffs.py')
         self.assertTrue(node.state, NodeState.ADDED)
         self.assertTrue(node.added)
@@ -560,8 +566,8 @@
         self.assertFalse(node.not_changed)
         self.assertFalse(node.removed)
 
-        node = self.repo\
-            .get_changeset('33fa3223355104431402a888fa77a4e9956feb3e')\
+        node = self.repo \
+            .get_changeset('33fa3223355104431402a888fa77a4e9956feb3e') \
             .get_node('.hgignore')
         self.assertTrue(node.state, NodeState.CHANGED)
         self.assertFalse(node.added)
@@ -569,8 +575,8 @@
         self.assertFalse(node.not_changed)
         self.assertFalse(node.removed)
 
-        node = self.repo\
-            .get_changeset('e29b67bd158580fc90fc5e9111240b90e6e86064')\
+        node = self.repo \
+            .get_changeset('e29b67bd158580fc90fc5e9111240b90e6e86064') \
             .get_node('setup.py')
         self.assertTrue(node.state, NodeState.NOT_CHANGED)
         self.assertFalse(node.added)
@@ -615,24 +621,24 @@
 
     def test_author_email(self):
         self.assertEqual('marcin@python-blog.com',
-          self.repo.get_changeset('c1214f7e79e02fc37156ff215cd71275450cffc3')\
+          self.repo.get_changeset('c1214f7e79e02fc37156ff215cd71275450cffc3') \
           .author_email)
         self.assertEqual('lukasz.balcerzak@python-center.pl',
-          self.repo.get_changeset('ff7ca51e58c505fec0dd2491de52c622bb7a806b')\
+          self.repo.get_changeset('ff7ca51e58c505fec0dd2491de52c622bb7a806b') \
           .author_email)
-        self.assertEqual('none@none',
-          self.repo.get_changeset('8430a588b43b5d6da365400117c89400326e7992')\
+        self.assertEqual('',
+          self.repo.get_changeset('8430a588b43b5d6da365400117c89400326e7992') \
           .author_email)
 
     def test_author_username(self):
         self.assertEqual('Marcin Kuzminski',
-          self.repo.get_changeset('c1214f7e79e02fc37156ff215cd71275450cffc3')\
+          self.repo.get_changeset('c1214f7e79e02fc37156ff215cd71275450cffc3') \
           .author_name)
         self.assertEqual('Lukasz Balcerzak',
-          self.repo.get_changeset('ff7ca51e58c505fec0dd2491de52c622bb7a806b')\
+          self.repo.get_changeset('ff7ca51e58c505fec0dd2491de52c622bb7a806b') \
           .author_name)
-        self.assertEqual('marcink',
-          self.repo.get_changeset('8430a588b43b5d6da365400117c89400326e7992')\
+        self.assertEqual('marcink none@none',
+          self.repo.get_changeset('8430a588b43b5d6da365400117c89400326e7992') \
           .author_name)
 
 
@@ -784,7 +790,7 @@
         # Create a dictionary where keys are hook names, and values are paths to
         # them. Deduplicates code in tests a bit.
         self.hook_directory = self.repo.get_hook_location()
-        self.kallithea_hooks = {h: os.path.join(self.hook_directory, h) for h in ("pre-receive", "post-receive")}
+        self.kallithea_hooks = dict((h, os.path.join(self.hook_directory, h)) for h in ("pre-receive", "post-receive"))
 
     def test_hooks_created_if_missing(self):
         """
--- a/kallithea/tests/vcs/test_hg.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/vcs/test_hg.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,5 +1,10 @@
 
 import os
+
+import pytest
+
+import tempfile
+from kallithea.lib.utils2 import safe_str
 from kallithea.lib.vcs.backends.hg import MercurialRepository, MercurialChangeset
 from kallithea.lib.vcs.exceptions import RepositoryError, VCSError, NodeDoesNotExistError
 from kallithea.lib.vcs.nodes import NodeKind, NodeState
@@ -19,15 +24,15 @@
 
     def __check_for_existing_repo(self):
         if os.path.exists(TEST_HG_REPO_CLONE):
-            self.fail('Cannot test mercurial clone repo as location %s already '
+            pytest.fail('Cannot test mercurial clone repo as location %s already '
                       'exists. You should manually remove it first.'
                       % TEST_HG_REPO_CLONE)
 
     def setUp(self):
-        self.repo = MercurialRepository(TEST_HG_REPO)
+        self.repo = MercurialRepository(safe_str(TEST_HG_REPO))
 
     def test_wrong_repo_path(self):
-        wrong_repo_path = '/tmp/errorrepo'
+        wrong_repo_path = os.path.join(tempfile.gettempdir(), 'errorrepo')
         self.assertRaises(RepositoryError, MercurialRepository, wrong_repo_path)
 
     def test_unicode_path_repo(self):
@@ -35,7 +40,7 @@
 
     def test_repo_clone(self):
         self.__check_for_existing_repo()
-        repo = MercurialRepository(TEST_HG_REPO)
+        repo = MercurialRepository(safe_str(TEST_HG_REPO))
         repo_clone = MercurialRepository(TEST_HG_REPO_CLONE,
             src_url=TEST_HG_REPO, update_after_clone=True)
         self.assertEqual(len(repo.revisions), len(repo_clone.revisions))
@@ -45,7 +50,7 @@
             self.assertEqual(raw_id, repo_clone.get_changeset(raw_id).raw_id)
 
     def test_repo_clone_with_update(self):
-        repo = MercurialRepository(TEST_HG_REPO)
+        repo = MercurialRepository(safe_str(TEST_HG_REPO))
         repo_clone = MercurialRepository(TEST_HG_REPO_CLONE + '_w_update',
             src_url=TEST_HG_REPO, update_after_clone=True)
         self.assertEqual(len(repo.revisions), len(repo_clone.revisions))
@@ -56,7 +61,7 @@
                                                     'MANIFEST.in')), True,)
 
     def test_repo_clone_without_update(self):
-        repo = MercurialRepository(TEST_HG_REPO)
+        repo = MercurialRepository(safe_str(TEST_HG_REPO))
         repo_clone = MercurialRepository(TEST_HG_REPO_CLONE + '_wo_update',
             src_url=TEST_HG_REPO, update_after_clone=False)
         self.assertEqual(len(repo.revisions), len(repo_clone.revisions))
@@ -66,7 +71,7 @@
 
     def test_pull(self):
         if os.path.exists(TEST_HG_REPO_PULL):
-            self.fail('Cannot test mercurial pull command as location %s '
+            pytest.fail('Cannot test mercurial pull command as location %s '
                       'already exists. You should manually remove it first'
                       % TEST_HG_REPO_PULL)
         repo_new = MercurialRepository(TEST_HG_REPO_PULL, create=True)
@@ -242,7 +247,7 @@
 class MercurialChangesetTest(unittest.TestCase):
 
     def setUp(self):
-        self.repo = MercurialRepository(TEST_HG_REPO)
+        self.repo = MercurialRepository(safe_str(TEST_HG_REPO))
 
     def _test_equality(self, changeset):
         revision = changeset.revision
@@ -302,8 +307,8 @@
         self.assertTrue(api is chset.get_node('docs/api'))
         index = api.get_node('index.rst')
         self.assertTrue(index is chset.get_node('docs/api/index.rst'))
-        self.assertTrue(index is chset.get_node('docs')\
-            .get_node('api')\
+        self.assertTrue(index is chset.get_node('docs') \
+            .get_node('api') \
             .get_node('index.rst'))
 
     def test_branch_and_tags(self):
--- a/kallithea/tests/vcs/test_nodes.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/vcs/test_nodes.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,5 +1,6 @@
 
 import stat
+import mimetypes
 from kallithea.lib.vcs.nodes import DirNode
 from kallithea.lib.vcs.nodes import FileNode
 from kallithea.lib.vcs.nodes import Node
@@ -12,7 +13,7 @@
 
     def test_init(self):
         """
-        Cannot innitialize Node objects with path with slash at the beginning.
+        Cannot initialize Node objects with path with slash at the beginning.
         """
         wrong_paths = (
             '/foo',
@@ -76,7 +77,7 @@
     '''
     def _test_trailing_slash(self, path):
         if not path.endswith('/'):
-            self.fail("Trailing slash tests needs paths to end with slash")
+            pytest.fail("Trailing slash tests needs paths to end with slash")
         for kind in NodeKind.FILE, NodeKind.DIR:
             self.assertRaises(NodeError, Node, path=path, kind=kind)
 
@@ -159,11 +160,11 @@
         my_node3 = FileNode('myfile3')
         my_node3._mimetype = [ext,ext]
 
-        self.assertEqual(py_node.mimetype,'text/x-python')
-        self.assertEqual(py_node.get_mimetype(),('text/x-python',None))
+        self.assertEqual(py_node.mimetype, mimetypes.guess_type(py_node.name)[0])
+        self.assertEqual(py_node.get_mimetype(), mimetypes.guess_type(py_node.name))
 
-        self.assertEqual(tar_node.mimetype,'application/x-tar')
-        self.assertEqual(tar_node.get_mimetype(),('application/x-tar','gzip'))
+        self.assertEqual(tar_node.mimetype, mimetypes.guess_type(tar_node.name)[0])
+        self.assertEqual(tar_node.get_mimetype(), mimetypes.guess_type(tar_node.name))
 
         self.assertRaises(NodeError,my_node2.get_mimetype)
 
--- a/kallithea/tests/vcs/test_utils.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/vcs/test_utils.py	Fri Nov 18 01:11:13 2016 +0100
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
 
 import os
 import mock
@@ -204,6 +205,8 @@
                    ('justname', '')),
                   ('Mr Double Name withemail@example.com ',
                    ('Mr Double Name', 'withemail@example.com')),
+                  (u'John Doe <джондо à éẋàṁṗłê.ç°ḿ>',
+                   (u'John Doe <\u0434\u0436\u043e\u043d\u0434\u043e \xe0 \xe9\u1e8b\xe0\u1e41\u1e57\u0142\xea.\xe7\xb0\u1e3f>', '')),
                   ]
 
     def test_author_email(self):
--- a/kallithea/tests/vcs/test_utils_filesize.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/vcs/test_utils_filesize.py	Fri Nov 18 01:11:13 2016 +0100
@@ -17,7 +17,7 @@
     def test_gigabytes(self):
         self.assertEqual(filesizeformat(1024 * 1024 * 1024 * 12.92), '12.92 GB')
 
-    def test_that_function_respects_sep_paramtere(self):
+    def test_that_function_respects_sep_parameter(self):
         self.assertEqual(filesizeformat(1, ''), '1B')
 
 
--- a/kallithea/tests/vcs/test_vcs.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/vcs/test_vcs.py	Fri Nov 18 01:11:13 2016 +0100
@@ -2,6 +2,7 @@
 import os
 import shutil
 
+from kallithea.lib.utils2 import safe_str
 from kallithea.lib.vcs import VCSError, get_repo, get_backend
 from kallithea.lib.vcs.backends.hg import MercurialRepository
 from kallithea.lib.vcs.utils.compat import unittest
@@ -22,14 +23,14 @@
         alias = 'hg'
         path = TEST_HG_REPO
         backend = get_backend(alias)
-        repo = backend(path)
+        repo = backend(safe_str(path))
         self.assertEqual('hg',repo.alias)
 
     def test_alias_detect_git(self):
         alias = 'git'
         path = TEST_GIT_REPO
         backend = get_backend(alias)
-        repo = backend(path)
+        repo = backend(safe_str(path))
         self.assertEqual('git',repo.alias)
 
     def test_wrong_alias(self):
@@ -40,28 +41,28 @@
         alias = 'hg'
         path = TEST_HG_REPO
         backend = get_backend(alias)
-        repo = backend(path)
+        repo = backend(safe_str(path))
 
-        self.assertEqual(repo.__class__, get_repo(path, alias).__class__)
-        self.assertEqual(repo.path, get_repo(path, alias).path)
+        self.assertEqual(repo.__class__, get_repo(safe_str(path), alias).__class__)
+        self.assertEqual(repo.path, get_repo(safe_str(path), alias).path)
 
     def test_get_repo_autoalias_hg(self):
         alias = 'hg'
         path = TEST_HG_REPO
         backend = get_backend(alias)
-        repo = backend(path)
+        repo = backend(safe_str(path))
 
-        self.assertEqual(repo.__class__, get_repo(path).__class__)
-        self.assertEqual(repo.path, get_repo(path).path)
+        self.assertEqual(repo.__class__, get_repo(safe_str(path)).__class__)
+        self.assertEqual(repo.path, get_repo(safe_str(path)).path)
 
     def test_get_repo_autoalias_git(self):
         alias = 'git'
         path = TEST_GIT_REPO
         backend = get_backend(alias)
-        repo = backend(path)
+        repo = backend(safe_str(path))
 
-        self.assertEqual(repo.__class__, get_repo(path).__class__)
-        self.assertEqual(repo.path, get_repo(path).path)
+        self.assertEqual(repo.__class__, get_repo(safe_str(path)).__class__)
+        self.assertEqual(repo.path, get_repo(safe_str(path)).path)
 
 
     def test_get_repo_err(self):
--- a/kallithea/tests/vcs/test_workdirs.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/tests/vcs/test_workdirs.py	Fri Nov 18 01:11:13 2016 +0100
@@ -63,7 +63,7 @@
         self.repo.workdir.checkout_branch('foobar')
         self.assertEqual(self.repo.workdir.get_changeset(), head)
 
-        # Make sure that old head is still there after update to defualt branch
+        # Make sure that old head is still there after update to default branch
         self.repo.workdir.checkout_branch(self.default_branch)
         self.assertEqual(self.repo.workdir.get_changeset(), old_head)
 
--- a/kallithea/websetup.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/kallithea/websetup.py	Fri Nov 18 01:11:13 2016 +0100
@@ -37,11 +37,10 @@
 
 def setup_app(command, conf, vars):
     """Place any commands to setup kallithea here"""
-    dbconf = conf['sqlalchemy.db1.url']
+    dbconf = conf['sqlalchemy.url']
     dbmanage = DbManage(log_sql=True, dbconf=dbconf, root=conf['here'],
                         tests=False, cli_args=command.options.__dict__)
     dbmanage.create_tables(override=True)
-    dbmanage.set_db_version()
     opts = dbmanage.config_prompt(None)
     dbmanage.create_settings(opts)
     dbmanage.create_default_user()
@@ -49,5 +48,4 @@
     dbmanage.create_permissions()
     dbmanage.populate_default_permissions()
     Session().commit()
-    load_environment(conf.global_conf, conf.local_conf, initial=True)
-    DbManage.check_waitress()
+    load_environment(conf.global_conf, conf.local_conf)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pytest.ini	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,9 @@
+[pytest]
+# only look for tests in kallithea/tests
+python_files = kallithea/tests/**/test_*.py
+addopts =
+    # --verbose
+    # show extra test summary info as specified by chars (f)ailed, (E)error, (s)skipped, (x)failed, (X)passed, (w)warnings.
+    -rfEsxXw
+    # Shorter scrollbacks; less stuff to scroll through
+    --tb=short
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/dbmigrate-test	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,122 @@
+#!/bin/sh -e
+
+if [ $# -lt 2 ] || [ $# -gt 3 ]; then
+    cat >&2 <<EOD
+usage: $0 CONFIG_FILE FROM_REV [TO_REV]
+
+Runs a database migration from FROM_REV to TO_REV (default: current
+working directory parent), using the specified CONFIG_FILE (.ini file).
+
+Test is run using a clean Kallithea install, in a temporary virtual
+environment. FROM_REV and (optional) TO_REV should be Mercurial revision
+identifiers (e.g. changeset hash or a version number tag). The working
+directory is not touched, but the database referenced in the config file
+will be (re)created.
+
+Only SQLite is available out of the box; for MySQL or PostgreSQL, set
+the EXTRA environment variable to the required package(s), and it'll
+be installed in the virtual environment. (E.g. EXTRA=MySQL-python or
+EXTRA=psycopg2.)
+
+The temporary directory is not removed, allowing follow-up examination
+of the upgrade results. It is, however, created in /tmp by default,
+which many Linux distributions automatically clean at regular intervals.
+EOD
+    exit 1
+fi
+
+config_file=$(readlink -f "$1")
+from_rev=$2
+to_rev=$3
+source_repo=$(dirname "$(dirname "$(readlink -f "$0")")")
+
+announce() {
+    echo
+    echo "$1"
+    echo
+}
+
+quiet_if_ok() (
+    local output
+    local st
+    set +e
+    output=$("$@" < /dev/null 2>&1)
+    st=$?
+    if [ $st -ne 0 ]; then
+        echo "$output" >&2
+        echo "Command $@ returned exit status $st." >&2
+        exit 1
+    fi
+)
+
+HG() {
+    "${HG:-hg}" --repository "$source_repo" "$@"
+}
+
+# If upgrading to "current revision", warn if working directory is dirty.
+if [ ! "$to_rev" ] && [ "$(HG status -mard)" ]; then
+    announce "Warning: Uncommitted changes in working directory will be ignored!"
+fi
+
+from_rev_hash=$(HG id --id --rev "${from_rev:-.}")
+to_rev_hash=$(HG id --id --rev "${to_rev:-.}")
+temp=$(readlink -f "$(mktemp --tmpdir -d 'dbmigrate-test.XXXXXX')")
+
+cat <<EOD
+Config file:    $config_file
+EOD
+sed -n -e 's/^sqlalchemy\.url *= */Database URL:   /p' "$config_file"
+cat <<EOD
+Working dir:    $temp
+Repository:     $source_repo
+Upgrade from:   $from_rev_hash (${from_rev:-current})
+Upgrade to:     $to_rev_hash (${to_rev:-current})
+Extra packages: ${EXTRA:-(none)}
+EOD
+
+mkdir "$temp/repos" # empty
+
+# Enable caching for old pip versions (this will cache the pip upgrade)
+# Newer pip versions cache automatically, and don't use this variable.
+if [ ! "$PIP_DOWNLOAD_CACHE" ]; then
+    export PIP_DOWNLOAD_CACHE=$HOME/.cache/pip/legacy
+fi
+
+install_kallithea() {
+    local prefix=$1
+    local rev=$2
+
+    announce "Installing Kallithea $rev in $prefix..."
+
+    "${VIRTUALENV:-virtualenv}" --quiet "$prefix-env"
+    HG archive --rev "$rev" "$prefix"
+
+    (
+        cd "$prefix"
+        . "$prefix-env/bin/activate"
+        pip install --quiet --upgrade pip setuptools mercurial $EXTRA
+        pip install --quiet -e .
+    )
+}
+
+install_kallithea "$temp/from" "$from_rev_hash"
+(
+    cd "$temp/from"
+    . "$temp/from-env/bin/activate"
+    announce "Initializing database..."
+    quiet_if_ok paster setup-db "$config_file" --repos="$temp/repos" --user=doe --email=doe@example.com --password=123456 --no-public-access --force-yes
+    alembic -c "$config_file" current -v
+)
+
+install_kallithea "$temp/to" "$to_rev_hash"
+(
+    cd "$temp/to"
+    . "$temp/to-env/bin/activate"
+
+    announce "Commencing database upgrade from shown Alembic revision to head..."
+    alembic -c "$config_file" current -v
+    alembic -c "$config_file" upgrade head
+    announce "Upgrade complete, now at the shown Alembic revision:"
+    alembic -c "$config_file" current -v
+)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/docs-headings.py	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,79 @@
+#!/usr/bin/env python2
+
+"""
+Consistent formatting of rst section titles
+"""
+
+import re
+import subprocess
+
+spaces = [
+    (0, 1), # we assume this is a over-and-underlined header
+    (2, 1),
+    (1, 1),
+    (1, 0),
+    (1, 0),
+    ]
+
+# http://sphinx-doc.org/rest.html :
+#   for the Python documentation, this convention is used which you may follow:
+#   # with overline, for parts
+#   * with overline, for chapters
+#   =, for sections
+#   -, for subsections
+#   ^, for subsubsections
+#   ", for paragraphs
+pystyles = ['#', '*', '=', '-', '^', '"']
+
+# match on a header line underlined with one of the valid characters
+headermatch = re.compile(r'''\n*(.+)\n([][!"#$%&'()*+,./:;<=>?@\\^_`{|}~-])\2{2,}\n+''', flags=re.MULTILINE)
+
+
+def main():
+    for fn in subprocess.check_output(['hg', 'loc', 'set:**.rst+kallithea/i18n/how_to']).splitlines():
+        print 'processing %s:' % fn
+        s = file(fn).read()
+
+        # find levels and their styles
+        lastpos = 0
+        styles = []
+        for markup in headermatch.findall(s):
+            style = markup[1]
+            if style in styles:
+                stylepos = styles.index(style)
+                if stylepos > lastpos + 1:
+                    print 'bad style %r with level %s - was at %s' % (style, stylepos, lastpos)
+            else:
+                stylepos = len(styles)
+                if stylepos > lastpos + 1:
+                    print 'bad new style %r - expected %r' % (style, styles[lastpos + 1])
+                else:
+                    styles.append(style)
+            lastpos = stylepos
+
+        # remove superfluous spacing (may however be restored by header spacing)
+        s = re.sub(r'''(\n\n)\n*''', r'\1', s, flags=re.MULTILINE)
+
+        if styles:
+            newstyles = pystyles[pystyles.index(styles[0]):]
+
+            def subf(m):
+                title, style = m.groups()
+                level = styles.index(style)
+                before, after = spaces[level]
+                newstyle = newstyles[level]
+                return '\n' * (before + 1) + title + '\n' + newstyle * len(title) + '\n' * (after + 1)
+            s = headermatch.sub(subf, s)
+
+        # remove superfluous spacing when headers are adjacent
+        s = re.sub(r'''(\n.+\n([][!"#$%&'()*+,./:;<=>?@\\^_`{|}~-])\2{2,}\n\n\n)\n*''', r'\1', s, flags=re.MULTILINE)
+        # fix trailing space and spacing before link sections
+        s = s.strip() + '\n'
+        s = re.sub(r'''\n+((?:\.\. _[^\n]*\n)+)$''', r'\n\n\n\1', s)
+
+        file(fn, 'w').write(s)
+        print subprocess.check_output(['hg', 'diff', fn])
+        print
+
+if __name__ == '__main__':
+    main()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/generate-ini.py	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,177 @@
+#!/usr/bin/env python2
+"""
+Based on kallithea/bin/template.ini.mako, generate
+  kallithea/config/deployment.ini_tmpl
+  development.ini
+  kallithea/tests/test.ini
+"""
+
+import re
+
+makofile = 'kallithea/bin/template.ini.mako'
+
+# the mako conditionals used in all other ini files and templates
+selected_mako_conditionals = set([
+    "database_engine == 'sqlite'",
+    "http_server == 'waitress'",
+    "error_aggregation_service == 'errormator'",
+    "error_aggregation_service == 'sentry'",
+])
+
+# the mako variables used in all other ini files and templates
+mako_variable_values = {
+    'host': '127.0.0.1',
+    'port': '5000',
+    'here': '%(here)s',
+    'uuid()': '${app_instance_uuid}',
+}
+
+# files to be generated from the mako template
+ini_files = [
+    ('kallithea/config/deployment.ini_tmpl',
+        '''
+        Kallithea - Example config
+
+        The %(here)s variable will be replaced with the parent directory of this file
+        ''',
+        {}, # exactly the same settings as template.ini.mako
+    ),
+    ('kallithea/tests/test.ini',
+        '''
+        Kallithea - config for tests:
+        initial_repo_scan = true
+        sqlalchemy and kallithea_test.sqlite
+        custom logging
+
+        The %(here)s variable will be replaced with the parent directory of this file
+        ''',
+        {
+            '[server:main]': {
+                'port': '4999',
+            },
+            '[app:main]': {
+                'initial_repo_scan': 'true',
+                'app_instance_uuid': 'test',
+                'show_revision_number': 'true',
+                'beaker.cache.sql_cache_short.expire': '1',
+                'beaker.session.secret': '{74e0cd75-b339-478b-b129-07dd221def1f}',
+                'cache_dir': '%(here)s/../../data/test/cache',
+                'index_dir': '%(here)s/../../data/test/index',
+                'archive_cache_dir': '%(here)s/../../data/test/tarballcache',
+                'beaker.cache.data_dir': '%(here)s/../../data/test/cache/data',
+                'beaker.cache.lock_dir': '%(here)s/../../data/test/cache/lock',
+                'sqlalchemy.url': 'sqlite:///%(here)s/kallithea_test.sqlite',
+            },
+            '[handler_console]': {
+                'level': 'DEBUG',
+                'formatter': 'color_formatter',
+            },
+            # The 'handler_console_sql' block is very similar to the one in
+            # development.ini, but without the explicit 'level=DEBUG' setting:
+            # it causes duplicate sqlalchemy debug logs, one through
+            # handler_console_sql and another through another path.
+            '[handler_console_sql]': {
+                'formatter': 'color_formatter_sql',
+            },
+        },
+    ),
+    ('development.ini',
+        '''
+        Kallithea - Development config:
+        listening on *:5000
+        sqlite and kallithea.db
+        initial_repo_scan = true
+        set debug = true
+        verbose and colorful logging
+
+        The %(here)s variable will be replaced with the parent directory of this file
+        ''',
+        {
+            '[server:main]': {
+                'host': '0.0.0.0',
+            },
+            '[app:main]': {
+                'initial_repo_scan': 'true',
+                'set debug': 'true',
+                'app_instance_uuid': 'development-not-secret',
+                'beaker.session.secret': 'development-not-secret',
+            },
+            '[handler_console]': {
+                'level': 'DEBUG',
+                'formatter': 'color_formatter',
+            },
+            '[handler_console_sql]': {
+                'level': 'DEBUG',
+                'formatter': 'color_formatter_sql',
+            },
+        },
+    ),
+]
+
+
+def main():
+    # make sure all mako lines starting with '#' (the '##' comments) are marked up as <text>
+    print 'reading:', makofile
+    mako_org = file(makofile).read()
+    mako_no_text_markup = re.sub(r'</?%text>', '', mako_org)
+    mako_marked_up = re.sub(r'\n(##.*)', r'\n<%text>\1</%text>', mako_no_text_markup, flags=re.MULTILINE)
+    if mako_marked_up != mako_org:
+        print 'writing:', makofile
+        file(makofile, 'w').write(mako_marked_up)
+
+    # select the right mako conditionals for the other less sophisticated formats
+    def sub_conditionals(m):
+        """given a %if...%endif match, replace with just the selected
+        conditional sections enabled and the rest as comments
+        """
+        conditional_lines = m.group(1)
+        def sub_conditional(m):
+            """given a conditional and the corresponding lines, return them raw
+            or commented out, based on whether conditional is selected
+            """
+            criteria, lines = m.groups()
+            if criteria not in selected_mako_conditionals:
+                lines = '\n'.join((l if not l or l.startswith('#') else '#' + l) for l in lines.split('\n'))
+            return lines
+        conditional_lines = re.sub(r'^%(?:el)?if (.*):\n((?:^[^%\n].*\n|\n)*)',
+            sub_conditional, conditional_lines, flags=re.MULTILINE)
+        return conditional_lines
+    mako_no_conditionals = re.sub(r'^(%if .*\n(?:[^%\n].*\n|%elif .*\n|\n)*)%endif\n',
+        sub_conditionals, mako_no_text_markup, flags=re.MULTILINE)
+
+    # expand mako variables
+    def pyrepl(m):
+        return mako_variable_values.get(m.group(1), m.group(0))
+    mako_no_variables = re.sub(r'\${([^}]*)}', pyrepl, mako_no_conditionals)
+
+    # remove utf-8 coding header
+    base_ini = re.sub(r'^## -\*- coding: utf-8 -\*-\n', '', mako_no_variables)
+
+    # create ini files
+    for fn, desc, settings in ini_files:
+        print 'updating:', fn
+        ini_lines = re.sub(
+            '# Kallithea - config file generated with kallithea-config *#\n',
+            ''.join('# %-77s#\n' % l.strip() for l in desc.strip().split('\n')),
+            base_ini)
+        def process_section(m):
+            """process a ini section, replacing values as necessary"""
+            sectionname, lines = m.groups()
+            if sectionname in settings:
+                section_settings = settings[sectionname]
+                def process_line(m):
+                    """process a section line and update value if necessary"""
+                    setting, value = m.groups()
+                    line = m.group(0)
+                    if setting in section_settings:
+                        line = '%s = %s' % (setting, section_settings[setting])
+                        if '$' not in value:
+                            line = '#%s = %s\n%s' % (setting, value, line)
+                    return line.rstrip()
+                lines = re.sub(r'^([^#\n].*) = ?(.*)', process_line, lines, flags=re.MULTILINE)
+            return sectionname + '\n' + lines
+        ini_lines = re.sub(r'^(\[.*\])\n((?:(?:[^[\n].*)?\n)*)', process_section, ini_lines, flags=re.MULTILINE)
+        file(fn, 'w').write(ini_lines)
+
+if __name__ == '__main__':
+    main()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/logformat.py	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,39 @@
+#!/usr/bin/env python2
+
+import re
+import sys
+
+if len(sys.argv) < 2:
+    print 'Cleanup of superfluous % formatting of log statements.'
+    print 'Usage:'
+    print '''  hg revert `hg loc '*.py'|grep -v logformat.py` && scripts/logformat.py `hg loc '*.py'` && hg diff'''
+    raise SystemExit(1)
+
+
+logre = r'''
+(log\.(?:error|info|warning|debug)
+[(][ \n]*
+)
+%s
+(
+[ \n]*[)]
+)
+'''
+res = [
+    # handle % () - keeping spaces around the old %
+    (re.compile(logre % r'''("[^"]*"|'[^']*')   ([\n ]*) %  ([\n ]*) \( ( (?:[^()]|\n)* (?: \( (?:[^()]|\n)* \) (?:[^()]|\n)* )* ) \) ''', flags=re.MULTILINE|re.VERBOSE), r'\1\2,\3\4\5\6'),
+    # handle % without () - keeping spaces around the old %
+    (re.compile(logre % r'''("[^"]*"|'[^']*')   ([\n ]*) %  ([\n ]*)    ( (?:[^()]|\n)* (?: \( (?:[^()]|\n)* \) (?:[^()]|\n)* )* )    ''', flags=re.MULTILINE|re.VERBOSE), r'\1\2,\3\4\5\6'),
+    # remove extra space if it is on next line
+    (re.compile(logre % r'''("[^"]*"|'[^']*') , (\n [ ]) ([ ][\n ]*)    ( (?:[^()]|\n)* (?: \( (?:[^()]|\n)* \) (?:[^()]|\n)* )* )    ''', flags=re.MULTILINE|re.VERBOSE), r'\1\2,\3\4\5\6'),
+    # remove extra space if it is on same line
+    (re.compile(logre % r'''("[^"]*"|'[^']*') , [ ]+  () (   [\n ]+)    ( (?:[^()]|\n)* (?: \( (?:[^()]|\n)* \) (?:[^()]|\n)* )* )    ''', flags=re.MULTILINE|re.VERBOSE), r'\1\2,\3\4\5\6'),
+    # remove trailing , and space
+    (re.compile(logre % r'''("[^"]*"|'[^']*') ,       () (   [\n ]*)    ( (?:[^()]|\n)* (?: \( (?:[^()]|\n)* \) (?:[^()]|\n)* )* [^(), \n] ) [ ,]*''', flags=re.MULTILINE|re.VERBOSE), r'\1\2,\3\4\5\6'),
+    ]
+
+for f in sys.argv[1:]:
+    s = file(f).read()
+    for r, t in res:
+        s = r.sub(t, s)
+    file(f, 'w').write(s)
--- a/scripts/manifest	Thu Nov 17 13:09:43 2016 +0800
+++ b/scripts/manifest	Fri Nov 18 01:11:13 2016 +0100
@@ -23,7 +23,6 @@
 docs/api/
 docs/api/api.rst
 docs/api/models.rst
-docs/changelog.rst
 docs/conf.py
 docs/contributing.rst
 docs/images/
@@ -640,9 +639,8 @@
 kallithea/public/js/bootstrap.js
 kallithea/public/js/codemirror_loadmode.js
 kallithea/public/js/graph.js
-kallithea/public/js/jquery-1.11.1.min.js
+kallithea/public/js/jquery.min.js
 kallithea/public/js/mergely.js
-kallithea/public/js/mousetrap.js
 kallithea/public/js/native.history.js
 kallithea/public/js/select2/
 kallithea/public/js/select2/select2-bootstrap.css
@@ -918,7 +916,6 @@
 kallithea/tests/other/test_libs.py
 kallithea/tests/other/test_mail.py
 kallithea/tests/other/test_validators.py
-kallithea/tests/parameterized.py
 kallithea/tests/scripts/
 kallithea/tests/scripts/create_rc.sh
 kallithea/tests/scripts/manual_test_concurrency.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/run-all-cleanup	Fri Nov 18 01:11:13 2016 +0100
@@ -0,0 +1,10 @@
+#!/bin/sh
+
+# Convenience script for running various idempotent source code cleanup scripts
+
+set -e
+set -x
+
+scripts/docs-headings.py
+scripts/generate-ini.py
+scripts/whitespacecleanup.sh
--- a/scripts/whitespacecleanup.sh	Thu Nov 17 13:09:43 2016 +0800
+++ b/scripts/whitespacecleanup.sh	Fri Nov 18 01:11:13 2016 +0100
@@ -2,10 +2,11 @@
 
 # Enforce some consistency in whitespace - just to avoid spurious whitespaces changes
 
-files=`hg loc '*.py' '*.html' '*.css' '*.rst' '*.txt' '*.js' '*.ini' '*.cfg' CONTRIBUTORS LICENSE.md| egrep -v '/lockfiles.py|LICENSE-MERGELY.html|/codemirror/|/fontello/|(graph|mergely|native.history|select2/select2|yui.flot|yui.2.9)\.js$'`
+files=`hg loc '*.py' '*.html' '*.css' '*.rst' '*.txt' '*.js' '*.ini' '*.cfg' CONTRIBUTORS LICENSE.md | egrep -v '/lockfiles.py|LICENSE-MERGELY.html|/codemirror/|/fontello/|(graph|mergely|native.history|select2/select2|yui.flot|yui.2.9|jquery.dataTables)\.js$|/email_templates/|/test_dump_html_mails.ref.html'`
 
 sed -i -e "s,`printf '\t'`,    ,g" $files
 sed -i -e "s,  *$,,g" $files
+sed -i -e 's,\([^ ]\)\\$,\1 \\,g' -e 's,\(["'"'"']["'"'"']["'"'"']\) \\$,\1\\,g' $files
 # ensure one trailing newline - remove empty last line and make last line include trailing newline:
 sed -i -e '$,${/^$/d}' -e '$a\' $files
 
@@ -17,6 +18,7 @@
 sed -i -e 's/^\([^ ,/]\+ [^,]*[^ ,]\) *, *\(.\)/\1,\n\2/g' kallithea/public/css/{style,contextbar}.css
 sed -i -e 's/^\([^ ,/].*\)   */\1 /g' kallithea/public/css/{style,contextbar}.css
 sed -i -e 's,^--$,-- ,g' kallithea/templates/email_templates/main.txt
+sed -i -e 's,[ 	][ 	]*$,,g' -e 's, 	,	,g' kallithea/public/js/graph.js
 
 hg mani | xargs chmod -x
 hg loc 'set:!binary()&grep("^#!")&!(**_tmpl.py)&!(**/template**)' | xargs chmod +x
--- a/setup.cfg	Thu Nov 17 13:09:43 2016 +0800
+++ b/setup.cfg	Fri Nov 18 01:11:13 2016 +0100
@@ -3,22 +3,8 @@
 tag_svn_revision = 0
 tag_date = 0
 
-[nosetests]
-verbose = True
-verbosity = 2
-with-pylons = kallithea/tests/test.ini
-detailed-errors = 1
-nologcapture = 1
-
-[pytest]
-# only look for tests in kallithea/tests
-python_files = kallithea/tests/**/test_*.py
-addopts =
-    # --verbose
-    # show extra test summary info as specified by chars (f)ailed, (E)error, (s)skipped, (x)failed, (X)passed, (w)warnings.
-    -rfEsxXw
-    # Shorter scrollbacks; less stuff to scroll through
-    --tb=short
+[aliases]
+test = pytest
 
 [compile_catalog]
 domain = kallithea
--- a/setup.py	Thu Nov 17 13:09:43 2016 +0800
+++ b/setup.py	Fri Nov 18 01:11:13 2016 +0100
@@ -4,7 +4,7 @@
 import sys
 import platform
 
-if sys.version_info < (2, 6):
+if sys.version_info < (2, 6) or sys.version_info >= (3,):
     raise Exception('Kallithea requires python 2.6 or 2.7')
 
 
@@ -35,37 +35,35 @@
 is_windows = __platform__ in ['Windows']
 
 requirements = [
-    "waitress==0.8.8",
+    "alembic>=0.8.0,<0.9",
+    "waitress>=0.8.8,<1.0",
     "webob>=1.0.8,<=1.1.1",
-    "webtest==1.4.3",
     "Pylons>=1.0.0,<=1.0.2",
+    "WebTest<2.0", # make the Pylons dependency pick a version that supports our WebOb version
     "Beaker==1.6.4",
     "WebHelpers==1.3",
     "formencode>=1.2.4,<=1.2.6",
-    "SQLAlchemy==0.7.10",
+    "SQLAlchemy>=1.0,<1.1",
     "Mako>=0.9.0,<=1.0.0",
     "pygments>=1.5",
     "whoosh>=2.4.0,<=2.5.7",
-    "celery>=2.2.5,<2.3",
+    "celery>=3.1,<3.2",
     "babel>=0.9.6,<=1.3",
     "python-dateutil>=1.5.0,<2.0.0",
     "markdown==2.2.1",
     "docutils>=0.8.1,<=0.11",
-    "mock",
     "URLObject==2.3.4",
     "Routes==1.13",
-    "dulwich>=0.9.9,<=0.9.9",
-    "mercurial>=2.9,<3.8",
+    "dulwich>=0.14.1",
+    "mercurial>=2.9,<4.0",
 ]
 
 if sys.version_info < (2, 7):
     requirements.append("importlib==1.0.1")
-    requirements.append("unittest2")
     requirements.append("argparse")
 
 if not is_windows:
-    requirements.append("py-bcrypt>=0.3.0,<=0.4")
-
+    requirements.append("bcrypt>=2.0.0")
 
 dependency_links = [
 ]
@@ -88,9 +86,6 @@
 # relative to sys.prefix
 data_files = []
 
-# additional files that goes into package itself
-package_data = {'kallithea': ['i18n/*/LC_MESSAGES/*.mo', ], }
-
 description = ('Kallithea is a fast and powerful management tool '
                'for Mercurial and Git with a built in push/pull server, '
                'full text search and code-review.')
@@ -103,24 +98,16 @@
 
 # long description
 README_FILE = 'README.rst'
-CHANGELOG_FILE = 'docs/changelog.rst'
 try:
-    long_description = open(README_FILE).read() + '\n\n' + \
-        open(CHANGELOG_FILE).read()
-
+    long_description = open(README_FILE).read()
 except IOError as err:
     sys.stderr.write(
-        "[WARNING] Cannot find file specified as long_description (%s)\n or "
-        "changelog (%s) skipping that file" % (README_FILE, CHANGELOG_FILE)
+        "[WARNING] Cannot find file specified as long_description (%s)\n"
+        % README_FILE
     )
     long_description = description
 
-try:
-    from setuptools import setup, find_packages
-except ImportError:
-    from ez_setup import use_setuptools
-    use_setuptools()
-    from setuptools import setup, find_packages
+import setuptools
 
 # monkey patch setuptools to use distutils owner/group functionality
 from setuptools.command import sdist
@@ -131,10 +118,9 @@
         self.owner = self.group = 'root'
 sdist.sdist = sdist_new
 
-# packages
-packages = find_packages(exclude=['ez_setup'])
+packages = setuptools.find_packages(exclude=['ez_setup'])
 
-setup(
+setuptools.setup(
     name='Kallithea',
     version=__version__,
     description=description,
@@ -147,12 +133,10 @@
     url=__url__,
     install_requires=requirements,
     classifiers=classifiers,
-    setup_requires=["PasteScript>=1.6.3"],
+    setup_requires=['PasteScript>=1.6.3'],
     data_files=data_files,
     packages=packages,
     include_package_data=True,
-    test_suite='nose.collector',
-    package_data=package_data,
     message_extractors={'kallithea': [
             ('**.py', 'python', None),
             ('templates/**.mako', 'mako', {'input_encoding': 'utf-8'}),
@@ -182,10 +166,7 @@
     ishell=kallithea.lib.paster_commands.ishell:Command
     make-index=kallithea.lib.paster_commands.make_index:Command
     upgrade-db=kallithea.lib.dbmigrate:UpgradeDb
-    celeryd=kallithea.lib.celerypylons.commands:CeleryDaemonCommand
+    celeryd=kallithea.lib.paster_commands.celeryd:Command
     install-iis=kallithea.lib.paster_commands.install_iis:Command
-
-    [nose.plugins]
-    pylons = pylons.test:PylonsPlugin
     """,
 )
--- a/tox.ini	Thu Nov 17 13:09:43 2016 +0800
+++ b/tox.ini	Fri Nov 18 01:11:13 2016 +0100
@@ -1,13 +1,14 @@
 [tox]
 minversion = 1.8
-envlist = py{26,27}-{pytest,nose}
+envlist = py{26,27}-pytest
 
 [testenv]
 setenv =
     PYTHONHASHSEED = 0
 deps =
-    nose: nose
-    pytest: pytest
+    -r{toxinidir}/dev_requirements.txt
+    py26-pytest: unittest2
+    python-ldap
+    python-pam
 commands =
-    nose: nosetests {posargs}
     pytest: py.test {posargs}