repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
deepglo | deepglo-master/run_scripts/run_pems.py | #### OS and commanline arguments
import sys
import multiprocessing as mp
import gzip
import subprocess
from pathlib import Path
import argparse
import logging
import os
sys.path.append('./')
#sys.path.append("/efs/users/rajatse/DeepGLOv2/")
#### DeepGLO model imports
from DeepGLO.metrics import *
from DeepGLO.DeepGL... | 3,544 | 25.259259 | 88 | py |
deepglo | deepglo-master/run_scripts/__init__.py | # Implement your code here.
| 28 | 13.5 | 27 | py |
deepglo | deepglo-master/run_scripts/run_electricity.py | #### OS and commanline arguments
import sys
import multiprocessing as mp
import gzip
import subprocess
from pathlib import Path
import argparse
import logging
import os
sys.path.append('./')
#### DeepGLO model imports
from DeepGLO.metrics import *
from DeepGLO.DeepGLO import *
from DeepGLO.LocalModel import *
import... | 3,478 | 25.157895 | 87 | py |
deepglo | deepglo-master/datasets/reshape_data.py | import numpy as np
traffic = np.load('./traffic.npy')
traffic = traffic.transpose()
np.save('./traffic.npy',traffic)
| 123 | 10.272727 | 34 | py |
jinja | jinja-main/examples/basic/test.py | from jinja2 import Environment
from jinja2.loaders import DictLoader
env = Environment(
loader=DictLoader(
{
"child.html": """\
{% extends default_layout or 'default.html' %}
{% include helpers = 'helpers.html' %}
{% macro get_the_answer() %}42{% endmacro %}
{% title = 'Hello World' %}
{% block... | 675 | 21.533333 | 46 | py |
jinja | jinja-main/examples/basic/debugger.py | from jinja2 import Environment
from jinja2.loaders import FileSystemLoader
env = Environment(loader=FileSystemLoader("templates"))
tmpl = env.get_template("broken.html")
print(tmpl.render(seq=[3, 2, 4, 5, 3, 2, 0, 2, 1]))
| 223 | 31 | 55 | py |
jinja | jinja-main/examples/basic/translate.py | from jinja2 import Environment
env = Environment(extensions=["jinja2.ext.i18n"])
env.globals["gettext"] = {"Hello %(user)s!": "Hallo %(user)s!"}.__getitem__
env.globals["ngettext"] = lambda s, p, n: {
"%(count)s user": "%(count)d Benutzer",
"%(count)s users": "%(count)d Benutzer",
}[s if n == 1 else p]
print(
... | 544 | 27.684211 | 75 | py |
jinja | jinja-main/examples/basic/cycle.py | from jinja2 import Environment
env = Environment(
line_statement_prefix="#", variable_start_string="${", variable_end_string="}"
)
print(
env.from_string(
"""\
<ul>
# for item in range(10)
<li class="${loop.cycle('odd', 'even')}">${item}</li>
# endfor
</ul>\
"""
).render()
)
| 301 | 16.764706 | 82 | py |
jinja | jinja-main/examples/basic/test_loop_filter.py | from jinja2 import Environment
tmpl = Environment().from_string(
"""\
<ul>
{%- for item in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if item % 2 == 0 %}
<li>{{ loop.index }} / {{ loop.length }}: {{ item }}</li>
{%- endfor %}
</ul>
if condition: {{ 1 if foo else 0 }}
"""
)
print(tmpl.render(foo=True))
| 301 | 20.571429 | 67 | py |
jinja | jinja-main/examples/basic/inheritance.py | from jinja2 import Environment
from jinja2.loaders import DictLoader
env = Environment(
loader=DictLoader(
{
"a": "[A[{% block body %}{% endblock %}]]",
"b": "{% extends 'a' %}{% block body %}[B]{% endblock %}",
"c": "{% extends 'b' %}{% block body %}###{{ super() }}###{... | 392 | 27.071429 | 86 | py |
jinja | jinja-main/examples/basic/test_filter_and_linestatements.py | from jinja2 import Environment
env = Environment(
line_statement_prefix="%", variable_start_string="${", variable_end_string="}"
)
tmpl = env.from_string(
"""\
% macro foo()
${caller(42)}
% endmacro
<ul>
% for item in seq
<li>${item}</li>
% endfor
</ul>
% call(var) foo()
[${var}]
% endcall
% filter... | 456 | 15.321429 | 82 | py |
jinja | jinja-main/src/jinja2/visitor.py | """API for traversing the AST nodes. Implemented by the compiler and
meta introspection.
"""
import typing as t
from .nodes import Node
if t.TYPE_CHECKING:
import typing_extensions as te
class VisitCallable(te.Protocol):
def __call__(self, node: Node, *args: t.Any, **kwargs: t.Any) -> t.Any:
... | 3,568 | 37.376344 | 84 | py |
jinja | jinja-main/src/jinja2/parser.py | """Parse tokens from the lexer into nodes for the compiler."""
import typing
import typing as t
from . import nodes
from .exceptions import TemplateAssertionError
from .exceptions import TemplateSyntaxError
from .lexer import describe_token
from .lexer import describe_token_expr
if t.TYPE_CHECKING:
import typing_... | 39,896 | 37.288868 | 88 | py |
jinja | jinja-main/src/jinja2/nodes.py | """AST nodes generated by the parser for the compiler. Also provides
some node tree helper functions used by the parser and compiler in order
to normalize nodes.
"""
import inspect
import operator
import typing as t
from collections import deque
from markupsafe import Markup
from .utils import _PassArg
if t.TYPE_CHE... | 34,565 | 27.685477 | 88 | py |
jinja | jinja-main/src/jinja2/loaders.py | """API and implementations for loading templates from different data
sources.
"""
import importlib.util
import os
import posixpath
import sys
import typing as t
import weakref
import zipimport
from collections import abc
from hashlib import sha1
from importlib import import_module
from types import ModuleType
from .ex... | 23,058 | 33.72741 | 88 | py |
jinja | jinja-main/src/jinja2/async_utils.py | import inspect
import typing as t
from functools import WRAPPER_ASSIGNMENTS
from functools import wraps
from .utils import _PassArg
from .utils import pass_eval_context
V = t.TypeVar("V")
def async_variant(normal_func): # type: ignore
def decorator(async_func): # type: ignore
pass_arg = _PassArg.from_... | 2,477 | 28.152941 | 88 | py |
jinja | jinja-main/src/jinja2/tests.py | """Built-in template tests used with the ``is`` operator."""
import operator
import typing as t
from collections import abc
from numbers import Number
from .runtime import Undefined
from .utils import pass_environment
if t.TYPE_CHECKING:
from .environment import Environment
def test_odd(value: int) -> bool:
... | 5,912 | 22.097656 | 78 | py |
jinja | jinja-main/src/jinja2/ext.py | """Extension API for adding custom tags and behavior."""
import pprint
import re
import typing as t
from markupsafe import Markup
from . import defaults
from . import nodes
from .environment import Environment
from .exceptions import TemplateAssertionError
from .exceptions import TemplateSyntaxError
from .runtime imp... | 31,470 | 35.594186 | 88 | py |
jinja | jinja-main/src/jinja2/environment.py | """Classes for managing templates and their runtime and compile time
options.
"""
import os
import typing
import typing as t
import weakref
from collections import ChainMap
from functools import lru_cache
from functools import partial
from functools import reduce
from types import CodeType
from markupsafe import Marku... | 61,362 | 35.744311 | 88 | py |
jinja | jinja-main/src/jinja2/exceptions.py | import typing as t
if t.TYPE_CHECKING:
from .runtime import Undefined
class TemplateError(Exception):
"""Baseclass for all template errors."""
def __init__(self, message: t.Optional[str] = None) -> None:
super().__init__(message)
@property
def message(self) -> t.Optional[str]:
r... | 5,071 | 29.371257 | 84 | py |
jinja | jinja-main/src/jinja2/constants.py | #: list of lorem ipsum words used by the lipsum() helper function
LOREM_IPSUM_WORDS = """\
a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at
auctor augue bibendum blandit class commodo condimentum congue consectetuer
consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus
d... | 1,433 | 67.285714 | 79 | py |
jinja | jinja-main/src/jinja2/lexer.py | """Implements a Jinja / Python combination lexer. The ``Lexer`` class
is used to do some preprocessing. It filters out invalid operators like
the bitshift operators we don't allow in templates. It separates
template code and python code in expressions.
"""
import re
import typing as t
from ast import literal_eval
from ... | 29,752 | 33.317186 | 88 | py |
jinja | jinja-main/src/jinja2/nativetypes.py | import typing as t
from ast import literal_eval
from ast import parse
from itertools import chain
from itertools import islice
from types import GeneratorType
from . import nodes
from .compiler import CodeGenerator
from .compiler import Frame
from .compiler import has_safe_repr
from .environment import Environment
fro... | 4,210 | 31.145038 | 83 | py |
jinja | jinja-main/src/jinja2/idtracking.py | import typing as t
from . import nodes
from .visitor import NodeVisitor
VAR_LOAD_PARAMETER = "param"
VAR_LOAD_RESOLVE = "resolve"
VAR_LOAD_ALIAS = "alias"
VAR_LOAD_UNDEFINED = "undefined"
def find_symbols(
nodes: t.Iterable[nodes.Node], parent_symbols: t.Optional["Symbols"] = None
) -> "Symbols":
sym = Symb... | 10,704 | 32.557994 | 85 | py |
jinja | jinja-main/src/jinja2/utils.py | import enum
import json
import os
import re
import typing as t
from collections import abc
from collections import deque
from random import choice
from random import randrange
from threading import Lock
from types import CodeType
from urllib.parse import quote_from_bytes
import markupsafe
if t.TYPE_CHECKING:
impo... | 23,961 | 30.612137 | 87 | py |
jinja | jinja-main/src/jinja2/sandbox.py | """A sandbox layer that ensures unsafe operations cannot be performed.
Useful when the template itself comes from an untrusted source.
"""
import operator
import types
import typing as t
from _string import formatter_field_name_split # type: ignore
from collections import abc
from collections import deque
from string ... | 14,615 | 33.06993 | 88 | py |
jinja | jinja-main/src/jinja2/_identifier.py | import re
# generated by scripts/generate_identifier_pattern.py
pattern = re.compile(
r"[\w·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣ৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఄా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎... | 805 | 114.142857 | 715 | py |
jinja | jinja-main/src/jinja2/runtime.py | """The runtime functions and state used by compiled templates."""
import functools
import sys
import typing as t
from collections import abc
from itertools import chain
from markupsafe import escape # noqa: F401
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import auto_aiter
from .a... | 33,443 | 30.700474 | 88 | py |
jinja | jinja-main/src/jinja2/compiler.py | """Compiles nodes from the parser into Python code."""
import typing as t
from contextlib import contextmanager
from functools import update_wrapper
from io import StringIO
from itertools import chain
from keyword import iskeyword as is_python_keyword
from markupsafe import escape
from markupsafe import Markup
from .... | 72,171 | 35.878896 | 88 | py |
jinja | jinja-main/src/jinja2/defaults.py | import typing as t
from .filters import FILTERS as DEFAULT_FILTERS # noqa: F401
from .tests import TESTS as DEFAULT_TESTS # noqa: F401
from .utils import Cycler
from .utils import generate_lorem_ipsum
from .utils import Joiner
from .utils import Namespace
if t.TYPE_CHECKING:
import typing_extensions as te
# de... | 1,267 | 24.877551 | 61 | py |
jinja | jinja-main/src/jinja2/bccache.py | """The optional bytecode cache system. This is useful if you have very
complex template situations and the compilation of all those templates
slows down your application too much.
Situations where this is useful are often forking web applications that
are initialized on the first request.
"""
import errno
import fnmat... | 14,061 | 33.550369 | 87 | py |
jinja | jinja-main/src/jinja2/__init__.py | """Jinja is a template engine written in pure Python. It provides a
non-XML syntax that supports inline expressions and an optional
sandboxed environment.
"""
from .bccache import BytecodeCache as BytecodeCache
from .bccache import FileSystemBytecodeCache as FileSystemBytecodeCache
from .bccache import MemcachedBytecod... | 1,932 | 49.868421 | 72 | py |
jinja | jinja-main/src/jinja2/meta.py | """Functions that expose information about templates that might be
interesting for introspection.
"""
import typing as t
from . import nodes
from .compiler import CodeGenerator
from .compiler import Frame
if t.TYPE_CHECKING:
from .environment import Environment
class TrackingCodeGenerator(CodeGenerator):
""... | 4,396 | 38.258929 | 82 | py |
jinja | jinja-main/src/jinja2/filters.py | """Built-in template filters used with the ``|`` operator."""
import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .asy... | 53,707 | 28.110027 | 87 | py |
jinja | jinja-main/src/jinja2/debug.py | import sys
import typing as t
from types import CodeType
from types import TracebackType
from .exceptions import TemplateSyntaxError
from .utils import internal_code
from .utils import missing
if t.TYPE_CHECKING:
from .runtime import Context
def rewrite_traceback_stack(source: t.Optional[str] = None) -> BaseExc... | 6,299 | 31.8125 | 87 | py |
jinja | jinja-main/src/jinja2/optimizer.py | """The optimizer tries to constant fold expressions and modify the AST
in place so that it should be faster to evaluate.
Because the AST does not contain all the scoping information and the
compiler has to find that out, we cannot do all the optimizations we
want. For example, loop unrolling doesn't work because unrol... | 1,650 | 33.395833 | 73 | py |
jinja | jinja-main/scripts/generate_identifier_pattern.py | import itertools
import os
import re
import sys
def get_characters():
"""Find every Unicode character that is valid in a Python `identifier`_ but
is not matched by the regex ``\\w`` group.
``\\w`` matches some characters that aren't valid in identifiers, but
:meth:`str.isidentifier` will catch that l... | 2,085 | 26.813333 | 88 | py |
jinja | jinja-main/tests/test_inheritance.py | import pytest
from jinja2 import DictLoader
from jinja2 import Environment
from jinja2 import TemplateRuntimeError
from jinja2 import TemplateSyntaxError
LAYOUTTEMPLATE = """\
|{% block block1 %}block 1 from layout{% endblock %}
|{% block block2 %}block 2 from layout{% endblock %}
|{% block block3 %}
{% block block4 ... | 13,611 | 31.642686 | 88 | py |
jinja | jinja-main/tests/test_idtracking.py | from jinja2 import nodes
from jinja2.idtracking import symbols_for_node
def test_basics():
for_loop = nodes.For(
nodes.Name("foo", "store"),
nodes.Name("seq", "load"),
[nodes.Output([nodes.Name("foo", "load")])],
[],
None,
False,
)
tmpl = nodes.Template(
... | 8,653 | 28.738832 | 87 | py |
jinja | jinja-main/tests/test_lexnparse.py | import pytest
from jinja2 import Environment
from jinja2 import nodes
from jinja2 import Template
from jinja2 import TemplateSyntaxError
from jinja2 import UndefinedError
from jinja2.lexer import Token
from jinja2.lexer import TOKEN_BLOCK_BEGIN
from jinja2.lexer import TOKEN_BLOCK_END
from jinja2.lexer import TOKEN_EO... | 35,464 | 33.398642 | 88 | py |
jinja | jinja-main/tests/test_regression.py | import pytest
from jinja2 import DictLoader
from jinja2 import Environment
from jinja2 import PrefixLoader
from jinja2 import Template
from jinja2 import TemplateAssertionError
from jinja2 import TemplateNotFound
from jinja2 import TemplateSyntaxError
from jinja2.utils import pass_context
class TestCorner:
def t... | 22,249 | 28.865772 | 88 | py |
jinja | jinja-main/tests/test_api.py | import shutil
import tempfile
from pathlib import Path
import pytest
from jinja2 import ChainableUndefined
from jinja2 import DebugUndefined
from jinja2 import DictLoader
from jinja2 import Environment
from jinja2 import is_undefined
from jinja2 import make_logging_undefined
from jinja2 import meta
from jinja2 import... | 16,999 | 38.08046 | 88 | py |
jinja | jinja-main/tests/test_pickle.py | import pickle
def test_environment(env):
env = pickle.loads(pickle.dumps(env))
assert env.from_string("x={{ x }}").render(x=42) == "x=42"
| 148 | 20.285714 | 62 | py |
jinja | jinja-main/tests/test_security.py | import pytest
from markupsafe import escape
from jinja2 import Environment
from jinja2.exceptions import SecurityError
from jinja2.exceptions import TemplateRuntimeError
from jinja2.exceptions import TemplateSyntaxError
from jinja2.nodes import EvalContext
from jinja2.sandbox import ImmutableSandboxedEnvironment
from ... | 6,176 | 34.5 | 88 | py |
jinja | jinja-main/tests/test_runtime.py | import itertools
from jinja2 import Template
from jinja2.runtime import LoopContext
TEST_IDX_TEMPLATE_STR_1 = (
"[{% for i in lst|reverse %}(len={{ loop.length }},"
" revindex={{ loop.revindex }}, index={{ loop.index }}, val={{ i }}){% endfor %}]"
)
TEST_IDX0_TEMPLATE_STR_1 = (
"[{% for i in lst|reverse %... | 2,192 | 27.855263 | 86 | py |
jinja | jinja-main/tests/conftest.py | from pathlib import Path
import pytest
from jinja2 import loaders
from jinja2.environment import Environment
@pytest.fixture
def env():
"""returns a new environment."""
return Environment()
@pytest.fixture
def dict_loader():
"""returns DictLoader"""
return loaders.DictLoader({"justdict.html": "FOO... | 1,184 | 22.7 | 75 | py |
jinja | jinja-main/tests/test_filters.py | import random
from collections import namedtuple
import pytest
from markupsafe import Markup
from jinja2 import Environment
from jinja2 import StrictUndefined
from jinja2 import TemplateRuntimeError
from jinja2 import UndefinedError
from jinja2.exceptions import TemplateAssertionError
class Magic:
def __init__(... | 32,359 | 35.940639 | 88 | py |
jinja | jinja-main/tests/test_nativetypes.py | import math
import pytest
from jinja2.exceptions import UndefinedError
from jinja2.nativetypes import NativeEnvironment
from jinja2.nativetypes import NativeTemplate
from jinja2.runtime import Undefined
@pytest.fixture
def env():
return NativeEnvironment()
def test_is_defined_native_return(env):
t = env.f... | 4,275 | 25.233129 | 87 | py |
jinja | jinja-main/tests/test_async.py | import asyncio
import pytest
from jinja2 import ChainableUndefined
from jinja2 import DictLoader
from jinja2 import Environment
from jinja2 import Template
from jinja2.async_utils import auto_aiter
from jinja2.exceptions import TemplateNotFound
from jinja2.exceptions import TemplatesNotFound
from jinja2.exceptions im... | 22,225 | 32.624811 | 88 | py |
jinja | jinja-main/tests/test_imports.py | import pytest
from jinja2.environment import Environment
from jinja2.exceptions import TemplateNotFound
from jinja2.exceptions import TemplatesNotFound
from jinja2.exceptions import TemplateSyntaxError
from jinja2.exceptions import UndefinedError
from jinja2.loaders import DictLoader
@pytest.fixture
def test_env():
... | 7,571 | 35.757282 | 88 | py |
jinja | jinja-main/tests/test_loader.py | import importlib.abc
import importlib.machinery
import importlib.util
import os
import platform
import shutil
import sys
import tempfile
import time
import weakref
from pathlib import Path
import pytest
from jinja2 import Environment
from jinja2 import loaders
from jinja2 import PackageLoader
from jinja2.exceptions i... | 14,874 | 34.843373 | 87 | py |
jinja | jinja-main/tests/test_bytecode_cache.py | import pytest
from jinja2 import Environment
from jinja2.bccache import Bucket
from jinja2.bccache import FileSystemBytecodeCache
from jinja2.bccache import MemcachedBytecodeCache
from jinja2.exceptions import TemplateNotFound
@pytest.fixture
def env(package_loader, tmp_path):
bytecode_cache = FileSystemBytecode... | 1,984 | 24.448718 | 76 | py |
jinja | jinja-main/tests/test_compile.py | import os
import re
from jinja2.environment import Environment
from jinja2.loaders import DictLoader
def test_filters_deterministic(tmp_path):
src = "".join(f"{{{{ {i}|filter{i} }}}}" for i in range(10))
env = Environment(loader=DictLoader({"foo": src}))
env.filters.update(dict.fromkeys((f"filter{i}" for... | 1,084 | 36.413793 | 86 | py |
jinja | jinja-main/tests/test_async_filters.py | from collections import namedtuple
import pytest
from markupsafe import Markup
from jinja2 import Environment
from jinja2.async_utils import auto_aiter
async def make_aiter(iter):
for item in iter:
yield item
def mark_dualiter(parameter, factory):
def decorator(f):
return pytest.mark.param... | 8,001 | 28.20438 | 86 | py |
jinja | jinja-main/tests/test_ext.py | import re
from io import BytesIO
import pytest
from jinja2 import DictLoader
from jinja2 import Environment
from jinja2 import nodes
from jinja2 import pass_context
from jinja2.exceptions import TemplateAssertionError
from jinja2.ext import Extension
from jinja2.lexer import count_newlines
from jinja2.lexer import To... | 25,754 | 34.42641 | 87 | py |
jinja | jinja-main/tests/test_debug.py | import pickle
import re
from traceback import format_exception
import pytest
from jinja2 import ChoiceLoader
from jinja2 import DictLoader
from jinja2 import Environment
from jinja2 import TemplateSyntaxError
@pytest.fixture
def fs_env(filesystem_loader):
"""returns a new environment."""
return Environment(... | 3,704 | 30.398305 | 88 | py |
jinja | jinja-main/tests/test_tests.py | import pytest
from markupsafe import Markup
from jinja2 import Environment
from jinja2 import TemplateAssertionError
from jinja2 import TemplateRuntimeError
class MyDict(dict):
pass
class TestTestsCase:
def test_defined(self, env):
tmpl = env.from_string("{{ missing is defined }}|{{ true is defined... | 7,851 | 32.555556 | 83 | py |
jinja | jinja-main/tests/test_core_tags.py | import pytest
from jinja2 import DictLoader
from jinja2 import Environment
from jinja2 import TemplateRuntimeError
from jinja2 import TemplateSyntaxError
from jinja2 import UndefinedError
@pytest.fixture
def env_trim():
return Environment(trim_blocks=True)
class TestForLoop:
def test_simple(self, env):
... | 20,316 | 33.088926 | 88 | py |
jinja | jinja-main/tests/test_nodes.py | def test_template_hash(env):
template = env.parse("hash test")
hash(template)
| 86 | 20.75 | 37 | py |
jinja | jinja-main/tests/test_utils.py | import pickle
import random
from collections import deque
from copy import copy as shallow_copy
import pytest
from markupsafe import Markup
from jinja2.utils import consume
from jinja2.utils import generate_lorem_ipsum
from jinja2.utils import LRUCache
from jinja2.utils import missing
from jinja2.utils import object_... | 5,631 | 29.27957 | 87 | py |
jinja | jinja-main/tests/res/__init__.py | 0 | 0 | 0 | py | |
jinja | jinja-main/docs/conf.py | from pallets_sphinx_themes import get_version
from pallets_sphinx_themes import ProjectLink
# Project --------------------------------------------------------------
project = "Jinja"
copyright = "2007 Pallets"
author = "Pallets"
release, version = get_version("Jinja2")
# General -------------------------------------... | 1,856 | 34.711538 | 86 | py |
jinja | jinja-main/docs/examples/cache_extension.py | from jinja2 import nodes
from jinja2.ext import Extension
class FragmentCacheExtension(Extension):
# a set of names that trigger the extension.
tags = {"cache"}
def __init__(self, environment):
super().__init__(environment)
# add the defaults to the environment
environment.extend... | 2,053 | 36.345455 | 75 | py |
jinja | jinja-main/docs/examples/inline_gettext_extension.py | import re
from jinja2.exceptions import TemplateSyntaxError
from jinja2.ext import Extension
from jinja2.lexer import count_newlines
from jinja2.lexer import Token
_outside_re = re.compile(r"\\?(gettext|_)\(")
_inside_re = re.compile(r"\\?[()]")
class InlineGettext(Extension):
"""This extension implements supp... | 2,398 | 31.863014 | 68 | py |
HyperIMBA | HyperIMBA-main/main.py | import argparse
import torch
import dataloader as dl
import torch.nn.functional as F
import numpy as np
from models import GatHyper, SageHyper, GcnHyper
import test as tt
def main(args):
if args.dataset == 'all':
ds_names = ['Cora','Citeseer','Photo','Actor','chameleon','Squirrel']
else:
ds_nam... | 5,254 | 56.119565 | 183 | py |
HyperIMBA | HyperIMBA-main/test.py | import torch
from sklearn.metrics import f1_score
import torch.nn.functional as F
def test(model, data, train_mask, val_mask, test_mask, alpha):
with torch.no_grad():
model.eval()
logits, accs = model(data, alpha), []
for mask in [train_mask,val_mask,test_mask]:
pred = logits[ma... | 617 | 37.625 | 81 | py |
HyperIMBA | HyperIMBA-main/dataloader.py | import torch_geometric.datasets as dt
import torch_geometric.transforms as T
import torch
import numpy as np
from dgl.data.utils import generate_mask_tensor, idx2mask
from sklearn.model_selection import train_test_split
def select_dataset(ds,spcial):
if ds=='Cora' or ds=='Citeseer':
ds_loader='Planetoid'
... | 3,365 | 41.607595 | 156 | py |
HyperIMBA | HyperIMBA-main/calculator.py | #Calculate Hyperbolic Embedding
import argparse
import torch
import numpy as np
from models.Poincare import PoincareModel
import dataloader as dl
from torch_geometric.utils import degree, to_networkx
from GraphRicciCurvature.OllivierRicci import OllivierRicci
parser = argparse.ArgumentParser(description='Calculate Hyp... | 2,190 | 41.134615 | 155 | py |
HyperIMBA | HyperIMBA-main/models/GcnHyper.py | from typing import Optional, Tuple
import numpy as np
import torch
from torch import Tensor
from torch.nn import Parameter
from torch_scatter import scatter_add
from torch_sparse import SparseTensor, fill_diag, matmul, mul
from torch_sparse import sum as sparsesum
import torch.nn.functional as F
from torch_geometric.... | 12,196 | 40.06734 | 131 | py |
HyperIMBA | HyperIMBA-main/models/SageHyper.py | import numpy as np
import torch
from torch.nn import Sequential as seq, Parameter,LeakyReLU,init,Linear
from typing import List, Optional, Tuple, Union
import torch.nn.functional as F
from torch import Tensor
from torch.nn import LSTM
from torch_sparse import SparseTensor, matmul
from torch_geometric.nn.aggr import ... | 9,477 | 38.327801 | 131 | py |
HyperIMBA | HyperIMBA-main/models/GatHyper.py | from typing import Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Parameter
from torch_sparse import SparseTensor, set_diag
import math
import numpy as np
from typing import Any
from torch.nn import Sequential as seq, Parameter,LeakyReLU,init,Linear
f... | 12,092 | 39.043046 | 136 | py |
HyperIMBA | HyperIMBA-main/models/Poincare.py | import time
import networkx as nx
import tqdm
import numpy as np
def norm(x, axis=None):
return np.linalg.norm(x, axis=axis)
def poincare_dist(u, v, eps=1e-5):
d = 1 + 2 * norm(u-v)**2 / ((1 - norm(u)**2) * (1 - norm(v)**2) + eps)
return np.arccosh(d)
class PoincareModel():
def __init__(self, re... | 5,663 | 41.268657 | 120 | py |
larq | larq-main/setup.py | from setuptools import find_packages, setup
def readme():
with open("README.md") as f:
return f.read()
setup(
name="larq",
version="0.13.3",
python_requires=">=3.7",
author="Plumerai",
author_email="opensource@plumerai.com",
description="An Open Source Machine Learning Library fo... | 2,122 | 32.171875 | 97 | py |
larq | larq-main/larq/optimizers_test.py | import numpy as np
import pytest
import tensorflow as tf
from packaging import version
from tensorflow import keras
from tensorflow.python.keras import testing_utils
import larq as lq
from larq import testing_utils as lq_testing_utils
if version.parse(tf.__version__) >= version.parse("2.11"):
from tensorflow.kera... | 10,528 | 37.01083 | 88 | py |
larq | larq-main/larq/callbacks.py | from typing import Any, Callable, MutableMapping, Optional
from tensorflow import keras
class HyperparameterScheduler(keras.callbacks.Callback):
"""Generic hyperparameter scheduler.
!!! example
```python
bop = lq.optimizers.Bop(threshold=1e-6, gamma=1e-3)
adam = tf.keras.optimizers.A... | 4,375 | 36.724138 | 89 | py |
larq | larq-main/larq/quantizers.py | """A Quantizer defines the way of transforming a full precision input to a
quantized output and the pseudo-gradient method used for the backwards pass.
Quantizers can either be used through quantizer arguments that are supported
for Larq layers, such as `input_quantizer` and `kernel_quantizer`; or they
can be used sim... | 23,775 | 30.449735 | 141 | py |
larq | larq-main/larq/context.py | """Context managers that configure global behaviour of Larq."""
import contextlib
import threading
__all__ = [
"metrics_scope",
"quantized_scope",
"get_training_metrics",
"should_quantize",
]
_quantized_scope = threading.local()
_quantized_scope.should_quantize = False
@contextlib.contextmanager
d... | 2,953 | 29.453608 | 95 | py |
larq | larq-main/larq/conftest.py | import pytest
import tensorflow as tf
from packaging import version
from tensorflow.python.distribute import strategy_combinations
from tensorflow.python.eager import context
from larq import context as lq_context
if version.parse(tf.__version__) >= version.parse("1.15"):
strategy_combinations.set_virtual_cpus_to... | 2,508 | 27.511364 | 85 | py |
larq | larq-main/larq/version_test.py | import larq
def test_version():
assert hasattr(larq, "__version__") and "." in larq.__version__
| 102 | 16.166667 | 67 | py |
larq | larq-main/larq/context_test.py | import pytest
from larq import context
def test_scope():
assert context.get_training_metrics() == set()
with context.metrics_scope(["flip_ratio"]):
assert context.get_training_metrics() == {"flip_ratio"}
assert context.get_training_metrics() == set()
with pytest.raises(ValueError, match=r".*u... | 426 | 29.5 | 69 | py |
larq | larq-main/larq/math.py | """Math operations that are specific to extremely quantized networks."""
import tensorflow as tf
def sign(x):
r"""A sign function that will never be zero
\\[
f(x) = \begin{cases}
-1 & x < 0 \\\
\hphantom{-}1 & x \geq 0
\end{cases}
\\]
This function is similar to
[`tf.math.sig... | 909 | 19.222222 | 86 | py |
larq | larq-main/larq/testing_utils.py | import numpy as np
import tensorflow as tf
import larq as lq
def _eval_tensor(tensor):
if tensor is None:
return None
elif callable(tensor):
return _eval_helper(tensor())
else:
return tensor.numpy()
def _eval_helper(tensors):
if tensors is None:
return None
retur... | 7,954 | 34.044053 | 117 | py |
larq | larq-main/larq/quantized_variable.py | """Contains QuantizedVariable, a variable that can be quantized in the forward pass."""
from typing import Optional
import tensorflow as tf
from packaging import version
from tensorflow.python.distribute.values import DistributedVariable
from tensorflow.python.framework import ops
from tensorflow.python.ops import res... | 17,061 | 36.915556 | 148 | py |
larq | larq-main/larq/optimizers.py | """Neural networks with extremely low-precision weights and activations, such as
Binarized Neural Networks (BNNs), usually contain a mix of low-precision weights (e.g.
1-bit) and higher-precision weights (e.g. 8-bit, 16-bit, or 32-bit). Examples of this
include the first and last layers of image classificiation models... | 14,848 | 39.350543 | 201 | py |
larq | larq-main/larq/math_test.py | import numpy as np
import pytest
import tensorflow as tf
import larq as lq
from larq.testing_utils import generate_real_values_with_zeros
@pytest.mark.parametrize("fn", [lq.math.sign])
def test_sign(fn):
x = tf.keras.backend.placeholder(ndim=2)
f = tf.keras.backend.function([x], [fn(x)])
binarized_values... | 1,299 | 31.5 | 80 | py |
larq | larq-main/larq/layers_base.py | import logging
from typing import Optional
import tensorflow as tf
from larq import context, quantizers, utils
from larq.quantized_variable import QuantizedVariable
from larq.quantizers import NoOp, QuantizerType
log = logging.getLogger(__name__)
def _is_binary(quantizer):
return getattr(quantizer, "precision"... | 9,491 | 35.933852 | 94 | py |
larq | larq-main/larq/utils.py | from contextlib import contextmanager
import tensorflow as tf
def memory_as_readable_str(num_bits: int) -> str:
"""Generate a human-readable string for the memory size.
1 KiB = 1024 B; we use the binary prefix (KiB) [1,2] instead of the decimal prefix
(KB) to avoid any confusion with multiplying by 1000... | 1,874 | 25.408451 | 105 | py |
larq | larq-main/larq/models_test.py | import numpy as np
import pytest
import tensorflow as tf
from packaging import version
import larq as lq
from larq.models import ModelProfile
class ToyModel(tf.keras.Model):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.conv = lq.layers.QuantConv2D(
filters=32,
... | 11,312 | 33.281818 | 88 | py |
larq | larq-main/larq/metrics_test.py | import numpy as np
import pytest
import tensorflow as tf
from larq import metrics
def test_config():
mcv = metrics.FlipRatio(values_dtype="int16", name="mcv", dtype=tf.float16)
assert mcv.name == "mcv"
assert mcv.stateful
assert mcv.dtype == tf.float16
assert mcv.values_dtype == tf.int16
mcv... | 3,102 | 28.836538 | 79 | py |
larq | larq-main/larq/layers.py | """Each Quantized Layer requires a `input_quantizer` and `kernel_quantizer` that
describes the way of quantizing the activation of the previous layer and the weights
respectively.
If both `input_quantizer` and `kernel_quantizer` are `None` the layer
is equivalent to a full precision layer.
"""
import tensorflow as tf... | 65,598 | 46.535507 | 91 | py |
larq | larq-main/larq/callbacks_test.py | import math
import numpy as np
import pytest
import tensorflow as tf
from packaging import version
from tensorflow.python.keras import testing_utils
import larq as lq
from larq import testing_utils as lq_testing_utils
from larq.callbacks import HyperparameterScheduler
if version.parse(tf.__version__) >= version.pars... | 6,015 | 27.647619 | 87 | py |
larq | larq-main/larq/constraints_test.py | import numpy as np
import pytest
import tensorflow as tf
import larq as lq
from larq.testing_utils import generate_real_values_with_zeros
@pytest.mark.parametrize("name", ["weight_clip"])
def test_serialization(name):
fn = tf.keras.constraints.get(name)
ref_fn = getattr(lq.constraints, name)()
assert fn.... | 811 | 31.48 | 73 | py |
larq | larq-main/larq/layers_test.py | import inspect
import numpy as np
import pytest
import tensorflow as tf
from packaging import version
import larq as lq
from larq import testing_utils
PARAMS_ALL_LAYERS = [
(lq.layers.QuantDense, tf.keras.layers.Dense, (3, 2), dict(units=3)),
(
lq.layers.QuantConv1D,
tf.keras.layers.Conv1D,
... | 12,025 | 34.68546 | 91 | py |
larq | larq-main/larq/constraints.py | """Functions from the `constraints` module allow setting constraints
(eg. weight clipping) on network parameters during optimization.
The penalties are applied on a per-layer basis. The exact API will depend on the layer,
but the layers `QuantDense`, `QuantConv1D`, `QuantConv2D` and `QuantConv3D` have a
unified API.
... | 1,392 | 25.283019 | 87 | py |
larq | larq-main/larq/models.py | import itertools
from dataclasses import dataclass
from typing import Any, Callable, Iterator, Mapping, Optional, Sequence, TypeVar, Union
import numpy as np
import tensorflow as tf
from terminaltables import AsciiTable
from larq import layers as lq_layers
from larq.utils import memory_as_readable_str
__all__ = ["su... | 16,824 | 31.861328 | 105 | py |
larq | larq-main/larq/metrics.py | """We add metrics specific to extremely quantized networks using a
`larq.context.metrics_scope` rather than through the `metrics` parameter of
`model.compile()`, where most common metrics reside. This is because, to calculate
metrics like the `flip_ratio`, we need a layer's kernel or activation and not just the
`y_true... | 3,341 | 34.935484 | 86 | py |
larq | larq-main/larq/activations.py | """Activations can either be used through an `Activation` layer, or through the
`activation` argument supported by all forward layers:
```python
import tensorflow as tf
import larq as lq
model.add(lq.layers.QuantDense(64))
model.add(tf.keras.layers.Activation('hard_tanh'))
```
This is equivalent to:
```python
model... | 1,481 | 21.119403 | 79 | py |
larq | larq-main/larq/__init__.py | from larq import ( # pytype: disable=pyi-error
activations,
callbacks,
constraints,
context,
layers,
math,
metrics,
models,
optimizers,
quantizers,
utils,
)
try:
from importlib import metadata # type: ignore
except ImportError:
# Running on pre-3.8 Python; use impo... | 630 | 16.527778 | 63 | py |
larq | larq-main/larq/quantizers_test.py | import functools
import numpy as np
import pytest
import tensorflow as tf
from packaging import version
import larq as lq
from larq import testing_utils
class DummyTrainableQuantizer(tf.keras.layers.Layer):
"""Used to test whether we can set layers as quantizers without any throws."""
_custom_metrics = Non... | 17,283 | 37.238938 | 96 | py |
larq | larq-main/larq/utils_test.py | from larq import utils
def test_memory_as_readable_str():
correct_strings = [ # 2^i bits, from i = 0 to 74
"0.12 B",
"0.25 B",
"0.50 B",
"1.00 B",
"2.00 B",
"4.00 B",
"8.00 B",
"16.00 B",
"32.00 B",
"64.00 B",
"128.00 B",
... | 1,280 | 19.66129 | 67 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.