_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q274700 | _maybe_class_to_py_ast | test | def _maybe_class_to_py_ast(_: GeneratorContext, node: MaybeClass) -> GeneratedPyAST:
"""Generate a Python AST node for accessing a potential Python module
| python | {
"resource": ""
} |
q274701 | _maybe_host_form_to_py_ast | test | def _maybe_host_form_to_py_ast(
_: GeneratorContext, node: MaybeHostForm
) -> GeneratedPyAST:
"""Generate a Python AST node for accessing a potential Python module
| python | {
"resource": ""
} |
q274702 | _const_val_to_py_ast | test | def _const_val_to_py_ast(ctx: GeneratorContext, form: LispForm) -> GeneratedPyAST:
"""Generate Python AST nodes for constant Lisp forms.
Nested values in collections for :const nodes are not parsed, so recursive
structures need to call into this function to generate Python AST nodes for
nested elements. For top-level :const Lisp AST nodes, see
`_const_node_to_py_ast`."""
handle_value = _CONST_VALUE_HANDLERS.get(type(form))
if handle_value is | python | {
"resource": ""
} |
q274703 | _collection_literal_to_py_ast | test | def _collection_literal_to_py_ast(
ctx: GeneratorContext, form: Iterable[LispForm]
) -> Iterable[GeneratedPyAST]:
"""Turn a quoted collection literal of Lisp forms into Python AST nodes.
This function can only handle constant values. It does not | python | {
"resource": ""
} |
q274704 | gen_py_ast | test | def gen_py_ast(ctx: GeneratorContext, lisp_ast: Node) -> GeneratedPyAST:
"""Take a Lisp AST node as an argument and produce zero or more Python
AST nodes.
This is the primary entrypoint for generating AST nodes from Lisp
syntax. It may be called recursively to compile child forms."""
op: NodeOp = lisp_ast.op
assert op is not None, "Lisp AST nodes must have | python | {
"resource": ""
} |
q274705 | _module_imports | test | def _module_imports(ctx: GeneratorContext) -> Iterable[ast.Import]:
"""Generate the Python Import AST node for importing all required
language support modules."""
# Yield `import basilisp` so code attempting to call fully qualified
# `basilisp.lang...` modules don't result in compiler errors
| python | {
"resource": ""
} |
q274706 | _from_module_import | test | def _from_module_import() -> ast.ImportFrom:
"""Generate the Python From ... Import AST node for importing
language support | python | {
"resource": ""
} |
q274707 | _ns_var | test | def _ns_var(
py_ns_var: str = _NS_VAR, lisp_ns_var: str = LISP_NS_VAR, lisp_ns_ns: str = CORE_NS
) -> ast.Assign:
"""Assign a Python variable named `ns_var` to the value of the current
namespace."""
return ast.Assign(
targets=[ast.Name(id=py_ns_var, ctx=ast.Store())],
value=ast.Call(
func=_FIND_VAR_FN_NAME,
args=[
ast.Call(
| python | {
"resource": ""
} |
q274708 | set | test | def set(members: Iterable[T], meta=None) -> Set[T]: # pylint:disable=redefined-builtin | python | {
"resource": ""
} |
q274709 | s | test | def s(*members: T, meta=None) -> Set[T]:
"""Creates a new set from members."""
| python | {
"resource": ""
} |
q274710 | PythonASTOptimizer.visit_ExceptHandler | test | def visit_ExceptHandler(self, node: ast.ExceptHandler) -> Optional[ast.AST]:
"""Eliminate dead code from except handler bodies."""
new_node = self.generic_visit(node)
assert isinstance(new_node, ast.ExceptHandler)
return ast.copy_location(
ast.ExceptHandler(
| python | {
"resource": ""
} |
q274711 | PythonASTOptimizer.visit_Expr | test | def visit_Expr(self, node: ast.Expr) -> Optional[ast.Expr]:
"""Eliminate no-op constant expressions which are in the tree
as standalone statements."""
if isinstance(
node.value,
(
ast.Constant, # type: ignore
ast.Name,
| python | {
"resource": ""
} |
q274712 | PythonASTOptimizer.visit_FunctionDef | test | def visit_FunctionDef(self, node: ast.FunctionDef) -> Optional[ast.AST]:
"""Eliminate dead code from function bodies."""
new_node = self.generic_visit(node)
assert isinstance(new_node, ast.FunctionDef)
return ast.copy_location(
ast.FunctionDef(
name=new_node.name,
args=new_node.args,
| python | {
"resource": ""
} |
q274713 | PythonASTOptimizer.visit_While | test | def visit_While(self, node: ast.While) -> Optional[ast.AST]:
"""Eliminate dead code from while bodies."""
new_node = self.generic_visit(node)
assert isinstance(new_node, ast.While)
return ast.copy_location(
ast.While(
| python | {
"resource": ""
} |
q274714 | PythonASTOptimizer.visit_Try | test | def visit_Try(self, node: ast.Try) -> Optional[ast.AST]:
"""Eliminate dead code from except try bodies."""
new_node = self.generic_visit(node)
assert isinstance(new_node, ast.Try)
return ast.copy_location(
ast.Try(
body=_filter_dead_code(new_node.body),
| python | {
"resource": ""
} |
q274715 | _new_module | test | def _new_module(name: str, doc=None) -> types.ModuleType:
"""Create a new empty Basilisp Python module.
Modules are created for each Namespace when it is created."""
mod = types.ModuleType(name, doc=doc)
mod.__loader__ = | python | {
"resource": ""
} |
q274716 | first | test | def first(o):
"""If o is a ISeq, return the first element from o. If o is None, return
None. Otherwise, coerces o to a Seq and returns | python | {
"resource": ""
} |
q274717 | rest | test | def rest(o) -> Optional[ISeq]:
"""If o is a ISeq, return the elements after the first in o. If o is None,
returns an empty seq. Otherwise, coerces o to a seq and returns the rest."""
if o is None:
return None
if isinstance(o, ISeq):
| python | {
"resource": ""
} |
q274718 | nthrest | test | def nthrest(coll, i: int):
"""Returns the nth rest sequence of coll, or coll if i is 0."""
while True:
if coll is None:
return None
| python | {
"resource": ""
} |
q274719 | nthnext | test | def nthnext(coll, i: int) -> Optional[ISeq]:
"""Returns the nth next sequence of coll."""
while True:
if coll is None:
return None
if | python | {
"resource": ""
} |
q274720 | cons | test | def cons(o, seq) -> ISeq:
"""Creates a new sequence where o is the first element and seq is the rest.
If seq is None, return a list containing o. If seq is not a ISeq, attempt
to coerce it to a ISeq and then cons o onto the resulting sequence."""
if seq is None:
return llist.l(o) | python | {
"resource": ""
} |
q274721 | to_seq | test | def to_seq(o) -> Optional[ISeq]:
"""Coerce the argument o to a ISeq. If o is None, return None."""
if o is None:
return None
if isinstance(o, ISeq):
| python | {
"resource": ""
} |
q274722 | concat | test | def concat(*seqs) -> ISeq:
"""Concatenate the sequences given by seqs into a single ISeq."""
| python | {
"resource": ""
} |
q274723 | assoc | test | def assoc(m, *kvs):
"""Associate keys to values in associative data structure m. If m is None,
returns a new Map with key-values kvs."""
if m is None:
return lmap.Map.empty().assoc(*kvs)
if | python | {
"resource": ""
} |
q274724 | conj | test | def conj(coll, *xs):
"""Conjoin xs to collection. New elements may be added in different positions
depending on the type of coll. conj returns the same type as coll. If coll
is None, return a list with xs conjoined."""
if coll is None:
l = llist.List.empty()
return l.cons(*xs)
| python | {
"resource": ""
} |
q274725 | partial | test | def partial(f, *args):
"""Return a function which is the partial application of f with args."""
| python | {
"resource": ""
} |
q274726 | deref | test | def deref(o, timeout_s=None, timeout_val=None):
"""Dereference a Deref object and return its contents.
If o is an object implementing IBlockingDeref and timeout_s and
timeout_val are supplied, deref will wait at most timeout_s seconds,
returning timeout_val if timeout_s seconds elapse and o has not
returned."""
if isinstance(o, IDeref):
| python | {
"resource": ""
} |
q274727 | equals | test | def equals(v1, v2) -> bool:
"""Compare two objects by value. Unlike the standard Python equality operator,
this function does not consider 1 == True or 0 == False. All other equality
operations are the same and performed using Python's | python | {
"resource": ""
} |
q274728 | divide | test | def divide(x: LispNumber, y: LispNumber) -> LispNumber:
"""Division reducer. If both arguments are integers, return a Fraction.
Otherwise, return the true division of x and y."""
| python | {
"resource": ""
} |
q274729 | sort | test | def sort(coll, f=None) -> Optional[ISeq]:
"""Return a sorted sequence of the elements in coll. If a comparator | python | {
"resource": ""
} |
q274730 | contains | test | def contains(coll, k):
"""Return true if o contains the key k."""
if isinstance(coll, IAssociative):
| python | {
"resource": ""
} |
q274731 | get | test | def get(m, k, default=None):
"""Return the value of k in m. Return default if k not found in m."""
if isinstance(m, IAssociative):
| python | {
"resource": ""
} |
q274732 | to_lisp | test | def to_lisp(o, keywordize_keys: bool = True):
"""Recursively convert Python collections into Lisp collections."""
if not isinstance(o, (dict, frozenset, list, set, tuple)):
| python | {
"resource": ""
} |
q274733 | to_py | test | def to_py(o, keyword_fn: Callable[[kw.Keyword], Any] = _kw_name):
"""Recursively convert Lisp collections into Python collections."""
if isinstance(o, ISeq):
return _to_py_list(o, keyword_fn=keyword_fn)
elif not isinstance(
| python | {
"resource": ""
} |
q274734 | lrepr | test | def lrepr(o, human_readable: bool = False) -> str:
"""Produce a string representation of an object. If human_readable is False,
the string representation of Lisp objects is something that can be read back
in by the reader as the same object."""
core_ns = Namespace.get(sym.symbol(CORE_NS))
assert core_ns is not None
return lobj.lrepr(
o,
human_readable=human_readable, | python | {
"resource": ""
} |
q274735 | _collect_args | test | def _collect_args(args) -> ISeq:
"""Collect Python starred arguments into a Basilisp list."""
if isinstance(args, tuple):
return llist.list(args)
| python | {
"resource": ""
} |
q274736 | _trampoline | test | def _trampoline(f):
"""Trampoline a function repeatedly until it is finished recurring to help
avoid stack growth."""
@functools.wraps(f)
def trampoline(*args, **kwargs):
while True:
ret = f(*args, **kwargs)
| python | {
"resource": ""
} |
q274737 | _with_attrs | test | def _with_attrs(**kwargs):
"""Decorator to set attributes on a function. Returns the original
function after setting the attributes named by the keyword arguments."""
def decorator(f):
| python | {
"resource": ""
} |
q274738 | _fn_with_meta | test | def _fn_with_meta(f, meta: Optional[lmap.Map]):
"""Return a new function with the given meta. If the function f already
has a meta map, then merge the """
if not isinstance(meta, lmap.Map):
raise TypeError("meta must be a map")
if inspect.iscoroutinefunction(f):
@functools.wraps(f)
async def wrapped_f(*args, **kwargs):
return await f(*args, **kwargs)
else:
@functools.wraps(f) # type: ignore
def wrapped_f(*args, **kwargs):
return f(*args, | python | {
"resource": ""
} |
q274739 | _basilisp_fn | test | def _basilisp_fn(f):
"""Create a Basilisp function, setting meta and supplying a with_meta
method implementation.""" | python | {
"resource": ""
} |
q274740 | resolve_alias | test | def resolve_alias(s: sym.Symbol, ns: Optional[Namespace] = None) -> sym.Symbol:
"""Resolve the aliased symbol in the current namespace."""
if s in _SPECIAL_FORMS:
return s
ns = Maybe(ns).or_else(get_current_ns)
if s.ns is not None:
aliased_ns = ns.get_alias(sym.symbol(s.ns)) | python | {
"resource": ""
} |
q274741 | resolve_var | test | def resolve_var(s: sym.Symbol, ns: Optional[Namespace] = None) -> Optional[Var]:
"""Resolve the aliased | python | {
"resource": ""
} |
q274742 | add_generated_python | test | def add_generated_python(
generated_python: str,
var_name: str = _GENERATED_PYTHON_VAR_NAME,
which_ns: Optional[str] = None,
) -> None:
"""Add generated Python code to a dynamic variable in which_ns."""
if which_ns is None:
which_ns = get_current_ns().name
ns_sym = sym.Symbol(var_name, ns=which_ns)
v = Maybe(Var.find(ns_sym)).or_else(
lambda: Var.intern(
| python | {
"resource": ""
} |
q274743 | bootstrap | test | def bootstrap(ns_var_name: str = NS_VAR_NAME, core_ns_name: str = CORE_NS) -> None:
"""Bootstrap the environment with functions that are are difficult to
express with the very minimal lisp environment."""
core_ns_sym = sym.symbol(core_ns_name)
ns_var_sym = sym.symbol(ns_var_name, ns=core_ns_name)
__NS = Maybe(Var.find(ns_var_sym)).or_else_raise(
lambda: RuntimeException(f"Dynamic Var {ns_var_sym} not bound!")
)
def in_ns(s: sym.Symbol):
ns = Namespace.get_or_create(s)
__NS.value = ns
return ns
Var.intern_unbound(core_ns_sym, sym.symbol("unquote"))
Var.intern_unbound(core_ns_sym, sym.symbol("unquote-splicing"))
Var.intern(
core_ns_sym, sym.symbol("in-ns"), in_ns, meta=lmap.map({_REDEF_META_KEY: True})
)
Var.intern(
core_ns_sym,
sym.symbol(_PRINT_GENERATED_PY_VAR_NAME),
False,
dynamic=True,
meta=lmap.map({_PRIVATE_META_KEY: True}),
)
Var.intern(
core_ns_sym,
sym.symbol(_GENERATED_PYTHON_VAR_NAME),
"",
dynamic=True,
meta=lmap.map({_PRIVATE_META_KEY: True}),
)
# Dynamic Vars for controlling printing
Var.intern(
| python | {
"resource": ""
} |
q274744 | Var.intern | test | def intern(
ns: sym.Symbol, name: sym.Symbol, val, dynamic: bool = False, meta=None
) -> "Var":
"""Intern the value bound to the symbol `name` in namespace `ns`."""
var_ns = Namespace.get_or_create(ns) | python | {
"resource": ""
} |
q274745 | Var.intern_unbound | test | def intern_unbound(
ns: sym.Symbol, name: sym.Symbol, dynamic: bool = False, meta=None
) -> "Var":
"""Create a new unbound `Var` instance to the symbol `name` in namespace `ns`."""
| python | {
"resource": ""
} |
q274746 | Var.find_in_ns | test | def find_in_ns(ns_sym: sym.Symbol, name_sym: sym.Symbol) -> "Optional[Var]":
"""Return the value current bound to the name `name_sym` in the namespace
specified by `ns_sym`."""
| python | {
"resource": ""
} |
q274747 | Var.find | test | def find(ns_qualified_sym: sym.Symbol) -> "Optional[Var]":
"""Return the value currently bound to the name in the namespace specified
by `ns_qualified_sym`."""
ns = Maybe(ns_qualified_sym.ns).or_else_raise(
lambda: ValueError(
f"Namespace must be specified in Symbol | python | {
"resource": ""
} |
q274748 | Var.find_safe | test | def find_safe(ns_qualified_sym: sym.Symbol) -> "Var":
"""Return the Var currently bound to the name in the namespace specified
by `ns_qualified_sym`. If no Var is bound to that name, raise an exception.
This is a utility method to return useful debugging information when code
refers to an invalid symbol at runtime."""
| python | {
"resource": ""
} |
q274749 | Namespace.add_default_import | test | def add_default_import(cls, module: str):
"""Add a gated default import to the default imports.
In particular, we need to avoid importing 'basilisp.core' before we have
finished macro-expanding."""
| python | {
"resource": ""
} |
q274750 | Namespace.add_alias | test | def add_alias(self, alias: sym.Symbol, namespace: "Namespace") -> None:
| python | {
"resource": ""
} |
q274751 | Namespace.intern | test | def intern(self, sym: sym.Symbol, var: Var, force: bool = False) -> Var:
"""Intern the Var given in this namespace mapped by the given Symbol.
If the Symbol already maps to | python | {
"resource": ""
} |
q274752 | Namespace._intern | test | def _intern(
m: lmap.Map, sym: sym.Symbol, new_var: Var, force: bool = False
) -> lmap.Map:
"""Swap function used by intern to atomically | python | {
"resource": ""
} |
q274753 | Namespace.find | test | def find(self, sym: sym.Symbol) -> Optional[Var]:
"""Find Vars mapped by the given Symbol input or None if no Vars are
mapped by that Symbol."""
| python | {
"resource": ""
} |
q274754 | Namespace.add_import | test | def add_import(
self, sym: sym.Symbol, module: types.ModuleType, *aliases: sym.Symbol
) -> None:
"""Add the Symbol as an imported Symbol in this Namespace. If aliases are given,
the aliases will be applied to the """
self._imports.swap(lambda m: m.assoc(sym, module))
if aliases:
| python | {
"resource": ""
} |
q274755 | Namespace.get_import | test | def get_import(self, sym: sym.Symbol) -> Optional[types.ModuleType]:
"""Return the module if a moduled named by sym has been imported into
this Namespace, None otherwise.
First try to resolve a module directly with the given name. If no module
can be resolved, attempt to resolve the module using import aliases."""
mod = self.imports.entry(sym, | python | {
"resource": ""
} |
q274756 | Namespace.add_refer | test | def add_refer(self, sym: sym.Symbol, var: Var) -> None:
"""Refer var in this namespace | python | {
"resource": ""
} |
q274757 | Namespace.get_refer | test | def get_refer(self, sym: sym.Symbol) -> Optional[Var]:
"""Get the Var referred by Symbol or None if it | python | {
"resource": ""
} |
q274758 | Namespace.__refer_all | test | def __refer_all(cls, refers: lmap.Map, other_ns_interns: lmap.Map) -> lmap.Map:
"""Refer all _public_ interns from another namespace."""
final_refers = refers
for entry in other_ns_interns:
s: sym.Symbol = entry.key
| python | {
"resource": ""
} |
q274759 | Namespace.refer_all | test | def refer_all(self, other_ns: "Namespace"):
"""Refer all the Vars in the other namespace."""
| python | {
"resource": ""
} |
q274760 | Namespace.__get_or_create | test | def __get_or_create(
ns_cache: NamespaceMap,
name: sym.Symbol,
module: types.ModuleType = None,
core_ns_name=CORE_NS,
) -> lmap.Map:
"""Private swap function used by `get_or_create` to atomically swap
the new namespace map into the global cache."""
ns = ns_cache.entry(name, None)
if ns is not None:
return ns_cache
new_ns = Namespace(name, module=module)
if name.name != core_ns_name:
| python | {
"resource": ""
} |
q274761 | Namespace.get_or_create | test | def get_or_create(
cls, name: sym.Symbol, module: types.ModuleType = None
) -> "Namespace":
"""Get the namespace bound to the symbol `name` in | python | {
"resource": ""
} |
q274762 | Namespace.get | test | def get(cls, name: sym.Symbol) -> "Optional[Namespace]":
"""Get the namespace bound to the symbol `name` in the global namespace
cache. Return the namespace if it | python | {
"resource": ""
} |
q274763 | Namespace.remove | test | def remove(cls, name: sym.Symbol) -> Optional["Namespace"]:
"""Remove the namespace bound to the symbol `name` in the global
namespace cache and return that namespace.
Return None if the namespace did not exist in the cache."""
while True:
oldval: lmap.Map = cls._NAMESPACES.deref()
| python | {
"resource": ""
} |
q274764 | Namespace.__completion_matcher | test | def __completion_matcher(text: str) -> CompletionMatcher:
"""Return a function which matches any symbol keys from map entries
against the given text."""
| python | {
"resource": ""
} |
q274765 | Namespace.__complete_alias | test | def __complete_alias(
self, prefix: str, name_in_ns: Optional[str] = None
) -> Iterable[str]:
"""Return an iterable of possible completions matching the given
prefix from the list of aliased namespaces. If name_in_ns is given,
further attempt to refine the list to matching names in that namespace."""
candidates = filter(
Namespace.__completion_matcher(prefix), [(s, n) for s, n in self.aliases]
)
if name_in_ns is not None:
for _, candidate_ns in candidates:
| python | {
"resource": ""
} |
q274766 | Namespace.__complete_imports_and_aliases | test | def __complete_imports_and_aliases(
self, prefix: str, name_in_module: Optional[str] = None
) -> Iterable[str]:
"""Return an iterable of possible completions matching the given
prefix from the list of imports and aliased imports. If name_in_module
is given, further attempt to refine the list to matching names in that
namespace."""
imports = self.imports
aliases = lmap.map(
{
alias: imports.entry(import_name)
for alias, import_name in self.import_aliases
}
| python | {
"resource": ""
} |
q274767 | Namespace.__complete_interns | test | def __complete_interns(
self, value: str, include_private_vars: bool = True
) -> Iterable[str]:
"""Return an iterable of possible completions matching the given
prefix from the list of interned Vars."""
if include_private_vars:
is_match = Namespace.__completion_matcher(value)
else:
_is_match = Namespace.__completion_matcher(value)
| python | {
"resource": ""
} |
q274768 | Namespace.__complete_refers | test | def __complete_refers(self, value: str) -> Iterable[str]:
"""Return an iterable of possible completions matching the given
prefix from the list of referred Vars."""
return map(
lambda entry: f"{entry[0].name}",
| python | {
"resource": ""
} |
q274769 | Namespace.complete | test | def complete(self, text: str) -> Iterable[str]:
"""Return an iterable of possible completions for the given text in
this namespace."""
assert not text.startswith(":")
if "/" in text:
prefix, suffix = text.split("/", maxsplit=1)
results = itertools.chain(
self.__complete_alias(prefix, name_in_ns=suffix),
self.__complete_imports_and_aliases(prefix, name_in_module=suffix),
)
else:
results = itertools.chain( | python | {
"resource": ""
} |
q274770 | _TrampolineArgs.args | test | def args(self) -> Tuple:
"""Return the arguments for a trampolined function. If the function
that is being trampolined has varargs, unroll the final argument if
it is a sequence."""
if not self._has_varargs:
| python | {
"resource": ""
} |
q274771 | list | test | def list(members, meta=None) -> List: # pylint:disable=redefined-builtin
"""Creates a new list."""
return List( | python | {
"resource": ""
} |
q274772 | l | test | def l(*members, meta=None) -> List:
"""Creates a new list from members."""
return List( # pylint: | python | {
"resource": ""
} |
q274773 | change_style | test | def change_style(style, representer):
"""
This function is used to format the key value as a multi-line string maintaining the line breaks
"""
def new_representer(dumper, data):
| python | {
"resource": ""
} |
q274774 | decrypt | test | def decrypt(token, key_store, key_purpose, leeway=120):
"""This decrypts the provided jwe token, then decodes resulting jwt token and returns
the payload.
:param str token: The jwe token.
:param key_store: The key store.
:param str key_purpose: Context for the key.
:param int leeway: Extra allowed time in seconds after expiration to account for clock skew.
:return: The decrypted payload.
"""
tokens | python | {
"resource": ""
} |
q274775 | encrypt | test | def encrypt(json, key_store, key_purpose):
"""This encrypts the supplied json and returns a jwe token.
:param str json: The json to be encrypted.
:param key_store: The key store.
:param str key_purpose: Context for the key.
| python | {
"resource": ""
} |
q274776 | BaseCacheWrapper.delete | test | def delete(self, *args):
"""Remove the key from the request cache and from memcache."""
cache = get_cache()
| python | {
"resource": ""
} |
q274777 | Constraint.to_python | test | def to_python(self):
"""Deconstruct the ``Constraint`` instance to a tuple.
Returns:
tuple: The deconstructed ``Constraint``.
"""
return (
self.selector,
| python | {
"resource": ""
} |
q274778 | AsyncCAM.close | test | def close(self):
"""Close stream."""
if self.writer.can_write_eof():
| python | {
"resource": ""
} |
q274779 | parse_str_to_expression | test | def parse_str_to_expression(fiql_str):
"""Parse a FIQL formatted string into an ``Expression``.
Args:
fiql_str (string): The FIQL formatted string we want to parse.
Returns:
Expression: An ``Expression`` object representing the parsed FIQL
string.
Raises:
FiqlFormatException: Unable to parse string due to incorrect
formatting.
Example:
>>> expression = parse_str_to_expression(
... "name==bar,dob=gt=1990-01-01")
"""
#pylint: disable=too-many-branches
nesting_lvl = 0
last_element = None
expression = Expression()
for (preamble, selector, comparison, argument) in iter_parse(fiql_str):
if preamble:
for char in preamble:
if char == '(':
if isinstance(last_element, BaseExpression):
raise FiqlFormatException(
"%s can not be followed by %s" % (
last_element.__class__, Expression))
expression = expression.create_nested_expression()
nesting_lvl += 1
elif char == ')':
expression = expression.get_parent()
last_element = expression
nesting_lvl -= 1
else:
if not expression.has_constraint():
raise FiqlFormatException(
"%s proceeding initial %s" % (
Operator, Constraint))
if isinstance(last_element, | python | {
"resource": ""
} |
q274780 | dump | test | def dump(ndb_model, fp, **kwargs):
"""Custom json dump using the custom | python | {
"resource": ""
} |
q274781 | NdbDecoder.object_hook_handler | test | def object_hook_handler(self, val):
"""Handles decoding of nested date strings."""
return {k: | python | {
"resource": ""
} |
q274782 | NdbDecoder.decode_date | test | def decode_date(self, val):
"""Tries to decode strings that look like dates into datetime objects."""
if isinstance(val, basestring) and val.count('-') == 2 and len(val) > 9:
try:
dt = dateutil.parser.parse(val)
# Check for UTC.
if val.endswith(('+00:00', '-00:00', 'Z')):
| python | {
"resource": ""
} |
q274783 | NdbDecoder.decode | test | def decode(self, val):
"""Override of the default decode method that also uses decode_date."""
# First try the date decoder.
new_val = self.decode_date(val)
if val != new_val:
| python | {
"resource": ""
} |
q274784 | NdbEncoder.default | test | def default(self, obj):
"""Overriding the default JSONEncoder.default for NDB support."""
obj_type = type(obj)
# NDB Models return a repr to calls from type().
if obj_type not in self._ndb_type_encoding:
if hasattr(obj, '__metaclass__'):
obj_type = obj.__metaclass__
else:
# Try to encode subclasses of types
| python | {
"resource": ""
} |
q274785 | validate_version | test | def validate_version():
"""Validate version before release."""
import leicacam
version_string = leicacam.__version__
versions = version_string.split('.', 3)
try:
for ver in versions:
int(ver)
except ValueError:
| python | {
"resource": ""
} |
q274786 | generate | test | def generate():
"""Generate changelog."""
old_dir = os.getcwd()
proj_dir = os.path.join(os.path.dirname(__file__), os.pardir)
os.chdir(proj_dir)
version = validate_version()
if not version:
os.chdir(old_dir)
return
print('Generating changelog for version {}'.format(version))
options = [
| python | {
"resource": ""
} |
q274787 | strongly_connected_components | test | def strongly_connected_components(graph: Graph) -> List:
"""Find the strongly connected components in a graph using Tarjan's algorithm.
The `graph` argument should be a dictionary mapping node names to sequences of successor nodes.
"""
assert check_argument_types()
result = []
stack = []
low = {}
def visit(node: str):
if node in low: return
num = len(low)
low[node] = num
stack_pos = len(stack)
stack.append(node)
| python | {
"resource": ""
} |
q274788 | robust_topological_sort | test | def robust_topological_sort(graph: Graph) -> list:
"""Identify strongly connected components then perform a topological sort of those components."""
assert check_argument_types()
components = strongly_connected_components(graph)
node_component = {}
for component in components:
for node in component:
node_component[node] = component
component_graph = {}
for component in components:
component_graph[component] = []
for node in graph: | python | {
"resource": ""
} |
q274789 | BaseExpression.set_parent | test | def set_parent(self, parent):
"""Set parent ``Expression`` for this object.
Args:
parent (Expression): The ``Expression`` which contains this object.
Raises:
FiqlObjectException: Parent must be of type ``Expression``.
"""
| python | {
"resource": ""
} |
q274790 | BaseExpression.get_parent | test | def get_parent(self):
"""Get the parent ``Expression`` for this object.
Returns:
Expression: The ``Expression`` which contains this object.
Raises:
FiqlObjectException: Parent is ``None``.
"""
if not isinstance(self.parent, | python | {
"resource": ""
} |
q274791 | Expression.add_operator | test | def add_operator(self, operator):
"""Add an ``Operator`` to the ``Expression``.
The ``Operator`` may result in a new ``Expression`` if an ``Operator``
already exists and is of a different precedence.
There are three possibilities when adding an ``Operator`` to an
``Expression`` depending on whether or not an ``Operator`` already
exists:
- No ``Operator`` on the working ``Expression``; Simply set the
``Operator`` and return ``self``.
- ``Operator`` already exists and is higher in precedence; The
``Operator`` and last ``Constraint`` belong in a sub-expression of
the working ``Expression``.
- ``Operator`` already exists and is lower in precedence; The
``Operator`` belongs to the parent of the working ``Expression``
whether one currently exists or not. To remain in the context of
the top ``Expression``, this method will return the parent here
rather than ``self``.
Args:
operator (Operator): What we are adding.
Returns:
Expression: ``self`` or related ``Expression``.
Raises:
FiqlObjectExpression: Operator is not a valid ``Operator``.
"""
if not | python | {
"resource": ""
} |
q274792 | Expression.add_element | test | def add_element(self, element):
"""Add an element of type ``Operator``, ``Constraint``, or
``Expression`` to the ``Expression``.
Args:
element: ``Constraint``, ``Expression``, or ``Operator``.
Returns:
Expression: ``self``
Raises:
FiqlObjectException: Element is not a valid type.
"""
if isinstance(element, BaseExpression):
| python | {
"resource": ""
} |
q274793 | Expression.op_and | test | def op_and(self, *elements):
"""Update the ``Expression`` by joining the specified additional
``elements`` using an "AND" ``Operator``
Args:
*elements (BaseExpression): The ``Expression`` and/or
| python | {
"resource": ""
} |
q274794 | Expression.op_or | test | def op_or(self, *elements):
"""Update the ``Expression`` by joining the specified additional
``elements`` using an "OR" ``Operator``
Args:
*elements (BaseExpression): The ``Expression`` and/or
| python | {
"resource": ""
} |
q274795 | logger | test | def logger(function):
"""Decorate passed in function and log message to module logger."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
"""Wrap function."""
sep = kwargs.get('sep', ' ')
end = kwargs.get('end', '') # do not add newline by default
| python | {
"resource": ""
} |
q274796 | _parse_receive | test | def _parse_receive(incomming):
"""Parse received response.
Parameters
----------
incomming : bytes string
Incomming bytes from socket server.
Returns
-------
list of OrderedDict
Received message as a list of OrderedDict.
"""
debug(b'< ' + incomming)
# remove terminating null byte | python | {
"resource": ""
} |
q274797 | tuples_as_dict | test | def tuples_as_dict(_list):
"""Translate a list of tuples to OrderedDict with key and val as strings.
Parameters
----------
_list : list of tuples
Returns
-------
collections.OrderedDict
Example
-------
::
>>> tuples_as_dict([('cmd', 'val'), ('cmd2', 'val2')])
| python | {
"resource": ""
} |
q274798 | check_messages | test | def check_messages(msgs, cmd, value=None):
"""Check if specific message is present.
Parameters
----------
cmd : string
Command to check for in bytestring from microscope CAM interface. If
``value`` is falsey, value of received command does not matter.
value : string
Check if ``cmd:value`` is received.
Returns
-------
| python | {
"resource": ""
} |
q274799 | BaseCAM._prepare_send | test | def _prepare_send(self, commands):
"""Prepare message to be sent.
Parameters
----------
commands : list of tuples or bytes string
Commands as a list of tuples or a bytes string. cam.prefix is
allways prepended before sending.
Returns
-------
string
Message to be sent.
"""
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.