repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
ahawker/ulid | ulid/base32.py | decode_randomness | python | def decode_randomness(randomness: str) -> bytes:
encoded = str_to_bytes(randomness, 16)
decoding = DECODING
return bytes((
((decoding[encoded[0]] << 3) | (decoding[encoded[1]] >> 2)) & 0xFF,
((decoding[encoded[1]] << 6) | (decoding[encoded[2]] << 1) | (decoding[encoded[3]] >> 4)) & 0xFF,
... | Decode the given Base32 encoded :class:`~str` instance to :class:`~bytes`.
The given :class:`~str` are expected to represent the last 16 characters of a ULID, which
are cryptographically secure random values.
.. note:: This uses an optimized strategy from the `NUlid` project for decoding ULID
stri... | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/base32.py#L305-L337 | [
"def str_to_bytes(value: str, expected_length: int) -> bytes:\n \"\"\"\n Convert the given string to bytes and validate it is within the Base32 character set.\n\n :param value: String to convert to bytes\n :type value: :class:`~str`\n :param expected_length: Expected length of the input string\n :... | """
ulid/base32
~~~~~~~~~~~
Functionality for encoding/decoding ULID strings/bytes using Base32 format.
.. note:: This module makes the trade-off of code duplication for inline
computations over multiple function calls for performance reasons. I'll
check metrics in the future to see ho... |
ahawker/ulid | ulid/base32.py | str_to_bytes | python | def str_to_bytes(value: str, expected_length: int) -> bytes:
length = len(value)
if length != expected_length:
raise ValueError('Expects {} characters for decoding; got {}'.format(expected_length, length))
try:
encoded = value.encode('ascii')
except UnicodeEncodeError as ex:
rai... | Convert the given string to bytes and validate it is within the Base32 character set.
:param value: String to convert to bytes
:type value: :class:`~str`
:param expected_length: Expected length of the input string
:type expected_length: :class:`~int`
:return: Value converted to bytes.
:rtype: :... | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/base32.py#L340-L368 | null | """
ulid/base32
~~~~~~~~~~~
Functionality for encoding/decoding ULID strings/bytes using Base32 format.
.. note:: This module makes the trade-off of code duplication for inline
computations over multiple function calls for performance reasons. I'll
check metrics in the future to see ho... |
tommikaikkonen/prettyprinter | prettyprinter/prettyprinter.py | comment | python | def comment(value, comment_text):
if isinstance(value, Doc):
return comment_doc(value, comment_text)
return comment_value(value, comment_text) | Annotates a value or a Doc with a comment.
When printed by prettyprinter, the comment will be
rendered next to the value or Doc. | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/prettyprinter.py#L156-L164 | [
"def comment_doc(doc, comment_text):\n \"\"\"Annotates a Doc with a comment; used by the layout algorithm.\n\n You don't need to call this unless you're doing something low-level\n with Docs; use ``comment`` instead.\n\n ``prettyprinter`` will make sure the parent (or top-level) handler\n will render... | import inspect
import math
import re
import sys
import warnings
import ast
from collections import OrderedDict
from functools import singledispatch, partial
from itertools import chain, cycle
from traceback import format_exception
from types import (
FunctionType,
BuiltinFunctionType,
BuiltinMethodType
)
fr... |
tommikaikkonen/prettyprinter | prettyprinter/prettyprinter.py | register_pretty | python | def register_pretty(type=None, predicate=None):
if type is None and predicate is None:
raise ValueError(
"You must provide either the 'type' or 'predicate' argument."
)
if type is not None and predicate is not None:
raise ValueError(
"You must provide either the... | Returns a decorator that registers the decorated function
as the pretty printer for instances of ``type``.
:param type: the type to register the pretty printer for, or a ``str``
to indicate the module and name, e.g.: ``'collections.Counter'``.
:param predicate: a predicate function that ta... | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/prettyprinter.py#L462-L544 | null | import inspect
import math
import re
import sys
import warnings
import ast
from collections import OrderedDict
from functools import singledispatch, partial
from itertools import chain, cycle
from traceback import format_exception
from types import (
FunctionType,
BuiltinFunctionType,
BuiltinMethodType
)
fr... |
tommikaikkonen/prettyprinter | prettyprinter/prettyprinter.py | commentdoc | python | def commentdoc(text):
if not text:
raise ValueError(
'Expected non-empty comment str, got {}'.format(repr(text))
)
commentlines = []
for line in text.splitlines():
alternating_words_ws = list(filter(None, WHITESPACE_PATTERN_TEXT.split(line)))
starts_with_whitespa... | Returns a Doc representing a comment `text`. `text` is
treated as words, and any whitespace may be used to break
the comment to multiple lines. | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/prettyprinter.py#L599-L654 | [
"def concat(docs):\n \"\"\"Returns a concatenation of the documents in the iterable argument\"\"\"\n return Concat(map(validate_doc, docs))\n",
"def fill(docs):\n return Fill(map(validate_doc, docs))\n",
"def identity(x):\n return x\n",
"def intersperse(x, ys):\n \"\"\"\n Returns an iterable... | import inspect
import math
import re
import sys
import warnings
import ast
from collections import OrderedDict
from functools import singledispatch, partial
from itertools import chain, cycle
from traceback import format_exception
from types import (
FunctionType,
BuiltinFunctionType,
BuiltinMethodType
)
fr... |
tommikaikkonen/prettyprinter | prettyprinter/prettyprinter.py | pretty_call | python | def pretty_call(ctx, fn, *args, **kwargs):
return pretty_call_alt(ctx, fn, args, kwargs) | Returns a Doc that represents a function call to :keyword:`fn` with
the remaining positional and keyword arguments.
You can only use this function on Python 3.6+. On Python 3.5, the order
of keyword arguments is not maintained, and you have to use
:func:`~prettyprinter.pretty_call_alt`.
Given an a... | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/prettyprinter.py#L728-L761 | [
"def pretty_call_alt(ctx, fn, args=(), kwargs=()):\n \"\"\"Returns a Doc that represents a function call to :keyword:`fn` with\n the ``args`` and ``kwargs``.\n\n Given an arbitrary context ``ctx``,::\n\n pretty_call_alt(ctx, sorted, args=([7, 4, 5], ), kwargs=[('reverse', True)])\n\n Will result ... | import inspect
import math
import re
import sys
import warnings
import ast
from collections import OrderedDict
from functools import singledispatch, partial
from itertools import chain, cycle
from traceback import format_exception
from types import (
FunctionType,
BuiltinFunctionType,
BuiltinMethodType
)
fr... |
tommikaikkonen/prettyprinter | prettyprinter/prettyprinter.py | pretty_call_alt | python | def pretty_call_alt(ctx, fn, args=(), kwargs=()):
fndoc = general_identifier(fn)
if ctx.depth_left <= 0:
return concat([fndoc, LPAREN, ELLIPSIS, RPAREN])
if not kwargs and len(args) == 1:
sole_arg = args[0]
unwrapped_sole_arg, _comment, _trailing_comment = unwrap_comments(args[0])... | Returns a Doc that represents a function call to :keyword:`fn` with
the ``args`` and ``kwargs``.
Given an arbitrary context ``ctx``,::
pretty_call_alt(ctx, sorted, args=([7, 4, 5], ), kwargs=[('reverse', True)])
Will result in output::
sorted([7, 4, 5], reverse=True)
The layout algo... | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/prettyprinter.py#L764-L846 | [
"def concat(docs):\n \"\"\"Returns a concatenation of the documents in the iterable argument\"\"\"\n return Concat(map(validate_doc, docs))\n",
"def build_fncall(\n ctx,\n fndoc,\n argdocs=(),\n kwargdocs=(),\n hug_sole_arg=False,\n trailing_comment=None,\n):\n \"\"\"Builds a doc that l... | import inspect
import math
import re
import sys
import warnings
import ast
from collections import OrderedDict
from functools import singledispatch, partial
from itertools import chain, cycle
from traceback import format_exception
from types import (
FunctionType,
BuiltinFunctionType,
BuiltinMethodType
)
fr... |
tommikaikkonen/prettyprinter | prettyprinter/prettyprinter.py | build_fncall | python | def build_fncall(
ctx,
fndoc,
argdocs=(),
kwargdocs=(),
hug_sole_arg=False,
trailing_comment=None,
):
if callable(fndoc):
fndoc = general_identifier(fndoc)
has_comment = bool(trailing_comment)
argdocs = list(argdocs)
kwargdocs = list(kwargdocs)
kwargdocs = [
... | Builds a doc that looks like a function call,
from docs that represent the function, arguments
and keyword arguments.
If ``hug_sole_arg`` is True, and the represented
functional call is done with a single non-keyword
argument, the function call parentheses will hug
the sole argument doc without... | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/prettyprinter.py#L849-L1003 | [
"def group(doc):\n \"\"\"Annotates doc with special meaning to the layout algorithm, so that the\n document is attempted to output on a single line if it is possible within\n the layout constraints. To lay out the doc on a single line, the `when_flat`\n branch of ``FlatChoice`` is used.\"\"\"\n retur... | import inspect
import math
import re
import sys
import warnings
import ast
from collections import OrderedDict
from functools import singledispatch, partial
from itertools import chain, cycle
from traceback import format_exception
from types import (
FunctionType,
BuiltinFunctionType,
BuiltinMethodType
)
fr... |
tommikaikkonen/prettyprinter | prettyprinter/prettyprinter.py | PrettyContext.assoc | python | def assoc(self, key, value):
return self._replace(user_ctx={
**self.user_ctx,
key: value,
}) | Return a modified PrettyContext with ``key`` set to ``value`` | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/prettyprinter.py#L297-L304 | [
"def _replace(self, **kwargs):\n passed_keys = set(kwargs.keys())\n fieldnames = type(self).__slots__\n assert passed_keys.issubset(set(fieldnames))\n return PrettyContext(\n **{\n k: (\n kwargs[k]\n if k in passed_keys\n else getattr(self, ... | class PrettyContext:
"""
An immutable object used to track context during construction of
layout primitives. An instance of PrettyContext is passed to every
pretty printer definition.
As a performance optimization, the ``visited`` set is implemented
as mutable.
"""
__slots__ = (
... |
tommikaikkonen/prettyprinter | prettyprinter/doc.py | align | python | def align(doc):
validate_doc(doc)
def evaluator(indent, column, page_width, ribbon_width):
return Nest(column - indent, doc)
return contextual(evaluator) | Aligns each new line in ``doc`` with the first new line. | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/doc.py#L57-L64 | [
"def validate_doc(doc):\n if not isinstance(doc, Doc) and not isinstance(doc, str):\n raise ValueError('Invalid doc: {}'.format(repr(doc)))\n\n return doc\n",
"def contextual(fn):\n \"\"\"Returns a Doc that is lazily evaluated when deciding the layout.\n\n ``fn`` must be a function that accepts... | from .doctypes import ( # noqa
AlwaysBreak,
Concat,
Contextual,
Doc,
FlatChoice,
Fill,
Group,
Nest,
Annotated,
NIL,
LINE,
SOFTLINE,
HARDLINE,
)
from .utils import intersperse # noqa
def validate_doc(doc):
if not isinstance(doc, Doc) and not isinstance(doc, str... |
tommikaikkonen/prettyprinter | prettyprinter/layout.py | smart_fitting_predicate | python | def smart_fitting_predicate(
page_width,
ribbon_frac,
min_nesting_level,
max_width,
triplestack
):
chars_left = max_width
while chars_left >= 0:
if not triplestack:
return True
indent, mode, doc = triplestack.pop()
if doc is NIL:
continue
... | Lookahead until the last doc at the current indentation level.
Pretty, but not as fast. | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/layout.py#L124-L208 | [
"def normalize_doc(doc):\n if isinstance(doc, str):\n if doc == '':\n return NIL\n return doc\n return doc.normalize()\n"
] | """
The layout algorithm here was inspired by the following
papers and libraries:
- Wadler, P. (1998). A prettier printer
https://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf
- Lindig, C. (2000) Strictly Pretty
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.34.2200
- Extensions to the Wa... |
tommikaikkonen/prettyprinter | prettyprinter/color.py | set_default_style | python | def set_default_style(style):
global default_style
if style == 'dark':
style = default_dark_style
elif style == 'light':
style = default_light_style
if not issubclass(style, Style):
raise TypeError(
"style must be a subclass of pygments.styles.Style or "
... | Sets default global style to be used by ``prettyprinter.cpprint``.
:param style: the style to set, either subclass of
``pygments.styles.Style`` or one of ``'dark'``, ``'light'`` | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/color.py#L134-L151 | null | import os
import colorful
from pygments import token, styles
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, Text, \
Number, Operator, Generic, Whitespace, Punctuation, Other, Literal
from .sdoctypes import (
SLine,
SAnnotationPush,
SAnnotationPop,
)
... |
tommikaikkonen/prettyprinter | prettyprinter/extras/ipython_repr_pretty.py | CompatRepresentationPrinter.indent | python | def indent(self, indent):
curr_docparts = self._docparts
self._docparts = []
self.indentation += indent
try:
yield
finally:
self.indentation -= indent
indented_docparts = self._docparts
self._docparts = curr_docparts
sel... | with statement support for indenting/dedenting. | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/extras/ipython_repr_pretty.py#L81-L92 | [
"def concat(docs):\n \"\"\"Returns a concatenation of the documents in the iterable argument\"\"\"\n return Concat(map(validate_doc, docs))\n",
"def nest(i, doc):\n return Nest(i, validate_doc(doc))\n"
] | class CompatRepresentationPrinter(OriginalRepresentationPrinter):
def __init__(self, *args, **kwargs):
self._prettyprinter_ctx = kwargs.pop('prettyprinter_ctx')
super().__init__(*args, **kwargs)
# self.output should be assigned by the superclass
assert isinstance(self.output, NoopSt... |
tommikaikkonen/prettyprinter | prettyprinter/utils.py | intersperse | python | def intersperse(x, ys):
it = iter(ys)
try:
y = next(it)
except StopIteration:
return
yield y
for y in it:
yield x
yield y | Returns an iterable where ``x`` is inserted between
each element of ``ys``
:type ys: Iterable | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/utils.py#L5-L23 | null | from itertools import islice
import shutil
def find(predicate, iterable, default=None):
filtered = iter((x for x in iterable if predicate(x)))
return next(filtered, default)
def rfind_idx(predicate, seq):
length = len(seq)
for i, el in enumerate(reversed(seq)):
if predicate(el):
... |
tommikaikkonen/prettyprinter | prettyprinter/__init__.py | pformat | python | def pformat(
object,
indent=_UNSET_SENTINEL,
width=_UNSET_SENTINEL,
depth=_UNSET_SENTINEL,
*,
ribbon_width=_UNSET_SENTINEL,
max_seq_len=_UNSET_SENTINEL,
compact=_UNSET_SENTINEL,
sort_dict_keys=_UNSET_SENTINEL
):
sdocs = python_to_sdocs(
object,
**_merge_defaults(
... | Returns a pretty printed representation of the object as a ``str``.
Accepts the same parameters as :func:`~prettyprinter.pprint`.
The output is not colored. | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/__init__.py#L110-L139 | [
"def python_to_sdocs(\n value,\n indent,\n width,\n depth,\n ribbon_width,\n max_seq_len,\n sort_dict_keys\n):\n if depth is None:\n depth = float('inf')\n\n doc = pretty_python_value(\n value,\n ctx=PrettyContext(\n indent=indent,\n depth_left=d... | # -*- coding: utf-8 -*-
"""Top-level package for prettyprinter."""
__author__ = """Tommi Kaikkonen"""
__email__ = 'kaikkonentommi@gmail.com'
__version__ = '0.17.0'
from io import StringIO
from importlib import import_module
from types import MappingProxyType
import sys
import warnings
from pprint import isrecursive... |
tommikaikkonen/prettyprinter | prettyprinter/__init__.py | pprint | python | def pprint(
object,
stream=_UNSET_SENTINEL,
indent=_UNSET_SENTINEL,
width=_UNSET_SENTINEL,
depth=_UNSET_SENTINEL,
*,
compact=False,
ribbon_width=_UNSET_SENTINEL,
max_seq_len=_UNSET_SENTINEL,
sort_dict_keys=_UNSET_SENTINEL,
end='\n'
):
sdocs = python_to_sdocs(
obje... | Pretty print a Python value ``object`` to ``stream``,
which defaults to ``sys.stdout``. The output will not be colored.
:param indent: number of spaces to add for each level of nesting.
:param stream: the output stream, defaults to ``sys.stdout``
:param width: a soft maximum allowed number of columns i... | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/__init__.py#L142-L195 | [
"def python_to_sdocs(\n value,\n indent,\n width,\n depth,\n ribbon_width,\n max_seq_len,\n sort_dict_keys\n):\n if depth is None:\n depth = float('inf')\n\n doc = pretty_python_value(\n value,\n ctx=PrettyContext(\n indent=indent,\n depth_left=d... | # -*- coding: utf-8 -*-
"""Top-level package for prettyprinter."""
__author__ = """Tommi Kaikkonen"""
__email__ = 'kaikkonentommi@gmail.com'
__version__ = '0.17.0'
from io import StringIO
from importlib import import_module
from types import MappingProxyType
import sys
import warnings
from pprint import isrecursive... |
tommikaikkonen/prettyprinter | prettyprinter/__init__.py | cpprint | python | def cpprint(
object,
stream=_UNSET_SENTINEL,
indent=_UNSET_SENTINEL,
width=_UNSET_SENTINEL,
depth=_UNSET_SENTINEL,
*,
compact=False,
ribbon_width=_UNSET_SENTINEL,
max_seq_len=_UNSET_SENTINEL,
sort_dict_keys=_UNSET_SENTINEL,
style=None,
end='\n'
):
sdocs = python_to_sd... | Pretty print a Python value ``object`` to ``stream``,
which defaults to sys.stdout. The output will be colored and
syntax highlighted.
:param indent: number of spaces to add for each level of nesting.
:param stream: the output stream, defaults to sys.stdout
:param width: a soft maximum allowed numb... | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/__init__.py#L198-L257 | [
"def colored_render_to_stream(\n stream,\n sdocs,\n style,\n newline='\\n',\n separator=' '\n):\n if style is None:\n style = default_style\n\n evald = list(sdocs)\n\n if not evald:\n return\n\n color_cache = {}\n\n colorstack = []\n\n sdoc_lines = as_lines(evald)\n\n ... | # -*- coding: utf-8 -*-
"""Top-level package for prettyprinter."""
__author__ = """Tommi Kaikkonen"""
__email__ = 'kaikkonentommi@gmail.com'
__version__ = '0.17.0'
from io import StringIO
from importlib import import_module
from types import MappingProxyType
import sys
import warnings
from pprint import isrecursive... |
tommikaikkonen/prettyprinter | prettyprinter/__init__.py | install_extras | python | def install_extras(
include=ALL_EXTRAS,
*,
exclude=EMPTY_SET,
raise_on_error=False,
warn_on_error=True
):
"""Installs extras.
Installing an extra means registering pretty printers for objects from third
party libraries and/or enabling integrations with other python programs.
- ``'a... | Installs extras.
Installing an extra means registering pretty printers for objects from third
party libraries and/or enabling integrations with other python programs.
- ``'attrs'`` - automatically pretty prints classes created using the ``attrs`` package.
- ``'dataclasses'`` - automatically pretty pri... | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/__init__.py#L273-L341 | null | # -*- coding: utf-8 -*-
"""Top-level package for prettyprinter."""
__author__ = """Tommi Kaikkonen"""
__email__ = 'kaikkonentommi@gmail.com'
__version__ = '0.17.0'
from io import StringIO
from importlib import import_module
from types import MappingProxyType
import sys
import warnings
from pprint import isrecursive... |
tommikaikkonen/prettyprinter | prettyprinter/__init__.py | set_default_config | python | def set_default_config(
*,
style=_UNSET_SENTINEL,
max_seq_len=_UNSET_SENTINEL,
width=_UNSET_SENTINEL,
ribbon_width=_UNSET_SENTINEL,
depth=_UNSET_SENTINEL,
sort_dict_keys=_UNSET_SENTINEL
):
global _default_config
if style is not _UNSET_SENTINEL:
set_default_style(style)
... | Sets the default configuration values used when calling
`pprint`, `cpprint`, or `pformat`, if those values weren't
explicitly provided. Only overrides the values provided in
the keyword arguments. | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/__init__.py#L344-L382 | [
"def set_default_style(style):\n \"\"\"Sets default global style to be used by ``prettyprinter.cpprint``.\n\n :param style: the style to set, either subclass of\n ``pygments.styles.Style`` or one of ``'dark'``, ``'light'``\n \"\"\"\n global default_style\n if style == 'dark':\n ... | # -*- coding: utf-8 -*-
"""Top-level package for prettyprinter."""
__author__ = """Tommi Kaikkonen"""
__email__ = 'kaikkonentommi@gmail.com'
__version__ = '0.17.0'
from io import StringIO
from importlib import import_module
from types import MappingProxyType
import sys
import warnings
from pprint import isrecursive... |
tommikaikkonen/prettyprinter | prettyprinter/__init__.py | pretty_repr | python | def pretty_repr(instance):
instance_type = type(instance)
if not is_registered(
instance_type,
check_superclasses=True,
check_deferred=True,
register_deferred=True
):
warnings.warn(
"pretty_repr is assigned as the __repr__ method of "
"'{}'. H... | A function assignable to the ``__repr__`` dunder method, so that
the ``prettyprinter`` definition for the type is used to provide
repr output. Usage:
.. code:: python
from prettyprinter import pretty_repr
class MyClass:
__repr__ = pretty_repr | train | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/__init__.py#L385-L419 | [
"def is_registered(\n type,\n *,\n check_superclasses=False,\n check_deferred=True,\n register_deferred=True\n):\n if not check_deferred and register_deferred:\n raise ValueError(\n 'register_deferred may not be True when check_deferred is False'\n )\n\n if type in pret... | # -*- coding: utf-8 -*-
"""Top-level package for prettyprinter."""
__author__ = """Tommi Kaikkonen"""
__email__ = 'kaikkonentommi@gmail.com'
__version__ = '0.17.0'
from io import StringIO
from importlib import import_module
from types import MappingProxyType
import sys
import warnings
from pprint import isrecursive... |
kstateome/django-cas | cas/models.py | get_tgt_for | python | def get_tgt_for(user):
if not settings.CAS_PROXY_CALLBACK:
raise CasConfigException("No proxy callback set in settings")
try:
return Tgt.objects.get(username=user.username)
except ObjectDoesNotExist:
logger.warning('No ticket found for user {user}'.format(
user=user.user... | Fetch a ticket granting ticket for a given user.
:param user: UserObj
:return: TGT or Exepction | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/models.py#L77-L94 | null | import logging
from datetime import datetime
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
try:
from urlparse import urljoin
except ImportError:
from urllib.parse import urljoin
try:
from urllib import urlencode
except ImportError:
from urllib.par... |
kstateome/django-cas | cas/models.py | delete_old_tickets | python | def delete_old_tickets(**kwargs):
sender = kwargs.get('sender', None)
now = datetime.now()
expire = datetime(now.year, now.month, now.day - 2)
sender.objects.filter(created__lt=expire).delete() | Delete tickets if they are over 2 days old
kwargs = ['raw', 'signal', 'instance', 'sender', 'created'] | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/models.py#L97-L106 | null | import logging
from datetime import datetime
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
try:
from urlparse import urljoin
except ImportError:
from urllib.parse import urljoin
try:
from urllib import urlencode
except ImportError:
from urllib.par... |
kstateome/django-cas | cas/models.py | Tgt.get_proxy_ticket_for | python | def get_proxy_ticket_for(self, service):
if not settings.CAS_PROXY_CALLBACK:
raise CasConfigException("No proxy callback set in settings")
params = {'pgt': self.tgt, 'targetService': service}
url = (urljoin(settings.CAS_SERVER_URL, 'proxy') + '?' +
urlencode(params)... | Verifies CAS 2.0+ XML-based authentication ticket.
:param: service
Returns username on success and None on failure. | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/models.py#L36-L65 | null | class Tgt(models.Model):
username = models.CharField(max_length=255, unique=True)
tgt = models.CharField(max_length=255)
|
kstateome/django-cas | cas/backends.py | _verify_cas1 | python | def _verify_cas1(ticket, service):
params = {'ticket': ticket, 'service': service}
url = (urljoin(settings.CAS_SERVER_URL, 'validate') + '?' +
urlencode(params))
page = urlopen(url)
try:
verified = page.readline().strip()
if verified == 'yes':
return page.readlin... | Verifies CAS 1.0 authentication ticket.
:param: ticket
:param: service
Returns username on success and None on failure. | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/backends.py#L36-L58 | null | import logging
from xml.dom import minidom
import time
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
try:
from urllib import urlopen
except ImportError:
fro... |
kstateome/django-cas | cas/backends.py | _internal_verify_cas | python | def _internal_verify_cas(ticket, service, suffix):
params = {'ticket': ticket, 'service': service}
if settings.CAS_PROXY_CALLBACK:
params['pgtUrl'] = settings.CAS_PROXY_CALLBACK
url = (urljoin(settings.CAS_SERVER_URL, suffix) + '?' +
urlencode(params))
page = urlopen(url)
user... | Verifies CAS 2.0 and 3.0 XML-based authentication ticket.
Returns username on success and None on failure. | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/backends.py#L75-L138 | null | import logging
from xml.dom import minidom
import time
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
try:
from urllib import urlopen
except ImportError:
fro... |
kstateome/django-cas | cas/backends.py | verify_proxy_ticket | python | def verify_proxy_ticket(ticket, service):
params = {'ticket': ticket, 'service': service}
url = (urljoin(settings.CAS_SERVER_URL, 'proxyValidate') + '?' +
urlencode(params))
page = urlopen(url)
try:
response = page.read()
tree = ElementTree.fromstring(response)
if ... | Verifies CAS 2.0+ XML-based proxy ticket.
:param: ticket
:param: service
Returns username on success and None on failure. | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/backends.py#L141-L171 | null | import logging
from xml.dom import minidom
import time
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
try:
from urllib import urlopen
except ImportError:
fro... |
kstateome/django-cas | cas/backends.py | _get_pgtiou | python | def _get_pgtiou(pgt):
pgtIou = None
retries_left = 5
if not settings.CAS_PGT_FETCH_WAIT:
retries_left = 1
while not pgtIou and retries_left:
try:
return PgtIOU.objects.get(tgt=pgt)
except PgtIOU.DoesNotExist:
if settings.CAS_PGT_FETCH_WAIT:
... | Returns a PgtIOU object given a pgt.
The PgtIOU (tgt) is set by the CAS server in a different request
that has completed before this call, however, it may not be found in
the database by this calling thread, hence the attempt to get the
ticket is retried for up to 5 seconds. This should be handled some... | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/backends.py#L181-L213 | null | import logging
from xml.dom import minidom
import time
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
try:
from urllib import urlopen
except ImportError:
fro... |
kstateome/django-cas | cas/backends.py | CASBackend.authenticate | python | def authenticate(self, request, ticket, service):
User = get_user_model()
username = _verify(ticket, service)
if not username:
return None
try:
user = User.objects.get(username__iexact=username)
except User.DoesNotExist:
# user will have an ... | Verifies CAS ticket and gets or creates User object
NB: Use of PT to identify proxy | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/backends.py#L224-L245 | null | class CASBackend(object):
"""
CAS authentication backend
"""
supports_object_permissions = False
supports_inactive_user = False
def get_user(self, user_id):
"""
Retrieve the user's entry in the User model if it exists
"""
User = get_user_model()
try:
... |
kstateome/django-cas | cas/decorators.py | gateway | python | def gateway():
if settings.CAS_GATEWAY == False:
raise ImproperlyConfigured('CAS_GATEWAY must be set to True')
def wrap(func):
def wrapped_f(*args):
from cas.views import login
request = args[0]
try:
# use callable for pre-django 2.0
... | Authenticates single sign on session if ticket is available,
but doesn't redirect to sign in url otherwise. | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/decorators.py#L60-L106 | null | try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponseForbidden, HttpResponseRedirec... |
kstateome/django-cas | cas/views.py | _service_url | python | def _service_url(request, redirect_to=None, gateway=False):
if settings.CAS_FORCE_SSL_SERVICE_URL:
protocol = 'https://'
else:
protocol = ('http://', 'https://')[request.is_secure()]
host = request.get_host()
service = protocol + host + request.path
if redirect_to:
if '?' in... | Generates application service URL for CAS
:param: request Request Object
:param: redirect_to URL to redriect to
:param: gateway Should this be a gatewayed pass through | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/views.py#L32-L79 | null | import logging
import datetime
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
from operator import itemgetter
from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpRes... |
kstateome/django-cas | cas/views.py | _redirect_url | python | def _redirect_url(request):
next = request.GET.get(REDIRECT_FIELD_NAME)
if not next:
if settings.CAS_IGNORE_REFERER:
next = settings.CAS_REDIRECT_URL
else:
next = request.META.get('HTTP_REFERER', settings.CAS_REDIRECT_URL)
host = request.get_host()
pref... | Redirects to referring page, or CAS_REDIRECT_URL if no referrer is
set.
:param: request RequestObj | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/views.py#L82-L105 | null | import logging
import datetime
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
from operator import itemgetter
from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpRes... |
kstateome/django-cas | cas/views.py | _login_url | python | def _login_url(service, ticket='ST', gateway=False):
LOGINS = {'ST': 'login',
'PT': 'proxyValidate'}
if gateway:
params = {'service': service, 'gateway': 'true'}
else:
params = {'service': service}
if settings.CAS_EXTRA_LOGIN_PARAMS:
params.update(settings.CAS_EXT... | Generates CAS login URL
:param: service Service URL
:param: ticket Ticket
:param: gateway Gatewayed | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/views.py#L108-L133 | null | import logging
import datetime
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
from operator import itemgetter
from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpRes... |
kstateome/django-cas | cas/views.py | _logout_url | python | def _logout_url(request, next_page=None):
url = urlparse.urljoin(settings.CAS_SERVER_URL, 'logout')
if next_page and getattr(settings, 'CAS_PROVIDE_URL_TO_LOGOUT', True):
parsed_url = urlparse.urlparse(next_page)
if parsed_url.scheme: #If next_page is a protocol-rooted url, skip redirect url c... | Generates CAS logout URL
:param: request RequestObj
:param: next_page Page to redirect after logout. | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/views.py#L136-L156 | null | import logging
import datetime
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
from operator import itemgetter
from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpRes... |
kstateome/django-cas | cas/views.py | login | python | def login(request, next_page=None, required=False, gateway=False):
if not next_page:
next_page = _redirect_url(request)
try:
# use callable for pre-django 2.0
is_authenticated = request.user.is_authenticated()
except TypeError:
is_authenticated = request.user.is_authenticat... | Forwards to CAS login URL or verifies CAS ticket
:param: request RequestObj
:param: next_page Next page to redirect after login
:param: required
:param: gateway Gatewayed response | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/views.py#L159-L222 | [
"def _redirect_url(request):\n \"\"\"\n Redirects to referring page, or CAS_REDIRECT_URL if no referrer is\n set.\n\n :param: request RequestObj\n\n \"\"\"\n\n next = request.GET.get(REDIRECT_FIELD_NAME)\n\n if not next:\n if settings.CAS_IGNORE_REFERER:\n next = settings.CAS_... | import logging
import datetime
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
from operator import itemgetter
from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpRes... |
kstateome/django-cas | cas/views.py | logout | python | def logout(request, next_page=None):
auth.logout(request)
if not next_page:
next_page = _redirect_url(request)
if settings.CAS_LOGOUT_COMPLETELY:
return HttpResponseRedirect(_logout_url(request, next_page))
else:
return HttpResponseRedirect(next_page) | Redirects to CAS logout page
:param: request RequestObj
:param: next_page Page to redirect to | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/views.py#L225-L242 | [
"def _redirect_url(request):\n \"\"\"\n Redirects to referring page, or CAS_REDIRECT_URL if no referrer is\n set.\n\n :param: request RequestObj\n\n \"\"\"\n\n next = request.GET.get(REDIRECT_FIELD_NAME)\n\n if not next:\n if settings.CAS_IGNORE_REFERER:\n next = settings.CAS_... | import logging
import datetime
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
from operator import itemgetter
from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpRes... |
kstateome/django-cas | cas/views.py | proxy_callback | python | def proxy_callback(request):
pgtIou = request.GET.get('pgtIou')
tgt = request.GET.get('pgtId')
if not (pgtIou and tgt):
logger.info('No pgtIou or tgt found in request.GET')
return HttpResponse('No pgtIOO', content_type="text/plain")
try:
PgtIOU.objects.create(tgt=tgt, pgtIou=p... | Handles CAS 2.0+ XML-based proxy callback call.
Stores the proxy granting ticket in the database for
future use.
NB: Use created and set it in python in case database
has issues with setting up the default timestamp value | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/views.py#L245-L270 | null | import logging
import datetime
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
from operator import itemgetter
from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpRes... |
kstateome/django-cas | cas/middleware.py | CASMiddleware.process_view | python | def process_view(self, request, view_func, view_args, view_kwargs):
if view_func == login:
return cas_login(request, *view_args, **view_kwargs)
elif view_func == logout:
return cas_logout(request, *view_args, **view_kwargs)
if settings.CAS_ADMIN_PREFIX:
if n... | Forwards unauthenticated requests to the admin page to the CAS
login URL, as well as calls to django.contrib.auth.views.login and
logout. | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/middleware.py#L53-L86 | [
"def login(request, next_page=None, required=False, gateway=False):\n \"\"\"\n Forwards to CAS login URL or verifies CAS ticket\n\n :param: request RequestObj\n :param: next_page Next page to redirect after login\n :param: required\n :param: gateway Gatewayed response\n\n \"\"\"\n\n if not n... | class CASMiddleware(MiddlewareMixin):
"""
Middleware that allows CAS authentication on admin pages
"""
def process_request(self, request):
"""
Checks that the authentication middleware is installed
:param: request
"""
error = ("The Django CAS middleware requir... |
kstateome/django-cas | cas/middleware.py | CASMiddleware.process_exception | python | def process_exception(self, request, exception):
if isinstance(exception, CasTicketException):
do_logout(request)
# This assumes that request.path requires authentication.
return HttpResponseRedirect(request.path)
else:
return None | When we get a CasTicketException, that is probably caused by the ticket timing out.
So logout/login and get the same page again. | train | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/middleware.py#L88-L99 | null | class CASMiddleware(MiddlewareMixin):
"""
Middleware that allows CAS authentication on admin pages
"""
def process_request(self, request):
"""
Checks that the authentication middleware is installed
:param: request
"""
error = ("The Django CAS middleware requir... |
tox-dev/tox-travis | src/tox_travis/after.py | travis_after | python | def travis_after(ini, envlist):
# after-all disabled for pull requests
if os.environ.get('TRAVIS_PULL_REQUEST', 'false') != 'false':
return
if not after_config_matches(ini, envlist):
return # This is not the one that needs to wait
github_token = os.environ.get('GITHUB_TOKEN')
if n... | Wait for all jobs to finish, then exit successfully. | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/after.py#L25-L62 | [
"def after_config_matches(ini, envlist):\n \"\"\"Determine if this job should wait for the others.\"\"\"\n section = ini.sections.get('travis:after', {})\n\n if not section:\n return False # Never wait if it's not configured\n\n if 'envlist' in section or 'toxenv' in section:\n if 'toxenv... | """Add a flag to pause and wait for all Travis jobs to complete."""
from __future__ import print_function
import os
import sys
import json
import time
from tox.config import _split_env as split_env
try:
import urllib.request as urllib2
except ImportError:
import urllib2 # Python 2
from .utils import TRAVIS_F... |
tox-dev/tox-travis | src/tox_travis/after.py | after_config_matches | python | def after_config_matches(ini, envlist):
section = ini.sections.get('travis:after', {})
if not section:
return False # Never wait if it's not configured
if 'envlist' in section or 'toxenv' in section:
if 'toxenv' in section:
print('The "toxenv" key of the [travis:after] section... | Determine if this job should wait for the others. | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/after.py#L65-L96 | [
"def parse_dict(value):\n \"\"\"Parse a dict value from the tox config.\n\n .. code-block: ini\n\n [travis]\n python =\n 2.7: py27, docs\n 3.5: py{35,36}\n\n With this config, the value of ``python`` would be parsed\n by this function, and would return::\n\n {\... | """Add a flag to pause and wait for all Travis jobs to complete."""
from __future__ import print_function
import os
import sys
import json
import time
from tox.config import _split_env as split_env
try:
import urllib.request as urllib2
except ImportError:
import urllib2 # Python 2
from .utils import TRAVIS_F... |
tox-dev/tox-travis | src/tox_travis/after.py | get_job_statuses | python | def get_job_statuses(github_token, api_url, build_id,
polling_interval, job_number):
auth = get_json('{api_url}/auth/github'.format(api_url=api_url),
data={'github_token': github_token})['access_token']
while True:
build = get_json('{api_url}/builds/{build_id}'.... | Wait for all the travis jobs to complete.
Once the other jobs are complete, return a list of booleans,
indicating whether or not the job was successful. Ignore jobs
marked "allow_failure". | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/after.py#L99-L127 | [
"def get_json(url, auth=None, data=None):\n \"\"\"Make a GET request, and return the response as parsed JSON.\"\"\"\n headers = {\n 'Accept': 'application/vnd.travis-ci.2+json',\n 'User-Agent': 'Travis/Tox-Travis-1.0a',\n # User-Agent must start with \"Travis/\" in order to work\n }\n ... | """Add a flag to pause and wait for all Travis jobs to complete."""
from __future__ import print_function
import os
import sys
import json
import time
from tox.config import _split_env as split_env
try:
import urllib.request as urllib2
except ImportError:
import urllib2 # Python 2
from .utils import TRAVIS_F... |
tox-dev/tox-travis | src/tox_travis/after.py | get_json | python | def get_json(url, auth=None, data=None):
headers = {
'Accept': 'application/vnd.travis-ci.2+json',
'User-Agent': 'Travis/Tox-Travis-1.0a',
# User-Agent must start with "Travis/" in order to work
}
if auth:
headers['Authorization'] = 'token {auth}'.format(auth=auth)
param... | Make a GET request, and return the response as parsed JSON. | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/after.py#L130-L147 | null | """Add a flag to pause and wait for all Travis jobs to complete."""
from __future__ import print_function
import os
import sys
import json
import time
from tox.config import _split_env as split_env
try:
import urllib.request as urllib2
except ImportError:
import urllib2 # Python 2
from .utils import TRAVIS_F... |
tox-dev/tox-travis | src/tox_travis/envlist.py | detect_envlist | python | def detect_envlist(ini):
# Find the envs that tox knows about
declared_envs = get_declared_envs(ini)
# Find all the envs for all the desired factors given
desired_factors = get_desired_factors(ini)
# Reduce desired factors
desired_envs = ['-'.join(env) for env in product(*desired_factors)]
... | Default envlist automatically based on the Travis environment. | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L14-L27 | [
"def get_declared_envs(ini):\n \"\"\"Get the full list of envs from the tox ini.\n\n This notably also includes envs that aren't in the envlist,\n but are declared by having their own testenv:envname section.\n\n The envs are expected in a particular order. First the ones\n declared in the envlist, t... | """Default Tox envlist based on the Travis environment."""
from __future__ import print_function
import os
import re
import sys
from itertools import product
import tox.config
from tox.config import _split_env as split_env
from .utils import TRAVIS_FACTORS, parse_dict
def autogen_envconfigs(config, envs):
"""... |
tox-dev/tox-travis | src/tox_travis/envlist.py | autogen_envconfigs | python | def autogen_envconfigs(config, envs):
prefix = 'tox' if config.toxinipath.basename == 'setup.cfg' else None
reader = tox.config.SectionReader("tox", config._cfg, prefix=prefix)
distshare_default = "{homedir}/.tox/distshare"
reader.addsubstitutions(toxinidir=config.toxinidir,
... | Make the envconfigs for undeclared envs.
This is a stripped-down version of parseini.__init__ made for making
an envconfig. | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L30-L59 | null | """Default Tox envlist based on the Travis environment."""
from __future__ import print_function
import os
import re
import sys
from itertools import product
import tox.config
from tox.config import _split_env as split_env
from .utils import TRAVIS_FACTORS, parse_dict
def detect_envlist(ini):
"""Default envlist... |
tox-dev/tox-travis | src/tox_travis/envlist.py | get_declared_envs | python | def get_declared_envs(ini):
tox_section_name = 'tox:tox' if ini.path.endswith('setup.cfg') else 'tox'
tox_section = ini.sections.get(tox_section_name, {})
envlist = split_env(tox_section.get('envlist', []))
# Add additional envs that are declared as sections in the ini
section_envs = [
sect... | Get the full list of envs from the tox ini.
This notably also includes envs that aren't in the envlist,
but are declared by having their own testenv:envname section.
The envs are expected in a particular order. First the ones
declared in the envlist, then the other testenvs in order. | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L62-L81 | null | """Default Tox envlist based on the Travis environment."""
from __future__ import print_function
import os
import re
import sys
from itertools import product
import tox.config
from tox.config import _split_env as split_env
from .utils import TRAVIS_FACTORS, parse_dict
def detect_envlist(ini):
"""Default envlist... |
tox-dev/tox-travis | src/tox_travis/envlist.py | get_version_info | python | def get_version_info():
overrides = os.environ.get('__TOX_TRAVIS_SYS_VERSION')
if overrides:
version, major, minor = overrides.split(',')[:3]
major, minor = int(major), int(minor)
else:
version, (major, minor) = sys.version, sys.version_info[:2]
return version, major, minor | Get version info from the sys module.
Override from environment for testing. | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L84-L95 | null | """Default Tox envlist based on the Travis environment."""
from __future__ import print_function
import os
import re
import sys
from itertools import product
import tox.config
from tox.config import _split_env as split_env
from .utils import TRAVIS_FACTORS, parse_dict
def detect_envlist(ini):
"""Default envlist... |
tox-dev/tox-travis | src/tox_travis/envlist.py | guess_python_env | python | def guess_python_env():
version, major, minor = get_version_info()
if 'PyPy' in version:
return 'pypy3' if major == 3 else 'pypy'
return 'py{major}{minor}'.format(major=major, minor=minor) | Guess the default python env to use. | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L98-L103 | [
"def get_version_info():\n \"\"\"Get version info from the sys module.\n\n Override from environment for testing.\n \"\"\"\n overrides = os.environ.get('__TOX_TRAVIS_SYS_VERSION')\n if overrides:\n version, major, minor = overrides.split(',')[:3]\n major, minor = int(major), int(minor)\... | """Default Tox envlist based on the Travis environment."""
from __future__ import print_function
import os
import re
import sys
from itertools import product
import tox.config
from tox.config import _split_env as split_env
from .utils import TRAVIS_FACTORS, parse_dict
def detect_envlist(ini):
"""Default envlist... |
tox-dev/tox-travis | src/tox_travis/envlist.py | get_default_envlist | python | def get_default_envlist(version):
if version in ['pypy', 'pypy3']:
return version
# Assume single digit major and minor versions
match = re.match(r'^(\d)\.(\d)(?:\.\d+)?$', version or '')
if match:
major, minor = match.groups()
return 'py{major}{minor}'.format(major=major, minor... | Parse a default tox env based on the version.
The version comes from the ``TRAVIS_PYTHON_VERSION`` environment
variable. If that isn't set or is invalid, then use
sys.version_info to come up with a reasonable default. | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L106-L122 | [
"def guess_python_env():\n \"\"\"Guess the default python env to use.\"\"\"\n version, major, minor = get_version_info()\n if 'PyPy' in version:\n return 'pypy3' if major == 3 else 'pypy'\n return 'py{major}{minor}'.format(major=major, minor=minor)\n"
] | """Default Tox envlist based on the Travis environment."""
from __future__ import print_function
import os
import re
import sys
from itertools import product
import tox.config
from tox.config import _split_env as split_env
from .utils import TRAVIS_FACTORS, parse_dict
def detect_envlist(ini):
"""Default envlist... |
tox-dev/tox-travis | src/tox_travis/envlist.py | get_desired_factors | python | def get_desired_factors(ini):
# Find configuration based on known travis factors
travis_section = ini.sections.get('travis', {})
found_factors = [
(factor, parse_dict(travis_section[factor]))
for factor in TRAVIS_FACTORS
if factor in travis_section
]
# Backward compatibility... | Get the list of desired envs per declared factor.
Look at all the accepted configuration locations, and give a list
of envlists, one for each Travis factor found.
Look in the ``[travis]`` section for the known Travis factors,
which are backed by environment variable checking behind the
scenes, but... | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L125-L197 | [
"def get_default_envlist(version):\n \"\"\"Parse a default tox env based on the version.\n\n The version comes from the ``TRAVIS_PYTHON_VERSION`` environment\n variable. If that isn't set or is invalid, then use\n sys.version_info to come up with a reasonable default.\n \"\"\"\n if version in ['py... | """Default Tox envlist based on the Travis environment."""
from __future__ import print_function
import os
import re
import sys
from itertools import product
import tox.config
from tox.config import _split_env as split_env
from .utils import TRAVIS_FACTORS, parse_dict
def detect_envlist(ini):
"""Default envlist... |
tox-dev/tox-travis | src/tox_travis/envlist.py | match_envs | python | def match_envs(declared_envs, desired_envs, passthru):
matched = [
declared for declared in declared_envs
if any(env_matches(declared, desired) for desired in desired_envs)
]
return desired_envs if not matched and passthru else matched | Determine the envs that match the desired_envs.
If ``passthru` is True, and none of the declared envs match the
desired envs, then the desired envs will be used verbatim.
:param declared_envs: The envs that are declared in the tox config.
:param desired_envs: The envs desired from the tox-travis confi... | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L200-L215 | null | """Default Tox envlist based on the Travis environment."""
from __future__ import print_function
import os
import re
import sys
from itertools import product
import tox.config
from tox.config import _split_env as split_env
from .utils import TRAVIS_FACTORS, parse_dict
def detect_envlist(ini):
"""Default envlist... |
tox-dev/tox-travis | src/tox_travis/envlist.py | env_matches | python | def env_matches(declared, desired):
desired_factors = desired.split('-')
declared_factors = declared.split('-')
return all(factor in declared_factors for factor in desired_factors) | Determine if a declared env matches a desired env.
Rather than simply using the name of the env verbatim, take a
closer look to see if all the desired factors are fulfilled. If
the desired factors are fulfilled, but there are other factors,
it should still match the env. | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L218-L228 | null | """Default Tox envlist based on the Travis environment."""
from __future__ import print_function
import os
import re
import sys
from itertools import product
import tox.config
from tox.config import _split_env as split_env
from .utils import TRAVIS_FACTORS, parse_dict
def detect_envlist(ini):
"""Default envlist... |
tox-dev/tox-travis | src/tox_travis/envlist.py | override_ignore_outcome | python | def override_ignore_outcome(ini):
travis_reader = tox.config.SectionReader("travis", ini)
return travis_reader.getbool('unignore_outcomes', False) | Decide whether to override ignore_outcomes. | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L231-L234 | null | """Default Tox envlist based on the Travis environment."""
from __future__ import print_function
import os
import re
import sys
from itertools import product
import tox.config
from tox.config import _split_env as split_env
from .utils import TRAVIS_FACTORS, parse_dict
def detect_envlist(ini):
"""Default envlist... |
tox-dev/tox-travis | src/tox_travis/hooks.py | tox_addoption | python | def tox_addoption(parser):
parser.add_argument(
'--travis-after', dest='travis_after', action='store_true',
help='Exit successfully after all Travis jobs complete successfully.')
if 'TRAVIS' in os.environ:
pypy_version_monkeypatch()
subcommand_test_monkeypatch(tox_subcommand_tes... | Add arguments and needed monkeypatches. | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/hooks.py#L19-L27 | [
"def pypy_version_monkeypatch():\n \"\"\"Patch Tox to work with non-default PyPy 3 versions.\"\"\"\n # Travis virtualenv do not provide `pypy3`, which tox tries to execute.\n # This doesnt affect Travis python version `pypy3`, as the pyenv pypy3\n # is in the PATH.\n # https://github.com/travis-ci/tr... | """Tox hook implementations."""
from __future__ import print_function
import os
import sys
import tox
from .envlist import (
detect_envlist,
autogen_envconfigs,
override_ignore_outcome,
)
from .hacks import (
pypy_version_monkeypatch,
subcommand_test_monkeypatch,
)
from .after import travis_after
... |
tox-dev/tox-travis | src/tox_travis/hooks.py | tox_configure | python | def tox_configure(config):
if 'TRAVIS' not in os.environ:
return
ini = config._cfg
# envlist
if 'TOXENV' not in os.environ and not config.option.env:
envlist = detect_envlist(ini)
undeclared = set(envlist) - set(config.envconfigs)
if undeclared:
print('Match... | Check for the presence of the added options. | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/hooks.py#L31-L59 | [
"def detect_envlist(ini):\n \"\"\"Default envlist automatically based on the Travis environment.\"\"\"\n # Find the envs that tox knows about\n declared_envs = get_declared_envs(ini)\n\n # Find all the envs for all the desired factors given\n desired_factors = get_desired_factors(ini)\n\n # Reduce... | """Tox hook implementations."""
from __future__ import print_function
import os
import sys
import tox
from .envlist import (
detect_envlist,
autogen_envconfigs,
override_ignore_outcome,
)
from .hacks import (
pypy_version_monkeypatch,
subcommand_test_monkeypatch,
)
from .after import travis_after
... |
tox-dev/tox-travis | src/tox_travis/utils.py | parse_dict | python | def parse_dict(value):
lines = [line.strip() for line in value.strip().splitlines()]
pairs = [line.split(':', 1) for line in lines if line]
return dict((k.strip(), v.strip()) for k, v in pairs) | Parse a dict value from the tox config.
.. code-block: ini
[travis]
python =
2.7: py27, docs
3.5: py{35,36}
With this config, the value of ``python`` would be parsed
by this function, and would return::
{
'2.7': 'py27, docs',
'3.5':... | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/utils.py#L11-L32 | null | """Shared constants and utility functions."""
# Mapping Travis factors to the associated env variables
TRAVIS_FACTORS = {
'os': 'TRAVIS_OS_NAME',
'language': 'TRAVIS_LANGUAGE',
'python': 'TRAVIS_PYTHON_VERSION',
}
|
tox-dev/tox-travis | src/tox_travis/hacks.py | pypy_version_monkeypatch | python | def pypy_version_monkeypatch():
# Travis virtualenv do not provide `pypy3`, which tox tries to execute.
# This doesnt affect Travis python version `pypy3`, as the pyenv pypy3
# is in the PATH.
# https://github.com/travis-ci/travis-ci/issues/6304
# Force use of the virtualenv `python`.
version = ... | Patch Tox to work with non-default PyPy 3 versions. | train | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/hacks.py#L9-L18 | null | import os
try:
from tox.config import default_factors
except ImportError:
default_factors = None
def subcommand_test_monkeypatch(post):
"""Monkeypatch Tox session to call a hook when commands finish."""
import tox.session
real_subcommand_test = tox.session.Session.subcommand_test
def subcom... |
LPgenerator/django-db-mailer | dbmail/providers/pubnub/push.py | send | python | def send(channel, message, **kwargs):
pubnub = Pubnub(
publish_key=settings.PUBNUB_PUB_KEY,
subscribe_key=settings.PUBNUB_SUB_KEY,
secret_key=settings.PUBNUB_SEC_KEY,
ssl_on=kwargs.pop('ssl_on', False), **kwargs)
return pubnub.publish(channel=channel, message={"text": message}) | Site: http://www.pubnub.com/
API: https://www.mashape.com/pubnub/pubnub-network
Desc: real-time browser notifications
Installation and usage:
pip install -U pubnub
Tests for browser notification http://127.0.0.1:8000/browser_notification/ | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/pubnub/push.py#L11-L27 | null | # -*- encoding: utf-8 -*-
from django.conf import settings
from Pubnub import Pubnub
class PushOverError(Exception):
pass
|
LPgenerator/django-db-mailer | dbmail/providers/boxcar/push.py | send | python | def send(token, title, **kwargs):
headers = {
"Content-type": "application/x-www-form-urlencoded",
"User-Agent": "DBMail/%s" % get_version(),
}
data = {
"user_credentials": token,
"notification[title]": from_unicode(title),
"notification[sound]": "notifier-2"
}
... | Site: https://boxcar.io/
API: http://help.boxcar.io/knowledgebase/topics/48115-boxcar-api
Desc: Best app for system administrators | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/boxcar/push.py#L19-L48 | [
"def get_version():\n return '.'.join(map(str, VERSION))\n",
"def from_unicode(text, text_length=None):\n try:\n text = text.encode('utf-8', 'ignore')\n except UnicodeDecodeError:\n pass\n\n if text_length is not None:\n text = text[0:text_length]\n\n return text\n"
] | # -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urllib import urlencode
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlencode
from dbmail.providers.prowl.push import from_unicode
from dbmail import get_version
class BoxcarError(Except... |
LPgenerator/django-db-mailer | dbmail/providers/slack/push.py | send | python | def send(channel, message, **kwargs):
headers = {
"Content-type": "application/x-www-form-urlencoded",
"User-Agent": "DBMail/%s" % get_version(),
}
username = from_unicode(kwargs.pop("username", settings.SLACK_USERNAME))
hook_url = from_unicode(kwargs.pop("hook_url", settings.SLACK_HOOC... | Site: https://slack.com
API: https://api.slack.com
Desc: real-time messaging | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/slack/push.py#L23-L65 | [
"def get_version():\n return '.'.join(map(str, VERSION))\n",
"def from_unicode(text, text_length=None):\n try:\n text = text.encode('utf-8', 'ignore')\n except UnicodeDecodeError:\n pass\n\n if text_length is not None:\n text = text[0:text_length]\n\n return text\n"
] | # -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urlparse import urlparse
from urllib import urlencode
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlparse, urlencode
from json import dumps
from django.conf import settings
from dbma... |
LPgenerator/django-db-mailer | dbmail/providers/smsaero/sms.py | send | python | def send(sms_to, sms_body, **kwargs):
headers = {
"User-Agent": "DBMail/%s" % get_version(),
}
kwargs.update({
'user': settings.SMSAERO_LOGIN,
'password': settings.SMSAERO_MD5_PASSWORD,
'from': kwargs.pop('sms_from', settings.SMSAERO_FROM),
'to': sms_to.replace('+', ... | Site: http://smsaero.ru/
API: http://smsaero.ru/api/ | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/smsaero/sms.py#L23-L61 | [
"def get_version():\n return '.'.join(map(str, VERSION))\n",
"def from_unicode(text, text_length=None):\n try:\n text = text.encode('utf-8', 'ignore')\n except UnicodeDecodeError:\n pass\n\n if text_length is not None:\n text = text[0:text_length]\n\n return text\n"
] | # -*- coding: utf-8 -*-
try:
from httplib import HTTPConnection
from urllib import urlencode
except ImportError:
from http.client import HTTPConnection
from urllib.parse import urlencode
from django.conf import settings
from dbmail.providers.prowl.push import from_unicode
from dbmail import get_vers... |
LPgenerator/django-db-mailer | dbmail/providers/sendinblue/mail.py | email_list_to_email_dict | python | def email_list_to_email_dict(email_list):
if email_list is None:
return {}
result = {}
for value in email_list:
realname, address = email.utils.parseaddr(value)
result[address] = realname if realname and address else address
return result | Convert a list of email to a dict of email. | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/sendinblue/mail.py#L15-L23 | null | """SendInBlue mail provider."""
import base64
import email
from mailin import Mailin
class SendInBlueError(Exception):
"""Custom exception."""
pass
def email_address_to_list(email_address):
"""Convert an email address to a list."""
realname, address = email.utils.parseaddr(email_address)
ret... |
LPgenerator/django-db-mailer | dbmail/providers/sendinblue/mail.py | email_address_to_list | python | def email_address_to_list(email_address):
realname, address = email.utils.parseaddr(email_address)
return (
[address, realname] if realname and address else
[email_address, email_address]
) | Convert an email address to a list. | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/sendinblue/mail.py#L26-L32 | null | """SendInBlue mail provider."""
import base64
import email
from mailin import Mailin
class SendInBlueError(Exception):
"""Custom exception."""
pass
def email_list_to_email_dict(email_list):
"""Convert a list of email to a dict of email."""
if email_list is None:
return {}
result = {}
... |
LPgenerator/django-db-mailer | dbmail/providers/sendinblue/mail.py | send | python | def send(sender_instance):
m = Mailin(
"https://api.sendinblue.com/v2.0",
sender_instance._kwargs.get("api_key")
)
data = {
"to": email_list_to_email_dict(sender_instance._recipient_list),
"cc": email_list_to_email_dict(sender_instance._cc),
"bcc": email_list_to_email... | Send a transactional email using SendInBlue API.
Site: https://www.sendinblue.com
API: https://apidocs.sendinblue.com/ | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/sendinblue/mail.py#L35-L65 | [
"def email_list_to_email_dict(email_list):\n \"\"\"Convert a list of email to a dict of email.\"\"\"\n if email_list is None:\n return {}\n result = {}\n for value in email_list:\n realname, address = email.utils.parseaddr(value)\n result[address] = realname if realname and address ... | """SendInBlue mail provider."""
import base64
import email
from mailin import Mailin
class SendInBlueError(Exception):
"""Custom exception."""
pass
def email_list_to_email_dict(email_list):
"""Convert a list of email to a dict of email."""
if email_list is None:
return {}
result = {}
... |
LPgenerator/django-db-mailer | dbmail/providers/iqsms/sms.py | send | python | def send(sms_to, sms_body, **kwargs):
headers = {
"User-Agent": "DBMail/%s" % get_version(),
'Authorization': 'Basic %s' % b64encode(
"%s:%s" % (
settings.IQSMS_API_LOGIN, settings.IQSMS_API_PASSWORD
)).decode("ascii")
}
kwargs.update({
'phone... | Site: http://iqsms.ru/
API: http://iqsms.ru/api/ | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/iqsms/sms.py#L22-L52 | [
"def get_version():\n return '.'.join(map(str, VERSION))\n",
"def from_unicode(text, text_length=None):\n try:\n text = text.encode('utf-8', 'ignore')\n except UnicodeDecodeError:\n pass\n\n if text_length is not None:\n text = text[0:text_length]\n\n return text\n"
] | # -*- encoding: utf-8 -*-
try:
from httplib import HTTPConnection
from urllib import urlencode
except ImportError:
from http.client import HTTPConnection
from urllib.parse import urlencode
from base64 import b64encode
from django.conf import settings
from dbmail.providers.prowl.push import from_unic... |
LPgenerator/django-db-mailer | dbmail/providers/parse_com/push.py | send | python | def send(device_id, description, **kwargs):
headers = {
"X-Parse-Application-Id": settings.PARSE_APP_ID,
"X-Parse-REST-API-Key": settings.PARSE_API_KEY,
"User-Agent": "DBMail/%s" % get_version(),
"Content-type": "application/json",
}
data = {
"where": {
"... | Site: http://parse.com
API: https://www.parse.com/docs/push_guide#scheduled/REST
Desc: Best app for system administrators | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/parse_com/push.py#L19-L59 | [
"def get_version():\n return '.'.join(map(str, VERSION))\n"
] | # -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
except ImportError:
from http.client import HTTPSConnection
from json import dumps, loads
from django.conf import settings
from dbmail import get_version
class ParseComError(Exception):
pass
|
LPgenerator/django-db-mailer | dbmail/providers/prowl/push.py | send | python | def send(api_key, description, **kwargs):
headers = {
"User-Agent": "DBMail/%s" % get_version(),
"Content-type": "application/x-www-form-urlencoded"
}
application = from_unicode(kwargs.pop("app", settings.PROWL_APP), 256)
event = from_unicode(kwargs.pop("event", 'Alert'), 1024)
desc... | Site: http://prowlapp.com
API: http://prowlapp.com/api.php
Desc: Best app for system administrators | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/prowl/push.py#L30-L71 | [
"def get_version():\n return '.'.join(map(str, VERSION))\n",
"def from_unicode(text, text_length=None):\n try:\n text = text.encode('utf-8', 'ignore')\n except UnicodeDecodeError:\n pass\n\n if text_length is not None:\n text = text[0:text_length]\n\n return text\n"
] | # -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urllib import urlencode
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlencode
from django.conf import settings
from dbmail import get_version
class ProwlError(Exception):
pass
def f... |
LPgenerator/django-db-mailer | dbmail/providers/apple/apns.py | send | python | def send(token_hex, message, **kwargs):
is_enhanced = kwargs.pop('is_enhanced', False)
identifier = kwargs.pop('identifier', 0)
expiry = kwargs.pop('expiry', 0)
alert = {
"title": kwargs.pop("event"),
"body": message,
"action": kwargs.pop(
'apns_action', defaults.APN... | Site: https://apple.com
API: https://developer.apple.com
Desc: iOS notifications | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/apple/apns.py#L21-L79 | null | # -*- encoding: utf-8 -*-
from binascii import a2b_hex
from json import dumps
from socket import socket, AF_INET, SOCK_STREAM
from struct import pack
from time import time
try:
from ssl import wrap_socket
except ImportError:
from socket import ssl as wrap_socket
from django.conf import settings
from dbmail ... |
LPgenerator/django-db-mailer | dbmail/providers/pushall/push.py | send | python | def send(ch, message, **kwargs):
params = {
'type': kwargs.pop('req_type', 'self'),
'key': settings.PUSHALL_API_KEYS[ch]['key'],
'id': settings.PUSHALL_API_KEYS[ch]['id'],
'title': kwargs.pop(
"title", settings.PUSHALL_API_KEYS[ch].get('title') or ""),
'text': mes... | Site: https://pushall.ru
API: https://pushall.ru/blog/api
Desc: App for notification to devices/browsers and messaging apps | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/pushall/push.py#L14-L46 | null | # -*- encoding: utf-8 -*-
from json import loads
from urllib import urlencode
from urllib2 import urlopen, Request
from django.conf import settings
class PushAllError(Exception):
pass
|
LPgenerator/django-db-mailer | dbmail/providers/telegram/bot.py | send | python | def send(to, message, **kwargs):
available_kwargs_keys = [
'parse_mode',
'disable_web_page_preview',
'disable_notification',
'reply_to_message_id',
'reply_markup'
]
available_kwargs = {
k: v for k, v in kwargs.iteritems() if k in available_kwargs_keys
}
... | SITE: https://github.com/nickoala/telepot
TELEGRAM API: https://core.telegram.org/bots/api
Installation:
pip install 'telepot>=10.4' | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/telegram/bot.py#L7-L29 | null | # -*- encoding: utf-8 -*-
import telepot
from django.conf import settings
|
LPgenerator/django-db-mailer | dbmail/providers/google/browser.py | send | python | def send(reg_id, message, **kwargs):
subscription_info = kwargs.pop('subscription_info')
payload = {
"title": kwargs.pop("event"),
"body": message,
"url": kwargs.pop("push_url", None)
}
payload.update(kwargs)
wp = WebPusher(subscription_info)
response = wp.send(
... | Site: https://developers.google.com
API: https://developers.google.com/web/updates/2016/03/web-push-encryption
Desc: Web Push notifications for Chrome and FireFox
Installation:
pip install 'pywebpush>=0.4.0' | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/google/browser.py#L13-L40 | null | # -*- encoding: utf-8 -*-
from json import dumps, loads
from django.conf import settings
from pywebpush import WebPusher
class GCMError(Exception):
pass
|
LPgenerator/django-db-mailer | dbmail/providers/apple/apns2.py | send | python | def send(token_hex, message, **kwargs):
priority = kwargs.pop('priority', 10)
topic = kwargs.pop('topic', None)
alert = {
"title": kwargs.pop("event"),
"body": message,
"action": kwargs.pop(
'apns_action', defaults.APNS_PROVIDER_DEFAULT_ACTION)
}
data = {
... | Site: https://apple.com
API: https://developer.apple.com
Desc: iOS notifications
Installation and usage:
pip install hyper | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/apple/apns2.py#L11-L56 | null | from json import dumps
from django.conf import settings
from hyper import HTTP20Connection
from hyper.tls import init_context
from dbmail import defaults
from dbmail.providers.apple.errors import APNsError
|
LPgenerator/django-db-mailer | dbmail/providers/twilio/sms.py | send | python | def send(sms_to, sms_body, **kwargs):
headers = {
"Content-type": "application/x-www-form-urlencoded",
"User-Agent": "DBMail/%s" % get_version(),
'Authorization': 'Basic %s' % b64encode(
"%s:%s" % (
settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN
... | Site: https://www.twilio.com/
API: https://www.twilio.com/docs/api/rest/sending-messages | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/twilio/sms.py#L23-L55 | [
"def get_version():\n return '.'.join(map(str, VERSION))\n",
"def from_unicode(text, text_length=None):\n try:\n text = text.encode('utf-8', 'ignore')\n except UnicodeDecodeError:\n pass\n\n if text_length is not None:\n text = text[0:text_length]\n\n return text\n"
] | # -*- coding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urllib import urlencode
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlencode
from base64 import b64encode
from json import loads
from django.conf import settings
from dbmail.providers.prow... |
LPgenerator/django-db-mailer | dbmail/providers/pushover/push.py | send | python | def send(user, message, **kwargs):
headers = {
"Content-type": "application/x-www-form-urlencoded",
"User-Agent": "DBMail/%s" % get_version(),
}
title = from_unicode(kwargs.pop("title", settings.PUSHOVER_APP))
message = from_unicode(message)
data = {
"token": settings.PUSHO... | Site: https://pushover.net/
API: https://pushover.net/api
Desc: real-time notifications | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/pushover/push.py#L22-L61 | [
"def get_version():\n return '.'.join(map(str, VERSION))\n",
"def from_unicode(text, text_length=None):\n try:\n text = text.encode('utf-8', 'ignore')\n except UnicodeDecodeError:\n pass\n\n if text_length is not None:\n text = text[0:text_length]\n\n return text\n"
] | # -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urllib import urlencode
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlencode
from json import loads
from django.conf import settings
from dbmail import get_version
from dbmail.providers.... |
LPgenerator/django-db-mailer | dbmail/providers/google/android.py | send | python | def send(user, message, **kwargs):
headers = {
"Content-type": "application/json",
"Authorization": "key=" + kwargs.pop("gcm_key", settings.GCM_KEY)
}
hook_url = 'https://android.googleapis.com/gcm/send'
data = {
"registration_ids": [user],
"data": {
"title... | Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/google/android.py#L18-L55 | null | # -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urlparse import urlparse
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlparse
from json import dumps, loads
from django.conf import settings
class GCMError(Exception):
pass
|
gregmuellegger/django-superform | django_superform/forms.py | SuperFormMixin.add_composite_field | python | def add_composite_field(self, name, field):
self.composite_fields[name] = field
self._init_composite_field(name, field) | Add a dynamic composite field to the already existing ones and
initialize it appropriatly. | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/forms.py#L189-L195 | [
"def _init_composite_field(self, name, field):\n if hasattr(field, 'get_form'):\n form = field.get_form(self, name)\n self.forms[name] = form\n if hasattr(field, 'get_formset'):\n formset = field.get_formset(self, name)\n self.formsets[name] = formset\n"
] | class SuperFormMixin(object):
"""
The base class for all super forms. It does not inherit from any other
classes, so you are free to mix it into any custom form class you have. You
need to use it together with ``SuperFormMetaclass``, like this:
.. code:: python
from django_superform import... |
gregmuellegger/django-superform | django_superform/forms.py | SuperFormMixin.get_composite_field_value | python | def get_composite_field_value(self, name):
field = self.composite_fields[name]
if hasattr(field, 'get_form'):
return self.forms[name]
if hasattr(field, 'get_formset'):
return self.formsets[name] | Return the form/formset instance for the given field name. | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/forms.py#L197-L205 | null | class SuperFormMixin(object):
"""
The base class for all super forms. It does not inherit from any other
classes, so you are free to mix it into any custom form class you have. You
need to use it together with ``SuperFormMetaclass``, like this:
.. code:: python
from django_superform import... |
gregmuellegger/django-superform | django_superform/forms.py | SuperFormMixin._init_composite_fields | python | def _init_composite_fields(self):
# The base_composite_fields class attribute is the *class-wide*
# definition of fields. Because a particular *instance* of the class
# might want to alter self.composite_fields, we create
# self.composite_fields here by copying base_composite_fields.
... | Setup the forms and formsets. | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/forms.py#L215-L229 | [
"def _init_composite_field(self, name, field):\n if hasattr(field, 'get_form'):\n form = field.get_form(self, name)\n self.forms[name] = form\n if hasattr(field, 'get_formset'):\n formset = field.get_formset(self, name)\n self.formsets[name] = formset\n"
] | class SuperFormMixin(object):
"""
The base class for all super forms. It does not inherit from any other
classes, so you are free to mix it into any custom form class you have. You
need to use it together with ``SuperFormMetaclass``, like this:
.. code:: python
from django_superform import... |
gregmuellegger/django-superform | django_superform/forms.py | SuperFormMixin.full_clean | python | def full_clean(self):
super(SuperFormMixin, self).full_clean()
for field_name, composite in self.forms.items():
composite.full_clean()
if not composite.is_valid() and composite._errors:
self._errors[field_name] = ErrorDict(composite._errors)
for field_name... | Clean the form, including all formsets and add formset errors to the
errors dict. Errors of nested forms and formsets are only included if
they actually contain errors. | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/forms.py#L231-L245 | null | class SuperFormMixin(object):
"""
The base class for all super forms. It does not inherit from any other
classes, so you are free to mix it into any custom form class you have. You
need to use it together with ``SuperFormMetaclass``, like this:
.. code:: python
from django_superform import... |
gregmuellegger/django-superform | django_superform/forms.py | SuperFormMixin.media | python | def media(self):
media_list = []
media_list.append(super(SuperFormMixin, self).media)
for composite_name in self.composite_fields.keys():
form = self.get_composite_field_value(composite_name)
media_list.append(form.media)
return reduce(lambda a, b: a + b, media_li... | Incooperate composite field's media. | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/forms.py#L248-L257 | [
"def get_composite_field_value(self, name):\n \"\"\"\n Return the form/formset instance for the given field name.\n \"\"\"\n field = self.composite_fields[name]\n if hasattr(field, 'get_form'):\n return self.forms[name]\n if hasattr(field, 'get_formset'):\n return self.formsets[name]... | class SuperFormMixin(object):
"""
The base class for all super forms. It does not inherit from any other
classes, so you are free to mix it into any custom form class you have. You
need to use it together with ``SuperFormMetaclass``, like this:
.. code:: python
from django_superform import... |
gregmuellegger/django-superform | django_superform/forms.py | SuperModelFormMixin.save | python | def save(self, commit=True):
saved_obj = self.save_form(commit=commit)
self.save_forms(commit=commit)
self.save_formsets(commit=commit)
return saved_obj | When saving a super model form, the nested forms and formsets will be
saved as well.
The implementation of ``.save()`` looks like this:
.. code:: python
saved_obj = self.save_form()
self.save_forms()
self.save_formsets()
return saved_obj
... | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/forms.py#L277-L307 | [
"def save_form(self, commit=True):\n \"\"\"\n This calls Django's ``ModelForm.save()``. It only takes care of\n saving this actual form, and leaves the nested forms and formsets\n alone.\n\n We separate this out of the\n :meth:`~django_superform.forms.SuperModelForm.save` method to make\n exten... | class SuperModelFormMixin(SuperFormMixin):
"""
Can be used in with your custom form subclasses like this:
.. code:: python
from django_superform import SuperModelFormMixin
from django_superform import SuperModelFormMetaclass
import six
class MySuperForm(six.with_metaclass(... |
gregmuellegger/django-superform | django_superform/forms.py | SuperModelFormMixin.save_form | python | def save_form(self, commit=True):
return super(SuperModelFormMixin, self).save(commit=commit) | This calls Django's ``ModelForm.save()``. It only takes care of
saving this actual form, and leaves the nested forms and formsets
alone.
We separate this out of the
:meth:`~django_superform.forms.SuperModelForm.save` method to make
extensibility easier. | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/forms.py#L337-L347 | null | class SuperModelFormMixin(SuperFormMixin):
"""
Can be used in with your custom form subclasses like this:
.. code:: python
from django_superform import SuperModelFormMixin
from django_superform import SuperModelFormMetaclass
import six
class MySuperForm(six.with_metaclass(... |
gregmuellegger/django-superform | django_superform/forms.py | SuperModelFormMixin.save_formsets | python | def save_formsets(self, commit=True):
saved_composites = []
for name, composite in self.formsets.items():
field = self.composite_fields[name]
if hasattr(field, 'save'):
field.save(self, name, composite, commit=commit)
saved_composites.append(compos... | Save all formsets. If ``commit=False``, it will modify the form's
``save_m2m()`` so that it also calls the formsets' ``save_m2m()``
methods. | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/forms.py#L359-L372 | [
"def _extend_save_m2m(self, name, composites):\n additional_save_m2m = []\n for composite in composites:\n if hasattr(composite, 'save_m2m'):\n additional_save_m2m.append(composite.save_m2m)\n\n if not additional_save_m2m:\n return\n\n def additional_saves():\n for save_m... | class SuperModelFormMixin(SuperFormMixin):
"""
Can be used in with your custom form subclasses like this:
.. code:: python
from django_superform import SuperModelFormMixin
from django_superform import SuperModelFormMetaclass
import six
class MySuperForm(six.with_metaclass(... |
gregmuellegger/django-superform | django_superform/fields.py | CompositeField.get_prefix | python | def get_prefix(self, form, name):
return '{form_prefix}{prefix_name}-{field_name}'.format(
form_prefix=form.prefix + '-' if form.prefix else '',
prefix_name=self.prefix_name,
field_name=name) | Return the prefix that is used for the formset. | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L67-L74 | null | class CompositeField(BaseCompositeField):
"""
Implements the base structure that is relevant for all composite fields.
This field cannot be used directly, use a subclass of it.
"""
prefix_name = 'composite'
def __init__(self, *args, **kwargs):
super(CompositeField, self).__init__(*args... |
gregmuellegger/django-superform | django_superform/fields.py | CompositeField.get_initial | python | def get_initial(self, form, name):
if hasattr(form, 'initial'):
return form.initial.get(name, None)
return None | Get the initial data that got passed into the superform for this
composite field. It should return ``None`` if no initial values where
given. | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L76-L85 | null | class CompositeField(BaseCompositeField):
"""
Implements the base structure that is relevant for all composite fields.
This field cannot be used directly, use a subclass of it.
"""
prefix_name = 'composite'
def __init__(self, *args, **kwargs):
super(CompositeField, self).__init__(*args... |
gregmuellegger/django-superform | django_superform/fields.py | CompositeField.get_kwargs | python | def get_kwargs(self, form, name):
kwargs = {
'prefix': self.get_prefix(form, name),
'initial': self.get_initial(form, name),
}
kwargs.update(self.default_kwargs)
return kwargs | Return the keyword arguments that are used to instantiate the formset. | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L87-L96 | [
"def get_prefix(self, form, name):\n \"\"\"\n Return the prefix that is used for the formset.\n \"\"\"\n return '{form_prefix}{prefix_name}-{field_name}'.format(\n form_prefix=form.prefix + '-' if form.prefix else '',\n prefix_name=self.prefix_name,\n field_name=name)\n",
"def get... | class CompositeField(BaseCompositeField):
"""
Implements the base structure that is relevant for all composite fields.
This field cannot be used directly, use a subclass of it.
"""
prefix_name = 'composite'
def __init__(self, *args, **kwargs):
super(CompositeField, self).__init__(*args... |
gregmuellegger/django-superform | django_superform/fields.py | FormField.get_form | python | def get_form(self, form, name):
kwargs = self.get_kwargs(form, name)
form_class = self.get_form_class(form, name)
composite_form = form_class(
data=form.data if form.is_bound else None,
files=form.files if form.is_bound else None,
**kwargs)
return comp... | Get an instance of the form. | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L170-L180 | [
"def get_kwargs(self, form, name):\n \"\"\"\n Return the keyword arguments that are used to instantiate the formset.\n \"\"\"\n kwargs = {\n 'prefix': self.get_prefix(form, name),\n 'initial': self.get_initial(form, name),\n }\n kwargs.update(self.default_kwargs)\n return kwargs\n... | class FormField(CompositeField):
"""
A field that can be used to nest a form inside another form::
from django import forms
from django_superform import SuperForm
class AddressForm(forms.Form):
street = forms.CharField()
city = forms.CharField()
class R... |
gregmuellegger/django-superform | django_superform/fields.py | ModelFormField.get_kwargs | python | def get_kwargs(self, form, name):
kwargs = super(ModelFormField, self).get_kwargs(form, name)
instance = self.get_instance(form, name)
kwargs.setdefault('instance', instance)
kwargs.setdefault('empty_permitted', not self.required)
return kwargs | Return the keyword arguments that are used to instantiate the formset.
The ``instance`` kwarg will be set to the value returned by
:meth:`~django_superform.fields.ModelFormField.get_instance`. The
``empty_permitted`` kwarg will be set to the inverse of the
``required`` argument passed i... | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L238-L251 | [
"def get_kwargs(self, form, name):\n \"\"\"\n Return the keyword arguments that are used to instantiate the formset.\n \"\"\"\n kwargs = {\n 'prefix': self.get_prefix(form, name),\n 'initial': self.get_initial(form, name),\n }\n kwargs.update(self.default_kwargs)\n return kwargs\n... | class ModelFormField(FormField):
"""
This class is the to :class:`~django_superform.fields.FormField` what
Django's :class:`ModelForm` is to :class:`Form`. It has the same behaviour
as :class:`~django_superform.fields.FormField` but will also save the
nested form if the super form is saved. Here is ... |
gregmuellegger/django-superform | django_superform/fields.py | ModelFormField.shall_save | python | def shall_save(self, form, name, composite_form):
if composite_form.empty_permitted and not composite_form.has_changed():
return False
return True | Return ``True`` if the given ``composite_form`` (the nested form of
this field) shall be saved. Return ``False`` if the form shall not be
saved together with the super-form.
By default it will return ``False`` if the form was not changed and the
``empty_permitted`` argument for the form... | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L253-L265 | null | class ModelFormField(FormField):
"""
This class is the to :class:`~django_superform.fields.FormField` what
Django's :class:`ModelForm` is to :class:`Form`. It has the same behaviour
as :class:`~django_superform.fields.FormField` but will also save the
nested form if the super form is saved. Here is ... |
gregmuellegger/django-superform | django_superform/fields.py | ModelFormField.save | python | def save(self, form, name, composite_form, commit):
if self.shall_save(form, name, composite_form):
return composite_form.save(commit=commit)
return None | This method is called by
:meth:`django_superform.forms.SuperModelForm.save` in order to save the
modelform that this field takes care of and calls on the nested form's
``save()`` method. But only if
:meth:`~django_superform.fields.ModelFormField.shall_save` returns
``True``. | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L267-L278 | [
"def shall_save(self, form, name, composite_form):\n \"\"\"\n Return ``True`` if the given ``composite_form`` (the nested form of\n this field) shall be saved. Return ``False`` if the form shall not be\n saved together with the super-form.\n\n By default it will return ``False`` if the form was not c... | class ModelFormField(FormField):
"""
This class is the to :class:`~django_superform.fields.FormField` what
Django's :class:`ModelForm` is to :class:`Form`. It has the same behaviour
as :class:`~django_superform.fields.FormField` but will also save the
nested form if the super form is saved. Here is ... |
gregmuellegger/django-superform | django_superform/fields.py | ForeignKeyFormField.allow_blank | python | def allow_blank(self, form, name):
if self.blank is not None:
return self.blank
model = form._meta.model
field = model._meta.get_field(self.get_field_name(form, name))
return field.blank | Allow blank determines if the form might be completely empty. If it's
empty it will result in a None as the saved value for the ForeignKey. | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L301-L310 | [
"def get_field_name(self, form, name):\n return self.field_name or name\n"
] | class ForeignKeyFormField(ModelFormField):
def __init__(self, form_class, kwargs=None, field_name=None, blank=None,
**field_kwargs):
super(ForeignKeyFormField, self).__init__(form_class, kwargs,
**field_kwargs)
self.field_name = fiel... |
gregmuellegger/django-superform | django_superform/fields.py | FormSetField.get_formset | python | def get_formset(self, form, name):
kwargs = self.get_kwargs(form, name)
formset_class = self.get_formset_class(form, name)
formset = formset_class(
form.data if form.is_bound else None,
form.files if form.is_bound else None,
**kwargs)
return formset | Get an instance of the formset. | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L367-L377 | [
"def get_kwargs(self, form, name):\n \"\"\"\n Return the keyword arguments that are used to instantiate the formset.\n \"\"\"\n kwargs = {\n 'prefix': self.get_prefix(form, name),\n 'initial': self.get_initial(form, name),\n }\n kwargs.update(self.default_kwargs)\n return kwargs\n... | class FormSetField(CompositeField):
"""
First argument is a formset class that is instantiated by this
FormSetField.
You can pass the ``kwargs`` argument to specify kwargs values that
are used when the ``formset_class`` is instantiated.
"""
prefix_name = 'formset'
widget = FormSetWidge... |
gregmuellegger/django-superform | django_superform/fields.py | InlineFormSetField.get_formset_class | python | def get_formset_class(self, form, name):
if self.formset_class is not None:
return self.formset_class
formset_class = inlineformset_factory(
self.get_parent_model(form, name),
self.get_model(form, name),
**self.formset_factory_kwargs)
return formse... | Either return the formset class that was provided as argument to the
__init__ method, or build one based on the ``parent_model`` and
``model`` attributes. | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L479-L491 | [
"def get_model(self, form, name):\n return self.model\n",
"def get_parent_model(self, form, name):\n if self.parent_model is not None:\n return self.parent_model\n return form._meta.model\n"
] | class InlineFormSetField(ModelFormSetField):
"""
The ``InlineFormSetField`` helps when you want to use a inline formset.
You can pass in either the keyword argument ``formset_class`` which is a
ready to use formset that inherits from ``BaseInlineFormSet`` or was
created by the ``inlineformset_facto... |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.__parse_json_data | python | def __parse_json_data(self, data):
if isinstance(data, dict) or isinstance(data, list):
self._raw_data = data
self._json_data = copy.deepcopy(self._raw_data)
else:
raise TypeError("Provided Data is not json") | Process Json data
:@param data
:@type data: json/dict
:throws TypeError | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L32-L44 | null | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.__parse_json_file | python | def __parse_json_file(self, file_path):
if file_path == '' or os.path.splitext(file_path)[1] != '.json':
raise IOError('Invalid Json file')
with open(file_path) as json_file:
self._raw_data = json.load(json_file)
self._json_data = copy.deepcopy(self._raw_data) | Process Json file data
:@param file_path
:@type file_path: string
:@throws IOError | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L46-L60 | null | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.__get_value_from_data | python | def __get_value_from_data(self, key, data):
if key.isdigit():
return data[int(key)]
if key not in data:
raise KeyError("Key not exists")
return data.get(key) | Find value from json data
:@pram key
:@type: string
:@pram data
:@type data: dict
:@return object
:@throws KeyError | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L62-L80 | null | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.at | python | def at(self, root):
leafs = root.strip(" ").split('.')
for leaf in leafs:
if leaf:
self._json_data = self.__get_value_from_data(leaf, self._json_data)
return self | Set root where PyJsonq start to prepare
:@param root
:@type root: string
:@return self
:@throws KeyError | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L101-L114 | [
"def __get_value_from_data(self, key, data):\n \"\"\"Find value from json data\n\n :@pram key\n :@type: string\n\n :@pram data\n :@type data: dict\n\n :@return object\n :@throws KeyError\n \"\"\"\n if key.isdigit():\n return data[int(key)]\n\n if key not in data:\n raise ... | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.reset | python | def reset(self, data={}):
if data and (isinstance(data, dict) or isinstance(data, list)):
self._json_data = data
else:
self._json_data = copy.deepcopy(self._raw_data)
self.__reset_queries()
return self | JsonQuery object cen be reset to new data
according to given data or previously given raw Json data
:@param data: {}
:@type data: json/dict
:@return self | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L120-L136 | [
"def __reset_queries(self):\n \"\"\"Reset previous query data\"\"\"\n\n self._queries = []\n self._current_query_index = 0\n"
] | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.__store_query | python | def __store_query(self, query_items):
temp_index = self._current_query_index
if len(self._queries) - 1 < temp_index:
self._queries.append([])
self._queries[temp_index].append(query_items) | Make where clause
:@param query_items
:@type query_items: dict | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L138-L148 | null | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.__execute_queries | python | def __execute_queries(self):
def func(item):
or_check = False
for queries in self._queries:
and_check = True
for query in queries:
and_check &= self._matcher._match(
item.get(query.get('key'), None),
... | Execute all condition and filter result data | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L157-L173 | null | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.where | python | def where(self, key, operator, value):
self.__store_query({"key": key, "operator": operator, "value": value})
return self | Make where clause
:@param key
:@param operator
:@param value
:@type key,operator,value: string
:@return self | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L177-L188 | [
"def __store_query(self, query_items):\n \"\"\"Make where clause\n\n :@param query_items\n :@type query_items: dict\n \"\"\"\n temp_index = self._current_query_index\n if len(self._queries) - 1 < temp_index:\n self._queries.append([])\n\n self._queries[temp_index].append(query_items)\n"
... | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.