code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def get_base(self) -> Optional[str]:
"""Return the "base" revision as a string.
This is the revision number of the script that
has a ``down_revision`` of None.
If the script directory has multiple bases, an error is raised;
:meth:`.ScriptDirectory.get_bases` should be
p... | Return the "base" revision as a string.
This is the revision number of the script that
has a ``down_revision`` of None.
If the script directory has multiple bases, an error is raised;
:meth:`.ScriptDirectory.get_bases` should be
preferred.
| get_base | python | sqlalchemy/alembic | alembic/script/base.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/base.py | MIT |
def generate_revision(
self,
revid: str,
message: Optional[str],
head: Optional[_RevIdType] = None,
splice: Optional[bool] = False,
branch_labels: Optional[_RevIdType] = None,
version_path: Union[str, os.PathLike[str], None] = None,
file_template: Optional... | Generate a new revision file.
This runs the ``script.py.mako`` template, given
template arguments, and creates a new file.
:param revid: String revision id. Typically this
comes from ``alembic.util.rev_id()``.
:param message: the revision message, the one passed
by t... | generate_revision | python | sqlalchemy/alembic | alembic/script/base.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/base.py | MIT |
def longdoc(self) -> str:
"""Return the docstring given in the script."""
doc = self.module.__doc__
if doc:
if hasattr(self.module, "_alembic_source_encoding"):
doc = doc.decode( # type: ignore[attr-defined]
self.module._alembic_source_encoding
... | Return the docstring given in the script. | longdoc | python | sqlalchemy/alembic | alembic/script/base.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/base.py | MIT |
def _revision_map(self) -> _RevisionMapType:
"""memoized attribute, initializes the revision map from the
initial collection.
"""
# Ordering required for some tests to pass (but not required in
# general)
map_: _InterimRevisionMapType = sqlautil.OrderedDict()
he... | memoized attribute, initializes the revision map from the
initial collection.
| _revision_map | python | sqlalchemy/alembic | alembic/script/revision.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/revision.py | MIT |
def _add_depends_on(
self, revisions: Collection[Revision], map_: _RevisionMapType
) -> None:
"""Resolve the 'dependencies' for each revision in a collection
in terms of actual revision ids, as opposed to branch labels or other
symbolic names.
The collection is then assigned... | Resolve the 'dependencies' for each revision in a collection
in terms of actual revision ids, as opposed to branch labels or other
symbolic names.
The collection is then assigned to the _resolved_dependencies
attribute on each revision object.
| _add_depends_on | python | sqlalchemy/alembic | alembic/script/revision.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/revision.py | MIT |
def add_revision(self, revision: Revision, _replace: bool = False) -> None:
"""add a single revision to an existing map.
This method is for single-revision use cases, it's not
appropriate for fully populating an entire revision map.
"""
map_ = self._revision_map
if not ... | add a single revision to an existing map.
This method is for single-revision use cases, it's not
appropriate for fully populating an entire revision map.
| add_revision | python | sqlalchemy/alembic | alembic/script/revision.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/revision.py | MIT |
def get_revisions(
self, id_: Optional[_GetRevArg]
) -> Tuple[Optional[_RevisionOrBase], ...]:
"""Return the :class:`.Revision` instances with the given rev id
or identifiers.
May be given a single identifier, a sequence of identifiers, or the
special symbols "head" or "base... | Return the :class:`.Revision` instances with the given rev id
or identifiers.
May be given a single identifier, a sequence of identifiers, or the
special symbols "head" or "base". The result is a tuple of one
or more identifiers, or an empty tuple in the case of "base".
In the... | get_revisions | python | sqlalchemy/alembic | alembic/script/revision.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/revision.py | MIT |
def get_revision(self, id_: Optional[str]) -> Optional[Revision]:
"""Return the :class:`.Revision` instance with the given rev id.
If a symbolic name such as "head" or "base" is given, resolves
the identifier into the current head or base revision. If the symbolic
name refers to multip... | Return the :class:`.Revision` instance with the given rev id.
If a symbolic name such as "head" or "base" is given, resolves
the identifier into the current head or base revision. If the symbolic
name refers to multiples, :class:`.MultipleHeads` is raised.
Supports partial identifiers... | get_revision | python | sqlalchemy/alembic | alembic/script/revision.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/revision.py | MIT |
def iterate_revisions(
self,
upper: _RevisionIdentifierType,
lower: _RevisionIdentifierType,
implicit_base: bool = False,
inclusive: bool = False,
assert_relative_length: bool = True,
select_for_downgrade: bool = False,
) -> Iterator[Revision]:
"""Iter... | Iterate through script revisions, starting at the given
upper revision identifier and ending at the lower.
The traversal uses strictly the `down_revision`
marker inside each migration script, so
it is a requirement that upper >= lower,
else you'll get nothing back.
The ... | iterate_revisions | python | sqlalchemy/alembic | alembic/script/revision.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/revision.py | MIT |
def _topological_sort(
self,
revisions: Collection[Revision],
heads: Any,
) -> List[str]:
"""Yield revision ids of a collection of Revision objects in
topological sorted order (i.e. revisions always come after their
down_revisions and dependencies). Uses the order of ... | Yield revision ids of a collection of Revision objects in
topological sorted order (i.e. revisions always come after their
down_revisions and dependencies). Uses the order of keys in
_revision_map to sort.
| _topological_sort | python | sqlalchemy/alembic | alembic/script/revision.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/revision.py | MIT |
def _walk(
self,
start: Optional[Union[str, Revision]],
steps: int,
branch_label: Optional[str] = None,
no_overwalk: bool = True,
) -> Optional[_RevisionOrBase]:
"""
Walk the requested number of :steps up (steps > 0) or down (steps < 0)
the revision tr... |
Walk the requested number of :steps up (steps > 0) or down (steps < 0)
the revision tree.
:branch_label is used to select branches only when walking up.
If the walk goes past the boundaries of the tree and :no_overwalk is
True, None is returned, otherwise the walk terminates e... | _walk | python | sqlalchemy/alembic | alembic/script/revision.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/revision.py | MIT |
def _parse_downgrade_target(
self,
current_revisions: _RevisionIdentifierType,
target: _RevisionIdentifierType,
assert_relative_length: bool,
) -> Tuple[Optional[str], Optional[_RevisionOrBase]]:
"""
Parse downgrade command syntax :target to retrieve the target revisi... |
Parse downgrade command syntax :target to retrieve the target revision
and branch label (if any) given the :current_revisions stamp of the
database.
Returns a tuple (branch_label, target_revision) where branch_label
is a string from the command specifying the branch to consider... | _parse_downgrade_target | python | sqlalchemy/alembic | alembic/script/revision.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/revision.py | MIT |
def _parse_upgrade_target(
self,
current_revisions: _RevisionIdentifierType,
target: _RevisionIdentifierType,
assert_relative_length: bool,
) -> Tuple[Optional[_RevisionOrBase], ...]:
"""
Parse upgrade command syntax :target to retrieve the target revision
and... |
Parse upgrade command syntax :target to retrieve the target revision
and given the :current_revisions stamp of the database.
Returns a tuple of Revision objects which should be iterated/upgraded
to. The target may be specified in absolute form, or relative to
:current_revisions... | _parse_upgrade_target | python | sqlalchemy/alembic | alembic/script/revision.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/revision.py | MIT |
def _collect_downgrade_revisions(
self,
upper: _RevisionIdentifierType,
lower: _RevisionIdentifierType,
inclusive: bool,
implicit_base: bool,
assert_relative_length: bool,
) -> Tuple[Set[Revision], Tuple[Optional[_RevisionOrBase], ...]]:
"""
Compute th... |
Compute the set of current revisions specified by :upper, and the
downgrade target specified by :target. Return all dependents of target
which are currently active.
:inclusive=True includes the target revision in the set
| _collect_downgrade_revisions | python | sqlalchemy/alembic | alembic/script/revision.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/revision.py | MIT |
def _collect_upgrade_revisions(
self,
upper: _RevisionIdentifierType,
lower: _RevisionIdentifierType,
inclusive: bool,
implicit_base: bool,
assert_relative_length: bool,
) -> Tuple[Set[Revision], Tuple[Revision, ...]]:
"""
Compute the set of required r... |
Compute the set of required revisions specified by :upper, and the
current set of active revisions specified by :lower. Find the
difference between the two to compute the required upgrades.
:inclusive=True includes the current/lower revisions in the set
:implicit_base=False on... | _collect_upgrade_revisions | python | sqlalchemy/alembic | alembic/script/revision.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/revision.py | MIT |
def _is_real_base(self) -> bool:
"""Return True if this :class:`.Revision` is a "real" base revision,
e.g. that it has no dependencies either."""
# we use self.dependencies here because this is called up
# in initialization where _real_dependencies isn't set up
# yet
ret... | Return True if this :class:`.Revision` is a "real" base revision,
e.g. that it has no dependencies either. | _is_real_base | python | sqlalchemy/alembic | alembic/script/revision.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/revision.py | MIT |
def register(name: str) -> Callable:
"""A function decorator that will register that function as a write hook.
See the documentation linked below for an example.
.. seealso::
:ref:`post_write_hooks_custom`
"""
def decorate(fn):
_registry[name] = fn
return fn
return... | A function decorator that will register that function as a write hook.
See the documentation linked below for an example.
.. seealso::
:ref:`post_write_hooks_custom`
| register | python | sqlalchemy/alembic | alembic/script/write_hooks.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/write_hooks.py | MIT |
def _invoke(
name: str,
revision_path: Union[str, os.PathLike[str]],
options: PostWriteHookConfig,
) -> Any:
"""Invokes the formatter registered for the given name.
:param name: The name of a formatter in the registry
:param revision: string path to the revision file
:param options: A dict ... | Invokes the formatter registered for the given name.
:param name: The name of a formatter in the registry
:param revision: string path to the revision file
:param options: A dict containing kwargs passed to the
specified formatter.
:raises: :class:`alembic.util.CommandError`
| _invoke | python | sqlalchemy/alembic | alembic/script/write_hooks.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/write_hooks.py | MIT |
def _parse_cmdline_options(cmdline_options_str: str, path: str) -> List[str]:
"""Parse options from a string into a list.
Also substitutes the revision script token with the actual filename of
the revision script.
If the revision script token doesn't occur in the options string, it is
automaticall... | Parse options from a string into a list.
Also substitutes the revision script token with the actual filename of
the revision script.
If the revision script token doesn't occur in the options string, it is
automatically prepended.
| _parse_cmdline_options | python | sqlalchemy/alembic | alembic/script/write_hooks.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/script/write_hooks.py | MIT |
async def run_async_migrations() -> None:
"""In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
... | In this scenario we need to create an Engine
and associate a connection with the context.
| run_async_migrations | python | sqlalchemy/alembic | alembic/templates/async/env.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/templates/async/env.py | MIT |
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
... | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
| run_migrations_online | python | sqlalchemy/alembic | alembic/templates/generic/env.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/templates/generic/env.py | MIT |
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# for the direct-to-DB use case, start a transaction on all
# engines, then run all migrations, then commit all transactions.
... | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
| run_migrations_online | python | sqlalchemy/alembic | alembic/templates/multidb/env.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/templates/multidb/env.py | MIT |
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
... | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
| run_migrations_online | python | sqlalchemy/alembic | alembic/templates/pyproject/env.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/templates/pyproject/env.py | MIT |
def _assert_proper_exception_context(exception):
"""assert that any exception we're catching does not have a __context__
without a __cause__, and that __suppress_context__ is never set.
Python 3 will report nested as exceptions as "during the handling of
error X, error Y occurred". That's not what we w... | assert that any exception we're catching does not have a __context__
without a __cause__, and that __suppress_context__ is never set.
Python 3 will report nested as exceptions as "during the handling of
error X, error Y occurred". That's not what we want to do. we want
these exceptions in a cause chai... | _assert_proper_exception_context | python | sqlalchemy/alembic | alembic/testing/assertions.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/testing/assertions.py | MIT |
def _no_sql_pyproject_config(dialect="postgresql", directives=""):
"""use a postgresql url with no host so that
connections guaranteed to fail"""
dir_ = _join_path(_get_staging_directory(), "scripts")
return _write_toml_config(
f"""
[tool.alembic]
script_location ="{dir_}"
{textwrap.dedent(dire... | use a postgresql url with no host so that
connections guaranteed to fail | _no_sql_pyproject_config | python | sqlalchemy/alembic | alembic/testing/env.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/testing/env.py | MIT |
def _no_sql_testing_config(dialect="postgresql", directives=""):
"""use a postgresql url with no host so that
connections guaranteed to fail"""
dir_ = _join_path(_get_staging_directory(), "scripts")
return _write_config_file(
f"""
[alembic]
script_location ={dir_}
sqlalchemy.url = {dialect}://
{... | use a postgresql url with no host so that
connections guaranteed to fail | _no_sql_testing_config | python | sqlalchemy/alembic | alembic/testing/env.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/testing/env.py | MIT |
def multi_heads_fixture(cfg, a, b, c):
"""Create a multiple head fixture from the three-revs fixture"""
# a->b->c
# -> d -> e
# -> f
d = util.rev_id()
e = util.rev_id()
f = util.rev_id()
script = ScriptDirectory.from_config(cfg)
script.generate_revision(
d, "revisio... | Create a multiple head fixture from the three-revs fixture | multi_heads_fixture | python | sqlalchemy/alembic | alembic/testing/env.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/testing/env.py | MIT |
def _multidb_testing_config(engines):
"""alembic.ini fixture to work exactly with the 'multidb' template"""
dir_ = _join_path(_get_staging_directory(), "scripts")
sqlalchemy_future = "future" in config.db.__class__.__module__
databases = ", ".join(engines.keys())
engines = "\n\n".join(
f"... | alembic.ini fixture to work exactly with the 'multidb' template | _multidb_testing_config | python | sqlalchemy/alembic | alembic/testing/env.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/testing/env.py | MIT |
def flag_combinations(*combinations):
"""A facade around @testing.combinations() oriented towards boolean
keyword-based arguments.
Basically generates a nice looking identifier based on the keywords
and also sets up the argument names.
E.g.::
@testing.flag_combinations(
dict(l... | A facade around @testing.combinations() oriented towards boolean
keyword-based arguments.
Basically generates a nice looking identifier based on the keywords
and also sets up the argument names.
E.g.::
@testing.flag_combinations(
dict(lazy=False, passive=False),
dict(l... | flag_combinations | python | sqlalchemy/alembic | alembic/testing/util.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/testing/util.py | MIT |
def resolve_lambda(__fn, **kw):
"""Given a no-arg lambda and a namespace, return a new lambda that
has all the values filled in.
This is used so that we can have module-level fixtures that
refer to instance-level variables using lambdas.
"""
pos_args = inspect_getfullargspec(__fn)[0]
pass... | Given a no-arg lambda and a namespace, return a new lambda that
has all the values filled in.
This is used so that we can have module-level fixtures that
refer to instance-level variables using lambdas.
| resolve_lambda | python | sqlalchemy/alembic | alembic/testing/util.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/testing/util.py | MIT |
def setup_filters():
"""Set global warning behavior for the test suite."""
warnings.resetwarnings()
warnings.filterwarnings("error", category=sa_exc.SADeprecationWarning)
warnings.filterwarnings("error", category=sa_exc.SAWarning)
# some selected deprecations...
warnings.filterwarnings("error... | Set global warning behavior for the test suite. | setup_filters | python | sqlalchemy/alembic | alembic/testing/warnings.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/testing/warnings.py | MIT |
def test_nochange_ondelete_restrict(self):
"""test the RESTRICT option which MySQL doesn't report on"""
diffs = self._fk_opts_fixture(
{"ondelete": "restrict"}, {"ondelete": "restrict"}
)
eq_(diffs, []) | test the RESTRICT option which MySQL doesn't report on | test_nochange_ondelete_restrict | python | sqlalchemy/alembic | alembic/testing/suite/test_autogen_fks.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/testing/suite/test_autogen_fks.py | MIT |
def test_nochange_onupdate_restrict(self):
"""test the RESTRICT option which MySQL doesn't report on"""
diffs = self._fk_opts_fixture(
{"onupdate": "restrict"}, {"onupdate": "restrict"}
)
eq_(diffs, []) | test the RESTRICT option which MySQL doesn't report on | test_nochange_onupdate_restrict | python | sqlalchemy/alembic | alembic/testing/suite/test_autogen_fks.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/testing/suite/test_autogen_fks.py | MIT |
def test_nochange_ondelete_noaction(self):
"""test the NO ACTION option which generally comes back as None"""
diffs = self._fk_opts_fixture(
{"ondelete": "no action"}, {"ondelete": "no action"}
)
eq_(diffs, []) | test the NO ACTION option which generally comes back as None | test_nochange_ondelete_noaction | python | sqlalchemy/alembic | alembic/testing/suite/test_autogen_fks.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/testing/suite/test_autogen_fks.py | MIT |
def test_nochange_onupdate_noaction(self):
"""test the NO ACTION option which generally comes back as None"""
diffs = self._fk_opts_fixture(
{"onupdate": "no action"}, {"onupdate": "no action"}
)
eq_(diffs, []) | test the NO ACTION option which generally comes back as None | test_nochange_onupdate_noaction | python | sqlalchemy/alembic | alembic/testing/suite/test_autogen_fks.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/testing/suite/test_autogen_fks.py | MIT |
def test_change_ondelete_from_restrict(self):
"""test the RESTRICT option which MySQL doesn't report on"""
# note that this is impossible to detect if we change
# from RESTRICT to NO ACTION on MySQL.
diffs = self._fk_opts_fixture(
{"ondelete": "restrict"}, {"ondelete": "casc... | test the RESTRICT option which MySQL doesn't report on | test_change_ondelete_from_restrict | python | sqlalchemy/alembic | alembic/testing/suite/test_autogen_fks.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/testing/suite/test_autogen_fks.py | MIT |
def test_change_onupdate_from_restrict(self):
"""test the RESTRICT option which MySQL doesn't report on"""
# note that this is impossible to detect if we change
# from RESTRICT to NO ACTION on MySQL.
diffs = self._fk_opts_fixture(
{"onupdate": "restrict"}, {"onupdate": "casc... | test the RESTRICT option which MySQL doesn't report on | test_change_onupdate_from_restrict | python | sqlalchemy/alembic | alembic/testing/suite/test_autogen_fks.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/testing/suite/test_autogen_fks.py | MIT |
def path_relative_to(
path: Path, other: Path, *, walk_up: bool = False
) -> Path:
"""
Calculate the relative path of 'path' with respect to 'other',
optionally allowing 'path' to be outside the subtree of 'other'.
OK I used AI for this, sorry
"""
try:
... |
Calculate the relative path of 'path' with respect to 'other',
optionally allowing 'path' to be outside the subtree of 'other'.
OK I used AI for this, sorry
| path_relative_to | python | sqlalchemy/alembic | alembic/util/compat.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/util/compat.py | MIT |
def open_in_editor(
filename: str, environ: Optional[Dict[str, str]] = None
) -> None:
"""
Opens the given file in a text editor. If the environment variable
``EDITOR`` is set, this is taken as preference.
Otherwise, a list of commonly installed editors is tried.
If no editor matches, an :py:e... |
Opens the given file in a text editor. If the environment variable
``EDITOR`` is set, this is taken as preference.
Otherwise, a list of commonly installed editors is tried.
If no editor matches, an :py:exc:`OSError` is raised.
:param filename: The filename to open. Will be passed verbatim to th... | open_in_editor | python | sqlalchemy/alembic | alembic/util/editor.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/util/editor.py | MIT |
def branch(self) -> Dispatcher:
"""Return a copy of this dispatcher that is independently
writable."""
d = Dispatcher()
if self.uselist:
d._registry.update(
(k, [fn for fn in self._registry[k]]) for k in self._registry
)
else:
... | Return a copy of this dispatcher that is independently
writable. | branch | python | sqlalchemy/alembic | alembic/util/langhelpers.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/util/langhelpers.py | MIT |
def coerce_resource_to_filename(fname_or_resource: str) -> pathlib.Path:
"""Interpret a filename as either a filesystem location or as a package
resource.
Names that are non absolute paths and contain a colon
are interpreted as resources and coerced to a file location.
"""
# TODO: there seem t... | Interpret a filename as either a filesystem location or as a package
resource.
Names that are non absolute paths and contain a colon
are interpreted as resources and coerced to a file location.
| coerce_resource_to_filename | python | sqlalchemy/alembic | alembic/util/pyfiles.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/util/pyfiles.py | MIT |
def pyc_file_from_path(
path: Union[str, os.PathLike[str]],
) -> Optional[pathlib.Path]:
"""Given a python source path, locate the .pyc."""
pathpath = pathlib.Path(path)
candidate = pathlib.Path(
importlib.util.cache_from_source(pathpath.as_posix())
)
if candidate.exists():
retu... | Given a python source path, locate the .pyc. | pyc_file_from_path | python | sqlalchemy/alembic | alembic/util/pyfiles.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/util/pyfiles.py | MIT |
def load_python_file(
dir_: Union[str, os.PathLike[str]], filename: Union[str, os.PathLike[str]]
) -> ModuleType:
"""Load a file from the given path as a Python module."""
dir_ = pathlib.Path(dir_)
filename_as_path = pathlib.Path(filename)
filename = filename_as_path.name
module_id = re.sub(r"... | Load a file from the given path as a Python module. | load_python_file | python | sqlalchemy/alembic | alembic/util/pyfiles.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/util/pyfiles.py | MIT |
def _preserving_path_as_str(path: Union[str, os.PathLike[str]]) -> str:
"""receive str/pathlike and return a string.
Does not convert an incoming string path to a Path first, to help with
unit tests that are doing string path round trips without OS-specific
processing if not necessary.
"""
if ... | receive str/pathlike and return a string.
Does not convert an incoming string path to a Path first, to help with
unit tests that are doing string path round trips without OS-specific
processing if not necessary.
| _preserving_path_as_str | python | sqlalchemy/alembic | alembic/util/pyfiles.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/util/pyfiles.py | MIT |
def _find_columns(clause):
"""locate Column objects within the given expression."""
cols: Set[ColumnElement[Any]] = set()
traverse(clause, {}, {"column": cols.add})
return cols | locate Column objects within the given expression. | _find_columns | python | sqlalchemy/alembic | alembic/util/sqla_compat.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/util/sqla_compat.py | MIT |
def _textual_index_column(
table: Table, text_: Union[str, TextClause, ColumnElement[Any]]
) -> Union[ColumnElement[Any], Column[Any]]:
"""a workaround for the Index construct's severe lack of flexibility"""
if isinstance(text_, str):
c = Column(text_, sqltypes.NULLTYPE)
table.append_column(... | a workaround for the Index construct's severe lack of flexibility | _textual_index_column | python | sqlalchemy/alembic | alembic/util/sqla_compat.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/util/sqla_compat.py | MIT |
def non_native_boolean(self):
"""test will fail if native boolean is provided"""
return exclusions.fails_if(
exclusions.LambdaPredicate(
lambda config: config.db.dialect.supports_native_boolean
)
) | test will fail if native boolean is provided | non_native_boolean | python | sqlalchemy/alembic | tests/requirements.py | https://github.com/sqlalchemy/alembic/blob/master/tests/requirements.py | MIT |
def non_native_boolean_check_constraint(self):
"""backend creates a check constraint for booleans if enabled"""
return exclusions.only_on(
exclusions.LambdaPredicate(
lambda config: not config.db.dialect.supports_native_boolean
and config.db.dialect.non_nativ... | backend creates a check constraint for booleans if enabled | non_native_boolean_check_constraint | python | sqlalchemy/alembic | tests/requirements.py | https://github.com/sqlalchemy/alembic/blob/master/tests/requirements.py | MIT |
def reflects_pk_names(self):
"""Target driver reflects the name of primary key constraints."""
return exclusions.fails_on_everything_except(
"postgresql", "oracle", "mssql", "sybase", "sqlite"
) | Target driver reflects the name of primary key constraints. | reflects_pk_names | python | sqlalchemy/alembic | tests/requirements.py | https://github.com/sqlalchemy/alembic/blob/master/tests/requirements.py | MIT |
def test_render_diffs_batch(self):
"""test a full render in batch mode including indentation"""
template_args = {}
self.context.opts["render_as_batch"] = True
autogenerate._render_migration_diffs(self.context, template_args)
eq_(
template_args["upgrades"],
... | test a full render in batch mode including indentation | test_render_diffs_batch | python | sqlalchemy/alembic | tests/test_autogen_composition.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_autogen_composition.py | MIT |
def test_render_diffs_extras(self):
"""test a full render including indentation (include and schema)"""
template_args = {}
self.context.opts.update(
{
"include_object": _default_include_object,
"include_schemas": True,
}
)
... | test a full render including indentation (include and schema) | test_render_diffs_extras | python | sqlalchemy/alembic | tests/test_autogen_composition.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_autogen_composition.py | MIT |
def test_diffs_order(self):
"""
Added in order to test that child tables(tables with FKs) are
generated before their parent tables
"""
ctx = self.autogen_context
uo = ops.UpgradeOps(ops=[])
autogenerate._produce_net_changes(ctx, uo)
diffs = uo.as_diffs()
... |
Added in order to test that child tables(tables with FKs) are
generated before their parent tables
| test_diffs_order | python | sqlalchemy/alembic | tests/test_autogen_diffs.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_autogen_diffs.py | MIT |
def test_nothing_changed_cols_unsorted(self):
"""test #1240
MySQL doubles unique constraints as indexes, so we need to make
sure we aren't comparing index sigs to unique constraint sigs,
which we were doing previously by mistake. As their signatures
were compatible, things "wo... | test #1240
MySQL doubles unique constraints as indexes, so we need to make
sure we aren't comparing index sigs to unique constraint sigs,
which we were doing previously by mistake. As their signatures
were compatible, things "worked" but once index sigs changed
col name sortin... | test_nothing_changed_cols_unsorted | python | sqlalchemy/alembic | tests/test_autogen_indexes.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_autogen_indexes.py | MIT |
def test_repr_custom_type(self, modname, construct):
"""test #1167 as well as other user defined type variations"""
self.autogen_context.opts["user_module_prefix"] = None
class MyType(UserDefinedType):
pass
if modname == "sqlaname":
MyType.__module__ = mod = "s... | test #1167 as well as other user defined type variations | test_repr_custom_type | python | sqlalchemy/alembic | tests/test_autogen_render.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_autogen_render.py | MIT |
def test_render_check_constraint_renamed(self):
"""test that constraints from autogenerate render with
the naming convention name explicitly. These names should
be frozen into the migration scripts so that they remain
the same if the application's naming convention changes.
How... | test that constraints from autogenerate render with
the naming convention name explicitly. These names should
be frozen into the migration scripts so that they remain
the same if the application's naming convention changes.
However, op.create_table() and others need to be careful that
... | test_render_check_constraint_renamed | python | sqlalchemy/alembic | tests/test_autogen_render.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_autogen_render.py | MIT |
def test_config_file_failure_modes(self):
"""with two config files supported at the same time, test failure
modes with multiple --config directives
"""
c1 = config.CommandLine()
with expect_raises_message(
util.CommandError, "only one ini file may be indicated"
... | with two config files supported at the same time, test failure
modes with multiple --config directives
| test_config_file_failure_modes | python | sqlalchemy/alembic | tests/test_command.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_command.py | MIT |
def test_config_file_resolution(
self, args, expected_toml, expected_conf, pop_alembic_config_env
):
"""with two config files supported at the same time, test resolution
of --config / ALEMBIC_CONFIG to always "do what's expected"
"""
c1 = config.CommandLine()
if "ALE... | with two config files supported at the same time, test resolution
of --config / ALEMBIC_CONFIG to always "do what's expected"
| test_config_file_resolution | python | sqlalchemy/alembic | tests/test_command.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_command.py | MIT |
def test_init_file_relative_version_token(
self,
template,
directory,
toml_file_name,
config_file_name,
expected_toml_location,
expected_ini_location,
clear_staging_dir,
):
"""in 1.16.0 with the advent of pyproject.toml, we are also rendering
... | in 1.16.0 with the advent of pyproject.toml, we are also rendering
the script_location value relative to the ``%(here)s`` token, if
the given path is a relative path. ``%(here)s`` is relative to the
owning config file either alembic.ini or pyproject.toml.
| test_init_file_relative_version_token | python | sqlalchemy/alembic | tests/test_command.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_command.py | MIT |
def test_add_column_schema_type(self):
"""Test that a schema type generates its constraints...."""
context = op_fixture()
op.add_column(
"t1", Column("c1", Boolean(create_constraint=True), nullable=False)
)
context.assert_(
"ALTER TABLE t1 ADD COLUMN c1 BO... | Test that a schema type generates its constraints.... | test_add_column_schema_type | python | sqlalchemy/alembic | tests/test_op.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_op.py | MIT |
def test_add_column_schema_schema_type(self):
"""Test that a schema type generates its constraints...."""
context = op_fixture()
op.add_column(
"t1",
Column("c1", Boolean(create_constraint=True), nullable=False),
schema="foo",
)
context.assert_... | Test that a schema type generates its constraints.... | test_add_column_schema_schema_type | python | sqlalchemy/alembic | tests/test_op.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_op.py | MIT |
def test_add_column_schema_type_checks_rule(self):
"""Test that a schema type doesn't generate a
constraint based on check rule."""
context = op_fixture("postgresql")
op.add_column(
"t1", Column("c1", Boolean(create_constraint=True), nullable=False)
)
context.... | Test that a schema type doesn't generate a
constraint based on check rule. | test_add_column_schema_type_checks_rule | python | sqlalchemy/alembic | tests/test_op.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_op.py | MIT |
def test_add_foreign_key_composite_self_referential(self):
"""test #1215
the same column name is present on both sides.
"""
context = op_fixture()
op.create_foreign_key(
"fk_test", "t1", "t1", ["foo", "bar"], ["bat", "bar"]
)
context.assert_(
... | test #1215
the same column name is present on both sides.
| test_add_foreign_key_composite_self_referential | python | sqlalchemy/alembic | tests/test_op.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_op.py | MIT |
def test_primary_key_skip(self):
"""Test that SERIAL cols are just skipped"""
t1 = Table(
"sometable", self.metadata, Column("id", Integer, primary_key=True)
)
t2 = Table(
"sometable", MetaData(), Column("id", Integer, primary_key=True)
)
assert no... | Test that SERIAL cols are just skipped | test_primary_key_skip | python | sqlalchemy/alembic | tests/test_postgresql.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_postgresql.py | MIT |
def test_inline_exclude_constraint_text(self):
"""test for #1184.
Requires SQLAlchemy 2.0.5 due to issue
https://github.com/sqlalchemy/sqlalchemy/issues/9401
"""
autogen_context = self.autogen_context
m = MetaData()
t = Table(
"TTable",
... | test for #1184.
Requires SQLAlchemy 2.0.5 due to issue
https://github.com/sqlalchemy/sqlalchemy/issues/9401
| test_inline_exclude_constraint_text | python | sqlalchemy/alembic | tests/test_postgresql.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_postgresql.py | MIT |
def test_ignore_for_non_recursive(self, non_recursive_fixture):
"""test traversal is non-recursive when the feature is not enabled
(subdirectories are ignored).
"""
self._setup_revision_files(
[
"r0",
"r1",
("dir_1", ["r2", "r... | test traversal is non-recursive when the feature is not enabled
(subdirectories are ignored).
| test_ignore_for_non_recursive | python | sqlalchemy/alembic | tests/test_script_consumption.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_script_consumption.py | MIT |
def test_downgrade_to_existing(self):
"""test for #838; downgrade to a revision that's already in
current heads, but is not itself a head."""
self._assert_downgrade(
self.a.revision, [self.a.revision], [], {self.a.revision}
) | test for #838; downgrade to a revision that's already in
current heads, but is not itself a head. | test_downgrade_to_existing | python | sqlalchemy/alembic | tests/test_version_traversal.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py | MIT |
def test_downgrade_to_existing_head(self):
"""test for #839; downgrade to a revision that's already in current
heads, which *is* itself a head."""
self._assert_downgrade(
self.e.revision, [self.e.revision], [], {self.e.revision}
) | test for #839; downgrade to a revision that's already in current
heads, which *is* itself a head. | test_downgrade_to_existing_head | python | sqlalchemy/alembic | tests/test_version_traversal.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py | MIT |
def test_relative_downgrade_baseplus2(self):
"""base+2 points to b, no branch label, drop everything above b."""
self._assert_downgrade(
"base+2",
[self.d2.revision, self.d1.revision],
[
self.down_(self.d1),
self.down_(self.c1),
... | base+2 points to b, no branch label, drop everything above b. | test_relative_downgrade_baseplus2 | python | sqlalchemy/alembic | tests/test_version_traversal.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py | MIT |
def test_relative_downgrade_branchplus2(self):
"""
Correct behaviour (per
https://github.com/sqlalchemy/alembic/pull/763#issuecomment-738741297)
Only the c2branch should be downgraded, right back to base+2 = b
"""
self._assert_downgrade(
"c2branch@base+2",
... |
Correct behaviour (per
https://github.com/sqlalchemy/alembic/pull/763#issuecomment-738741297)
Only the c2branch should be downgraded, right back to base+2 = b
| test_relative_downgrade_branchplus2 | python | sqlalchemy/alembic | tests/test_version_traversal.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py | MIT |
def test_downgrade_single_branch_c1branch(self):
"""Use branch label to specify the branch to downgrade."""
self._assert_downgrade(
f"c1branch@{self.b.revision}",
(self.c1.revision, self.d2.revision),
[
self.down_(self.c1),
],
{... | Use branch label to specify the branch to downgrade. | test_downgrade_single_branch_c1branch | python | sqlalchemy/alembic | tests/test_version_traversal.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py | MIT |
def test_downgrade_single_branch_c1branch_from_d1_head(self):
"""Use branch label to specify the branch (where the branch label is
not on the head revision)."""
self._assert_downgrade(
f"c2branch@{self.b.revision}",
(self.c1.revision, self.d2.revision),
[
... | Use branch label to specify the branch (where the branch label is
not on the head revision). | test_downgrade_single_branch_c1branch_from_d1_head | python | sqlalchemy/alembic | tests/test_version_traversal.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py | MIT |
def test_downgrade_single_branch_c2(self):
"""Use a revision on the branch (not head) to specify the branch."""
self._assert_downgrade(
f"{self.c2.revision}@{self.b.revision}",
(self.d1.revision, self.d2.revision),
[
self.down_(self.d2),
... | Use a revision on the branch (not head) to specify the branch. | test_downgrade_single_branch_c2 | python | sqlalchemy/alembic | tests/test_version_traversal.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py | MIT |
def test_downgrade_single_branch_d1(self):
"""Use the head revision to specify the branch."""
self._assert_downgrade(
f"{self.d1.revision}@{self.b.revision}",
(self.d1.revision, self.d2.revision),
[
self.down_(self.d1),
self.down_(self.... | Use the head revision to specify the branch. | test_downgrade_single_branch_d1 | python | sqlalchemy/alembic | tests/test_version_traversal.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py | MIT |
def test_downgrade_no_effect_branched(self):
"""Added for good measure when there are multiple branches."""
self._assert_downgrade(
self.c2.revision,
[self.d1.revision, self.c2.revision],
[],
{self.d1.revision, self.c2.revision},
)
self._as... | Added for good measure when there are multiple branches. | test_downgrade_no_effect_branched | python | sqlalchemy/alembic | tests/test_version_traversal.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py | MIT |
def setup_class(cls):
"""
33e21c000cfe -> 178d4e761bbd (head),
2bef33cb3a58, 3904558db1c6, 968330f320d -> 33e21c000cfe (mergepoint)
46c99f866004 -> 18f46b42410d (head),
2bef33cb3a58, 3904558db1c6, 968330f320d -> 46c99f866004 (mergepoint)
f0fa4315825 -> 3904558db1c6 (bran... |
33e21c000cfe -> 178d4e761bbd (head),
2bef33cb3a58, 3904558db1c6, 968330f320d -> 33e21c000cfe (mergepoint)
46c99f866004 -> 18f46b42410d (head),
2bef33cb3a58, 3904558db1c6, 968330f320d -> 46c99f866004 (mergepoint)
f0fa4315825 -> 3904558db1c6 (branchpoint),
--------------... | setup_class | python | sqlalchemy/alembic | tests/test_version_traversal.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py | MIT |
def test_downgrade_independent_branch(self):
"""c2branch depends on c1branch so can be taken down on its own.
Current behaviour also takes down the dependency unnecessarily."""
self._assert_downgrade(
f"c2branch@{self.b.revision}",
(self.d1.revision, self.d2.revision),
... | c2branch depends on c1branch so can be taken down on its own.
Current behaviour also takes down the dependency unnecessarily. | test_downgrade_independent_branch | python | sqlalchemy/alembic | tests/test_version_traversal.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py | MIT |
def test_downgrade_branch_dependency(self):
"""c2branch depends on c1branch so taking down c1branch requires taking
down both"""
destination = f"c1branch@{self.b.revision}"
source = self.d1.revision, self.d2.revision
revs = self.env._downgrade_revs(destination, source)
# ... | c2branch depends on c1branch so taking down c1branch requires taking
down both | test_downgrade_branch_dependency | python | sqlalchemy/alembic | tests/test_version_traversal.py | https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py | MIT |
def build_instruction_kwargs(row: dict) -> dict:
"""Builds the list of `kwargs` for each instruction in `instruction_id_list`."""
kwargs = row["kwargs"]
if kwargs is None:
return {"valid_kwargs_json": False}
try:
kwargs = json.loads(row["kwargs"])
except json.JSONDecodeError:
... | Builds the list of `kwargs` for each instruction in `instruction_id_list`. | build_instruction_kwargs | python | huggingface/smollm | text/data/smoltalk/constraints/filter_ifeval_data.py | https://github.com/huggingface/smollm/blob/master/text/data/smoltalk/constraints/filter_ifeval_data.py | Apache-2.0 |
def filter_not_valid_rows(row: dict) -> bool:
"""Filters out rows which their JSON kwargs are not valid or that the instructions
in their `instruction_id_list` conflict each other."""
valid_kwargs_json = row["valid_kwargs_json"]
if not valid_kwargs_json:
return False
instruction_id_list = r... | Filters out rows which their JSON kwargs are not valid or that the instructions
in their `instruction_id_list` conflict each other. | filter_not_valid_rows | python | huggingface/smollm | text/data/smoltalk/constraints/filter_ifeval_data.py | https://github.com/huggingface/smollm/blob/master/text/data/smoltalk/constraints/filter_ifeval_data.py | Apache-2.0 |
def get_ifeval_results(row: dict) -> dict:
"""Checks if the `response` correct is OK using the IFEval benchmark code from `lm-evaluation-harness`."""
results = [row["response"]]
doc = row.copy()
doc["kwargs"] = json.loads(doc["kwargs"])
try:
return process_results(doc, results)
except Ex... | Checks if the `response` correct is OK using the IFEval benchmark code from `lm-evaluation-harness`. | get_ifeval_results | python | huggingface/smollm | text/data/smoltalk/constraints/filter_ifeval_data.py | https://github.com/huggingface/smollm/blob/master/text/data/smoltalk/constraints/filter_ifeval_data.py | Apache-2.0 |
def update_summary_chat(self, chat_display: tk.Text, sender: str, message: str):
"""Update the summary chat display with new message"""
chat_display.config(state='normal')
# Add the message with appropriate styling
chat_display.insert(tk.END, "\n") # Add spacing
chat_di... | Update the summary chat display with new message | update_summary_chat | python | huggingface/smollm | tools/smol_tools/demo_tkinter.py | https://github.com/huggingface/smollm/blob/master/tools/smol_tools/demo_tkinter.py | Apache-2.0 |
def process_summary_question(self, original_text: str, question: str,
chat_display: tk.Text, chat_input: tk.Text):
"""Process a follow-up question about the summarized text"""
if not question.strip():
return
# Clear input
chat_inpu... | Process a follow-up question about the summarized text | process_summary_question | python | huggingface/smollm | tools/smol_tools/demo_tkinter.py | https://github.com/huggingface/smollm/blob/master/tools/smol_tools/demo_tkinter.py | Apache-2.0 |
def get_weather(city: str) -> str:
"""
Returns the weather forecast for a given city.
Args:
city: The name of the city.
Returns:
A string with a mock weather forecast.
"""
url = 'https://wttr.in/{}?format=+%C,+%t'.format(city)
res = requests.get(url).text
return f"The ... |
Returns the weather forecast for a given city.
Args:
city: The name of the city.
Returns:
A string with a mock weather forecast.
| get_weather | python | huggingface/smollm | tools/smol_tools/smol_tools/agent.py | https://github.com/huggingface/smollm/blob/master/tools/smol_tools/smol_tools/agent.py | Apache-2.0 |
def open_webbrowser(url: str) -> str:
"""
This is a tool that opens a web browser to the given website.
If the user asks to open a website or a browser, you should use this tool.
Args:
url: The url to open.
"""
webbrowser.open(url)
return f"I opened {url.replace('https://', '').repl... |
This is a tool that opens a web browser to the given website.
If the user asks to open a website or a browser, you should use this tool.
Args:
url: The url to open.
| open_webbrowser | python | huggingface/smollm | tools/smol_tools/smol_tools/agent.py | https://github.com/huggingface/smollm/blob/master/tools/smol_tools/smol_tools/agent.py | Apache-2.0 |
def _warm_up(self):
"""Warm up the model with a test prompt"""
print(f"Warming up {self.__class__.__name__}...")
test_text = "This is a test message to warm up the model."
# Consume the generator to complete the warm-up
for _ in self.process(test_text):
pass
p... | Warm up the model with a test prompt | _warm_up | python | huggingface/smollm | tools/smol_tools/smol_tools/base.py | https://github.com/huggingface/smollm/blob/master/tools/smol_tools/smol_tools/base.py | Apache-2.0 |
def _create_chat_completion(
self,
messages: List[Dict[str, str]],
temperature: float = 0.4,
top_p: float = 0.9,
top_k: int = 50,
repeat_penalty: float = 1.2,
max_tokens: int = 256
) -> Generator[str, None, None]:
"""Helper method to create chat comp... | Helper method to create chat completions with standard parameters | _create_chat_completion | python | huggingface/smollm | tools/smol_tools/smol_tools/base.py | https://github.com/huggingface/smollm/blob/master/tools/smol_tools/smol_tools/base.py | Apache-2.0 |
def start_new_chat(self):
"""Start a new chat with a unique ID"""
self.current_chat_id = datetime.now().strftime("%Y%m%d_%H%M%S")
self.chat_history = []
self._original_chat_state = None | Start a new chat with a unique ID | start_new_chat | python | huggingface/smollm | tools/smol_tools/smol_tools/chatter.py | https://github.com/huggingface/smollm/blob/master/tools/smol_tools/smol_tools/chatter.py | Apache-2.0 |
def save_current_chat(self, title: str = None, overwrite: bool = False):
"""Save the current chat to disk if it has any messages"""
if not self.chat_history:
return
if title:
# If overwriting, use existing chat_id if it matches the title
if not ov... | Save the current chat to disk if it has any messages | save_current_chat | python | huggingface/smollm | tools/smol_tools/smol_tools/chatter.py | https://github.com/huggingface/smollm/blob/master/tools/smol_tools/smol_tools/chatter.py | Apache-2.0 |
def is_chat_modified(self) -> bool:
"""Check if the current chat has been modified since loading"""
if self._original_chat_state is None:
# New chat that hasn't been saved yet
return len(self.chat_history) > 0
current_state = [msg.to_dict() for msg in self.ch... | Check if the current chat has been modified since loading | is_chat_modified | python | huggingface/smollm | tools/smol_tools/smol_tools/chatter.py | https://github.com/huggingface/smollm/blob/master/tools/smol_tools/smol_tools/chatter.py | Apache-2.0 |
def get_saved_chats(self) -> List[str]:
"""Get list of saved chat IDs"""
chats = []
for filename in os.listdir(self.chats_dir):
if filename.startswith('chat_') and filename.endswith('.json'):
chat_id = filename[5:-5] # Remove 'chat_' prefix and '.json' suffix
... | Get list of saved chat IDs | get_saved_chats | python | huggingface/smollm | tools/smol_tools/smol_tools/chatter.py | https://github.com/huggingface/smollm/blob/master/tools/smol_tools/smol_tools/chatter.py | Apache-2.0 |
def _check_remaining_indices(self) -> List[int]:
"""When taking screenshots of some websites, it often fails for some reasons.
Therefore, we do a try/except and skip the indices of the json where it failed.
We can go through them again to increase our success rate.
This function checks t... | When taking screenshots of some websites, it often fails for some reasons.
Therefore, we do a try/except and skip the indices of the json where it failed.
We can go through them again to increase our success rate.
This function checks the indices of the json files that are yet to be processed.
... | _check_remaining_indices | python | huggingface/smollm | vision/data/datasets_processing_scripts/build_websight_v02/python_scripts/04_screenshot_html_codes.py | https://github.com/huggingface/smollm/blob/master/vision/data/datasets_processing_scripts/build_websight_v02/python_scripts/04_screenshot_html_codes.py | Apache-2.0 |
def _modify_image_urls(self, html_code: str) -> str:
"""When an image URL appears more than once, when the HTML is rendered,
the same image is displayed. The trick is to add a `_` at the end of the
keyword of the URL to generate another image, still corresponding to the
same keyword.
... | When an image URL appears more than once, when the HTML is rendered,
the same image is displayed. The trick is to add a `_` at the end of the
keyword of the URL to generate another image, still corresponding to the
same keyword.
| _modify_image_urls | python | huggingface/smollm | vision/data/datasets_processing_scripts/build_websight_v02/python_scripts/04_screenshot_html_codes.py | https://github.com/huggingface/smollm/blob/master/vision/data/datasets_processing_scripts/build_websight_v02/python_scripts/04_screenshot_html_codes.py | Apache-2.0 |
def create_dict_qbench(split):
"""`split` is "train", "validation" or "test"."""
dict_qbench = {"image": [], "question": [], "label": [], "tested_labels": []}
#
with open(PATHS_JSON_QBENCH[split], "r") as f:
data_qbench = json.load(f)
#
for example in tqdm(data_qbench):
dict_qben... | `split` is "train", "validation" or "test". | create_dict_qbench | python | huggingface/smollm | vision/data/datasets_processing_scripts/integrate_evaluation_benchmarks_chatbot/qbench.py | https://github.com/huggingface/smollm/blob/master/vision/data/datasets_processing_scripts/integrate_evaluation_benchmarks_chatbot/qbench.py | Apache-2.0 |
def create_ds_scienceqa(split):
"""`split` is "train", "validation" or "test"."""
ds_scienceqa = load_dataset(DS_NAME, split=split)
#
def map_transform_scienceqa(example):
question = example["question"]
#
all_choices = example["choices"]
index_answer = example["answer"]
... | `split` is "train", "validation" or "test". | create_ds_scienceqa | python | huggingface/smollm | vision/data/datasets_processing_scripts/integrate_evaluation_benchmarks_chatbot/scienceqa.py | https://github.com/huggingface/smollm/blob/master/vision/data/datasets_processing_scripts/integrate_evaluation_benchmarks_chatbot/scienceqa.py | Apache-2.0 |
def create_ds_scienceqa(split, max_num_choices, all_tested_labels):
"""`split` is "train", "validation" or "test"."""
ds_scienceqa = load_dataset(DS_NAME, split=split)
#
def map_transform_scienceqa(example):
question = example["question"]
lecture = example["lecture"]
hint = exam... | `split` is "train", "validation" or "test". | create_ds_scienceqa | python | huggingface/smollm | vision/data/datasets_processing_scripts/integrate_evaluation_benchmarks_chatbot/scienceqa_no_mcq.py | https://github.com/huggingface/smollm/blob/master/vision/data/datasets_processing_scripts/integrate_evaluation_benchmarks_chatbot/scienceqa_no_mcq.py | Apache-2.0 |
def require_torch(test_case):
"""
Decorator marking a test that requires PyTorch.
These tests are skipped when PyTorch isn't installed.
"""
if not is_torch_available():
return unittest.skip("test requires PyTorch")(test_case)
else:
return test_case |
Decorator marking a test that requires PyTorch.
These tests are skipped when PyTorch isn't installed.
| require_torch | python | huggingface/smollm | vision/m4/testing_utils.py | https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py | Apache-2.0 |
def require_torch_no_gpus(test_case):
"""
Decorator marking a test that requires a setup without GPUs (in PyTorch). These tests are skipped on a machine with GPUs.
To run *only* the no gpu tests, assuming all test names contain no_gpu: $ pytest -sv ./tests -k "no_gpu"
"""
import torch
if is_to... |
Decorator marking a test that requires a setup without GPUs (in PyTorch). These tests are skipped on a machine with GPUs.
To run *only* the no gpu tests, assuming all test names contain no_gpu: $ pytest -sv ./tests -k "no_gpu"
| require_torch_no_gpus | python | huggingface/smollm | vision/m4/testing_utils.py | https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py | Apache-2.0 |
def require_torch_multi_gpu(test_case):
"""
Decorator marking a test that requires a multi-GPU setup (in PyTorch). These tests are skipped on a machine without
multiple GPUs.
To run *only* the multi_gpu tests, assuming all test names contain multi_gpu: $ pytest -sv ./tests -k "multi_gpu"
"""
if... |
Decorator marking a test that requires a multi-GPU setup (in PyTorch). These tests are skipped on a machine without
multiple GPUs.
To run *only* the multi_gpu tests, assuming all test names contain multi_gpu: $ pytest -sv ./tests -k "multi_gpu"
| require_torch_multi_gpu | python | huggingface/smollm | vision/m4/testing_utils.py | https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py | Apache-2.0 |
def require_torch_non_multi_gpu(test_case):
"""
Decorator marking a test that requires 0 or 1 GPU setup (in PyTorch).
"""
if not is_torch_available():
return unittest.skip("test requires PyTorch")(test_case)
import torch
if torch.cuda.device_count() > 1:
return unittest.skip("t... |
Decorator marking a test that requires 0 or 1 GPU setup (in PyTorch).
| require_torch_non_multi_gpu | python | huggingface/smollm | vision/m4/testing_utils.py | https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py | Apache-2.0 |
def require_torch_up_to_2_gpus(test_case):
"""
Decorator marking a test that requires 0 or 1 or 2 GPU setup (in PyTorch).
"""
if not is_torch_available():
return unittest.skip("test requires PyTorch")(test_case)
import torch
if torch.cuda.device_count() > 2:
return unittest.ski... |
Decorator marking a test that requires 0 or 1 or 2 GPU setup (in PyTorch).
| require_torch_up_to_2_gpus | python | huggingface/smollm | vision/m4/testing_utils.py | https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py | Apache-2.0 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.