We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Fix unit display
Since the recent version of Pint, we get problems in HTML display both in docs and in jupyter notebooks. 
This is linked with the "H" format that strangely return non html string. Try some example from the Pint doc
shows the same problem in notebook.  

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `spectrochempy/units/units.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 # ======================================================================================================================
4 #  Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France.                                  =
5 #  CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory                         =
6 # ======================================================================================================================
7 
8 """The core interface to the Pint library
9 
10 """
11 
12 __all__ = ['Unit', 'Quantity', 'ur', 'set_nmr_context', 'DimensionalityError']
13 
14 from warnings import warn
15 
16 from pint import set_application_registry
17 from pint import UnitRegistry, DimensionalityError
18 from pint.unit import UnitsContainer
19 from pint.quantity import _Quantity as Quantity
20 # from pint.measurement import _Measurement as Measure
21 from pint.unit import _Unit as Unit
22 from pint import formatting
23 from pint.formatting import siunitx_format_unit
24 from pint import Context
25 from pint.converters import ScaleConverter
26 from pint.unit import UnitDefinition
27 
28 # ======================================================================================================================
29 # Modify the pint behaviour
30 # ======================================================================================================================
31 #  TODO: better ways ??
32 
33 _PRETTY_EXPONENTS = '⁰¹²³⁴⁵⁶⁷⁸⁹'
34 
35 
36 # ----------------------------------------------------------------------------------------------------------------------
37 def _pretty_fmt_exponent(num):
38     """Format an number into a pretty printed exponent using unicode.
39     """
40     # work badly for decimals as superscript dot do not exist in unicode
41     # (as far as we know)
42     ret = '{0:n}'.format(num).replace('-', '⁻').replace('.', u"\u2027")
43     for n in range(10):
44         ret = ret.replace(str(n), _PRETTY_EXPONENTS[n])
45     return ret
46 
47 
48 formats = {
49     'P': {  # Pretty format.
50         'as_ratio': False,  # True in pint
51         'single_denominator': False,
52         'product_fmt': '·',
53         'division_fmt': '/',
54         'power_fmt': '{}{}',
55         'parentheses_fmt': '({})',
56         'exp_call': _pretty_fmt_exponent,
57     },
58     'L': {  # spectrochempy Latex format.
59         'as_ratio': False,  # True in pint
60         'single_denominator': True,
61         'product_fmt': r' \cdot ',
62         'division_fmt': r'\frac[{}][{}]',
63         'power_fmt': '{}^[{}]',
64         'parentheses_fmt': r'\left({}\right)',
65     },
66     'H': {  # spectrochempy HTML format.
67         'as_ratio': False,  # True in pint
68         'single_denominator': False,
69         'product_fmt': r'.',
70         'division_fmt': r'{}/{}',
71         'power_fmt': '{}<sup>{}</sup>',
72         'parentheses_fmt': r'{}',
73     },
74     'K': {  # spectrochempy Compact format.
75         'as_ratio': False,
76         'single_denominator': False,
77         'product_fmt': '.',
78         'division_fmt': '/',
79         'power_fmt': '{}^{}',
80         'parentheses_fmt': r'({})',
81     },
82 
83 }
84 
85 formatting._FORMATS.update(formats)
86 formatting._KNOWN_TYPES = frozenset(list(formatting._FORMATS.keys()) + ['~'])
87 
88 setattr(Quantity, '_repr_html_', lambda cls: cls.__format__('~H'))
89 setattr(Quantity, '_repr_latex_', lambda cls: "$" + cls.__format__('~L') + "$")
90 
91 # TODO: work on this latex format
92 
93 setattr(Unit, 'scaling', property(lambda u: u._REGISTRY.Quantity(1., u._units).to_base_units().magnitude))
94 
95 
96 # ----------------------------------------------------------------------------------------------------------------------
97 def __format__(self, spec):
98     # modify Pint unit __format__
99 
100     spec = spec or self.default_format
101 
102     # special cases
103     if "Lx" in spec:  # the LaTeX siunitx code
104         return r"\si[]{%s}" % siunitx_format_unit(self)
105 
106     if '~' in spec or 'K' in spec or 'T' in spec or 'L' in spec:  # spectrochempy modified
107         if self.dimensionless and 'absorbance' not in self._units:
108             if self._units == 'ppm':
109                 units = UnitsContainer({'ppm': 1})
110             elif self._units == 'percent':
111                 units = UnitsContainer({'%': 1})
112             elif self._units == 'weight_percent':
113                 units = UnitsContainer({'wt.%': 1})
114             elif self._units == 'radian':
115                 units = UnitsContainer({'rad': 1})
116             elif self._units == 'degree':
117                 units = UnitsContainer({'deg': 1})
118             # elif self._units == 'absorbance':
119             #    units = UnitsContainer({'a.u.': 1})
120             elif abs(self.scaling - 1.) < 1.e-10:
121                 units = UnitsContainer({'': 1})
122             else:
123                 units = UnitsContainer(
124                     {'scaled-dimensionless (%.2g)' % self.scaling: 1})
125         else:
126             units = UnitsContainer(dict((self._REGISTRY._get_symbol(key), value)
127                                         for key, value in list(self._units.items())))
128         spec = spec.replace('~', '')
129     else:
130         units = self._units
131 
132     if "H" in spec:
133         # HTML / Jupyter Notebook
134         return r"\[" + format(units, spec).replace(" ", r"\ ") + r"\]"
135 
136     return '%s' % (format(units, spec))
137 
138 
139 setattr(Unit, '__format__', __format__)
140 
141 if globals().get('U_', None) is None:
142     # filename = resource_filename(PKG, 'spectrochempy.txt')
143     U_ = UnitRegistry(on_redefinition='ignore')  # filename)
144     set_application_registry(U_)
145     U_.enable_contexts('spectroscopy', 'boltzmann', 'chemistry')
146     del UnitRegistry  # to avoid importing it
147 
148 else:
149     warn('Unit registry was already set up. Bypassed the new loading')
150 
151 U_.define('__wrapped__ = 1')  # <- hack to avoid an error with pytest (doctest activated)
152 U_.define('ppm = 1. = ppm')
153 U_.define('absorbance = 1. = a.u.')
154 U_.define('Kubelka_Munk = 1. = K.M.')
155 
156 U_.define(UnitDefinition('percent', 'pct', (), ScaleConverter(1 / 100.0)))
157 U_.define(UnitDefinition('weight_percent', 'wt_pct', (), ScaleConverter(1 / 100.0)))
158 
159 U_.default_format = ''  # .2fK'
160 Q_ = U_.Quantity
161 Q_.default_format = ''  # .2fK'
162 
163 
164 # Context for NMR
165 # ----------------------------------------------------------------------------------------------------------------------
166 
167 def set_nmr_context(larmor):
168     """Set a NMR context relative to the given Larmor frequency
169 
170     Parameters
171     ----------
172     larmor : Quantity or float
173         The Larmor frequency of the current nucleus.
174         If it is not a quantity it is assumed to be given in MHz
175 
176 
177     Examples
178     --------
179 
180     First we set the NMR context,
181 
182     >>> set_nmr_context(104.3 * U_.MHz)
183 
184     then, we can use the context as follow :
185 
186     >>> fhz = 10000 * U_.Hz
187     >>> with U_.context('nmr'):
188     ...    fppm = fhz.to('ppm')
189     >>> print("{:~.3f}".format(fppm))
190     95.877 ppm
191 
192     or in the opposite direction
193 
194     >>> with U_.context('nmr'):
195     ...    fhz = fppm.to('kHz')
196     >>> print("{:~.3f}".format(fhz))
197     10.000 kHz
198 
199     Now we update the context :
200 
201     >>> with U_.context('nmr', larmor=100. * U_.MHz):
202     ...    fppm = fhz.to('ppm')
203     >>> print("{:~.3f}".format(fppm))
204     100.000 ppm
205 
206     >>> set_nmr_context(75 * U_.MHz)
207     >>> fhz = 10000 * U_.Hz
208     >>> with U_.context('nmr'):
209     ...    fppm = fhz.to('ppm')
210     >>> print("{:~.3f}".format(fppm))
211     133.333 ppm
212     """
213 
214     if not isinstance(larmor, U_.Quantity):
215         larmor = larmor * U_.MHz
216 
217     if 'nmr' not in list(U_._contexts.keys()):
218         c = Context('nmr', defaults={'larmor': larmor})
219 
220         c.add_transformation('[]', '[frequency]',
221                              lambda U_, x, **kwargs: x * kwargs.get(
222                                  'larmor') / 1.e6)
223         c.add_transformation('[frequency]', '[]',
224                              lambda U_, x, **kwargs: x * 1.e6 / kwargs.get(
225                                  'larmor'))
226         U_.add_context(c)
227 
228     else:
229 
230         c = U_._contexts['nmr']
231         c.defaults['larmor'] = larmor
232 
233 
234 # set alias for units and uncertainties
235 # ----------------------------------------------------------------------------------------------------------------------
236 ur = U_
237 Quantity = Q_
238 
239 # ======================================================================================================================
240 if __name__ == '__main__':
241     pass
242
```
--- END FILES ---

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

Here is an example:

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

```

diff --git a/spectrochempy/units/units.py b/spectrochempy/units/units.py
--- a/spectrochempy/units/units.py
+++ b/spectrochempy/units/units.py
@@ -39,7 +39,7 @@
     """
     # work badly for decimals as superscript dot do not exist in unicode
     # (as far as we know)
-    ret = '{0:n}'.format(num).replace('-', '⁻').replace('.', u"\u2027")
+    ret = '{0:n}'.format(num).replace('-', '⁻').replace('.', "\u22C5")
     for n in range(10):
         ret = ret.replace(str(n), _PRETTY_EXPONENTS[n])
     return ret
@@ -85,7 +85,14 @@
 formatting._FORMATS.update(formats)
 formatting._KNOWN_TYPES = frozenset(list(formatting._FORMATS.keys()) + ['~'])
 
-setattr(Quantity, '_repr_html_', lambda cls: cls.__format__('~H'))
+def _repr_html_(cls):
+    p = cls.__format__('~H')
+    # attempt to solve a display problem in notebook (recent version of pint
+    # have a strange way to handle HTML. For me it doen't work
+    p = p.replace(r'\[','').replace(r'\]','').replace(r'\ ',' ')
+    return p
+
+setattr(Quantity, '_repr_html_', _repr_html_)
 setattr(Quantity, '_repr_latex_', lambda cls: "$" + cls.__format__('~L') + "$")
 
 # TODO: work on this latex format
@@ -130,7 +137,7 @@
         units = self._units
 
     if "H" in spec:
-        # HTML / Jupyter Notebook
+        # HTML / Jupyter Notebook (
         return r"\[" + format(units, spec).replace(" ", r"\ ") + r"\]"
 
     return '%s' % (format(units, spec))

{"golden_diff": "diff --git a/spectrochempy/units/units.py b/spectrochempy/units/units.py\n--- a/spectrochempy/units/units.py\n+++ b/spectrochempy/units/units.py\n@@ -39,7 +39,7 @@\n     \"\"\"\n     # work badly for decimals as superscript dot do not exist in unicode\n     # (as far as we know)\n-    ret = '{0:n}'.format(num).replace('-', '\u207b').replace('.', u\"\\u2027\")\n+    ret = '{0:n}'.format(num).replace('-', '\u207b').replace('.', \"\\u22C5\")\n     for n in range(10):\n         ret = ret.replace(str(n), _PRETTY_EXPONENTS[n])\n     return ret\n@@ -85,7 +85,14 @@\n formatting._FORMATS.update(formats)\n formatting._KNOWN_TYPES = frozenset(list(formatting._FORMATS.keys()) + ['~'])\n \n-setattr(Quantity, '_repr_html_', lambda cls: cls.__format__('~H'))\n+def _repr_html_(cls):\n+    p = cls.__format__('~H')\n+    # attempt to solve a display problem in notebook (recent version of pint\n+    # have a strange way to handle HTML. For me it doen't work\n+    p = p.replace(r'\\[','').replace(r'\\]','').replace(r'\\ ',' ')\n+    return p\n+\n+setattr(Quantity, '_repr_html_', _repr_html_)\n setattr(Quantity, '_repr_latex_', lambda cls: \"$\" + cls.__format__('~L') + \"$\")\n \n # TODO: work on this latex format\n@@ -130,7 +137,7 @@\n         units = self._units\n \n     if \"H\" in spec:\n-        # HTML / Jupyter Notebook\n+        # HTML / Jupyter Notebook (\n         return r\"\\[\" + format(units, spec).replace(\" \", r\"\\ \") + r\"\\]\"\n \n     return '%s' % (format(units, spec))\n", "issue": "Fix unit display\nSince the recent version of Pint, we get problems in HTML display both in docs and in jupyter notebooks. \r\nThis is linked with the \"H\" format that strangely return non html string. Try some example from the Pint doc\r\nshows the same problem in notebook.  \n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\n# ======================================================================================================================\n#  Copyright (\u00a9) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France.                                  =\n#  CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory                         =\n# ======================================================================================================================\n\n\"\"\"The core interface to the Pint library\n\n\"\"\"\n\n__all__ = ['Unit', 'Quantity', 'ur', 'set_nmr_context', 'DimensionalityError']\n\nfrom warnings import warn\n\nfrom pint import set_application_registry\nfrom pint import UnitRegistry, DimensionalityError\nfrom pint.unit import UnitsContainer\nfrom pint.quantity import _Quantity as Quantity\n# from pint.measurement import _Measurement as Measure\nfrom pint.unit import _Unit as Unit\nfrom pint import formatting\nfrom pint.formatting import siunitx_format_unit\nfrom pint import Context\nfrom pint.converters import ScaleConverter\nfrom pint.unit import UnitDefinition\n\n# ======================================================================================================================\n# Modify the pint behaviour\n# ======================================================================================================================\n#  TODO: better ways ??\n\n_PRETTY_EXPONENTS = '\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079'\n\n\n# ----------------------------------------------------------------------------------------------------------------------\ndef _pretty_fmt_exponent(num):\n    \"\"\"Format an number into a pretty printed exponent using unicode.\n    \"\"\"\n    # work badly for decimals as superscript dot do not exist in unicode\n    # (as far as we know)\n    ret = '{0:n}'.format(num).replace('-', '\u207b').replace('.', u\"\\u2027\")\n    for n in range(10):\n        ret = ret.replace(str(n), _PRETTY_EXPONENTS[n])\n    return ret\n\n\nformats = {\n    'P': {  # Pretty format.\n        'as_ratio': False,  # True in pint\n        'single_denominator': False,\n        'product_fmt': '\u00b7',\n        'division_fmt': '/',\n        'power_fmt': '{}{}',\n        'parentheses_fmt': '({})',\n        'exp_call': _pretty_fmt_exponent,\n    },\n    'L': {  # spectrochempy Latex format.\n        'as_ratio': False,  # True in pint\n        'single_denominator': True,\n        'product_fmt': r' \\cdot ',\n        'division_fmt': r'\\frac[{}][{}]',\n        'power_fmt': '{}^[{}]',\n        'parentheses_fmt': r'\\left({}\\right)',\n    },\n    'H': {  # spectrochempy HTML format.\n        'as_ratio': False,  # True in pint\n        'single_denominator': False,\n        'product_fmt': r'.',\n        'division_fmt': r'{}/{}',\n        'power_fmt': '{}<sup>{}</sup>',\n        'parentheses_fmt': r'{}',\n    },\n    'K': {  # spectrochempy Compact format.\n        'as_ratio': False,\n        'single_denominator': False,\n        'product_fmt': '.',\n        'division_fmt': '/',\n        'power_fmt': '{}^{}',\n        'parentheses_fmt': r'({})',\n    },\n\n}\n\nformatting._FORMATS.update(formats)\nformatting._KNOWN_TYPES = frozenset(list(formatting._FORMATS.keys()) + ['~'])\n\nsetattr(Quantity, '_repr_html_', lambda cls: cls.__format__('~H'))\nsetattr(Quantity, '_repr_latex_', lambda cls: \"$\" + cls.__format__('~L') + \"$\")\n\n# TODO: work on this latex format\n\nsetattr(Unit, 'scaling', property(lambda u: u._REGISTRY.Quantity(1., u._units).to_base_units().magnitude))\n\n\n# ----------------------------------------------------------------------------------------------------------------------\ndef __format__(self, spec):\n    # modify Pint unit __format__\n\n    spec = spec or self.default_format\n\n    # special cases\n    if \"Lx\" in spec:  # the LaTeX siunitx code\n        return r\"\\si[]{%s}\" % siunitx_format_unit(self)\n\n    if '~' in spec or 'K' in spec or 'T' in spec or 'L' in spec:  # spectrochempy modified\n        if self.dimensionless and 'absorbance' not in self._units:\n            if self._units == 'ppm':\n                units = UnitsContainer({'ppm': 1})\n            elif self._units == 'percent':\n                units = UnitsContainer({'%': 1})\n            elif self._units == 'weight_percent':\n                units = UnitsContainer({'wt.%': 1})\n            elif self._units == 'radian':\n                units = UnitsContainer({'rad': 1})\n            elif self._units == 'degree':\n                units = UnitsContainer({'deg': 1})\n            # elif self._units == 'absorbance':\n            #    units = UnitsContainer({'a.u.': 1})\n            elif abs(self.scaling - 1.) < 1.e-10:\n                units = UnitsContainer({'': 1})\n            else:\n                units = UnitsContainer(\n                    {'scaled-dimensionless (%.2g)' % self.scaling: 1})\n        else:\n            units = UnitsContainer(dict((self._REGISTRY._get_symbol(key), value)\n                                        for key, value in list(self._units.items())))\n        spec = spec.replace('~', '')\n    else:\n        units = self._units\n\n    if \"H\" in spec:\n        # HTML / Jupyter Notebook\n        return r\"\\[\" + format(units, spec).replace(\" \", r\"\\ \") + r\"\\]\"\n\n    return '%s' % (format(units, spec))\n\n\nsetattr(Unit, '__format__', __format__)\n\nif globals().get('U_', None) is None:\n    # filename = resource_filename(PKG, 'spectrochempy.txt')\n    U_ = UnitRegistry(on_redefinition='ignore')  # filename)\n    set_application_registry(U_)\n    U_.enable_contexts('spectroscopy', 'boltzmann', 'chemistry')\n    del UnitRegistry  # to avoid importing it\n\nelse:\n    warn('Unit registry was already set up. Bypassed the new loading')\n\nU_.define('__wrapped__ = 1')  # <- hack to avoid an error with pytest (doctest activated)\nU_.define('ppm = 1. = ppm')\nU_.define('absorbance = 1. = a.u.')\nU_.define('Kubelka_Munk = 1. = K.M.')\n\nU_.define(UnitDefinition('percent', 'pct', (), ScaleConverter(1 / 100.0)))\nU_.define(UnitDefinition('weight_percent', 'wt_pct', (), ScaleConverter(1 / 100.0)))\n\nU_.default_format = ''  # .2fK'\nQ_ = U_.Quantity\nQ_.default_format = ''  # .2fK'\n\n\n# Context for NMR\n# ----------------------------------------------------------------------------------------------------------------------\n\ndef set_nmr_context(larmor):\n    \"\"\"Set a NMR context relative to the given Larmor frequency\n\n    Parameters\n    ----------\n    larmor : Quantity or float\n        The Larmor frequency of the current nucleus.\n        If it is not a quantity it is assumed to be given in MHz\n\n\n    Examples\n    --------\n\n    First we set the NMR context,\n\n    >>> set_nmr_context(104.3 * U_.MHz)\n\n    then, we can use the context as follow :\n\n    >>> fhz = 10000 * U_.Hz\n    >>> with U_.context('nmr'):\n    ...    fppm = fhz.to('ppm')\n    >>> print(\"{:~.3f}\".format(fppm))\n    95.877 ppm\n\n    or in the opposite direction\n\n    >>> with U_.context('nmr'):\n    ...    fhz = fppm.to('kHz')\n    >>> print(\"{:~.3f}\".format(fhz))\n    10.000 kHz\n\n    Now we update the context :\n\n    >>> with U_.context('nmr', larmor=100. * U_.MHz):\n    ...    fppm = fhz.to('ppm')\n    >>> print(\"{:~.3f}\".format(fppm))\n    100.000 ppm\n\n    >>> set_nmr_context(75 * U_.MHz)\n    >>> fhz = 10000 * U_.Hz\n    >>> with U_.context('nmr'):\n    ...    fppm = fhz.to('ppm')\n    >>> print(\"{:~.3f}\".format(fppm))\n    133.333 ppm\n    \"\"\"\n\n    if not isinstance(larmor, U_.Quantity):\n        larmor = larmor * U_.MHz\n\n    if 'nmr' not in list(U_._contexts.keys()):\n        c = Context('nmr', defaults={'larmor': larmor})\n\n        c.add_transformation('[]', '[frequency]',\n                             lambda U_, x, **kwargs: x * kwargs.get(\n                                 'larmor') / 1.e6)\n        c.add_transformation('[frequency]', '[]',\n                             lambda U_, x, **kwargs: x * 1.e6 / kwargs.get(\n                                 'larmor'))\n        U_.add_context(c)\n\n    else:\n\n        c = U_._contexts['nmr']\n        c.defaults['larmor'] = larmor\n\n\n# set alias for units and uncertainties\n# ----------------------------------------------------------------------------------------------------------------------\nur = U_\nQuantity = Q_\n\n# ======================================================================================================================\nif __name__ == '__main__':\n    pass\n", "path": "spectrochempy/units/units.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\n# ======================================================================================================================\n#  Copyright (\u00a9) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France.                                  =\n#  CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory                         =\n# ======================================================================================================================\n\n\"\"\"The core interface to the Pint library\n\n\"\"\"\n\n__all__ = ['Unit', 'Quantity', 'ur', 'set_nmr_context', 'DimensionalityError']\n\nfrom warnings import warn\n\nfrom pint import set_application_registry\nfrom pint import UnitRegistry, DimensionalityError\nfrom pint.unit import UnitsContainer\nfrom pint.quantity import _Quantity as Quantity\n# from pint.measurement import _Measurement as Measure\nfrom pint.unit import _Unit as Unit\nfrom pint import formatting\nfrom pint.formatting import siunitx_format_unit\nfrom pint import Context\nfrom pint.converters import ScaleConverter\nfrom pint.unit import UnitDefinition\n\n# ======================================================================================================================\n# Modify the pint behaviour\n# ======================================================================================================================\n#  TODO: better ways ??\n\n_PRETTY_EXPONENTS = '\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079'\n\n\n# ----------------------------------------------------------------------------------------------------------------------\ndef _pretty_fmt_exponent(num):\n    \"\"\"Format an number into a pretty printed exponent using unicode.\n    \"\"\"\n    # work badly for decimals as superscript dot do not exist in unicode\n    # (as far as we know)\n    ret = '{0:n}'.format(num).replace('-', '\u207b').replace('.', \"\\u22C5\")\n    for n in range(10):\n        ret = ret.replace(str(n), _PRETTY_EXPONENTS[n])\n    return ret\n\n\nformats = {\n    'P': {  # Pretty format.\n        'as_ratio': False,  # True in pint\n        'single_denominator': False,\n        'product_fmt': '\u00b7',\n        'division_fmt': '/',\n        'power_fmt': '{}{}',\n        'parentheses_fmt': '({})',\n        'exp_call': _pretty_fmt_exponent,\n    },\n    'L': {  # spectrochempy Latex format.\n        'as_ratio': False,  # True in pint\n        'single_denominator': True,\n        'product_fmt': r' \\cdot ',\n        'division_fmt': r'\\frac[{}][{}]',\n        'power_fmt': '{}^[{}]',\n        'parentheses_fmt': r'\\left({}\\right)',\n    },\n    'H': {  # spectrochempy HTML format.\n        'as_ratio': False,  # True in pint\n        'single_denominator': False,\n        'product_fmt': r'.',\n        'division_fmt': r'{}/{}',\n        'power_fmt': '{}<sup>{}</sup>',\n        'parentheses_fmt': r'{}',\n    },\n    'K': {  # spectrochempy Compact format.\n        'as_ratio': False,\n        'single_denominator': False,\n        'product_fmt': '.',\n        'division_fmt': '/',\n        'power_fmt': '{}^{}',\n        'parentheses_fmt': r'({})',\n    },\n\n}\n\nformatting._FORMATS.update(formats)\nformatting._KNOWN_TYPES = frozenset(list(formatting._FORMATS.keys()) + ['~'])\n\ndef _repr_html_(cls):\n    p = cls.__format__('~H')\n    # attempt to solve a display problem in notebook (recent version of pint\n    # have a strange way to handle HTML. For me it doen't work\n    p = p.replace(r'\\[','').replace(r'\\]','').replace(r'\\ ',' ')\n    return p\n\nsetattr(Quantity, '_repr_html_', _repr_html_)\nsetattr(Quantity, '_repr_latex_', lambda cls: \"$\" + cls.__format__('~L') + \"$\")\n\n# TODO: work on this latex format\n\nsetattr(Unit, 'scaling', property(lambda u: u._REGISTRY.Quantity(1., u._units).to_base_units().magnitude))\n\n\n# ----------------------------------------------------------------------------------------------------------------------\ndef __format__(self, spec):\n    # modify Pint unit __format__\n\n    spec = spec or self.default_format\n\n    # special cases\n    if \"Lx\" in spec:  # the LaTeX siunitx code\n        return r\"\\si[]{%s}\" % siunitx_format_unit(self)\n\n    if '~' in spec or 'K' in spec or 'T' in spec or 'L' in spec:  # spectrochempy modified\n        if self.dimensionless and 'absorbance' not in self._units:\n            if self._units == 'ppm':\n                units = UnitsContainer({'ppm': 1})\n            elif self._units == 'percent':\n                units = UnitsContainer({'%': 1})\n            elif self._units == 'weight_percent':\n                units = UnitsContainer({'wt.%': 1})\n            elif self._units == 'radian':\n                units = UnitsContainer({'rad': 1})\n            elif self._units == 'degree':\n                units = UnitsContainer({'deg': 1})\n            # elif self._units == 'absorbance':\n            #    units = UnitsContainer({'a.u.': 1})\n            elif abs(self.scaling - 1.) < 1.e-10:\n                units = UnitsContainer({'': 1})\n            else:\n                units = UnitsContainer(\n                    {'scaled-dimensionless (%.2g)' % self.scaling: 1})\n        else:\n            units = UnitsContainer(dict((self._REGISTRY._get_symbol(key), value)\n                                        for key, value in list(self._units.items())))\n        spec = spec.replace('~', '')\n    else:\n        units = self._units\n\n    if \"H\" in spec:\n        # HTML / Jupyter Notebook (\n        return r\"\\[\" + format(units, spec).replace(\" \", r\"\\ \") + r\"\\]\"\n\n    return '%s' % (format(units, spec))\n\n\nsetattr(Unit, '__format__', __format__)\n\nif globals().get('U_', None) is None:\n    # filename = resource_filename(PKG, 'spectrochempy.txt')\n    U_ = UnitRegistry(on_redefinition='ignore')  # filename)\n    set_application_registry(U_)\n    U_.enable_contexts('spectroscopy', 'boltzmann', 'chemistry')\n    del UnitRegistry  # to avoid importing it\n\nelse:\n    warn('Unit registry was already set up. Bypassed the new loading')\n\nU_.define('__wrapped__ = 1')  # <- hack to avoid an error with pytest (doctest activated)\nU_.define('ppm = 1. = ppm')\nU_.define('absorbance = 1. = a.u.')\nU_.define('Kubelka_Munk = 1. = K.M.')\n\nU_.define(UnitDefinition('percent', 'pct', (), ScaleConverter(1 / 100.0)))\nU_.define(UnitDefinition('weight_percent', 'wt_pct', (), ScaleConverter(1 / 100.0)))\n\nU_.default_format = ''  # .2fK'\nQ_ = U_.Quantity\nQ_.default_format = ''  # .2fK'\n\n\n# Context for NMR\n# ----------------------------------------------------------------------------------------------------------------------\n\ndef set_nmr_context(larmor):\n    \"\"\"Set a NMR context relative to the given Larmor frequency\n\n    Parameters\n    ----------\n    larmor : Quantity or float\n        The Larmor frequency of the current nucleus.\n        If it is not a quantity it is assumed to be given in MHz\n\n\n    Examples\n    --------\n\n    First we set the NMR context,\n\n    >>> set_nmr_context(104.3 * U_.MHz)\n\n    then, we can use the context as follow :\n\n    >>> fhz = 10000 * U_.Hz\n    >>> with U_.context('nmr'):\n    ...    fppm = fhz.to('ppm')\n    >>> print(\"{:~.3f}\".format(fppm))\n    95.877 ppm\n\n    or in the opposite direction\n\n    >>> with U_.context('nmr'):\n    ...    fhz = fppm.to('kHz')\n    >>> print(\"{:~.3f}\".format(fhz))\n    10.000 kHz\n\n    Now we update the context :\n\n    >>> with U_.context('nmr', larmor=100. * U_.MHz):\n    ...    fppm = fhz.to('ppm')\n    >>> print(\"{:~.3f}\".format(fppm))\n    100.000 ppm\n\n    >>> set_nmr_context(75 * U_.MHz)\n    >>> fhz = 10000 * U_.Hz\n    >>> with U_.context('nmr'):\n    ...    fppm = fhz.to('ppm')\n    >>> print(\"{:~.3f}\".format(fppm))\n    133.333 ppm\n    \"\"\"\n\n    if not isinstance(larmor, U_.Quantity):\n        larmor = larmor * U_.MHz\n\n    if 'nmr' not in list(U_._contexts.keys()):\n        c = Context('nmr', defaults={'larmor': larmor})\n\n        c.add_transformation('[]', '[frequency]',\n                             lambda U_, x, **kwargs: x * kwargs.get(\n                                 'larmor') / 1.e6)\n        c.add_transformation('[frequency]', '[]',\n                             lambda U_, x, **kwargs: x * 1.e6 / kwargs.get(\n                                 'larmor'))\n        U_.add_context(c)\n\n    else:\n\n        c = U_._contexts['nmr']\n        c.defaults['larmor'] = larmor\n\n\n# set alias for units and uncertainties\n# ----------------------------------------------------------------------------------------------------------------------\nur = U_\nQuantity = Q_\n\n# ======================================================================================================================\nif __name__ == '__main__':\n    pass\n", "path": "spectrochempy/units/units.py"}]}