code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def _factor_lhs(self, out_port):
n = self.cdim
assert (0 <= out_port < n)
out_inv = self.permutation.index(out_port)
# (I) is equivalent to
# m_{out_port -> (n-1)} << self << m_{(n-1)
# -> out_inv} == (red_self + cid(1)) (I')
red_se... | With::
n := self.cdim
out_inv := invert_permutation(self.permutation)[out_port]
m_{k->l} := map_signals_circuit({k:l}, n)
solve the equation (I) containing ``self``::
m_{out_port -> (n-1)} << self
== (red_self + cid(1)) << m_{ou... |
def cdim(self):
if self._cdim is None:
self._cdim = sum((circuit.cdim for circuit in self.operands))
return self._cdim | Circuit dimension (sum of dimensions of the operands) |
def immutable_attribs(cls):
cls = attr.s(cls, frozen=True)
defaults = OrderedDict([(a.name, a.default) for a in cls.__attrs_attrs__])
def repr_(self):
from qnet.printing import srepr
real_cls = self.__class__
class_name = real_cls.__name__
args = []
for name in ... | Class decorator like ``attr.s(frozen=True)`` with improved __repr__ |
def save(self,
data,
chart_type,
options=None,
filename='chart',
w=800,
h=420,
overwrite=True):
html = self.render(
data=data,
chart_type=chart_type,
options=options,
... | Save the rendered html to a file in the same directory as the notebook. |
def _unicode_sub_super(string, mapping, max_len=None):
string = str(string)
if string.startswith('(') and string.endswith(')'):
len_string = len(string) - 2
else:
len_string = len(string)
if max_len is not None:
if len_string > max_len:
raise KeyError("max_len ex... | Try to render a subscript or superscript string in unicode, fall back on
ascii if this is not possible |
def _translate_symbols(string):
res = []
string = str(string)
for s in re.split(r'(\W+)', string, flags=re.UNICODE):
tex_str = _GREEK_DICTIONARY.get(s)
if tex_str:
res.append(tex_str)
elif s.lower() in _GREEK_DICTIONARY:
res.append(_GREEK_DICTIONARY[s])
... | Given a description of a Greek letter or other special character,
return the appropriate unicode letter. |
def render(self, data, div_id="chart", head=""):
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(
... | Render the data in HTML template. |
def plot_and_save(self,
data,
w=800,
h=420,
filename='chart',
overwrite=True):
self.save(data, filename, overwrite)
return IFrame(filename + '.html', w, h) | Save the rendered html to a file and returns an IFrame to display the plot in the notebook. |
def plot(self, data, w=800, h=420):
return HTML(
self.iframe.format(
source=self.render(
data=data, div_id="chart", head=self.head),
w=w,
h=h)) | Output an iframe containing the plot in the notebook without saving. |
def _get_from_cache(self, expr):
is_cached, res = super()._get_from_cache(expr)
if is_cached:
indent_str = " " * self._print_level
return True, indent(res, indent_str)
else:
return False, None | Obtain cached result, prepend with the keyname if necessary, and
indent for the current level |
def _write_to_cache(self, expr, res):
res = dedent(res)
super()._write_to_cache(expr, res) | Store the cached result without indentation, and without the
keyname |
def emptyPrinter(self, expr):
indent_str = " " * (self._print_level - 1)
lines = []
if isinstance(expr.__class__, Singleton):
# We exploit that Singletons override __expr__ to directly return
# their name
return indent_str + repr(expr)
if i... | Fallback printer |
def _translate_symbols(string):
res = []
for s in re.split(r'([,.:\s=]+)', string):
tex_str = _TEX_GREEK_DICTIONARY.get(s)
if tex_str:
res.append(tex_str)
elif s.lower() in greek_letters_set:
res.append("\\" + s.lower())
elif s in other_symbols:
... | Given a description of a Greek letter or other special character,
return the appropriate latex. |
def _render_str(self, string):
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_latex_sub_super(
name, ... | Returned a texified version of the string |
def _render_op(
self, identifier, hs=None, dagger=False, args=None, superop=False):
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... | Render an operator
Args:
identifier (str): The identifier (name/symbol) of the operator. May
include a subscript, denoted by '_'.
hs (qnet.algebra.hilbert_space_algebra.HilbertSpace): The Hilbert
space in which the operator is defined
dagger (... |
def is_symbol(string):
return (
is_int(string) or is_float(string) or
is_constant(string) or is_unary(string) or
is_binary(string) or
(string == '(') or (string == ')')
) | Return true if the string is a mathematical symbol. |
def find_word_groups(string, words):
scale_pattern = '|'.join(words)
# For example:
# (?:(?:\d+)\s+(?:hundred|thousand)*\s*)+(?:\d+|hundred|thousand)+
regex = re.compile(
r'(?:(?:\d+)\s+(?:' +
scale_pattern +
r')*\s*)+(?:\d+|' +
scale_pattern + r')+'
)
result... | Find matches for words in the format "3 thousand 6 hundred 2".
The words parameter should be the list of words to check for
such as "hundred". |
def replace_word_tokens(string, language):
words = mathwords.word_groups_for_language(language)
# Replace operator words with numeric operators
operators = words['binary_operators'].copy()
if 'unary_operators' in words:
operators.update(words['unary_operators'])
for operator in list(o... | Given a string and an ISO 639-2 language code,
return the string with the words replaced with
an operational equivalent. |
def to_postfix(tokens):
precedence = {
'/': 4,
'*': 4,
'+': 3,
'-': 3,
'^': 2,
'(': 1
}
postfix = []
opstack = []
for token in tokens:
if is_int(token):
postfix.append(int(token))
elif is_float(token):
pos... | Convert a list of evaluatable tokens to postfix format. |
def evaluate_postfix(tokens):
stack = []
for token in tokens:
total = None
if is_int(token) or is_float(token) or is_constant(token):
stack.append(token)
elif is_unary(token):
a = stack.pop()
total = mathwords.UNARY_FUNCTIONS[token](a)
e... | Given a list of evaluatable tokens in postfix format,
calculate a solution. |
def tokenize(string, language=None, escape='___'):
# Set all words to lowercase
string = string.lower()
# Ignore punctuation
if len(string) and not string[-1].isalnum():
character = string[-1]
string = string[:-1] + ' ' + character
# Parenthesis must have space around them to ... | Given a string, return a list of math symbol tokens |
def parse(string, language=None):
if language:
string = replace_word_tokens(string, language)
tokens = tokenize(string)
postfix = to_postfix(tokens)
return evaluate_postfix(postfix) | Return a solution to the equation in the input string. |
def extract_expression(dirty_string, language):
tokens = tokenize(dirty_string, language)
start_index = 0
end_index = len(tokens)
for part in tokens:
if is_symbol(part) or is_word(part, language):
break
else:
start_index += 1
for part in reversed(token... | Give a string such as: "What is 4 + 4?"
Return the string "4 + 4" |
def expr_order_key(expr):
if hasattr(expr, '_order_key'):
return expr._order_key
try:
if isinstance(expr.kwargs, OrderedDict):
key_vals = expr.kwargs.values()
else:
key_vals = [expr.kwargs[key] for key in sorted(expr.kwargs)]
return KeyTuple((expr.__c... | A default order key for arbitrary expressions |
def ensure_local_space(hs, cls=LocalSpace):
if isinstance(hs, (str, int)):
try:
hs = cls(hs)
except TypeError as exc_info:
raise TypeError(
"Cannot convert %s '%s' into a %s instance: %s"
% (hs.__class__.__name__, hs, cls.__name__, str(exc... | Ensure that the given `hs` is an instance of :class:`LocalSpace`.
If `hs` an instance of :class:`str` or :class:`int`, it will be converted
to a `cls` (if possible). If it already is an instace of `cls`, `hs`
will be returned unchanged.
Args:
hs (HilbertSpace or str or int): The Hilbert space ... |
def _series_expand_combine_prod(c1, c2, order):
from qnet.algebra.core.scalar_algebra import Zero
res = []
c1 = list(c1)
c2 = list(c2)
for n in range(order + 1):
summands = []
for k in range(n + 1):
if c1[k].is_zero or c2[n-k].is_zero:
summands.append... | Given the result of the ``c1._series_expand(...)`` and
``c2._series_expand(...)``, construct the result of
``(c1*c2)._series_expand(...)`` |
def diff(self, sym: Symbol, n: int = 1, expand_simplify: bool = True):
if not isinstance(sym, sympy.Basic):
raise TypeError("%s needs to be a Sympy symbol" % sym)
if sym.free_symbols.issubset(self.free_symbols):
# QuantumDerivative.create delegates internally to _diff (t... | Differentiate by scalar parameter `sym`.
Args:
sym: What to differentiate by.
n: How often to differentiate
expand_simplify: Whether to simplify the result.
Returns:
The n-th derivative. |
def series_expand(
self, param: Symbol, about, order: int) -> tuple:
r
expansion = self._series_expand(param, about, order)
# _series_expand is generally not "type-stable", so we continue to
# ensure the type-stability
res = []
for v in expansion:
... | r"""Expand the expression as a truncated power series in a
scalar parameter.
When expanding an expr for a parameter $x$ about the point $x_0$ up to
order $N$, the resulting coefficients $(c_1, \dots, c_N)$ fulfill
.. math::
\text{expr} = \sum_{n=0}^{N} c_n (x - x_0)^n + O(... |
def factor_for_space(self, spc):
if spc == TrivialSpace:
ops_on_spc = [
o for o in self.operands if o.space is TrivialSpace]
ops_not_on_spc = [
o for o in self.operands if o.space > TrivialSpace]
else:
ops_on_spc = [
... | Return a tuple of two products, where the first product contains the
given Hilbert space, and the second product is disjunct from it. |
def create(cls, op, *, derivs, vals=None):
# To ensure stable ordering in Expression._get_instance_key, we explicitly
# convert `derivs` and `vals` to a tuple structure with a custom sorting key.
if not isinstance(derivs, tuple):
derivs = cls._dict_to_ordered_tuple(dict(deri... | Instantiate the derivative by repeatedly calling
the :meth:`~QuantumExpression._diff` method of `op` and evaluating the
result at the given `vals`. |
def evaluate_at(self, vals):
new_vals = self._vals.copy()
new_vals.update(vals)
return self.__class__(self.operand, derivs=self._derivs, vals=new_vals) | Evaluate the derivative at a specific point |
def free_symbols(self):
if self._free_symbols is None:
if len(self._vals) == 0:
self._free_symbols = self.operand.free_symbols
else:
dummy_map = {}
for sym in self._vals.keys():
dummy_map[sym] = sympy.Dummy()
... | Set of free SymPy symbols contained within the expression. |
def bound_symbols(self):
if self._bound_symbols is None:
res = set()
self._bound_symbols = res.union(
*[sym.free_symbols for sym in self._vals.keys()])
return self._bound_symbols | Set of Sympy symbols that are eliminated by evaluation. |
def generate_clickable_map(self):
# type: () -> unicode
if self.clickable:
return '\n'.join([self.content[0]] + self.clickable + [self.content[-1]])
else:
return '' | Generate clickable map tags if clickable item exists.
If not exists, this only returns empty string. |
def Jzjmcoeff(ls, m, shift) -> sympy.Expr:
r'''Eigenvalue of the $\Op{J}_z$ (:class:`Jz`) operator
.. math::
\Op{J}_{z} \ket{s, m} = m \ket{s, m}
See also :func:`Jpjmcoeff`.
'''
assert isinstance(ls, SpinSpace)
n = ls.dimension
s = sympify(n - 1) / 2
assert n == int(2 * s + 1)... | r'''Eigenvalue of the $\Op{J}_z$ (:class:`Jz`) operator
.. math::
\Op{J}_{z} \ket{s, m} = m \ket{s, m}
See also :func:`Jpjmcoeff`. |
def try_import(objname):
# type: (unicode) -> Any
try:
__import__(objname)
return sys.modules.get(objname) # type: ignore
except (ImportError, ValueError): # ValueError,py27 -> ImportError,py3
matched = module_sig_re.match(objname) # type: ignore
if not matched:
... | Import a object or module using *name* and *currentmodule*.
*name* should be a relative name from *currentmodule* or
a fully-qualified name.
Returns imported object or module. If failed, returns None value. |
def import_classes(name, currmodule):
# type: (unicode, unicode) -> Any
target = None
# import class or module using currmodule
if currmodule:
target = try_import(currmodule + '.' + name)
# import class or module without currmodule
if target is None:
target = try_import(na... | Import a class using its fully-qualified *name*. |
def html_visit_inheritance_diagram(self, node):
# type: (nodes.NodeVisitor, inheritance_diagram) -> None
graph = node['graph']
graph_hash = get_graph_hash(node)
name = 'inheritance%s' % graph_hash
# Create a mapping from fully-qualified class names to URLs.
graphviz_output_format = self.b... | Output the graph for HTML. This will insert a PNG with clickable
image map. |
def latex_visit_inheritance_diagram(self, node):
# type: (nodes.NodeVisitor, inheritance_diagram) -> None
graph = node['graph']
graph_hash = get_graph_hash(node)
name = 'inheritance%s' % graph_hash
dotcode = graph.generate_dot(name, env=self.builder.env,
graph... | Output the graph for LaTeX. This will insert a PDF. |
def texinfo_visit_inheritance_diagram(self, node):
# type: (nodes.NodeVisitor, inheritance_diagram) -> None
graph = node['graph']
graph_hash = get_graph_hash(node)
name = 'inheritance%s' % graph_hash
dotcode = graph.generate_dot(name, env=self.builder.env,
gra... | Output the graph for Texinfo. This will insert a PNG. |
def _import_classes(self, class_names, currmodule):
# type: (unicode, str) -> List[Any]
classes = [] # type: List[Any]
for name in class_names:
classes.extend(import_classes(name, currmodule))
return classes | Import a list of classes. |
def _class_info(self, classes, show_builtins, private_bases, parts, aliases, top_classes):
# type: (List[Any], bool, bool, int, Optional[Dict[unicode, unicode]], List[Any]) -> List[Tuple[unicode, unicode, List[unicode], unicode]] # NOQA
all_classes = {}
py_builtins = vars(builtins).val... | Return name and bases for all classes that are ancestors of
*classes*.
*parts* gives the number of dotted name parts that is removed from the
displayed node names.
*top_classes* gives the name(s) of the top most ancestor class to traverse
to. Multiple names can be specified sep... |
def class_name(self, cls, parts=0, aliases=None):
# type: (Any, int, Optional[Dict[unicode, unicode]]) -> unicode
module = cls.__module__
if module in ('__builtin__', 'builtins'):
fullname = cls.__name__
else:
fullname = '%s.%s' % (module, cls.__name__)
... | Given a class object, return a fully-qualified name.
This works for things I've tested in matplotlib so far, but may not be
completely general. |
def codemirror_settings_update(configs, parameters, on=None, names=None):
# Deep copy of given config
output = copy.deepcopy(configs)
# Optionnaly filtering config from given names
if names:
output = {k: output[k] for k in names}
# Select every config if selectors is empty
if not ... | Return a new dictionnary of configs updated with given parameters.
You may use ``on`` and ``names`` arguments to select config or filter out
some configs from returned dict.
Arguments:
configs (dict): Dictionnary of configurations to update.
parameters (dict): Dictionnary of parameters to ... |
def lhs(self):
lhs = self._lhs
i = 0
while lhs is None:
i -= 1
lhs = self._prev_lhs[i]
return lhs | The left-hand-side of the equation |
def set_tag(self, tag):
return Eq(
self._lhs, self._rhs, tag=tag,
_prev_lhs=self._prev_lhs, _prev_rhs=self._prev_rhs,
_prev_tags=self._prev_tags) | Return a copy of the equation with a new `tag` |
def apply(self, func, *args, cont=False, tag=None, **kwargs):
new_lhs = func(self.lhs, *args, **kwargs)
if new_lhs == self.lhs and cont:
new_lhs = None
new_rhs = func(self.rhs, *args, **kwargs)
new_tag = tag
return self._update(new_lhs, new_rhs, new_tag, cont... | Apply `func` to both sides of the equation
Returns a new equation where the left-hand-side and right-hand side
are replaced by the application of `func`::
lhs=func(lhs, *args, **kwargs)
rhs=func(rhs, *args, **kwargs)
If ``cont=True``, the resulting equation will keep a... |
def apply_mtd(self, mtd, *args, cont=False, tag=None, **kwargs):
new_lhs = getattr(self.lhs, mtd)(*args, **kwargs)
if new_lhs == self.lhs and cont:
new_lhs = None
new_rhs = getattr(self.rhs, mtd)(*args, **kwargs)
new_tag = tag
return self._update(new_lhs, new... | Call the method `mtd` on both sides of the equation
That is, the left-hand-side and right-hand-side are replaced by::
lhs=lhs.<mtd>(*args, **kwargs)
rhs=rhs.<mtd>(*args, **kwargs)
The `cont` and `tag` parameters are as in :meth:`apply`. |
def substitute(self, var_map, cont=False, tag=None):
return self.apply(substitute, var_map=var_map, cont=cont, tag=tag) | Substitute sub-expressions both on the lhs and rhs
Args:
var_map (dict): Dictionary with entries of the form
``{expr: substitution}`` |
def verify(self, func=None, *args, **kwargs):
res = (
self.lhs.expand().simplify_scalar() -
self.rhs.expand().simplify_scalar())
if func is not None:
return func(res, *args, **kwargs)
else:
return res | Subtract the rhs from the lhs of the equation
Before the substraction, each side is expanded and any scalars are
simplified. If given, `func` with the positional arguments `args` and
keyword-arguments `kwargs` is applied to the result before returning
it.
You may complete the v... |
def copy(self):
return Eq(
self._lhs, self._rhs, tag=self._tag,
_prev_lhs=self._prev_lhs, _prev_rhs=self._prev_rhs,
_prev_tags=self._prev_tags) | Return a copy of the equation |
def free_symbols(self):
try:
lhs_syms = self.lhs.free_symbols
except AttributeError:
lhs_syms = set()
try:
rhs_syms = self.rhs.free_symbols
except AttributeError:
rhs_syms = set()
return lhs_syms | rhs_syms | Set of free SymPy symbols contained within the equation. |
def bound_symbols(self):
try:
lhs_syms = self.lhs.bound_symbols
except AttributeError:
lhs_syms = set()
try:
rhs_syms = self.rhs.bound_symbols
except AttributeError:
rhs_syms = set()
return lhs_syms | rhs_syms | Set of bound SymPy symbols contained within the equation. |
def basis_state(i, n):
v = sympy.zeros(n, 1)
v[i] = 1
return v | ``n x 1`` `sympy.Matrix` representing the `i`'th eigenstate of an
`n`-dimensional Hilbert space (`i` >= 0) |
def SympyCreate(n):
a = sympy.zeros(n)
for i in range(1, n):
a += sympy.sqrt(i) * basis_state(i, n) * basis_state(i-1, n).H
return a | Creation operator for a Hilbert space of dimension `n`, as an instance
of `sympy.Matrix` |
def formfield_for_dbfield(self, db_field, **kwargs):
overrides = self.formfield_overrides.get(db_field.name)
if overrides:
kwargs.update(overrides)
field = super(AbstractEntryBaseAdmin, self).formfield_for_dbfield(db_field, **kwargs)
# Pass user to the form.
... | Allow formfield_overrides to contain field names too. |
def product(*generators, repeat=1):
if len(generators) == 0:
yield ()
else:
generators = generators * repeat
it = generators[0]
for item in it() if callable(it) else iter(it):
for items in product(*generators[1:]):
yield (item, ) + items | Cartesian product akin to :func:`itertools.product`, but accepting
generator functions
Unlike :func:`itertools.product` this function does not convert the input
iterables into tuples. Thus, it can handle large or infinite inputs. As a
drawback, however, it only works with "restartable" iterables (somet... |
def incr_primed(self, incr=1):
return self.__class__(
self.name, primed=self._primed + incr,
**self._assumptions.generator) | Return a copy of the index with an incremented :attr:`primed` |
def no_instance_caching():
# this assumes that no sub-class of Expression shadows
# Expression.instance_caching
orig_flag = Expression.instance_caching
Expression.instance_caching = False
try:
yield
finally:
Expression.instance_caching = orig_flag | Temporarily disable instance caching in :meth:`~.Expression.create`
Within the managed context, :meth:`~.Expression.create` will not use any
caching, for any class. |
def temporary_instance_cache(*classes):
orig_instances = []
for cls in classes:
orig_instances.append(cls._instances)
cls._instances = {}
try:
yield
finally:
for i, cls in enumerate(classes):
cls._instances = orig_instances[i] | Use a temporary cache for instances in :meth:`~.Expression.create`
The instance cache used by :meth:`~.Expression.create` for any of the given
`classes` will be cleared upon entering the managed context, and restored
on leaving it. That is, no cached instances from outside of the managed
context will ... |
def _split_identifier(self, identifier):
try:
name, subscript = identifier.split("_", 1)
except (TypeError, ValueError, AttributeError):
name = identifier
subscript = ''
return self._render_str(name), self._render_str(subscript) | Split the given identifier at the first underscore into (rendered)
name and subscript. Both `name` and `subscript` are rendered as
strings |
def _split_op(
self, identifier, hs_label=None, dagger=False, args=None):
if self._isinstance(identifier, 'SymbolicLabelBase'):
identifier = QnetAsciiDefaultPrinter()._print_SCALAR_TYPES(
identifier.expr)
name, total_subscript = self._split_identifier(ide... | Return `name`, total `subscript`, total `superscript` and
`arguments` str. All of the returned strings are fully rendered.
Args:
identifier (str or SymbolicLabelBase): A (non-rendered/ascii)
identifier that may include a subscript. The output `name` will
be t... |
def _render_hs_label(self, hs):
if isinstance(hs.__class__, Singleton):
return self._render_str(hs.label)
else:
return self._tensor_sym.join(
[self._render_str(ls.label) for ls in hs.local_factors]) | Return the label of the given Hilbert space as a string |
def _braket_fmt(self, expr_type):
mapping = {
'bra': {
True: '<{label}|^({space})',
'subscript': '<{label}|_({space})',
False: '<{label}|'},
'ket': {
True: '|{label}>^({space})',
'subscript': '|{lab... | Return a format string for printing an `expr_type`
ket/bra/ketbra/braket |
def _render_op(
self, identifier, hs=None, dagger=False, args=None, superop=False):
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... | Render an operator
Args:
identifier (str or SymbolicLabelBase): The identifier (name/symbol)
of the operator. May include a subscript, denoted by '_'.
hs (qnet.algebra.hilbert_space_algebra.HilbertSpace): The Hilbert
space in which the operator is defined... |
def parenthesize(self, expr, level, *args, strict=False, **kwargs):
needs_parenths = (
(precedence(expr) < level) or
(strict and precedence(expr) == level))
if needs_parenths:
return (
self._parenth_left + self.doprint(expr, *args, **kwargs) +... | Render `expr` and wrap the result in parentheses if the precedence
of `expr` is below the given `level` (or at the given `level` if
`strict` is True. Extra `args` and `kwargs` are passed to the internal
`doit` renderer |
def _curve(x1, y1, x2, y2, hunit = HUNIT, vunit = VUNIT):
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) | Return a PyX curved path from (x1, y1) to (x2, y2),
such that the slope at either end is zero. |
def nested_tuple(container):
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 isinsta... | 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 ... |
def precedence(item):
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 PR... | Returns the precedence of a given object. |
def render(self,
data,
chart_type,
chart_package='corechart',
options=None,
div_id="chart",
head=""):
if not self.is_valid_name(div_id):
raise ValueError(
"Name {} is invalid. Only lett... | Render the data in HTML template. |
def plot(self,
data,
chart_type,
chart_package='corechart',
options=None,
w=800,
h=420):
return HTML(
self.iframe.format(
source=self.render(
data=data,
opti... | Output an iframe containing the plot in the notebook without saving. |
def published(self, for_user=None):
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.mode... | Return only published entries for the current site. |
def authors(self, *usernames):
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}) | Return the entries written by the given usernames
When multiple tags are provided, they operate as "OR" query. |
def categories(self, *category_slugs):
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, Transla... | Return the entries with the given category slugs.
When multiple tags are provided, they operate as "OR" query. |
def tagged(self, *tag_slugs):
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 s... | Return the items which are tagged with a specific tag.
When multiple tags are provided, they operate as "OR" query. |
def format(self, **kwargs):
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... | Format and combine the name, subscript, and superscript |
def _render_str(self, string):
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... | Returned a unicodified version of the string |
def _braket_fmt(self, expr_type):
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... | Return a format string for printing an `expr_type`
ket/bra/ketbra/braket |
def _render_op(
self, identifier, hs=None, dagger=False, args=None, superop=False):
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... | 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... |
def PauliX(local_space, states=None):
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)) | 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... |
def PauliY(local_space, states=None):
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)) | 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` |
def PauliZ(local_space, states=None):
r
local_space, states = _get_pauli_args(local_space, states)
g, e = states
return (
LocalProjector(g, hs=local_space) - LocalProjector(e, hs=local_space)) | 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` |
def render_head_repr(
expr: Any, sub_render=None, key_sub_render=None) -> str:
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):
... | 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... |
def derationalize_denom(expr):
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
numera... | 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... |
def entries(self):
# 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, Transla... | Return the entries that are published under this node. |
def get_entry_url(self, entry):
# 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 ass... | Return the URL of a blog entry, relative to this page. |
def create_placeholder(self, slot="blog_contents", role='m', title=None):
return Placeholder.objects.create_for_object(self, slot, role=role, title=title) | 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` |
def similar_objects(self, num=None, **filters):
# 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) | Find similar objects using related tags. |
def save_as_png(self, filename, width=300, height=250, render_time=1):
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(fi... | Open saved html file in an virtual browser and save a screen shot to PNG format. |
def get_version(filename):
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) | Extract the package version |
def blogurl(parser, token):
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) | 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 ... |
def format_year(year):
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) | 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. |
def free_symbols(self):
return set([
sym for sym in self.term.free_symbols
if sym not in self.bound_symbols]) | Set of all free symbols |
def terms(self):
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 i... | 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` |
def doit(
self, classes=None, recursive=True, indices=None, max_terms=None,
**kwargs):
return super().doit(
classes, recursive, indices=indices, max_terms=max_terms, **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:
... |
def make_disjunct_indices(self, *others):
new = self
other_index_symbols = set()
for other in others:
try:
if isinstance(other, IdxSym):
other_index_symbols.add(other)
elif isinstance(other, IndexRangeBase):
... | 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... |
def codemirror_field_js_assets(*args):
manifesto = CodemirrorAssetTagRender()
manifesto.register_from_fields(*args)
return mark_safe(manifesto.js_html()) | Tag to render CodeMirror Javascript assets needed for all given fields.
Example:
::
{% load djangocodemirror_tags %}
{% codemirror_field_js_assets form.myfield1 form.myfield2 %} |
def codemirror_field_css_assets(*args):
manifesto = CodemirrorAssetTagRender()
manifesto.register_from_fields(*args)
return mark_safe(manifesto.css_html()) | Tag to render CodeMirror CSS assets needed for all given fields.
Example:
::
{% load djangocodemirror_tags %}
{% codemirror_field_css_assets form.myfield1 form.myfield2 %} |
def codemirror_field_js_bundle(field):
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 bun... | 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... |
def codemirror_field_css_bundle(field):
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 b... | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.