id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
231,400 | FPGAwars/apio | apio/commands/sim.py | cli | def cli(ctx, project_dir):
"""Launch the verilog simulation."""
exit_code = SCons(project_dir).sim()
ctx.exit(exit_code) | python | def cli(ctx, project_dir):
exit_code = SCons(project_dir).sim()
ctx.exit(exit_code) | [
"def",
"cli",
"(",
"ctx",
",",
"project_dir",
")",
":",
"exit_code",
"=",
"SCons",
"(",
"project_dir",
")",
".",
"sim",
"(",
")",
"ctx",
".",
"exit",
"(",
"exit_code",
")"
] | Launch the verilog simulation. | [
"Launch",
"the",
"verilog",
"simulation",
"."
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/sim.py#L21-L25 |
231,401 | FPGAwars/apio | apio/commands/uninstall.py | cli | def cli(ctx, packages, all, list, platform):
"""Uninstall packages."""
if packages:
_uninstall(packages, platform)
elif all: # pragma: no cover
packages = Resources(platform).packages
_uninstall(packages, platform)
elif list:
Resources(platform).list_packages(installed=True, notinstalled=False)
else:
click.secho(ctx.get_help()) | python | def cli(ctx, packages, all, list, platform):
if packages:
_uninstall(packages, platform)
elif all: # pragma: no cover
packages = Resources(platform).packages
_uninstall(packages, platform)
elif list:
Resources(platform).list_packages(installed=True, notinstalled=False)
else:
click.secho(ctx.get_help()) | [
"def",
"cli",
"(",
"ctx",
",",
"packages",
",",
"all",
",",
"list",
",",
"platform",
")",
":",
"if",
"packages",
":",
"_uninstall",
"(",
"packages",
",",
"platform",
")",
"elif",
"all",
":",
"# pragma: no cover",
"packages",
"=",
"Resources",
"(",
"platf... | Uninstall packages. | [
"Uninstall",
"packages",
"."
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/uninstall.py#L31-L42 |
231,402 | wq/django-rest-pandas | rest_pandas/serializers.py | PandasSerializer.get_index_fields | def get_index_fields(self):
"""
List of fields to use for index
"""
index_fields = self.get_meta_option('index', [])
if index_fields:
return index_fields
model = getattr(self.model_serializer_meta, 'model', None)
if model:
pk_name = model._meta.pk.name
if pk_name in self.child.get_fields():
return [pk_name]
return [] | python | def get_index_fields(self):
index_fields = self.get_meta_option('index', [])
if index_fields:
return index_fields
model = getattr(self.model_serializer_meta, 'model', None)
if model:
pk_name = model._meta.pk.name
if pk_name in self.child.get_fields():
return [pk_name]
return [] | [
"def",
"get_index_fields",
"(",
"self",
")",
":",
"index_fields",
"=",
"self",
".",
"get_meta_option",
"(",
"'index'",
",",
"[",
"]",
")",
"if",
"index_fields",
":",
"return",
"index_fields",
"model",
"=",
"getattr",
"(",
"self",
".",
"model_serializer_meta",
... | List of fields to use for index | [
"List",
"of",
"fields",
"to",
"use",
"for",
"index"
] | 544177e576a8d54cb46cea6240586c07216f6c49 | https://github.com/wq/django-rest-pandas/blob/544177e576a8d54cb46cea6240586c07216f6c49/rest_pandas/serializers.py#L69-L83 |
231,403 | wq/django-rest-pandas | rest_pandas/serializers.py | PandasUnstackedSerializer.transform_dataframe | def transform_dataframe(self, dataframe):
"""
Unstack the dataframe so header fields are across the top.
"""
dataframe.columns.name = ""
for i in range(len(self.get_header_fields())):
dataframe = dataframe.unstack()
# Remove blank rows / columns
dataframe = dataframe.dropna(
axis=0, how='all'
).dropna(
axis=1, how='all'
)
return dataframe | python | def transform_dataframe(self, dataframe):
dataframe.columns.name = ""
for i in range(len(self.get_header_fields())):
dataframe = dataframe.unstack()
# Remove blank rows / columns
dataframe = dataframe.dropna(
axis=0, how='all'
).dropna(
axis=1, how='all'
)
return dataframe | [
"def",
"transform_dataframe",
"(",
"self",
",",
"dataframe",
")",
":",
"dataframe",
".",
"columns",
".",
"name",
"=",
"\"\"",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"get_header_fields",
"(",
")",
")",
")",
":",
"dataframe",
"=",
"data... | Unstack the dataframe so header fields are across the top. | [
"Unstack",
"the",
"dataframe",
"so",
"header",
"fields",
"are",
"across",
"the",
"top",
"."
] | 544177e576a8d54cb46cea6240586c07216f6c49 | https://github.com/wq/django-rest-pandas/blob/544177e576a8d54cb46cea6240586c07216f6c49/rest_pandas/serializers.py#L116-L131 |
231,404 | wq/django-rest-pandas | rest_pandas/serializers.py | PandasScatterSerializer.transform_dataframe | def transform_dataframe(self, dataframe):
"""
Unstack the dataframe so header consists of a composite 'value' header
plus any other header fields.
"""
coord_fields = self.get_coord_fields()
header_fields = self.get_header_fields()
# Remove any pairs that don't have data for both x & y
for i in range(len(coord_fields)):
dataframe = dataframe.unstack()
dataframe = dataframe.dropna(axis=1, how='all')
dataframe = dataframe.dropna(axis=0, how='any')
# Unstack series header
for i in range(len(header_fields)):
dataframe = dataframe.unstack()
# Compute new column headers
columns = []
for i in range(len(header_fields) + 1):
columns.append([])
for col in dataframe.columns:
value_name = col[0]
coord_names = list(col[1:len(coord_fields) + 1])
header_names = list(col[len(coord_fields) + 1:])
coord_name = ''
for name in coord_names:
if name != self.index_none_value:
coord_name += name + '-'
coord_name += value_name
columns[0].append(coord_name)
for i, header_name in enumerate(header_names):
columns[1 + i].append(header_name)
dataframe.columns = columns
dataframe.columns.names = [''] + header_fields
return dataframe | python | def transform_dataframe(self, dataframe):
coord_fields = self.get_coord_fields()
header_fields = self.get_header_fields()
# Remove any pairs that don't have data for both x & y
for i in range(len(coord_fields)):
dataframe = dataframe.unstack()
dataframe = dataframe.dropna(axis=1, how='all')
dataframe = dataframe.dropna(axis=0, how='any')
# Unstack series header
for i in range(len(header_fields)):
dataframe = dataframe.unstack()
# Compute new column headers
columns = []
for i in range(len(header_fields) + 1):
columns.append([])
for col in dataframe.columns:
value_name = col[0]
coord_names = list(col[1:len(coord_fields) + 1])
header_names = list(col[len(coord_fields) + 1:])
coord_name = ''
for name in coord_names:
if name != self.index_none_value:
coord_name += name + '-'
coord_name += value_name
columns[0].append(coord_name)
for i, header_name in enumerate(header_names):
columns[1 + i].append(header_name)
dataframe.columns = columns
dataframe.columns.names = [''] + header_fields
return dataframe | [
"def",
"transform_dataframe",
"(",
"self",
",",
"dataframe",
")",
":",
"coord_fields",
"=",
"self",
".",
"get_coord_fields",
"(",
")",
"header_fields",
"=",
"self",
".",
"get_header_fields",
"(",
")",
"# Remove any pairs that don't have data for both x & y",
"for",
"i... | Unstack the dataframe so header consists of a composite 'value' header
plus any other header fields. | [
"Unstack",
"the",
"dataframe",
"so",
"header",
"consists",
"of",
"a",
"composite",
"value",
"header",
"plus",
"any",
"other",
"header",
"fields",
"."
] | 544177e576a8d54cb46cea6240586c07216f6c49 | https://github.com/wq/django-rest-pandas/blob/544177e576a8d54cb46cea6240586c07216f6c49/rest_pandas/serializers.py#L159-L198 |
231,405 | wq/django-rest-pandas | rest_pandas/serializers.py | PandasBoxplotSerializer.compute_boxplot | def compute_boxplot(self, series):
"""
Compute boxplot for given pandas Series.
"""
from matplotlib.cbook import boxplot_stats
series = series[series.notnull()]
if len(series.values) == 0:
return {}
elif not is_numeric_dtype(series):
return self.non_numeric_stats(series)
stats = boxplot_stats(list(series.values))[0]
stats['count'] = len(series.values)
stats['fliers'] = "|".join(map(str, stats['fliers']))
return stats | python | def compute_boxplot(self, series):
from matplotlib.cbook import boxplot_stats
series = series[series.notnull()]
if len(series.values) == 0:
return {}
elif not is_numeric_dtype(series):
return self.non_numeric_stats(series)
stats = boxplot_stats(list(series.values))[0]
stats['count'] = len(series.values)
stats['fliers'] = "|".join(map(str, stats['fliers']))
return stats | [
"def",
"compute_boxplot",
"(",
"self",
",",
"series",
")",
":",
"from",
"matplotlib",
".",
"cbook",
"import",
"boxplot_stats",
"series",
"=",
"series",
"[",
"series",
".",
"notnull",
"(",
")",
"]",
"if",
"len",
"(",
"series",
".",
"values",
")",
"==",
... | Compute boxplot for given pandas Series. | [
"Compute",
"boxplot",
"for",
"given",
"pandas",
"Series",
"."
] | 544177e576a8d54cb46cea6240586c07216f6c49 | https://github.com/wq/django-rest-pandas/blob/544177e576a8d54cb46cea6240586c07216f6c49/rest_pandas/serializers.py#L331-L344 |
231,406 | ets-labs/python-dependency-injector | examples/containers/dynamic_runtime_creation.py | import_cls | def import_cls(cls_name):
"""Import class by its fully qualified name.
In terms of current example it is just a small helper function. Please,
don't use it in production approaches.
"""
path_components = cls_name.split('.')
module = __import__('.'.join(path_components[:-1]),
locals(),
globals(),
fromlist=path_components[-1:])
return getattr(module, path_components[-1]) | python | def import_cls(cls_name):
path_components = cls_name.split('.')
module = __import__('.'.join(path_components[:-1]),
locals(),
globals(),
fromlist=path_components[-1:])
return getattr(module, path_components[-1]) | [
"def",
"import_cls",
"(",
"cls_name",
")",
":",
"path_components",
"=",
"cls_name",
".",
"split",
"(",
"'.'",
")",
"module",
"=",
"__import__",
"(",
"'.'",
".",
"join",
"(",
"path_components",
"[",
":",
"-",
"1",
"]",
")",
",",
"locals",
"(",
")",
",... | Import class by its fully qualified name.
In terms of current example it is just a small helper function. Please,
don't use it in production approaches. | [
"Import",
"class",
"by",
"its",
"fully",
"qualified",
"name",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/containers/dynamic_runtime_creation.py#L13-L24 |
231,407 | ets-labs/python-dependency-injector | examples/miniapps/services_v1/example/main.py | main | def main(uid, password, photo, users_service, auth_service, photos_service):
"""Authenticate user and upload photo."""
user = users_service.get_user_by_id(uid)
auth_service.authenticate(user, password)
photos_service.upload_photo(user['uid'], photo) | python | def main(uid, password, photo, users_service, auth_service, photos_service):
user = users_service.get_user_by_id(uid)
auth_service.authenticate(user, password)
photos_service.upload_photo(user['uid'], photo) | [
"def",
"main",
"(",
"uid",
",",
"password",
",",
"photo",
",",
"users_service",
",",
"auth_service",
",",
"photos_service",
")",
":",
"user",
"=",
"users_service",
".",
"get_user_by_id",
"(",
"uid",
")",
"auth_service",
".",
"authenticate",
"(",
"user",
",",... | Authenticate user and upload photo. | [
"Authenticate",
"user",
"and",
"upload",
"photo",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/services_v1/example/main.py#L4-L8 |
231,408 | ets-labs/python-dependency-injector | examples/miniapps/use_cases/example/use_cases.py | SignupUseCase.execute | def execute(self, email):
"""Execute use case handling."""
print('Sign up user {0}'.format(email))
self.email_sender.send(email, 'Welcome, "{}"'.format(email)) | python | def execute(self, email):
print('Sign up user {0}'.format(email))
self.email_sender.send(email, 'Welcome, "{}"'.format(email)) | [
"def",
"execute",
"(",
"self",
",",
"email",
")",
":",
"print",
"(",
"'Sign up user {0}'",
".",
"format",
"(",
"email",
")",
")",
"self",
".",
"email_sender",
".",
"send",
"(",
"email",
",",
"'Welcome, \"{}\"'",
".",
"format",
"(",
"email",
")",
")"
] | Execute use case handling. | [
"Execute",
"use",
"case",
"handling",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/use_cases/example/use_cases.py#L19-L22 |
231,409 | ets-labs/python-dependency-injector | examples/miniapps/services_v1/example/services.py | UsersService.get_user_by_id | def get_user_by_id(self, uid):
"""Return user's data by identifier."""
self.logger.debug('User %s has been found in database', uid)
return dict(uid=uid, password_hash='secret_hash') | python | def get_user_by_id(self, uid):
self.logger.debug('User %s has been found in database', uid)
return dict(uid=uid, password_hash='secret_hash') | [
"def",
"get_user_by_id",
"(",
"self",
",",
"uid",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'User %s has been found in database'",
",",
"uid",
")",
"return",
"dict",
"(",
"uid",
"=",
"uid",
",",
"password_hash",
"=",
"'secret_hash'",
")"
] | Return user's data by identifier. | [
"Return",
"user",
"s",
"data",
"by",
"identifier",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/services_v1/example/services.py#L16-L19 |
231,410 | ets-labs/python-dependency-injector | examples/miniapps/services_v1/example/services.py | AuthService.authenticate | def authenticate(self, user, password):
"""Authenticate user."""
assert user['password_hash'] == '_'.join((password, 'hash'))
self.logger.debug('User %s has been successfully authenticated',
user['uid']) | python | def authenticate(self, user, password):
assert user['password_hash'] == '_'.join((password, 'hash'))
self.logger.debug('User %s has been successfully authenticated',
user['uid']) | [
"def",
"authenticate",
"(",
"self",
",",
"user",
",",
"password",
")",
":",
"assert",
"user",
"[",
"'password_hash'",
"]",
"==",
"'_'",
".",
"join",
"(",
"(",
"password",
",",
"'hash'",
")",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'User %s has ... | Authenticate user. | [
"Authenticate",
"user",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/services_v1/example/services.py#L31-L35 |
231,411 | ets-labs/python-dependency-injector | examples/miniapps/mail_service/example.py | MailService.send | def send(self, email, body):
"""Send email."""
print('Connecting server {0}:{1} with {2}:{3}'.format(
self._host, self._port, self._login, self._password))
print('Sending "{0}" to "{1}"'.format(body, email)) | python | def send(self, email, body):
print('Connecting server {0}:{1} with {2}:{3}'.format(
self._host, self._port, self._login, self._password))
print('Sending "{0}" to "{1}"'.format(body, email)) | [
"def",
"send",
"(",
"self",
",",
"email",
",",
"body",
")",
":",
"print",
"(",
"'Connecting server {0}:{1} with {2}:{3}'",
".",
"format",
"(",
"self",
".",
"_host",
",",
"self",
".",
"_port",
",",
"self",
".",
"_login",
",",
"self",
".",
"_password",
")"... | Send email. | [
"Send",
"email",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/mail_service/example.py#L22-L26 |
231,412 | ets-labs/python-dependency-injector | examples/providers/factory_delegation.py | User.main_photo | def main_photo(self):
"""Return user's main photo."""
if not self._main_photo:
self._main_photo = self.photos_factory()
return self._main_photo | python | def main_photo(self):
if not self._main_photo:
self._main_photo = self.photos_factory()
return self._main_photo | [
"def",
"main_photo",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_main_photo",
":",
"self",
".",
"_main_photo",
"=",
"self",
".",
"photos_factory",
"(",
")",
"return",
"self",
".",
"_main_photo"
] | Return user's main photo. | [
"Return",
"user",
"s",
"main",
"photo",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/providers/factory_delegation.py#L20-L24 |
231,413 | ets-labs/python-dependency-injector | examples/miniapps/movie_lister/example/db.py | init_sqlite | def init_sqlite(movies_data, database):
"""Initialize sqlite3 movies database.
:param movies_data: Data about movies
:type movies_data: tuple[tuple]
:param database: Connection to sqlite database with movies data
:type database: sqlite3.Connection
"""
with database:
database.execute('CREATE TABLE IF NOT EXISTS movies '
'(name text, year int, director text)')
database.execute('DELETE FROM movies')
database.executemany('INSERT INTO movies VALUES (?,?,?)', movies_data) | python | def init_sqlite(movies_data, database):
with database:
database.execute('CREATE TABLE IF NOT EXISTS movies '
'(name text, year int, director text)')
database.execute('DELETE FROM movies')
database.executemany('INSERT INTO movies VALUES (?,?,?)', movies_data) | [
"def",
"init_sqlite",
"(",
"movies_data",
",",
"database",
")",
":",
"with",
"database",
":",
"database",
".",
"execute",
"(",
"'CREATE TABLE IF NOT EXISTS movies '",
"'(name text, year int, director text)'",
")",
"database",
".",
"execute",
"(",
"'DELETE FROM movies'",
... | Initialize sqlite3 movies database.
:param movies_data: Data about movies
:type movies_data: tuple[tuple]
:param database: Connection to sqlite database with movies data
:type database: sqlite3.Connection | [
"Initialize",
"sqlite3",
"movies",
"database",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/movie_lister/example/db.py#L6-L19 |
231,414 | ets-labs/python-dependency-injector | examples/miniapps/movie_lister/example/db.py | init_csv | def init_csv(movies_data, csv_file_path, delimiter):
"""Initialize csv movies database.
:param movies_data: Data about movies
:type movies_data: tuple[tuple]
:param csv_file_path: Path to csv file with movies data
:type csv_file_path: str
:param delimiter: Csv file's delimiter
:type delimiter: str
"""
with open(csv_file_path, 'w') as csv_file:
csv.writer(csv_file, delimiter=delimiter).writerows(movies_data) | python | def init_csv(movies_data, csv_file_path, delimiter):
with open(csv_file_path, 'w') as csv_file:
csv.writer(csv_file, delimiter=delimiter).writerows(movies_data) | [
"def",
"init_csv",
"(",
"movies_data",
",",
"csv_file_path",
",",
"delimiter",
")",
":",
"with",
"open",
"(",
"csv_file_path",
",",
"'w'",
")",
"as",
"csv_file",
":",
"csv",
".",
"writer",
"(",
"csv_file",
",",
"delimiter",
"=",
"delimiter",
")",
".",
"w... | Initialize csv movies database.
:param movies_data: Data about movies
:type movies_data: tuple[tuple]
:param csv_file_path: Path to csv file with movies data
:type csv_file_path: str
:param delimiter: Csv file's delimiter
:type delimiter: str | [
"Initialize",
"csv",
"movies",
"database",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/movie_lister/example/db.py#L22-L35 |
231,415 | ets-labs/python-dependency-injector | examples/providers/factory_aggregate/games.py | Game.play | def play(self):
"""Play game."""
print('{0} and {1} are playing {2}'.format(
self.player1, self.player2, self.__class__.__name__.lower())) | python | def play(self):
print('{0} and {1} are playing {2}'.format(
self.player1, self.player2, self.__class__.__name__.lower())) | [
"def",
"play",
"(",
"self",
")",
":",
"print",
"(",
"'{0} and {1} are playing {2}'",
".",
"format",
"(",
"self",
".",
"player1",
",",
"self",
".",
"player2",
",",
"self",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
")",
")"
] | Play game. | [
"Play",
"game",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/providers/factory_aggregate/games.py#L12-L15 |
231,416 | ets-labs/python-dependency-injector | examples/miniapps/password_hashing/example.py | UsersService.create_user | def create_user(self, name, password):
"""Create user with hashed password."""
hashed_password = self._password_hasher(password)
return dict(name=name, password=hashed_password) | python | def create_user(self, name, password):
hashed_password = self._password_hasher(password)
return dict(name=name, password=hashed_password) | [
"def",
"create_user",
"(",
"self",
",",
"name",
",",
"password",
")",
":",
"hashed_password",
"=",
"self",
".",
"_password_hasher",
"(",
"password",
")",
"return",
"dict",
"(",
"name",
"=",
"name",
",",
"password",
"=",
"hashed_password",
")"
] | Create user with hashed password. | [
"Create",
"user",
"with",
"hashed",
"password",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/password_hashing/example.py#L16-L19 |
231,417 | ets-labs/python-dependency-injector | examples/miniapps/api_client/api.py | ApiClient.call | def call(self, operation, data):
"""Make some network operations."""
print('API call [{0}:{1}], method - {2}, data - {3}'.format(
self.host, self.api_key, operation, repr(data))) | python | def call(self, operation, data):
print('API call [{0}:{1}], method - {2}, data - {3}'.format(
self.host, self.api_key, operation, repr(data))) | [
"def",
"call",
"(",
"self",
",",
"operation",
",",
"data",
")",
":",
"print",
"(",
"'API call [{0}:{1}], method - {2}, data - {3}'",
".",
"format",
"(",
"self",
".",
"host",
",",
"self",
".",
"api_key",
",",
"operation",
",",
"repr",
"(",
"data",
")",
")",... | Make some network operations. | [
"Make",
"some",
"network",
"operations",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/api_client/api.py#L12-L15 |
231,418 | ets-labs/python-dependency-injector | examples/miniapps/movie_lister/movies/listers.py | MovieLister.movies_directed_by | def movies_directed_by(self, director):
"""Return list of movies that were directed by certain person.
:param director: Director's name
:type director: str
:rtype: list[movies.models.Movie]
:return: List of movie instances.
"""
return [movie for movie in self._movie_finder.find_all()
if movie.director == director] | python | def movies_directed_by(self, director):
return [movie for movie in self._movie_finder.find_all()
if movie.director == director] | [
"def",
"movies_directed_by",
"(",
"self",
",",
"director",
")",
":",
"return",
"[",
"movie",
"for",
"movie",
"in",
"self",
".",
"_movie_finder",
".",
"find_all",
"(",
")",
"if",
"movie",
".",
"director",
"==",
"director",
"]"
] | Return list of movies that were directed by certain person.
:param director: Director's name
:type director: str
:rtype: list[movies.models.Movie]
:return: List of movie instances. | [
"Return",
"list",
"of",
"movies",
"that",
"were",
"directed",
"by",
"certain",
"person",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/movie_lister/movies/listers.py#L22-L32 |
231,419 | ets-labs/python-dependency-injector | examples/miniapps/movie_lister/movies/listers.py | MovieLister.movies_released_in | def movies_released_in(self, year):
"""Return list of movies that were released in certain year.
:param year: Release year
:type year: int
:rtype: list[movies.models.Movie]
:return: List of movie instances.
"""
return [movie for movie in self._movie_finder.find_all()
if movie.year == year] | python | def movies_released_in(self, year):
return [movie for movie in self._movie_finder.find_all()
if movie.year == year] | [
"def",
"movies_released_in",
"(",
"self",
",",
"year",
")",
":",
"return",
"[",
"movie",
"for",
"movie",
"in",
"self",
".",
"_movie_finder",
".",
"find_all",
"(",
")",
"if",
"movie",
".",
"year",
"==",
"year",
"]"
] | Return list of movies that were released in certain year.
:param year: Release year
:type year: int
:rtype: list[movies.models.Movie]
:return: List of movie instances. | [
"Return",
"list",
"of",
"movies",
"that",
"were",
"released",
"in",
"certain",
"year",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/movie_lister/movies/listers.py#L34-L44 |
231,420 | ets-labs/python-dependency-injector | examples/providers/dependency.py | UsersService.init_database | def init_database(self):
"""Initialize database, if it has not been initialized yet."""
with contextlib.closing(self.database.cursor()) as cursor:
cursor.execute("""
CREATE TABLE IF NOT EXISTS users(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(32)
)
""") | python | def init_database(self):
with contextlib.closing(self.database.cursor()) as cursor:
cursor.execute("""
CREATE TABLE IF NOT EXISTS users(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(32)
)
""") | [
"def",
"init_database",
"(",
"self",
")",
":",
"with",
"contextlib",
".",
"closing",
"(",
"self",
".",
"database",
".",
"cursor",
"(",
")",
")",
"as",
"cursor",
":",
"cursor",
".",
"execute",
"(",
"\"\"\"\n CREATE TABLE IF NOT EXISTS users(\n ... | Initialize database, if it has not been initialized yet. | [
"Initialize",
"database",
"if",
"it",
"has",
"not",
"been",
"initialized",
"yet",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/providers/dependency.py#L24-L32 |
231,421 | ets-labs/python-dependency-injector | examples/providers/dependency.py | UsersService.create | def create(self, name):
"""Create user with provided name and return his id."""
with contextlib.closing(self.database.cursor()) as cursor:
cursor.execute('INSERT INTO users(name) VALUES (?)', (name,))
return cursor.lastrowid | python | def create(self, name):
with contextlib.closing(self.database.cursor()) as cursor:
cursor.execute('INSERT INTO users(name) VALUES (?)', (name,))
return cursor.lastrowid | [
"def",
"create",
"(",
"self",
",",
"name",
")",
":",
"with",
"contextlib",
".",
"closing",
"(",
"self",
".",
"database",
".",
"cursor",
"(",
")",
")",
"as",
"cursor",
":",
"cursor",
".",
"execute",
"(",
"'INSERT INTO users(name) VALUES (?)'",
",",
"(",
"... | Create user with provided name and return his id. | [
"Create",
"user",
"with",
"provided",
"name",
"and",
"return",
"his",
"id",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/providers/dependency.py#L34-L38 |
231,422 | ets-labs/python-dependency-injector | examples/providers/dependency.py | UsersService.get_by_id | def get_by_id(self, id):
"""Return user info by user id."""
with contextlib.closing(self.database.cursor()) as cursor:
cursor.execute('SELECT id, name FROM users WHERE id=?', (id,))
return cursor.fetchone() | python | def get_by_id(self, id):
with contextlib.closing(self.database.cursor()) as cursor:
cursor.execute('SELECT id, name FROM users WHERE id=?', (id,))
return cursor.fetchone() | [
"def",
"get_by_id",
"(",
"self",
",",
"id",
")",
":",
"with",
"contextlib",
".",
"closing",
"(",
"self",
".",
"database",
".",
"cursor",
"(",
")",
")",
"as",
"cursor",
":",
"cursor",
".",
"execute",
"(",
"'SELECT id, name FROM users WHERE id=?'",
",",
"(",... | Return user info by user id. | [
"Return",
"user",
"info",
"by",
"user",
"id",
"."
] | d04fe41eb17f667da38b97525e2d16c8f2d272fe | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/providers/dependency.py#L40-L44 |
231,423 | mattlisiv/newsapi-python | newsapi/newsapi_client.py | NewsApiClient.get_top_headlines | def get_top_headlines(self, q=None, sources=None, language='en', country=None, category=None, page_size=None,
page=None):
"""
Returns live top and breaking headlines for a country, specific category in a country, single source, or multiple sources..
Optional parameters:
(str) q - return headlines w/ specific keyword or phrase. For example:
'bitcoin', 'trump', 'tesla', 'ethereum', etc.
(str) sources - return headlines of news sources! some Valid values are:
'bbc-news', 'the-verge', 'abc-news', 'crypto coins news',
'ary news','associated press','wired','aftenposten','australian financial review','axios',
'bbc news','bild','blasting news','bloomberg','business insider','engadget','google news',
'hacker news','info money,'recode','techcrunch','techradar','the next web','the verge' etc.
(str) language - The 2-letter ISO-639-1 code of the language you want to get headlines for. Valid values are:
'ar','de','en','es','fr','he','it','nl','no','pt','ru','se','ud','zh'
(str) country - The 2-letter ISO 3166-1 code of the country you want to get headlines! Valid values are:
'ae','ar','at','au','be','bg','br','ca','ch','cn','co','cu','cz','de','eg','fr','gb','gr',
'hk','hu','id','ie','il','in','it','jp','kr','lt','lv','ma','mx','my','ng','nl','no','nz',
'ph','pl','pt','ro','rs','ru','sa','se','sg','si','sk','th','tr','tw','ua','us'
(str) category - The category you want to get headlines for! Valid values are:
'business','entertainment','general','health','science','sports','technology'
(int) page_size - The number of results to return per page (request). 20 is the default, 100 is the maximum.
(int) page - Use this to page through the results if the total results found is greater than the page size.
"""
# Define Payload
payload = {}
# Keyword/Phrase
if q is not None:
if type(q) == str:
payload['q'] = q
else:
raise TypeError('keyword/phrase q param should be a of type str')
# Sources
if (sources is not None) and ((country is not None) or (category is not None)):
raise ValueError('cannot mix country/category param with sources param.')
# Sources
if sources is not None:
if type(sources) == str:
payload['sources'] = sources
else:
raise TypeError('sources param should be of type str')
# Language
if language is not None:
if type(language) == str:
if language in const.languages:
payload['language'] = language
else:
raise ValueError('invalid language')
else:
raise TypeError('language param should be of type str')
# Country
if country is not None:
if type(country) == str:
if country in const.countries:
payload['country'] = country
else:
raise ValueError('invalid country')
else:
raise TypeError('country param should be of type str')
# Category
if category is not None:
if type(category) == str:
if category in const.categories:
payload['category'] = category
else:
raise ValueError('invalid category')
else:
raise TypeError('category param should be of type str')
# Page Size
if page_size is not None:
if type(page_size) == int:
if 0 <= page_size <= 100:
payload['pageSize'] = page_size
else:
raise ValueError('page_size param should be an int between 1 and 100')
else:
raise TypeError('page_size param should be an int')
# Page
if page is not None:
if type(page) == int:
if page > 0:
payload['page'] = page
else:
raise ValueError('page param should be an int greater than 0')
else:
raise TypeError('page param should be an int')
# Send Request
r = requests.get(const.TOP_HEADLINES_URL, auth=self.auth, timeout=30, params=payload)
# Check Status of Request
if r.status_code != requests.codes.ok:
raise NewsAPIException(r.json())
return r.json() | python | def get_top_headlines(self, q=None, sources=None, language='en', country=None, category=None, page_size=None,
page=None):
# Define Payload
payload = {}
# Keyword/Phrase
if q is not None:
if type(q) == str:
payload['q'] = q
else:
raise TypeError('keyword/phrase q param should be a of type str')
# Sources
if (sources is not None) and ((country is not None) or (category is not None)):
raise ValueError('cannot mix country/category param with sources param.')
# Sources
if sources is not None:
if type(sources) == str:
payload['sources'] = sources
else:
raise TypeError('sources param should be of type str')
# Language
if language is not None:
if type(language) == str:
if language in const.languages:
payload['language'] = language
else:
raise ValueError('invalid language')
else:
raise TypeError('language param should be of type str')
# Country
if country is not None:
if type(country) == str:
if country in const.countries:
payload['country'] = country
else:
raise ValueError('invalid country')
else:
raise TypeError('country param should be of type str')
# Category
if category is not None:
if type(category) == str:
if category in const.categories:
payload['category'] = category
else:
raise ValueError('invalid category')
else:
raise TypeError('category param should be of type str')
# Page Size
if page_size is not None:
if type(page_size) == int:
if 0 <= page_size <= 100:
payload['pageSize'] = page_size
else:
raise ValueError('page_size param should be an int between 1 and 100')
else:
raise TypeError('page_size param should be an int')
# Page
if page is not None:
if type(page) == int:
if page > 0:
payload['page'] = page
else:
raise ValueError('page param should be an int greater than 0')
else:
raise TypeError('page param should be an int')
# Send Request
r = requests.get(const.TOP_HEADLINES_URL, auth=self.auth, timeout=30, params=payload)
# Check Status of Request
if r.status_code != requests.codes.ok:
raise NewsAPIException(r.json())
return r.json() | [
"def",
"get_top_headlines",
"(",
"self",
",",
"q",
"=",
"None",
",",
"sources",
"=",
"None",
",",
"language",
"=",
"'en'",
",",
"country",
"=",
"None",
",",
"category",
"=",
"None",
",",
"page_size",
"=",
"None",
",",
"page",
"=",
"None",
")",
":",
... | Returns live top and breaking headlines for a country, specific category in a country, single source, or multiple sources..
Optional parameters:
(str) q - return headlines w/ specific keyword or phrase. For example:
'bitcoin', 'trump', 'tesla', 'ethereum', etc.
(str) sources - return headlines of news sources! some Valid values are:
'bbc-news', 'the-verge', 'abc-news', 'crypto coins news',
'ary news','associated press','wired','aftenposten','australian financial review','axios',
'bbc news','bild','blasting news','bloomberg','business insider','engadget','google news',
'hacker news','info money,'recode','techcrunch','techradar','the next web','the verge' etc.
(str) language - The 2-letter ISO-639-1 code of the language you want to get headlines for. Valid values are:
'ar','de','en','es','fr','he','it','nl','no','pt','ru','se','ud','zh'
(str) country - The 2-letter ISO 3166-1 code of the country you want to get headlines! Valid values are:
'ae','ar','at','au','be','bg','br','ca','ch','cn','co','cu','cz','de','eg','fr','gb','gr',
'hk','hu','id','ie','il','in','it','jp','kr','lt','lv','ma','mx','my','ng','nl','no','nz',
'ph','pl','pt','ro','rs','ru','sa','se','sg','si','sk','th','tr','tw','ua','us'
(str) category - The category you want to get headlines for! Valid values are:
'business','entertainment','general','health','science','sports','technology'
(int) page_size - The number of results to return per page (request). 20 is the default, 100 is the maximum.
(int) page - Use this to page through the results if the total results found is greater than the page size. | [
"Returns",
"live",
"top",
"and",
"breaking",
"headlines",
"for",
"a",
"country",
"specific",
"category",
"in",
"a",
"country",
"single",
"source",
"or",
"multiple",
"sources",
".."
] | aec6ef142149c184cc93fcf75c37d78a0341daf4 | https://github.com/mattlisiv/newsapi-python/blob/aec6ef142149c184cc93fcf75c37d78a0341daf4/newsapi/newsapi_client.py#L12-L121 |
231,424 | mattlisiv/newsapi-python | newsapi/newsapi_client.py | NewsApiClient.get_sources | def get_sources(self, category=None, language=None, country=None):
"""
Returns the subset of news publishers that top headlines...
Optional parameters:
(str) category - The category you want to get headlines for! Valid values are:
'business','entertainment','general','health','science','sports','technology'
(str) language - The 2-letter ISO-639-1 code of the language you want to get headlines for. Valid values are:
'ar','de','en','es','fr','he','it','nl','no','pt','ru','se','ud','zh'
(str) country - The 2-letter ISO 3166-1 code of the country you want to get headlines! Valid values are:
'ae','ar','at','au','be','bg','br','ca','ch','cn','co','cu','cz','de','eg','fr','gb','gr',
'hk','hu','id','ie','il','in','it','jp','kr','lt','lv','ma','mx','my','ng','nl','no','nz',
'ph','pl','pt','ro','rs','ru','sa','se','sg','si','sk','th','tr','tw','ua','us'
(str) category - The category you want to get headlines for! Valid values are:
'business','entertainment','general','health','science','sports','technology'
"""
# Define Payload
payload = {}
# Language
if language is not None:
if type(language) == str:
if language in const.languages:
payload['language'] = language
else:
raise ValueError('invalid language')
else:
raise TypeError('language param should be of type str')
# Country
if country is not None:
if type(country) == str:
if country in const.countries:
payload['country'] = country
else:
raise ValueError('invalid country')
else:
raise TypeError('country param should be of type str')
# Category
if category is not None:
if type(category) == str:
if category in const.categories:
payload['category'] = category
else:
raise ValueError('invalid category')
else:
raise TypeError('category param should be of type str')
# Send Request
r = requests.get(const.SOURCES_URL, auth=self.auth, timeout=30, params=payload)
# Check Status of Request
if r.status_code != requests.codes.ok:
raise NewsAPIException(r.json())
return r.json() | python | def get_sources(self, category=None, language=None, country=None):
# Define Payload
payload = {}
# Language
if language is not None:
if type(language) == str:
if language in const.languages:
payload['language'] = language
else:
raise ValueError('invalid language')
else:
raise TypeError('language param should be of type str')
# Country
if country is not None:
if type(country) == str:
if country in const.countries:
payload['country'] = country
else:
raise ValueError('invalid country')
else:
raise TypeError('country param should be of type str')
# Category
if category is not None:
if type(category) == str:
if category in const.categories:
payload['category'] = category
else:
raise ValueError('invalid category')
else:
raise TypeError('category param should be of type str')
# Send Request
r = requests.get(const.SOURCES_URL, auth=self.auth, timeout=30, params=payload)
# Check Status of Request
if r.status_code != requests.codes.ok:
raise NewsAPIException(r.json())
return r.json() | [
"def",
"get_sources",
"(",
"self",
",",
"category",
"=",
"None",
",",
"language",
"=",
"None",
",",
"country",
"=",
"None",
")",
":",
"# Define Payload",
"payload",
"=",
"{",
"}",
"# Language",
"if",
"language",
"is",
"not",
"None",
":",
"if",
"type",
... | Returns the subset of news publishers that top headlines...
Optional parameters:
(str) category - The category you want to get headlines for! Valid values are:
'business','entertainment','general','health','science','sports','technology'
(str) language - The 2-letter ISO-639-1 code of the language you want to get headlines for. Valid values are:
'ar','de','en','es','fr','he','it','nl','no','pt','ru','se','ud','zh'
(str) country - The 2-letter ISO 3166-1 code of the country you want to get headlines! Valid values are:
'ae','ar','at','au','be','bg','br','ca','ch','cn','co','cu','cz','de','eg','fr','gb','gr',
'hk','hu','id','ie','il','in','it','jp','kr','lt','lv','ma','mx','my','ng','nl','no','nz',
'ph','pl','pt','ro','rs','ru','sa','se','sg','si','sk','th','tr','tw','ua','us'
(str) category - The category you want to get headlines for! Valid values are:
'business','entertainment','general','health','science','sports','technology' | [
"Returns",
"the",
"subset",
"of",
"news",
"publishers",
"that",
"top",
"headlines",
"..."
] | aec6ef142149c184cc93fcf75c37d78a0341daf4 | https://github.com/mattlisiv/newsapi-python/blob/aec6ef142149c184cc93fcf75c37d78a0341daf4/newsapi/newsapi_client.py#L265-L326 |
231,425 | metachris/logzero | logzero/__init__.py | setup_logger | def setup_logger(name=None, logfile=None, level=logging.DEBUG, formatter=None, maxBytes=0, backupCount=0, fileLoglevel=None, disableStderrLogger=False):
"""
Configures and returns a fully configured logger instance, no hassles.
If a logger with the specified name already exists, it returns the existing instance,
else creates a new one.
If you set the ``logfile`` parameter with a filename, the logger will save the messages to the logfile,
but does not rotate by default. If you want to enable log rotation, set both ``maxBytes`` and ``backupCount``.
Usage:
.. code-block:: python
from logzero import setup_logger
logger = setup_logger()
logger.info("hello")
:arg string name: Name of the `Logger object <https://docs.python.org/2/library/logging.html#logger-objects>`_. Multiple calls to ``setup_logger()`` with the same name will always return a reference to the same Logger object. (default: ``__name__``)
:arg string logfile: If set, also write logs to the specified filename.
:arg int level: Minimum `logging-level <https://docs.python.org/2/library/logging.html#logging-levels>`_ to display (default: ``logging.DEBUG``).
:arg Formatter formatter: `Python logging Formatter object <https://docs.python.org/2/library/logging.html#formatter-objects>`_ (by default uses the internal LogFormatter).
:arg int maxBytes: Size of the logfile when rollover should occur. Defaults to 0, rollover never occurs.
:arg int backupCount: Number of backups to keep. Defaults to 0, rollover never occurs.
:arg int fileLoglevel: Minimum `logging-level <https://docs.python.org/2/library/logging.html#logging-levels>`_ for the file logger (is not set, it will use the loglevel from the ``level`` argument)
:arg bool disableStderrLogger: Should the default stderr logger be disabled. Defaults to False.
:return: A fully configured Python logging `Logger object <https://docs.python.org/2/library/logging.html#logger-objects>`_ you can use with ``.debug("msg")``, etc.
"""
_logger = logging.getLogger(name or __name__)
_logger.propagate = False
_logger.setLevel(level)
# Reconfigure existing handlers
stderr_stream_handler = None
for handler in list(_logger.handlers):
if hasattr(handler, LOGZERO_INTERNAL_LOGGER_ATTR):
if isinstance(handler, logging.FileHandler):
# Internal FileHandler needs to be removed and re-setup to be able
# to set a new logfile.
_logger.removeHandler(handler)
continue
elif isinstance(handler, logging.StreamHandler):
stderr_stream_handler = handler
# reconfigure handler
handler.setLevel(level)
handler.setFormatter(formatter or LogFormatter())
# remove the stderr handler (stream_handler) if disabled
if disableStderrLogger:
if stderr_stream_handler is not None:
_logger.removeHandler(stderr_stream_handler)
elif stderr_stream_handler is None:
stderr_stream_handler = logging.StreamHandler()
setattr(stderr_stream_handler, LOGZERO_INTERNAL_LOGGER_ATTR, True)
stderr_stream_handler.setLevel(level)
stderr_stream_handler.setFormatter(formatter or LogFormatter())
_logger.addHandler(stderr_stream_handler)
if logfile:
rotating_filehandler = RotatingFileHandler(filename=logfile, maxBytes=maxBytes, backupCount=backupCount)
setattr(rotating_filehandler, LOGZERO_INTERNAL_LOGGER_ATTR, True)
rotating_filehandler.setLevel(fileLoglevel or level)
rotating_filehandler.setFormatter(formatter or LogFormatter(color=False))
_logger.addHandler(rotating_filehandler)
return _logger | python | def setup_logger(name=None, logfile=None, level=logging.DEBUG, formatter=None, maxBytes=0, backupCount=0, fileLoglevel=None, disableStderrLogger=False):
_logger = logging.getLogger(name or __name__)
_logger.propagate = False
_logger.setLevel(level)
# Reconfigure existing handlers
stderr_stream_handler = None
for handler in list(_logger.handlers):
if hasattr(handler, LOGZERO_INTERNAL_LOGGER_ATTR):
if isinstance(handler, logging.FileHandler):
# Internal FileHandler needs to be removed and re-setup to be able
# to set a new logfile.
_logger.removeHandler(handler)
continue
elif isinstance(handler, logging.StreamHandler):
stderr_stream_handler = handler
# reconfigure handler
handler.setLevel(level)
handler.setFormatter(formatter or LogFormatter())
# remove the stderr handler (stream_handler) if disabled
if disableStderrLogger:
if stderr_stream_handler is not None:
_logger.removeHandler(stderr_stream_handler)
elif stderr_stream_handler is None:
stderr_stream_handler = logging.StreamHandler()
setattr(stderr_stream_handler, LOGZERO_INTERNAL_LOGGER_ATTR, True)
stderr_stream_handler.setLevel(level)
stderr_stream_handler.setFormatter(formatter or LogFormatter())
_logger.addHandler(stderr_stream_handler)
if logfile:
rotating_filehandler = RotatingFileHandler(filename=logfile, maxBytes=maxBytes, backupCount=backupCount)
setattr(rotating_filehandler, LOGZERO_INTERNAL_LOGGER_ATTR, True)
rotating_filehandler.setLevel(fileLoglevel or level)
rotating_filehandler.setFormatter(formatter or LogFormatter(color=False))
_logger.addHandler(rotating_filehandler)
return _logger | [
"def",
"setup_logger",
"(",
"name",
"=",
"None",
",",
"logfile",
"=",
"None",
",",
"level",
"=",
"logging",
".",
"DEBUG",
",",
"formatter",
"=",
"None",
",",
"maxBytes",
"=",
"0",
",",
"backupCount",
"=",
"0",
",",
"fileLoglevel",
"=",
"None",
",",
"... | Configures and returns a fully configured logger instance, no hassles.
If a logger with the specified name already exists, it returns the existing instance,
else creates a new one.
If you set the ``logfile`` parameter with a filename, the logger will save the messages to the logfile,
but does not rotate by default. If you want to enable log rotation, set both ``maxBytes`` and ``backupCount``.
Usage:
.. code-block:: python
from logzero import setup_logger
logger = setup_logger()
logger.info("hello")
:arg string name: Name of the `Logger object <https://docs.python.org/2/library/logging.html#logger-objects>`_. Multiple calls to ``setup_logger()`` with the same name will always return a reference to the same Logger object. (default: ``__name__``)
:arg string logfile: If set, also write logs to the specified filename.
:arg int level: Minimum `logging-level <https://docs.python.org/2/library/logging.html#logging-levels>`_ to display (default: ``logging.DEBUG``).
:arg Formatter formatter: `Python logging Formatter object <https://docs.python.org/2/library/logging.html#formatter-objects>`_ (by default uses the internal LogFormatter).
:arg int maxBytes: Size of the logfile when rollover should occur. Defaults to 0, rollover never occurs.
:arg int backupCount: Number of backups to keep. Defaults to 0, rollover never occurs.
:arg int fileLoglevel: Minimum `logging-level <https://docs.python.org/2/library/logging.html#logging-levels>`_ for the file logger (is not set, it will use the loglevel from the ``level`` argument)
:arg bool disableStderrLogger: Should the default stderr logger be disabled. Defaults to False.
:return: A fully configured Python logging `Logger object <https://docs.python.org/2/library/logging.html#logger-objects>`_ you can use with ``.debug("msg")``, etc. | [
"Configures",
"and",
"returns",
"a",
"fully",
"configured",
"logger",
"instance",
"no",
"hassles",
".",
"If",
"a",
"logger",
"with",
"the",
"specified",
"name",
"already",
"exists",
"it",
"returns",
"the",
"existing",
"instance",
"else",
"creates",
"a",
"new",... | b5d49fc2b118c370994c4ae5360d7c246d43ddc8 | https://github.com/metachris/logzero/blob/b5d49fc2b118c370994c4ae5360d7c246d43ddc8/logzero/__init__.py#L87-L152 |
231,426 | metachris/logzero | logzero/__init__.py | to_unicode | def to_unicode(value):
"""
Converts a string argument to a unicode string.
If the argument is already a unicode string or None, it is returned
unchanged. Otherwise it must be a byte string and is decoded as utf8.
"""
if isinstance(value, _TO_UNICODE_TYPES):
return value
if not isinstance(value, bytes):
raise TypeError(
"Expected bytes, unicode, or None; got %r" % type(value))
return value.decode("utf-8") | python | def to_unicode(value):
if isinstance(value, _TO_UNICODE_TYPES):
return value
if not isinstance(value, bytes):
raise TypeError(
"Expected bytes, unicode, or None; got %r" % type(value))
return value.decode("utf-8") | [
"def",
"to_unicode",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"_TO_UNICODE_TYPES",
")",
":",
"return",
"value",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected bytes, unicode, or Non... | Converts a string argument to a unicode string.
If the argument is already a unicode string or None, it is returned
unchanged. Otherwise it must be a byte string and is decoded as utf8. | [
"Converts",
"a",
"string",
"argument",
"to",
"a",
"unicode",
"string",
".",
"If",
"the",
"argument",
"is",
"already",
"a",
"unicode",
"string",
"or",
"None",
"it",
"is",
"returned",
"unchanged",
".",
"Otherwise",
"it",
"must",
"be",
"a",
"byte",
"string",
... | b5d49fc2b118c370994c4ae5360d7c246d43ddc8 | https://github.com/metachris/logzero/blob/b5d49fc2b118c370994c4ae5360d7c246d43ddc8/logzero/__init__.py#L273-L284 |
231,427 | metachris/logzero | logzero/__init__.py | reset_default_logger | def reset_default_logger():
"""
Resets the internal default logger to the initial configuration
"""
global logger
global _loglevel
global _logfile
global _formatter
_loglevel = logging.DEBUG
_logfile = None
_formatter = None
logger = setup_logger(name=LOGZERO_DEFAULT_LOGGER, logfile=_logfile, level=_loglevel, formatter=_formatter) | python | def reset_default_logger():
global logger
global _loglevel
global _logfile
global _formatter
_loglevel = logging.DEBUG
_logfile = None
_formatter = None
logger = setup_logger(name=LOGZERO_DEFAULT_LOGGER, logfile=_logfile, level=_loglevel, formatter=_formatter) | [
"def",
"reset_default_logger",
"(",
")",
":",
"global",
"logger",
"global",
"_loglevel",
"global",
"_logfile",
"global",
"_formatter",
"_loglevel",
"=",
"logging",
".",
"DEBUG",
"_logfile",
"=",
"None",
"_formatter",
"=",
"None",
"logger",
"=",
"setup_logger",
"... | Resets the internal default logger to the initial configuration | [
"Resets",
"the",
"internal",
"default",
"logger",
"to",
"the",
"initial",
"configuration"
] | b5d49fc2b118c370994c4ae5360d7c246d43ddc8 | https://github.com/metachris/logzero/blob/b5d49fc2b118c370994c4ae5360d7c246d43ddc8/logzero/__init__.py#L320-L331 |
231,428 | moble/quaternion | quaternion_time_series.py | slerp | def slerp(R1, R2, t1, t2, t_out):
"""Spherical linear interpolation of rotors
This function uses a simpler interface than the more fundamental
`slerp_evaluate` and `slerp_vectorized` functions. The latter
are fast, being implemented at the C level, but take input `tau`
instead of time. This function adjusts the time accordingly.
Parameters
----------
R1: quaternion
Quaternion at beginning of interpolation
R2: quaternion
Quaternion at end of interpolation
t1: float
Time corresponding to R1
t2: float
Time corresponding to R2
t_out: float or array of floats
Times to which the rotors should be interpolated
"""
tau = (t_out-t1)/(t2-t1)
return np.slerp_vectorized(R1, R2, tau) | python | def slerp(R1, R2, t1, t2, t_out):
tau = (t_out-t1)/(t2-t1)
return np.slerp_vectorized(R1, R2, tau) | [
"def",
"slerp",
"(",
"R1",
",",
"R2",
",",
"t1",
",",
"t2",
",",
"t_out",
")",
":",
"tau",
"=",
"(",
"t_out",
"-",
"t1",
")",
"/",
"(",
"t2",
"-",
"t1",
")",
"return",
"np",
".",
"slerp_vectorized",
"(",
"R1",
",",
"R2",
",",
"tau",
")"
] | Spherical linear interpolation of rotors
This function uses a simpler interface than the more fundamental
`slerp_evaluate` and `slerp_vectorized` functions. The latter
are fast, being implemented at the C level, but take input `tau`
instead of time. This function adjusts the time accordingly.
Parameters
----------
R1: quaternion
Quaternion at beginning of interpolation
R2: quaternion
Quaternion at end of interpolation
t1: float
Time corresponding to R1
t2: float
Time corresponding to R2
t_out: float or array of floats
Times to which the rotors should be interpolated | [
"Spherical",
"linear",
"interpolation",
"of",
"rotors"
] | 7a323e81b391d6892e2874073e495e0beb057e85 | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/quaternion_time_series.py#L11-L35 |
231,429 | moble/quaternion | quaternion_time_series.py | squad | def squad(R_in, t_in, t_out):
"""Spherical "quadrangular" interpolation of rotors with a cubic spline
This is the best way to interpolate rotations. It uses the analog
of a cubic spline, except that the interpolant is confined to the
rotor manifold in a natural way. Alternative methods involving
interpolation of other coordinates on the rotation group or
normalization of interpolated values give bad results. The
results from this method are as natural as any, and are continuous
in first and second derivatives.
The input `R_in` rotors are assumed to be reasonably continuous
(no sign flips), and the input `t` arrays are assumed to be
sorted. No checking is done for either case, and you may get
silently bad results if these conditions are violated.
This function simplifies the calling, compared to `squad_evaluate`
(which takes a set of four quaternions forming the edges of the
"quadrangle", and the normalized time `tau`) and `squad_vectorized`
(which takes the same arguments, but in array form, and efficiently
loops over them).
Parameters
----------
R_in: array of quaternions
A time-series of rotors (unit quaternions) to be interpolated
t_in: array of float
The times corresponding to R_in
t_out: array of float
The times to which R_in should be interpolated
"""
if R_in.size == 0 or t_out.size == 0:
return np.array((), dtype=np.quaternion)
# This list contains an index for each `t_out` such that
# t_in[i-1] <= t_out < t_in[i]
# Note that `side='right'` is much faster in my tests
# i_in_for_out = t_in.searchsorted(t_out, side='left')
# np.clip(i_in_for_out, 0, len(t_in) - 1, out=i_in_for_out)
i_in_for_out = t_in.searchsorted(t_out, side='right')-1
# Now, for each index `i` in `i_in`, we need to compute the
# interpolation "coefficients" (`A_i`, `B_ip1`).
#
# I previously tested an explicit version of the loops below,
# comparing `stride_tricks.as_strided` with explicit
# implementation via `roll` (as seen here). I found that the
# `roll` was significantly more efficient for simple calculations,
# though the difference is probably totally washed out here. In
# any case, it might be useful to test again.
#
A = R_in * np.exp((- np.log((~R_in) * np.roll(R_in, -1))
+ np.log((~np.roll(R_in, 1)) * R_in) * ((np.roll(t_in, -1) - t_in) / (t_in - np.roll(t_in, 1)))
) * 0.25)
B = np.roll(R_in, -1) * np.exp((np.log((~np.roll(R_in, -1)) * np.roll(R_in, -2))
* ((np.roll(t_in, -1) - t_in) / (np.roll(t_in, -2) - np.roll(t_in, -1)))
- np.log((~R_in) * np.roll(R_in, -1))) * -0.25)
# Correct the first and last A time steps, and last two B time steps. We extend R_in with the following wrap-around
# values:
# R_in[0-1] = R_in[0]*(~R_in[1])*R_in[0]
# R_in[n+0] = R_in[-1] * (~R_in[-2]) * R_in[-1]
# R_in[n+1] = R_in[0] * (~R_in[-1]) * R_in[0]
# = R_in[-1] * (~R_in[-2]) * R_in[-1] * (~R_in[-1]) * R_in[-1] * (~R_in[-2]) * R_in[-1]
# = R_in[-1] * (~R_in[-2]) * R_in[-1] * (~R_in[-2]) * R_in[-1]
# A[i] = R_in[i] * np.exp((- np.log((~R_in[i]) * R_in[i+1])
# + np.log((~R_in[i-1]) * R_in[i]) * ((t_in[i+1] - t_in[i]) / (t_in[i] - t_in[i-1]))
# ) * 0.25)
# A[0] = R_in[0] * np.exp((- np.log((~R_in[0]) * R_in[1]) + np.log((~R_in[0])*R_in[1]*(~R_in[0])) * R_in[0]) * 0.25)
# = R_in[0]
A[0] = R_in[0]
# A[-1] = R_in[-1] * np.exp((- np.log((~R_in[-1]) * R_in[n+0])
# + np.log((~R_in[-2]) * R_in[-1]) * ((t_in[n+0] - t_in[-1]) / (t_in[-1] - t_in[-2]))
# ) * 0.25)
# = R_in[-1] * np.exp((- np.log((~R_in[-1]) * R_in[n+0]) + np.log((~R_in[-2]) * R_in[-1])) * 0.25)
# = R_in[-1] * np.exp((- np.log((~R_in[-1]) * R_in[-1] * (~R_in[-2]) * R_in[-1])
# + np.log((~R_in[-2]) * R_in[-1])) * 0.25)
# = R_in[-1] * np.exp((- np.log((~R_in[-2]) * R_in[-1]) + np.log((~R_in[-2]) * R_in[-1])) * 0.25)
# = R_in[-1]
A[-1] = R_in[-1]
# B[i] = R_in[i+1] * np.exp((np.log((~R_in[i+1]) * R_in[i+2]) * ((t_in[i+1] - t_in[i]) / (t_in[i+2] - t_in[i+1]))
# - np.log((~R_in[i]) * R_in[i+1])) * -0.25)
# B[-2] = R_in[-1] * np.exp((np.log((~R_in[-1]) * R_in[0]) * ((t_in[-1] - t_in[-2]) / (t_in[0] - t_in[-1]))
# - np.log((~R_in[-2]) * R_in[-1])) * -0.25)
# = R_in[-1] * np.exp((np.log((~R_in[-1]) * R_in[0]) - np.log((~R_in[-2]) * R_in[-1])) * -0.25)
# = R_in[-1] * np.exp((np.log((~R_in[-1]) * R_in[-1] * (~R_in[-2]) * R_in[-1])
# - np.log((~R_in[-2]) * R_in[-1])) * -0.25)
# = R_in[-1] * np.exp((np.log((~R_in[-2]) * R_in[-1]) - np.log((~R_in[-2]) * R_in[-1])) * -0.25)
# = R_in[-1]
B[-2] = R_in[-1]
# B[-1] = R_in[0]
# B[-1] = R_in[0] * np.exp((np.log((~R_in[0]) * R_in[1]) - np.log((~R_in[-1]) * R_in[0])) * -0.25)
# = R_in[-1] * (~R_in[-2]) * R_in[-1]
# * np.exp((np.log((~(R_in[-1] * (~R_in[-2]) * R_in[-1])) * R_in[-1] * (~R_in[-2]) * R_in[-1] * (~R_in[-2]) * R_in[-1])
# - np.log((~R_in[-1]) * R_in[-1] * (~R_in[-2]) * R_in[-1])) * -0.25)
# = R_in[-1] * (~R_in[-2]) * R_in[-1]
# * np.exp((np.log(((~R_in[-1]) * R_in[-2] * (~R_in[-1])) * R_in[-1] * (~R_in[-2]) * R_in[-1] * (~R_in[-2]) * R_in[-1])
# - np.log((~R_in[-1]) * R_in[-1] * (~R_in[-2]) * R_in[-1])) * -0.25)
# * np.exp((np.log((~R_in[-2]) * R_in[-1])
# - np.log((~R_in[-2]) * R_in[-1])) * -0.25)
B[-1] = R_in[-1] * (~R_in[-2]) * R_in[-1]
# Use the coefficients at the corresponding t_out indices to
# compute the squad interpolant
# R_ip1 = np.array(np.roll(R_in, -1)[i_in_for_out])
# R_ip1[-1] = R_in[-1]*(~R_in[-2])*R_in[-1]
R_ip1 = np.roll(R_in, -1)
R_ip1[-1] = R_in[-1]*(~R_in[-2])*R_in[-1]
R_ip1 = np.array(R_ip1[i_in_for_out])
t_inp1 = np.roll(t_in, -1)
t_inp1[-1] = t_in[-1] + (t_in[-1] - t_in[-2])
tau = (t_out - t_in[i_in_for_out]) / ((t_inp1 - t_in)[i_in_for_out])
# tau = (t_out - t_in[i_in_for_out]) / ((np.roll(t_in, -1) - t_in)[i_in_for_out])
R_out = np.squad_vectorized(tau, R_in[i_in_for_out], A[i_in_for_out], B[i_in_for_out], R_ip1)
return R_out | python | def squad(R_in, t_in, t_out):
if R_in.size == 0 or t_out.size == 0:
return np.array((), dtype=np.quaternion)
# This list contains an index for each `t_out` such that
# t_in[i-1] <= t_out < t_in[i]
# Note that `side='right'` is much faster in my tests
# i_in_for_out = t_in.searchsorted(t_out, side='left')
# np.clip(i_in_for_out, 0, len(t_in) - 1, out=i_in_for_out)
i_in_for_out = t_in.searchsorted(t_out, side='right')-1
# Now, for each index `i` in `i_in`, we need to compute the
# interpolation "coefficients" (`A_i`, `B_ip1`).
#
# I previously tested an explicit version of the loops below,
# comparing `stride_tricks.as_strided` with explicit
# implementation via `roll` (as seen here). I found that the
# `roll` was significantly more efficient for simple calculations,
# though the difference is probably totally washed out here. In
# any case, it might be useful to test again.
#
A = R_in * np.exp((- np.log((~R_in) * np.roll(R_in, -1))
+ np.log((~np.roll(R_in, 1)) * R_in) * ((np.roll(t_in, -1) - t_in) / (t_in - np.roll(t_in, 1)))
) * 0.25)
B = np.roll(R_in, -1) * np.exp((np.log((~np.roll(R_in, -1)) * np.roll(R_in, -2))
* ((np.roll(t_in, -1) - t_in) / (np.roll(t_in, -2) - np.roll(t_in, -1)))
- np.log((~R_in) * np.roll(R_in, -1))) * -0.25)
# Correct the first and last A time steps, and last two B time steps. We extend R_in with the following wrap-around
# values:
# R_in[0-1] = R_in[0]*(~R_in[1])*R_in[0]
# R_in[n+0] = R_in[-1] * (~R_in[-2]) * R_in[-1]
# R_in[n+1] = R_in[0] * (~R_in[-1]) * R_in[0]
# = R_in[-1] * (~R_in[-2]) * R_in[-1] * (~R_in[-1]) * R_in[-1] * (~R_in[-2]) * R_in[-1]
# = R_in[-1] * (~R_in[-2]) * R_in[-1] * (~R_in[-2]) * R_in[-1]
# A[i] = R_in[i] * np.exp((- np.log((~R_in[i]) * R_in[i+1])
# + np.log((~R_in[i-1]) * R_in[i]) * ((t_in[i+1] - t_in[i]) / (t_in[i] - t_in[i-1]))
# ) * 0.25)
# A[0] = R_in[0] * np.exp((- np.log((~R_in[0]) * R_in[1]) + np.log((~R_in[0])*R_in[1]*(~R_in[0])) * R_in[0]) * 0.25)
# = R_in[0]
A[0] = R_in[0]
# A[-1] = R_in[-1] * np.exp((- np.log((~R_in[-1]) * R_in[n+0])
# + np.log((~R_in[-2]) * R_in[-1]) * ((t_in[n+0] - t_in[-1]) / (t_in[-1] - t_in[-2]))
# ) * 0.25)
# = R_in[-1] * np.exp((- np.log((~R_in[-1]) * R_in[n+0]) + np.log((~R_in[-2]) * R_in[-1])) * 0.25)
# = R_in[-1] * np.exp((- np.log((~R_in[-1]) * R_in[-1] * (~R_in[-2]) * R_in[-1])
# + np.log((~R_in[-2]) * R_in[-1])) * 0.25)
# = R_in[-1] * np.exp((- np.log((~R_in[-2]) * R_in[-1]) + np.log((~R_in[-2]) * R_in[-1])) * 0.25)
# = R_in[-1]
A[-1] = R_in[-1]
# B[i] = R_in[i+1] * np.exp((np.log((~R_in[i+1]) * R_in[i+2]) * ((t_in[i+1] - t_in[i]) / (t_in[i+2] - t_in[i+1]))
# - np.log((~R_in[i]) * R_in[i+1])) * -0.25)
# B[-2] = R_in[-1] * np.exp((np.log((~R_in[-1]) * R_in[0]) * ((t_in[-1] - t_in[-2]) / (t_in[0] - t_in[-1]))
# - np.log((~R_in[-2]) * R_in[-1])) * -0.25)
# = R_in[-1] * np.exp((np.log((~R_in[-1]) * R_in[0]) - np.log((~R_in[-2]) * R_in[-1])) * -0.25)
# = R_in[-1] * np.exp((np.log((~R_in[-1]) * R_in[-1] * (~R_in[-2]) * R_in[-1])
# - np.log((~R_in[-2]) * R_in[-1])) * -0.25)
# = R_in[-1] * np.exp((np.log((~R_in[-2]) * R_in[-1]) - np.log((~R_in[-2]) * R_in[-1])) * -0.25)
# = R_in[-1]
B[-2] = R_in[-1]
# B[-1] = R_in[0]
# B[-1] = R_in[0] * np.exp((np.log((~R_in[0]) * R_in[1]) - np.log((~R_in[-1]) * R_in[0])) * -0.25)
# = R_in[-1] * (~R_in[-2]) * R_in[-1]
# * np.exp((np.log((~(R_in[-1] * (~R_in[-2]) * R_in[-1])) * R_in[-1] * (~R_in[-2]) * R_in[-1] * (~R_in[-2]) * R_in[-1])
# - np.log((~R_in[-1]) * R_in[-1] * (~R_in[-2]) * R_in[-1])) * -0.25)
# = R_in[-1] * (~R_in[-2]) * R_in[-1]
# * np.exp((np.log(((~R_in[-1]) * R_in[-2] * (~R_in[-1])) * R_in[-1] * (~R_in[-2]) * R_in[-1] * (~R_in[-2]) * R_in[-1])
# - np.log((~R_in[-1]) * R_in[-1] * (~R_in[-2]) * R_in[-1])) * -0.25)
# * np.exp((np.log((~R_in[-2]) * R_in[-1])
# - np.log((~R_in[-2]) * R_in[-1])) * -0.25)
B[-1] = R_in[-1] * (~R_in[-2]) * R_in[-1]
# Use the coefficients at the corresponding t_out indices to
# compute the squad interpolant
# R_ip1 = np.array(np.roll(R_in, -1)[i_in_for_out])
# R_ip1[-1] = R_in[-1]*(~R_in[-2])*R_in[-1]
R_ip1 = np.roll(R_in, -1)
R_ip1[-1] = R_in[-1]*(~R_in[-2])*R_in[-1]
R_ip1 = np.array(R_ip1[i_in_for_out])
t_inp1 = np.roll(t_in, -1)
t_inp1[-1] = t_in[-1] + (t_in[-1] - t_in[-2])
tau = (t_out - t_in[i_in_for_out]) / ((t_inp1 - t_in)[i_in_for_out])
# tau = (t_out - t_in[i_in_for_out]) / ((np.roll(t_in, -1) - t_in)[i_in_for_out])
R_out = np.squad_vectorized(tau, R_in[i_in_for_out], A[i_in_for_out], B[i_in_for_out], R_ip1)
return R_out | [
"def",
"squad",
"(",
"R_in",
",",
"t_in",
",",
"t_out",
")",
":",
"if",
"R_in",
".",
"size",
"==",
"0",
"or",
"t_out",
".",
"size",
"==",
"0",
":",
"return",
"np",
".",
"array",
"(",
"(",
")",
",",
"dtype",
"=",
"np",
".",
"quaternion",
")",
... | Spherical "quadrangular" interpolation of rotors with a cubic spline
This is the best way to interpolate rotations. It uses the analog
of a cubic spline, except that the interpolant is confined to the
rotor manifold in a natural way. Alternative methods involving
interpolation of other coordinates on the rotation group or
normalization of interpolated values give bad results. The
results from this method are as natural as any, and are continuous
in first and second derivatives.
The input `R_in` rotors are assumed to be reasonably continuous
(no sign flips), and the input `t` arrays are assumed to be
sorted. No checking is done for either case, and you may get
silently bad results if these conditions are violated.
This function simplifies the calling, compared to `squad_evaluate`
(which takes a set of four quaternions forming the edges of the
"quadrangle", and the normalized time `tau`) and `squad_vectorized`
(which takes the same arguments, but in array form, and efficiently
loops over them).
Parameters
----------
R_in: array of quaternions
A time-series of rotors (unit quaternions) to be interpolated
t_in: array of float
The times corresponding to R_in
t_out: array of float
The times to which R_in should be interpolated | [
"Spherical",
"quadrangular",
"interpolation",
"of",
"rotors",
"with",
"a",
"cubic",
"spline"
] | 7a323e81b391d6892e2874073e495e0beb057e85 | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/quaternion_time_series.py#L38-L154 |
231,430 | moble/quaternion | quaternion_time_series.py | integrate_angular_velocity | def integrate_angular_velocity(Omega, t0, t1, R0=None, tolerance=1e-12):
"""Compute frame with given angular velocity
Parameters
==========
Omega: tuple or callable
Angular velocity from which to compute frame. Can be
1) a 2-tuple of float arrays (t, v) giving the angular velocity vector at a series of times,
2) a function of time that returns the 3-vector angular velocity, or
3) a function of time and orientation (t, R) that returns the 3-vector angular velocity
In case 1, the angular velocity will be interpolated to the required times. Note that accuracy
is poor in case 1.
t0: float
Initial time
t1: float
Final time
R0: quaternion, optional
Initial frame orientation. Defaults to 1 (the identity orientation).
tolerance: float, optional
Absolute tolerance used in integration. Defaults to 1e-12.
Returns
=======
t: float array
R: quaternion array
"""
import warnings
from scipy.integrate import ode
if R0 is None:
R0 = quaternion.one
input_is_tabulated = False
try:
t_Omega, v = Omega
from scipy.interpolate import InterpolatedUnivariateSpline
Omega_x = InterpolatedUnivariateSpline(t_Omega, v[:, 0])
Omega_y = InterpolatedUnivariateSpline(t_Omega, v[:, 1])
Omega_z = InterpolatedUnivariateSpline(t_Omega, v[:, 2])
def Omega_func(t, R):
return [Omega_x(t), Omega_y(t), Omega_z(t)]
Omega_func(t0, R0)
input_is_tabulated = True
except (TypeError, ValueError):
def Omega_func(t, R):
return Omega(t, R)
try:
Omega_func(t0, R0)
except TypeError:
def Omega_func(t, R):
return Omega(t)
Omega_func(t0, R0)
def RHS(t, y):
R = quaternion.quaternion(*y)
return (0.5 * quaternion.quaternion(0.0, *Omega_func(t, R)) * R).components
y0 = R0.components
if input_is_tabulated:
from scipy.integrate import solve_ivp
t = t_Omega
t_span = [t_Omega[0], t_Omega[-1]]
solution = solve_ivp(RHS, t_span, y0, t_eval=t_Omega, atol=tolerance, rtol=100*np.finfo(float).eps)
R = quaternion.from_float_array(solution.y.T)
else:
solver = ode(RHS)
solver.set_initial_value(y0, t0)
solver.set_integrator('dop853', nsteps=1, atol=tolerance, rtol=0.0)
solver._integrator.iwork[2] = -1 # suppress Fortran-printed warning
t = appending_array((int(t1-t0),))
t.append(solver.t)
R = appending_array((int(t1-t0), 4))
R.append(solver.y)
warnings.filterwarnings("ignore", category=UserWarning)
t_last = solver.t
while solver.t < t1:
solver.integrate(t1, step=True)
if solver.t > t_last:
t.append(solver.t)
R.append(solver.y)
t_last = solver.t
warnings.resetwarnings()
t = t.a
R = quaternion.as_quat_array(R.a)
return t, R | python | def integrate_angular_velocity(Omega, t0, t1, R0=None, tolerance=1e-12):
import warnings
from scipy.integrate import ode
if R0 is None:
R0 = quaternion.one
input_is_tabulated = False
try:
t_Omega, v = Omega
from scipy.interpolate import InterpolatedUnivariateSpline
Omega_x = InterpolatedUnivariateSpline(t_Omega, v[:, 0])
Omega_y = InterpolatedUnivariateSpline(t_Omega, v[:, 1])
Omega_z = InterpolatedUnivariateSpline(t_Omega, v[:, 2])
def Omega_func(t, R):
return [Omega_x(t), Omega_y(t), Omega_z(t)]
Omega_func(t0, R0)
input_is_tabulated = True
except (TypeError, ValueError):
def Omega_func(t, R):
return Omega(t, R)
try:
Omega_func(t0, R0)
except TypeError:
def Omega_func(t, R):
return Omega(t)
Omega_func(t0, R0)
def RHS(t, y):
R = quaternion.quaternion(*y)
return (0.5 * quaternion.quaternion(0.0, *Omega_func(t, R)) * R).components
y0 = R0.components
if input_is_tabulated:
from scipy.integrate import solve_ivp
t = t_Omega
t_span = [t_Omega[0], t_Omega[-1]]
solution = solve_ivp(RHS, t_span, y0, t_eval=t_Omega, atol=tolerance, rtol=100*np.finfo(float).eps)
R = quaternion.from_float_array(solution.y.T)
else:
solver = ode(RHS)
solver.set_initial_value(y0, t0)
solver.set_integrator('dop853', nsteps=1, atol=tolerance, rtol=0.0)
solver._integrator.iwork[2] = -1 # suppress Fortran-printed warning
t = appending_array((int(t1-t0),))
t.append(solver.t)
R = appending_array((int(t1-t0), 4))
R.append(solver.y)
warnings.filterwarnings("ignore", category=UserWarning)
t_last = solver.t
while solver.t < t1:
solver.integrate(t1, step=True)
if solver.t > t_last:
t.append(solver.t)
R.append(solver.y)
t_last = solver.t
warnings.resetwarnings()
t = t.a
R = quaternion.as_quat_array(R.a)
return t, R | [
"def",
"integrate_angular_velocity",
"(",
"Omega",
",",
"t0",
",",
"t1",
",",
"R0",
"=",
"None",
",",
"tolerance",
"=",
"1e-12",
")",
":",
"import",
"warnings",
"from",
"scipy",
".",
"integrate",
"import",
"ode",
"if",
"R0",
"is",
"None",
":",
"R0",
"=... | Compute frame with given angular velocity
Parameters
==========
Omega: tuple or callable
Angular velocity from which to compute frame. Can be
1) a 2-tuple of float arrays (t, v) giving the angular velocity vector at a series of times,
2) a function of time that returns the 3-vector angular velocity, or
3) a function of time and orientation (t, R) that returns the 3-vector angular velocity
In case 1, the angular velocity will be interpolated to the required times. Note that accuracy
is poor in case 1.
t0: float
Initial time
t1: float
Final time
R0: quaternion, optional
Initial frame orientation. Defaults to 1 (the identity orientation).
tolerance: float, optional
Absolute tolerance used in integration. Defaults to 1e-12.
Returns
=======
t: float array
R: quaternion array | [
"Compute",
"frame",
"with",
"given",
"angular",
"velocity"
] | 7a323e81b391d6892e2874073e495e0beb057e85 | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/quaternion_time_series.py#L203-L291 |
231,431 | moble/quaternion | quaternion_time_series.py | minimal_rotation | def minimal_rotation(R, t, iterations=2):
"""Adjust frame so that there is no rotation about z' axis
The output of this function is a frame that rotates the z axis onto the same z' axis as the
input frame, but with minimal rotation about that axis. This is done by pre-composing the input
rotation with a rotation about the z axis through an angle gamma, where
dgamma/dt = 2*(dR/dt * z * R.conjugate()).w
This ensures that the angular velocity has no component along the z' axis.
Note that this condition becomes easier to impose the closer the input rotation is to a
minimally rotating frame, which means that repeated application of this function improves its
accuracy. By default, this function is iterated twice, though a few more iterations may be
called for.
Parameters
==========
R: quaternion array
Time series describing rotation
t: float array
Corresponding times at which R is measured
iterations: int [defaults to 2]
Repeat the minimization to refine the result
"""
from scipy.interpolate import InterpolatedUnivariateSpline as spline
if iterations == 0:
return R
R = quaternion.as_float_array(R)
Rdot = np.empty_like(R)
for i in range(4):
Rdot[:, i] = spline(t, R[:, i]).derivative()(t)
R = quaternion.from_float_array(R)
Rdot = quaternion.from_float_array(Rdot)
halfgammadot = quaternion.as_float_array(Rdot * quaternion.z * R.conjugate())[:, 0]
halfgamma = spline(t, halfgammadot).antiderivative()(t)
Rgamma = np.exp(quaternion.z * halfgamma)
return minimal_rotation(R * Rgamma, t, iterations=iterations-1) | python | def minimal_rotation(R, t, iterations=2):
from scipy.interpolate import InterpolatedUnivariateSpline as spline
if iterations == 0:
return R
R = quaternion.as_float_array(R)
Rdot = np.empty_like(R)
for i in range(4):
Rdot[:, i] = spline(t, R[:, i]).derivative()(t)
R = quaternion.from_float_array(R)
Rdot = quaternion.from_float_array(Rdot)
halfgammadot = quaternion.as_float_array(Rdot * quaternion.z * R.conjugate())[:, 0]
halfgamma = spline(t, halfgammadot).antiderivative()(t)
Rgamma = np.exp(quaternion.z * halfgamma)
return minimal_rotation(R * Rgamma, t, iterations=iterations-1) | [
"def",
"minimal_rotation",
"(",
"R",
",",
"t",
",",
"iterations",
"=",
"2",
")",
":",
"from",
"scipy",
".",
"interpolate",
"import",
"InterpolatedUnivariateSpline",
"as",
"spline",
"if",
"iterations",
"==",
"0",
":",
"return",
"R",
"R",
"=",
"quaternion",
... | Adjust frame so that there is no rotation about z' axis
The output of this function is a frame that rotates the z axis onto the same z' axis as the
input frame, but with minimal rotation about that axis. This is done by pre-composing the input
rotation with a rotation about the z axis through an angle gamma, where
dgamma/dt = 2*(dR/dt * z * R.conjugate()).w
This ensures that the angular velocity has no component along the z' axis.
Note that this condition becomes easier to impose the closer the input rotation is to a
minimally rotating frame, which means that repeated application of this function improves its
accuracy. By default, this function is iterated twice, though a few more iterations may be
called for.
Parameters
==========
R: quaternion array
Time series describing rotation
t: float array
Corresponding times at which R is measured
iterations: int [defaults to 2]
Repeat the minimization to refine the result | [
"Adjust",
"frame",
"so",
"that",
"there",
"is",
"no",
"rotation",
"about",
"z",
"axis"
] | 7a323e81b391d6892e2874073e495e0beb057e85 | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/quaternion_time_series.py#L294-L332 |
231,432 | moble/quaternion | means.py | mean_rotor_in_chordal_metric | def mean_rotor_in_chordal_metric(R, t=None):
"""Return rotor that is closest to all R in the least-squares sense
This can be done (quasi-)analytically because of the simplicity of
the chordal metric function. The only approximation is the simple
2nd-order discrete formula for the definite integral of the input
rotor function.
Note that the `t` argument is optional. If it is present, the
times are used to weight the corresponding integral. If it is not
present, a simple sum is used instead (which may be slightly
faster).
"""
if not t:
return np.quaternion(*(np.sum(as_float_array(R)))).normalized()
mean = np.empty((4,), dtype=float)
definite_integral(as_float_array(R), t, mean)
return np.quaternion(*mean).normalized() | python | def mean_rotor_in_chordal_metric(R, t=None):
if not t:
return np.quaternion(*(np.sum(as_float_array(R)))).normalized()
mean = np.empty((4,), dtype=float)
definite_integral(as_float_array(R), t, mean)
return np.quaternion(*mean).normalized() | [
"def",
"mean_rotor_in_chordal_metric",
"(",
"R",
",",
"t",
"=",
"None",
")",
":",
"if",
"not",
"t",
":",
"return",
"np",
".",
"quaternion",
"(",
"*",
"(",
"np",
".",
"sum",
"(",
"as_float_array",
"(",
"R",
")",
")",
")",
")",
".",
"normalized",
"("... | Return rotor that is closest to all R in the least-squares sense
This can be done (quasi-)analytically because of the simplicity of
the chordal metric function. The only approximation is the simple
2nd-order discrete formula for the definite integral of the input
rotor function.
Note that the `t` argument is optional. If it is present, the
times are used to weight the corresponding integral. If it is not
present, a simple sum is used instead (which may be slightly
faster). | [
"Return",
"rotor",
"that",
"is",
"closest",
"to",
"all",
"R",
"in",
"the",
"least",
"-",
"squares",
"sense"
] | 7a323e81b391d6892e2874073e495e0beb057e85 | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/means.py#L11-L29 |
231,433 | moble/quaternion | __init__.py | as_float_array | def as_float_array(a):
"""View the quaternion array as an array of floats
This function is fast (of order 1 microsecond) because no data is
copied; the returned quantity is just a "view" of the original.
The output view has one more dimension (of size 4) than the input
array, but is otherwise the same shape.
"""
return np.asarray(a, dtype=np.quaternion).view((np.double, 4)) | python | def as_float_array(a):
return np.asarray(a, dtype=np.quaternion).view((np.double, 4)) | [
"def",
"as_float_array",
"(",
"a",
")",
":",
"return",
"np",
".",
"asarray",
"(",
"a",
",",
"dtype",
"=",
"np",
".",
"quaternion",
")",
".",
"view",
"(",
"(",
"np",
".",
"double",
",",
"4",
")",
")"
] | View the quaternion array as an array of floats
This function is fast (of order 1 microsecond) because no data is
copied; the returned quantity is just a "view" of the original.
The output view has one more dimension (of size 4) than the input
array, but is otherwise the same shape. | [
"View",
"the",
"quaternion",
"array",
"as",
"an",
"array",
"of",
"floats"
] | 7a323e81b391d6892e2874073e495e0beb057e85 | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L53-L63 |
231,434 | moble/quaternion | __init__.py | as_quat_array | def as_quat_array(a):
"""View a float array as an array of quaternions
The input array must have a final dimension whose size is
divisible by four (or better yet *is* 4), because successive
indices in that last dimension will be considered successive
components of the output quaternion.
This function is usually fast (of order 1 microsecond) because no
data is copied; the returned quantity is just a "view" of the
original. However, if the input array is not C-contiguous
(basically, as you increment the index into the last dimension of
the array, you just move to the neighboring float in memory), the
data will need to be copied which may be quite slow. Therefore,
you should try to ensure that the input array is in that order.
Slices and transpositions will frequently break that rule.
We will not convert back from a two-spinor array because there is
no unique convention for them, so I don't want to mess with that.
Also, we want to discourage users from the slow, memory-copying
process of swapping columns required for useful definitions of
the two-spinors.
"""
a = np.asarray(a, dtype=np.double)
# fast path
if a.shape == (4,):
return quaternion(a[0], a[1], a[2], a[3])
# view only works if the last axis is C-contiguous
if not a.flags['C_CONTIGUOUS'] or a.strides[-1] != a.itemsize:
a = a.copy(order='C')
try:
av = a.view(np.quaternion)
except ValueError as e:
message = (str(e) + '\n '
+ 'Failed to view input data as a series of quaternions. '
+ 'Please ensure that the last dimension has size divisible by 4.\n '
+ 'Input data has shape {0} and dtype {1}.'.format(a.shape, a.dtype))
raise ValueError(message)
# special case: don't create an axis for a single quaternion, to
# match the output of `as_float_array`
if av.shape[-1] == 1:
av = av.reshape(a.shape[:-1])
return av | python | def as_quat_array(a):
a = np.asarray(a, dtype=np.double)
# fast path
if a.shape == (4,):
return quaternion(a[0], a[1], a[2], a[3])
# view only works if the last axis is C-contiguous
if not a.flags['C_CONTIGUOUS'] or a.strides[-1] != a.itemsize:
a = a.copy(order='C')
try:
av = a.view(np.quaternion)
except ValueError as e:
message = (str(e) + '\n '
+ 'Failed to view input data as a series of quaternions. '
+ 'Please ensure that the last dimension has size divisible by 4.\n '
+ 'Input data has shape {0} and dtype {1}.'.format(a.shape, a.dtype))
raise ValueError(message)
# special case: don't create an axis for a single quaternion, to
# match the output of `as_float_array`
if av.shape[-1] == 1:
av = av.reshape(a.shape[:-1])
return av | [
"def",
"as_quat_array",
"(",
"a",
")",
":",
"a",
"=",
"np",
".",
"asarray",
"(",
"a",
",",
"dtype",
"=",
"np",
".",
"double",
")",
"# fast path",
"if",
"a",
".",
"shape",
"==",
"(",
"4",
",",
")",
":",
"return",
"quaternion",
"(",
"a",
"[",
"0"... | View a float array as an array of quaternions
The input array must have a final dimension whose size is
divisible by four (or better yet *is* 4), because successive
indices in that last dimension will be considered successive
components of the output quaternion.
This function is usually fast (of order 1 microsecond) because no
data is copied; the returned quantity is just a "view" of the
original. However, if the input array is not C-contiguous
(basically, as you increment the index into the last dimension of
the array, you just move to the neighboring float in memory), the
data will need to be copied which may be quite slow. Therefore,
you should try to ensure that the input array is in that order.
Slices and transpositions will frequently break that rule.
We will not convert back from a two-spinor array because there is
no unique convention for them, so I don't want to mess with that.
Also, we want to discourage users from the slow, memory-copying
process of swapping columns required for useful definitions of
the two-spinors. | [
"View",
"a",
"float",
"array",
"as",
"an",
"array",
"of",
"quaternions"
] | 7a323e81b391d6892e2874073e495e0beb057e85 | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L66-L113 |
231,435 | moble/quaternion | __init__.py | as_spinor_array | def as_spinor_array(a):
"""View a quaternion array as spinors in two-complex representation
This function is relatively slow and scales poorly, because memory
copying is apparently involved -- I think it's due to the
"advanced indexing" required to swap the columns.
"""
a = np.atleast_1d(a)
assert a.dtype == np.dtype(np.quaternion)
# I'm not sure why it has to be so complicated, but all of these steps
# appear to be necessary in this case.
return a.view(np.float).reshape(a.shape + (4,))[..., [0, 3, 2, 1]].ravel().view(np.complex).reshape(a.shape + (2,)) | python | def as_spinor_array(a):
a = np.atleast_1d(a)
assert a.dtype == np.dtype(np.quaternion)
# I'm not sure why it has to be so complicated, but all of these steps
# appear to be necessary in this case.
return a.view(np.float).reshape(a.shape + (4,))[..., [0, 3, 2, 1]].ravel().view(np.complex).reshape(a.shape + (2,)) | [
"def",
"as_spinor_array",
"(",
"a",
")",
":",
"a",
"=",
"np",
".",
"atleast_1d",
"(",
"a",
")",
"assert",
"a",
".",
"dtype",
"==",
"np",
".",
"dtype",
"(",
"np",
".",
"quaternion",
")",
"# I'm not sure why it has to be so complicated, but all of these steps",
... | View a quaternion array as spinors in two-complex representation
This function is relatively slow and scales poorly, because memory
copying is apparently involved -- I think it's due to the
"advanced indexing" required to swap the columns. | [
"View",
"a",
"quaternion",
"array",
"as",
"spinors",
"in",
"two",
"-",
"complex",
"representation"
] | 7a323e81b391d6892e2874073e495e0beb057e85 | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L120-L132 |
231,436 | moble/quaternion | __init__.py | from_rotation_vector | def from_rotation_vector(rot):
"""Convert input 3-vector in axis-angle representation to unit quaternion
Parameters
----------
rot: (Nx3) float array
Each vector represents the axis of the rotation, with norm
proportional to the angle of the rotation in radians.
Returns
-------
q: array of quaternions
Unit quaternions resulting in rotations corresponding to input
rotations. Output shape is rot.shape[:-1].
"""
rot = np.array(rot, copy=False)
quats = np.zeros(rot.shape[:-1]+(4,))
quats[..., 1:] = rot[...]/2
quats = as_quat_array(quats)
return np.exp(quats) | python | def from_rotation_vector(rot):
rot = np.array(rot, copy=False)
quats = np.zeros(rot.shape[:-1]+(4,))
quats[..., 1:] = rot[...]/2
quats = as_quat_array(quats)
return np.exp(quats) | [
"def",
"from_rotation_vector",
"(",
"rot",
")",
":",
"rot",
"=",
"np",
".",
"array",
"(",
"rot",
",",
"copy",
"=",
"False",
")",
"quats",
"=",
"np",
".",
"zeros",
"(",
"rot",
".",
"shape",
"[",
":",
"-",
"1",
"]",
"+",
"(",
"4",
",",
")",
")"... | Convert input 3-vector in axis-angle representation to unit quaternion
Parameters
----------
rot: (Nx3) float array
Each vector represents the axis of the rotation, with norm
proportional to the angle of the rotation in radians.
Returns
-------
q: array of quaternions
Unit quaternions resulting in rotations corresponding to input
rotations. Output shape is rot.shape[:-1]. | [
"Convert",
"input",
"3",
"-",
"vector",
"in",
"axis",
"-",
"angle",
"representation",
"to",
"unit",
"quaternion"
] | 7a323e81b391d6892e2874073e495e0beb057e85 | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L351-L371 |
231,437 | moble/quaternion | __init__.py | as_euler_angles | def as_euler_angles(q):
"""Open Pandora's Box
If somebody is trying to make you use Euler angles, tell them no, and
walk away, and go and tell your mum.
You don't want to use Euler angles. They are awful. Stay away. It's
one thing to convert from Euler angles to quaternions; at least you're
moving in the right direction. But to go the other way?! It's just not
right.
Assumes the Euler angles correspond to the quaternion R via
R = exp(alpha*z/2) * exp(beta*y/2) * exp(gamma*z/2)
The angles are naturally in radians.
NOTE: Before opening an issue reporting something "wrong" with this
function, be sure to read all of the following page, *especially* the
very last section about opening issues or pull requests.
<https://github.com/moble/quaternion/wiki/Euler-angles-are-horrible>
Parameters
----------
q: quaternion or array of quaternions
The quaternion(s) need not be normalized, but must all be nonzero
Returns
-------
alpha_beta_gamma: float array
Output shape is q.shape+(3,). These represent the angles (alpha,
beta, gamma) in radians, where the normalized input quaternion
represents `exp(alpha*z/2) * exp(beta*y/2) * exp(gamma*z/2)`.
Raises
------
AllHell
...if you try to actually use Euler angles, when you could have
been using quaternions like a sensible person.
"""
alpha_beta_gamma = np.empty(q.shape + (3,), dtype=np.float)
n = np.norm(q)
q = as_float_array(q)
alpha_beta_gamma[..., 0] = np.arctan2(q[..., 3], q[..., 0]) + np.arctan2(-q[..., 1], q[..., 2])
alpha_beta_gamma[..., 1] = 2*np.arccos(np.sqrt((q[..., 0]**2 + q[..., 3]**2)/n))
alpha_beta_gamma[..., 2] = np.arctan2(q[..., 3], q[..., 0]) - np.arctan2(-q[..., 1], q[..., 2])
return alpha_beta_gamma | python | def as_euler_angles(q):
alpha_beta_gamma = np.empty(q.shape + (3,), dtype=np.float)
n = np.norm(q)
q = as_float_array(q)
alpha_beta_gamma[..., 0] = np.arctan2(q[..., 3], q[..., 0]) + np.arctan2(-q[..., 1], q[..., 2])
alpha_beta_gamma[..., 1] = 2*np.arccos(np.sqrt((q[..., 0]**2 + q[..., 3]**2)/n))
alpha_beta_gamma[..., 2] = np.arctan2(q[..., 3], q[..., 0]) - np.arctan2(-q[..., 1], q[..., 2])
return alpha_beta_gamma | [
"def",
"as_euler_angles",
"(",
"q",
")",
":",
"alpha_beta_gamma",
"=",
"np",
".",
"empty",
"(",
"q",
".",
"shape",
"+",
"(",
"3",
",",
")",
",",
"dtype",
"=",
"np",
".",
"float",
")",
"n",
"=",
"np",
".",
"norm",
"(",
"q",
")",
"q",
"=",
"as_... | Open Pandora's Box
If somebody is trying to make you use Euler angles, tell them no, and
walk away, and go and tell your mum.
You don't want to use Euler angles. They are awful. Stay away. It's
one thing to convert from Euler angles to quaternions; at least you're
moving in the right direction. But to go the other way?! It's just not
right.
Assumes the Euler angles correspond to the quaternion R via
R = exp(alpha*z/2) * exp(beta*y/2) * exp(gamma*z/2)
The angles are naturally in radians.
NOTE: Before opening an issue reporting something "wrong" with this
function, be sure to read all of the following page, *especially* the
very last section about opening issues or pull requests.
<https://github.com/moble/quaternion/wiki/Euler-angles-are-horrible>
Parameters
----------
q: quaternion or array of quaternions
The quaternion(s) need not be normalized, but must all be nonzero
Returns
-------
alpha_beta_gamma: float array
Output shape is q.shape+(3,). These represent the angles (alpha,
beta, gamma) in radians, where the normalized input quaternion
represents `exp(alpha*z/2) * exp(beta*y/2) * exp(gamma*z/2)`.
Raises
------
AllHell
...if you try to actually use Euler angles, when you could have
been using quaternions like a sensible person. | [
"Open",
"Pandora",
"s",
"Box"
] | 7a323e81b391d6892e2874073e495e0beb057e85 | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L374-L421 |
231,438 | moble/quaternion | __init__.py | from_euler_angles | def from_euler_angles(alpha_beta_gamma, beta=None, gamma=None):
"""Improve your life drastically
Assumes the Euler angles correspond to the quaternion R via
R = exp(alpha*z/2) * exp(beta*y/2) * exp(gamma*z/2)
The angles naturally must be in radians for this to make any sense.
NOTE: Before opening an issue reporting something "wrong" with this
function, be sure to read all of the following page, *especially* the
very last section about opening issues or pull requests.
<https://github.com/moble/quaternion/wiki/Euler-angles-are-horrible>
Parameters
----------
alpha_beta_gamma: float or array of floats
This argument may either contain an array with last dimension of
size 3, where those three elements describe the (alpha, beta, gamma)
radian values for each rotation; or it may contain just the alpha
values, in which case the next two arguments must also be given.
beta: None, float, or array of floats
If this array is given, it must be able to broadcast against the
first and third arguments.
gamma: None, float, or array of floats
If this array is given, it must be able to broadcast against the
first and second arguments.
Returns
-------
R: quaternion array
The shape of this array will be the same as the input, except that
the last dimension will be removed.
"""
# Figure out the input angles from either type of input
if gamma is None:
alpha_beta_gamma = np.asarray(alpha_beta_gamma, dtype=np.double)
alpha = alpha_beta_gamma[..., 0]
beta = alpha_beta_gamma[..., 1]
gamma = alpha_beta_gamma[..., 2]
else:
alpha = np.asarray(alpha_beta_gamma, dtype=np.double)
beta = np.asarray(beta, dtype=np.double)
gamma = np.asarray(gamma, dtype=np.double)
# Set up the output array
R = np.empty(np.broadcast(alpha, beta, gamma).shape + (4,), dtype=np.double)
# Compute the actual values of the quaternion components
R[..., 0] = np.cos(beta/2)*np.cos((alpha+gamma)/2) # scalar quaternion components
R[..., 1] = -np.sin(beta/2)*np.sin((alpha-gamma)/2) # x quaternion components
R[..., 2] = np.sin(beta/2)*np.cos((alpha-gamma)/2) # y quaternion components
R[..., 3] = np.cos(beta/2)*np.sin((alpha+gamma)/2) # z quaternion components
return as_quat_array(R) | python | def from_euler_angles(alpha_beta_gamma, beta=None, gamma=None):
# Figure out the input angles from either type of input
if gamma is None:
alpha_beta_gamma = np.asarray(alpha_beta_gamma, dtype=np.double)
alpha = alpha_beta_gamma[..., 0]
beta = alpha_beta_gamma[..., 1]
gamma = alpha_beta_gamma[..., 2]
else:
alpha = np.asarray(alpha_beta_gamma, dtype=np.double)
beta = np.asarray(beta, dtype=np.double)
gamma = np.asarray(gamma, dtype=np.double)
# Set up the output array
R = np.empty(np.broadcast(alpha, beta, gamma).shape + (4,), dtype=np.double)
# Compute the actual values of the quaternion components
R[..., 0] = np.cos(beta/2)*np.cos((alpha+gamma)/2) # scalar quaternion components
R[..., 1] = -np.sin(beta/2)*np.sin((alpha-gamma)/2) # x quaternion components
R[..., 2] = np.sin(beta/2)*np.cos((alpha-gamma)/2) # y quaternion components
R[..., 3] = np.cos(beta/2)*np.sin((alpha+gamma)/2) # z quaternion components
return as_quat_array(R) | [
"def",
"from_euler_angles",
"(",
"alpha_beta_gamma",
",",
"beta",
"=",
"None",
",",
"gamma",
"=",
"None",
")",
":",
"# Figure out the input angles from either type of input",
"if",
"gamma",
"is",
"None",
":",
"alpha_beta_gamma",
"=",
"np",
".",
"asarray",
"(",
"al... | Improve your life drastically
Assumes the Euler angles correspond to the quaternion R via
R = exp(alpha*z/2) * exp(beta*y/2) * exp(gamma*z/2)
The angles naturally must be in radians for this to make any sense.
NOTE: Before opening an issue reporting something "wrong" with this
function, be sure to read all of the following page, *especially* the
very last section about opening issues or pull requests.
<https://github.com/moble/quaternion/wiki/Euler-angles-are-horrible>
Parameters
----------
alpha_beta_gamma: float or array of floats
This argument may either contain an array with last dimension of
size 3, where those three elements describe the (alpha, beta, gamma)
radian values for each rotation; or it may contain just the alpha
values, in which case the next two arguments must also be given.
beta: None, float, or array of floats
If this array is given, it must be able to broadcast against the
first and third arguments.
gamma: None, float, or array of floats
If this array is given, it must be able to broadcast against the
first and second arguments.
Returns
-------
R: quaternion array
The shape of this array will be the same as the input, except that
the last dimension will be removed. | [
"Improve",
"your",
"life",
"drastically"
] | 7a323e81b391d6892e2874073e495e0beb057e85 | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L424-L479 |
231,439 | moble/quaternion | __init__.py | from_spherical_coords | def from_spherical_coords(theta_phi, phi=None):
"""Return the quaternion corresponding to these spherical coordinates
Assumes the spherical coordinates correspond to the quaternion R via
R = exp(phi*z/2) * exp(theta*y/2)
The angles naturally must be in radians for this to make any sense.
Note that this quaternion rotates `z` onto the point with the given
spherical coordinates, but also rotates `x` and `y` onto the usual basis
vectors (theta and phi, respectively) at that point.
Parameters
----------
theta_phi: float or array of floats
This argument may either contain an array with last dimension of
size 2, where those two elements describe the (theta, phi) values in
radians for each point; or it may contain just the theta values in
radians, in which case the next argument must also be given.
phi: None, float, or array of floats
If this array is given, it must be able to broadcast against the
first argument.
Returns
-------
R: quaternion array
If the second argument is not given to this function, the shape
will be the same as the input shape except for the last dimension,
which will be removed. If the second argument is given, this
output array will have the shape resulting from broadcasting the
two input arrays against each other.
"""
# Figure out the input angles from either type of input
if phi is None:
theta_phi = np.asarray(theta_phi, dtype=np.double)
theta = theta_phi[..., 0]
phi = theta_phi[..., 1]
else:
theta = np.asarray(theta_phi, dtype=np.double)
phi = np.asarray(phi, dtype=np.double)
# Set up the output array
R = np.empty(np.broadcast(theta, phi).shape + (4,), dtype=np.double)
# Compute the actual values of the quaternion components
R[..., 0] = np.cos(phi/2)*np.cos(theta/2) # scalar quaternion components
R[..., 1] = -np.sin(phi/2)*np.sin(theta/2) # x quaternion components
R[..., 2] = np.cos(phi/2)*np.sin(theta/2) # y quaternion components
R[..., 3] = np.sin(phi/2)*np.cos(theta/2) # z quaternion components
return as_quat_array(R) | python | def from_spherical_coords(theta_phi, phi=None):
# Figure out the input angles from either type of input
if phi is None:
theta_phi = np.asarray(theta_phi, dtype=np.double)
theta = theta_phi[..., 0]
phi = theta_phi[..., 1]
else:
theta = np.asarray(theta_phi, dtype=np.double)
phi = np.asarray(phi, dtype=np.double)
# Set up the output array
R = np.empty(np.broadcast(theta, phi).shape + (4,), dtype=np.double)
# Compute the actual values of the quaternion components
R[..., 0] = np.cos(phi/2)*np.cos(theta/2) # scalar quaternion components
R[..., 1] = -np.sin(phi/2)*np.sin(theta/2) # x quaternion components
R[..., 2] = np.cos(phi/2)*np.sin(theta/2) # y quaternion components
R[..., 3] = np.sin(phi/2)*np.cos(theta/2) # z quaternion components
return as_quat_array(R) | [
"def",
"from_spherical_coords",
"(",
"theta_phi",
",",
"phi",
"=",
"None",
")",
":",
"# Figure out the input angles from either type of input",
"if",
"phi",
"is",
"None",
":",
"theta_phi",
"=",
"np",
".",
"asarray",
"(",
"theta_phi",
",",
"dtype",
"=",
"np",
"."... | Return the quaternion corresponding to these spherical coordinates
Assumes the spherical coordinates correspond to the quaternion R via
R = exp(phi*z/2) * exp(theta*y/2)
The angles naturally must be in radians for this to make any sense.
Note that this quaternion rotates `z` onto the point with the given
spherical coordinates, but also rotates `x` and `y` onto the usual basis
vectors (theta and phi, respectively) at that point.
Parameters
----------
theta_phi: float or array of floats
This argument may either contain an array with last dimension of
size 2, where those two elements describe the (theta, phi) values in
radians for each point; or it may contain just the theta values in
radians, in which case the next argument must also be given.
phi: None, float, or array of floats
If this array is given, it must be able to broadcast against the
first argument.
Returns
-------
R: quaternion array
If the second argument is not given to this function, the shape
will be the same as the input shape except for the last dimension,
which will be removed. If the second argument is given, this
output array will have the shape resulting from broadcasting the
two input arrays against each other. | [
"Return",
"the",
"quaternion",
"corresponding",
"to",
"these",
"spherical",
"coordinates"
] | 7a323e81b391d6892e2874073e495e0beb057e85 | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L507-L559 |
231,440 | moble/quaternion | __init__.py | rotate_vectors | def rotate_vectors(R, v, axis=-1):
"""Rotate vectors by given quaternions
For simplicity, this function simply converts the input
quaternion(s) to a matrix, and rotates the input vector(s) by the
usual matrix multiplication. However, it should be noted that if
each input quaternion is only used to rotate a single vector, it
is more efficient (in terms of operation counts) to use the
formula
v' = v + 2 * r x (s * v + r x v) / m
where x represents the cross product, s and r are the scalar and
vector parts of the quaternion, respectively, and m is the sum of
the squares of the components of the quaternion. If you are
looping over a very large number of quaternions, and just rotating
a single vector each time, you might want to implement that
alternative algorithm using numba (or something that doesn't use
python).
Parameters
==========
R: quaternion array
Quaternions by which to rotate the input vectors
v: float array
Three-vectors to be rotated.
axis: int
Axis of the `v` array to use as the vector dimension. This
axis of `v` must have length 3.
Returns
=======
vprime: float array
The rotated vectors. This array has shape R.shape+v.shape.
"""
R = np.asarray(R, dtype=np.quaternion)
v = np.asarray(v, dtype=float)
if v.ndim < 1 or 3 not in v.shape:
raise ValueError("Input `v` does not have at least one dimension of length 3")
if v.shape[axis] != 3:
raise ValueError("Input `v` axis {0} has length {1}, not 3.".format(axis, v.shape[axis]))
m = as_rotation_matrix(R)
m_axes = list(range(m.ndim))
v_axes = list(range(m.ndim, m.ndim+v.ndim))
mv_axes = list(v_axes)
mv_axes[axis] = m_axes[-2]
mv_axes = m_axes[:-2] + mv_axes
v_axes[axis] = m_axes[-1]
return np.einsum(m, m_axes, v, v_axes, mv_axes) | python | def rotate_vectors(R, v, axis=-1):
R = np.asarray(R, dtype=np.quaternion)
v = np.asarray(v, dtype=float)
if v.ndim < 1 or 3 not in v.shape:
raise ValueError("Input `v` does not have at least one dimension of length 3")
if v.shape[axis] != 3:
raise ValueError("Input `v` axis {0} has length {1}, not 3.".format(axis, v.shape[axis]))
m = as_rotation_matrix(R)
m_axes = list(range(m.ndim))
v_axes = list(range(m.ndim, m.ndim+v.ndim))
mv_axes = list(v_axes)
mv_axes[axis] = m_axes[-2]
mv_axes = m_axes[:-2] + mv_axes
v_axes[axis] = m_axes[-1]
return np.einsum(m, m_axes, v, v_axes, mv_axes) | [
"def",
"rotate_vectors",
"(",
"R",
",",
"v",
",",
"axis",
"=",
"-",
"1",
")",
":",
"R",
"=",
"np",
".",
"asarray",
"(",
"R",
",",
"dtype",
"=",
"np",
".",
"quaternion",
")",
"v",
"=",
"np",
".",
"asarray",
"(",
"v",
",",
"dtype",
"=",
"float"... | Rotate vectors by given quaternions
For simplicity, this function simply converts the input
quaternion(s) to a matrix, and rotates the input vector(s) by the
usual matrix multiplication. However, it should be noted that if
each input quaternion is only used to rotate a single vector, it
is more efficient (in terms of operation counts) to use the
formula
v' = v + 2 * r x (s * v + r x v) / m
where x represents the cross product, s and r are the scalar and
vector parts of the quaternion, respectively, and m is the sum of
the squares of the components of the quaternion. If you are
looping over a very large number of quaternions, and just rotating
a single vector each time, you might want to implement that
alternative algorithm using numba (or something that doesn't use
python).
Parameters
==========
R: quaternion array
Quaternions by which to rotate the input vectors
v: float array
Three-vectors to be rotated.
axis: int
Axis of the `v` array to use as the vector dimension. This
axis of `v` must have length 3.
Returns
=======
vprime: float array
The rotated vectors. This array has shape R.shape+v.shape. | [
"Rotate",
"vectors",
"by",
"given",
"quaternions"
] | 7a323e81b391d6892e2874073e495e0beb057e85 | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L562-L612 |
231,441 | moble/quaternion | __init__.py | isclose | def isclose(a, b, rtol=4*np.finfo(float).eps, atol=0.0, equal_nan=False):
"""
Returns a boolean array where two arrays are element-wise equal within a
tolerance.
This function is essentially a copy of the `numpy.isclose` function,
with different default tolerances and one minor changes necessary to
deal correctly with quaternions.
The tolerance values are positive, typically very small numbers. The
relative difference (`rtol` * abs(`b`)) and the absolute difference
`atol` are added together to compare against the absolute difference
between `a` and `b`.
Parameters
----------
a, b : array_like
Input arrays to compare.
rtol : float
The relative tolerance parameter (see Notes).
atol : float
The absolute tolerance parameter (see Notes).
equal_nan : bool
Whether to compare NaN's as equal. If True, NaN's in `a` will be
considered equal to NaN's in `b` in the output array.
Returns
-------
y : array_like
Returns a boolean array of where `a` and `b` are equal within the
given tolerance. If both `a` and `b` are scalars, returns a single
boolean value.
See Also
--------
allclose
Notes
-----
For finite values, isclose uses the following equation to test whether
two floating point values are equivalent:
absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
The above equation is not symmetric in `a` and `b`, so that
`isclose(a, b)` might be different from `isclose(b, a)` in
some rare cases.
Examples
--------
>>> quaternion.isclose([1e10*quaternion.x, 1e-7*quaternion.y], [1.00001e10*quaternion.x, 1e-8*quaternion.y],
... rtol=1.e-5, atol=1.e-8)
array([True, False])
>>> quaternion.isclose([1e10*quaternion.x, 1e-8*quaternion.y], [1.00001e10*quaternion.x, 1e-9*quaternion.y],
... rtol=1.e-5, atol=1.e-8)
array([True, True])
>>> quaternion.isclose([1e10*quaternion.x, 1e-8*quaternion.y], [1.0001e10*quaternion.x, 1e-9*quaternion.y],
... rtol=1.e-5, atol=1.e-8)
array([False, True])
>>> quaternion.isclose([quaternion.x, np.nan*quaternion.y], [quaternion.x, np.nan*quaternion.y])
array([True, False])
>>> quaternion.isclose([quaternion.x, np.nan*quaternion.y], [quaternion.x, np.nan*quaternion.y], equal_nan=True)
array([True, True])
"""
def within_tol(x, y, atol, rtol):
with np.errstate(invalid='ignore'):
result = np.less_equal(abs(x-y), atol + rtol * abs(y))
if np.isscalar(a) and np.isscalar(b):
result = bool(result)
return result
x = np.array(a, copy=False, subok=True, ndmin=1)
y = np.array(b, copy=False, subok=True, ndmin=1)
# Make sure y is an inexact type to avoid bad behavior on abs(MIN_INT).
# This will cause casting of x later. Also, make sure to allow subclasses
# (e.g., for numpy.ma).
try:
dt = np.result_type(y, 1.)
except TypeError:
dt = np.dtype(np.quaternion)
y = np.array(y, dtype=dt, copy=False, subok=True)
xfin = np.isfinite(x)
yfin = np.isfinite(y)
if np.all(xfin) and np.all(yfin):
return within_tol(x, y, atol, rtol)
else:
finite = xfin & yfin
cond = np.zeros_like(finite, subok=True)
# Because we're using boolean indexing, x & y must be the same shape.
# Ideally, we'd just do x, y = broadcast_arrays(x, y). It's in
# lib.stride_tricks, though, so we can't import it here.
x = x * np.ones_like(cond)
y = y * np.ones_like(cond)
# Avoid subtraction with infinite/nan values...
cond[finite] = within_tol(x[finite], y[finite], atol, rtol)
# Check for equality of infinite values...
cond[~finite] = (x[~finite] == y[~finite])
if equal_nan:
# Make NaN == NaN
both_nan = np.isnan(x) & np.isnan(y)
cond[both_nan] = both_nan[both_nan]
if np.isscalar(a) and np.isscalar(b):
return bool(cond)
else:
return cond | python | def isclose(a, b, rtol=4*np.finfo(float).eps, atol=0.0, equal_nan=False):
def within_tol(x, y, atol, rtol):
with np.errstate(invalid='ignore'):
result = np.less_equal(abs(x-y), atol + rtol * abs(y))
if np.isscalar(a) and np.isscalar(b):
result = bool(result)
return result
x = np.array(a, copy=False, subok=True, ndmin=1)
y = np.array(b, copy=False, subok=True, ndmin=1)
# Make sure y is an inexact type to avoid bad behavior on abs(MIN_INT).
# This will cause casting of x later. Also, make sure to allow subclasses
# (e.g., for numpy.ma).
try:
dt = np.result_type(y, 1.)
except TypeError:
dt = np.dtype(np.quaternion)
y = np.array(y, dtype=dt, copy=False, subok=True)
xfin = np.isfinite(x)
yfin = np.isfinite(y)
if np.all(xfin) and np.all(yfin):
return within_tol(x, y, atol, rtol)
else:
finite = xfin & yfin
cond = np.zeros_like(finite, subok=True)
# Because we're using boolean indexing, x & y must be the same shape.
# Ideally, we'd just do x, y = broadcast_arrays(x, y). It's in
# lib.stride_tricks, though, so we can't import it here.
x = x * np.ones_like(cond)
y = y * np.ones_like(cond)
# Avoid subtraction with infinite/nan values...
cond[finite] = within_tol(x[finite], y[finite], atol, rtol)
# Check for equality of infinite values...
cond[~finite] = (x[~finite] == y[~finite])
if equal_nan:
# Make NaN == NaN
both_nan = np.isnan(x) & np.isnan(y)
cond[both_nan] = both_nan[both_nan]
if np.isscalar(a) and np.isscalar(b):
return bool(cond)
else:
return cond | [
"def",
"isclose",
"(",
"a",
",",
"b",
",",
"rtol",
"=",
"4",
"*",
"np",
".",
"finfo",
"(",
"float",
")",
".",
"eps",
",",
"atol",
"=",
"0.0",
",",
"equal_nan",
"=",
"False",
")",
":",
"def",
"within_tol",
"(",
"x",
",",
"y",
",",
"atol",
",",... | Returns a boolean array where two arrays are element-wise equal within a
tolerance.
This function is essentially a copy of the `numpy.isclose` function,
with different default tolerances and one minor changes necessary to
deal correctly with quaternions.
The tolerance values are positive, typically very small numbers. The
relative difference (`rtol` * abs(`b`)) and the absolute difference
`atol` are added together to compare against the absolute difference
between `a` and `b`.
Parameters
----------
a, b : array_like
Input arrays to compare.
rtol : float
The relative tolerance parameter (see Notes).
atol : float
The absolute tolerance parameter (see Notes).
equal_nan : bool
Whether to compare NaN's as equal. If True, NaN's in `a` will be
considered equal to NaN's in `b` in the output array.
Returns
-------
y : array_like
Returns a boolean array of where `a` and `b` are equal within the
given tolerance. If both `a` and `b` are scalars, returns a single
boolean value.
See Also
--------
allclose
Notes
-----
For finite values, isclose uses the following equation to test whether
two floating point values are equivalent:
absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
The above equation is not symmetric in `a` and `b`, so that
`isclose(a, b)` might be different from `isclose(b, a)` in
some rare cases.
Examples
--------
>>> quaternion.isclose([1e10*quaternion.x, 1e-7*quaternion.y], [1.00001e10*quaternion.x, 1e-8*quaternion.y],
... rtol=1.e-5, atol=1.e-8)
array([True, False])
>>> quaternion.isclose([1e10*quaternion.x, 1e-8*quaternion.y], [1.00001e10*quaternion.x, 1e-9*quaternion.y],
... rtol=1.e-5, atol=1.e-8)
array([True, True])
>>> quaternion.isclose([1e10*quaternion.x, 1e-8*quaternion.y], [1.0001e10*quaternion.x, 1e-9*quaternion.y],
... rtol=1.e-5, atol=1.e-8)
array([False, True])
>>> quaternion.isclose([quaternion.x, np.nan*quaternion.y], [quaternion.x, np.nan*quaternion.y])
array([True, False])
>>> quaternion.isclose([quaternion.x, np.nan*quaternion.y], [quaternion.x, np.nan*quaternion.y], equal_nan=True)
array([True, True]) | [
"Returns",
"a",
"boolean",
"array",
"where",
"two",
"arrays",
"are",
"element",
"-",
"wise",
"equal",
"within",
"a",
"tolerance",
"."
] | 7a323e81b391d6892e2874073e495e0beb057e85 | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L615-L722 |
231,442 | moble/quaternion | __init__.py | allclose | def allclose(a, b, rtol=4*np.finfo(float).eps, atol=0.0, equal_nan=False, verbose=False):
"""
Returns True if two arrays are element-wise equal within a tolerance.
This function is essentially a wrapper for the `quaternion.isclose`
function, but returns a single boolean value of True if all elements
of the output from `quaternion.isclose` are True, and False otherwise.
This function also adds the option.
Note that this function has stricter tolerances than the
`numpy.allclose` function, as well as the additional `verbose` option.
Parameters
----------
a, b : array_like
Input arrays to compare.
rtol : float
The relative tolerance parameter (see Notes).
atol : float
The absolute tolerance parameter (see Notes).
equal_nan : bool
Whether to compare NaN's as equal. If True, NaN's in `a` will be
considered equal to NaN's in `b` in the output array.
verbose : bool
If the return value is False,
Returns
-------
allclose : bool
Returns True if the two arrays are equal within the given
tolerance; False otherwise.
See Also
--------
isclose, numpy.all, numpy.any, numpy.allclose
Returns
-------
allclose : bool
Returns True if the two arrays are equal within the given
tolerance; False otherwise.
Notes
-----
If the following equation is element-wise True, then allclose returns
True.
absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
The above equation is not symmetric in `a` and `b`, so that
`allclose(a, b)` might be different from `allclose(b, a)` in
some rare cases.
"""
close = isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
result = np.all(close)
if verbose and not result:
print('Non-close values:')
for i in np.argwhere(close == False):
i = tuple(i)
print('\n x[{0}]={1}\n y[{0}]={2}'.format(i, a[i], b[i]))
return result | python | def allclose(a, b, rtol=4*np.finfo(float).eps, atol=0.0, equal_nan=False, verbose=False):
close = isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
result = np.all(close)
if verbose and not result:
print('Non-close values:')
for i in np.argwhere(close == False):
i = tuple(i)
print('\n x[{0}]={1}\n y[{0}]={2}'.format(i, a[i], b[i]))
return result | [
"def",
"allclose",
"(",
"a",
",",
"b",
",",
"rtol",
"=",
"4",
"*",
"np",
".",
"finfo",
"(",
"float",
")",
".",
"eps",
",",
"atol",
"=",
"0.0",
",",
"equal_nan",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"close",
"=",
"isclose",
"(",... | Returns True if two arrays are element-wise equal within a tolerance.
This function is essentially a wrapper for the `quaternion.isclose`
function, but returns a single boolean value of True if all elements
of the output from `quaternion.isclose` are True, and False otherwise.
This function also adds the option.
Note that this function has stricter tolerances than the
`numpy.allclose` function, as well as the additional `verbose` option.
Parameters
----------
a, b : array_like
Input arrays to compare.
rtol : float
The relative tolerance parameter (see Notes).
atol : float
The absolute tolerance parameter (see Notes).
equal_nan : bool
Whether to compare NaN's as equal. If True, NaN's in `a` will be
considered equal to NaN's in `b` in the output array.
verbose : bool
If the return value is False,
Returns
-------
allclose : bool
Returns True if the two arrays are equal within the given
tolerance; False otherwise.
See Also
--------
isclose, numpy.all, numpy.any, numpy.allclose
Returns
-------
allclose : bool
Returns True if the two arrays are equal within the given
tolerance; False otherwise.
Notes
-----
If the following equation is element-wise True, then allclose returns
True.
absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
The above equation is not symmetric in `a` and `b`, so that
`allclose(a, b)` might be different from `allclose(b, a)` in
some rare cases. | [
"Returns",
"True",
"if",
"two",
"arrays",
"are",
"element",
"-",
"wise",
"equal",
"within",
"a",
"tolerance",
"."
] | 7a323e81b391d6892e2874073e495e0beb057e85 | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L725-L786 |
231,443 | moble/quaternion | calculus.py | derivative | def derivative(f, t):
"""Fourth-order finite-differencing with non-uniform time steps
The formula for this finite difference comes from Eq. (A 5b) of "Derivative formulas and errors for non-uniformly
spaced points" by M. K. Bowen and Ronald Smith. As explained in their Eqs. (B 9b) and (B 10b), this is a
fourth-order formula -- though that's a squishy concept with non-uniform time steps.
TODO: If there are fewer than five points, the function should revert to simpler (lower-order) formulas.
"""
dfdt = np.empty_like(f)
if (f.ndim == 1):
_derivative(f, t, dfdt)
elif (f.ndim == 2):
_derivative_2d(f, t, dfdt)
elif (f.ndim == 3):
_derivative_3d(f, t, dfdt)
else:
raise NotImplementedError("Taking derivatives of {0}-dimensional arrays is not yet implemented".format(f.ndim))
return dfdt | python | def derivative(f, t):
dfdt = np.empty_like(f)
if (f.ndim == 1):
_derivative(f, t, dfdt)
elif (f.ndim == 2):
_derivative_2d(f, t, dfdt)
elif (f.ndim == 3):
_derivative_3d(f, t, dfdt)
else:
raise NotImplementedError("Taking derivatives of {0}-dimensional arrays is not yet implemented".format(f.ndim))
return dfdt | [
"def",
"derivative",
"(",
"f",
",",
"t",
")",
":",
"dfdt",
"=",
"np",
".",
"empty_like",
"(",
"f",
")",
"if",
"(",
"f",
".",
"ndim",
"==",
"1",
")",
":",
"_derivative",
"(",
"f",
",",
"t",
",",
"dfdt",
")",
"elif",
"(",
"f",
".",
"ndim",
"=... | Fourth-order finite-differencing with non-uniform time steps
The formula for this finite difference comes from Eq. (A 5b) of "Derivative formulas and errors for non-uniformly
spaced points" by M. K. Bowen and Ronald Smith. As explained in their Eqs. (B 9b) and (B 10b), this is a
fourth-order formula -- though that's a squishy concept with non-uniform time steps.
TODO: If there are fewer than five points, the function should revert to simpler (lower-order) formulas. | [
"Fourth",
"-",
"order",
"finite",
"-",
"differencing",
"with",
"non",
"-",
"uniform",
"time",
"steps"
] | 7a323e81b391d6892e2874073e495e0beb057e85 | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/calculus.py#L9-L28 |
231,444 | deschler/django-modeltranslation | modeltranslation/models.py | autodiscover | def autodiscover():
"""
Auto-discover INSTALLED_APPS translation.py modules and fail silently when
not present. This forces an import on them to register.
Also import explicit modules.
"""
import os
import sys
import copy
from django.utils.module_loading import module_has_submodule
from modeltranslation.translator import translator
from modeltranslation.settings import TRANSLATION_FILES, DEBUG
from importlib import import_module
from django.apps import apps
mods = [(app_config.name, app_config.module) for app_config in apps.get_app_configs()]
for (app, mod) in mods:
# Attempt to import the app's translation module.
module = '%s.translation' % app
before_import_registry = copy.copy(translator._registry)
try:
import_module(module)
except:
# Reset the model registry to the state before the last import as
# this import will have to reoccur on the next request and this
# could raise NotRegistered and AlreadyRegistered exceptions
translator._registry = before_import_registry
# Decide whether to bubble up this error. If the app just
# doesn't have an translation module, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, 'translation'):
raise
for module in TRANSLATION_FILES:
import_module(module)
# In debug mode, print a list of registered models and pid to stdout.
# Note: Differing model order is fine, we don't rely on a particular
# order, as far as base classes are registered before subclasses.
if DEBUG:
try:
if sys.argv[1] in ('runserver', 'runserver_plus'):
models = translator.get_registered_models()
names = ', '.join(m.__name__ for m in models)
print('modeltranslation: Registered %d models for translation'
' (%s) [pid: %d].' % (len(models), names, os.getpid()))
except IndexError:
pass | python | def autodiscover():
import os
import sys
import copy
from django.utils.module_loading import module_has_submodule
from modeltranslation.translator import translator
from modeltranslation.settings import TRANSLATION_FILES, DEBUG
from importlib import import_module
from django.apps import apps
mods = [(app_config.name, app_config.module) for app_config in apps.get_app_configs()]
for (app, mod) in mods:
# Attempt to import the app's translation module.
module = '%s.translation' % app
before_import_registry = copy.copy(translator._registry)
try:
import_module(module)
except:
# Reset the model registry to the state before the last import as
# this import will have to reoccur on the next request and this
# could raise NotRegistered and AlreadyRegistered exceptions
translator._registry = before_import_registry
# Decide whether to bubble up this error. If the app just
# doesn't have an translation module, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, 'translation'):
raise
for module in TRANSLATION_FILES:
import_module(module)
# In debug mode, print a list of registered models and pid to stdout.
# Note: Differing model order is fine, we don't rely on a particular
# order, as far as base classes are registered before subclasses.
if DEBUG:
try:
if sys.argv[1] in ('runserver', 'runserver_plus'):
models = translator.get_registered_models()
names = ', '.join(m.__name__ for m in models)
print('modeltranslation: Registered %d models for translation'
' (%s) [pid: %d].' % (len(models), names, os.getpid()))
except IndexError:
pass | [
"def",
"autodiscover",
"(",
")",
":",
"import",
"os",
"import",
"sys",
"import",
"copy",
"from",
"django",
".",
"utils",
".",
"module_loading",
"import",
"module_has_submodule",
"from",
"modeltranslation",
".",
"translator",
"import",
"translator",
"from",
"modelt... | Auto-discover INSTALLED_APPS translation.py modules and fail silently when
not present. This forces an import on them to register.
Also import explicit modules. | [
"Auto",
"-",
"discover",
"INSTALLED_APPS",
"translation",
".",
"py",
"modules",
"and",
"fail",
"silently",
"when",
"not",
"present",
".",
"This",
"forces",
"an",
"import",
"on",
"them",
"to",
"register",
".",
"Also",
"import",
"explicit",
"modules",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/models.py#L4-L53 |
231,445 | deschler/django-modeltranslation | modeltranslation/utils.py | build_css_class | def build_css_class(localized_fieldname, prefix=''):
"""
Returns a css class based on ``localized_fieldname`` which is easily
splitable and capable of regionalized language codes.
Takes an optional ``prefix`` which is prepended to the returned string.
"""
bits = localized_fieldname.split('_')
css_class = ''
if len(bits) == 1:
css_class = str(localized_fieldname)
elif len(bits) == 2:
# Fieldname without underscore and short language code
# Examples:
# 'foo_de' --> 'foo-de',
# 'bar_en' --> 'bar-en'
css_class = '-'.join(bits)
elif len(bits) > 2:
# Try regionalized language code
# Examples:
# 'foo_es_ar' --> 'foo-es_ar',
# 'foo_bar_zh_tw' --> 'foo_bar-zh_tw'
css_class = _join_css_class(bits, 2)
if not css_class:
# Try short language code
# Examples:
# 'foo_bar_de' --> 'foo_bar-de',
# 'foo_bar_baz_de' --> 'foo_bar_baz-de'
css_class = _join_css_class(bits, 1)
return '%s-%s' % (prefix, css_class) if prefix else css_class | python | def build_css_class(localized_fieldname, prefix=''):
bits = localized_fieldname.split('_')
css_class = ''
if len(bits) == 1:
css_class = str(localized_fieldname)
elif len(bits) == 2:
# Fieldname without underscore and short language code
# Examples:
# 'foo_de' --> 'foo-de',
# 'bar_en' --> 'bar-en'
css_class = '-'.join(bits)
elif len(bits) > 2:
# Try regionalized language code
# Examples:
# 'foo_es_ar' --> 'foo-es_ar',
# 'foo_bar_zh_tw' --> 'foo_bar-zh_tw'
css_class = _join_css_class(bits, 2)
if not css_class:
# Try short language code
# Examples:
# 'foo_bar_de' --> 'foo_bar-de',
# 'foo_bar_baz_de' --> 'foo_bar_baz-de'
css_class = _join_css_class(bits, 1)
return '%s-%s' % (prefix, css_class) if prefix else css_class | [
"def",
"build_css_class",
"(",
"localized_fieldname",
",",
"prefix",
"=",
"''",
")",
":",
"bits",
"=",
"localized_fieldname",
".",
"split",
"(",
"'_'",
")",
"css_class",
"=",
"''",
"if",
"len",
"(",
"bits",
")",
"==",
"1",
":",
"css_class",
"=",
"str",
... | Returns a css class based on ``localized_fieldname`` which is easily
splitable and capable of regionalized language codes.
Takes an optional ``prefix`` which is prepended to the returned string. | [
"Returns",
"a",
"css",
"class",
"based",
"on",
"localized_fieldname",
"which",
"is",
"easily",
"splitable",
"and",
"capable",
"of",
"regionalized",
"language",
"codes",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/utils.py#L64-L93 |
231,446 | deschler/django-modeltranslation | modeltranslation/utils.py | unique | def unique(seq):
"""
Returns a generator yielding unique sequence members in order
A set by itself will return unique values without any regard for order.
>>> list(unique([1, 2, 3, 2, 2, 4, 1]))
[1, 2, 3, 4]
"""
seen = set()
return (x for x in seq if x not in seen and not seen.add(x)) | python | def unique(seq):
seen = set()
return (x for x in seq if x not in seen and not seen.add(x)) | [
"def",
"unique",
"(",
"seq",
")",
":",
"seen",
"=",
"set",
"(",
")",
"return",
"(",
"x",
"for",
"x",
"in",
"seq",
"if",
"x",
"not",
"in",
"seen",
"and",
"not",
"seen",
".",
"add",
"(",
"x",
")",
")"
] | Returns a generator yielding unique sequence members in order
A set by itself will return unique values without any regard for order.
>>> list(unique([1, 2, 3, 2, 2, 4, 1]))
[1, 2, 3, 4] | [
"Returns",
"a",
"generator",
"yielding",
"unique",
"sequence",
"members",
"in",
"order"
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/utils.py#L96-L106 |
231,447 | deschler/django-modeltranslation | modeltranslation/utils.py | resolution_order | def resolution_order(lang, override=None):
"""
Return order of languages which should be checked for parameter language.
First is always the parameter language, later are fallback languages.
Override parameter has priority over FALLBACK_LANGUAGES.
"""
if not settings.ENABLE_FALLBACKS:
return (lang,)
if override is None:
override = {}
fallback_for_lang = override.get(lang, settings.FALLBACK_LANGUAGES.get(lang, ()))
fallback_def = override.get('default', settings.FALLBACK_LANGUAGES['default'])
order = (lang,) + fallback_for_lang + fallback_def
return tuple(unique(order)) | python | def resolution_order(lang, override=None):
if not settings.ENABLE_FALLBACKS:
return (lang,)
if override is None:
override = {}
fallback_for_lang = override.get(lang, settings.FALLBACK_LANGUAGES.get(lang, ()))
fallback_def = override.get('default', settings.FALLBACK_LANGUAGES['default'])
order = (lang,) + fallback_for_lang + fallback_def
return tuple(unique(order)) | [
"def",
"resolution_order",
"(",
"lang",
",",
"override",
"=",
"None",
")",
":",
"if",
"not",
"settings",
".",
"ENABLE_FALLBACKS",
":",
"return",
"(",
"lang",
",",
")",
"if",
"override",
"is",
"None",
":",
"override",
"=",
"{",
"}",
"fallback_for_lang",
"... | Return order of languages which should be checked for parameter language.
First is always the parameter language, later are fallback languages.
Override parameter has priority over FALLBACK_LANGUAGES. | [
"Return",
"order",
"of",
"languages",
"which",
"should",
"be",
"checked",
"for",
"parameter",
"language",
".",
"First",
"is",
"always",
"the",
"parameter",
"language",
"later",
"are",
"fallback",
"languages",
".",
"Override",
"parameter",
"has",
"priority",
"ove... | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/utils.py#L109-L122 |
231,448 | deschler/django-modeltranslation | modeltranslation/utils.py | fallbacks | def fallbacks(enable=True):
"""
Temporarily switch all language fallbacks on or off.
Example:
with fallbacks(False):
lang_has_slug = bool(self.slug)
May be used to enable fallbacks just when they're needed saving on some
processing or check if there is a value for the current language (not
knowing the language)
"""
current_enable_fallbacks = settings.ENABLE_FALLBACKS
settings.ENABLE_FALLBACKS = enable
try:
yield
finally:
settings.ENABLE_FALLBACKS = current_enable_fallbacks | python | def fallbacks(enable=True):
current_enable_fallbacks = settings.ENABLE_FALLBACKS
settings.ENABLE_FALLBACKS = enable
try:
yield
finally:
settings.ENABLE_FALLBACKS = current_enable_fallbacks | [
"def",
"fallbacks",
"(",
"enable",
"=",
"True",
")",
":",
"current_enable_fallbacks",
"=",
"settings",
".",
"ENABLE_FALLBACKS",
"settings",
".",
"ENABLE_FALLBACKS",
"=",
"enable",
"try",
":",
"yield",
"finally",
":",
"settings",
".",
"ENABLE_FALLBACKS",
"=",
"cu... | Temporarily switch all language fallbacks on or off.
Example:
with fallbacks(False):
lang_has_slug = bool(self.slug)
May be used to enable fallbacks just when they're needed saving on some
processing or check if there is a value for the current language (not
knowing the language) | [
"Temporarily",
"switch",
"all",
"language",
"fallbacks",
"on",
"or",
"off",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/utils.py#L153-L171 |
231,449 | deschler/django-modeltranslation | modeltranslation/utils.py | parse_field | def parse_field(setting, field_name, default):
"""
Extract result from single-value or dict-type setting like fallback_values.
"""
if isinstance(setting, dict):
return setting.get(field_name, default)
else:
return setting | python | def parse_field(setting, field_name, default):
if isinstance(setting, dict):
return setting.get(field_name, default)
else:
return setting | [
"def",
"parse_field",
"(",
"setting",
",",
"field_name",
",",
"default",
")",
":",
"if",
"isinstance",
"(",
"setting",
",",
"dict",
")",
":",
"return",
"setting",
".",
"get",
"(",
"field_name",
",",
"default",
")",
"else",
":",
"return",
"setting"
] | Extract result from single-value or dict-type setting like fallback_values. | [
"Extract",
"result",
"from",
"single",
"-",
"value",
"or",
"dict",
"-",
"type",
"setting",
"like",
"fallback_values",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/utils.py#L174-L181 |
231,450 | deschler/django-modeltranslation | modeltranslation/manager.py | append_translated | def append_translated(model, fields):
"If translated field is encountered, add also all its translation fields."
fields = set(fields)
from modeltranslation.translator import translator
opts = translator.get_options_for_model(model)
for key, translated in opts.fields.items():
if key in fields:
fields = fields.union(f.name for f in translated)
return fields | python | def append_translated(model, fields):
"If translated field is encountered, add also all its translation fields."
fields = set(fields)
from modeltranslation.translator import translator
opts = translator.get_options_for_model(model)
for key, translated in opts.fields.items():
if key in fields:
fields = fields.union(f.name for f in translated)
return fields | [
"def",
"append_translated",
"(",
"model",
",",
"fields",
")",
":",
"fields",
"=",
"set",
"(",
"fields",
")",
"from",
"modeltranslation",
".",
"translator",
"import",
"translator",
"opts",
"=",
"translator",
".",
"get_options_for_model",
"(",
"model",
")",
"for... | If translated field is encountered, add also all its translation fields. | [
"If",
"translated",
"field",
"is",
"encountered",
"add",
"also",
"all",
"its",
"translation",
"fields",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/manager.py#L79-L87 |
231,451 | deschler/django-modeltranslation | modeltranslation/manager.py | MultilingualQuerySet._rewrite_col | def _rewrite_col(self, col):
"""Django >= 1.7 column name rewriting"""
if isinstance(col, Col):
new_name = rewrite_lookup_key(self.model, col.target.name)
if col.target.name != new_name:
new_field = self.model._meta.get_field(new_name)
if col.target is col.source:
col.source = new_field
col.target = new_field
elif hasattr(col, 'col'):
self._rewrite_col(col.col)
elif hasattr(col, 'lhs'):
self._rewrite_col(col.lhs) | python | def _rewrite_col(self, col):
if isinstance(col, Col):
new_name = rewrite_lookup_key(self.model, col.target.name)
if col.target.name != new_name:
new_field = self.model._meta.get_field(new_name)
if col.target is col.source:
col.source = new_field
col.target = new_field
elif hasattr(col, 'col'):
self._rewrite_col(col.col)
elif hasattr(col, 'lhs'):
self._rewrite_col(col.lhs) | [
"def",
"_rewrite_col",
"(",
"self",
",",
"col",
")",
":",
"if",
"isinstance",
"(",
"col",
",",
"Col",
")",
":",
"new_name",
"=",
"rewrite_lookup_key",
"(",
"self",
".",
"model",
",",
"col",
".",
"target",
".",
"name",
")",
"if",
"col",
".",
"target",... | Django >= 1.7 column name rewriting | [
"Django",
">",
"=",
"1",
".",
"7",
"column",
"name",
"rewriting"
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/manager.py#L238-L250 |
231,452 | deschler/django-modeltranslation | modeltranslation/manager.py | MultilingualQuerySet._rewrite_where | def _rewrite_where(self, q):
"""
Rewrite field names inside WHERE tree.
"""
if isinstance(q, Lookup):
self._rewrite_col(q.lhs)
if isinstance(q, Node):
for child in q.children:
self._rewrite_where(child) | python | def _rewrite_where(self, q):
if isinstance(q, Lookup):
self._rewrite_col(q.lhs)
if isinstance(q, Node):
for child in q.children:
self._rewrite_where(child) | [
"def",
"_rewrite_where",
"(",
"self",
",",
"q",
")",
":",
"if",
"isinstance",
"(",
"q",
",",
"Lookup",
")",
":",
"self",
".",
"_rewrite_col",
"(",
"q",
".",
"lhs",
")",
"if",
"isinstance",
"(",
"q",
",",
"Node",
")",
":",
"for",
"child",
"in",
"q... | Rewrite field names inside WHERE tree. | [
"Rewrite",
"field",
"names",
"inside",
"WHERE",
"tree",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/manager.py#L252-L260 |
231,453 | deschler/django-modeltranslation | modeltranslation/manager.py | MultilingualQuerySet._rewrite_q | def _rewrite_q(self, q):
"""Rewrite field names inside Q call."""
if isinstance(q, tuple) and len(q) == 2:
return rewrite_lookup_key(self.model, q[0]), q[1]
if isinstance(q, Node):
q.children = list(map(self._rewrite_q, q.children))
return q | python | def _rewrite_q(self, q):
if isinstance(q, tuple) and len(q) == 2:
return rewrite_lookup_key(self.model, q[0]), q[1]
if isinstance(q, Node):
q.children = list(map(self._rewrite_q, q.children))
return q | [
"def",
"_rewrite_q",
"(",
"self",
",",
"q",
")",
":",
"if",
"isinstance",
"(",
"q",
",",
"tuple",
")",
"and",
"len",
"(",
"q",
")",
"==",
"2",
":",
"return",
"rewrite_lookup_key",
"(",
"self",
".",
"model",
",",
"q",
"[",
"0",
"]",
")",
",",
"q... | Rewrite field names inside Q call. | [
"Rewrite",
"field",
"names",
"inside",
"Q",
"call",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/manager.py#L274-L280 |
231,454 | deschler/django-modeltranslation | modeltranslation/manager.py | MultilingualQuerySet._rewrite_f | def _rewrite_f(self, q):
"""
Rewrite field names inside F call.
"""
if isinstance(q, models.F):
q.name = rewrite_lookup_key(self.model, q.name)
return q
if isinstance(q, Node):
q.children = list(map(self._rewrite_f, q.children))
# Django >= 1.8
if hasattr(q, 'lhs'):
q.lhs = self._rewrite_f(q.lhs)
if hasattr(q, 'rhs'):
q.rhs = self._rewrite_f(q.rhs)
return q | python | def _rewrite_f(self, q):
if isinstance(q, models.F):
q.name = rewrite_lookup_key(self.model, q.name)
return q
if isinstance(q, Node):
q.children = list(map(self._rewrite_f, q.children))
# Django >= 1.8
if hasattr(q, 'lhs'):
q.lhs = self._rewrite_f(q.lhs)
if hasattr(q, 'rhs'):
q.rhs = self._rewrite_f(q.rhs)
return q | [
"def",
"_rewrite_f",
"(",
"self",
",",
"q",
")",
":",
"if",
"isinstance",
"(",
"q",
",",
"models",
".",
"F",
")",
":",
"q",
".",
"name",
"=",
"rewrite_lookup_key",
"(",
"self",
".",
"model",
",",
"q",
".",
"name",
")",
"return",
"q",
"if",
"isins... | Rewrite field names inside F call. | [
"Rewrite",
"field",
"names",
"inside",
"F",
"call",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/manager.py#L283-L297 |
231,455 | deschler/django-modeltranslation | modeltranslation/manager.py | MultilingualQuerySet.order_by | def order_by(self, *field_names):
"""
Change translatable field names in an ``order_by`` argument
to translation fields for the current language.
"""
if not self._rewrite:
return super(MultilingualQuerySet, self).order_by(*field_names)
new_args = []
for key in field_names:
new_args.append(rewrite_order_lookup_key(self.model, key))
return super(MultilingualQuerySet, self).order_by(*new_args) | python | def order_by(self, *field_names):
if not self._rewrite:
return super(MultilingualQuerySet, self).order_by(*field_names)
new_args = []
for key in field_names:
new_args.append(rewrite_order_lookup_key(self.model, key))
return super(MultilingualQuerySet, self).order_by(*new_args) | [
"def",
"order_by",
"(",
"self",
",",
"*",
"field_names",
")",
":",
"if",
"not",
"self",
".",
"_rewrite",
":",
"return",
"super",
"(",
"MultilingualQuerySet",
",",
"self",
")",
".",
"order_by",
"(",
"*",
"field_names",
")",
"new_args",
"=",
"[",
"]",
"f... | Change translatable field names in an ``order_by`` argument
to translation fields for the current language. | [
"Change",
"translatable",
"field",
"names",
"in",
"an",
"order_by",
"argument",
"to",
"translation",
"fields",
"for",
"the",
"current",
"language",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/manager.py#L314-L324 |
231,456 | deschler/django-modeltranslation | modeltranslation/translator.py | add_translation_fields | def add_translation_fields(model, opts):
"""
Monkey patches the original model class to provide additional fields for
every language.
Adds newly created translation fields to the given translation options.
"""
model_empty_values = getattr(opts, 'empty_values', NONE)
for field_name in opts.local_fields.keys():
field_empty_value = parse_field(model_empty_values, field_name, NONE)
for l in mt_settings.AVAILABLE_LANGUAGES:
# Create a dynamic translation field
translation_field = create_translation_field(
model=model, field_name=field_name, lang=l, empty_value=field_empty_value)
# Construct the name for the localized field
localized_field_name = build_localized_fieldname(field_name, l)
# Check if the model already has a field by that name
if hasattr(model, localized_field_name):
# Check if are not dealing with abstract field inherited.
for cls in model.__mro__:
if hasattr(cls, '_meta') and cls.__dict__.get(localized_field_name, None):
cls_opts = translator._get_options_for_model(cls)
if not cls._meta.abstract or field_name not in cls_opts.local_fields:
raise ValueError("Error adding translation field. Model '%s' already"
" contains a field named '%s'." %
(model._meta.object_name, localized_field_name))
# This approach implements the translation fields as full valid
# django model fields and therefore adds them via add_to_class
model.add_to_class(localized_field_name, translation_field)
opts.add_translation_field(field_name, translation_field)
# Rebuild information about parents fields. If there are opts.local_fields, field cache would be
# invalidated (by model._meta.add_field() function). Otherwise, we need to do it manually.
if len(opts.local_fields) == 0:
model._meta._expire_cache()
model._meta.get_fields() | python | def add_translation_fields(model, opts):
model_empty_values = getattr(opts, 'empty_values', NONE)
for field_name in opts.local_fields.keys():
field_empty_value = parse_field(model_empty_values, field_name, NONE)
for l in mt_settings.AVAILABLE_LANGUAGES:
# Create a dynamic translation field
translation_field = create_translation_field(
model=model, field_name=field_name, lang=l, empty_value=field_empty_value)
# Construct the name for the localized field
localized_field_name = build_localized_fieldname(field_name, l)
# Check if the model already has a field by that name
if hasattr(model, localized_field_name):
# Check if are not dealing with abstract field inherited.
for cls in model.__mro__:
if hasattr(cls, '_meta') and cls.__dict__.get(localized_field_name, None):
cls_opts = translator._get_options_for_model(cls)
if not cls._meta.abstract or field_name not in cls_opts.local_fields:
raise ValueError("Error adding translation field. Model '%s' already"
" contains a field named '%s'." %
(model._meta.object_name, localized_field_name))
# This approach implements the translation fields as full valid
# django model fields and therefore adds them via add_to_class
model.add_to_class(localized_field_name, translation_field)
opts.add_translation_field(field_name, translation_field)
# Rebuild information about parents fields. If there are opts.local_fields, field cache would be
# invalidated (by model._meta.add_field() function). Otherwise, we need to do it manually.
if len(opts.local_fields) == 0:
model._meta._expire_cache()
model._meta.get_fields() | [
"def",
"add_translation_fields",
"(",
"model",
",",
"opts",
")",
":",
"model_empty_values",
"=",
"getattr",
"(",
"opts",
",",
"'empty_values'",
",",
"NONE",
")",
"for",
"field_name",
"in",
"opts",
".",
"local_fields",
".",
"keys",
"(",
")",
":",
"field_empty... | Monkey patches the original model class to provide additional fields for
every language.
Adds newly created translation fields to the given translation options. | [
"Monkey",
"patches",
"the",
"original",
"model",
"class",
"to",
"provide",
"additional",
"fields",
"for",
"every",
"language",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/translator.py#L127-L163 |
231,457 | deschler/django-modeltranslation | modeltranslation/translator.py | patch_clean_fields | def patch_clean_fields(model):
"""
Patch clean_fields method to handle different form types submission.
"""
old_clean_fields = model.clean_fields
def new_clean_fields(self, exclude=None):
if hasattr(self, '_mt_form_pending_clear'):
# Some form translation fields has been marked as clearing value.
# Check if corresponding translated field was also saved (not excluded):
# - if yes, it seems like form for MT-unaware app. Ignore clearing (left value from
# translated field unchanged), as if field was omitted from form
# - if no, then proceed as normally: clear the field
for field_name, value in self._mt_form_pending_clear.items():
field = self._meta.get_field(field_name)
orig_field_name = field.translated_field.name
if orig_field_name in exclude:
field.save_form_data(self, value, check=False)
delattr(self, '_mt_form_pending_clear')
old_clean_fields(self, exclude)
model.clean_fields = new_clean_fields | python | def patch_clean_fields(model):
old_clean_fields = model.clean_fields
def new_clean_fields(self, exclude=None):
if hasattr(self, '_mt_form_pending_clear'):
# Some form translation fields has been marked as clearing value.
# Check if corresponding translated field was also saved (not excluded):
# - if yes, it seems like form for MT-unaware app. Ignore clearing (left value from
# translated field unchanged), as if field was omitted from form
# - if no, then proceed as normally: clear the field
for field_name, value in self._mt_form_pending_clear.items():
field = self._meta.get_field(field_name)
orig_field_name = field.translated_field.name
if orig_field_name in exclude:
field.save_form_data(self, value, check=False)
delattr(self, '_mt_form_pending_clear')
old_clean_fields(self, exclude)
model.clean_fields = new_clean_fields | [
"def",
"patch_clean_fields",
"(",
"model",
")",
":",
"old_clean_fields",
"=",
"model",
".",
"clean_fields",
"def",
"new_clean_fields",
"(",
"self",
",",
"exclude",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_mt_form_pending_clear'",
")",
":",
... | Patch clean_fields method to handle different form types submission. | [
"Patch",
"clean_fields",
"method",
"to",
"handle",
"different",
"form",
"types",
"submission",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/translator.py#L245-L265 |
231,458 | deschler/django-modeltranslation | modeltranslation/translator.py | patch_related_object_descriptor_caching | def patch_related_object_descriptor_caching(ro_descriptor):
"""
Patch SingleRelatedObjectDescriptor or ReverseSingleRelatedObjectDescriptor to use
language-aware caching.
"""
class NewSingleObjectDescriptor(LanguageCacheSingleObjectDescriptor, ro_descriptor.__class__):
pass
if django.VERSION[0] == 2:
ro_descriptor.related.get_cache_name = partial(
NewSingleObjectDescriptor.get_cache_name,
ro_descriptor,
)
ro_descriptor.accessor = ro_descriptor.related.get_accessor_name()
ro_descriptor.__class__ = NewSingleObjectDescriptor | python | def patch_related_object_descriptor_caching(ro_descriptor):
class NewSingleObjectDescriptor(LanguageCacheSingleObjectDescriptor, ro_descriptor.__class__):
pass
if django.VERSION[0] == 2:
ro_descriptor.related.get_cache_name = partial(
NewSingleObjectDescriptor.get_cache_name,
ro_descriptor,
)
ro_descriptor.accessor = ro_descriptor.related.get_accessor_name()
ro_descriptor.__class__ = NewSingleObjectDescriptor | [
"def",
"patch_related_object_descriptor_caching",
"(",
"ro_descriptor",
")",
":",
"class",
"NewSingleObjectDescriptor",
"(",
"LanguageCacheSingleObjectDescriptor",
",",
"ro_descriptor",
".",
"__class__",
")",
":",
"pass",
"if",
"django",
".",
"VERSION",
"[",
"0",
"]",
... | Patch SingleRelatedObjectDescriptor or ReverseSingleRelatedObjectDescriptor to use
language-aware caching. | [
"Patch",
"SingleRelatedObjectDescriptor",
"or",
"ReverseSingleRelatedObjectDescriptor",
"to",
"use",
"language",
"-",
"aware",
"caching",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/translator.py#L363-L378 |
231,459 | deschler/django-modeltranslation | modeltranslation/translator.py | TranslationOptions.validate | def validate(self):
"""
Perform options validation.
"""
# TODO: at the moment only required_languages is validated.
# Maybe check other options as well?
if self.required_languages:
if isinstance(self.required_languages, (tuple, list)):
self._check_languages(self.required_languages)
else:
self._check_languages(self.required_languages.keys(), extra=('default',))
for fieldnames in self.required_languages.values():
if any(f not in self.fields for f in fieldnames):
raise ImproperlyConfigured(
'Fieldname in required_languages which is not in fields option.') | python | def validate(self):
# TODO: at the moment only required_languages is validated.
# Maybe check other options as well?
if self.required_languages:
if isinstance(self.required_languages, (tuple, list)):
self._check_languages(self.required_languages)
else:
self._check_languages(self.required_languages.keys(), extra=('default',))
for fieldnames in self.required_languages.values():
if any(f not in self.fields for f in fieldnames):
raise ImproperlyConfigured(
'Fieldname in required_languages which is not in fields option.') | [
"def",
"validate",
"(",
"self",
")",
":",
"# TODO: at the moment only required_languages is validated.",
"# Maybe check other options as well?",
"if",
"self",
".",
"required_languages",
":",
"if",
"isinstance",
"(",
"self",
".",
"required_languages",
",",
"(",
"tuple",
",... | Perform options validation. | [
"Perform",
"options",
"validation",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/translator.py#L78-L92 |
231,460 | deschler/django-modeltranslation | modeltranslation/translator.py | TranslationOptions.update | def update(self, other):
"""
Update with options from a superclass.
"""
if other.model._meta.abstract:
self.local_fields.update(other.local_fields)
self.fields.update(other.fields) | python | def update(self, other):
if other.model._meta.abstract:
self.local_fields.update(other.local_fields)
self.fields.update(other.fields) | [
"def",
"update",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
".",
"model",
".",
"_meta",
".",
"abstract",
":",
"self",
".",
"local_fields",
".",
"update",
"(",
"other",
".",
"local_fields",
")",
"self",
".",
"fields",
".",
"update",
"(",
"oth... | Update with options from a superclass. | [
"Update",
"with",
"options",
"from",
"a",
"superclass",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/translator.py#L100-L106 |
231,461 | deschler/django-modeltranslation | modeltranslation/translator.py | TranslationOptions.add_translation_field | def add_translation_field(self, field, translation_field):
"""
Add a new translation field to both fields dicts.
"""
self.local_fields[field].add(translation_field)
self.fields[field].add(translation_field) | python | def add_translation_field(self, field, translation_field):
self.local_fields[field].add(translation_field)
self.fields[field].add(translation_field) | [
"def",
"add_translation_field",
"(",
"self",
",",
"field",
",",
"translation_field",
")",
":",
"self",
".",
"local_fields",
"[",
"field",
"]",
".",
"add",
"(",
"translation_field",
")",
"self",
".",
"fields",
"[",
"field",
"]",
".",
"add",
"(",
"translatio... | Add a new translation field to both fields dicts. | [
"Add",
"a",
"new",
"translation",
"field",
"to",
"both",
"fields",
"dicts",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/translator.py#L108-L113 |
231,462 | deschler/django-modeltranslation | modeltranslation/translator.py | Translator.get_registered_models | def get_registered_models(self, abstract=True):
"""
Returns a list of all registered models, or just concrete
registered models.
"""
return [model for (model, opts) in self._registry.items()
if opts.registered and (not model._meta.abstract or abstract)] | python | def get_registered_models(self, abstract=True):
return [model for (model, opts) in self._registry.items()
if opts.registered and (not model._meta.abstract or abstract)] | [
"def",
"get_registered_models",
"(",
"self",
",",
"abstract",
"=",
"True",
")",
":",
"return",
"[",
"model",
"for",
"(",
"model",
",",
"opts",
")",
"in",
"self",
".",
"_registry",
".",
"items",
"(",
")",
"if",
"opts",
".",
"registered",
"and",
"(",
"... | Returns a list of all registered models, or just concrete
registered models. | [
"Returns",
"a",
"list",
"of",
"all",
"registered",
"models",
"or",
"just",
"concrete",
"registered",
"models",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/translator.py#L533-L539 |
231,463 | deschler/django-modeltranslation | modeltranslation/translator.py | Translator._get_options_for_model | def _get_options_for_model(self, model, opts_class=None, **options):
"""
Returns an instance of translation options with translated fields
defined for the ``model`` and inherited from superclasses.
"""
if model not in self._registry:
# Create a new type for backwards compatibility.
opts = type("%sTranslationOptions" % model.__name__,
(opts_class or TranslationOptions,), options)(model)
# Fields for translation may be inherited from abstract
# superclasses, so we need to look at all parents.
for base in model.__bases__:
if not hasattr(base, '_meta'):
# Things without _meta aren't functional models, so they're
# uninteresting parents.
continue
opts.update(self._get_options_for_model(base))
# Cache options for all models -- we may want to compute options
# of registered subclasses of unregistered models.
self._registry[model] = opts
return self._registry[model] | python | def _get_options_for_model(self, model, opts_class=None, **options):
if model not in self._registry:
# Create a new type for backwards compatibility.
opts = type("%sTranslationOptions" % model.__name__,
(opts_class or TranslationOptions,), options)(model)
# Fields for translation may be inherited from abstract
# superclasses, so we need to look at all parents.
for base in model.__bases__:
if not hasattr(base, '_meta'):
# Things without _meta aren't functional models, so they're
# uninteresting parents.
continue
opts.update(self._get_options_for_model(base))
# Cache options for all models -- we may want to compute options
# of registered subclasses of unregistered models.
self._registry[model] = opts
return self._registry[model] | [
"def",
"_get_options_for_model",
"(",
"self",
",",
"model",
",",
"opts_class",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"if",
"model",
"not",
"in",
"self",
".",
"_registry",
":",
"# Create a new type for backwards compatibility.",
"opts",
"=",
"type",
... | Returns an instance of translation options with translated fields
defined for the ``model`` and inherited from superclasses. | [
"Returns",
"an",
"instance",
"of",
"translation",
"options",
"with",
"translated",
"fields",
"defined",
"for",
"the",
"model",
"and",
"inherited",
"from",
"superclasses",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/translator.py#L541-L564 |
231,464 | deschler/django-modeltranslation | modeltranslation/translator.py | Translator.get_options_for_model | def get_options_for_model(self, model):
"""
Thin wrapper around ``_get_options_for_model`` to preserve the
semantic of throwing exception for models not directly registered.
"""
opts = self._get_options_for_model(model)
if not opts.registered and not opts.related:
raise NotRegistered('The model "%s" is not registered for '
'translation' % model.__name__)
return opts | python | def get_options_for_model(self, model):
opts = self._get_options_for_model(model)
if not opts.registered and not opts.related:
raise NotRegistered('The model "%s" is not registered for '
'translation' % model.__name__)
return opts | [
"def",
"get_options_for_model",
"(",
"self",
",",
"model",
")",
":",
"opts",
"=",
"self",
".",
"_get_options_for_model",
"(",
"model",
")",
"if",
"not",
"opts",
".",
"registered",
"and",
"not",
"opts",
".",
"related",
":",
"raise",
"NotRegistered",
"(",
"'... | Thin wrapper around ``_get_options_for_model`` to preserve the
semantic of throwing exception for models not directly registered. | [
"Thin",
"wrapper",
"around",
"_get_options_for_model",
"to",
"preserve",
"the",
"semantic",
"of",
"throwing",
"exception",
"for",
"models",
"not",
"directly",
"registered",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/translator.py#L566-L575 |
231,465 | deschler/django-modeltranslation | modeltranslation/management/commands/sync_translation_fields.py | Command.get_table_fields | def get_table_fields(self, db_table):
"""
Gets table fields from schema.
"""
db_table_desc = self.introspection.get_table_description(self.cursor, db_table)
return [t[0] for t in db_table_desc] | python | def get_table_fields(self, db_table):
db_table_desc = self.introspection.get_table_description(self.cursor, db_table)
return [t[0] for t in db_table_desc] | [
"def",
"get_table_fields",
"(",
"self",
",",
"db_table",
")",
":",
"db_table_desc",
"=",
"self",
".",
"introspection",
".",
"get_table_description",
"(",
"self",
".",
"cursor",
",",
"db_table",
")",
"return",
"[",
"t",
"[",
"0",
"]",
"for",
"t",
"in",
"d... | Gets table fields from schema. | [
"Gets",
"table",
"fields",
"from",
"schema",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/management/commands/sync_translation_fields.py#L106-L111 |
231,466 | deschler/django-modeltranslation | modeltranslation/management/commands/sync_translation_fields.py | Command.get_missing_languages | def get_missing_languages(self, field_name, db_table):
"""
Gets only missings fields.
"""
db_table_fields = self.get_table_fields(db_table)
for lang_code in AVAILABLE_LANGUAGES:
if build_localized_fieldname(field_name, lang_code) not in db_table_fields:
yield lang_code | python | def get_missing_languages(self, field_name, db_table):
db_table_fields = self.get_table_fields(db_table)
for lang_code in AVAILABLE_LANGUAGES:
if build_localized_fieldname(field_name, lang_code) not in db_table_fields:
yield lang_code | [
"def",
"get_missing_languages",
"(",
"self",
",",
"field_name",
",",
"db_table",
")",
":",
"db_table_fields",
"=",
"self",
".",
"get_table_fields",
"(",
"db_table",
")",
"for",
"lang_code",
"in",
"AVAILABLE_LANGUAGES",
":",
"if",
"build_localized_fieldname",
"(",
... | Gets only missings fields. | [
"Gets",
"only",
"missings",
"fields",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/management/commands/sync_translation_fields.py#L113-L120 |
231,467 | deschler/django-modeltranslation | modeltranslation/management/commands/sync_translation_fields.py | Command.get_sync_sql | def get_sync_sql(self, field_name, missing_langs, model):
"""
Returns SQL needed for sync schema for a new translatable field.
"""
qn = connection.ops.quote_name
style = no_style()
sql_output = []
db_table = model._meta.db_table
for lang in missing_langs:
new_field = build_localized_fieldname(field_name, lang)
f = model._meta.get_field(new_field)
col_type = f.db_type(connection=connection)
field_sql = [style.SQL_FIELD(qn(f.column)), style.SQL_COLTYPE(col_type)]
# column creation
stmt = "ALTER TABLE %s ADD COLUMN %s" % (qn(db_table), ' '.join(field_sql))
if not f.null:
stmt += " " + style.SQL_KEYWORD('NOT NULL')
sql_output.append(stmt + ";")
return sql_output | python | def get_sync_sql(self, field_name, missing_langs, model):
qn = connection.ops.quote_name
style = no_style()
sql_output = []
db_table = model._meta.db_table
for lang in missing_langs:
new_field = build_localized_fieldname(field_name, lang)
f = model._meta.get_field(new_field)
col_type = f.db_type(connection=connection)
field_sql = [style.SQL_FIELD(qn(f.column)), style.SQL_COLTYPE(col_type)]
# column creation
stmt = "ALTER TABLE %s ADD COLUMN %s" % (qn(db_table), ' '.join(field_sql))
if not f.null:
stmt += " " + style.SQL_KEYWORD('NOT NULL')
sql_output.append(stmt + ";")
return sql_output | [
"def",
"get_sync_sql",
"(",
"self",
",",
"field_name",
",",
"missing_langs",
",",
"model",
")",
":",
"qn",
"=",
"connection",
".",
"ops",
".",
"quote_name",
"style",
"=",
"no_style",
"(",
")",
"sql_output",
"=",
"[",
"]",
"db_table",
"=",
"model",
".",
... | Returns SQL needed for sync schema for a new translatable field. | [
"Returns",
"SQL",
"needed",
"for",
"sync",
"schema",
"for",
"a",
"new",
"translatable",
"field",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/management/commands/sync_translation_fields.py#L122-L140 |
231,468 | deschler/django-modeltranslation | modeltranslation/fields.py | create_translation_field | def create_translation_field(model, field_name, lang, empty_value):
"""
Translation field factory. Returns a ``TranslationField`` based on a
fieldname and a language.
The list of supported fields can be extended by defining a tuple of field
names in the projects settings.py like this::
MODELTRANSLATION_CUSTOM_FIELDS = ('MyField', 'MyOtherField',)
If the class is neither a subclass of fields in ``SUPPORTED_FIELDS``, nor
in ``CUSTOM_FIELDS`` an ``ImproperlyConfigured`` exception will be raised.
"""
if empty_value not in ('', 'both', None, NONE):
raise ImproperlyConfigured('%s is not a valid empty_value.' % empty_value)
field = model._meta.get_field(field_name)
cls_name = field.__class__.__name__
if not (isinstance(field, SUPPORTED_FIELDS) or cls_name in mt_settings.CUSTOM_FIELDS):
raise ImproperlyConfigured(
'%s is not supported by modeltranslation.' % cls_name)
translation_class = field_factory(field.__class__)
return translation_class(translated_field=field, language=lang, empty_value=empty_value) | python | def create_translation_field(model, field_name, lang, empty_value):
if empty_value not in ('', 'both', None, NONE):
raise ImproperlyConfigured('%s is not a valid empty_value.' % empty_value)
field = model._meta.get_field(field_name)
cls_name = field.__class__.__name__
if not (isinstance(field, SUPPORTED_FIELDS) or cls_name in mt_settings.CUSTOM_FIELDS):
raise ImproperlyConfigured(
'%s is not supported by modeltranslation.' % cls_name)
translation_class = field_factory(field.__class__)
return translation_class(translated_field=field, language=lang, empty_value=empty_value) | [
"def",
"create_translation_field",
"(",
"model",
",",
"field_name",
",",
"lang",
",",
"empty_value",
")",
":",
"if",
"empty_value",
"not",
"in",
"(",
"''",
",",
"'both'",
",",
"None",
",",
"NONE",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"'%s is not a... | Translation field factory. Returns a ``TranslationField`` based on a
fieldname and a language.
The list of supported fields can be extended by defining a tuple of field
names in the projects settings.py like this::
MODELTRANSLATION_CUSTOM_FIELDS = ('MyField', 'MyOtherField',)
If the class is neither a subclass of fields in ``SUPPORTED_FIELDS``, nor
in ``CUSTOM_FIELDS`` an ``ImproperlyConfigured`` exception will be raised. | [
"Translation",
"field",
"factory",
".",
"Returns",
"a",
"TranslationField",
"based",
"on",
"a",
"fieldname",
"and",
"a",
"language",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/fields.py#L49-L70 |
231,469 | deschler/django-modeltranslation | modeltranslation/fields.py | TranslationFieldDescriptor.meaningful_value | def meaningful_value(self, val, undefined):
"""
Check if val is considered non-empty.
"""
if isinstance(val, fields.files.FieldFile):
return val.name and not (
isinstance(undefined, fields.files.FieldFile) and val == undefined)
return val is not None and val != undefined | python | def meaningful_value(self, val, undefined):
if isinstance(val, fields.files.FieldFile):
return val.name and not (
isinstance(undefined, fields.files.FieldFile) and val == undefined)
return val is not None and val != undefined | [
"def",
"meaningful_value",
"(",
"self",
",",
"val",
",",
"undefined",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"fields",
".",
"files",
".",
"FieldFile",
")",
":",
"return",
"val",
".",
"name",
"and",
"not",
"(",
"isinstance",
"(",
"undefined",
",... | Check if val is considered non-empty. | [
"Check",
"if",
"val",
"is",
"considered",
"non",
"-",
"empty",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/fields.py#L324-L331 |
231,470 | deschler/django-modeltranslation | modeltranslation/fields.py | LanguageCacheSingleObjectDescriptor.cache_name | def cache_name(self):
"""
Used in django 1.x
"""
lang = get_language()
cache = build_localized_fieldname(self.accessor, lang)
return "_%s_cache" % cache | python | def cache_name(self):
lang = get_language()
cache = build_localized_fieldname(self.accessor, lang)
return "_%s_cache" % cache | [
"def",
"cache_name",
"(",
"self",
")",
":",
"lang",
"=",
"get_language",
"(",
")",
"cache",
"=",
"build_localized_fieldname",
"(",
"self",
".",
"accessor",
",",
"lang",
")",
"return",
"\"_%s_cache\"",
"%",
"cache"
] | Used in django 1.x | [
"Used",
"in",
"django",
"1",
".",
"x"
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/fields.py#L406-L412 |
231,471 | deschler/django-modeltranslation | modeltranslation/admin.py | TranslationBaseModelAdmin.replace_orig_field | def replace_orig_field(self, option):
"""
Replaces each original field in `option` that is registered for
translation by its translation fields.
Returns a new list with replaced fields. If `option` contains no
registered fields, it is returned unmodified.
>>> self = TranslationAdmin() # PyFlakes
>>> print(self.trans_opts.fields.keys())
['title',]
>>> get_translation_fields(self.trans_opts.fields.keys()[0])
['title_de', 'title_en']
>>> self.replace_orig_field(['title', 'url'])
['title_de', 'title_en', 'url']
Note that grouped fields are flattened. We do this because:
1. They are hard to handle in the jquery-ui tabs implementation
2. They don't scale well with more than a few languages
3. It's better than not handling them at all (okay that's weak)
>>> self.replace_orig_field((('title', 'url'), 'email', 'text'))
['title_de', 'title_en', 'url_de', 'url_en', 'email_de', 'email_en', 'text']
"""
if option:
option_new = list(option)
for opt in option:
if opt in self.trans_opts.fields:
index = option_new.index(opt)
option_new[index:index + 1] = get_translation_fields(opt)
elif isinstance(opt, (tuple, list)) and (
[o for o in opt if o in self.trans_opts.fields]):
index = option_new.index(opt)
option_new[index:index + 1] = self.replace_orig_field(opt)
option = option_new
return option | python | def replace_orig_field(self, option):
if option:
option_new = list(option)
for opt in option:
if opt in self.trans_opts.fields:
index = option_new.index(opt)
option_new[index:index + 1] = get_translation_fields(opt)
elif isinstance(opt, (tuple, list)) and (
[o for o in opt if o in self.trans_opts.fields]):
index = option_new.index(opt)
option_new[index:index + 1] = self.replace_orig_field(opt)
option = option_new
return option | [
"def",
"replace_orig_field",
"(",
"self",
",",
"option",
")",
":",
"if",
"option",
":",
"option_new",
"=",
"list",
"(",
"option",
")",
"for",
"opt",
"in",
"option",
":",
"if",
"opt",
"in",
"self",
".",
"trans_opts",
".",
"fields",
":",
"index",
"=",
... | Replaces each original field in `option` that is registered for
translation by its translation fields.
Returns a new list with replaced fields. If `option` contains no
registered fields, it is returned unmodified.
>>> self = TranslationAdmin() # PyFlakes
>>> print(self.trans_opts.fields.keys())
['title',]
>>> get_translation_fields(self.trans_opts.fields.keys()[0])
['title_de', 'title_en']
>>> self.replace_orig_field(['title', 'url'])
['title_de', 'title_en', 'url']
Note that grouped fields are flattened. We do this because:
1. They are hard to handle in the jquery-ui tabs implementation
2. They don't scale well with more than a few languages
3. It's better than not handling them at all (okay that's weak)
>>> self.replace_orig_field((('title', 'url'), 'email', 'text'))
['title_de', 'title_en', 'url_de', 'url_en', 'email_de', 'email_en', 'text'] | [
"Replaces",
"each",
"original",
"field",
"in",
"option",
"that",
"is",
"registered",
"for",
"translation",
"by",
"its",
"translation",
"fields",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/admin.py#L113-L149 |
231,472 | deschler/django-modeltranslation | modeltranslation/admin.py | TranslationBaseModelAdmin._get_form_or_formset | def _get_form_or_formset(self, request, obj, **kwargs):
"""
Generic code shared by get_form and get_formset.
"""
if self.exclude is None:
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(self.get_readonly_fields(request, obj))
if not self.exclude and hasattr(self.form, '_meta') and self.form._meta.exclude:
# Take the custom ModelForm's Meta.exclude into account only if the
# ModelAdmin doesn't define its own.
exclude.extend(self.form._meta.exclude)
# If exclude is an empty list we pass None to be consistant with the
# default on modelform_factory
exclude = self.replace_orig_field(exclude) or None
exclude = self._exclude_original_fields(exclude)
kwargs.update({'exclude': exclude})
return kwargs | python | def _get_form_or_formset(self, request, obj, **kwargs):
if self.exclude is None:
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(self.get_readonly_fields(request, obj))
if not self.exclude and hasattr(self.form, '_meta') and self.form._meta.exclude:
# Take the custom ModelForm's Meta.exclude into account only if the
# ModelAdmin doesn't define its own.
exclude.extend(self.form._meta.exclude)
# If exclude is an empty list we pass None to be consistant with the
# default on modelform_factory
exclude = self.replace_orig_field(exclude) or None
exclude = self._exclude_original_fields(exclude)
kwargs.update({'exclude': exclude})
return kwargs | [
"def",
"_get_form_or_formset",
"(",
"self",
",",
"request",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"exclude",
"is",
"None",
":",
"exclude",
"=",
"[",
"]",
"else",
":",
"exclude",
"=",
"list",
"(",
"self",
".",
"exclude",
... | Generic code shared by get_form and get_formset. | [
"Generic",
"code",
"shared",
"by",
"get_form",
"and",
"get_formset",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/admin.py#L180-L199 |
231,473 | deschler/django-modeltranslation | modeltranslation/admin.py | TranslationBaseModelAdmin._get_fieldsets_post_form_or_formset | def _get_fieldsets_post_form_or_formset(self, request, form, obj=None):
"""
Generic get_fieldsets code, shared by
TranslationAdmin and TranslationInlineModelAdmin.
"""
base_fields = self.replace_orig_field(form.base_fields.keys())
fields = base_fields + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': self.replace_orig_field(fields)})] | python | def _get_fieldsets_post_form_or_formset(self, request, form, obj=None):
base_fields = self.replace_orig_field(form.base_fields.keys())
fields = base_fields + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': self.replace_orig_field(fields)})] | [
"def",
"_get_fieldsets_post_form_or_formset",
"(",
"self",
",",
"request",
",",
"form",
",",
"obj",
"=",
"None",
")",
":",
"base_fields",
"=",
"self",
".",
"replace_orig_field",
"(",
"form",
".",
"base_fields",
".",
"keys",
"(",
")",
")",
"fields",
"=",
"b... | Generic get_fieldsets code, shared by
TranslationAdmin and TranslationInlineModelAdmin. | [
"Generic",
"get_fieldsets",
"code",
"shared",
"by",
"TranslationAdmin",
"and",
"TranslationInlineModelAdmin",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/admin.py#L208-L215 |
231,474 | deschler/django-modeltranslation | modeltranslation/widgets.py | ClearableWidgetWrapper.media | def media(self):
"""
Combines media of both components and adds a small script that unchecks
the clear box, when a value in any wrapped input is modified.
"""
return self.widget.media + self.checkbox.media + Media(self.Media) | python | def media(self):
return self.widget.media + self.checkbox.media + Media(self.Media) | [
"def",
"media",
"(",
"self",
")",
":",
"return",
"self",
".",
"widget",
".",
"media",
"+",
"self",
".",
"checkbox",
".",
"media",
"+",
"Media",
"(",
"self",
".",
"Media",
")"
] | Combines media of both components and adds a small script that unchecks
the clear box, when a value in any wrapped input is modified. | [
"Combines",
"media",
"of",
"both",
"components",
"and",
"adds",
"a",
"small",
"script",
"that",
"unchecks",
"the",
"clear",
"box",
"when",
"a",
"value",
"in",
"any",
"wrapped",
"input",
"is",
"modified",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/widgets.py#L53-L58 |
231,475 | deschler/django-modeltranslation | modeltranslation/widgets.py | ClearableWidgetWrapper.value_from_datadict | def value_from_datadict(self, data, files, name):
"""
If the clear checkbox is checked returns the configured empty value,
completely ignoring the original input.
"""
clear = self.checkbox.value_from_datadict(data, files, self.clear_checkbox_name(name))
if clear:
return self.empty_value
return self.widget.value_from_datadict(data, files, name) | python | def value_from_datadict(self, data, files, name):
clear = self.checkbox.value_from_datadict(data, files, self.clear_checkbox_name(name))
if clear:
return self.empty_value
return self.widget.value_from_datadict(data, files, name) | [
"def",
"value_from_datadict",
"(",
"self",
",",
"data",
",",
"files",
",",
"name",
")",
":",
"clear",
"=",
"self",
".",
"checkbox",
".",
"value_from_datadict",
"(",
"data",
",",
"files",
",",
"self",
".",
"clear_checkbox_name",
"(",
"name",
")",
")",
"if... | If the clear checkbox is checked returns the configured empty value,
completely ignoring the original input. | [
"If",
"the",
"clear",
"checkbox",
"is",
"checked",
"returns",
"the",
"configured",
"empty",
"value",
"completely",
"ignoring",
"the",
"original",
"input",
"."
] | 18fec04a5105cbd83fc3759f4fda20135b3a848c | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/widgets.py#L80-L88 |
231,476 | maximdanilchenko/aiohttp-apispec | aiohttp_apispec/aiohttp_apispec.py | setup_aiohttp_apispec | def setup_aiohttp_apispec(
app: web.Application,
*,
title: str = "API documentation",
version: str = "0.0.1",
url: str = "/api/docs/swagger.json",
request_data_name: str = "data",
swagger_path: str = None,
static_path: str = '/static/swagger',
**kwargs
) -> None:
"""
aiohttp-apispec extension.
Usage:
.. code-block:: python
from aiohttp_apispec import docs, request_schema, setup_aiohttp_apispec
from aiohttp import web
from marshmallow import Schema, fields
class RequestSchema(Schema):
id = fields.Int()
name = fields.Str(description='name')
bool_field = fields.Bool()
@docs(tags=['mytag'],
summary='Test method summary',
description='Test method description')
@request_schema(RequestSchema)
async def index(request):
return web.json_response({'msg': 'done', 'data': {}})
app = web.Application()
app.router.add_post('/v1/test', index)
# init docs with all parameters, usual for ApiSpec
setup_aiohttp_apispec(app=app,
title='My Documentation',
version='v1',
url='/api/docs/api-docs')
# now we can find it on 'http://localhost:8080/api/docs/api-docs'
web.run_app(app)
:param Application app: aiohttp web app
:param str title: API title
:param str version: API version
:param str url: url for swagger spec in JSON format
:param str request_data_name: name of the key in Request object
where validated data will be placed by
validation_middleware (``'data'`` by default)
:param str swagger_path: experimental SwaggerUI support (starting from v1.1.0).
By default it is None (disabled)
:param str static_path: path for static files used by SwaggerUI
(if it is enabled with ``swagger_path``)
:param kwargs: any apispec.APISpec kwargs
"""
AiohttpApiSpec(
url,
app,
request_data_name,
title=title,
version=version,
swagger_path=swagger_path,
static_path=static_path,
**kwargs
) | python | def setup_aiohttp_apispec(
app: web.Application,
*,
title: str = "API documentation",
version: str = "0.0.1",
url: str = "/api/docs/swagger.json",
request_data_name: str = "data",
swagger_path: str = None,
static_path: str = '/static/swagger',
**kwargs
) -> None:
AiohttpApiSpec(
url,
app,
request_data_name,
title=title,
version=version,
swagger_path=swagger_path,
static_path=static_path,
**kwargs
) | [
"def",
"setup_aiohttp_apispec",
"(",
"app",
":",
"web",
".",
"Application",
",",
"*",
",",
"title",
":",
"str",
"=",
"\"API documentation\"",
",",
"version",
":",
"str",
"=",
"\"0.0.1\"",
",",
"url",
":",
"str",
"=",
"\"/api/docs/swagger.json\"",
",",
"reque... | aiohttp-apispec extension.
Usage:
.. code-block:: python
from aiohttp_apispec import docs, request_schema, setup_aiohttp_apispec
from aiohttp import web
from marshmallow import Schema, fields
class RequestSchema(Schema):
id = fields.Int()
name = fields.Str(description='name')
bool_field = fields.Bool()
@docs(tags=['mytag'],
summary='Test method summary',
description='Test method description')
@request_schema(RequestSchema)
async def index(request):
return web.json_response({'msg': 'done', 'data': {}})
app = web.Application()
app.router.add_post('/v1/test', index)
# init docs with all parameters, usual for ApiSpec
setup_aiohttp_apispec(app=app,
title='My Documentation',
version='v1',
url='/api/docs/api-docs')
# now we can find it on 'http://localhost:8080/api/docs/api-docs'
web.run_app(app)
:param Application app: aiohttp web app
:param str title: API title
:param str version: API version
:param str url: url for swagger spec in JSON format
:param str request_data_name: name of the key in Request object
where validated data will be placed by
validation_middleware (``'data'`` by default)
:param str swagger_path: experimental SwaggerUI support (starting from v1.1.0).
By default it is None (disabled)
:param str static_path: path for static files used by SwaggerUI
(if it is enabled with ``swagger_path``)
:param kwargs: any apispec.APISpec kwargs | [
"aiohttp",
"-",
"apispec",
"extension",
"."
] | 9119931ef04f9e9df9e1d9fc04d44bade41399ba | https://github.com/maximdanilchenko/aiohttp-apispec/blob/9119931ef04f9e9df9e1d9fc04d44bade41399ba/aiohttp_apispec/aiohttp_apispec.py#L146-L217 |
231,477 | maximdanilchenko/aiohttp-apispec | aiohttp_apispec/decorators.py | docs | def docs(**kwargs):
"""
Annotate the decorated view function with the specified Swagger
attributes.
Usage:
.. code-block:: python
from aiohttp import web
@docs(tags=['my_tag'],
summary='Test method summary',
description='Test method description',
parameters=[{
'in': 'header',
'name': 'X-Request-ID',
'schema': {'type': 'string', 'format': 'uuid'},
'required': 'true'
}]
)
async def index(request):
return web.json_response({'msg': 'done', 'data': {}})
"""
def wrapper(func):
kwargs["produces"] = ["application/json"]
if not hasattr(func, "__apispec__"):
func.__apispec__ = {"parameters": [], "responses": {}}
extra_parameters = kwargs.pop("parameters", [])
extra_responses = kwargs.pop("responses", {})
func.__apispec__["parameters"].extend(extra_parameters)
func.__apispec__["responses"].update(extra_responses)
func.__apispec__.update(kwargs)
return func
return wrapper | python | def docs(**kwargs):
def wrapper(func):
kwargs["produces"] = ["application/json"]
if not hasattr(func, "__apispec__"):
func.__apispec__ = {"parameters": [], "responses": {}}
extra_parameters = kwargs.pop("parameters", [])
extra_responses = kwargs.pop("responses", {})
func.__apispec__["parameters"].extend(extra_parameters)
func.__apispec__["responses"].update(extra_responses)
func.__apispec__.update(kwargs)
return func
return wrapper | [
"def",
"docs",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"kwargs",
"[",
"\"produces\"",
"]",
"=",
"[",
"\"application/json\"",
"]",
"if",
"not",
"hasattr",
"(",
"func",
",",
"\"__apispec__\"",
")",
":",
"func",
".",
... | Annotate the decorated view function with the specified Swagger
attributes.
Usage:
.. code-block:: python
from aiohttp import web
@docs(tags=['my_tag'],
summary='Test method summary',
description='Test method description',
parameters=[{
'in': 'header',
'name': 'X-Request-ID',
'schema': {'type': 'string', 'format': 'uuid'},
'required': 'true'
}]
)
async def index(request):
return web.json_response({'msg': 'done', 'data': {}}) | [
"Annotate",
"the",
"decorated",
"view",
"function",
"with",
"the",
"specified",
"Swagger",
"attributes",
"."
] | 9119931ef04f9e9df9e1d9fc04d44bade41399ba | https://github.com/maximdanilchenko/aiohttp-apispec/blob/9119931ef04f9e9df9e1d9fc04d44bade41399ba/aiohttp_apispec/decorators.py#L1-L38 |
231,478 | maximdanilchenko/aiohttp-apispec | aiohttp_apispec/decorators.py | response_schema | def response_schema(schema, code=200, required=False, description=None):
"""
Add response info into the swagger spec
Usage:
.. code-block:: python
from aiohttp import web
from marshmallow import Schema, fields
class ResponseSchema(Schema):
msg = fields.Str()
data = fields.Dict()
@response_schema(ResponseSchema(), 200)
async def index(request):
return web.json_response({'msg': 'done', 'data': {}})
:param str description: response description
:param bool required:
:param schema: :class:`Schema <marshmallow.Schema>` class or instance
:param int code: HTTP response code
"""
if callable(schema):
schema = schema()
def wrapper(func):
if not hasattr(func, "__apispec__"):
func.__apispec__ = {"parameters": [], "responses": {}}
func.__apispec__["responses"]["%s" % code] = {
"schema": schema,
"required": required,
"description": description,
}
return func
return wrapper | python | def response_schema(schema, code=200, required=False, description=None):
if callable(schema):
schema = schema()
def wrapper(func):
if not hasattr(func, "__apispec__"):
func.__apispec__ = {"parameters": [], "responses": {}}
func.__apispec__["responses"]["%s" % code] = {
"schema": schema,
"required": required,
"description": description,
}
return func
return wrapper | [
"def",
"response_schema",
"(",
"schema",
",",
"code",
"=",
"200",
",",
"required",
"=",
"False",
",",
"description",
"=",
"None",
")",
":",
"if",
"callable",
"(",
"schema",
")",
":",
"schema",
"=",
"schema",
"(",
")",
"def",
"wrapper",
"(",
"func",
"... | Add response info into the swagger spec
Usage:
.. code-block:: python
from aiohttp import web
from marshmallow import Schema, fields
class ResponseSchema(Schema):
msg = fields.Str()
data = fields.Dict()
@response_schema(ResponseSchema(), 200)
async def index(request):
return web.json_response({'msg': 'done', 'data': {}})
:param str description: response description
:param bool required:
:param schema: :class:`Schema <marshmallow.Schema>` class or instance
:param int code: HTTP response code | [
"Add",
"response",
"info",
"into",
"the",
"swagger",
"spec"
] | 9119931ef04f9e9df9e1d9fc04d44bade41399ba | https://github.com/maximdanilchenko/aiohttp-apispec/blob/9119931ef04f9e9df9e1d9fc04d44bade41399ba/aiohttp_apispec/decorators.py#L108-L146 |
231,479 | maximdanilchenko/aiohttp-apispec | aiohttp_apispec/middlewares.py | validation_middleware | async def validation_middleware(request: web.Request, handler) -> web.Response:
"""
Validation middleware for aiohttp web app
Usage:
.. code-block:: python
app.middlewares.append(validation_middleware)
"""
orig_handler = request.match_info.handler
if not hasattr(orig_handler, "__schemas__"):
if not issubclass_py37fix(orig_handler, web.View):
return await handler(request)
sub_handler = getattr(orig_handler, request.method.lower(), None)
if sub_handler is None:
return await handler(request)
if not hasattr(sub_handler, "__schemas__"):
return await handler(request)
schemas = sub_handler.__schemas__
else:
schemas = orig_handler.__schemas__
kwargs = {}
for schema in schemas:
data = await parser.parse(
schema["schema"], request, locations=schema["locations"]
)
if data:
kwargs.update(data)
kwargs.update(request.match_info)
request[request.app["_apispec_request_data_name"]] = kwargs
return await handler(request) | python | async def validation_middleware(request: web.Request, handler) -> web.Response:
orig_handler = request.match_info.handler
if not hasattr(orig_handler, "__schemas__"):
if not issubclass_py37fix(orig_handler, web.View):
return await handler(request)
sub_handler = getattr(orig_handler, request.method.lower(), None)
if sub_handler is None:
return await handler(request)
if not hasattr(sub_handler, "__schemas__"):
return await handler(request)
schemas = sub_handler.__schemas__
else:
schemas = orig_handler.__schemas__
kwargs = {}
for schema in schemas:
data = await parser.parse(
schema["schema"], request, locations=schema["locations"]
)
if data:
kwargs.update(data)
kwargs.update(request.match_info)
request[request.app["_apispec_request_data_name"]] = kwargs
return await handler(request) | [
"async",
"def",
"validation_middleware",
"(",
"request",
":",
"web",
".",
"Request",
",",
"handler",
")",
"->",
"web",
".",
"Response",
":",
"orig_handler",
"=",
"request",
".",
"match_info",
".",
"handler",
"if",
"not",
"hasattr",
"(",
"orig_handler",
",",
... | Validation middleware for aiohttp web app
Usage:
.. code-block:: python
app.middlewares.append(validation_middleware) | [
"Validation",
"middleware",
"for",
"aiohttp",
"web",
"app"
] | 9119931ef04f9e9df9e1d9fc04d44bade41399ba | https://github.com/maximdanilchenko/aiohttp-apispec/blob/9119931ef04f9e9df9e1d9fc04d44bade41399ba/aiohttp_apispec/middlewares.py#L8-L41 |
231,480 | odlgroup/odl | odl/util/vectorization.py | is_valid_input_array | def is_valid_input_array(x, ndim=None):
"""Test if ``x`` is a correctly shaped point array in R^d."""
x = np.asarray(x)
if ndim is None or ndim == 1:
return x.ndim == 1 and x.size > 1 or x.ndim == 2 and x.shape[0] == 1
else:
return x.ndim == 2 and x.shape[0] == ndim | python | def is_valid_input_array(x, ndim=None):
x = np.asarray(x)
if ndim is None or ndim == 1:
return x.ndim == 1 and x.size > 1 or x.ndim == 2 and x.shape[0] == 1
else:
return x.ndim == 2 and x.shape[0] == ndim | [
"def",
"is_valid_input_array",
"(",
"x",
",",
"ndim",
"=",
"None",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"if",
"ndim",
"is",
"None",
"or",
"ndim",
"==",
"1",
":",
"return",
"x",
".",
"ndim",
"==",
"1",
"and",
"x",
".",
"size"... | Test if ``x`` is a correctly shaped point array in R^d. | [
"Test",
"if",
"x",
"is",
"a",
"correctly",
"shaped",
"point",
"array",
"in",
"R^d",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/util/vectorization.py#L22-L29 |
231,481 | odlgroup/odl | odl/util/vectorization.py | is_valid_input_meshgrid | def is_valid_input_meshgrid(x, ndim):
"""Test if ``x`` is a `meshgrid` sequence for points in R^d."""
# This case is triggered in FunctionSpaceElement.__call__ if the
# domain does not have an 'ndim' attribute. We return False and
# continue.
if ndim is None:
return False
if not isinstance(x, tuple):
return False
if ndim > 1:
try:
np.broadcast(*x)
except (ValueError, TypeError): # cannot be broadcast
return False
return (len(x) == ndim and
all(isinstance(xi, np.ndarray) for xi in x) and
all(xi.ndim == ndim for xi in x)) | python | def is_valid_input_meshgrid(x, ndim):
# This case is triggered in FunctionSpaceElement.__call__ if the
# domain does not have an 'ndim' attribute. We return False and
# continue.
if ndim is None:
return False
if not isinstance(x, tuple):
return False
if ndim > 1:
try:
np.broadcast(*x)
except (ValueError, TypeError): # cannot be broadcast
return False
return (len(x) == ndim and
all(isinstance(xi, np.ndarray) for xi in x) and
all(xi.ndim == ndim for xi in x)) | [
"def",
"is_valid_input_meshgrid",
"(",
"x",
",",
"ndim",
")",
":",
"# This case is triggered in FunctionSpaceElement.__call__ if the",
"# domain does not have an 'ndim' attribute. We return False and",
"# continue.",
"if",
"ndim",
"is",
"None",
":",
"return",
"False",
"if",
"no... | Test if ``x`` is a `meshgrid` sequence for points in R^d. | [
"Test",
"if",
"x",
"is",
"a",
"meshgrid",
"sequence",
"for",
"points",
"in",
"R^d",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/util/vectorization.py#L32-L51 |
231,482 | odlgroup/odl | odl/util/vectorization.py | out_shape_from_meshgrid | def out_shape_from_meshgrid(mesh):
"""Get the broadcast output shape from a `meshgrid`."""
if len(mesh) == 1:
return (len(mesh[0]),)
else:
return np.broadcast(*mesh).shape | python | def out_shape_from_meshgrid(mesh):
if len(mesh) == 1:
return (len(mesh[0]),)
else:
return np.broadcast(*mesh).shape | [
"def",
"out_shape_from_meshgrid",
"(",
"mesh",
")",
":",
"if",
"len",
"(",
"mesh",
")",
"==",
"1",
":",
"return",
"(",
"len",
"(",
"mesh",
"[",
"0",
"]",
")",
",",
")",
"else",
":",
"return",
"np",
".",
"broadcast",
"(",
"*",
"mesh",
")",
".",
... | Get the broadcast output shape from a `meshgrid`. | [
"Get",
"the",
"broadcast",
"output",
"shape",
"from",
"a",
"meshgrid",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/util/vectorization.py#L54-L59 |
231,483 | odlgroup/odl | odl/util/vectorization.py | out_shape_from_array | def out_shape_from_array(arr):
"""Get the output shape from an array."""
arr = np.asarray(arr)
if arr.ndim == 1:
return arr.shape
else:
return (arr.shape[1],) | python | def out_shape_from_array(arr):
arr = np.asarray(arr)
if arr.ndim == 1:
return arr.shape
else:
return (arr.shape[1],) | [
"def",
"out_shape_from_array",
"(",
"arr",
")",
":",
"arr",
"=",
"np",
".",
"asarray",
"(",
"arr",
")",
"if",
"arr",
".",
"ndim",
"==",
"1",
":",
"return",
"arr",
".",
"shape",
"else",
":",
"return",
"(",
"arr",
".",
"shape",
"[",
"1",
"]",
",",
... | Get the output shape from an array. | [
"Get",
"the",
"output",
"shape",
"from",
"an",
"array",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/util/vectorization.py#L62-L68 |
231,484 | odlgroup/odl | odl/util/vectorization.py | vectorize._wrapper | def _wrapper(func, *vect_args, **vect_kwargs):
"""Return the vectorized wrapper function."""
if not hasattr(func, '__name__'):
# Set name if not available. Happens if func is actually a function
func.__name__ = '{}.__call__'.format(func.__class__.__name__)
return wraps(func)(_NumpyVectorizeWrapper(func, *vect_args,
**vect_kwargs)) | python | def _wrapper(func, *vect_args, **vect_kwargs):
if not hasattr(func, '__name__'):
# Set name if not available. Happens if func is actually a function
func.__name__ = '{}.__call__'.format(func.__class__.__name__)
return wraps(func)(_NumpyVectorizeWrapper(func, *vect_args,
**vect_kwargs)) | [
"def",
"_wrapper",
"(",
"func",
",",
"*",
"vect_args",
",",
"*",
"*",
"vect_kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"func",
",",
"'__name__'",
")",
":",
"# Set name if not available. Happens if func is actually a function",
"func",
".",
"__name__",
"=",
... | Return the vectorized wrapper function. | [
"Return",
"the",
"vectorized",
"wrapper",
"function",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/util/vectorization.py#L221-L228 |
231,485 | odlgroup/odl | odl/operator/pspace_ops.py | ProductSpaceOperator._convert_to_spmatrix | def _convert_to_spmatrix(operators):
"""Convert an array-like object of operators to a sparse matrix."""
# Lazy import to improve `import odl` time
import scipy.sparse
# Convert ops to sparse representation. This is not trivial because
# operators can be indexable themselves and give the wrong impression
# of an extra dimension. So we have to infer the shape manually
# first and extract the indices of nonzero positions.
nrows = len(operators)
ncols = None
irow, icol, data = [], [], []
for i, row in enumerate(operators):
try:
iter(row)
except TypeError:
raise ValueError(
'`operators` must be a matrix of `Operator` objects, `0` '
'or `None`, got {!r} (row {} = {!r} is not iterable)'
''.format(operators, i, row))
if isinstance(row, Operator):
raise ValueError(
'`operators` must be a matrix of `Operator` objects, `0` '
'or `None`, but row {} is an `Operator` {!r}'
''.format(i, row))
if ncols is None:
ncols = len(row)
elif len(row) != ncols:
raise ValueError(
'all rows in `operators` must have the same length, but '
'length {} of row {} differs from previous common length '
'{}'.format(len(row), i, ncols))
for j, col in enumerate(row):
if col is None or col is 0:
pass
elif isinstance(col, Operator):
irow.append(i)
icol.append(j)
data.append(col)
else:
raise ValueError(
'`operators` must be a matrix of `Operator` objects, '
'`0` or `None`, got entry {!r} at ({}, {})'
''.format(col, i, j))
# Create object array explicitly, threby avoiding erroneous conversion
# in `coo_matrix.__init__`
data_arr = np.empty(len(data), dtype=object)
data_arr[:] = data
return scipy.sparse.coo_matrix((data_arr, (irow, icol)),
shape=(nrows, ncols)) | python | def _convert_to_spmatrix(operators):
# Lazy import to improve `import odl` time
import scipy.sparse
# Convert ops to sparse representation. This is not trivial because
# operators can be indexable themselves and give the wrong impression
# of an extra dimension. So we have to infer the shape manually
# first and extract the indices of nonzero positions.
nrows = len(operators)
ncols = None
irow, icol, data = [], [], []
for i, row in enumerate(operators):
try:
iter(row)
except TypeError:
raise ValueError(
'`operators` must be a matrix of `Operator` objects, `0` '
'or `None`, got {!r} (row {} = {!r} is not iterable)'
''.format(operators, i, row))
if isinstance(row, Operator):
raise ValueError(
'`operators` must be a matrix of `Operator` objects, `0` '
'or `None`, but row {} is an `Operator` {!r}'
''.format(i, row))
if ncols is None:
ncols = len(row)
elif len(row) != ncols:
raise ValueError(
'all rows in `operators` must have the same length, but '
'length {} of row {} differs from previous common length '
'{}'.format(len(row), i, ncols))
for j, col in enumerate(row):
if col is None or col is 0:
pass
elif isinstance(col, Operator):
irow.append(i)
icol.append(j)
data.append(col)
else:
raise ValueError(
'`operators` must be a matrix of `Operator` objects, '
'`0` or `None`, got entry {!r} at ({}, {})'
''.format(col, i, j))
# Create object array explicitly, threby avoiding erroneous conversion
# in `coo_matrix.__init__`
data_arr = np.empty(len(data), dtype=object)
data_arr[:] = data
return scipy.sparse.coo_matrix((data_arr, (irow, icol)),
shape=(nrows, ncols)) | [
"def",
"_convert_to_spmatrix",
"(",
"operators",
")",
":",
"# Lazy import to improve `import odl` time",
"import",
"scipy",
".",
"sparse",
"# Convert ops to sparse representation. This is not trivial because",
"# operators can be indexable themselves and give the wrong impression",
"# of a... | Convert an array-like object of operators to a sparse matrix. | [
"Convert",
"an",
"array",
"-",
"like",
"object",
"of",
"operators",
"to",
"a",
"sparse",
"matrix",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/pspace_ops.py#L230-L283 |
231,486 | odlgroup/odl | odl/operator/pspace_ops.py | ProductSpaceOperator._call | def _call(self, x, out=None):
"""Call the operators on the parts of ``x``."""
# TODO: add optimization in case an operator appears repeatedly in a
# row
if out is None:
out = self.range.zero()
for i, j, op in zip(self.ops.row, self.ops.col, self.ops.data):
out[i] += op(x[j])
else:
has_evaluated_row = np.zeros(len(self.range), dtype=bool)
for i, j, op in zip(self.ops.row, self.ops.col, self.ops.data):
if not has_evaluated_row[i]:
op(x[j], out=out[i])
else:
# TODO: optimize
out[i] += op(x[j])
has_evaluated_row[i] = True
for i, evaluated in enumerate(has_evaluated_row):
if not evaluated:
out[i].set_zero()
return out | python | def _call(self, x, out=None):
# TODO: add optimization in case an operator appears repeatedly in a
# row
if out is None:
out = self.range.zero()
for i, j, op in zip(self.ops.row, self.ops.col, self.ops.data):
out[i] += op(x[j])
else:
has_evaluated_row = np.zeros(len(self.range), dtype=bool)
for i, j, op in zip(self.ops.row, self.ops.col, self.ops.data):
if not has_evaluated_row[i]:
op(x[j], out=out[i])
else:
# TODO: optimize
out[i] += op(x[j])
has_evaluated_row[i] = True
for i, evaluated in enumerate(has_evaluated_row):
if not evaluated:
out[i].set_zero()
return out | [
"def",
"_call",
"(",
"self",
",",
"x",
",",
"out",
"=",
"None",
")",
":",
"# TODO: add optimization in case an operator appears repeatedly in a",
"# row",
"if",
"out",
"is",
"None",
":",
"out",
"=",
"self",
".",
"range",
".",
"zero",
"(",
")",
"for",
"i",
... | Call the operators on the parts of ``x``. | [
"Call",
"the",
"operators",
"on",
"the",
"parts",
"of",
"x",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/pspace_ops.py#L290-L313 |
231,487 | odlgroup/odl | odl/operator/pspace_ops.py | ProductSpaceOperator.derivative | def derivative(self, x):
"""Derivative of the product space operator.
Parameters
----------
x : `domain` element
The point to take the derivative in
Returns
-------
adjoint : linear`ProductSpaceOperator`
The derivative
Examples
--------
>>> r3 = odl.rn(3)
>>> pspace = odl.ProductSpace(r3, r3)
>>> I = odl.IdentityOperator(r3)
>>> x = pspace.element([[1, 2, 3], [4, 5, 6]])
Example with linear operator (derivative is itself)
>>> prod_op = ProductSpaceOperator([[0, I], [0, 0]],
... domain=pspace, range=pspace)
>>> prod_op(x)
ProductSpace(rn(3), 2).element([
[ 4., 5., 6.],
[ 0., 0., 0.]
])
>>> prod_op.derivative(x)(x)
ProductSpace(rn(3), 2).element([
[ 4., 5., 6.],
[ 0., 0., 0.]
])
Example with affine operator
>>> residual_op = I - r3.element([1, 1, 1])
>>> op = ProductSpaceOperator([[0, residual_op], [0, 0]],
... domain=pspace, range=pspace)
Calling operator gives offset by [1, 1, 1]
>>> op(x)
ProductSpace(rn(3), 2).element([
[ 3., 4., 5.],
[ 0., 0., 0.]
])
Derivative of affine operator does not have this offset
>>> op.derivative(x)(x)
ProductSpace(rn(3), 2).element([
[ 4., 5., 6.],
[ 0., 0., 0.]
])
"""
# Lazy import to improve `import odl` time
import scipy.sparse
# Short circuit optimization
if self.is_linear:
return self
deriv_ops = [op.derivative(x[col]) for op, col in zip(self.ops.data,
self.ops.col)]
data = np.empty(len(deriv_ops), dtype=object)
data[:] = deriv_ops
indices = [self.ops.row, self.ops.col]
shape = self.ops.shape
deriv_matrix = scipy.sparse.coo_matrix((data, indices), shape)
return ProductSpaceOperator(deriv_matrix, self.domain, self.range) | python | def derivative(self, x):
# Lazy import to improve `import odl` time
import scipy.sparse
# Short circuit optimization
if self.is_linear:
return self
deriv_ops = [op.derivative(x[col]) for op, col in zip(self.ops.data,
self.ops.col)]
data = np.empty(len(deriv_ops), dtype=object)
data[:] = deriv_ops
indices = [self.ops.row, self.ops.col]
shape = self.ops.shape
deriv_matrix = scipy.sparse.coo_matrix((data, indices), shape)
return ProductSpaceOperator(deriv_matrix, self.domain, self.range) | [
"def",
"derivative",
"(",
"self",
",",
"x",
")",
":",
"# Lazy import to improve `import odl` time",
"import",
"scipy",
".",
"sparse",
"# Short circuit optimization",
"if",
"self",
".",
"is_linear",
":",
"return",
"self",
"deriv_ops",
"=",
"[",
"op",
".",
"derivati... | Derivative of the product space operator.
Parameters
----------
x : `domain` element
The point to take the derivative in
Returns
-------
adjoint : linear`ProductSpaceOperator`
The derivative
Examples
--------
>>> r3 = odl.rn(3)
>>> pspace = odl.ProductSpace(r3, r3)
>>> I = odl.IdentityOperator(r3)
>>> x = pspace.element([[1, 2, 3], [4, 5, 6]])
Example with linear operator (derivative is itself)
>>> prod_op = ProductSpaceOperator([[0, I], [0, 0]],
... domain=pspace, range=pspace)
>>> prod_op(x)
ProductSpace(rn(3), 2).element([
[ 4., 5., 6.],
[ 0., 0., 0.]
])
>>> prod_op.derivative(x)(x)
ProductSpace(rn(3), 2).element([
[ 4., 5., 6.],
[ 0., 0., 0.]
])
Example with affine operator
>>> residual_op = I - r3.element([1, 1, 1])
>>> op = ProductSpaceOperator([[0, residual_op], [0, 0]],
... domain=pspace, range=pspace)
Calling operator gives offset by [1, 1, 1]
>>> op(x)
ProductSpace(rn(3), 2).element([
[ 3., 4., 5.],
[ 0., 0., 0.]
])
Derivative of affine operator does not have this offset
>>> op.derivative(x)(x)
ProductSpace(rn(3), 2).element([
[ 4., 5., 6.],
[ 0., 0., 0.]
]) | [
"Derivative",
"of",
"the",
"product",
"space",
"operator",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/pspace_ops.py#L315-L386 |
231,488 | odlgroup/odl | odl/operator/pspace_ops.py | ComponentProjection._call | def _call(self, x, out=None):
"""Project ``x`` onto the subspace."""
if out is None:
out = x[self.index].copy()
else:
out.assign(x[self.index])
return out | python | def _call(self, x, out=None):
if out is None:
out = x[self.index].copy()
else:
out.assign(x[self.index])
return out | [
"def",
"_call",
"(",
"self",
",",
"x",
",",
"out",
"=",
"None",
")",
":",
"if",
"out",
"is",
"None",
":",
"out",
"=",
"x",
"[",
"self",
".",
"index",
"]",
".",
"copy",
"(",
")",
"else",
":",
"out",
".",
"assign",
"(",
"x",
"[",
"self",
".",... | Project ``x`` onto the subspace. | [
"Project",
"x",
"onto",
"the",
"subspace",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/pspace_ops.py#L589-L595 |
231,489 | odlgroup/odl | odl/operator/pspace_ops.py | ComponentProjectionAdjoint._call | def _call(self, x, out=None):
"""Extend ``x`` from the subspace."""
if out is None:
out = self.range.zero()
else:
out.set_zero()
out[self.index] = x
return out | python | def _call(self, x, out=None):
if out is None:
out = self.range.zero()
else:
out.set_zero()
out[self.index] = x
return out | [
"def",
"_call",
"(",
"self",
",",
"x",
",",
"out",
"=",
"None",
")",
":",
"if",
"out",
"is",
"None",
":",
"out",
"=",
"self",
".",
"range",
".",
"zero",
"(",
")",
"else",
":",
"out",
".",
"set_zero",
"(",
")",
"out",
"[",
"self",
".",
"index"... | Extend ``x`` from the subspace. | [
"Extend",
"x",
"from",
"the",
"subspace",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/pspace_ops.py#L685-L693 |
231,490 | odlgroup/odl | odl/operator/pspace_ops.py | BroadcastOperator._call | def _call(self, x, out=None):
"""Evaluate all operators in ``x`` and broadcast."""
wrapped_x = self.prod_op.domain.element([x], cast=False)
return self.prod_op(wrapped_x, out=out) | python | def _call(self, x, out=None):
wrapped_x = self.prod_op.domain.element([x], cast=False)
return self.prod_op(wrapped_x, out=out) | [
"def",
"_call",
"(",
"self",
",",
"x",
",",
"out",
"=",
"None",
")",
":",
"wrapped_x",
"=",
"self",
".",
"prod_op",
".",
"domain",
".",
"element",
"(",
"[",
"x",
"]",
",",
"cast",
"=",
"False",
")",
"return",
"self",
".",
"prod_op",
"(",
"wrapped... | Evaluate all operators in ``x`` and broadcast. | [
"Evaluate",
"all",
"operators",
"in",
"x",
"and",
"broadcast",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/pspace_ops.py#L805-L808 |
231,491 | odlgroup/odl | odl/operator/pspace_ops.py | BroadcastOperator.derivative | def derivative(self, x):
"""Derivative of the broadcast operator.
Parameters
----------
x : `domain` element
The point to take the derivative in
Returns
-------
adjoint : linear `BroadcastOperator`
The derivative
Examples
--------
Example with an affine operator:
>>> I = odl.IdentityOperator(odl.rn(3))
>>> residual_op = I - I.domain.element([1, 1, 1])
>>> op = BroadcastOperator(residual_op, 2 * residual_op)
Calling operator offsets by ``[1, 1, 1]``:
>>> x = [1, 2, 3]
>>> op(x)
ProductSpace(rn(3), 2).element([
[ 0., 1., 2.],
[ 0., 2., 4.]
])
The derivative of this affine operator does not have an offset:
>>> op.derivative(x)(x)
ProductSpace(rn(3), 2).element([
[ 1., 2., 3.],
[ 2., 4., 6.]
])
"""
return BroadcastOperator(*[op.derivative(x) for op in
self.operators]) | python | def derivative(self, x):
return BroadcastOperator(*[op.derivative(x) for op in
self.operators]) | [
"def",
"derivative",
"(",
"self",
",",
"x",
")",
":",
"return",
"BroadcastOperator",
"(",
"*",
"[",
"op",
".",
"derivative",
"(",
"x",
")",
"for",
"op",
"in",
"self",
".",
"operators",
"]",
")"
] | Derivative of the broadcast operator.
Parameters
----------
x : `domain` element
The point to take the derivative in
Returns
-------
adjoint : linear `BroadcastOperator`
The derivative
Examples
--------
Example with an affine operator:
>>> I = odl.IdentityOperator(odl.rn(3))
>>> residual_op = I - I.domain.element([1, 1, 1])
>>> op = BroadcastOperator(residual_op, 2 * residual_op)
Calling operator offsets by ``[1, 1, 1]``:
>>> x = [1, 2, 3]
>>> op(x)
ProductSpace(rn(3), 2).element([
[ 0., 1., 2.],
[ 0., 2., 4.]
])
The derivative of this affine operator does not have an offset:
>>> op.derivative(x)(x)
ProductSpace(rn(3), 2).element([
[ 1., 2., 3.],
[ 2., 4., 6.]
]) | [
"Derivative",
"of",
"the",
"broadcast",
"operator",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/pspace_ops.py#L810-L849 |
231,492 | odlgroup/odl | odl/operator/pspace_ops.py | ReductionOperator._call | def _call(self, x, out=None):
"""Apply operators to ``x`` and sum."""
if out is None:
return self.prod_op(x)[0]
else:
wrapped_out = self.prod_op.range.element([out], cast=False)
pspace_result = self.prod_op(x, out=wrapped_out)
return pspace_result[0] | python | def _call(self, x, out=None):
if out is None:
return self.prod_op(x)[0]
else:
wrapped_out = self.prod_op.range.element([out], cast=False)
pspace_result = self.prod_op(x, out=wrapped_out)
return pspace_result[0] | [
"def",
"_call",
"(",
"self",
",",
"x",
",",
"out",
"=",
"None",
")",
":",
"if",
"out",
"is",
"None",
":",
"return",
"self",
".",
"prod_op",
"(",
"x",
")",
"[",
"0",
"]",
"else",
":",
"wrapped_out",
"=",
"self",
".",
"prod_op",
".",
"range",
"."... | Apply operators to ``x`` and sum. | [
"Apply",
"operators",
"to",
"x",
"and",
"sum",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/pspace_ops.py#L982-L989 |
231,493 | odlgroup/odl | odl/operator/pspace_ops.py | ReductionOperator.derivative | def derivative(self, x):
"""Derivative of the reduction operator.
Parameters
----------
x : `domain` element
The point to take the derivative in.
Returns
-------
derivative : linear `BroadcastOperator`
Examples
--------
>>> r3 = odl.rn(3)
>>> I = odl.IdentityOperator(r3)
>>> x = [1.0, 2.0, 3.0]
>>> y = [4.0, 6.0, 8.0]
Example with linear operator (derivative is itself)
>>> op = ReductionOperator(I, 2 * I)
>>> op([x, y])
rn(3).element([ 9., 14., 19.])
>>> op.derivative([x, y])([x, y])
rn(3).element([ 9., 14., 19.])
Example with affine operator
>>> residual_op = I - r3.element([1, 1, 1])
>>> op = ReductionOperator(residual_op, 2 * residual_op)
Calling operator gives offset by [3, 3, 3]
>>> op([x, y])
rn(3).element([ 6., 11., 16.])
Derivative of affine operator does not have this offset
>>> op.derivative([x, y])([x, y])
rn(3).element([ 9., 14., 19.])
"""
return ReductionOperator(*[op.derivative(xi)
for op, xi in zip(self.operators, x)]) | python | def derivative(self, x):
return ReductionOperator(*[op.derivative(xi)
for op, xi in zip(self.operators, x)]) | [
"def",
"derivative",
"(",
"self",
",",
"x",
")",
":",
"return",
"ReductionOperator",
"(",
"*",
"[",
"op",
".",
"derivative",
"(",
"xi",
")",
"for",
"op",
",",
"xi",
"in",
"zip",
"(",
"self",
".",
"operators",
",",
"x",
")",
"]",
")"
] | Derivative of the reduction operator.
Parameters
----------
x : `domain` element
The point to take the derivative in.
Returns
-------
derivative : linear `BroadcastOperator`
Examples
--------
>>> r3 = odl.rn(3)
>>> I = odl.IdentityOperator(r3)
>>> x = [1.0, 2.0, 3.0]
>>> y = [4.0, 6.0, 8.0]
Example with linear operator (derivative is itself)
>>> op = ReductionOperator(I, 2 * I)
>>> op([x, y])
rn(3).element([ 9., 14., 19.])
>>> op.derivative([x, y])([x, y])
rn(3).element([ 9., 14., 19.])
Example with affine operator
>>> residual_op = I - r3.element([1, 1, 1])
>>> op = ReductionOperator(residual_op, 2 * residual_op)
Calling operator gives offset by [3, 3, 3]
>>> op([x, y])
rn(3).element([ 6., 11., 16.])
Derivative of affine operator does not have this offset
>>> op.derivative([x, y])([x, y])
rn(3).element([ 9., 14., 19.]) | [
"Derivative",
"of",
"the",
"reduction",
"operator",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/pspace_ops.py#L991-L1034 |
231,494 | odlgroup/odl | odl/contrib/shearlab/shearlab_operator.py | load_julia_with_Shearlab | def load_julia_with_Shearlab():
"""Function to load Shearlab."""
# Importing base
j = julia.Julia()
j.eval('using Shearlab')
j.eval('using PyPlot')
j.eval('using Images')
return j | python | def load_julia_with_Shearlab():
# Importing base
j = julia.Julia()
j.eval('using Shearlab')
j.eval('using PyPlot')
j.eval('using Images')
return j | [
"def",
"load_julia_with_Shearlab",
"(",
")",
":",
"# Importing base",
"j",
"=",
"julia",
".",
"Julia",
"(",
")",
"j",
".",
"eval",
"(",
"'using Shearlab'",
")",
"j",
".",
"eval",
"(",
"'using PyPlot'",
")",
"j",
".",
"eval",
"(",
"'using Images'",
")",
"... | Function to load Shearlab. | [
"Function",
"to",
"load",
"Shearlab",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/shearlab/shearlab_operator.py#L216-L223 |
231,495 | odlgroup/odl | odl/contrib/shearlab/shearlab_operator.py | load_image | def load_image(name, n, m=None, gpu=None, square=None):
"""Function to load images with certain size."""
if m is None:
m = n
if gpu is None:
gpu = 0
if square is None:
square = 0
command = ('Shearlab.load_image("{}", {}, {}, {}, {})'.format(name,
n, m, gpu, square))
return j.eval(command) | python | def load_image(name, n, m=None, gpu=None, square=None):
if m is None:
m = n
if gpu is None:
gpu = 0
if square is None:
square = 0
command = ('Shearlab.load_image("{}", {}, {}, {}, {})'.format(name,
n, m, gpu, square))
return j.eval(command) | [
"def",
"load_image",
"(",
"name",
",",
"n",
",",
"m",
"=",
"None",
",",
"gpu",
"=",
"None",
",",
"square",
"=",
"None",
")",
":",
"if",
"m",
"is",
"None",
":",
"m",
"=",
"n",
"if",
"gpu",
"is",
"None",
":",
"gpu",
"=",
"0",
"if",
"square",
... | Function to load images with certain size. | [
"Function",
"to",
"load",
"images",
"with",
"certain",
"size",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/shearlab/shearlab_operator.py#L229-L239 |
231,496 | odlgroup/odl | odl/contrib/shearlab/shearlab_operator.py | imageplot | def imageplot(f, str=None, sbpt=None):
"""Plot an image generated by the library."""
# Function to plot images
if str is None:
str = ''
if sbpt is None:
sbpt = []
if sbpt != []:
plt.subplot(sbpt[0], sbpt[1], sbpt[2])
imgplot = plt.imshow(f, interpolation='nearest')
imgplot.set_cmap('gray')
plt.axis('off')
if str != '':
plt.title(str) | python | def imageplot(f, str=None, sbpt=None):
# Function to plot images
if str is None:
str = ''
if sbpt is None:
sbpt = []
if sbpt != []:
plt.subplot(sbpt[0], sbpt[1], sbpt[2])
imgplot = plt.imshow(f, interpolation='nearest')
imgplot.set_cmap('gray')
plt.axis('off')
if str != '':
plt.title(str) | [
"def",
"imageplot",
"(",
"f",
",",
"str",
"=",
"None",
",",
"sbpt",
"=",
"None",
")",
":",
"# Function to plot images",
"if",
"str",
"is",
"None",
":",
"str",
"=",
"''",
"if",
"sbpt",
"is",
"None",
":",
"sbpt",
"=",
"[",
"]",
"if",
"sbpt",
"!=",
... | Plot an image generated by the library. | [
"Plot",
"an",
"image",
"generated",
"by",
"the",
"library",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/shearlab/shearlab_operator.py#L242-L255 |
231,497 | odlgroup/odl | odl/contrib/shearlab/shearlab_operator.py | getshearletsystem2D | def getshearletsystem2D(rows, cols, nScales, shearLevels=None,
full=None,
directionalFilter=None,
quadratureMirrorFilter=None):
"""Function to generate de 2D system."""
if shearLevels is None:
shearLevels = [float(ceil(i / 2)) for i in range(1, nScales + 1)]
if full is None:
full = 0
if directionalFilter is None:
directionalFilter = 'Shearlab.filt_gen("directional_shearlet")'
if quadratureMirrorFilter is None:
quadratureMirrorFilter = 'Shearlab.filt_gen("scaling_shearlet")'
j.eval('rows=' + str(rows))
j.eval('cols=' + str(cols))
j.eval('nScales=' + str(nScales))
j.eval('shearLevels=' + str(shearLevels))
j.eval('full=' + str(full))
j.eval('directionalFilter=' + directionalFilter)
j.eval('quadratureMirrorFilter=' + quadratureMirrorFilter)
j.eval('shearletsystem=Shearlab.getshearletsystem2D(rows, '
'cols, nScales, shearLevels, full, directionalFilter, '
'quadratureMirrorFilter) ')
shearlets = j.eval('shearletsystem.shearlets')
size = j.eval('shearletsystem.size')
shearLevels = j.eval('shearletsystem.shearLevels')
full = j.eval('shearletsystem.full')
nShearlets = j.eval('shearletsystem.nShearlets')
shearletIdxs = j.eval('shearletsystem.shearletIdxs')
dualFrameWeights = j.eval('shearletsystem.dualFrameWeights')
RMS = j.eval('shearletsystem.RMS')
isComplex = j.eval('shearletsystem.isComplex')
j.eval('shearletsystem = 0')
return Shearletsystem2D(shearlets, size, shearLevels, full, nShearlets,
shearletIdxs, dualFrameWeights, RMS, isComplex) | python | def getshearletsystem2D(rows, cols, nScales, shearLevels=None,
full=None,
directionalFilter=None,
quadratureMirrorFilter=None):
if shearLevels is None:
shearLevels = [float(ceil(i / 2)) for i in range(1, nScales + 1)]
if full is None:
full = 0
if directionalFilter is None:
directionalFilter = 'Shearlab.filt_gen("directional_shearlet")'
if quadratureMirrorFilter is None:
quadratureMirrorFilter = 'Shearlab.filt_gen("scaling_shearlet")'
j.eval('rows=' + str(rows))
j.eval('cols=' + str(cols))
j.eval('nScales=' + str(nScales))
j.eval('shearLevels=' + str(shearLevels))
j.eval('full=' + str(full))
j.eval('directionalFilter=' + directionalFilter)
j.eval('quadratureMirrorFilter=' + quadratureMirrorFilter)
j.eval('shearletsystem=Shearlab.getshearletsystem2D(rows, '
'cols, nScales, shearLevels, full, directionalFilter, '
'quadratureMirrorFilter) ')
shearlets = j.eval('shearletsystem.shearlets')
size = j.eval('shearletsystem.size')
shearLevels = j.eval('shearletsystem.shearLevels')
full = j.eval('shearletsystem.full')
nShearlets = j.eval('shearletsystem.nShearlets')
shearletIdxs = j.eval('shearletsystem.shearletIdxs')
dualFrameWeights = j.eval('shearletsystem.dualFrameWeights')
RMS = j.eval('shearletsystem.RMS')
isComplex = j.eval('shearletsystem.isComplex')
j.eval('shearletsystem = 0')
return Shearletsystem2D(shearlets, size, shearLevels, full, nShearlets,
shearletIdxs, dualFrameWeights, RMS, isComplex) | [
"def",
"getshearletsystem2D",
"(",
"rows",
",",
"cols",
",",
"nScales",
",",
"shearLevels",
"=",
"None",
",",
"full",
"=",
"None",
",",
"directionalFilter",
"=",
"None",
",",
"quadratureMirrorFilter",
"=",
"None",
")",
":",
"if",
"shearLevels",
"is",
"None",... | Function to generate de 2D system. | [
"Function",
"to",
"generate",
"de",
"2D",
"system",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/shearlab/shearlab_operator.py#L273-L307 |
231,498 | odlgroup/odl | odl/contrib/shearlab/shearlab_operator.py | sheardec2D | def sheardec2D(X, shearletsystem):
"""Shearlet Decomposition function."""
coeffs = np.zeros(shearletsystem.shearlets.shape, dtype=complex)
Xfreq = fftshift(fft2(ifftshift(X)))
for i in range(shearletsystem.nShearlets):
coeffs[:, :, i] = fftshift(ifft2(ifftshift(Xfreq * np.conj(
shearletsystem.shearlets[:, :, i]))))
return coeffs.real | python | def sheardec2D(X, shearletsystem):
coeffs = np.zeros(shearletsystem.shearlets.shape, dtype=complex)
Xfreq = fftshift(fft2(ifftshift(X)))
for i in range(shearletsystem.nShearlets):
coeffs[:, :, i] = fftshift(ifft2(ifftshift(Xfreq * np.conj(
shearletsystem.shearlets[:, :, i]))))
return coeffs.real | [
"def",
"sheardec2D",
"(",
"X",
",",
"shearletsystem",
")",
":",
"coeffs",
"=",
"np",
".",
"zeros",
"(",
"shearletsystem",
".",
"shearlets",
".",
"shape",
",",
"dtype",
"=",
"complex",
")",
"Xfreq",
"=",
"fftshift",
"(",
"fft2",
"(",
"ifftshift",
"(",
"... | Shearlet Decomposition function. | [
"Shearlet",
"Decomposition",
"function",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/shearlab/shearlab_operator.py#L310-L317 |
231,499 | odlgroup/odl | odl/contrib/shearlab/shearlab_operator.py | ShearlabOperator.adjoint | def adjoint(self):
"""The adjoint operator."""
op = self
class ShearlabOperatorAdjoint(odl.Operator):
"""Adjoint of the shearlet transform.
See Also
--------
odl.contrib.shearlab.ShearlabOperator
"""
def __init__(self):
"""Initialize a new instance."""
self.mutex = op.mutex
self.shearlet_system = op.shearlet_system
super(ShearlabOperatorAdjoint, self).__init__(
op.range, op.domain, True)
def _call(self, x):
"""``self(x)``."""
with op.mutex:
x = np.moveaxis(x, 0, -1)
return sheardecadjoint2D(x, op.shearlet_system)
@property
def adjoint(self):
"""The adjoint operator."""
return op
@property
def inverse(self):
"""The inverse operator."""
op = self
class ShearlabOperatorAdjointInverse(odl.Operator):
"""
Adjoint of the inverse/Inverse of the adjoint
of shearlet transform.
See Also
--------
odl.contrib.shearlab.ShearlabOperator
"""
def __init__(self):
"""Initialize a new instance."""
self.mutex = op.mutex
self.shearlet_system = op.shearlet_system
super(ShearlabOperatorAdjointInverse, self).__init__(
op.range, op.domain, True)
def _call(self, x):
"""``self(x)``."""
with op.mutex:
result = shearrecadjoint2D(x, op.shearlet_system)
return np.moveaxis(result, -1, 0)
@property
def adjoint(self):
"""The adjoint operator."""
return op.adjoint.inverse
@property
def inverse(self):
"""The inverse operator."""
return op
return ShearlabOperatorAdjointInverse()
return ShearlabOperatorAdjoint() | python | def adjoint(self):
op = self
class ShearlabOperatorAdjoint(odl.Operator):
"""Adjoint of the shearlet transform.
See Also
--------
odl.contrib.shearlab.ShearlabOperator
"""
def __init__(self):
"""Initialize a new instance."""
self.mutex = op.mutex
self.shearlet_system = op.shearlet_system
super(ShearlabOperatorAdjoint, self).__init__(
op.range, op.domain, True)
def _call(self, x):
"""``self(x)``."""
with op.mutex:
x = np.moveaxis(x, 0, -1)
return sheardecadjoint2D(x, op.shearlet_system)
@property
def adjoint(self):
return op
@property
def inverse(self):
"""The inverse operator."""
op = self
class ShearlabOperatorAdjointInverse(odl.Operator):
"""
Adjoint of the inverse/Inverse of the adjoint
of shearlet transform.
See Also
--------
odl.contrib.shearlab.ShearlabOperator
"""
def __init__(self):
"""Initialize a new instance."""
self.mutex = op.mutex
self.shearlet_system = op.shearlet_system
super(ShearlabOperatorAdjointInverse, self).__init__(
op.range, op.domain, True)
def _call(self, x):
"""``self(x)``."""
with op.mutex:
result = shearrecadjoint2D(x, op.shearlet_system)
return np.moveaxis(result, -1, 0)
@property
def adjoint(self):
return op.adjoint.inverse
@property
def inverse(self):
"""The inverse operator."""
return op
return ShearlabOperatorAdjointInverse()
return ShearlabOperatorAdjoint() | [
"def",
"adjoint",
"(",
"self",
")",
":",
"op",
"=",
"self",
"class",
"ShearlabOperatorAdjoint",
"(",
"odl",
".",
"Operator",
")",
":",
"\"\"\"Adjoint of the shearlet transform.\n\n See Also\n --------\n odl.contrib.shearlab.ShearlabOperator\n ... | The adjoint operator. | [
"The",
"adjoint",
"operator",
"."
] | b8443f6aca90e191ba36c91d32253c5a36249a6c | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/shearlab/shearlab_operator.py#L63-L135 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.