code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
ax1, ax2, axm = x1 * hunit, x2 * hunit, (x1 + x2) * hunit / 2 ay1, ay2 = y1 * vunit, y2 * vunit return pyx.path.curve(ax1, ay1, axm, ay1, axm, ay2, ax2, ay2)
def _curve(x1, y1, x2, y2, hunit = HUNIT, vunit = VUNIT)
Return a PyX curved path from (x1, y1) to (x2, y2), such that the slope at either end is zero.
2.531197
2.280457
1.109952
if direction == 'lr': hunit = abs(hunit) elif direction == 'rl': hunit = -abs(hunit) try: c, dims, c_in, c_out = draw_circuit_canvas(circuit, hunit = hunit, vunit = vunit, rhmargin = rhmargin, rvmargin = rvmargin, ...
def draw_circuit(circuit, filename, direction = 'lr', hunit = HUNIT, vunit = VUNIT, rhmargin = RHMARGIN, rvmargin = RVMARGIN, rpermutation_length = RPLENGTH, draw_boxes = True, permutation_arrows = False)
Generate a graphic representation of circuit and store them in a file. The graphics format is determined from the file extension. :param circuit: The circuit expression :type circuit: ca.Circuit :param filename: A filepath to store the output image under. The file name suffix determines the output grap...
3.349252
3.329604
1.005901
if isinstance(container, OrderedDict): return tuple(map(nested_tuple, container.items())) if isinstance(container, Mapping): return tuple(sorted_if_possible(map(nested_tuple, container.items()))) if not isinstance(container, (str, bytes)): if isinstance(container, Sequence): ...
def nested_tuple(container)
Recursively transform a container structure to a nested tuple. The function understands container types inheriting from the selected abstract base classes in `collections.abc`, and performs the following replacements: `Mapping` `tuple` of key-value pair `tuple`s. The order is preserved in the case ...
2.344922
2.291746
1.023203
try: mro = item.__class__.__mro__ except AttributeError: return PRECEDENCE["Atom"] for i in mro: n = i.__name__ if n in PRECEDENCE_FUNCTIONS: return PRECEDENCE_FUNCTIONS[n](item) elif n in PRECEDENCE_VALUES: return PRECEDENCE_VALUES[n] ...
def precedence(item)
Returns the precedence of a given object.
2.887912
2.738851
1.054425
if not self.is_valid_name(div_id): raise ValueError( "Name {} is invalid. Only letters, numbers, '_', and '-' are permitted ".format( div_id)) return Template(head + self.template).render( div_id=div_id.replace(" ", "_"), ...
def render(self, data, chart_type, chart_package='corechart', options=None, div_id="chart", head="")
Render the data in HTML template.
2.783445
2.662494
1.045427
return HTML( self.iframe.format( source=self.render( data=data, options=options, chart_type=chart_type, chart_package=chart_package, head=self.head), w=w, ...
def plot(self, data, chart_type, chart_package='corechart', options=None, w=800, h=420)
Output an iframe containing the plot in the notebook without saving.
3.660965
3.383987
1.08185
protosig = signature(prototype) positional, keyword = [], [] for name, param in protosig.parameters.items(): if param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD): raise TypeError("*args/**kwargs not supported in prototypes") if (param.default is not Parameter....
def callback_prototype(prototype)
Decorator to process a callback prototype. A callback prototype is a function whose signature includes all the values that will be passed by the callback API in question. The original function will be returned, with a ``prototype.adapt`` attribute which can be used to prepare third party callb...
2.696357
2.738855
0.984484
if appsettings.FLUENT_BLOGS_FILTER_SITE_ID: qs = self.parent_site(settings.SITE_ID) else: qs = self if for_user is not None and for_user.is_staff: return qs return qs \ .filter(status=self.model.PUBLISHED) \ .filter( ...
def published(self, for_user=None)
Return only published entries for the current site.
2.813596
2.598665
1.082708
if len(usernames) == 1: return self.filter(**{"author__{}".format(User.USERNAME_FIELD): usernames[0]}) else: return self.filter(**{"author__{}__in".format(User.USERNAME_FIELD): usernames})
def authors(self, *usernames)
Return the entries written by the given usernames When multiple tags are provided, they operate as "OR" query.
2.364539
2.365171
0.999733
categories_field = getattr(self.model, 'categories', None) if categories_field is None: raise AttributeError("The {0} does not include CategoriesEntryMixin".format(self.model.__name__)) if issubclass(categories_field.rel.model, TranslatableModel): # Needs a diff...
def categories(self, *category_slugs)
Return the entries with the given category slugs. When multiple tags are provided, they operate as "OR" query.
4.318259
4.239831
1.018498
if getattr(self.model, 'tags', None) is None: raise AttributeError("The {0} does not include TagsEntryMixin".format(self.model.__name__)) if len(tag_slugs) == 1: return self.filter(tags__slug=tag_slugs[0]) else: return self.filter(tags__slug__in=tag_...
def tagged(self, *tag_slugs)
Return the items which are tagged with a specific tag. When multiple tags are provided, they operate as "OR" query.
2.841756
2.736029
1.038642
mod = sys.modules[__name__] if exclude is None: exclude = [] for (_, submodname, ispkg) in pkgutil.iter_modules(path=__path__): if submodname.startswith('_') and not include_private_modules: continue submod = importlib.import_module('.' + submodname, __name__) ...
def _import_submodules( __all__, __path__, __name__, include=None, exclude=None, include_private_modules=False, require__all__=True, recursive=True)
Import all available submodules, all objects defined in the `__all__` lists of those submodules, and extend `__all__` with the imported objects. Args: __all__ (list): The list of public objects in the "root" module __path__ (str): The path where the ``__init__.py`` file for the "root" ...
1.944791
2.010704
0.967219
name = self.name.format(**kwargs) subs = [] if self.sub is not None: subs = [self.sub.format(**kwargs)] supers = [] if self.sup is not None: supers = [self.sup.format(**kwargs)] return render_unicode_sub_super( name, subs, su...
def format(self, **kwargs)
Format and combine the name, subscript, and superscript
4.153136
3.233064
1.284582
if isinstance(string, StrLabel): string = string._render(string.expr) string = str(string) if len(string) == 0: return '' name, supers, subs = split_super_sub(string) return render_unicode_sub_super( name, subs, supers, sub_first=True,...
def _render_str(self, string)
Returned a unicodified version of the string
7.092535
6.963981
1.01846
if self._settings['unicode_sub_super']: sub_sup_fmt = SubSupFmt else: sub_sup_fmt = SubSupFmtNoUni mapping = { 'bra': { True: sub_sup_fmt('⟨{label}|', sup='({space})'), 'subscript': sub_sup_fmt('⟨{label}|', sub='({space...
def _braket_fmt(self, expr_type)
Return a format string for printing an `expr_type` ket/bra/ketbra/braket
2.205806
2.108032
1.046382
hs_label = None if hs is not None and self._settings['show_hs_label']: hs_label = self._render_hs_label(hs) name, total_subscript, total_superscript, args_str \ = self._split_op(identifier, hs_label, dagger, args) if self._settings['unicode_op_hats'] and ...
def _render_op( self, identifier, hs=None, dagger=False, args=None, superop=False)
Render an operator Args: identifier (str or SymbolicLabelBase): The identifier (name/symbol) of the operator. May include a subscript, denoted by '_'. hs (HilbertSpace): The Hilbert space in which the operator is defined dagger (bool): Whether...
4.827668
5.168282
0.934095
r local_space, states = _get_pauli_args(local_space, states) g, e = states return ( LocalSigma.create(g, e, hs=local_space) + LocalSigma.create(e, g, hs=local_space))
def PauliX(local_space, states=None)
r"""Pauli-type X-operator .. math:: \hat{\sigma}_x = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} on an arbitrary two-level system. Args: local_space (str or int or .LocalSpace): Associated Hilbert space. If :class:`str` or :class:`int`, a :cla...
7.294221
7.76089
0.939869
r local_space, states = _get_pauli_args(local_space, states) g, e = states return I * (-LocalSigma.create(g, e, hs=local_space) + LocalSigma.create(e, g, hs=local_space))
def PauliY(local_space, states=None)
r""" Pauli-type Y-operator .. math:: \hat{\sigma}_x = \begin{pmatrix} 0 & -i \\ i & 0 \end{pmatrix} on an arbitrary two-level system. See :func:`PauliX`
7.418113
9.415597
0.787854
r local_space, states = _get_pauli_args(local_space, states) g, e = states return ( LocalProjector(g, hs=local_space) - LocalProjector(e, hs=local_space))
def PauliZ(local_space, states=None)
r"""Pauli-type Z-operator .. math:: \hat{\sigma}_x = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix} on an arbitrary two-level system. See :func:`PauliX`
8.521803
10.70907
0.795756
head_repr_fmt = r'{head}({args}{kwargs})' if sub_render is None: sub_render = render_head_repr if key_sub_render is None: key_sub_render = sub_render if isinstance(expr.__class__, Singleton): # We exploit that Singletons override __expr__ to directly return # their n...
def render_head_repr( expr: Any, sub_render=None, key_sub_render=None) -> str
Render a textual representation of `expr` using Positional and keyword arguments are recursively rendered using `sub_render`, which defaults to `render_head_repr` by default. If desired, a different renderer may be used for keyword arguments by giving `key_sub_renderer` Raises: AttributeEr...
2.704605
2.604356
1.038493
from qnet.algebra.pattern_matching import Pattern, ProtoExpr if hasattr(rules, 'items'): items = rules.items() # `rules` is already a dict / OrderedDict else: items = rules # `rules` is a list of (key, value) tuples keys = set() for key_rule in items: try: ...
def check_rules_dict(rules)
Verify the `rules` that classes may use for the `_rules` or `_binary_rules` class attribute. Specifically, `rules` must be a :class:`~collections.OrderedDict`-compatible object (list of key-value tuples, :class:`dict`, :class:`~collections.OrderedDict`) that maps a rule name (:class:`str`) to a...
2.811206
2.419887
1.16171
r_pos = -1 p_pos = -1 numerator = S.Zero denom_sq = S.One post_factors = [] if isinstance(expr, Mul): for pos, factor in enumerate(expr.args): if isinstance(factor, Rational) and r_pos < 0: r_pos = pos numerator, denom_sq = factor.p, facto...
def derationalize_denom(expr)
Try to de-rationalize the denominator of the given expression. The purpose is to allow to reconstruct e.g. ``1/sqrt(2)`` from ``sqrt(2)/2``. Specifically, this matches `expr` against the following pattern:: Mul(..., Rational(n, d), Pow(d, Rational(1, 2)), ...) and returns a tuple ``(numerato...
2.73822
2.525811
1.084095
# Since there is currently no filtering in place, return all entries. EntryModel = get_entry_model() qs = get_entry_model().objects.order_by('-publication_date') # Only limit to current language when this makes sense. if issubclass(EntryModel, TranslatableModel): ...
def entries(self)
Return the entries that are published under this node.
9.181276
8.228783
1.115751
# It could be possible this page is fetched as fallback, while the 'entry' does have a translation. # - Currently django-fluent-pages 1.0b3 `Page.objects.get_for_path()` assigns the language of retrieval # as current object language. The page is not assigned a fallback language instea...
def get_entry_url(self, entry)
Return the URL of a blog entry, relative to this page.
16.393766
15.612768
1.050023
return Placeholder.objects.create_for_object(self, slot, role=role, title=title)
def create_placeholder(self, slot="blog_contents", role='m', title=None)
Create a placeholder on this blog entry. To fill the content items, use :func:`ContentItemModel.objects.create_for_placeholder() <fluent_contents.models.managers.ContentItemManager.create_for_placeholder>`. :rtype: :class:`~fluent_contents.models.Placeholder`
4.212912
3.749213
1.123679
# TODO: filter appsettings.FLUENT_BLOGS_FILTER_SITE_ID: # filters.setdefault('parent_site', self.parent_site_id) # FIXME: Using super() doesn't work, calling directly. return TagsMixin.similar_objects(self, num=num, **filters)
def similar_objects(self, num=None, **filters)
Find similar objects using related tags.
13.049902
11.86208
1.100136
self.driver.set_window_size(width, height) self.driver.get('file://{path}/{filename}'.format( path=os.getcwd(), filename=filename + ".html")) time.sleep(render_time) self.driver.save_screenshot(filename + ".png")
def save_as_png(self, filename, width=300, height=250, render_time=1)
Open saved html file in an virtual browser and save a screen shot to PNG format.
2.545261
2.32589
1.094317
with open(filename) as in_fh: for line in in_fh: if line.startswith('__version__'): return line.split('=')[1].strip()[1:-1] raise ValueError("Cannot extract version from %s" % filename)
def get_version(filename)
Extract the package version
2.194806
2.127416
1.031677
if HAS_APP_URLS: from fluent_pages.templatetags.appurl_tags import appurl return appurl(parser, token) else: from django.template.defaulttags import url return url(parser, token)
def blogurl(parser, token)
Compatibility tag to allow django-fluent-blogs to operate stand-alone. Either the app can be hooked in the URLconf directly, or it can be added as a pagetype of django-fluent-pages. For the former, URL resolving works via the normal '{% url "viewname" arg1 arg2 %}' syntax. For the latter, the URL resolving ...
3.752682
2.762948
1.358217
if isinstance(year, (date, datetime)): # Django 1.5 and up, 'year' is a date object, consistent with month+day views. return unicode(year.year) else: # Django 1.4 just passes the kwarg as string. return unicode(year)
def format_year(year)
Format the year value of the ``YearArchiveView``, which can be a integer or date object. This tag is no longer needed, but exists for template compatibility. It was a compatibility tag for Django 1.4.
9.209647
7.857055
1.17215
return set([ sym for sym in self.term.free_symbols if sym not in self.bound_symbols])
def free_symbols(self)
Set of all free symbols
7.220716
6.977091
1.034918
from qnet.algebra.core.scalar_algebra import ScalarValue for mapping in yield_from_ranges(self.ranges): term = self.term.substitute(mapping) if isinstance(term, ScalarValue._val_types): term = ScalarValue.create(term) assert isinstance(term, E...
def terms(self)
Iterator over the terms of the sum Yield from the (possibly) infinite list of terms of the indexed sum, if the sum was written out explicitly. Each yielded term in an instance of :class:`.Expression`
8.139906
8.612868
0.945087
return super().doit( classes, recursive, indices=indices, max_terms=max_terms, **kwargs)
def doit( self, classes=None, recursive=True, indices=None, max_terms=None, **kwargs)
Write out the indexed sum explicitly If `classes` is None or :class:`IndexedSum` is in `classes`, (partially) write out the indexed sum in to an explicit sum of terms. If `recursive` is True, write out each of the new sum's summands by calling its :meth:`doit` method. Args: ...
2.771517
4.018728
0.68965
new = self other_index_symbols = set() for other in others: try: if isinstance(other, IdxSym): other_index_symbols.add(other) elif isinstance(other, IndexRangeBase): other_index_symbols.add(other.index_s...
def make_disjunct_indices(self, *others)
Return a copy with modified indices to ensure disjunct indices with `others`. Each element in `others` may be an index symbol (:class:`.IdxSym`), a index-range object (:class:`.IndexRangeBase`) or list of index-range objects, or an indexed operation (something with a ``ranges`` attribut...
2.941167
2.37109
1.240428
manifesto = CodemirrorAssetTagRender() manifesto.register_from_fields(*args) return mark_safe(manifesto.js_html())
def codemirror_field_js_assets(*args)
Tag to render CodeMirror Javascript assets needed for all given fields. Example: :: {% load djangocodemirror_tags %} {% codemirror_field_js_assets form.myfield1 form.myfield2 %}
19.722502
29.480217
0.669008
manifesto = CodemirrorAssetTagRender() manifesto.register_from_fields(*args) return mark_safe(manifesto.css_html())
def codemirror_field_css_assets(*args)
Tag to render CodeMirror CSS assets needed for all given fields. Example: :: {% load djangocodemirror_tags %} {% codemirror_field_css_assets form.myfield1 form.myfield2 %}
21.561701
29.988668
0.718995
manifesto = CodemirrorAssetTagRender() manifesto.register_from_fields(field) try: bundle_name = manifesto.js_bundle_names()[0] except IndexError: msg = ("Given field with configuration name '{}' does not have a " "Javascript bundle name") raise CodeMirrorFiel...
def codemirror_field_js_bundle(field)
Filter to get CodeMirror Javascript bundle name needed for a single field. Example: :: {% load djangocodemirror_tags %} {{ form.myfield|codemirror_field_js_bundle }} Arguments: field (django.forms.fields.Field): A form field that contains a widget :class:`djangocod...
8.344316
8.218143
1.015353
manifesto = CodemirrorAssetTagRender() manifesto.register_from_fields(field) try: bundle_name = manifesto.css_bundle_names()[0] except IndexError: msg = ("Given field with configuration name '{}' does not have a " "Javascript bundle name") raise CodeMirrorFie...
def codemirror_field_css_bundle(field)
Filter to get CodeMirror CSS bundle name needed for a single field. Example: :: {% load djangocodemirror_tags %} {{ form.myfield|codemirror_field_css_bundle }} Arguments: field (djangocodemirror.fields.CodeMirrorField): A form field. Raises: CodeMirrorFieldBundleE...
9.04211
8.180504
1.105324
manifesto = CodemirrorAssetTagRender() names = manifesto.register_from_fields(field) config = manifesto.get_codemirror_parameters(names[0]) return mark_safe(json.dumps(config))
def codemirror_parameters(field)
Filter to include CodeMirror parameters as a JSON string for a single field. This must be called only on an allready rendered field, meaning you must not use this filter on a field before a form. Else, the field widget won't be correctly initialized. Example: :: {% load django...
13.253112
17.556532
0.754882
output = io.StringIO() manifesto = CodemirrorAssetTagRender() manifesto.register(config_name) if assets: output.write(manifesto.css_html()) output.write(manifesto.js_html()) html = manifesto.codemirror_html(config_name, varname, element_id) output.write(html) content...
def codemirror_instance(config_name, varname, element_id, assets=True)
Return HTML to init a CodeMirror instance for an element. This will output the whole HTML needed to initialize a CodeMirror instance with needed assets loading. Assets can be omitted with the ``assets`` option. Example: :: {% load djangocodemirror_tags %} {% codemirror...
3.734288
4.367821
0.854954
# When filter is used within template we have to reach the field # instance through the BoundField. if hasattr(field, 'field'): widget = field.field.widget # When used out of template, we have a direct field instance else: widget = field.widget ...
def resolve_widget(self, field)
Given a Field or BoundField, return widget instance. Todo: Raise an exception if given field object does not have a widget. Arguments: field (Field or BoundField): A field instance. Returns: django.forms.widgets.Widget: Retrieved widget from giv...
8.767677
8.704395
1.00727
names = [] for field in args: widget = self.resolve_widget(field) self.register(widget.config_name) if widget.config_name not in names: names.append(widget.config_name) return names
def register_from_fields(self, *args)
Register config name from field widgets Arguments: *args: Fields that contains widget :class:`djangocodemirror.widget.CodeMirrorWidget`. Returns: list: List of registered config names from fields.
3.969568
3.18744
1.245378
url = os.path.join(settings.STATIC_URL, path) return tag_template.format(url=url)
def render_asset_html(self, path, tag_template)
Render HTML tag for a given path. Arguments: path (string): Relative path from static directory. tag_template (string): Template string for HTML tag. Returns: string: HTML tag with url from given path.
3.74739
4.510075
0.830893
output = io.StringIO() for item in self.css(): output.write( self.render_asset_html(item, settings.CODEMIRROR_CSS_ASSET_TAG) ) content = output.getvalue() output.close() return content
def css_html(self)
Render HTML tags for Javascript assets. Returns: string: HTML for CSS assets from every registered config.
5.691529
5.316246
1.070592
output = io.StringIO() for item in self.js(): output.write( self.render_asset_html(item, settings.CODEMIRROR_JS_ASSET_TAG) ) content = output.getvalue() output.close() return content
def js_html(self)
Render HTML tags for Javascript assets. Returns: string: HTML for Javascript assets from every registered config.
5.842684
5.353417
1.091393
parameters = json.dumps(self.get_codemirror_parameters(config_name), sort_keys=True) return settings.CODEMIRROR_FIELD_INIT_JS.format( varname=varname, inputid=element_id, settings=parameters, )
def codemirror_html(self, config_name, varname, element_id)
Render HTML for a CodeMirror instance. Since a CodeMirror instance have to be attached to a HTML element, this method requires a HTML element identifier with or without the ``#`` prefix, it depends from template in ``settings.CODEMIRROR_FIELD_INIT_JS`` (default one require to not ...
4.496671
4.442039
1.012299
if site_id is None: site_id = getattr(settings, 'SITE_ID', None) for lang_dict in FLUENT_BLOGS_LANGUAGES.get(site_id, ()): if lang_dict['code'] == language_code: return lang_dict return FLUENT_BLOGS_LANGUAGES['default']
def get_language_settings(language_code, site_id=None)
Return the language settings for the current site
2.766503
2.783089
0.99404
import better_apidoc better_apidoc.main([ 'better-apidoc', '-t', os.path.join('.', '_templates'), '--force', '--no-toc', '--separate', '-o', os.path.join('.', 'API'), os.path.join('..', 'src', 'qnet'), ])
def run_apidoc(_)
Generage API documentation
3.494157
3.554605
0.982995
def short_renderer(expr): res = renderer(expr) if len(res) > max_len: return '...' else: return res return short_renderer
def _shorten_render(renderer, max_len)
Return a modified that returns the representation of expr, or '...' if that representation is longer than `max_len`
4.851703
3.010414
1.61164
from qnet.printing import srepr lines = [] if unicode: draw = {'leaf': '└─ ', 'branch': '├─ ', 'line': '│'} sub_render = _shorten_render_unicode() else: draw = {'leaf': '+- ', 'branch': '+- ', 'line': '|'} sub_render = _shorten_render_ascii() to_str = lambda expr...
def print_tree( expr, attr='operands', padding='', exclude_type=None, depth=None, unicode=True, srepr_leaves=False, _last=False, _root=True, _level=0, _print=True)
Print a tree representation of the structure of `expr` Args: expr (Expression): expression to render attr (str): The attribute from which to get the children of `expr` padding (str): Whitespace by which the entire tree is idented exclude_type (type): Type (or list of types) which sh...
2.011454
2.126432
0.945929
from qnet.algebra.core.hilbert_space_algebra import LocalSpace from qnet.algebra.core.abstract_quantum_algebra import QuantumExpression default_hs_cls = getattr(importlib.import_module('qnet'), default_hs_cls) if issubclass(default_hs_cls, LocalSpace): QuantumExpression._default_hs_cls = de...
def init_algebra(*, default_hs_cls='LocalSpace')
Initialize the algebra system Args: default_hs_cls (str): The name of the :class:`.LocalSpace` subclass that should be used when implicitly creating Hilbert spaces, e.g. in :class:`.OperatorSymbol`
2.916895
3.117373
0.93569
if name not in settings.CODEMIRROR_SETTINGS: msg = ("Given config name '{}' does not exists in " "'settings.CODEMIRROR_SETTINGS'.") raise UnknowConfigError(msg.format(name)) parameters = copy.deepcopy(self.default_internal_config) parameters.u...
def register(self, name)
Register configuration for an editor instance. Arguments: name (string): Config name from available ones in ``settings.CODEMIRROR_SETTINGS``. Raises: UnknowConfigError: If given config name does not exist in ``settings.CODEMIRROR_SETTINGS``. ...
3.040251
2.566712
1.184493
params = [] for name in args: params.append(self.register(name)) return params
def register_many(self, *args)
Register many configuration names. Arguments: *args: Config names as strings. Returns: list: List of registered configs.
5.137889
5.805627
0.884984
if name not in settings.CODEMIRROR_MODES: msg = ("Given config name '{}' does not exists in " "'settings.CODEMIRROR_MODES'.") raise UnknowModeError(msg.format(name)) return settings.CODEMIRROR_MODES.get(name)
def resolve_mode(self, name)
From given mode name, return mode file path from ``settings.CODEMIRROR_MODES`` map. Arguments: name (string): Mode name. Raises: KeyError: When given name does not exist in ``settings.CODEMIRROR_MODES``. Returns: string: Mode file pa...
5.243808
4.116315
1.273908
if name not in settings.CODEMIRROR_THEMES: msg = ("Given theme name '{}' does not exists in " "'settings.CODEMIRROR_THEMES'.") raise UnknowThemeError(msg.format(name)) return settings.CODEMIRROR_THEMES.get(name)
def resolve_theme(self, name)
From given theme name, return theme file path from ``settings.CODEMIRROR_THEMES`` map. Arguments: name (string): Theme name. Raises: KeyError: When given name does not exist in ``settings.CODEMIRROR_THEMES``. Returns: string: Theme f...
4.162176
3.326874
1.251077
if name: if name not in self.registry: msg = "Given config name '{}' is not registered." raise NotRegisteredError(msg.format(name)) return {name: self.registry[name]} return self.registry
def get_configs(self, name=None)
Returns registred configurations. * If ``name`` argument is not given, default behavior is to return every config from all registred config; * If ``name`` argument is given, just return its config and nothing else; Keyword Arguments: name (string): Specific conf...
4.125476
3.453344
1.194632
if name not in self.registry: msg = "Given config name '{}' is not registered." raise NotRegisteredError(msg.format(name)) return copy.deepcopy(self.registry[name])
def get_config(self, name)
Return a registred configuration for given config name. Arguments: name (string): A registred config name. Raises: NotRegisteredError: If given config name does not exist in registry. Returns: dict: Configuration.
4.199461
3.480721
1.206492
config = self.get_config(name) return {k: config[k] for k in config if k not in self._internal_only}
def get_codemirror_parameters(self, name)
Return CodeMirror parameters for given configuration name. This is a reduced configuration from internal parameters. Arguments: name (string): Config name from available ones in ``settings.CODEMIRROR_SETTINGS``. Returns: dict: Parameters.
6.108647
7.485953
0.816015
filepaths = copy.copy(settings.CODEMIRROR_BASE_JS) configs = self.get_configs(name) names = sorted(configs) # Addons first for name in names: opts = configs[name] for item in opts.get('addons', []): if item not in filepaths: ...
def js(self, name=None)
Returns all needed Javascript filepaths for given config name (if given) or every registred config instead (if no name is given). Keyword Arguments: name (string): Specific config name to use instead of all. Returns: list: List of Javascript file paths.
3.829561
3.899051
0.982178
configs = self.get_configs(name) names = [] for k, v in configs.items(): if v.get('js_bundle_name'): names.append(v['js_bundle_name']) return sorted(names)
def js_bundle_names(self, name=None)
Returns all needed Javascript Bundle names for given config name (if given) or every registred config instead (if no name is given). Keyword Arguments: name (string): Specific config name to use instead of all. Returns: list: List of webasset bundle names.
3.022577
3.823735
0.790478
filepaths = copy.copy(settings.CODEMIRROR_BASE_CSS) configs = self.get_configs(name) names = sorted(configs) # Process themes for name in names: opts = configs[name] for item in opts.get('themes', []): resolved = self.resolve_the...
def css(self, name=None)
Returns all needed CSS filepaths for given config name (if given) or every registred config instead (if no name is given). Keyword Arguments: name (string): Specific config name to use instead of all. Returns: list: List of CSS file paths.
3.520325
3.471768
1.013986
if B: return A * B - B * A return SPre(A) - SPost(A)
def commutator(A, B=None)
Commutator of `A` and `B` If ``B != None``, return the commutator :math:`[A,B]`, otherwise return the super-operator :math:`[A,\cdot]`. The super-operator :math:`[A,\cdot]` maps any other operator ``B`` to the commutator :math:`[A, B] = A B - B A`. Args: A: The first operator to form the comm...
7.316834
13.873974
0.527378
if B: return A * B + B * A return SPre(A) + SPost(A)
def anti_commutator(A, B=None)
If ``B != None``, return the anti-commutator :math:`\{A,B\}`, otherwise return the super-operator :math:`\{A,\cdot\}`. The super-operator :math:`\{A,\cdot\}` maps any other operator ``B`` to the anti-commutator :math:`\{A, B\} = A B + B A`. Args: A: The first operator to form all anti-commutat...
8.322902
16.214434
0.513302
r if Ls is None: Ls = [] elif isinstance(Ls, Matrix): Ls = Ls.matrix.ravel().tolist() summands = [-I * commutator(H), ] summands.extend([lindblad(L) for L in Ls]) return SuperOperatorPlus.create(*summands)
def liouvillian(H, Ls=None)
r"""Return the Liouvillian super-operator associated with `H` and `Ls` The Liouvillian :math:`\mathcal{L}` generates the Markovian-dynamics of a system via the Master equation: .. math:: \dot{\rho} = \mathcal{L}\rho = -i[H,\rho] + \sum_{j=1}^n \mathcal{D}[L_j] \rho Args: H...
7.85988
6.385572
1.230881
arr = np_vstack(tuple(m.matrix for m in matrices)) # print(tuple(m.matrix.dtype for m in matrices)) # print(arr.dtype) return Matrix(arr)
def vstackm(matrices)
Generalizes `numpy.vstack` to :class:`Matrix` objects.
4.496117
4.38698
1.024877
r return vstackm((hstackm((A, B)), hstackm((C, D))))
def block_matrix(A, B, C, D)
r"""Generate the operator matrix with quadrants .. math:: \begin{pmatrix} A B \\ C D \end{pmatrix} Args: A (Matrix): Matrix of shape ``(n, m)`` B (Matrix): Matrix of shape ``(n, k)`` C (Matrix): Matrix of shape ``(l, m)`` D (Matrix): Matrix of shape ``(l, k)`` Retu...
9.888873
20.574783
0.480631
r assert check_permutation(permutation) n = len(permutation) op_matrix = np_zeros((n, n), dtype=int) for i, j in enumerate(permutation): op_matrix[j, i] = 1 return Matrix(op_matrix)
def permutation_matrix(permutation)
r"""Return orthogonal permutation matrix for permutation tuple Return an orthogonal permutation matrix :math:`M_\sigma` for a permutation :math:`\sigma` defined by the image tuple :math:`(\sigma(1), \sigma(2),\dots \sigma(n))`, such that .. math:: M_\sigma \vec{e}_i = \vec{e}_{\sigma(i)} ...
3.459185
4.686508
0.738116
n, m = self.shape if n != m: raise AttributeError("block_structure only defined for square " "matrices") for k in range(1, n): if ((self.matrix[:k, k:] == 0).all() and (self.matrix[k:, :k] == 0).all()): ...
def block_structure(self)
For square matrices this gives the block (-diagonal) structure of the matrix as a tuple of integers that sum up to the full dimension. :rtype: tuple
3.433495
3.316503
1.035276
for o in self.matrix.ravel(): try: if not o.is_zero: return False except AttributeError: if not o == 0: return False return True
def is_zero(self)
Are all elements of the matrix zero?
4.653061
3.546281
1.312096
try: return Matrix(np_conjugate(self.matrix)) except AttributeError: raise NoConjugateMatrix( "Matrix %s contains entries that have no defined " "conjugate" % str(self))
def conjugate(self)
The element-wise conjugate matrix This is defined only if all the entries in the matrix have a defined conjugate (i.e., they have a `conjugate` method). This is *not* the case for a matrix of operators. In such a case, only an :meth:`elementwise` :func:`adjoint` would be applicable, but...
6.066411
4.411337
1.375187
def re(val): if hasattr(val, 'real'): return val.real elif hasattr(val, 'as_real_imag'): return val.as_real_imag()[0] elif hasattr(val, 'conjugate'): return (val.conjugate() + val) / 2 else: ...
def real(self)
Element-wise real part Raises: NoConjugateMatrix: if entries have no `conjugate` method and no other way to determine the real part Note: A mathematically equivalent way to obtain a real matrix from a complex matrix ``M`` is:: (M.con...
5.913441
4.597097
1.286343
def im(val): if hasattr(val, 'imag'): return val.imag elif hasattr(val, 'as_real_imag'): return val.as_real_imag()[1] elif hasattr(val, 'conjugate'): return (val.conjugate() - val) / (2 * I) else: ...
def imag(self)
Element-wise imaginary part Raises: NoConjugateMatrix: if entries have no `conjugate` method and no other way to determine the imaginary part Note: A mathematically equivalent way to obtain an imaginary matrix from a complex matrix ``M`` is:: ...
6.467196
4.700335
1.375901
s = self.shape emat = [func(o, *args, **kwargs) for o in self.matrix.ravel()] return Matrix(np_array(emat).reshape(s))
def element_wise(self, func, *args, **kwargs)
Apply a function to each matrix element and return the result in a new operator matrix of the same shape. Args: func (FunctionType): A function to be applied to each element. It must take the element as its first argument. args: Additional positional arguments to...
6.319196
7.033056
0.898499
s = self.shape emats = zip(*[o.series_expand(param, about, order) for o in self.matrix.ravel()]) return tuple((Matrix(np_array(em).reshape(s)) for em in emats))
def series_expand(self, param: Symbol, about, order: int)
Expand the matrix expression as a truncated power series in a scalar parameter. Args: param: Expansion parameter. about (.Scalar): Point about which to expand. order: Maximum order of expansion >= 0 Returns: tuple of length (order+1), where the e...
10.097857
10.527702
0.95917
return self.element_wise( lambda o: o.expand() if isinstance(o, QuantumExpression) else o)
def expand(self)
Expand each matrix element distributively. Returns: Matrix: Expanded matrix.
13.37628
12.07784
1.107506
arg_spaces = [o.space for o in self.matrix.ravel() if hasattr(o, 'space')] if len(arg_spaces) == 0: return TrivialSpace else: return ProductSpace.create(*arg_spaces)
def space(self)
Combined Hilbert space of all matrix elements.
5.650377
5.32664
1.060777
def element_simplify(v): if isinstance(v, sympy.Basic): return func(v) elif isinstance(v, QuantumExpression): return v.simplify_scalar(func=func) else: return v return self.element_wise(element_simplify)
def simplify_scalar(self, func=sympy.simplify)
Simplify all scalar expressions appearing in the Matrix.
3.857057
3.925077
0.98267
initial = {} if self.kwargs.get('mode', None): filename = "{}.txt".format(self.kwargs['mode']) filepath = os.path.join(settings.BASE_DIR, 'demo_datas', filename) if os.path.exists(filepath): with io.open(filepath, 'r', encoding='utf-8') as fp...
def get_initial(self)
Try to find a demo source for given mode if any, if finded use it to fill the demo textarea.
3.056755
2.588469
1.180912
try: # Find the actual database fieldnames for the keyword. db_fieldnames = order_by_fields[orderby] except KeyError: raise ValueError("Invalid value for 'orderby': '{0}', supported values are: {1}".format(orderby, ', '.join(sorted(order_by_fields.keys())))) # Default to descen...
def _get_order_by(order, orderby, order_by_fields)
Return the order by syntax for a model. Checks whether use ascending or descending order, and maps the fieldnames.
4.244335
4.126891
1.028458
if queryset is None: queryset = get_entry_model().objects.all() if appsettings.FLUENT_BLOGS_FILTER_SITE_ID: queryset = queryset.parent_site(settings.SITE_ID) if not future: queryset = queryset.published() if year: queryset = queryset.filter(publication_date__year=...
def query_entries( queryset=None, year=None, month=None, day=None, category=None, category_slug=None, tag=None, tag_slug=None, author=None, author_slug=None, future=False, order=None, orderby=None, limit=None, )
Query the entries using a set of predefined filters. This interface is mainly used by the ``get_entries`` template tag.
1.87486
1.910278
0.981459
from taggit.models import Tag, TaggedItem # feature is still optional # Get queryset filters for published entries EntryModel = get_entry_model() ct = ContentType.objects.get_for_model(EntryModel) # take advantage of local caching. entry_filter = { 'status': EntryModel.PUBLISHED ...
def query_tags(order=None, orderby=None, limit=None)
Query the tags, with usage count included. This interface is mainly used by the ``get_tags`` template tag.
3.638993
3.571617
1.018864
Category = get_category_model() if issubclass(Category, TranslatableModel): return Category.objects.active_translations(language_code, slug=slug).get() else: return Category.objects.get(slug=slug)
def get_category_for_slug(slug, language_code=None)
Find the category for a given slug
3.153759
2.999532
1.051417
if year is None: return None if month is None: # year only start = datetime(year, 1, 1, 0, 0, 0, tzinfo=utc) end = datetime(year, 12, 31, 23, 59, 59, 999, tzinfo=utc) return (start, end) if day is None: # year + month only start = datetime(year,...
def get_date_range(year=None, month=None, day=None)
Return a start..end range to query for a specific month, day or year.
1.661002
1.610255
1.031514
assert isinstance(cls, Singleton), \ cls.__name__ + " must use Singleton metaclass" def self_instantiate(self): return self cls.__call__ = self_instantiate if hasattr(cls, '_hash_val'): cls.__hash__ = lambda self: hash(cls._hash_val) cls.__eq__ = lambda self, other...
def singleton_object(cls)
Class decorator that transforms (and replaces) a class definition (which must have a Singleton metaclass) with the actual singleton object. Ensures that the resulting object can still be "instantiated" (i.e., called), returning the same object. Also ensures the object can be pickled, is hashable, and ha...
2.656776
2.502155
1.061795
if len(args) == 0: args = None if len(kwargs) == 0: kwargs = None return Pattern(head, args, kwargs, mode=mode, wc_name=wc_name, conditions=conditions)
def pattern(head, *args, mode=1, wc_name=None, conditions=None, **kwargs) \ -> Pattern
Flat' constructor for the Pattern class Positional and keyword arguments are mapped into `args` and `kwargs`, respectively. Useful for defining rules that match an instantiated Expression with specific arguments
2.424413
2.404223
1.008398
# This routine is indented for the _rules and _binary_rules class # attributes of algebraic objects, which the match_replace and # match_replace_binary match against a ProtoExpr if len(args) == 0: args = None if len(kwargs) == 0: kwargs = None if wc_name is not None: ...
def pattern_head(*args, conditions=None, wc_name=None, **kwargs) -> Pattern
Constructor for a :class:`Pattern` matching a :class:`ProtoExpr` The patterns associated with :attr:`_rules` and :attr:`_binary_rules` of an :class:`Expression` subclass, or those passed to :meth:`Expression.add_rule`, must be instantiated through this routine. The function does not allow to set a wild...
8.398086
5.900855
1.423198
rx = re.compile(r"^([A-Za-z]?[A-Za-z0-9]*)(_{0,3})$") m = rx.match(name_mode) if not m: raise ValueError("Invalid name_mode: %s" % name_mode) wc_name, mode_underscores = m.groups() if wc_name == '': wc_name = None mode = len(mode_underscores) or Pattern.single return Pat...
def wc(name_mode="_", head=None, args=None, kwargs=None, *, conditions=None) \ -> Pattern
Constructor for a wildcard-:class:`Pattern` Helper function to create a Pattern object with an emphasis on wildcard patterns, if we don't care about the arguments of the matched expressions (otherwise, use :func:`pattern`) Args: name_mode (str): Combined `wc_name` and `mode` for :class:`Patter...
3.595902
3.126324
1.150201
try: # first try expr_or_pattern as a Pattern return expr_or_pattern.match(expr) except AttributeError: # expr_or_pattern is an expr, not a Pattern if expr_or_pattern == expr: return MatchDict() # success else: res = MatchDict() res.success = F...
def match_pattern(expr_or_pattern: object, expr: object) -> MatchDict
Recursively match `expr` with the given `expr_or_pattern` Args: expr_or_pattern: either a direct expression (equal to `expr` for a successful match), or an instance of :class:`Pattern`. expr: the expression to be matched
3.222736
3.355628
0.960397
for other in others: for key, val in other.items(): self[key] = val try: if not other.success: self.success = False self.reason = other.reason except AttributeError: pass
def update(self, *others)
Update dict with entries from `other` If `other` has an attribute ``success=False`` and ``reason``, those attributes are copied as well
3.259269
2.577974
1.264276
for arg in self._arg_iterator(self.args): if isinstance(arg, Pattern): if arg.mode > self.single: while True: yield arg else: yield arg else: yield arg
def extended_arg_patterns(self)
Iterator over patterns for positional arguments to be matched This yields the elements of :attr:`args`, extended by their `mode` value
6.199694
5.591648
1.108742
try: if last_arg_pattern.mode == self.single: raise ValueError("insufficient number of arguments") elif last_arg_pattern.mode == self.zero_or_more: if last_arg_pattern.wc_name is not None: if last_arg_pattern != current_arg_pat...
def _check_last_arg_pattern(self, current_arg_pattern, last_arg_pattern)
Given a "current" arg pattern (that was used to match the last actual argument of an expression), and another ("last") argument pattern, raise a ValueError, unless the "last" argument pattern is a "zero or more" wildcard. In that case, return a dict that maps the wildcard name to an empt...
3.007965
2.638535
1.140014
res = MatchDict() if self._has_non_single_arg: if self._non_single_arg_on_left: res.merge_lists = 1 else: res.merge_lists = -1 if self.head is not None: if not isinstance(expr, self.head): res.reason = (...
def match(self, expr) -> MatchDict
Match the given expression (recursively) Returns a :class:`MatchDict` instance that maps any wildcard names to the expressions that the corresponding wildcard pattern matches. For (sub-)pattern that have a `mode` attribute other than `Pattern.single`, the wildcard name is mapped to a li...
2.706583
2.703996
1.000957
result = [] try: for arg in expr.args: result.extend(self.findall(arg)) for arg in expr.kwargs.values(): result.extend(self.findall(arg)) except AttributeError: pass if self.match(expr): result.appen...
def findall(self, expr)
list of all matching (sub-)expressions in `expr` See also: :meth:`finditer` yields the matches (:class:`MatchDict` instances) for the matched expressions.
2.421254
2.735834
0.885015
try: for arg in expr.args: for m in self.finditer(arg): yield m for arg in expr.kwargs.values(): for m in self.finditer(arg): yield m except AttributeError: pass m = self.match(ex...
def finditer(self, expr)
Return an iterator over all matches in `expr` Iterate over all :class:`MatchDict` results of matches for any matching (sub-)expressions in `expr`. The order of the matches conforms to the equivalent matched expressions returned by :meth:`findall`.
2.413501
2.838537
0.850262
if self.wc_name is None: res = set() else: res = set([self.wc_name]) if self.args is not None: for arg in self.args: if isinstance(arg, Pattern): res.update(arg.wc_names) if self.kwargs is not None: ...
def wc_names(self)
Set of all wildcard names occurring in the pattern
2.104227
1.967944
1.069251
if cls is None: cls = self.cls if cls is None: raise TypeError("cls must a class") return cls.create(*self.args, **self.kwargs)
def instantiate(self, cls=None)
Return an instantiated Expression as ``cls.create(*self.args, **self.kwargs)`` Args: cls (class): The class of the instantiated expression. If not given, ``self.cls`` will be used.
3.74106
2.861494
1.30738
return cls(expr.args, expr.kwargs, cls=expr.__class__)
def from_expr(cls, expr)
Instantiate proto-expression from the given Expression
9.189105
8.391285
1.095077
global _EntryModel if _EntryModel is None: # This method is likely called the first time when the admin initializes, the sitemaps module is imported, or BaseBlogMixin is used. # Either way, it needs to happen after all apps have initialized, to make sure the model can be imported. ...
def get_entry_model()
Return the actual entry model that is in use. This function reads the :ref:`FLUENT_BLOGS_ENTRY_MODEL` setting to find the model. The model is automatically registered with *django-fluent-comments* and *django-any-urlfield* when it's installed.
3.361938
2.968898
1.132386
app_label, model_name = appsettings.FLUENT_BLOGS_CATEGORY_MODEL.rsplit('.', 1) try: return apps.get_model(app_label, model_name) except Exception as e: # ImportError/LookupError raise ImproperlyConfigured("Failed to import FLUENT_BLOGS_CATEGORY_MODEL '{0}': {1}".format( app...
def get_category_model()
Return the category model to use. This function reads the :ref:`FLUENT_BLOGS_CATEGORY_MODEL` setting to find the model.
2.938232
2.584632
1.136809
return mixed_reverse(viewname, args=args, kwargs=kwargs, current_app=current_app, **page_kwargs)
def blog_reverse(viewname, args=None, kwargs=None, current_app='fluent_blogs', **page_kwargs)
Reverse a URL to the blog, taking various configuration options into account. This is a compatibility function to allow django-fluent-blogs to operate stand-alone. Either the app can be hooked in the URLconf directly, or it can be added as a pagetype of *django-fluent-pages*.
2.444201
3.726243
0.655942