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 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
16,200
|
MacHu-GWU/uszipcode-project
|
fixcode.py
|
fixcode
|
def fixcode(**kwargs):
"""
auto pep8 format all python file in ``source code`` and ``tests`` dir.
"""
# repository direcotry
repo_dir = Path(__file__).parent.absolute()
# source code directory
source_dir = Path(repo_dir, package.__name__)
if source_dir.exists():
print("Source code locate at: '%s'." % source_dir)
print("Auto pep8 all python file ...")
source_dir.autopep8(**kwargs)
else:
print("Source code directory not found!")
# unittest code directory
unittest_dir = Path(repo_dir, "tests")
if unittest_dir.exists():
print("Unittest code locate at: '%s'." % unittest_dir)
print("Auto pep8 all python file ...")
unittest_dir.autopep8(**kwargs)
else:
print("Unittest code directory not found!")
print("Complete!")
|
python
|
def fixcode(**kwargs):
"""
auto pep8 format all python file in ``source code`` and ``tests`` dir.
"""
# repository direcotry
repo_dir = Path(__file__).parent.absolute()
# source code directory
source_dir = Path(repo_dir, package.__name__)
if source_dir.exists():
print("Source code locate at: '%s'." % source_dir)
print("Auto pep8 all python file ...")
source_dir.autopep8(**kwargs)
else:
print("Source code directory not found!")
# unittest code directory
unittest_dir = Path(repo_dir, "tests")
if unittest_dir.exists():
print("Unittest code locate at: '%s'." % unittest_dir)
print("Auto pep8 all python file ...")
unittest_dir.autopep8(**kwargs)
else:
print("Unittest code directory not found!")
print("Complete!")
|
[
"def",
"fixcode",
"(",
"*",
"*",
"kwargs",
")",
":",
"# repository direcotry",
"repo_dir",
"=",
"Path",
"(",
"__file__",
")",
".",
"parent",
".",
"absolute",
"(",
")",
"# source code directory",
"source_dir",
"=",
"Path",
"(",
"repo_dir",
",",
"package",
".",
"__name__",
")",
"if",
"source_dir",
".",
"exists",
"(",
")",
":",
"print",
"(",
"\"Source code locate at: '%s'.\"",
"%",
"source_dir",
")",
"print",
"(",
"\"Auto pep8 all python file ...\"",
")",
"source_dir",
".",
"autopep8",
"(",
"*",
"*",
"kwargs",
")",
"else",
":",
"print",
"(",
"\"Source code directory not found!\"",
")",
"# unittest code directory",
"unittest_dir",
"=",
"Path",
"(",
"repo_dir",
",",
"\"tests\"",
")",
"if",
"unittest_dir",
".",
"exists",
"(",
")",
":",
"print",
"(",
"\"Unittest code locate at: '%s'.\"",
"%",
"unittest_dir",
")",
"print",
"(",
"\"Auto pep8 all python file ...\"",
")",
"unittest_dir",
".",
"autopep8",
"(",
"*",
"*",
"kwargs",
")",
"else",
":",
"print",
"(",
"\"Unittest code directory not found!\"",
")",
"print",
"(",
"\"Complete!\"",
")"
] |
auto pep8 format all python file in ``source code`` and ``tests`` dir.
|
[
"auto",
"pep8",
"format",
"all",
"python",
"file",
"in",
"source",
"code",
"and",
"tests",
"dir",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/fixcode.py#L13-L39
|
16,201
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/pkg/prettytable/prettytable.py
|
PrettyTable._get_rows
|
def _get_rows(self, options):
"""Return only those data rows that should be printed, based on slicing and sorting.
Arguments:
options - dictionary of option settings."""
if options["oldsortslice"]:
rows = copy.deepcopy(self._rows[options["start"]:options["end"]])
else:
rows = copy.deepcopy(self._rows)
# Sort
if options["sortby"]:
sortindex = self._field_names.index(options["sortby"])
# Decorate
rows = [[row[sortindex]] + row for row in rows]
# Sort
rows.sort(reverse=options["reversesort"], key=options["sort_key"])
# Undecorate
rows = [row[1:] for row in rows]
# Slice if necessary
if not options["oldsortslice"]:
rows = rows[options["start"]:options["end"]]
return rows
|
python
|
def _get_rows(self, options):
"""Return only those data rows that should be printed, based on slicing and sorting.
Arguments:
options - dictionary of option settings."""
if options["oldsortslice"]:
rows = copy.deepcopy(self._rows[options["start"]:options["end"]])
else:
rows = copy.deepcopy(self._rows)
# Sort
if options["sortby"]:
sortindex = self._field_names.index(options["sortby"])
# Decorate
rows = [[row[sortindex]] + row for row in rows]
# Sort
rows.sort(reverse=options["reversesort"], key=options["sort_key"])
# Undecorate
rows = [row[1:] for row in rows]
# Slice if necessary
if not options["oldsortslice"]:
rows = rows[options["start"]:options["end"]]
return rows
|
[
"def",
"_get_rows",
"(",
"self",
",",
"options",
")",
":",
"if",
"options",
"[",
"\"oldsortslice\"",
"]",
":",
"rows",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_rows",
"[",
"options",
"[",
"\"start\"",
"]",
":",
"options",
"[",
"\"end\"",
"]",
"]",
")",
"else",
":",
"rows",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_rows",
")",
"# Sort",
"if",
"options",
"[",
"\"sortby\"",
"]",
":",
"sortindex",
"=",
"self",
".",
"_field_names",
".",
"index",
"(",
"options",
"[",
"\"sortby\"",
"]",
")",
"# Decorate",
"rows",
"=",
"[",
"[",
"row",
"[",
"sortindex",
"]",
"]",
"+",
"row",
"for",
"row",
"in",
"rows",
"]",
"# Sort",
"rows",
".",
"sort",
"(",
"reverse",
"=",
"options",
"[",
"\"reversesort\"",
"]",
",",
"key",
"=",
"options",
"[",
"\"sort_key\"",
"]",
")",
"# Undecorate",
"rows",
"=",
"[",
"row",
"[",
"1",
":",
"]",
"for",
"row",
"in",
"rows",
"]",
"# Slice if necessary",
"if",
"not",
"options",
"[",
"\"oldsortslice\"",
"]",
":",
"rows",
"=",
"rows",
"[",
"options",
"[",
"\"start\"",
"]",
":",
"options",
"[",
"\"end\"",
"]",
"]",
"return",
"rows"
] |
Return only those data rows that should be printed, based on slicing and sorting.
Arguments:
options - dictionary of option settings.
|
[
"Return",
"only",
"those",
"data",
"rows",
"that",
"should",
"be",
"printed",
"based",
"on",
"slicing",
"and",
"sorting",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/pkg/prettytable/prettytable.py#L1080-L1106
|
16,202
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/engine_creator.py
|
create_postgresql_pg8000
|
def create_postgresql_pg8000(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a postgresql database using pg8000.
"""
return create_engine(
_create_postgresql_pg8000(username, password, host, port, database),
**kwargs
)
|
python
|
def create_postgresql_pg8000(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a postgresql database using pg8000.
"""
return create_engine(
_create_postgresql_pg8000(username, password, host, port, database),
**kwargs
)
|
[
"def",
"create_postgresql_pg8000",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"return",
"create_engine",
"(",
"_create_postgresql_pg8000",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
")",
",",
"*",
"*",
"kwargs",
")"
] |
create an engine connected to a postgresql database using pg8000.
|
[
"create",
"an",
"engine",
"connected",
"to",
"a",
"postgresql",
"database",
"using",
"pg8000",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/engine_creator.py#L94-L101
|
16,203
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/engine_creator.py
|
create_postgresql_pygresql
|
def create_postgresql_pygresql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a postgresql database using pygresql.
"""
return create_engine(
_create_postgresql_pygresql(username, password, host, port, database),
**kwargs
)
|
python
|
def create_postgresql_pygresql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a postgresql database using pygresql.
"""
return create_engine(
_create_postgresql_pygresql(username, password, host, port, database),
**kwargs
)
|
[
"def",
"create_postgresql_pygresql",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"return",
"create_engine",
"(",
"_create_postgresql_pygresql",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
")",
",",
"*",
"*",
"kwargs",
")"
] |
create an engine connected to a postgresql database using pygresql.
|
[
"create",
"an",
"engine",
"connected",
"to",
"a",
"postgresql",
"database",
"using",
"pygresql",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/engine_creator.py#L110-L117
|
16,204
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/engine_creator.py
|
create_postgresql_psycopg2cffi
|
def create_postgresql_psycopg2cffi(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a postgresql database using psycopg2cffi.
"""
return create_engine(
_create_postgresql_psycopg2cffi(
username, password, host, port, database),
**kwargs
)
|
python
|
def create_postgresql_psycopg2cffi(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a postgresql database using psycopg2cffi.
"""
return create_engine(
_create_postgresql_psycopg2cffi(
username, password, host, port, database),
**kwargs
)
|
[
"def",
"create_postgresql_psycopg2cffi",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"return",
"create_engine",
"(",
"_create_postgresql_psycopg2cffi",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
")",
",",
"*",
"*",
"kwargs",
")"
] |
create an engine connected to a postgresql database using psycopg2cffi.
|
[
"create",
"an",
"engine",
"connected",
"to",
"a",
"postgresql",
"database",
"using",
"psycopg2cffi",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/engine_creator.py#L126-L134
|
16,205
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/engine_creator.py
|
create_postgresql_pypostgresql
|
def create_postgresql_pypostgresql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a postgresql database using pypostgresql.
"""
return create_engine(
_create_postgresql_pypostgresql(
username, password, host, port, database),
**kwargs
)
|
python
|
def create_postgresql_pypostgresql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a postgresql database using pypostgresql.
"""
return create_engine(
_create_postgresql_pypostgresql(
username, password, host, port, database),
**kwargs
)
|
[
"def",
"create_postgresql_pypostgresql",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"return",
"create_engine",
"(",
"_create_postgresql_pypostgresql",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
")",
",",
"*",
"*",
"kwargs",
")"
] |
create an engine connected to a postgresql database using pypostgresql.
|
[
"create",
"an",
"engine",
"connected",
"to",
"a",
"postgresql",
"database",
"using",
"pypostgresql",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/engine_creator.py#L143-L151
|
16,206
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/engine_creator.py
|
create_mysql_mysqlconnector
|
def create_mysql_mysqlconnector(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mysql database using mysqlconnector.
"""
return create_engine(
_create_mysql_mysqlconnector(username, password, host, port, database),
**kwargs
)
|
python
|
def create_mysql_mysqlconnector(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mysql database using mysqlconnector.
"""
return create_engine(
_create_mysql_mysqlconnector(username, password, host, port, database),
**kwargs
)
|
[
"def",
"create_mysql_mysqlconnector",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"return",
"create_engine",
"(",
"_create_mysql_mysqlconnector",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
")",
",",
"*",
"*",
"kwargs",
")"
] |
create an engine connected to a mysql database using mysqlconnector.
|
[
"create",
"an",
"engine",
"connected",
"to",
"a",
"mysql",
"database",
"using",
"mysqlconnector",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/engine_creator.py#L194-L201
|
16,207
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/engine_creator.py
|
create_mysql_oursql
|
def create_mysql_oursql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mysql database using oursql.
"""
return create_engine(
_create_mysql_oursql(username, password, host, port, database),
**kwargs
)
|
python
|
def create_mysql_oursql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mysql database using oursql.
"""
return create_engine(
_create_mysql_oursql(username, password, host, port, database),
**kwargs
)
|
[
"def",
"create_mysql_oursql",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"return",
"create_engine",
"(",
"_create_mysql_oursql",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
")",
",",
"*",
"*",
"kwargs",
")"
] |
create an engine connected to a mysql database using oursql.
|
[
"create",
"an",
"engine",
"connected",
"to",
"a",
"mysql",
"database",
"using",
"oursql",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/engine_creator.py#L210-L217
|
16,208
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/engine_creator.py
|
create_mysql_pymysql
|
def create_mysql_pymysql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mysql database using pymysql.
"""
return create_engine(
_create_mysql_pymysql(username, password, host, port, database),
**kwargs
)
|
python
|
def create_mysql_pymysql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mysql database using pymysql.
"""
return create_engine(
_create_mysql_pymysql(username, password, host, port, database),
**kwargs
)
|
[
"def",
"create_mysql_pymysql",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"return",
"create_engine",
"(",
"_create_mysql_pymysql",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
")",
",",
"*",
"*",
"kwargs",
")"
] |
create an engine connected to a mysql database using pymysql.
|
[
"create",
"an",
"engine",
"connected",
"to",
"a",
"mysql",
"database",
"using",
"pymysql",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/engine_creator.py#L226-L233
|
16,209
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/engine_creator.py
|
create_mysql_cymysql
|
def create_mysql_cymysql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mysql database using cymysql.
"""
return create_engine(
_create_mysql_cymysql(username, password, host, port, database),
**kwargs
)
|
python
|
def create_mysql_cymysql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mysql database using cymysql.
"""
return create_engine(
_create_mysql_cymysql(username, password, host, port, database),
**kwargs
)
|
[
"def",
"create_mysql_cymysql",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"return",
"create_engine",
"(",
"_create_mysql_cymysql",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
")",
",",
"*",
"*",
"kwargs",
")"
] |
create an engine connected to a mysql database using cymysql.
|
[
"create",
"an",
"engine",
"connected",
"to",
"a",
"mysql",
"database",
"using",
"cymysql",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/engine_creator.py#L242-L249
|
16,210
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/engine_creator.py
|
create_mssql_pyodbc
|
def create_mssql_pyodbc(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mssql database using pyodbc.
"""
return create_engine(
_create_mssql_pyodbc(username, password, host, port, database),
**kwargs
)
|
python
|
def create_mssql_pyodbc(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mssql database using pyodbc.
"""
return create_engine(
_create_mssql_pyodbc(username, password, host, port, database),
**kwargs
)
|
[
"def",
"create_mssql_pyodbc",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"return",
"create_engine",
"(",
"_create_mssql_pyodbc",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
")",
",",
"*",
"*",
"kwargs",
")"
] |
create an engine connected to a mssql database using pyodbc.
|
[
"create",
"an",
"engine",
"connected",
"to",
"a",
"mssql",
"database",
"using",
"pyodbc",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/engine_creator.py#L294-L301
|
16,211
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/engine_creator.py
|
create_mssql_pymssql
|
def create_mssql_pymssql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mssql database using pymssql.
"""
return create_engine(
_create_mssql_pymssql(username, password, host, port, database),
**kwargs
)
|
python
|
def create_mssql_pymssql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mssql database using pymssql.
"""
return create_engine(
_create_mssql_pymssql(username, password, host, port, database),
**kwargs
)
|
[
"def",
"create_mssql_pymssql",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"return",
"create_engine",
"(",
"_create_mssql_pymssql",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
")",
",",
"*",
"*",
"kwargs",
")"
] |
create an engine connected to a mssql database using pymssql.
|
[
"create",
"an",
"engine",
"connected",
"to",
"a",
"mssql",
"database",
"using",
"pymssql",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/engine_creator.py#L310-L317
|
16,212
|
MacHu-GWU/uszipcode-project
|
dataset/step2_merge_zipcode_data.py
|
titleize
|
def titleize(text):
"""Capitalizes all the words and replaces some characters in the string
to create a nicer looking title.
"""
if len(text) == 0: # if empty string, return it
return text
else:
text = text.lower() # lower all char
# delete redundant empty space
chunks = [chunk[0].upper() + chunk[1:] for chunk in text.split(" ") if len(chunk) >= 1]
return " ".join(chunks)
|
python
|
def titleize(text):
"""Capitalizes all the words and replaces some characters in the string
to create a nicer looking title.
"""
if len(text) == 0: # if empty string, return it
return text
else:
text = text.lower() # lower all char
# delete redundant empty space
chunks = [chunk[0].upper() + chunk[1:] for chunk in text.split(" ") if len(chunk) >= 1]
return " ".join(chunks)
|
[
"def",
"titleize",
"(",
"text",
")",
":",
"if",
"len",
"(",
"text",
")",
"==",
"0",
":",
"# if empty string, return it",
"return",
"text",
"else",
":",
"text",
"=",
"text",
".",
"lower",
"(",
")",
"# lower all char",
"# delete redundant empty space ",
"chunks",
"=",
"[",
"chunk",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"chunk",
"[",
"1",
":",
"]",
"for",
"chunk",
"in",
"text",
".",
"split",
"(",
"\" \"",
")",
"if",
"len",
"(",
"chunk",
")",
">=",
"1",
"]",
"return",
"\" \"",
".",
"join",
"(",
"chunks",
")"
] |
Capitalizes all the words and replaces some characters in the string
to create a nicer looking title.
|
[
"Capitalizes",
"all",
"the",
"words",
"and",
"replaces",
"some",
"characters",
"in",
"the",
"string",
"to",
"create",
"a",
"nicer",
"looking",
"title",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/dataset/step2_merge_zipcode_data.py#L14-L24
|
16,213
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/utils.py
|
grouper_list
|
def grouper_list(l, n):
"""Evenly divide list into fixed-length piece, no filled value if chunk
size smaller than fixed-length.
Example::
>>> list(grouper(range(10), n=3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
**中文文档**
将一个列表按照尺寸n, 依次打包输出, 有多少输出多少, 并不强制填充包的大小到n。
下列实现是按照性能从高到低进行排列的:
- 方法1: 建立一个counter, 在向chunk中添加元素时, 同时将counter与n比较, 如果一致
则yield。然后在最后将剩余的item视情况yield。
- 方法2: 建立一个list, 每次添加一个元素, 并检查size。
- 方法3: 调用grouper()函数, 然后对里面的None元素进行清理。
"""
chunk = list()
counter = 0
for item in l:
counter += 1
chunk.append(item)
if counter == n:
yield chunk
chunk = list()
counter = 0
if len(chunk) > 0:
yield chunk
|
python
|
def grouper_list(l, n):
"""Evenly divide list into fixed-length piece, no filled value if chunk
size smaller than fixed-length.
Example::
>>> list(grouper(range(10), n=3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
**中文文档**
将一个列表按照尺寸n, 依次打包输出, 有多少输出多少, 并不强制填充包的大小到n。
下列实现是按照性能从高到低进行排列的:
- 方法1: 建立一个counter, 在向chunk中添加元素时, 同时将counter与n比较, 如果一致
则yield。然后在最后将剩余的item视情况yield。
- 方法2: 建立一个list, 每次添加一个元素, 并检查size。
- 方法3: 调用grouper()函数, 然后对里面的None元素进行清理。
"""
chunk = list()
counter = 0
for item in l:
counter += 1
chunk.append(item)
if counter == n:
yield chunk
chunk = list()
counter = 0
if len(chunk) > 0:
yield chunk
|
[
"def",
"grouper_list",
"(",
"l",
",",
"n",
")",
":",
"chunk",
"=",
"list",
"(",
")",
"counter",
"=",
"0",
"for",
"item",
"in",
"l",
":",
"counter",
"+=",
"1",
"chunk",
".",
"append",
"(",
"item",
")",
"if",
"counter",
"==",
"n",
":",
"yield",
"chunk",
"chunk",
"=",
"list",
"(",
")",
"counter",
"=",
"0",
"if",
"len",
"(",
"chunk",
")",
">",
"0",
":",
"yield",
"chunk"
] |
Evenly divide list into fixed-length piece, no filled value if chunk
size smaller than fixed-length.
Example::
>>> list(grouper(range(10), n=3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
**中文文档**
将一个列表按照尺寸n, 依次打包输出, 有多少输出多少, 并不强制填充包的大小到n。
下列实现是按照性能从高到低进行排列的:
- 方法1: 建立一个counter, 在向chunk中添加元素时, 同时将counter与n比较, 如果一致
则yield。然后在最后将剩余的item视情况yield。
- 方法2: 建立一个list, 每次添加一个元素, 并检查size。
- 方法3: 调用grouper()函数, 然后对里面的None元素进行清理。
|
[
"Evenly",
"divide",
"list",
"into",
"fixed",
"-",
"length",
"piece",
"no",
"filled",
"value",
"if",
"chunk",
"size",
"smaller",
"than",
"fixed",
"-",
"length",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/utils.py#L16-L46
|
16,214
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/utils.py
|
convert_query_to_sql_statement
|
def convert_query_to_sql_statement(query):
"""
Convert a Query object created from orm query, into executable sql statement.
:param query: :class:`sqlalchemy.orm.Query`
:return: :class:`sqlalchemy.sql.selectable.Select`
"""
context = query._compile_context()
context.statement.use_labels = False
return context.statement
|
python
|
def convert_query_to_sql_statement(query):
"""
Convert a Query object created from orm query, into executable sql statement.
:param query: :class:`sqlalchemy.orm.Query`
:return: :class:`sqlalchemy.sql.selectable.Select`
"""
context = query._compile_context()
context.statement.use_labels = False
return context.statement
|
[
"def",
"convert_query_to_sql_statement",
"(",
"query",
")",
":",
"context",
"=",
"query",
".",
"_compile_context",
"(",
")",
"context",
".",
"statement",
".",
"use_labels",
"=",
"False",
"return",
"context",
".",
"statement"
] |
Convert a Query object created from orm query, into executable sql statement.
:param query: :class:`sqlalchemy.orm.Query`
:return: :class:`sqlalchemy.sql.selectable.Select`
|
[
"Convert",
"a",
"Query",
"object",
"created",
"from",
"orm",
"query",
"into",
"executable",
"sql",
"statement",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/utils.py#L49-L59
|
16,215
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/utils.py
|
execute_query_return_result_proxy
|
def execute_query_return_result_proxy(query):
"""
Execute a query, yield result proxy.
:param query: :class:`sqlalchemy.orm.Query`,
has to be created from ``session.query(Object)``
:return: :class:`sqlalchemy.engine.result.ResultProxy`
"""
context = query._compile_context()
context.statement.use_labels = False
if query._autoflush and not query._populate_existing:
query.session._autoflush()
conn = query._get_bind_args(
context,
query._connection_from_session,
close_with_result=True)
return conn.execute(context.statement, query._params)
|
python
|
def execute_query_return_result_proxy(query):
"""
Execute a query, yield result proxy.
:param query: :class:`sqlalchemy.orm.Query`,
has to be created from ``session.query(Object)``
:return: :class:`sqlalchemy.engine.result.ResultProxy`
"""
context = query._compile_context()
context.statement.use_labels = False
if query._autoflush and not query._populate_existing:
query.session._autoflush()
conn = query._get_bind_args(
context,
query._connection_from_session,
close_with_result=True)
return conn.execute(context.statement, query._params)
|
[
"def",
"execute_query_return_result_proxy",
"(",
"query",
")",
":",
"context",
"=",
"query",
".",
"_compile_context",
"(",
")",
"context",
".",
"statement",
".",
"use_labels",
"=",
"False",
"if",
"query",
".",
"_autoflush",
"and",
"not",
"query",
".",
"_populate_existing",
":",
"query",
".",
"session",
".",
"_autoflush",
"(",
")",
"conn",
"=",
"query",
".",
"_get_bind_args",
"(",
"context",
",",
"query",
".",
"_connection_from_session",
",",
"close_with_result",
"=",
"True",
")",
"return",
"conn",
".",
"execute",
"(",
"context",
".",
"statement",
",",
"query",
".",
"_params",
")"
] |
Execute a query, yield result proxy.
:param query: :class:`sqlalchemy.orm.Query`,
has to be created from ``session.query(Object)``
:return: :class:`sqlalchemy.engine.result.ResultProxy`
|
[
"Execute",
"a",
"query",
"yield",
"result",
"proxy",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/utils.py#L62-L81
|
16,216
|
MacHu-GWU/uszipcode-project
|
uszipcode/search.py
|
SearchEngine.find_state
|
def find_state(self, state, best_match=True, min_similarity=70):
"""
Fuzzy search correct state.
:param best_match: bool, when True, only the best matched state
will be return. otherwise, will return all matching states.
"""
result_state_short_list = list()
# check if it is a abbreviate name
if state.upper() in STATE_ABBR_SHORT_TO_LONG:
result_state_short_list.append(state.upper())
# if not, find out what is the state that user looking for
else:
if best_match:
state_long, confidence = extractOne(state, self.state_list)
if confidence >= min_similarity:
result_state_short_list.append(
STATE_ABBR_LONG_TO_SHORT[state_long])
else:
for state_long, confidence in extract(state, self.state_list):
if confidence >= min_similarity:
result_state_short_list.append(
STATE_ABBR_LONG_TO_SHORT[state_long])
if len(result_state_short_list) == 0:
message = ("'%s' is not a valid state name, use 2 letter "
"short name or correct full name please.")
raise ValueError(message % state)
return result_state_short_list
|
python
|
def find_state(self, state, best_match=True, min_similarity=70):
"""
Fuzzy search correct state.
:param best_match: bool, when True, only the best matched state
will be return. otherwise, will return all matching states.
"""
result_state_short_list = list()
# check if it is a abbreviate name
if state.upper() in STATE_ABBR_SHORT_TO_LONG:
result_state_short_list.append(state.upper())
# if not, find out what is the state that user looking for
else:
if best_match:
state_long, confidence = extractOne(state, self.state_list)
if confidence >= min_similarity:
result_state_short_list.append(
STATE_ABBR_LONG_TO_SHORT[state_long])
else:
for state_long, confidence in extract(state, self.state_list):
if confidence >= min_similarity:
result_state_short_list.append(
STATE_ABBR_LONG_TO_SHORT[state_long])
if len(result_state_short_list) == 0:
message = ("'%s' is not a valid state name, use 2 letter "
"short name or correct full name please.")
raise ValueError(message % state)
return result_state_short_list
|
[
"def",
"find_state",
"(",
"self",
",",
"state",
",",
"best_match",
"=",
"True",
",",
"min_similarity",
"=",
"70",
")",
":",
"result_state_short_list",
"=",
"list",
"(",
")",
"# check if it is a abbreviate name",
"if",
"state",
".",
"upper",
"(",
")",
"in",
"STATE_ABBR_SHORT_TO_LONG",
":",
"result_state_short_list",
".",
"append",
"(",
"state",
".",
"upper",
"(",
")",
")",
"# if not, find out what is the state that user looking for",
"else",
":",
"if",
"best_match",
":",
"state_long",
",",
"confidence",
"=",
"extractOne",
"(",
"state",
",",
"self",
".",
"state_list",
")",
"if",
"confidence",
">=",
"min_similarity",
":",
"result_state_short_list",
".",
"append",
"(",
"STATE_ABBR_LONG_TO_SHORT",
"[",
"state_long",
"]",
")",
"else",
":",
"for",
"state_long",
",",
"confidence",
"in",
"extract",
"(",
"state",
",",
"self",
".",
"state_list",
")",
":",
"if",
"confidence",
">=",
"min_similarity",
":",
"result_state_short_list",
".",
"append",
"(",
"STATE_ABBR_LONG_TO_SHORT",
"[",
"state_long",
"]",
")",
"if",
"len",
"(",
"result_state_short_list",
")",
"==",
"0",
":",
"message",
"=",
"(",
"\"'%s' is not a valid state name, use 2 letter \"",
"\"short name or correct full name please.\"",
")",
"raise",
"ValueError",
"(",
"message",
"%",
"state",
")",
"return",
"result_state_short_list"
] |
Fuzzy search correct state.
:param best_match: bool, when True, only the best matched state
will be return. otherwise, will return all matching states.
|
[
"Fuzzy",
"search",
"correct",
"state",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/search.py#L178-L209
|
16,217
|
MacHu-GWU/uszipcode-project
|
uszipcode/search.py
|
SearchEngine.find_city
|
def find_city(self, city, state=None, best_match=True, min_similarity=70):
"""
Fuzzy search correct city.
:param city: city name.
:param state: search city in specified state.
:param best_match: bool, when True, only the best matched city
will return. otherwise, will return all matching cities.
**中文文档**
如果给定了state, 则只在指定的state里的城市中寻找, 否则, 在全国所有的城市中寻找。
"""
# find out what is the city that user looking for
if state:
state_sort = self.find_state(state, best_match=True)[0]
city_pool = self.state_to_city_mapper[state_sort.upper()]
else:
city_pool = self.city_list
result_city_list = list()
if best_match:
city, confidence = extractOne(city, city_pool)
if confidence >= min_similarity:
result_city_list.append(city)
else:
for city, confidence in extract(city, city_pool):
if confidence >= min_similarity:
result_city_list.append(city)
if len(result_city_list) == 0:
raise ValueError("'%s' is not a valid city name" % city)
return result_city_list
|
python
|
def find_city(self, city, state=None, best_match=True, min_similarity=70):
"""
Fuzzy search correct city.
:param city: city name.
:param state: search city in specified state.
:param best_match: bool, when True, only the best matched city
will return. otherwise, will return all matching cities.
**中文文档**
如果给定了state, 则只在指定的state里的城市中寻找, 否则, 在全国所有的城市中寻找。
"""
# find out what is the city that user looking for
if state:
state_sort = self.find_state(state, best_match=True)[0]
city_pool = self.state_to_city_mapper[state_sort.upper()]
else:
city_pool = self.city_list
result_city_list = list()
if best_match:
city, confidence = extractOne(city, city_pool)
if confidence >= min_similarity:
result_city_list.append(city)
else:
for city, confidence in extract(city, city_pool):
if confidence >= min_similarity:
result_city_list.append(city)
if len(result_city_list) == 0:
raise ValueError("'%s' is not a valid city name" % city)
return result_city_list
|
[
"def",
"find_city",
"(",
"self",
",",
"city",
",",
"state",
"=",
"None",
",",
"best_match",
"=",
"True",
",",
"min_similarity",
"=",
"70",
")",
":",
"# find out what is the city that user looking for",
"if",
"state",
":",
"state_sort",
"=",
"self",
".",
"find_state",
"(",
"state",
",",
"best_match",
"=",
"True",
")",
"[",
"0",
"]",
"city_pool",
"=",
"self",
".",
"state_to_city_mapper",
"[",
"state_sort",
".",
"upper",
"(",
")",
"]",
"else",
":",
"city_pool",
"=",
"self",
".",
"city_list",
"result_city_list",
"=",
"list",
"(",
")",
"if",
"best_match",
":",
"city",
",",
"confidence",
"=",
"extractOne",
"(",
"city",
",",
"city_pool",
")",
"if",
"confidence",
">=",
"min_similarity",
":",
"result_city_list",
".",
"append",
"(",
"city",
")",
"else",
":",
"for",
"city",
",",
"confidence",
"in",
"extract",
"(",
"city",
",",
"city_pool",
")",
":",
"if",
"confidence",
">=",
"min_similarity",
":",
"result_city_list",
".",
"append",
"(",
"city",
")",
"if",
"len",
"(",
"result_city_list",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"'%s' is not a valid city name\"",
"%",
"city",
")",
"return",
"result_city_list"
] |
Fuzzy search correct city.
:param city: city name.
:param state: search city in specified state.
:param best_match: bool, when True, only the best matched city
will return. otherwise, will return all matching cities.
**中文文档**
如果给定了state, 则只在指定的state里的城市中寻找, 否则, 在全国所有的城市中寻找。
|
[
"Fuzzy",
"search",
"correct",
"city",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/search.py#L211-L245
|
16,218
|
MacHu-GWU/uszipcode-project
|
uszipcode/search.py
|
SearchEngine._resolve_sort_by
|
def _resolve_sort_by(sort_by, flag_radius_query):
"""
Result ``sort_by`` argument.
:param sort_by: str, or sqlalchemy ORM attribute.
:param flag_radius_query:
:return:
"""
if sort_by is None:
if flag_radius_query:
sort_by = SORT_BY_DIST
elif isinstance(sort_by, string_types):
if sort_by.lower() == SORT_BY_DIST:
if flag_radius_query is False:
msg = "`sort_by` arg can be 'dist' only under distance based query!"
raise ValueError(msg)
sort_by = SORT_BY_DIST
elif sort_by not in SimpleZipcode.__table__.columns:
msg = "`sort_by` arg has to be one of the Zipcode attribute or 'dist'!"
raise ValueError(msg)
else:
sort_by = sort_by.name
return sort_by
|
python
|
def _resolve_sort_by(sort_by, flag_radius_query):
"""
Result ``sort_by`` argument.
:param sort_by: str, or sqlalchemy ORM attribute.
:param flag_radius_query:
:return:
"""
if sort_by is None:
if flag_radius_query:
sort_by = SORT_BY_DIST
elif isinstance(sort_by, string_types):
if sort_by.lower() == SORT_BY_DIST:
if flag_radius_query is False:
msg = "`sort_by` arg can be 'dist' only under distance based query!"
raise ValueError(msg)
sort_by = SORT_BY_DIST
elif sort_by not in SimpleZipcode.__table__.columns:
msg = "`sort_by` arg has to be one of the Zipcode attribute or 'dist'!"
raise ValueError(msg)
else:
sort_by = sort_by.name
return sort_by
|
[
"def",
"_resolve_sort_by",
"(",
"sort_by",
",",
"flag_radius_query",
")",
":",
"if",
"sort_by",
"is",
"None",
":",
"if",
"flag_radius_query",
":",
"sort_by",
"=",
"SORT_BY_DIST",
"elif",
"isinstance",
"(",
"sort_by",
",",
"string_types",
")",
":",
"if",
"sort_by",
".",
"lower",
"(",
")",
"==",
"SORT_BY_DIST",
":",
"if",
"flag_radius_query",
"is",
"False",
":",
"msg",
"=",
"\"`sort_by` arg can be 'dist' only under distance based query!\"",
"raise",
"ValueError",
"(",
"msg",
")",
"sort_by",
"=",
"SORT_BY_DIST",
"elif",
"sort_by",
"not",
"in",
"SimpleZipcode",
".",
"__table__",
".",
"columns",
":",
"msg",
"=",
"\"`sort_by` arg has to be one of the Zipcode attribute or 'dist'!\"",
"raise",
"ValueError",
"(",
"msg",
")",
"else",
":",
"sort_by",
"=",
"sort_by",
".",
"name",
"return",
"sort_by"
] |
Result ``sort_by`` argument.
:param sort_by: str, or sqlalchemy ORM attribute.
:param flag_radius_query:
:return:
|
[
"Result",
"sort_by",
"argument",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/search.py#L248-L271
|
16,219
|
MacHu-GWU/uszipcode-project
|
uszipcode/search.py
|
SearchEngine.by_zipcode
|
def by_zipcode(self,
zipcode,
zipcode_type=None,
zero_padding=True):
"""
Search zipcode by exact 5 digits zipcode. No zero padding is needed.
:param zipcode: int or str, the zipcode will be automatically
zero padding to 5 digits.
:param zipcode_type: str or :class`~uszipcode.model.ZipcodeType` attribute.
by default, it returns any zipcode type.
:param zero_padding: bool, toggle on and off automatic zero padding.
"""
if zero_padding:
zipcode = str(zipcode).zfill(5)
else: # pragma: no cover
zipcode = str(zipcode)
res = self.query(
zipcode=zipcode,
sort_by=None,
returns=1,
zipcode_type=zipcode_type,
)
if len(res):
return res[0]
else:
return self.zip_klass()
|
python
|
def by_zipcode(self,
zipcode,
zipcode_type=None,
zero_padding=True):
"""
Search zipcode by exact 5 digits zipcode. No zero padding is needed.
:param zipcode: int or str, the zipcode will be automatically
zero padding to 5 digits.
:param zipcode_type: str or :class`~uszipcode.model.ZipcodeType` attribute.
by default, it returns any zipcode type.
:param zero_padding: bool, toggle on and off automatic zero padding.
"""
if zero_padding:
zipcode = str(zipcode).zfill(5)
else: # pragma: no cover
zipcode = str(zipcode)
res = self.query(
zipcode=zipcode,
sort_by=None,
returns=1,
zipcode_type=zipcode_type,
)
if len(res):
return res[0]
else:
return self.zip_klass()
|
[
"def",
"by_zipcode",
"(",
"self",
",",
"zipcode",
",",
"zipcode_type",
"=",
"None",
",",
"zero_padding",
"=",
"True",
")",
":",
"if",
"zero_padding",
":",
"zipcode",
"=",
"str",
"(",
"zipcode",
")",
".",
"zfill",
"(",
"5",
")",
"else",
":",
"# pragma: no cover",
"zipcode",
"=",
"str",
"(",
"zipcode",
")",
"res",
"=",
"self",
".",
"query",
"(",
"zipcode",
"=",
"zipcode",
",",
"sort_by",
"=",
"None",
",",
"returns",
"=",
"1",
",",
"zipcode_type",
"=",
"zipcode_type",
",",
")",
"if",
"len",
"(",
"res",
")",
":",
"return",
"res",
"[",
"0",
"]",
"else",
":",
"return",
"self",
".",
"zip_klass",
"(",
")"
] |
Search zipcode by exact 5 digits zipcode. No zero padding is needed.
:param zipcode: int or str, the zipcode will be automatically
zero padding to 5 digits.
:param zipcode_type: str or :class`~uszipcode.model.ZipcodeType` attribute.
by default, it returns any zipcode type.
:param zero_padding: bool, toggle on and off automatic zero padding.
|
[
"Search",
"zipcode",
"by",
"exact",
"5",
"digits",
"zipcode",
".",
"No",
"zero",
"padding",
"is",
"needed",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/search.py#L536-L563
|
16,220
|
MacHu-GWU/uszipcode-project
|
uszipcode/search.py
|
SearchEngine.by_prefix
|
def by_prefix(self,
prefix,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.zipcode.name,
ascending=True,
returns=DEFAULT_LIMIT):
"""
Search zipcode information by first N digits.
Returns multiple results.
"""
return self.query(
prefix=prefix,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
python
|
def by_prefix(self,
prefix,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.zipcode.name,
ascending=True,
returns=DEFAULT_LIMIT):
"""
Search zipcode information by first N digits.
Returns multiple results.
"""
return self.query(
prefix=prefix,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
[
"def",
"by_prefix",
"(",
"self",
",",
"prefix",
",",
"zipcode_type",
"=",
"ZipcodeType",
".",
"Standard",
",",
"sort_by",
"=",
"SimpleZipcode",
".",
"zipcode",
".",
"name",
",",
"ascending",
"=",
"True",
",",
"returns",
"=",
"DEFAULT_LIMIT",
")",
":",
"return",
"self",
".",
"query",
"(",
"prefix",
"=",
"prefix",
",",
"sort_by",
"=",
"sort_by",
",",
"zipcode_type",
"=",
"zipcode_type",
",",
"ascending",
"=",
"ascending",
",",
"returns",
"=",
"returns",
",",
")"
] |
Search zipcode information by first N digits.
Returns multiple results.
|
[
"Search",
"zipcode",
"information",
"by",
"first",
"N",
"digits",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/search.py#L565-L580
|
16,221
|
MacHu-GWU/uszipcode-project
|
uszipcode/search.py
|
SearchEngine.by_pattern
|
def by_pattern(self,
pattern,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.zipcode.name,
ascending=True,
returns=DEFAULT_LIMIT):
"""
Search zipcode by wildcard.
Returns multiple results.
"""
return self.query(
pattern=pattern,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
python
|
def by_pattern(self,
pattern,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.zipcode.name,
ascending=True,
returns=DEFAULT_LIMIT):
"""
Search zipcode by wildcard.
Returns multiple results.
"""
return self.query(
pattern=pattern,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
[
"def",
"by_pattern",
"(",
"self",
",",
"pattern",
",",
"zipcode_type",
"=",
"ZipcodeType",
".",
"Standard",
",",
"sort_by",
"=",
"SimpleZipcode",
".",
"zipcode",
".",
"name",
",",
"ascending",
"=",
"True",
",",
"returns",
"=",
"DEFAULT_LIMIT",
")",
":",
"return",
"self",
".",
"query",
"(",
"pattern",
"=",
"pattern",
",",
"sort_by",
"=",
"sort_by",
",",
"zipcode_type",
"=",
"zipcode_type",
",",
"ascending",
"=",
"ascending",
",",
"returns",
"=",
"returns",
",",
")"
] |
Search zipcode by wildcard.
Returns multiple results.
|
[
"Search",
"zipcode",
"by",
"wildcard",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/search.py#L582-L597
|
16,222
|
MacHu-GWU/uszipcode-project
|
uszipcode/search.py
|
SearchEngine.by_state
|
def by_state(self,
state,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.zipcode.name,
ascending=True,
returns=DEFAULT_LIMIT):
"""
Search zipcode information by fuzzy State name.
My engine use fuzzy match and guess what is the state you want.
"""
return self.query(
state=state,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
python
|
def by_state(self,
state,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.zipcode.name,
ascending=True,
returns=DEFAULT_LIMIT):
"""
Search zipcode information by fuzzy State name.
My engine use fuzzy match and guess what is the state you want.
"""
return self.query(
state=state,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
[
"def",
"by_state",
"(",
"self",
",",
"state",
",",
"zipcode_type",
"=",
"ZipcodeType",
".",
"Standard",
",",
"sort_by",
"=",
"SimpleZipcode",
".",
"zipcode",
".",
"name",
",",
"ascending",
"=",
"True",
",",
"returns",
"=",
"DEFAULT_LIMIT",
")",
":",
"return",
"self",
".",
"query",
"(",
"state",
"=",
"state",
",",
"sort_by",
"=",
"sort_by",
",",
"zipcode_type",
"=",
"zipcode_type",
",",
"ascending",
"=",
"ascending",
",",
"returns",
"=",
"returns",
",",
")"
] |
Search zipcode information by fuzzy State name.
My engine use fuzzy match and guess what is the state you want.
|
[
"Search",
"zipcode",
"information",
"by",
"fuzzy",
"State",
"name",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/search.py#L616-L631
|
16,223
|
MacHu-GWU/uszipcode-project
|
uszipcode/search.py
|
SearchEngine.by_coordinates
|
def by_coordinates(self,
lat,
lng,
radius=25.0,
zipcode_type=ZipcodeType.Standard,
sort_by=SORT_BY_DIST,
ascending=True,
returns=DEFAULT_LIMIT):
"""
Search zipcode information near a coordinates on a map.
Returns multiple results.
:param lat: center latitude.
:param lng: center longitude.
:param radius: only returns zipcode within X miles from ``lat``, ``lng``.
**中文文档**
1. 计算出在中心坐标处, 每一经度和纬度分别代表多少miles.
2. 以给定坐标为中心, 画出一个矩形, 长宽分别为半径的2倍多一点, 找到该
矩形内所有的Zipcode.
3. 对这些Zipcode计算出他们的距离, 然后按照距离远近排序。距离超过我们
限定的半径的直接丢弃.
"""
return self.query(
lat=lat, lng=lng, radius=radius,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
python
|
def by_coordinates(self,
lat,
lng,
radius=25.0,
zipcode_type=ZipcodeType.Standard,
sort_by=SORT_BY_DIST,
ascending=True,
returns=DEFAULT_LIMIT):
"""
Search zipcode information near a coordinates on a map.
Returns multiple results.
:param lat: center latitude.
:param lng: center longitude.
:param radius: only returns zipcode within X miles from ``lat``, ``lng``.
**中文文档**
1. 计算出在中心坐标处, 每一经度和纬度分别代表多少miles.
2. 以给定坐标为中心, 画出一个矩形, 长宽分别为半径的2倍多一点, 找到该
矩形内所有的Zipcode.
3. 对这些Zipcode计算出他们的距离, 然后按照距离远近排序。距离超过我们
限定的半径的直接丢弃.
"""
return self.query(
lat=lat, lng=lng, radius=radius,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
[
"def",
"by_coordinates",
"(",
"self",
",",
"lat",
",",
"lng",
",",
"radius",
"=",
"25.0",
",",
"zipcode_type",
"=",
"ZipcodeType",
".",
"Standard",
",",
"sort_by",
"=",
"SORT_BY_DIST",
",",
"ascending",
"=",
"True",
",",
"returns",
"=",
"DEFAULT_LIMIT",
")",
":",
"return",
"self",
".",
"query",
"(",
"lat",
"=",
"lat",
",",
"lng",
"=",
"lng",
",",
"radius",
"=",
"radius",
",",
"sort_by",
"=",
"sort_by",
",",
"zipcode_type",
"=",
"zipcode_type",
",",
"ascending",
"=",
"ascending",
",",
"returns",
"=",
"returns",
",",
")"
] |
Search zipcode information near a coordinates on a map.
Returns multiple results.
:param lat: center latitude.
:param lng: center longitude.
:param radius: only returns zipcode within X miles from ``lat``, ``lng``.
**中文文档**
1. 计算出在中心坐标处, 每一经度和纬度分别代表多少miles.
2. 以给定坐标为中心, 画出一个矩形, 长宽分别为半径的2倍多一点, 找到该
矩形内所有的Zipcode.
3. 对这些Zipcode计算出他们的距离, 然后按照距离远近排序。距离超过我们
限定的半径的直接丢弃.
|
[
"Search",
"zipcode",
"information",
"near",
"a",
"coordinates",
"on",
"a",
"map",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/search.py#L652-L681
|
16,224
|
MacHu-GWU/uszipcode-project
|
uszipcode/search.py
|
SearchEngine.by_population
|
def by_population(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.population.name,
ascending=False,
returns=DEFAULT_LIMIT):
"""
Search zipcode information by population range.
"""
return self.query(
population_lower=lower,
population_upper=upper,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
python
|
def by_population(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.population.name,
ascending=False,
returns=DEFAULT_LIMIT):
"""
Search zipcode information by population range.
"""
return self.query(
population_lower=lower,
population_upper=upper,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
[
"def",
"by_population",
"(",
"self",
",",
"lower",
"=",
"-",
"1",
",",
"upper",
"=",
"2",
"**",
"31",
",",
"zipcode_type",
"=",
"ZipcodeType",
".",
"Standard",
",",
"sort_by",
"=",
"SimpleZipcode",
".",
"population",
".",
"name",
",",
"ascending",
"=",
"False",
",",
"returns",
"=",
"DEFAULT_LIMIT",
")",
":",
"return",
"self",
".",
"query",
"(",
"population_lower",
"=",
"lower",
",",
"population_upper",
"=",
"upper",
",",
"sort_by",
"=",
"sort_by",
",",
"zipcode_type",
"=",
"zipcode_type",
",",
"ascending",
"=",
"ascending",
",",
"returns",
"=",
"returns",
",",
")"
] |
Search zipcode information by population range.
|
[
"Search",
"zipcode",
"information",
"by",
"population",
"range",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/search.py#L683-L698
|
16,225
|
MacHu-GWU/uszipcode-project
|
uszipcode/search.py
|
SearchEngine.by_population_density
|
def by_population_density(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.population_density.name,
ascending=False,
returns=DEFAULT_LIMIT):
"""
Search zipcode information by population density range.
`population density` is `population per square miles on land`
"""
return self.query(
population_density_lower=lower,
population_density_upper=upper,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
python
|
def by_population_density(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.population_density.name,
ascending=False,
returns=DEFAULT_LIMIT):
"""
Search zipcode information by population density range.
`population density` is `population per square miles on land`
"""
return self.query(
population_density_lower=lower,
population_density_upper=upper,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
[
"def",
"by_population_density",
"(",
"self",
",",
"lower",
"=",
"-",
"1",
",",
"upper",
"=",
"2",
"**",
"31",
",",
"zipcode_type",
"=",
"ZipcodeType",
".",
"Standard",
",",
"sort_by",
"=",
"SimpleZipcode",
".",
"population_density",
".",
"name",
",",
"ascending",
"=",
"False",
",",
"returns",
"=",
"DEFAULT_LIMIT",
")",
":",
"return",
"self",
".",
"query",
"(",
"population_density_lower",
"=",
"lower",
",",
"population_density_upper",
"=",
"upper",
",",
"sort_by",
"=",
"sort_by",
",",
"zipcode_type",
"=",
"zipcode_type",
",",
"ascending",
"=",
"ascending",
",",
"returns",
"=",
"returns",
",",
")"
] |
Search zipcode information by population density range.
`population density` is `population per square miles on land`
|
[
"Search",
"zipcode",
"information",
"by",
"population",
"density",
"range",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/search.py#L700-L717
|
16,226
|
MacHu-GWU/uszipcode-project
|
uszipcode/search.py
|
SearchEngine.by_housing_units
|
def by_housing_units(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.housing_units.name,
ascending=False,
returns=DEFAULT_LIMIT):
"""
Search zipcode information by house of units.
"""
return self.query(
housing_units_lower=lower,
housing_units_upper=upper,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
python
|
def by_housing_units(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.housing_units.name,
ascending=False,
returns=DEFAULT_LIMIT):
"""
Search zipcode information by house of units.
"""
return self.query(
housing_units_lower=lower,
housing_units_upper=upper,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
[
"def",
"by_housing_units",
"(",
"self",
",",
"lower",
"=",
"-",
"1",
",",
"upper",
"=",
"2",
"**",
"31",
",",
"zipcode_type",
"=",
"ZipcodeType",
".",
"Standard",
",",
"sort_by",
"=",
"SimpleZipcode",
".",
"housing_units",
".",
"name",
",",
"ascending",
"=",
"False",
",",
"returns",
"=",
"DEFAULT_LIMIT",
")",
":",
"return",
"self",
".",
"query",
"(",
"housing_units_lower",
"=",
"lower",
",",
"housing_units_upper",
"=",
"upper",
",",
"sort_by",
"=",
"sort_by",
",",
"zipcode_type",
"=",
"zipcode_type",
",",
"ascending",
"=",
"ascending",
",",
"returns",
"=",
"returns",
",",
")"
] |
Search zipcode information by house of units.
|
[
"Search",
"zipcode",
"information",
"by",
"house",
"of",
"units",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/search.py#L753-L768
|
16,227
|
MacHu-GWU/uszipcode-project
|
uszipcode/search.py
|
SearchEngine.by_occupied_housing_units
|
def by_occupied_housing_units(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.occupied_housing_units.name,
ascending=False,
returns=DEFAULT_LIMIT):
"""
Search zipcode information by occupied house of units.
"""
return self.query(
occupied_housing_units_lower=lower,
occupied_housing_units_upper=upper,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
python
|
def by_occupied_housing_units(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.occupied_housing_units.name,
ascending=False,
returns=DEFAULT_LIMIT):
"""
Search zipcode information by occupied house of units.
"""
return self.query(
occupied_housing_units_lower=lower,
occupied_housing_units_upper=upper,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
[
"def",
"by_occupied_housing_units",
"(",
"self",
",",
"lower",
"=",
"-",
"1",
",",
"upper",
"=",
"2",
"**",
"31",
",",
"zipcode_type",
"=",
"ZipcodeType",
".",
"Standard",
",",
"sort_by",
"=",
"SimpleZipcode",
".",
"occupied_housing_units",
".",
"name",
",",
"ascending",
"=",
"False",
",",
"returns",
"=",
"DEFAULT_LIMIT",
")",
":",
"return",
"self",
".",
"query",
"(",
"occupied_housing_units_lower",
"=",
"lower",
",",
"occupied_housing_units_upper",
"=",
"upper",
",",
"sort_by",
"=",
"sort_by",
",",
"zipcode_type",
"=",
"zipcode_type",
",",
"ascending",
"=",
"ascending",
",",
"returns",
"=",
"returns",
",",
")"
] |
Search zipcode information by occupied house of units.
|
[
"Search",
"zipcode",
"information",
"by",
"occupied",
"house",
"of",
"units",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/search.py#L770-L785
|
16,228
|
MacHu-GWU/uszipcode-project
|
uszipcode/search.py
|
SearchEngine.by_median_home_value
|
def by_median_home_value(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.median_home_value.name,
ascending=False,
returns=DEFAULT_LIMIT):
"""
Search zipcode information by median home value.
"""
return self.query(
median_home_value_lower=lower,
median_home_value_upper=upper,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
python
|
def by_median_home_value(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.median_home_value.name,
ascending=False,
returns=DEFAULT_LIMIT):
"""
Search zipcode information by median home value.
"""
return self.query(
median_home_value_lower=lower,
median_home_value_upper=upper,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
[
"def",
"by_median_home_value",
"(",
"self",
",",
"lower",
"=",
"-",
"1",
",",
"upper",
"=",
"2",
"**",
"31",
",",
"zipcode_type",
"=",
"ZipcodeType",
".",
"Standard",
",",
"sort_by",
"=",
"SimpleZipcode",
".",
"median_home_value",
".",
"name",
",",
"ascending",
"=",
"False",
",",
"returns",
"=",
"DEFAULT_LIMIT",
")",
":",
"return",
"self",
".",
"query",
"(",
"median_home_value_lower",
"=",
"lower",
",",
"median_home_value_upper",
"=",
"upper",
",",
"sort_by",
"=",
"sort_by",
",",
"zipcode_type",
"=",
"zipcode_type",
",",
"ascending",
"=",
"ascending",
",",
"returns",
"=",
"returns",
",",
")"
] |
Search zipcode information by median home value.
|
[
"Search",
"zipcode",
"information",
"by",
"median",
"home",
"value",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/search.py#L787-L802
|
16,229
|
MacHu-GWU/uszipcode-project
|
uszipcode/search.py
|
SearchEngine.by_median_household_income
|
def by_median_household_income(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.median_household_income.name,
ascending=False,
returns=DEFAULT_LIMIT):
"""
Search zipcode information by median household income.
"""
return self.query(
median_household_income_lower=lower,
median_household_income_upper=upper,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
python
|
def by_median_household_income(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.median_household_income.name,
ascending=False,
returns=DEFAULT_LIMIT):
"""
Search zipcode information by median household income.
"""
return self.query(
median_household_income_lower=lower,
median_household_income_upper=upper,
sort_by=sort_by, zipcode_type=zipcode_type,
ascending=ascending, returns=returns,
)
|
[
"def",
"by_median_household_income",
"(",
"self",
",",
"lower",
"=",
"-",
"1",
",",
"upper",
"=",
"2",
"**",
"31",
",",
"zipcode_type",
"=",
"ZipcodeType",
".",
"Standard",
",",
"sort_by",
"=",
"SimpleZipcode",
".",
"median_household_income",
".",
"name",
",",
"ascending",
"=",
"False",
",",
"returns",
"=",
"DEFAULT_LIMIT",
")",
":",
"return",
"self",
".",
"query",
"(",
"median_household_income_lower",
"=",
"lower",
",",
"median_household_income_upper",
"=",
"upper",
",",
"sort_by",
"=",
"sort_by",
",",
"zipcode_type",
"=",
"zipcode_type",
",",
"ascending",
"=",
"ascending",
",",
"returns",
"=",
"returns",
",",
")"
] |
Search zipcode information by median household income.
|
[
"Search",
"zipcode",
"information",
"by",
"median",
"household",
"income",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/search.py#L804-L819
|
16,230
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/crud/selecting.py
|
select_single_column
|
def select_single_column(engine, column):
"""
Select data from single column.
Example::
>>> select_single_column(engine, table_user.c.id)
[1, 2, 3]
>>> select_single_column(engine, table_user.c.name)
["Alice", "Bob", "Cathy"]
"""
s = select([column])
return column.name, [row[0] for row in engine.execute(s)]
|
python
|
def select_single_column(engine, column):
"""
Select data from single column.
Example::
>>> select_single_column(engine, table_user.c.id)
[1, 2, 3]
>>> select_single_column(engine, table_user.c.name)
["Alice", "Bob", "Cathy"]
"""
s = select([column])
return column.name, [row[0] for row in engine.execute(s)]
|
[
"def",
"select_single_column",
"(",
"engine",
",",
"column",
")",
":",
"s",
"=",
"select",
"(",
"[",
"column",
"]",
")",
"return",
"column",
".",
"name",
",",
"[",
"row",
"[",
"0",
"]",
"for",
"row",
"in",
"engine",
".",
"execute",
"(",
"s",
")",
"]"
] |
Select data from single column.
Example::
>>> select_single_column(engine, table_user.c.id)
[1, 2, 3]
>>> select_single_column(engine, table_user.c.name)
["Alice", "Bob", "Cathy"]
|
[
"Select",
"data",
"from",
"single",
"column",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/crud/selecting.py#L49-L62
|
16,231
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/crud/selecting.py
|
select_many_column
|
def select_many_column(engine, *columns):
"""
Select data from multiple columns.
Example::
>>> select_many_column(engine, table_user.c.id, table_user.c.name)
:param columns: list of sqlalchemy.Column instance
:returns headers: headers
:returns data: list of row
**中文文档**
返回多列中的数据。
"""
if isinstance(columns[0], Column):
pass
elif isinstance(columns[0], (list, tuple)):
columns = columns[0]
s = select(columns)
headers = [str(column) for column in columns]
data = [tuple(row) for row in engine.execute(s)]
return headers, data
|
python
|
def select_many_column(engine, *columns):
"""
Select data from multiple columns.
Example::
>>> select_many_column(engine, table_user.c.id, table_user.c.name)
:param columns: list of sqlalchemy.Column instance
:returns headers: headers
:returns data: list of row
**中文文档**
返回多列中的数据。
"""
if isinstance(columns[0], Column):
pass
elif isinstance(columns[0], (list, tuple)):
columns = columns[0]
s = select(columns)
headers = [str(column) for column in columns]
data = [tuple(row) for row in engine.execute(s)]
return headers, data
|
[
"def",
"select_many_column",
"(",
"engine",
",",
"*",
"columns",
")",
":",
"if",
"isinstance",
"(",
"columns",
"[",
"0",
"]",
",",
"Column",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"columns",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"columns",
"=",
"columns",
"[",
"0",
"]",
"s",
"=",
"select",
"(",
"columns",
")",
"headers",
"=",
"[",
"str",
"(",
"column",
")",
"for",
"column",
"in",
"columns",
"]",
"data",
"=",
"[",
"tuple",
"(",
"row",
")",
"for",
"row",
"in",
"engine",
".",
"execute",
"(",
"s",
")",
"]",
"return",
"headers",
",",
"data"
] |
Select data from multiple columns.
Example::
>>> select_many_column(engine, table_user.c.id, table_user.c.name)
:param columns: list of sqlalchemy.Column instance
:returns headers: headers
:returns data: list of row
**中文文档**
返回多列中的数据。
|
[
"Select",
"data",
"from",
"multiple",
"columns",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/crud/selecting.py#L65-L90
|
16,232
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/crud/selecting.py
|
select_random
|
def select_random(engine, table_or_columns, limit=5):
"""
Randomly select some rows from table.
"""
s = select(table_or_columns).order_by(func.random()).limit(limit)
return engine.execute(s).fetchall()
|
python
|
def select_random(engine, table_or_columns, limit=5):
"""
Randomly select some rows from table.
"""
s = select(table_or_columns).order_by(func.random()).limit(limit)
return engine.execute(s).fetchall()
|
[
"def",
"select_random",
"(",
"engine",
",",
"table_or_columns",
",",
"limit",
"=",
"5",
")",
":",
"s",
"=",
"select",
"(",
"table_or_columns",
")",
".",
"order_by",
"(",
"func",
".",
"random",
"(",
")",
")",
".",
"limit",
"(",
"limit",
")",
"return",
"engine",
".",
"execute",
"(",
"s",
")",
".",
"fetchall",
"(",
")"
] |
Randomly select some rows from table.
|
[
"Randomly",
"select",
"some",
"rows",
"from",
"table",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/crud/selecting.py#L114-L119
|
16,233
|
MacHu-GWU/uszipcode-project
|
uszipcode/pkg/sqlalchemy_mate/crud/inserting.py
|
smart_insert
|
def smart_insert(engine, table, data, minimal_size=5):
"""
An optimized Insert strategy. Guarantee successful and highest insertion
speed. But ATOMIC WRITE IS NOT ENSURED IF THE PROGRAM IS INTERRUPTED.
**中文文档**
在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要
远远快于逐条Insert。而如果无法预知, 那么我们采用如下策略:
1. 尝试Bulk Insert, Bulk Insert由于在结束前不Commit, 所以速度很快。
2. 如果失败了, 那么对数据的条数开平方根, 进行分包, 然后对每个包重复该逻辑。
3. 若还是尝试失败, 则继续分包, 当分包的大小小于一定数量时, 则使用逐条插入。
直到成功为止。
该Insert策略在内存上需要额外的 sqrt(nbytes) 的开销, 跟原数据相比体积很小。
但时间上是各种情况下平均最优的。
"""
insert = table.insert()
if isinstance(data, list):
# 首先进行尝试bulk insert
try:
engine.execute(insert, data)
# 失败了
except IntegrityError:
# 分析数据量
n = len(data)
# 如果数据条数多于一定数量
if n >= minimal_size ** 2:
# 则进行分包
n_chunk = math.floor(math.sqrt(n))
for chunk in grouper_list(data, n_chunk):
smart_insert(engine, table, chunk, minimal_size)
# 否则则一条条地逐条插入
else:
for row in data:
try:
engine.execute(insert, row)
except IntegrityError:
pass
else:
try:
engine.execute(insert, data)
except IntegrityError:
pass
|
python
|
def smart_insert(engine, table, data, minimal_size=5):
"""
An optimized Insert strategy. Guarantee successful and highest insertion
speed. But ATOMIC WRITE IS NOT ENSURED IF THE PROGRAM IS INTERRUPTED.
**中文文档**
在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要
远远快于逐条Insert。而如果无法预知, 那么我们采用如下策略:
1. 尝试Bulk Insert, Bulk Insert由于在结束前不Commit, 所以速度很快。
2. 如果失败了, 那么对数据的条数开平方根, 进行分包, 然后对每个包重复该逻辑。
3. 若还是尝试失败, 则继续分包, 当分包的大小小于一定数量时, 则使用逐条插入。
直到成功为止。
该Insert策略在内存上需要额外的 sqrt(nbytes) 的开销, 跟原数据相比体积很小。
但时间上是各种情况下平均最优的。
"""
insert = table.insert()
if isinstance(data, list):
# 首先进行尝试bulk insert
try:
engine.execute(insert, data)
# 失败了
except IntegrityError:
# 分析数据量
n = len(data)
# 如果数据条数多于一定数量
if n >= minimal_size ** 2:
# 则进行分包
n_chunk = math.floor(math.sqrt(n))
for chunk in grouper_list(data, n_chunk):
smart_insert(engine, table, chunk, minimal_size)
# 否则则一条条地逐条插入
else:
for row in data:
try:
engine.execute(insert, row)
except IntegrityError:
pass
else:
try:
engine.execute(insert, data)
except IntegrityError:
pass
|
[
"def",
"smart_insert",
"(",
"engine",
",",
"table",
",",
"data",
",",
"minimal_size",
"=",
"5",
")",
":",
"insert",
"=",
"table",
".",
"insert",
"(",
")",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"# 首先进行尝试bulk insert",
"try",
":",
"engine",
".",
"execute",
"(",
"insert",
",",
"data",
")",
"# 失败了",
"except",
"IntegrityError",
":",
"# 分析数据量",
"n",
"=",
"len",
"(",
"data",
")",
"# 如果数据条数多于一定数量",
"if",
"n",
">=",
"minimal_size",
"**",
"2",
":",
"# 则进行分包",
"n_chunk",
"=",
"math",
".",
"floor",
"(",
"math",
".",
"sqrt",
"(",
"n",
")",
")",
"for",
"chunk",
"in",
"grouper_list",
"(",
"data",
",",
"n_chunk",
")",
":",
"smart_insert",
"(",
"engine",
",",
"table",
",",
"chunk",
",",
"minimal_size",
")",
"# 否则则一条条地逐条插入",
"else",
":",
"for",
"row",
"in",
"data",
":",
"try",
":",
"engine",
".",
"execute",
"(",
"insert",
",",
"row",
")",
"except",
"IntegrityError",
":",
"pass",
"else",
":",
"try",
":",
"engine",
".",
"execute",
"(",
"insert",
",",
"data",
")",
"except",
"IntegrityError",
":",
"pass"
] |
An optimized Insert strategy. Guarantee successful and highest insertion
speed. But ATOMIC WRITE IS NOT ENSURED IF THE PROGRAM IS INTERRUPTED.
**中文文档**
在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要
远远快于逐条Insert。而如果无法预知, 那么我们采用如下策略:
1. 尝试Bulk Insert, Bulk Insert由于在结束前不Commit, 所以速度很快。
2. 如果失败了, 那么对数据的条数开平方根, 进行分包, 然后对每个包重复该逻辑。
3. 若还是尝试失败, 则继续分包, 当分包的大小小于一定数量时, 则使用逐条插入。
直到成功为止。
该Insert策略在内存上需要额外的 sqrt(nbytes) 的开销, 跟原数据相比体积很小。
但时间上是各种情况下平均最优的。
|
[
"An",
"optimized",
"Insert",
"strategy",
".",
"Guarantee",
"successful",
"and",
"highest",
"insertion",
"speed",
".",
"But",
"ATOMIC",
"WRITE",
"IS",
"NOT",
"ENSURED",
"IF",
"THE",
"PROGRAM",
"IS",
"INTERRUPTED",
"."
] |
96282b779a3efb422802de83c48ca284598ba952
|
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/crud/inserting.py#L16-L61
|
16,234
|
Hironsan/HateSonar
|
hatesonar/crawler/twitter.py
|
load_keys
|
def load_keys():
"""Loads Twitter keys.
Returns:
tuple: consumer_key, consumer_secret, access_token, access_token_secret
"""
consumer_key = os.environ.get('CONSUMER_KEY')
consumer_secret = os.environ.get('CONSUMER_SECRET')
access_token = os.environ.get('ACCESS_TOKEN')
access_token_secret = os.environ.get('ACCESS_TOKEN_SECRET')
return consumer_key, consumer_secret, access_token, access_token_secret
|
python
|
def load_keys():
"""Loads Twitter keys.
Returns:
tuple: consumer_key, consumer_secret, access_token, access_token_secret
"""
consumer_key = os.environ.get('CONSUMER_KEY')
consumer_secret = os.environ.get('CONSUMER_SECRET')
access_token = os.environ.get('ACCESS_TOKEN')
access_token_secret = os.environ.get('ACCESS_TOKEN_SECRET')
return consumer_key, consumer_secret, access_token, access_token_secret
|
[
"def",
"load_keys",
"(",
")",
":",
"consumer_key",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'CONSUMER_KEY'",
")",
"consumer_secret",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'CONSUMER_SECRET'",
")",
"access_token",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'ACCESS_TOKEN'",
")",
"access_token_secret",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'ACCESS_TOKEN_SECRET'",
")",
"return",
"consumer_key",
",",
"consumer_secret",
",",
"access_token",
",",
"access_token_secret"
] |
Loads Twitter keys.
Returns:
tuple: consumer_key, consumer_secret, access_token, access_token_secret
|
[
"Loads",
"Twitter",
"keys",
"."
] |
39ede274119bb128ac32ba3e6d7d58f6104d2354
|
https://github.com/Hironsan/HateSonar/blob/39ede274119bb128ac32ba3e6d7d58f6104d2354/hatesonar/crawler/twitter.py#L9-L20
|
16,235
|
Hironsan/HateSonar
|
hatesonar/crawler/twitter.py
|
TwitterAPI.search
|
def search(self, q):
"""Search tweets by keyword.
Args:
q: keyword
Returns:
list: tweet list
"""
results = self._api.search(q=q)
return results
|
python
|
def search(self, q):
"""Search tweets by keyword.
Args:
q: keyword
Returns:
list: tweet list
"""
results = self._api.search(q=q)
return results
|
[
"def",
"search",
"(",
"self",
",",
"q",
")",
":",
"results",
"=",
"self",
".",
"_api",
".",
"search",
"(",
"q",
"=",
"q",
")",
"return",
"results"
] |
Search tweets by keyword.
Args:
q: keyword
Returns:
list: tweet list
|
[
"Search",
"tweets",
"by",
"keyword",
"."
] |
39ede274119bb128ac32ba3e6d7d58f6104d2354
|
https://github.com/Hironsan/HateSonar/blob/39ede274119bb128ac32ba3e6d7d58f6104d2354/hatesonar/crawler/twitter.py#L30-L41
|
16,236
|
Hironsan/HateSonar
|
hatesonar/crawler/twitter.py
|
TwitterAPI.search_by_user
|
def search_by_user(self, screen_name, count=100):
"""Search tweets by user.
Args:
screen_name: screen name
count: the number of tweets
Returns:
list: tweet list
"""
results = self._api.user_timeline(screen_name=screen_name, count=count)
return results
|
python
|
def search_by_user(self, screen_name, count=100):
"""Search tweets by user.
Args:
screen_name: screen name
count: the number of tweets
Returns:
list: tweet list
"""
results = self._api.user_timeline(screen_name=screen_name, count=count)
return results
|
[
"def",
"search_by_user",
"(",
"self",
",",
"screen_name",
",",
"count",
"=",
"100",
")",
":",
"results",
"=",
"self",
".",
"_api",
".",
"user_timeline",
"(",
"screen_name",
"=",
"screen_name",
",",
"count",
"=",
"count",
")",
"return",
"results"
] |
Search tweets by user.
Args:
screen_name: screen name
count: the number of tweets
Returns:
list: tweet list
|
[
"Search",
"tweets",
"by",
"user",
"."
] |
39ede274119bb128ac32ba3e6d7d58f6104d2354
|
https://github.com/Hironsan/HateSonar/blob/39ede274119bb128ac32ba3e6d7d58f6104d2354/hatesonar/crawler/twitter.py#L43-L55
|
16,237
|
YosaiProject/yosai
|
yosai/core/mgt/mgt.py
|
AbstractRememberMeManager.on_successful_login
|
def on_successful_login(self, subject, authc_token, account_id):
"""
Reacts to the successful login attempt by first always
forgetting any previously stored identity. Then if the authc_token
is a ``RememberMe`` type of token, the associated identity
will be remembered for later retrieval during a new user session.
:param subject: the subject whose identifying attributes are being
remembered
:param authc_token: the token that resulted in a successful
authentication attempt
:param account_id: id of authenticated account
"""
# always clear any previous identity:
self.forget_identity(subject)
# now save the new identity:
if authc_token.is_remember_me:
self.remember_identity(subject, authc_token, account_id)
else:
msg = ("AuthenticationToken did not indicate that RememberMe is "
"requested. RememberMe functionality will not be executed "
"for corresponding account.")
logger.debug(msg)
|
python
|
def on_successful_login(self, subject, authc_token, account_id):
"""
Reacts to the successful login attempt by first always
forgetting any previously stored identity. Then if the authc_token
is a ``RememberMe`` type of token, the associated identity
will be remembered for later retrieval during a new user session.
:param subject: the subject whose identifying attributes are being
remembered
:param authc_token: the token that resulted in a successful
authentication attempt
:param account_id: id of authenticated account
"""
# always clear any previous identity:
self.forget_identity(subject)
# now save the new identity:
if authc_token.is_remember_me:
self.remember_identity(subject, authc_token, account_id)
else:
msg = ("AuthenticationToken did not indicate that RememberMe is "
"requested. RememberMe functionality will not be executed "
"for corresponding account.")
logger.debug(msg)
|
[
"def",
"on_successful_login",
"(",
"self",
",",
"subject",
",",
"authc_token",
",",
"account_id",
")",
":",
"# always clear any previous identity:",
"self",
".",
"forget_identity",
"(",
"subject",
")",
"# now save the new identity:",
"if",
"authc_token",
".",
"is_remember_me",
":",
"self",
".",
"remember_identity",
"(",
"subject",
",",
"authc_token",
",",
"account_id",
")",
"else",
":",
"msg",
"=",
"(",
"\"AuthenticationToken did not indicate that RememberMe is \"",
"\"requested. RememberMe functionality will not be executed \"",
"\"for corresponding account.\"",
")",
"logger",
".",
"debug",
"(",
"msg",
")"
] |
Reacts to the successful login attempt by first always
forgetting any previously stored identity. Then if the authc_token
is a ``RememberMe`` type of token, the associated identity
will be remembered for later retrieval during a new user session.
:param subject: the subject whose identifying attributes are being
remembered
:param authc_token: the token that resulted in a successful
authentication attempt
:param account_id: id of authenticated account
|
[
"Reacts",
"to",
"the",
"successful",
"login",
"attempt",
"by",
"first",
"always",
"forgetting",
"any",
"previously",
"stored",
"identity",
".",
"Then",
"if",
"the",
"authc_token",
"is",
"a",
"RememberMe",
"type",
"of",
"token",
"the",
"associated",
"identity",
"will",
"be",
"remembered",
"for",
"later",
"retrieval",
"during",
"a",
"new",
"user",
"session",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L137-L160
|
16,238
|
YosaiProject/yosai
|
yosai/core/mgt/mgt.py
|
AbstractRememberMeManager.remember_identity
|
def remember_identity(self, subject, authc_token, account_id):
"""
Yosai consolidates rememberIdentity, an overloaded method in java,
to a method that will use an identifier-else-account logic.
Remembers a subject-unique identity for retrieval later. This
implementation first resolves the exact identifying attributes to
remember. It then remembers these identifying attributes by calling
remember_identity(Subject, IdentifierCollection)
:param subject: the subject for which the identifying attributes are
being remembered
:param authc_token: ignored in the AbstractRememberMeManager
:param account_id: the account id of authenticated account
"""
try:
identifiers = self.get_identity_to_remember(subject, account_id)
except AttributeError:
msg = "Neither account_id nor identifier arguments passed"
raise AttributeError(msg)
encrypted = self.convert_identifiers_to_bytes(identifiers)
self.remember_encrypted_identity(subject, encrypted)
|
python
|
def remember_identity(self, subject, authc_token, account_id):
"""
Yosai consolidates rememberIdentity, an overloaded method in java,
to a method that will use an identifier-else-account logic.
Remembers a subject-unique identity for retrieval later. This
implementation first resolves the exact identifying attributes to
remember. It then remembers these identifying attributes by calling
remember_identity(Subject, IdentifierCollection)
:param subject: the subject for which the identifying attributes are
being remembered
:param authc_token: ignored in the AbstractRememberMeManager
:param account_id: the account id of authenticated account
"""
try:
identifiers = self.get_identity_to_remember(subject, account_id)
except AttributeError:
msg = "Neither account_id nor identifier arguments passed"
raise AttributeError(msg)
encrypted = self.convert_identifiers_to_bytes(identifiers)
self.remember_encrypted_identity(subject, encrypted)
|
[
"def",
"remember_identity",
"(",
"self",
",",
"subject",
",",
"authc_token",
",",
"account_id",
")",
":",
"try",
":",
"identifiers",
"=",
"self",
".",
"get_identity_to_remember",
"(",
"subject",
",",
"account_id",
")",
"except",
"AttributeError",
":",
"msg",
"=",
"\"Neither account_id nor identifier arguments passed\"",
"raise",
"AttributeError",
"(",
"msg",
")",
"encrypted",
"=",
"self",
".",
"convert_identifiers_to_bytes",
"(",
"identifiers",
")",
"self",
".",
"remember_encrypted_identity",
"(",
"subject",
",",
"encrypted",
")"
] |
Yosai consolidates rememberIdentity, an overloaded method in java,
to a method that will use an identifier-else-account logic.
Remembers a subject-unique identity for retrieval later. This
implementation first resolves the exact identifying attributes to
remember. It then remembers these identifying attributes by calling
remember_identity(Subject, IdentifierCollection)
:param subject: the subject for which the identifying attributes are
being remembered
:param authc_token: ignored in the AbstractRememberMeManager
:param account_id: the account id of authenticated account
|
[
"Yosai",
"consolidates",
"rememberIdentity",
"an",
"overloaded",
"method",
"in",
"java",
"to",
"a",
"method",
"that",
"will",
"use",
"an",
"identifier",
"-",
"else",
"-",
"account",
"logic",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L162-L183
|
16,239
|
YosaiProject/yosai
|
yosai/core/mgt/mgt.py
|
AbstractRememberMeManager.convert_bytes_to_identifiers
|
def convert_bytes_to_identifiers(self, encrypted, subject_context):
"""
If a cipher_service is available, it will be used to first decrypt the
serialized message. Then, the bytes are deserialized and returned.
:param serialized: the bytes to decrypt and then deserialize
:param subject_context: the contextual data, that is being
used to construct a Subject instance
:returns: the de-serialized identifier
"""
# unlike Shiro, Yosai assumes that the message is encrypted:
decrypted = self.decrypt(encrypted)
return self.serialization_manager.deserialize(decrypted)
|
python
|
def convert_bytes_to_identifiers(self, encrypted, subject_context):
"""
If a cipher_service is available, it will be used to first decrypt the
serialized message. Then, the bytes are deserialized and returned.
:param serialized: the bytes to decrypt and then deserialize
:param subject_context: the contextual data, that is being
used to construct a Subject instance
:returns: the de-serialized identifier
"""
# unlike Shiro, Yosai assumes that the message is encrypted:
decrypted = self.decrypt(encrypted)
return self.serialization_manager.deserialize(decrypted)
|
[
"def",
"convert_bytes_to_identifiers",
"(",
"self",
",",
"encrypted",
",",
"subject_context",
")",
":",
"# unlike Shiro, Yosai assumes that the message is encrypted:",
"decrypted",
"=",
"self",
".",
"decrypt",
"(",
"encrypted",
")",
"return",
"self",
".",
"serialization_manager",
".",
"deserialize",
"(",
"decrypted",
")"
] |
If a cipher_service is available, it will be used to first decrypt the
serialized message. Then, the bytes are deserialized and returned.
:param serialized: the bytes to decrypt and then deserialize
:param subject_context: the contextual data, that is being
used to construct a Subject instance
:returns: the de-serialized identifier
|
[
"If",
"a",
"cipher_service",
"is",
"available",
"it",
"will",
"be",
"used",
"to",
"first",
"decrypt",
"the",
"serialized",
"message",
".",
"Then",
"the",
"bytes",
"are",
"deserialized",
"and",
"returned",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L245-L259
|
16,240
|
YosaiProject/yosai
|
yosai/core/mgt/mgt.py
|
AbstractRememberMeManager.encrypt
|
def encrypt(self, serialized):
"""
Encrypts the serialized message using Fernet
:param serialized: the serialized object to encrypt
:type serialized: bytes
:returns: an encrypted bytes returned by Fernet
"""
fernet = Fernet(self.encryption_cipher_key)
return fernet.encrypt(serialized)
|
python
|
def encrypt(self, serialized):
"""
Encrypts the serialized message using Fernet
:param serialized: the serialized object to encrypt
:type serialized: bytes
:returns: an encrypted bytes returned by Fernet
"""
fernet = Fernet(self.encryption_cipher_key)
return fernet.encrypt(serialized)
|
[
"def",
"encrypt",
"(",
"self",
",",
"serialized",
")",
":",
"fernet",
"=",
"Fernet",
"(",
"self",
".",
"encryption_cipher_key",
")",
"return",
"fernet",
".",
"encrypt",
"(",
"serialized",
")"
] |
Encrypts the serialized message using Fernet
:param serialized: the serialized object to encrypt
:type serialized: bytes
:returns: an encrypted bytes returned by Fernet
|
[
"Encrypts",
"the",
"serialized",
"message",
"using",
"Fernet"
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L294-L304
|
16,241
|
YosaiProject/yosai
|
yosai/core/mgt/mgt.py
|
AbstractRememberMeManager.decrypt
|
def decrypt(self, encrypted):
"""
decrypts the encrypted message using Fernet
:param encrypted: the encrypted message
:returns: the decrypted, serialized identifier collection
"""
fernet = Fernet(self.decryption_cipher_key)
return fernet.decrypt(encrypted)
|
python
|
def decrypt(self, encrypted):
"""
decrypts the encrypted message using Fernet
:param encrypted: the encrypted message
:returns: the decrypted, serialized identifier collection
"""
fernet = Fernet(self.decryption_cipher_key)
return fernet.decrypt(encrypted)
|
[
"def",
"decrypt",
"(",
"self",
",",
"encrypted",
")",
":",
"fernet",
"=",
"Fernet",
"(",
"self",
".",
"decryption_cipher_key",
")",
"return",
"fernet",
".",
"decrypt",
"(",
"encrypted",
")"
] |
decrypts the encrypted message using Fernet
:param encrypted: the encrypted message
:returns: the decrypted, serialized identifier collection
|
[
"decrypts",
"the",
"encrypted",
"message",
"using",
"Fernet"
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L306-L314
|
16,242
|
YosaiProject/yosai
|
yosai/core/mgt/mgt.py
|
NativeSecurityManager.create_subject
|
def create_subject(self,
authc_token=None,
account_id=None,
existing_subject=None,
subject_context=None):
"""
Creates a ``Subject`` instance for the user represented by the given method
arguments.
It is an overloaded method, due to porting java to python, and is
consequently highly likely to be refactored.
It gets called in one of two ways:
1) when creating an anonymous subject, passing create_subject
a subject_context argument
2) following a after successful login, passing all but the context argument
This implementation functions as follows:
- Ensures that the ``SubjectContext`` exists and is as populated as it can be,
using heuristics to acquire data that may not have already been available
to it (such as a referenced session or remembered identifiers).
- Calls subject_context.do_create_subject to perform the Subject
instance creation
- Calls subject.save to ensure the constructed Subject's state is
accessible for future requests/invocations if necessary
- Returns the constructed Subject instance
:type authc_token: subject_abcs.AuthenticationToken
:param account_id: the identifiers of a newly authenticated user
:type account: SimpleIdentifierCollection
:param existing_subject: the existing Subject instance that initiated the
authentication attempt
:type subject: subject_abcs.Subject
:type subject_context: subject_abcs.SubjectContext
:returns: the Subject instance that represents the context and session
data for the newly authenticated subject
"""
if subject_context is None: # this that means a successful login just happened
# passing existing_subject is new to yosai:
context = self.create_subject_context(existing_subject)
context.authenticated = True
context.authentication_token = authc_token
context.account_id = account_id
if (existing_subject):
context.subject = existing_subject
else:
context = copy.copy(subject_context) # if this necessary? TBD.
context = self.ensure_security_manager(context)
context = self.resolve_session(context)
context = self.resolve_identifiers(context)
subject = self.do_create_subject(context) # DelegatingSubject
# save this subject for future reference if necessary:
# (this is needed here in case remember_me identifiers were resolved
# and they need to be stored in the session, so we don't constantly
# re-hydrate the remember_me identifier_collection on every operation).
self.save(subject)
return subject
|
python
|
def create_subject(self,
authc_token=None,
account_id=None,
existing_subject=None,
subject_context=None):
"""
Creates a ``Subject`` instance for the user represented by the given method
arguments.
It is an overloaded method, due to porting java to python, and is
consequently highly likely to be refactored.
It gets called in one of two ways:
1) when creating an anonymous subject, passing create_subject
a subject_context argument
2) following a after successful login, passing all but the context argument
This implementation functions as follows:
- Ensures that the ``SubjectContext`` exists and is as populated as it can be,
using heuristics to acquire data that may not have already been available
to it (such as a referenced session or remembered identifiers).
- Calls subject_context.do_create_subject to perform the Subject
instance creation
- Calls subject.save to ensure the constructed Subject's state is
accessible for future requests/invocations if necessary
- Returns the constructed Subject instance
:type authc_token: subject_abcs.AuthenticationToken
:param account_id: the identifiers of a newly authenticated user
:type account: SimpleIdentifierCollection
:param existing_subject: the existing Subject instance that initiated the
authentication attempt
:type subject: subject_abcs.Subject
:type subject_context: subject_abcs.SubjectContext
:returns: the Subject instance that represents the context and session
data for the newly authenticated subject
"""
if subject_context is None: # this that means a successful login just happened
# passing existing_subject is new to yosai:
context = self.create_subject_context(existing_subject)
context.authenticated = True
context.authentication_token = authc_token
context.account_id = account_id
if (existing_subject):
context.subject = existing_subject
else:
context = copy.copy(subject_context) # if this necessary? TBD.
context = self.ensure_security_manager(context)
context = self.resolve_session(context)
context = self.resolve_identifiers(context)
subject = self.do_create_subject(context) # DelegatingSubject
# save this subject for future reference if necessary:
# (this is needed here in case remember_me identifiers were resolved
# and they need to be stored in the session, so we don't constantly
# re-hydrate the remember_me identifier_collection on every operation).
self.save(subject)
return subject
|
[
"def",
"create_subject",
"(",
"self",
",",
"authc_token",
"=",
"None",
",",
"account_id",
"=",
"None",
",",
"existing_subject",
"=",
"None",
",",
"subject_context",
"=",
"None",
")",
":",
"if",
"subject_context",
"is",
"None",
":",
"# this that means a successful login just happened",
"# passing existing_subject is new to yosai:",
"context",
"=",
"self",
".",
"create_subject_context",
"(",
"existing_subject",
")",
"context",
".",
"authenticated",
"=",
"True",
"context",
".",
"authentication_token",
"=",
"authc_token",
"context",
".",
"account_id",
"=",
"account_id",
"if",
"(",
"existing_subject",
")",
":",
"context",
".",
"subject",
"=",
"existing_subject",
"else",
":",
"context",
"=",
"copy",
".",
"copy",
"(",
"subject_context",
")",
"# if this necessary? TBD.",
"context",
"=",
"self",
".",
"ensure_security_manager",
"(",
"context",
")",
"context",
"=",
"self",
".",
"resolve_session",
"(",
"context",
")",
"context",
"=",
"self",
".",
"resolve_identifiers",
"(",
"context",
")",
"subject",
"=",
"self",
".",
"do_create_subject",
"(",
"context",
")",
"# DelegatingSubject",
"# save this subject for future reference if necessary:",
"# (this is needed here in case remember_me identifiers were resolved",
"# and they need to be stored in the session, so we don't constantly",
"# re-hydrate the remember_me identifier_collection on every operation).",
"self",
".",
"save",
"(",
"subject",
")",
"return",
"subject"
] |
Creates a ``Subject`` instance for the user represented by the given method
arguments.
It is an overloaded method, due to porting java to python, and is
consequently highly likely to be refactored.
It gets called in one of two ways:
1) when creating an anonymous subject, passing create_subject
a subject_context argument
2) following a after successful login, passing all but the context argument
This implementation functions as follows:
- Ensures that the ``SubjectContext`` exists and is as populated as it can be,
using heuristics to acquire data that may not have already been available
to it (such as a referenced session or remembered identifiers).
- Calls subject_context.do_create_subject to perform the Subject
instance creation
- Calls subject.save to ensure the constructed Subject's state is
accessible for future requests/invocations if necessary
- Returns the constructed Subject instance
:type authc_token: subject_abcs.AuthenticationToken
:param account_id: the identifiers of a newly authenticated user
:type account: SimpleIdentifierCollection
:param existing_subject: the existing Subject instance that initiated the
authentication attempt
:type subject: subject_abcs.Subject
:type subject_context: subject_abcs.SubjectContext
:returns: the Subject instance that represents the context and session
data for the newly authenticated subject
|
[
"Creates",
"a",
"Subject",
"instance",
"for",
"the",
"user",
"represented",
"by",
"the",
"given",
"method",
"arguments",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L514-L582
|
16,243
|
YosaiProject/yosai
|
yosai/core/mgt/mgt.py
|
NativeSecurityManager.login
|
def login(self, subject, authc_token):
"""
Login authenticates a user using an AuthenticationToken. If authentication is
successful AND the Authenticator has determined that authentication is
complete for the account, login constructs a Subject instance representing
the authenticated account's identity. Once a subject instance is constructed,
it is bound to the application for subsequent access before being returned
to the caller.
If login successfully authenticates a token but the Authenticator has
determined that subject's account isn't considered authenticated,
the account is configured for multi-factor authentication.
Sessionless environments must pass all authentication tokens to login
at once.
:param authc_token: the authenticationToken to process for the login attempt
:type authc_token: authc_abcs.authenticationToken
:returns: a Subject representing the authenticated user
:raises AuthenticationException: if there is a problem authenticating
the specified authc_token
:raises AdditionalAuthenticationRequired: during multi-factor authentication
when additional tokens are required
"""
try:
# account_id is a SimpleIdentifierCollection
account_id = self.authenticator.authenticate_account(subject.identifiers,
authc_token)
# implies multi-factor authc not complete:
except AdditionalAuthenticationRequired as exc:
# identity needs to be accessible for subsequent authentication:
self.update_subject_identity(exc.account_id, subject)
# no need to propagate account further:
raise AdditionalAuthenticationRequired
except AuthenticationException as authc_ex:
try:
self.on_failed_login(authc_token, authc_ex, subject)
except Exception:
msg = ("on_failed_login method raised an exception. Logging "
"and propagating original AuthenticationException.")
logger.info(msg, exc_info=True)
raise
logged_in = self.create_subject(authc_token=authc_token,
account_id=account_id,
existing_subject=subject)
self.on_successful_login(authc_token, account_id, logged_in)
return logged_in
|
python
|
def login(self, subject, authc_token):
"""
Login authenticates a user using an AuthenticationToken. If authentication is
successful AND the Authenticator has determined that authentication is
complete for the account, login constructs a Subject instance representing
the authenticated account's identity. Once a subject instance is constructed,
it is bound to the application for subsequent access before being returned
to the caller.
If login successfully authenticates a token but the Authenticator has
determined that subject's account isn't considered authenticated,
the account is configured for multi-factor authentication.
Sessionless environments must pass all authentication tokens to login
at once.
:param authc_token: the authenticationToken to process for the login attempt
:type authc_token: authc_abcs.authenticationToken
:returns: a Subject representing the authenticated user
:raises AuthenticationException: if there is a problem authenticating
the specified authc_token
:raises AdditionalAuthenticationRequired: during multi-factor authentication
when additional tokens are required
"""
try:
# account_id is a SimpleIdentifierCollection
account_id = self.authenticator.authenticate_account(subject.identifiers,
authc_token)
# implies multi-factor authc not complete:
except AdditionalAuthenticationRequired as exc:
# identity needs to be accessible for subsequent authentication:
self.update_subject_identity(exc.account_id, subject)
# no need to propagate account further:
raise AdditionalAuthenticationRequired
except AuthenticationException as authc_ex:
try:
self.on_failed_login(authc_token, authc_ex, subject)
except Exception:
msg = ("on_failed_login method raised an exception. Logging "
"and propagating original AuthenticationException.")
logger.info(msg, exc_info=True)
raise
logged_in = self.create_subject(authc_token=authc_token,
account_id=account_id,
existing_subject=subject)
self.on_successful_login(authc_token, account_id, logged_in)
return logged_in
|
[
"def",
"login",
"(",
"self",
",",
"subject",
",",
"authc_token",
")",
":",
"try",
":",
"# account_id is a SimpleIdentifierCollection",
"account_id",
"=",
"self",
".",
"authenticator",
".",
"authenticate_account",
"(",
"subject",
".",
"identifiers",
",",
"authc_token",
")",
"# implies multi-factor authc not complete:",
"except",
"AdditionalAuthenticationRequired",
"as",
"exc",
":",
"# identity needs to be accessible for subsequent authentication:",
"self",
".",
"update_subject_identity",
"(",
"exc",
".",
"account_id",
",",
"subject",
")",
"# no need to propagate account further:",
"raise",
"AdditionalAuthenticationRequired",
"except",
"AuthenticationException",
"as",
"authc_ex",
":",
"try",
":",
"self",
".",
"on_failed_login",
"(",
"authc_token",
",",
"authc_ex",
",",
"subject",
")",
"except",
"Exception",
":",
"msg",
"=",
"(",
"\"on_failed_login method raised an exception. Logging \"",
"\"and propagating original AuthenticationException.\"",
")",
"logger",
".",
"info",
"(",
"msg",
",",
"exc_info",
"=",
"True",
")",
"raise",
"logged_in",
"=",
"self",
".",
"create_subject",
"(",
"authc_token",
"=",
"authc_token",
",",
"account_id",
"=",
"account_id",
",",
"existing_subject",
"=",
"subject",
")",
"self",
".",
"on_successful_login",
"(",
"authc_token",
",",
"account_id",
",",
"logged_in",
")",
"return",
"logged_in"
] |
Login authenticates a user using an AuthenticationToken. If authentication is
successful AND the Authenticator has determined that authentication is
complete for the account, login constructs a Subject instance representing
the authenticated account's identity. Once a subject instance is constructed,
it is bound to the application for subsequent access before being returned
to the caller.
If login successfully authenticates a token but the Authenticator has
determined that subject's account isn't considered authenticated,
the account is configured for multi-factor authentication.
Sessionless environments must pass all authentication tokens to login
at once.
:param authc_token: the authenticationToken to process for the login attempt
:type authc_token: authc_abcs.authenticationToken
:returns: a Subject representing the authenticated user
:raises AuthenticationException: if there is a problem authenticating
the specified authc_token
:raises AdditionalAuthenticationRequired: during multi-factor authentication
when additional tokens are required
|
[
"Login",
"authenticates",
"a",
"user",
"using",
"an",
"AuthenticationToken",
".",
"If",
"authentication",
"is",
"successful",
"AND",
"the",
"Authenticator",
"has",
"determined",
"that",
"authentication",
"is",
"complete",
"for",
"the",
"account",
"login",
"constructs",
"a",
"Subject",
"instance",
"representing",
"the",
"authenticated",
"account",
"s",
"identity",
".",
"Once",
"a",
"subject",
"instance",
"is",
"constructed",
"it",
"is",
"bound",
"to",
"the",
"application",
"for",
"subsequent",
"access",
"before",
"being",
"returned",
"to",
"the",
"caller",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L635-L684
|
16,244
|
YosaiProject/yosai
|
yosai/core/mgt/mgt.py
|
NativeSecurityManager.ensure_security_manager
|
def ensure_security_manager(self, subject_context):
"""
Determines whether there is a ``SecurityManager`` instance in the context,
and if not, adds 'self' to the context. This ensures that do_create_subject
will have access to a ``SecurityManager`` during Subject construction.
:param subject_context: the subject context data that may contain a
SecurityManager instance
:returns: the SubjectContext
"""
if (subject_context.resolve_security_manager() is not None):
msg = ("Subject Context resolved a security_manager "
"instance, so not re-assigning. Returning.")
logger.debug(msg)
return subject_context
msg = ("No security_manager found in context. Adding self "
"reference.")
logger.debug(msg)
subject_context.security_manager = self
return subject_context
|
python
|
def ensure_security_manager(self, subject_context):
"""
Determines whether there is a ``SecurityManager`` instance in the context,
and if not, adds 'self' to the context. This ensures that do_create_subject
will have access to a ``SecurityManager`` during Subject construction.
:param subject_context: the subject context data that may contain a
SecurityManager instance
:returns: the SubjectContext
"""
if (subject_context.resolve_security_manager() is not None):
msg = ("Subject Context resolved a security_manager "
"instance, so not re-assigning. Returning.")
logger.debug(msg)
return subject_context
msg = ("No security_manager found in context. Adding self "
"reference.")
logger.debug(msg)
subject_context.security_manager = self
return subject_context
|
[
"def",
"ensure_security_manager",
"(",
"self",
",",
"subject_context",
")",
":",
"if",
"(",
"subject_context",
".",
"resolve_security_manager",
"(",
")",
"is",
"not",
"None",
")",
":",
"msg",
"=",
"(",
"\"Subject Context resolved a security_manager \"",
"\"instance, so not re-assigning. Returning.\"",
")",
"logger",
".",
"debug",
"(",
"msg",
")",
"return",
"subject_context",
"msg",
"=",
"(",
"\"No security_manager found in context. Adding self \"",
"\"reference.\"",
")",
"logger",
".",
"debug",
"(",
"msg",
")",
"subject_context",
".",
"security_manager",
"=",
"self",
"return",
"subject_context"
] |
Determines whether there is a ``SecurityManager`` instance in the context,
and if not, adds 'self' to the context. This ensures that do_create_subject
will have access to a ``SecurityManager`` during Subject construction.
:param subject_context: the subject context data that may contain a
SecurityManager instance
:returns: the SubjectContext
|
[
"Determines",
"whether",
"there",
"is",
"a",
"SecurityManager",
"instance",
"in",
"the",
"context",
"and",
"if",
"not",
"adds",
"self",
"to",
"the",
"context",
".",
"This",
"ensures",
"that",
"do_create_subject",
"will",
"have",
"access",
"to",
"a",
"SecurityManager",
"during",
"Subject",
"construction",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L741-L763
|
16,245
|
YosaiProject/yosai
|
yosai/core/mgt/mgt.py
|
NativeSecurityManager.resolve_session
|
def resolve_session(self, subject_context):
"""
This method attempts to resolve any associated session based on the
context and returns a context that represents this resolved Session to
ensure it may be referenced, if needed, by the invoked do_create_subject
that performs actual ``Subject`` construction.
If there is a ``Session`` already in the context (because that is what the
caller wants to use for Subject construction) or if no session is
resolved, this method effectively does nothing, returning an
unmodified context as it was received by the method.
:param subject_context: the subject context data that may resolve a
Session instance
:returns: the context
"""
if (subject_context.resolve_session() is not None):
msg = ("Context already contains a session. Returning.")
logger.debug(msg)
return subject_context
try:
# Context couldn't resolve it directly, let's see if we can
# since we have direct access to the session manager:
session = self.resolve_context_session(subject_context)
# if session is None, given that subject_context.session
# is None there is no harm done by setting it to None again
subject_context.session = session
except InvalidSessionException:
msg = ("Resolved subject_subject_context context session is "
"invalid. Ignoring and creating an anonymous "
"(session-less) Subject instance.")
logger.debug(msg, exc_info=True)
return subject_context
|
python
|
def resolve_session(self, subject_context):
"""
This method attempts to resolve any associated session based on the
context and returns a context that represents this resolved Session to
ensure it may be referenced, if needed, by the invoked do_create_subject
that performs actual ``Subject`` construction.
If there is a ``Session`` already in the context (because that is what the
caller wants to use for Subject construction) or if no session is
resolved, this method effectively does nothing, returning an
unmodified context as it was received by the method.
:param subject_context: the subject context data that may resolve a
Session instance
:returns: the context
"""
if (subject_context.resolve_session() is not None):
msg = ("Context already contains a session. Returning.")
logger.debug(msg)
return subject_context
try:
# Context couldn't resolve it directly, let's see if we can
# since we have direct access to the session manager:
session = self.resolve_context_session(subject_context)
# if session is None, given that subject_context.session
# is None there is no harm done by setting it to None again
subject_context.session = session
except InvalidSessionException:
msg = ("Resolved subject_subject_context context session is "
"invalid. Ignoring and creating an anonymous "
"(session-less) Subject instance.")
logger.debug(msg, exc_info=True)
return subject_context
|
[
"def",
"resolve_session",
"(",
"self",
",",
"subject_context",
")",
":",
"if",
"(",
"subject_context",
".",
"resolve_session",
"(",
")",
"is",
"not",
"None",
")",
":",
"msg",
"=",
"(",
"\"Context already contains a session. Returning.\"",
")",
"logger",
".",
"debug",
"(",
"msg",
")",
"return",
"subject_context",
"try",
":",
"# Context couldn't resolve it directly, let's see if we can",
"# since we have direct access to the session manager:",
"session",
"=",
"self",
".",
"resolve_context_session",
"(",
"subject_context",
")",
"# if session is None, given that subject_context.session",
"# is None there is no harm done by setting it to None again",
"subject_context",
".",
"session",
"=",
"session",
"except",
"InvalidSessionException",
":",
"msg",
"=",
"(",
"\"Resolved subject_subject_context context session is \"",
"\"invalid. Ignoring and creating an anonymous \"",
"\"(session-less) Subject instance.\"",
")",
"logger",
".",
"debug",
"(",
"msg",
",",
"exc_info",
"=",
"True",
")",
"return",
"subject_context"
] |
This method attempts to resolve any associated session based on the
context and returns a context that represents this resolved Session to
ensure it may be referenced, if needed, by the invoked do_create_subject
that performs actual ``Subject`` construction.
If there is a ``Session`` already in the context (because that is what the
caller wants to use for Subject construction) or if no session is
resolved, this method effectively does nothing, returning an
unmodified context as it was received by the method.
:param subject_context: the subject context data that may resolve a
Session instance
:returns: the context
|
[
"This",
"method",
"attempts",
"to",
"resolve",
"any",
"associated",
"session",
"based",
"on",
"the",
"context",
"and",
"returns",
"a",
"context",
"that",
"represents",
"this",
"resolved",
"Session",
"to",
"ensure",
"it",
"may",
"be",
"referenced",
"if",
"needed",
"by",
"the",
"invoked",
"do_create_subject",
"that",
"performs",
"actual",
"Subject",
"construction",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L765-L801
|
16,246
|
YosaiProject/yosai
|
yosai/core/mgt/mgt.py
|
NativeSecurityManager.resolve_identifiers
|
def resolve_identifiers(self, subject_context):
"""
ensures that a subject_context has identifiers and if it doesn't will
attempt to locate them using heuristics
"""
session = subject_context.session
identifiers = subject_context.resolve_identifiers(session)
if (not identifiers):
msg = ("No identity (identifier_collection) found in the "
"subject_context. Looking for a remembered identity.")
logger.debug(msg)
identifiers = self.get_remembered_identity(subject_context)
if identifiers:
msg = ("Found remembered IdentifierCollection. Adding to the "
"context to be used for subject construction.")
logger.debug(msg)
subject_context.identifiers = identifiers
subject_context.remembered = True
else:
msg = ("No remembered identity found. Returning original "
"context.")
logger.debug(msg)
return subject_context
|
python
|
def resolve_identifiers(self, subject_context):
"""
ensures that a subject_context has identifiers and if it doesn't will
attempt to locate them using heuristics
"""
session = subject_context.session
identifiers = subject_context.resolve_identifiers(session)
if (not identifiers):
msg = ("No identity (identifier_collection) found in the "
"subject_context. Looking for a remembered identity.")
logger.debug(msg)
identifiers = self.get_remembered_identity(subject_context)
if identifiers:
msg = ("Found remembered IdentifierCollection. Adding to the "
"context to be used for subject construction.")
logger.debug(msg)
subject_context.identifiers = identifiers
subject_context.remembered = True
else:
msg = ("No remembered identity found. Returning original "
"context.")
logger.debug(msg)
return subject_context
|
[
"def",
"resolve_identifiers",
"(",
"self",
",",
"subject_context",
")",
":",
"session",
"=",
"subject_context",
".",
"session",
"identifiers",
"=",
"subject_context",
".",
"resolve_identifiers",
"(",
"session",
")",
"if",
"(",
"not",
"identifiers",
")",
":",
"msg",
"=",
"(",
"\"No identity (identifier_collection) found in the \"",
"\"subject_context. Looking for a remembered identity.\"",
")",
"logger",
".",
"debug",
"(",
"msg",
")",
"identifiers",
"=",
"self",
".",
"get_remembered_identity",
"(",
"subject_context",
")",
"if",
"identifiers",
":",
"msg",
"=",
"(",
"\"Found remembered IdentifierCollection. Adding to the \"",
"\"context to be used for subject construction.\"",
")",
"logger",
".",
"debug",
"(",
"msg",
")",
"subject_context",
".",
"identifiers",
"=",
"identifiers",
"subject_context",
".",
"remembered",
"=",
"True",
"else",
":",
"msg",
"=",
"(",
"\"No remembered identity found. Returning original \"",
"\"context.\"",
")",
"logger",
".",
"debug",
"(",
"msg",
")",
"return",
"subject_context"
] |
ensures that a subject_context has identifiers and if it doesn't will
attempt to locate them using heuristics
|
[
"ensures",
"that",
"a",
"subject_context",
"has",
"identifiers",
"and",
"if",
"it",
"doesn",
"t",
"will",
"attempt",
"to",
"locate",
"them",
"using",
"heuristics"
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L819-L847
|
16,247
|
YosaiProject/yosai
|
yosai/core/mgt/mgt.py
|
NativeSecurityManager.logout
|
def logout(self, subject):
"""
Logs out the specified Subject from the system.
Note that most application developers should not call this method unless
they have a good reason for doing so. The preferred way to logout a
Subject is to call ``Subject.logout()``, not by calling ``SecurityManager.logout``
directly. However, framework developers might find calling this method
directly useful in certain cases.
:param subject the subject to log out:
:type subject: subject_abcs.Subject
"""
if (subject is None):
msg = "Subject argument cannot be None."
raise ValueError(msg)
self.before_logout(subject)
identifiers = copy.copy(subject.identifiers) # copy is new to yosai
if (identifiers):
msg = ("Logging out subject with primary identifier {0}".format(
identifiers.primary_identifier))
logger.debug(msg)
try:
# this removes two internal attributes from the session:
self.delete(subject)
except Exception:
msg = "Unable to cleanly unbind Subject. Ignoring (logging out)."
logger.debug(msg, exc_info=True)
finally:
try:
self.stop_session(subject)
except Exception:
msg2 = ("Unable to cleanly stop Session for Subject. "
"Ignoring (logging out).")
logger.debug(msg2, exc_info=True)
|
python
|
def logout(self, subject):
"""
Logs out the specified Subject from the system.
Note that most application developers should not call this method unless
they have a good reason for doing so. The preferred way to logout a
Subject is to call ``Subject.logout()``, not by calling ``SecurityManager.logout``
directly. However, framework developers might find calling this method
directly useful in certain cases.
:param subject the subject to log out:
:type subject: subject_abcs.Subject
"""
if (subject is None):
msg = "Subject argument cannot be None."
raise ValueError(msg)
self.before_logout(subject)
identifiers = copy.copy(subject.identifiers) # copy is new to yosai
if (identifiers):
msg = ("Logging out subject with primary identifier {0}".format(
identifiers.primary_identifier))
logger.debug(msg)
try:
# this removes two internal attributes from the session:
self.delete(subject)
except Exception:
msg = "Unable to cleanly unbind Subject. Ignoring (logging out)."
logger.debug(msg, exc_info=True)
finally:
try:
self.stop_session(subject)
except Exception:
msg2 = ("Unable to cleanly stop Session for Subject. "
"Ignoring (logging out).")
logger.debug(msg2, exc_info=True)
|
[
"def",
"logout",
"(",
"self",
",",
"subject",
")",
":",
"if",
"(",
"subject",
"is",
"None",
")",
":",
"msg",
"=",
"\"Subject argument cannot be None.\"",
"raise",
"ValueError",
"(",
"msg",
")",
"self",
".",
"before_logout",
"(",
"subject",
")",
"identifiers",
"=",
"copy",
".",
"copy",
"(",
"subject",
".",
"identifiers",
")",
"# copy is new to yosai",
"if",
"(",
"identifiers",
")",
":",
"msg",
"=",
"(",
"\"Logging out subject with primary identifier {0}\"",
".",
"format",
"(",
"identifiers",
".",
"primary_identifier",
")",
")",
"logger",
".",
"debug",
"(",
"msg",
")",
"try",
":",
"# this removes two internal attributes from the session:",
"self",
".",
"delete",
"(",
"subject",
")",
"except",
"Exception",
":",
"msg",
"=",
"\"Unable to cleanly unbind Subject. Ignoring (logging out).\"",
"logger",
".",
"debug",
"(",
"msg",
",",
"exc_info",
"=",
"True",
")",
"finally",
":",
"try",
":",
"self",
".",
"stop_session",
"(",
"subject",
")",
"except",
"Exception",
":",
"msg2",
"=",
"(",
"\"Unable to cleanly stop Session for Subject. \"",
"\"Ignoring (logging out).\"",
")",
"logger",
".",
"debug",
"(",
"msg2",
",",
"exc_info",
"=",
"True",
")"
] |
Logs out the specified Subject from the system.
Note that most application developers should not call this method unless
they have a good reason for doing so. The preferred way to logout a
Subject is to call ``Subject.logout()``, not by calling ``SecurityManager.logout``
directly. However, framework developers might find calling this method
directly useful in certain cases.
:param subject the subject to log out:
:type subject: subject_abcs.Subject
|
[
"Logs",
"out",
"the",
"specified",
"Subject",
"from",
"the",
"system",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L865-L903
|
16,248
|
YosaiProject/yosai
|
yosai/core/realm/realm.py
|
AccountStoreRealm.is_permitted
|
def is_permitted(self, identifiers, permission_s):
"""
If the authorization info cannot be obtained from the accountstore,
permission check tuple yields False.
:type identifiers: subject_abcs.IdentifierCollection
:param permission_s: a collection of one or more permissions, represented
as string-based permissions or Permission objects
and NEVER comingled types
:type permission_s: list of string(s)
:yields: tuple(Permission, Boolean)
"""
identifier = identifiers.primary_identifier
for required in permission_s:
domain = Permission.get_domain(required)
# assigned is a list of json blobs:
assigned = self.get_authzd_permissions(identifier, domain)
is_permitted = False
for perms_blob in assigned:
is_permitted = self.permission_verifier.\
is_permitted_from_json(required, perms_blob)
yield (required, is_permitted)
|
python
|
def is_permitted(self, identifiers, permission_s):
"""
If the authorization info cannot be obtained from the accountstore,
permission check tuple yields False.
:type identifiers: subject_abcs.IdentifierCollection
:param permission_s: a collection of one or more permissions, represented
as string-based permissions or Permission objects
and NEVER comingled types
:type permission_s: list of string(s)
:yields: tuple(Permission, Boolean)
"""
identifier = identifiers.primary_identifier
for required in permission_s:
domain = Permission.get_domain(required)
# assigned is a list of json blobs:
assigned = self.get_authzd_permissions(identifier, domain)
is_permitted = False
for perms_blob in assigned:
is_permitted = self.permission_verifier.\
is_permitted_from_json(required, perms_blob)
yield (required, is_permitted)
|
[
"def",
"is_permitted",
"(",
"self",
",",
"identifiers",
",",
"permission_s",
")",
":",
"identifier",
"=",
"identifiers",
".",
"primary_identifier",
"for",
"required",
"in",
"permission_s",
":",
"domain",
"=",
"Permission",
".",
"get_domain",
"(",
"required",
")",
"# assigned is a list of json blobs:",
"assigned",
"=",
"self",
".",
"get_authzd_permissions",
"(",
"identifier",
",",
"domain",
")",
"is_permitted",
"=",
"False",
"for",
"perms_blob",
"in",
"assigned",
":",
"is_permitted",
"=",
"self",
".",
"permission_verifier",
".",
"is_permitted_from_json",
"(",
"required",
",",
"perms_blob",
")",
"yield",
"(",
"required",
",",
"is_permitted",
")"
] |
If the authorization info cannot be obtained from the accountstore,
permission check tuple yields False.
:type identifiers: subject_abcs.IdentifierCollection
:param permission_s: a collection of one or more permissions, represented
as string-based permissions or Permission objects
and NEVER comingled types
:type permission_s: list of string(s)
:yields: tuple(Permission, Boolean)
|
[
"If",
"the",
"authorization",
"info",
"cannot",
"be",
"obtained",
"from",
"the",
"accountstore",
"permission",
"check",
"tuple",
"yields",
"False",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/realm/realm.py#L377-L404
|
16,249
|
YosaiProject/yosai
|
yosai/core/realm/realm.py
|
AccountStoreRealm.has_role
|
def has_role(self, identifiers, required_role_s):
"""
Confirms whether a subject is a member of one or more roles.
If the authorization info cannot be obtained from the accountstore,
role check tuple yields False.
:type identifiers: subject_abcs.IdentifierCollection
:param required_role_s: a collection of 1..N Role identifiers
:type required_role_s: Set of String(s)
:yields: tuple(role, Boolean)
"""
identifier = identifiers.primary_identifier
# assigned_role_s is a set
assigned_role_s = self.get_authzd_roles(identifier)
if not assigned_role_s:
msg = 'has_role: no roles obtained from account_store for [{0}]'.\
format(identifier)
logger.warning(msg)
for role in required_role_s:
yield (role, False)
else:
for role in required_role_s:
hasrole = ({role} <= assigned_role_s)
yield (role, hasrole)
|
python
|
def has_role(self, identifiers, required_role_s):
"""
Confirms whether a subject is a member of one or more roles.
If the authorization info cannot be obtained from the accountstore,
role check tuple yields False.
:type identifiers: subject_abcs.IdentifierCollection
:param required_role_s: a collection of 1..N Role identifiers
:type required_role_s: Set of String(s)
:yields: tuple(role, Boolean)
"""
identifier = identifiers.primary_identifier
# assigned_role_s is a set
assigned_role_s = self.get_authzd_roles(identifier)
if not assigned_role_s:
msg = 'has_role: no roles obtained from account_store for [{0}]'.\
format(identifier)
logger.warning(msg)
for role in required_role_s:
yield (role, False)
else:
for role in required_role_s:
hasrole = ({role} <= assigned_role_s)
yield (role, hasrole)
|
[
"def",
"has_role",
"(",
"self",
",",
"identifiers",
",",
"required_role_s",
")",
":",
"identifier",
"=",
"identifiers",
".",
"primary_identifier",
"# assigned_role_s is a set",
"assigned_role_s",
"=",
"self",
".",
"get_authzd_roles",
"(",
"identifier",
")",
"if",
"not",
"assigned_role_s",
":",
"msg",
"=",
"'has_role: no roles obtained from account_store for [{0}]'",
".",
"format",
"(",
"identifier",
")",
"logger",
".",
"warning",
"(",
"msg",
")",
"for",
"role",
"in",
"required_role_s",
":",
"yield",
"(",
"role",
",",
"False",
")",
"else",
":",
"for",
"role",
"in",
"required_role_s",
":",
"hasrole",
"=",
"(",
"{",
"role",
"}",
"<=",
"assigned_role_s",
")",
"yield",
"(",
"role",
",",
"hasrole",
")"
] |
Confirms whether a subject is a member of one or more roles.
If the authorization info cannot be obtained from the accountstore,
role check tuple yields False.
:type identifiers: subject_abcs.IdentifierCollection
:param required_role_s: a collection of 1..N Role identifiers
:type required_role_s: Set of String(s)
:yields: tuple(role, Boolean)
|
[
"Confirms",
"whether",
"a",
"subject",
"is",
"a",
"member",
"of",
"one",
"or",
"more",
"roles",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/realm/realm.py#L406-L434
|
16,250
|
YosaiProject/yosai
|
yosai/web/session/session.py
|
WebSessionHandler.on_start
|
def on_start(self, session, session_context):
"""
Stores the Session's ID, usually as a Cookie, to associate with future
requests.
:param session: the session that was just ``createSession`` created
"""
session_id = session.session_id
web_registry = session_context['web_registry']
if self.is_session_id_cookie_enabled:
web_registry.session_id = session_id
logger.debug("Set SessionID cookie using id: " + str(session_id))
else:
msg = ("Session ID cookie is disabled. No cookie has been set for "
"new session with id: " + str(session_id))
logger.debug(msg)
|
python
|
def on_start(self, session, session_context):
"""
Stores the Session's ID, usually as a Cookie, to associate with future
requests.
:param session: the session that was just ``createSession`` created
"""
session_id = session.session_id
web_registry = session_context['web_registry']
if self.is_session_id_cookie_enabled:
web_registry.session_id = session_id
logger.debug("Set SessionID cookie using id: " + str(session_id))
else:
msg = ("Session ID cookie is disabled. No cookie has been set for "
"new session with id: " + str(session_id))
logger.debug(msg)
|
[
"def",
"on_start",
"(",
"self",
",",
"session",
",",
"session_context",
")",
":",
"session_id",
"=",
"session",
".",
"session_id",
"web_registry",
"=",
"session_context",
"[",
"'web_registry'",
"]",
"if",
"self",
".",
"is_session_id_cookie_enabled",
":",
"web_registry",
".",
"session_id",
"=",
"session_id",
"logger",
".",
"debug",
"(",
"\"Set SessionID cookie using id: \"",
"+",
"str",
"(",
"session_id",
")",
")",
"else",
":",
"msg",
"=",
"(",
"\"Session ID cookie is disabled. No cookie has been set for \"",
"\"new session with id: \"",
"+",
"str",
"(",
"session_id",
")",
")",
"logger",
".",
"debug",
"(",
"msg",
")"
] |
Stores the Session's ID, usually as a Cookie, to associate with future
requests.
:param session: the session that was just ``createSession`` created
|
[
"Stores",
"the",
"Session",
"s",
"ID",
"usually",
"as",
"a",
"Cookie",
"to",
"associate",
"with",
"future",
"requests",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/web/session/session.py#L95-L112
|
16,251
|
YosaiProject/yosai
|
yosai/web/session/session.py
|
WebSessionStorageEvaluator.is_session_storage_enabled
|
def is_session_storage_enabled(self, subject=None):
"""
Returns ``True`` if session storage is generally available (as determined
by the super class's global configuration property is_session_storage_enabled
and no request-specific override has turned off session storage, False
otherwise.
This means session storage is disabled if the is_session_storage_enabled
property is False or if a request attribute is discovered that turns off
session storage for the current request.
:param subject: the ``Subject`` for which session state persistence may
be enabled
:returns: ``True`` if session storage is generally available (as
determined by the super class's global configuration property
is_session_storage_enabled and no request-specific override has
turned off session storage, False otherwise.
"""
if subject.get_session(False):
# then use what already exists
return True
if not self.session_storage_enabled:
# honor global setting:
return False
# non-web subject instances can't be saved to web-only session managers:
if (not hasattr(subject, 'web_registry') and self.session_manager and
not isinstance(self.session_manager, session_abcs.NativeSessionManager)):
return False
return subject.web_registry.session_creation_enabled
|
python
|
def is_session_storage_enabled(self, subject=None):
"""
Returns ``True`` if session storage is generally available (as determined
by the super class's global configuration property is_session_storage_enabled
and no request-specific override has turned off session storage, False
otherwise.
This means session storage is disabled if the is_session_storage_enabled
property is False or if a request attribute is discovered that turns off
session storage for the current request.
:param subject: the ``Subject`` for which session state persistence may
be enabled
:returns: ``True`` if session storage is generally available (as
determined by the super class's global configuration property
is_session_storage_enabled and no request-specific override has
turned off session storage, False otherwise.
"""
if subject.get_session(False):
# then use what already exists
return True
if not self.session_storage_enabled:
# honor global setting:
return False
# non-web subject instances can't be saved to web-only session managers:
if (not hasattr(subject, 'web_registry') and self.session_manager and
not isinstance(self.session_manager, session_abcs.NativeSessionManager)):
return False
return subject.web_registry.session_creation_enabled
|
[
"def",
"is_session_storage_enabled",
"(",
"self",
",",
"subject",
"=",
"None",
")",
":",
"if",
"subject",
".",
"get_session",
"(",
"False",
")",
":",
"# then use what already exists",
"return",
"True",
"if",
"not",
"self",
".",
"session_storage_enabled",
":",
"# honor global setting:",
"return",
"False",
"# non-web subject instances can't be saved to web-only session managers:",
"if",
"(",
"not",
"hasattr",
"(",
"subject",
",",
"'web_registry'",
")",
"and",
"self",
".",
"session_manager",
"and",
"not",
"isinstance",
"(",
"self",
".",
"session_manager",
",",
"session_abcs",
".",
"NativeSessionManager",
")",
")",
":",
"return",
"False",
"return",
"subject",
".",
"web_registry",
".",
"session_creation_enabled"
] |
Returns ``True`` if session storage is generally available (as determined
by the super class's global configuration property is_session_storage_enabled
and no request-specific override has turned off session storage, False
otherwise.
This means session storage is disabled if the is_session_storage_enabled
property is False or if a request attribute is discovered that turns off
session storage for the current request.
:param subject: the ``Subject`` for which session state persistence may
be enabled
:returns: ``True`` if session storage is generally available (as
determined by the super class's global configuration property
is_session_storage_enabled and no request-specific override has
turned off session storage, False otherwise.
|
[
"Returns",
"True",
"if",
"session",
"storage",
"is",
"generally",
"available",
"(",
"as",
"determined",
"by",
"the",
"super",
"class",
"s",
"global",
"configuration",
"property",
"is_session_storage_enabled",
"and",
"no",
"request",
"-",
"specific",
"override",
"has",
"turned",
"off",
"session",
"storage",
"False",
"otherwise",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/web/session/session.py#L311-L343
|
16,252
|
YosaiProject/yosai
|
yosai/core/serialize/marshalling.py
|
default_marshaller
|
def default_marshaller(obj):
"""
Retrieve the state of the given object.
Calls the ``__getstate__()`` method of the object if available, otherwise returns the
``__dict__`` of the object.
:param obj: the object to marshal
:return: the marshalled object state
"""
if hasattr(obj, '__getstate__'):
return obj.__getstate__()
try:
return obj.__dict__
except AttributeError:
raise TypeError('{!r} has no __dict__ attribute and does not implement __getstate__()'
.format(obj.__class__.__name__))
|
python
|
def default_marshaller(obj):
"""
Retrieve the state of the given object.
Calls the ``__getstate__()`` method of the object if available, otherwise returns the
``__dict__`` of the object.
:param obj: the object to marshal
:return: the marshalled object state
"""
if hasattr(obj, '__getstate__'):
return obj.__getstate__()
try:
return obj.__dict__
except AttributeError:
raise TypeError('{!r} has no __dict__ attribute and does not implement __getstate__()'
.format(obj.__class__.__name__))
|
[
"def",
"default_marshaller",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'__getstate__'",
")",
":",
"return",
"obj",
".",
"__getstate__",
"(",
")",
"try",
":",
"return",
"obj",
".",
"__dict__",
"except",
"AttributeError",
":",
"raise",
"TypeError",
"(",
"'{!r} has no __dict__ attribute and does not implement __getstate__()'",
".",
"format",
"(",
"obj",
".",
"__class__",
".",
"__name__",
")",
")"
] |
Retrieve the state of the given object.
Calls the ``__getstate__()`` method of the object if available, otherwise returns the
``__dict__`` of the object.
:param obj: the object to marshal
:return: the marshalled object state
|
[
"Retrieve",
"the",
"state",
"of",
"the",
"given",
"object",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/serialize/marshalling.py#L5-L23
|
16,253
|
YosaiProject/yosai
|
yosai/core/serialize/marshalling.py
|
default_unmarshaller
|
def default_unmarshaller(instance, state):
"""
Restore the state of an object.
If the ``__setstate__()`` method exists on the instance, it is called with the state object
as the argument. Otherwise, the instance's ``__dict__`` is replaced with ``state``.
:param instance: an uninitialized instance
:param state: the state object, as returned by :func:`default_marshaller`
"""
if hasattr(instance, '__setstate__'):
instance.__setstate__(state)
else:
try:
instance.__dict__.update(state)
except AttributeError:
raise TypeError('{!r} has no __dict__ attribute and does not implement __setstate__()'
.format(instance.__class__.__name__))
|
python
|
def default_unmarshaller(instance, state):
"""
Restore the state of an object.
If the ``__setstate__()`` method exists on the instance, it is called with the state object
as the argument. Otherwise, the instance's ``__dict__`` is replaced with ``state``.
:param instance: an uninitialized instance
:param state: the state object, as returned by :func:`default_marshaller`
"""
if hasattr(instance, '__setstate__'):
instance.__setstate__(state)
else:
try:
instance.__dict__.update(state)
except AttributeError:
raise TypeError('{!r} has no __dict__ attribute and does not implement __setstate__()'
.format(instance.__class__.__name__))
|
[
"def",
"default_unmarshaller",
"(",
"instance",
",",
"state",
")",
":",
"if",
"hasattr",
"(",
"instance",
",",
"'__setstate__'",
")",
":",
"instance",
".",
"__setstate__",
"(",
"state",
")",
"else",
":",
"try",
":",
"instance",
".",
"__dict__",
".",
"update",
"(",
"state",
")",
"except",
"AttributeError",
":",
"raise",
"TypeError",
"(",
"'{!r} has no __dict__ attribute and does not implement __setstate__()'",
".",
"format",
"(",
"instance",
".",
"__class__",
".",
"__name__",
")",
")"
] |
Restore the state of an object.
If the ``__setstate__()`` method exists on the instance, it is called with the state object
as the argument. Otherwise, the instance's ``__dict__`` is replaced with ``state``.
:param instance: an uninitialized instance
:param state: the state object, as returned by :func:`default_marshaller`
|
[
"Restore",
"the",
"state",
"of",
"an",
"object",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/serialize/marshalling.py#L26-L44
|
16,254
|
YosaiProject/yosai
|
yosai/core/authc/authc.py
|
DefaultAuthenticator.do_authenticate_account
|
def do_authenticate_account(self, authc_token):
"""
Returns an account object only when the current token authenticates AND
the authentication process is complete, raising otherwise
:returns: Account
:raises AdditionalAuthenticationRequired: when additional tokens are required,
passing the account object
"""
try:
realms = self.token_realm_resolver[authc_token.__class__]
except KeyError:
raise KeyError('Unsupported Token Type Provided: ', authc_token.__class__.__name__)
if (len(self.realms) == 1):
account = self.authenticate_single_realm_account(realms[0], authc_token)
else:
account = self.authenticate_multi_realm_account(self.realms, authc_token)
cred_type = authc_token.token_info['cred_type']
attempts = account['authc_info'][cred_type].get('failed_attempts', [])
self.validate_locked(authc_token, attempts)
# TODO: refactor this to something less rigid as it is unreliable:
if len(account['authc_info']) > authc_token.token_info['tier']:
if self.mfa_dispatcher:
realm = self.token_realm_resolver[TOTPToken][0] # s/b only one
totp_token = realm.generate_totp_token(account)
mfa_info = account['authc_info']['totp_key']['2fa_info']
self.mfa_dispatcher.dispatch(authc_token.identifier,
mfa_info,
totp_token)
raise AdditionalAuthenticationRequired(account['account_id'])
return account
|
python
|
def do_authenticate_account(self, authc_token):
"""
Returns an account object only when the current token authenticates AND
the authentication process is complete, raising otherwise
:returns: Account
:raises AdditionalAuthenticationRequired: when additional tokens are required,
passing the account object
"""
try:
realms = self.token_realm_resolver[authc_token.__class__]
except KeyError:
raise KeyError('Unsupported Token Type Provided: ', authc_token.__class__.__name__)
if (len(self.realms) == 1):
account = self.authenticate_single_realm_account(realms[0], authc_token)
else:
account = self.authenticate_multi_realm_account(self.realms, authc_token)
cred_type = authc_token.token_info['cred_type']
attempts = account['authc_info'][cred_type].get('failed_attempts', [])
self.validate_locked(authc_token, attempts)
# TODO: refactor this to something less rigid as it is unreliable:
if len(account['authc_info']) > authc_token.token_info['tier']:
if self.mfa_dispatcher:
realm = self.token_realm_resolver[TOTPToken][0] # s/b only one
totp_token = realm.generate_totp_token(account)
mfa_info = account['authc_info']['totp_key']['2fa_info']
self.mfa_dispatcher.dispatch(authc_token.identifier,
mfa_info,
totp_token)
raise AdditionalAuthenticationRequired(account['account_id'])
return account
|
[
"def",
"do_authenticate_account",
"(",
"self",
",",
"authc_token",
")",
":",
"try",
":",
"realms",
"=",
"self",
".",
"token_realm_resolver",
"[",
"authc_token",
".",
"__class__",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"'Unsupported Token Type Provided: '",
",",
"authc_token",
".",
"__class__",
".",
"__name__",
")",
"if",
"(",
"len",
"(",
"self",
".",
"realms",
")",
"==",
"1",
")",
":",
"account",
"=",
"self",
".",
"authenticate_single_realm_account",
"(",
"realms",
"[",
"0",
"]",
",",
"authc_token",
")",
"else",
":",
"account",
"=",
"self",
".",
"authenticate_multi_realm_account",
"(",
"self",
".",
"realms",
",",
"authc_token",
")",
"cred_type",
"=",
"authc_token",
".",
"token_info",
"[",
"'cred_type'",
"]",
"attempts",
"=",
"account",
"[",
"'authc_info'",
"]",
"[",
"cred_type",
"]",
".",
"get",
"(",
"'failed_attempts'",
",",
"[",
"]",
")",
"self",
".",
"validate_locked",
"(",
"authc_token",
",",
"attempts",
")",
"# TODO: refactor this to something less rigid as it is unreliable:",
"if",
"len",
"(",
"account",
"[",
"'authc_info'",
"]",
")",
">",
"authc_token",
".",
"token_info",
"[",
"'tier'",
"]",
":",
"if",
"self",
".",
"mfa_dispatcher",
":",
"realm",
"=",
"self",
".",
"token_realm_resolver",
"[",
"TOTPToken",
"]",
"[",
"0",
"]",
"# s/b only one",
"totp_token",
"=",
"realm",
".",
"generate_totp_token",
"(",
"account",
")",
"mfa_info",
"=",
"account",
"[",
"'authc_info'",
"]",
"[",
"'totp_key'",
"]",
"[",
"'2fa_info'",
"]",
"self",
".",
"mfa_dispatcher",
".",
"dispatch",
"(",
"authc_token",
".",
"identifier",
",",
"mfa_info",
",",
"totp_token",
")",
"raise",
"AdditionalAuthenticationRequired",
"(",
"account",
"[",
"'account_id'",
"]",
")",
"return",
"account"
] |
Returns an account object only when the current token authenticates AND
the authentication process is complete, raising otherwise
:returns: Account
:raises AdditionalAuthenticationRequired: when additional tokens are required,
passing the account object
|
[
"Returns",
"an",
"account",
"object",
"only",
"when",
"the",
"current",
"token",
"authenticates",
"AND",
"the",
"authentication",
"process",
"is",
"complete",
"raising",
"otherwise"
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/authc/authc.py#L241-L274
|
16,255
|
YosaiProject/yosai
|
yosai/core/logging/formatters.py
|
JSONFormatter.extra_from_record
|
def extra_from_record(self, record):
"""Returns `extra` dict you passed to logger.
The `extra` keyword argument is used to populate the `__dict__` of
the `LogRecord`.
"""
return {
attr_name: record.__dict__[attr_name]
for attr_name in record.__dict__
if attr_name not in BUILTIN_ATTRS
}
|
python
|
def extra_from_record(self, record):
"""Returns `extra` dict you passed to logger.
The `extra` keyword argument is used to populate the `__dict__` of
the `LogRecord`.
"""
return {
attr_name: record.__dict__[attr_name]
for attr_name in record.__dict__
if attr_name not in BUILTIN_ATTRS
}
|
[
"def",
"extra_from_record",
"(",
"self",
",",
"record",
")",
":",
"return",
"{",
"attr_name",
":",
"record",
".",
"__dict__",
"[",
"attr_name",
"]",
"for",
"attr_name",
"in",
"record",
".",
"__dict__",
"if",
"attr_name",
"not",
"in",
"BUILTIN_ATTRS",
"}"
] |
Returns `extra` dict you passed to logger.
The `extra` keyword argument is used to populate the `__dict__` of
the `LogRecord`.
|
[
"Returns",
"extra",
"dict",
"you",
"passed",
"to",
"logger",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/logging/formatters.py#L37-L48
|
16,256
|
YosaiProject/yosai
|
yosai/core/subject/subject.py
|
SubjectStore.save
|
def save(self, subject):
"""
Saves the subject's state to the subject's ``Session`` only
if session storage is enabled for the subject. If session storage is
not enabled for the specific Subject, this method does nothing.
In either case, the argument Subject is returned directly (a new
``Subject`` instance is not created).
:param subject: the Subject instance for which its state will be
created or updated
:type subject: subject_abcs.Subject
:returns: the same Subject passed in (a new Subject instance is
not created).
"""
if (self.is_session_storage_enabled(subject)):
self.merge_identity(subject)
else:
msg = ("Session storage of subject state for Subject [{0}] has "
"been disabled: identity and authentication state are "
"expected to be initialized on every request or "
"invocation.".format(subject))
logger.debug(msg)
return subject
|
python
|
def save(self, subject):
"""
Saves the subject's state to the subject's ``Session`` only
if session storage is enabled for the subject. If session storage is
not enabled for the specific Subject, this method does nothing.
In either case, the argument Subject is returned directly (a new
``Subject`` instance is not created).
:param subject: the Subject instance for which its state will be
created or updated
:type subject: subject_abcs.Subject
:returns: the same Subject passed in (a new Subject instance is
not created).
"""
if (self.is_session_storage_enabled(subject)):
self.merge_identity(subject)
else:
msg = ("Session storage of subject state for Subject [{0}] has "
"been disabled: identity and authentication state are "
"expected to be initialized on every request or "
"invocation.".format(subject))
logger.debug(msg)
return subject
|
[
"def",
"save",
"(",
"self",
",",
"subject",
")",
":",
"if",
"(",
"self",
".",
"is_session_storage_enabled",
"(",
"subject",
")",
")",
":",
"self",
".",
"merge_identity",
"(",
"subject",
")",
"else",
":",
"msg",
"=",
"(",
"\"Session storage of subject state for Subject [{0}] has \"",
"\"been disabled: identity and authentication state are \"",
"\"expected to be initialized on every request or \"",
"\"invocation.\"",
".",
"format",
"(",
"subject",
")",
")",
"logger",
".",
"debug",
"(",
"msg",
")",
"return",
"subject"
] |
Saves the subject's state to the subject's ``Session`` only
if session storage is enabled for the subject. If session storage is
not enabled for the specific Subject, this method does nothing.
In either case, the argument Subject is returned directly (a new
``Subject`` instance is not created).
:param subject: the Subject instance for which its state will be
created or updated
:type subject: subject_abcs.Subject
:returns: the same Subject passed in (a new Subject instance is
not created).
|
[
"Saves",
"the",
"subject",
"s",
"state",
"to",
"the",
"subject",
"s",
"Session",
"only",
"if",
"session",
"storage",
"is",
"enabled",
"for",
"the",
"subject",
".",
"If",
"session",
"storage",
"is",
"not",
"enabled",
"for",
"the",
"specific",
"Subject",
"this",
"method",
"does",
"nothing",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/subject/subject.py#L656-L681
|
16,257
|
YosaiProject/yosai
|
yosai/core/subject/subject.py
|
SecurityManagerCreator.create_manager
|
def create_manager(self, yosai, settings, session_attributes):
"""
Order of execution matters. The sac must be set before the cache_handler is
instantiated so that the cache_handler's serialization manager instance
registers the sac.
"""
mgr_settings = SecurityManagerSettings(settings)
attributes = mgr_settings.attributes
realms = self._init_realms(settings, attributes['realms'])
session_attributes = self._init_session_attributes(session_attributes, attributes)
serialization_manager =\
SerializationManager(session_attributes,
serializer_scheme=attributes['serializer'])
# the cache_handler doesn't initialize a cache_realm until it gets
# a serialization manager, which is assigned within the SecurityManager
cache_handler = self._init_cache_handler(settings,
attributes['cache_handler'],
serialization_manager)
manager = mgr_settings.security_manager(yosai,
settings,
realms=realms,
cache_handler=cache_handler,
serialization_manager=serialization_manager)
return manager
|
python
|
def create_manager(self, yosai, settings, session_attributes):
"""
Order of execution matters. The sac must be set before the cache_handler is
instantiated so that the cache_handler's serialization manager instance
registers the sac.
"""
mgr_settings = SecurityManagerSettings(settings)
attributes = mgr_settings.attributes
realms = self._init_realms(settings, attributes['realms'])
session_attributes = self._init_session_attributes(session_attributes, attributes)
serialization_manager =\
SerializationManager(session_attributes,
serializer_scheme=attributes['serializer'])
# the cache_handler doesn't initialize a cache_realm until it gets
# a serialization manager, which is assigned within the SecurityManager
cache_handler = self._init_cache_handler(settings,
attributes['cache_handler'],
serialization_manager)
manager = mgr_settings.security_manager(yosai,
settings,
realms=realms,
cache_handler=cache_handler,
serialization_manager=serialization_manager)
return manager
|
[
"def",
"create_manager",
"(",
"self",
",",
"yosai",
",",
"settings",
",",
"session_attributes",
")",
":",
"mgr_settings",
"=",
"SecurityManagerSettings",
"(",
"settings",
")",
"attributes",
"=",
"mgr_settings",
".",
"attributes",
"realms",
"=",
"self",
".",
"_init_realms",
"(",
"settings",
",",
"attributes",
"[",
"'realms'",
"]",
")",
"session_attributes",
"=",
"self",
".",
"_init_session_attributes",
"(",
"session_attributes",
",",
"attributes",
")",
"serialization_manager",
"=",
"SerializationManager",
"(",
"session_attributes",
",",
"serializer_scheme",
"=",
"attributes",
"[",
"'serializer'",
"]",
")",
"# the cache_handler doesn't initialize a cache_realm until it gets",
"# a serialization manager, which is assigned within the SecurityManager",
"cache_handler",
"=",
"self",
".",
"_init_cache_handler",
"(",
"settings",
",",
"attributes",
"[",
"'cache_handler'",
"]",
",",
"serialization_manager",
")",
"manager",
"=",
"mgr_settings",
".",
"security_manager",
"(",
"yosai",
",",
"settings",
",",
"realms",
"=",
"realms",
",",
"cache_handler",
"=",
"cache_handler",
",",
"serialization_manager",
"=",
"serialization_manager",
")",
"return",
"manager"
] |
Order of execution matters. The sac must be set before the cache_handler is
instantiated so that the cache_handler's serialization manager instance
registers the sac.
|
[
"Order",
"of",
"execution",
"matters",
".",
"The",
"sac",
"must",
"be",
"set",
"before",
"the",
"cache_handler",
"is",
"instantiated",
"so",
"that",
"the",
"cache_handler",
"s",
"serialization",
"manager",
"instance",
"registers",
"the",
"sac",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/subject/subject.py#L1068-L1097
|
16,258
|
YosaiProject/yosai
|
yosai/core/authz/authz.py
|
ModularRealmAuthorizer.check_permission
|
def check_permission(self, identifiers, permission_s, logical_operator):
"""
like Yosai's authentication process, the authorization process will
raise an Exception to halt further authz checking once Yosai determines
that a Subject is unauthorized to receive the requested permission
:param identifiers: a collection of identifiers
:type identifiers: subject_abcs.IdentifierCollection
:param permission_s: a collection of 1..N permissions
:type permission_s: List of Permission objects or Strings
:param logical_operator: indicates whether all or at least one
permission check is true (any)
:type: any OR all (from python standard library)
:raises UnauthorizedException: if any permission is unauthorized
"""
self.assert_realms_configured()
permitted = self.is_permitted_collective(identifiers,
permission_s,
logical_operator)
if not permitted:
msg = "Subject lacks permission(s) to satisfy logical operation"
raise UnauthorizedException(msg)
|
python
|
def check_permission(self, identifiers, permission_s, logical_operator):
"""
like Yosai's authentication process, the authorization process will
raise an Exception to halt further authz checking once Yosai determines
that a Subject is unauthorized to receive the requested permission
:param identifiers: a collection of identifiers
:type identifiers: subject_abcs.IdentifierCollection
:param permission_s: a collection of 1..N permissions
:type permission_s: List of Permission objects or Strings
:param logical_operator: indicates whether all or at least one
permission check is true (any)
:type: any OR all (from python standard library)
:raises UnauthorizedException: if any permission is unauthorized
"""
self.assert_realms_configured()
permitted = self.is_permitted_collective(identifiers,
permission_s,
logical_operator)
if not permitted:
msg = "Subject lacks permission(s) to satisfy logical operation"
raise UnauthorizedException(msg)
|
[
"def",
"check_permission",
"(",
"self",
",",
"identifiers",
",",
"permission_s",
",",
"logical_operator",
")",
":",
"self",
".",
"assert_realms_configured",
"(",
")",
"permitted",
"=",
"self",
".",
"is_permitted_collective",
"(",
"identifiers",
",",
"permission_s",
",",
"logical_operator",
")",
"if",
"not",
"permitted",
":",
"msg",
"=",
"\"Subject lacks permission(s) to satisfy logical operation\"",
"raise",
"UnauthorizedException",
"(",
"msg",
")"
] |
like Yosai's authentication process, the authorization process will
raise an Exception to halt further authz checking once Yosai determines
that a Subject is unauthorized to receive the requested permission
:param identifiers: a collection of identifiers
:type identifiers: subject_abcs.IdentifierCollection
:param permission_s: a collection of 1..N permissions
:type permission_s: List of Permission objects or Strings
:param logical_operator: indicates whether all or at least one
permission check is true (any)
:type: any OR all (from python standard library)
:raises UnauthorizedException: if any permission is unauthorized
|
[
"like",
"Yosai",
"s",
"authentication",
"process",
"the",
"authorization",
"process",
"will",
"raise",
"an",
"Exception",
"to",
"halt",
"further",
"authz",
"checking",
"once",
"Yosai",
"determines",
"that",
"a",
"Subject",
"is",
"unauthorized",
"to",
"receive",
"the",
"requested",
"permission"
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/authz/authz.py#L292-L316
|
16,259
|
YosaiProject/yosai
|
yosai/core/subject/identifier.py
|
SimpleIdentifierCollection.by_type
|
def by_type(self, identifier_class):
"""
returns all unique instances of a type of identifier
:param identifier_class: the class to match identifier with
:returns: a tuple
"""
myidentifiers = set()
for identifier in self.source_identifiers.values():
if (isinstance(identifier, identifier_class)):
myidentifiers.update([identifier])
return set(myidentifiers)
|
python
|
def by_type(self, identifier_class):
"""
returns all unique instances of a type of identifier
:param identifier_class: the class to match identifier with
:returns: a tuple
"""
myidentifiers = set()
for identifier in self.source_identifiers.values():
if (isinstance(identifier, identifier_class)):
myidentifiers.update([identifier])
return set(myidentifiers)
|
[
"def",
"by_type",
"(",
"self",
",",
"identifier_class",
")",
":",
"myidentifiers",
"=",
"set",
"(",
")",
"for",
"identifier",
"in",
"self",
".",
"source_identifiers",
".",
"values",
"(",
")",
":",
"if",
"(",
"isinstance",
"(",
"identifier",
",",
"identifier_class",
")",
")",
":",
"myidentifiers",
".",
"update",
"(",
"[",
"identifier",
"]",
")",
"return",
"set",
"(",
"myidentifiers",
")"
] |
returns all unique instances of a type of identifier
:param identifier_class: the class to match identifier with
:returns: a tuple
|
[
"returns",
"all",
"unique",
"instances",
"of",
"a",
"type",
"of",
"identifier"
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/subject/identifier.py#L101-L112
|
16,260
|
YosaiProject/yosai
|
yosai/core/session/session.py
|
CachingSessionStore.create
|
def create(self, session):
"""
caches the session and caches an entry to associate the cached session
with the subject
"""
sessionid = super().create(session) # calls _do_create and verify
self._cache(session, sessionid)
return sessionid
|
python
|
def create(self, session):
"""
caches the session and caches an entry to associate the cached session
with the subject
"""
sessionid = super().create(session) # calls _do_create and verify
self._cache(session, sessionid)
return sessionid
|
[
"def",
"create",
"(",
"self",
",",
"session",
")",
":",
"sessionid",
"=",
"super",
"(",
")",
".",
"create",
"(",
"session",
")",
"# calls _do_create and verify",
"self",
".",
"_cache",
"(",
"session",
",",
"sessionid",
")",
"return",
"sessionid"
] |
caches the session and caches an entry to associate the cached session
with the subject
|
[
"caches",
"the",
"session",
"and",
"caches",
"an",
"entry",
"to",
"associate",
"the",
"cached",
"session",
"with",
"the",
"subject"
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/session/session.py#L213-L220
|
16,261
|
YosaiProject/yosai
|
yosai/core/session/session.py
|
NativeSessionManager.start
|
def start(self, session_context):
"""
unlike shiro, yosai does not apply session timeouts from within the
start method of the SessionManager but rather defers timeout settings
responsibilities to the SimpleSession, which uses session_settings
"""
# is a SimpleSesson:
session = self._create_session(session_context)
self.session_handler.on_start(session, session_context)
mysession = session_tuple(None, session.session_id)
self.notify_event(mysession, 'SESSION.START')
# Don't expose the EIS-tier Session object to the client-tier, but
# rather a DelegatingSession:
return self.create_exposed_session(session=session, context=session_context)
|
python
|
def start(self, session_context):
"""
unlike shiro, yosai does not apply session timeouts from within the
start method of the SessionManager but rather defers timeout settings
responsibilities to the SimpleSession, which uses session_settings
"""
# is a SimpleSesson:
session = self._create_session(session_context)
self.session_handler.on_start(session, session_context)
mysession = session_tuple(None, session.session_id)
self.notify_event(mysession, 'SESSION.START')
# Don't expose the EIS-tier Session object to the client-tier, but
# rather a DelegatingSession:
return self.create_exposed_session(session=session, context=session_context)
|
[
"def",
"start",
"(",
"self",
",",
"session_context",
")",
":",
"# is a SimpleSesson:",
"session",
"=",
"self",
".",
"_create_session",
"(",
"session_context",
")",
"self",
".",
"session_handler",
".",
"on_start",
"(",
"session",
",",
"session_context",
")",
"mysession",
"=",
"session_tuple",
"(",
"None",
",",
"session",
".",
"session_id",
")",
"self",
".",
"notify_event",
"(",
"mysession",
",",
"'SESSION.START'",
")",
"# Don't expose the EIS-tier Session object to the client-tier, but",
"# rather a DelegatingSession:",
"return",
"self",
".",
"create_exposed_session",
"(",
"session",
"=",
"session",
",",
"context",
"=",
"session_context",
")"
] |
unlike shiro, yosai does not apply session timeouts from within the
start method of the SessionManager but rather defers timeout settings
responsibilities to the SimpleSession, which uses session_settings
|
[
"unlike",
"shiro",
"yosai",
"does",
"not",
"apply",
"session",
"timeouts",
"from",
"within",
"the",
"start",
"method",
"of",
"the",
"SessionManager",
"but",
"rather",
"defers",
"timeout",
"settings",
"responsibilities",
"to",
"the",
"SimpleSession",
"which",
"uses",
"session_settings"
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/session/session.py#L921-L937
|
16,262
|
YosaiProject/yosai
|
yosai/core/conf/yosaisettings.py
|
LazySettings._setup
|
def _setup(self, name=None):
"""
Load the settings module referenced by env_var. This environment-
defined configuration process is called during the settings
configuration process.
"""
envvar = self.__dict__['env_var']
if envvar:
settings_file = os.environ.get(envvar)
else:
settings_file = self.__dict__['file_path']
if not settings_file:
msg = ("Requested settings, but none can be obtained for the envvar."
"Since no config filepath can be obtained, a default config "
"will be used.")
logger.error(msg)
raise OSError(msg)
self._wrapped = Settings(settings_file)
|
python
|
def _setup(self, name=None):
"""
Load the settings module referenced by env_var. This environment-
defined configuration process is called during the settings
configuration process.
"""
envvar = self.__dict__['env_var']
if envvar:
settings_file = os.environ.get(envvar)
else:
settings_file = self.__dict__['file_path']
if not settings_file:
msg = ("Requested settings, but none can be obtained for the envvar."
"Since no config filepath can be obtained, a default config "
"will be used.")
logger.error(msg)
raise OSError(msg)
self._wrapped = Settings(settings_file)
|
[
"def",
"_setup",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"envvar",
"=",
"self",
".",
"__dict__",
"[",
"'env_var'",
"]",
"if",
"envvar",
":",
"settings_file",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"envvar",
")",
"else",
":",
"settings_file",
"=",
"self",
".",
"__dict__",
"[",
"'file_path'",
"]",
"if",
"not",
"settings_file",
":",
"msg",
"=",
"(",
"\"Requested settings, but none can be obtained for the envvar.\"",
"\"Since no config filepath can be obtained, a default config \"",
"\"will be used.\"",
")",
"logger",
".",
"error",
"(",
"msg",
")",
"raise",
"OSError",
"(",
"msg",
")",
"self",
".",
"_wrapped",
"=",
"Settings",
"(",
"settings_file",
")"
] |
Load the settings module referenced by env_var. This environment-
defined configuration process is called during the settings
configuration process.
|
[
"Load",
"the",
"settings",
"module",
"referenced",
"by",
"env_var",
".",
"This",
"environment",
"-",
"defined",
"configuration",
"process",
"is",
"called",
"during",
"the",
"settings",
"configuration",
"process",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/conf/yosaisettings.py#L69-L88
|
16,263
|
YosaiProject/yosai
|
yosai/web/mgt/mgt.py
|
CookieRememberMeManager.remember_encrypted_identity
|
def remember_encrypted_identity(self, subject, encrypted):
"""
Base64-encodes the specified serialized byte array and sets that
base64-encoded String as the cookie value.
The ``subject`` instance is expected to be a ``WebSubject`` instance
with a web_registry handle so that an HTTP cookie may be set on an
outgoing response. If it is not a ``WebSubject`` or that ``WebSubject``
does not have a web_registry handle, this implementation does
nothing.
:param subject: the Subject for which the identity is being serialized
:param serialized: the serialized bytes to persist
:type serialized: bytearray
"""
try:
# base 64 encode it and store as a cookie:
encoded = base64.b64encode(encrypted).decode('utf-8')
subject.web_registry.remember_me = encoded
except AttributeError:
msg = ("Subject argument is not an HTTP-aware instance. This "
"is required to obtain a web registry in order to"
"set the RememberMe cookie. Returning immediately "
"and ignoring RememberMe operation.")
logger.debug(msg)
|
python
|
def remember_encrypted_identity(self, subject, encrypted):
"""
Base64-encodes the specified serialized byte array and sets that
base64-encoded String as the cookie value.
The ``subject`` instance is expected to be a ``WebSubject`` instance
with a web_registry handle so that an HTTP cookie may be set on an
outgoing response. If it is not a ``WebSubject`` or that ``WebSubject``
does not have a web_registry handle, this implementation does
nothing.
:param subject: the Subject for which the identity is being serialized
:param serialized: the serialized bytes to persist
:type serialized: bytearray
"""
try:
# base 64 encode it and store as a cookie:
encoded = base64.b64encode(encrypted).decode('utf-8')
subject.web_registry.remember_me = encoded
except AttributeError:
msg = ("Subject argument is not an HTTP-aware instance. This "
"is required to obtain a web registry in order to"
"set the RememberMe cookie. Returning immediately "
"and ignoring RememberMe operation.")
logger.debug(msg)
|
[
"def",
"remember_encrypted_identity",
"(",
"self",
",",
"subject",
",",
"encrypted",
")",
":",
"try",
":",
"# base 64 encode it and store as a cookie:",
"encoded",
"=",
"base64",
".",
"b64encode",
"(",
"encrypted",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"subject",
".",
"web_registry",
".",
"remember_me",
"=",
"encoded",
"except",
"AttributeError",
":",
"msg",
"=",
"(",
"\"Subject argument is not an HTTP-aware instance. This \"",
"\"is required to obtain a web registry in order to\"",
"\"set the RememberMe cookie. Returning immediately \"",
"\"and ignoring RememberMe operation.\"",
")",
"logger",
".",
"debug",
"(",
"msg",
")"
] |
Base64-encodes the specified serialized byte array and sets that
base64-encoded String as the cookie value.
The ``subject`` instance is expected to be a ``WebSubject`` instance
with a web_registry handle so that an HTTP cookie may be set on an
outgoing response. If it is not a ``WebSubject`` or that ``WebSubject``
does not have a web_registry handle, this implementation does
nothing.
:param subject: the Subject for which the identity is being serialized
:param serialized: the serialized bytes to persist
:type serialized: bytearray
|
[
"Base64",
"-",
"encodes",
"the",
"specified",
"serialized",
"byte",
"array",
"and",
"sets",
"that",
"base64",
"-",
"encoded",
"String",
"as",
"the",
"cookie",
"value",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/web/mgt/mgt.py#L156-L181
|
16,264
|
YosaiProject/yosai
|
yosai/web/mgt/mgt.py
|
CookieRememberMeManager.get_remembered_encrypted_identity
|
def get_remembered_encrypted_identity(self, subject_context):
"""
Returns a previously serialized identity byte array or None if the byte
array could not be acquired.
This implementation retrieves an HTTP cookie, Base64-decodes the cookie
value, and returns the resulting byte array.
The ``subject_context`` instance is expected to be a ``WebSubjectContext``
instance with a web_registry so that an HTTP cookie may be
retrieved from an incoming request. If it is not a ``WebSubjectContext``
or is one yet does not have a web_registry, this implementation returns
None.
:param subject_context: the contextual data used to construct a ``Subject`` instance
:returns: an encrypted, serialized identifier collection
"""
if (self.is_identity_removed(subject_context)):
if not isinstance(subject_context, web_subject_abcs.WebSubjectContext):
msg = ("SubjectContext argument is not an HTTP-aware instance. "
"This is required to obtain a web registry "
"in order to retrieve the RememberMe cookie. Returning "
"immediately and ignoring rememberMe operation.")
logger.debug(msg)
return None
remember_me = subject_context.web_registry.remember_me
# TBD:
# Browsers do not always remove cookies immediately
# ignore cookies that are scheduled for removal
# if (web_wsgi_abcs.Cookie.DELETED_COOKIE_VALUE.equals(base64)):
# return None
if remember_me:
logger.debug("Acquired encoded identity [" + str(remember_me) + "]")
encrypted = base64.b64decode(remember_me)
return encrypted
else:
# no cookie set - new site visitor?
return None
|
python
|
def get_remembered_encrypted_identity(self, subject_context):
"""
Returns a previously serialized identity byte array or None if the byte
array could not be acquired.
This implementation retrieves an HTTP cookie, Base64-decodes the cookie
value, and returns the resulting byte array.
The ``subject_context`` instance is expected to be a ``WebSubjectContext``
instance with a web_registry so that an HTTP cookie may be
retrieved from an incoming request. If it is not a ``WebSubjectContext``
or is one yet does not have a web_registry, this implementation returns
None.
:param subject_context: the contextual data used to construct a ``Subject`` instance
:returns: an encrypted, serialized identifier collection
"""
if (self.is_identity_removed(subject_context)):
if not isinstance(subject_context, web_subject_abcs.WebSubjectContext):
msg = ("SubjectContext argument is not an HTTP-aware instance. "
"This is required to obtain a web registry "
"in order to retrieve the RememberMe cookie. Returning "
"immediately and ignoring rememberMe operation.")
logger.debug(msg)
return None
remember_me = subject_context.web_registry.remember_me
# TBD:
# Browsers do not always remove cookies immediately
# ignore cookies that are scheduled for removal
# if (web_wsgi_abcs.Cookie.DELETED_COOKIE_VALUE.equals(base64)):
# return None
if remember_me:
logger.debug("Acquired encoded identity [" + str(remember_me) + "]")
encrypted = base64.b64decode(remember_me)
return encrypted
else:
# no cookie set - new site visitor?
return None
|
[
"def",
"get_remembered_encrypted_identity",
"(",
"self",
",",
"subject_context",
")",
":",
"if",
"(",
"self",
".",
"is_identity_removed",
"(",
"subject_context",
")",
")",
":",
"if",
"not",
"isinstance",
"(",
"subject_context",
",",
"web_subject_abcs",
".",
"WebSubjectContext",
")",
":",
"msg",
"=",
"(",
"\"SubjectContext argument is not an HTTP-aware instance. \"",
"\"This is required to obtain a web registry \"",
"\"in order to retrieve the RememberMe cookie. Returning \"",
"\"immediately and ignoring rememberMe operation.\"",
")",
"logger",
".",
"debug",
"(",
"msg",
")",
"return",
"None",
"remember_me",
"=",
"subject_context",
".",
"web_registry",
".",
"remember_me",
"# TBD:",
"# Browsers do not always remove cookies immediately",
"# ignore cookies that are scheduled for removal",
"# if (web_wsgi_abcs.Cookie.DELETED_COOKIE_VALUE.equals(base64)):",
"# return None",
"if",
"remember_me",
":",
"logger",
".",
"debug",
"(",
"\"Acquired encoded identity [\"",
"+",
"str",
"(",
"remember_me",
")",
"+",
"\"]\"",
")",
"encrypted",
"=",
"base64",
".",
"b64decode",
"(",
"remember_me",
")",
"return",
"encrypted",
"else",
":",
"# no cookie set - new site visitor?",
"return",
"None"
] |
Returns a previously serialized identity byte array or None if the byte
array could not be acquired.
This implementation retrieves an HTTP cookie, Base64-decodes the cookie
value, and returns the resulting byte array.
The ``subject_context`` instance is expected to be a ``WebSubjectContext``
instance with a web_registry so that an HTTP cookie may be
retrieved from an incoming request. If it is not a ``WebSubjectContext``
or is one yet does not have a web_registry, this implementation returns
None.
:param subject_context: the contextual data used to construct a ``Subject`` instance
:returns: an encrypted, serialized identifier collection
|
[
"Returns",
"a",
"previously",
"serialized",
"identity",
"byte",
"array",
"or",
"None",
"if",
"the",
"byte",
"array",
"could",
"not",
"be",
"acquired",
"."
] |
7f96aa6b837ceae9bf3d7387cd7e35f5ab032575
|
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/web/mgt/mgt.py#L190-L235
|
16,265
|
jobec/django-auth-adfs
|
django_auth_adfs/config.py
|
_get_settings_class
|
def _get_settings_class():
"""
Get the AUTH_ADFS setting from the Django settings.
"""
if not hasattr(django_settings, "AUTH_ADFS"):
msg = "The configuration directive 'AUTH_ADFS' was not found in your Django settings"
raise ImproperlyConfigured(msg)
cls = django_settings.AUTH_ADFS.get('SETTINGS_CLASS', DEFAULT_SETTINGS_CLASS)
return import_string(cls)
|
python
|
def _get_settings_class():
"""
Get the AUTH_ADFS setting from the Django settings.
"""
if not hasattr(django_settings, "AUTH_ADFS"):
msg = "The configuration directive 'AUTH_ADFS' was not found in your Django settings"
raise ImproperlyConfigured(msg)
cls = django_settings.AUTH_ADFS.get('SETTINGS_CLASS', DEFAULT_SETTINGS_CLASS)
return import_string(cls)
|
[
"def",
"_get_settings_class",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"django_settings",
",",
"\"AUTH_ADFS\"",
")",
":",
"msg",
"=",
"\"The configuration directive 'AUTH_ADFS' was not found in your Django settings\"",
"raise",
"ImproperlyConfigured",
"(",
"msg",
")",
"cls",
"=",
"django_settings",
".",
"AUTH_ADFS",
".",
"get",
"(",
"'SETTINGS_CLASS'",
",",
"DEFAULT_SETTINGS_CLASS",
")",
"return",
"import_string",
"(",
"cls",
")"
] |
Get the AUTH_ADFS setting from the Django settings.
|
[
"Get",
"the",
"AUTH_ADFS",
"setting",
"from",
"the",
"Django",
"settings",
"."
] |
07197be392724d16a6132b03d9eafb1d634749cf
|
https://github.com/jobec/django-auth-adfs/blob/07197be392724d16a6132b03d9eafb1d634749cf/django_auth_adfs/config.py#L33-L41
|
16,266
|
jobec/django-auth-adfs
|
django_auth_adfs/config.py
|
ProviderConfig.build_authorization_endpoint
|
def build_authorization_endpoint(self, request, disable_sso=None):
"""
This function returns the ADFS authorization URL.
Args:
request(django.http.request.HttpRequest): A django Request object
disable_sso(bool): Whether to disable single sign-on and force the ADFS server to show a login prompt.
Returns:
str: The redirect URI
"""
self.load_config()
redirect_to = request.GET.get(REDIRECT_FIELD_NAME, None)
if not redirect_to:
redirect_to = django_settings.LOGIN_REDIRECT_URL
redirect_to = base64.urlsafe_b64encode(redirect_to.encode()).decode()
query = QueryDict(mutable=True)
query.update({
"response_type": "code",
"client_id": settings.CLIENT_ID,
"resource": settings.RELYING_PARTY_ID,
"redirect_uri": self.redirect_uri(request),
"state": redirect_to,
})
if self._mode == "openid_connect":
query["scope"] = "openid"
if (disable_sso is None and settings.DISABLE_SSO) or disable_sso is True:
query["prompt"] = "login"
return "{0}?{1}".format(self.authorization_endpoint, query.urlencode())
|
python
|
def build_authorization_endpoint(self, request, disable_sso=None):
"""
This function returns the ADFS authorization URL.
Args:
request(django.http.request.HttpRequest): A django Request object
disable_sso(bool): Whether to disable single sign-on and force the ADFS server to show a login prompt.
Returns:
str: The redirect URI
"""
self.load_config()
redirect_to = request.GET.get(REDIRECT_FIELD_NAME, None)
if not redirect_to:
redirect_to = django_settings.LOGIN_REDIRECT_URL
redirect_to = base64.urlsafe_b64encode(redirect_to.encode()).decode()
query = QueryDict(mutable=True)
query.update({
"response_type": "code",
"client_id": settings.CLIENT_ID,
"resource": settings.RELYING_PARTY_ID,
"redirect_uri": self.redirect_uri(request),
"state": redirect_to,
})
if self._mode == "openid_connect":
query["scope"] = "openid"
if (disable_sso is None and settings.DISABLE_SSO) or disable_sso is True:
query["prompt"] = "login"
return "{0}?{1}".format(self.authorization_endpoint, query.urlencode())
|
[
"def",
"build_authorization_endpoint",
"(",
"self",
",",
"request",
",",
"disable_sso",
"=",
"None",
")",
":",
"self",
".",
"load_config",
"(",
")",
"redirect_to",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"REDIRECT_FIELD_NAME",
",",
"None",
")",
"if",
"not",
"redirect_to",
":",
"redirect_to",
"=",
"django_settings",
".",
"LOGIN_REDIRECT_URL",
"redirect_to",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"redirect_to",
".",
"encode",
"(",
")",
")",
".",
"decode",
"(",
")",
"query",
"=",
"QueryDict",
"(",
"mutable",
"=",
"True",
")",
"query",
".",
"update",
"(",
"{",
"\"response_type\"",
":",
"\"code\"",
",",
"\"client_id\"",
":",
"settings",
".",
"CLIENT_ID",
",",
"\"resource\"",
":",
"settings",
".",
"RELYING_PARTY_ID",
",",
"\"redirect_uri\"",
":",
"self",
".",
"redirect_uri",
"(",
"request",
")",
",",
"\"state\"",
":",
"redirect_to",
",",
"}",
")",
"if",
"self",
".",
"_mode",
"==",
"\"openid_connect\"",
":",
"query",
"[",
"\"scope\"",
"]",
"=",
"\"openid\"",
"if",
"(",
"disable_sso",
"is",
"None",
"and",
"settings",
".",
"DISABLE_SSO",
")",
"or",
"disable_sso",
"is",
"True",
":",
"query",
"[",
"\"prompt\"",
"]",
"=",
"\"login\"",
"return",
"\"{0}?{1}\"",
".",
"format",
"(",
"self",
".",
"authorization_endpoint",
",",
"query",
".",
"urlencode",
"(",
")",
")"
] |
This function returns the ADFS authorization URL.
Args:
request(django.http.request.HttpRequest): A django Request object
disable_sso(bool): Whether to disable single sign-on and force the ADFS server to show a login prompt.
Returns:
str: The redirect URI
|
[
"This",
"function",
"returns",
"the",
"ADFS",
"authorization",
"URL",
"."
] |
07197be392724d16a6132b03d9eafb1d634749cf
|
https://github.com/jobec/django-auth-adfs/blob/07197be392724d16a6132b03d9eafb1d634749cf/django_auth_adfs/config.py#L283-L313
|
16,267
|
jobec/django-auth-adfs
|
django_auth_adfs/backend.py
|
AdfsBaseBackend.create_user
|
def create_user(self, claims):
"""
Create the user if it doesn't exist yet
Args:
claims (dict): claims from the access token
Returns:
django.contrib.auth.models.User: A Django user
"""
# Create the user
username_claim = settings.USERNAME_CLAIM
usermodel = get_user_model()
user, created = usermodel.objects.get_or_create(**{
usermodel.USERNAME_FIELD: claims[username_claim]
})
if created or not user.password:
user.set_unusable_password()
logger.debug("User '{}' has been created.".format(claims[username_claim]))
return user
|
python
|
def create_user(self, claims):
"""
Create the user if it doesn't exist yet
Args:
claims (dict): claims from the access token
Returns:
django.contrib.auth.models.User: A Django user
"""
# Create the user
username_claim = settings.USERNAME_CLAIM
usermodel = get_user_model()
user, created = usermodel.objects.get_or_create(**{
usermodel.USERNAME_FIELD: claims[username_claim]
})
if created or not user.password:
user.set_unusable_password()
logger.debug("User '{}' has been created.".format(claims[username_claim]))
return user
|
[
"def",
"create_user",
"(",
"self",
",",
"claims",
")",
":",
"# Create the user",
"username_claim",
"=",
"settings",
".",
"USERNAME_CLAIM",
"usermodel",
"=",
"get_user_model",
"(",
")",
"user",
",",
"created",
"=",
"usermodel",
".",
"objects",
".",
"get_or_create",
"(",
"*",
"*",
"{",
"usermodel",
".",
"USERNAME_FIELD",
":",
"claims",
"[",
"username_claim",
"]",
"}",
")",
"if",
"created",
"or",
"not",
"user",
".",
"password",
":",
"user",
".",
"set_unusable_password",
"(",
")",
"logger",
".",
"debug",
"(",
"\"User '{}' has been created.\"",
".",
"format",
"(",
"claims",
"[",
"username_claim",
"]",
")",
")",
"return",
"user"
] |
Create the user if it doesn't exist yet
Args:
claims (dict): claims from the access token
Returns:
django.contrib.auth.models.User: A Django user
|
[
"Create",
"the",
"user",
"if",
"it",
"doesn",
"t",
"exist",
"yet"
] |
07197be392724d16a6132b03d9eafb1d634749cf
|
https://github.com/jobec/django-auth-adfs/blob/07197be392724d16a6132b03d9eafb1d634749cf/django_auth_adfs/backend.py#L110-L130
|
16,268
|
jobec/django-auth-adfs
|
django_auth_adfs/backend.py
|
AdfsBaseBackend.update_user_attributes
|
def update_user_attributes(self, user, claims):
"""
Updates user attributes based on the CLAIM_MAPPING setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): claims from the access token
"""
required_fields = [field.name for field in user._meta.fields if field.blank is False]
for field, claim in settings.CLAIM_MAPPING.items():
if hasattr(user, field):
if claim in claims:
setattr(user, field, claims[claim])
logger.debug("Attribute '{}' for user '{}' was set to '{}'.".format(field, user, claims[claim]))
else:
if field in required_fields:
msg = "Claim not found in access token: '{}'. Check ADFS claims mapping."
raise ImproperlyConfigured(msg.format(claim))
else:
msg = "Claim '{}' for user field '{}' was not found in the access token for user '{}'. " \
"Field is not required and will be left empty".format(claim, field, user)
logger.warning(msg)
else:
msg = "User model has no field named '{}'. Check ADFS claims mapping."
raise ImproperlyConfigured(msg.format(field))
|
python
|
def update_user_attributes(self, user, claims):
"""
Updates user attributes based on the CLAIM_MAPPING setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): claims from the access token
"""
required_fields = [field.name for field in user._meta.fields if field.blank is False]
for field, claim in settings.CLAIM_MAPPING.items():
if hasattr(user, field):
if claim in claims:
setattr(user, field, claims[claim])
logger.debug("Attribute '{}' for user '{}' was set to '{}'.".format(field, user, claims[claim]))
else:
if field in required_fields:
msg = "Claim not found in access token: '{}'. Check ADFS claims mapping."
raise ImproperlyConfigured(msg.format(claim))
else:
msg = "Claim '{}' for user field '{}' was not found in the access token for user '{}'. " \
"Field is not required and will be left empty".format(claim, field, user)
logger.warning(msg)
else:
msg = "User model has no field named '{}'. Check ADFS claims mapping."
raise ImproperlyConfigured(msg.format(field))
|
[
"def",
"update_user_attributes",
"(",
"self",
",",
"user",
",",
"claims",
")",
":",
"required_fields",
"=",
"[",
"field",
".",
"name",
"for",
"field",
"in",
"user",
".",
"_meta",
".",
"fields",
"if",
"field",
".",
"blank",
"is",
"False",
"]",
"for",
"field",
",",
"claim",
"in",
"settings",
".",
"CLAIM_MAPPING",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"user",
",",
"field",
")",
":",
"if",
"claim",
"in",
"claims",
":",
"setattr",
"(",
"user",
",",
"field",
",",
"claims",
"[",
"claim",
"]",
")",
"logger",
".",
"debug",
"(",
"\"Attribute '{}' for user '{}' was set to '{}'.\"",
".",
"format",
"(",
"field",
",",
"user",
",",
"claims",
"[",
"claim",
"]",
")",
")",
"else",
":",
"if",
"field",
"in",
"required_fields",
":",
"msg",
"=",
"\"Claim not found in access token: '{}'. Check ADFS claims mapping.\"",
"raise",
"ImproperlyConfigured",
"(",
"msg",
".",
"format",
"(",
"claim",
")",
")",
"else",
":",
"msg",
"=",
"\"Claim '{}' for user field '{}' was not found in the access token for user '{}'. \"",
"\"Field is not required and will be left empty\"",
".",
"format",
"(",
"claim",
",",
"field",
",",
"user",
")",
"logger",
".",
"warning",
"(",
"msg",
")",
"else",
":",
"msg",
"=",
"\"User model has no field named '{}'. Check ADFS claims mapping.\"",
"raise",
"ImproperlyConfigured",
"(",
"msg",
".",
"format",
"(",
"field",
")",
")"
] |
Updates user attributes based on the CLAIM_MAPPING setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): claims from the access token
|
[
"Updates",
"user",
"attributes",
"based",
"on",
"the",
"CLAIM_MAPPING",
"setting",
"."
] |
07197be392724d16a6132b03d9eafb1d634749cf
|
https://github.com/jobec/django-auth-adfs/blob/07197be392724d16a6132b03d9eafb1d634749cf/django_auth_adfs/backend.py#L132-L158
|
16,269
|
jobec/django-auth-adfs
|
django_auth_adfs/backend.py
|
AdfsBaseBackend.update_user_groups
|
def update_user_groups(self, user, claims):
"""
Updates user group memberships based on the GROUPS_CLAIM setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): Claims from the access token
"""
if settings.GROUPS_CLAIM is not None:
# Update the user's group memberships
django_groups = [group.name for group in user.groups.all()]
if settings.GROUPS_CLAIM in claims:
claim_groups = claims[settings.GROUPS_CLAIM]
if not isinstance(claim_groups, list):
claim_groups = [claim_groups, ]
else:
logger.debug(
"The configured groups claim '{}' was not found in the access token".format(settings.GROUPS_CLAIM))
claim_groups = []
# Make a diff of the user's groups.
# Removing a user from all groups and then re-add them would cause
# the autoincrement value for the database table storing the
# user-to-group mappings to increment for no reason.
groups_to_remove = set(django_groups) - set(claim_groups)
groups_to_add = set(claim_groups) - set(django_groups)
# Loop through the groups in the group claim and
# add the user to these groups as needed.
for group_name in groups_to_remove:
group = Group.objects.get(name=group_name)
user.groups.remove(group)
logger.debug("User removed from group '{}'".format(group_name))
for group_name in groups_to_add:
try:
if settings.MIRROR_GROUPS:
group, _ = Group.objects.get_or_create(name=group_name)
logger.debug("Created group '{}'".format(group_name))
else:
group = Group.objects.get(name=group_name)
user.groups.add(group)
logger.debug("User added to group '{}'".format(group_name))
except ObjectDoesNotExist:
# Silently fail for non-existing groups.
pass
|
python
|
def update_user_groups(self, user, claims):
"""
Updates user group memberships based on the GROUPS_CLAIM setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): Claims from the access token
"""
if settings.GROUPS_CLAIM is not None:
# Update the user's group memberships
django_groups = [group.name for group in user.groups.all()]
if settings.GROUPS_CLAIM in claims:
claim_groups = claims[settings.GROUPS_CLAIM]
if not isinstance(claim_groups, list):
claim_groups = [claim_groups, ]
else:
logger.debug(
"The configured groups claim '{}' was not found in the access token".format(settings.GROUPS_CLAIM))
claim_groups = []
# Make a diff of the user's groups.
# Removing a user from all groups and then re-add them would cause
# the autoincrement value for the database table storing the
# user-to-group mappings to increment for no reason.
groups_to_remove = set(django_groups) - set(claim_groups)
groups_to_add = set(claim_groups) - set(django_groups)
# Loop through the groups in the group claim and
# add the user to these groups as needed.
for group_name in groups_to_remove:
group = Group.objects.get(name=group_name)
user.groups.remove(group)
logger.debug("User removed from group '{}'".format(group_name))
for group_name in groups_to_add:
try:
if settings.MIRROR_GROUPS:
group, _ = Group.objects.get_or_create(name=group_name)
logger.debug("Created group '{}'".format(group_name))
else:
group = Group.objects.get(name=group_name)
user.groups.add(group)
logger.debug("User added to group '{}'".format(group_name))
except ObjectDoesNotExist:
# Silently fail for non-existing groups.
pass
|
[
"def",
"update_user_groups",
"(",
"self",
",",
"user",
",",
"claims",
")",
":",
"if",
"settings",
".",
"GROUPS_CLAIM",
"is",
"not",
"None",
":",
"# Update the user's group memberships",
"django_groups",
"=",
"[",
"group",
".",
"name",
"for",
"group",
"in",
"user",
".",
"groups",
".",
"all",
"(",
")",
"]",
"if",
"settings",
".",
"GROUPS_CLAIM",
"in",
"claims",
":",
"claim_groups",
"=",
"claims",
"[",
"settings",
".",
"GROUPS_CLAIM",
"]",
"if",
"not",
"isinstance",
"(",
"claim_groups",
",",
"list",
")",
":",
"claim_groups",
"=",
"[",
"claim_groups",
",",
"]",
"else",
":",
"logger",
".",
"debug",
"(",
"\"The configured groups claim '{}' was not found in the access token\"",
".",
"format",
"(",
"settings",
".",
"GROUPS_CLAIM",
")",
")",
"claim_groups",
"=",
"[",
"]",
"# Make a diff of the user's groups.",
"# Removing a user from all groups and then re-add them would cause",
"# the autoincrement value for the database table storing the",
"# user-to-group mappings to increment for no reason.",
"groups_to_remove",
"=",
"set",
"(",
"django_groups",
")",
"-",
"set",
"(",
"claim_groups",
")",
"groups_to_add",
"=",
"set",
"(",
"claim_groups",
")",
"-",
"set",
"(",
"django_groups",
")",
"# Loop through the groups in the group claim and",
"# add the user to these groups as needed.",
"for",
"group_name",
"in",
"groups_to_remove",
":",
"group",
"=",
"Group",
".",
"objects",
".",
"get",
"(",
"name",
"=",
"group_name",
")",
"user",
".",
"groups",
".",
"remove",
"(",
"group",
")",
"logger",
".",
"debug",
"(",
"\"User removed from group '{}'\"",
".",
"format",
"(",
"group_name",
")",
")",
"for",
"group_name",
"in",
"groups_to_add",
":",
"try",
":",
"if",
"settings",
".",
"MIRROR_GROUPS",
":",
"group",
",",
"_",
"=",
"Group",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"group_name",
")",
"logger",
".",
"debug",
"(",
"\"Created group '{}'\"",
".",
"format",
"(",
"group_name",
")",
")",
"else",
":",
"group",
"=",
"Group",
".",
"objects",
".",
"get",
"(",
"name",
"=",
"group_name",
")",
"user",
".",
"groups",
".",
"add",
"(",
"group",
")",
"logger",
".",
"debug",
"(",
"\"User added to group '{}'\"",
".",
"format",
"(",
"group_name",
")",
")",
"except",
"ObjectDoesNotExist",
":",
"# Silently fail for non-existing groups.",
"pass"
] |
Updates user group memberships based on the GROUPS_CLAIM setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): Claims from the access token
|
[
"Updates",
"user",
"group",
"memberships",
"based",
"on",
"the",
"GROUPS_CLAIM",
"setting",
"."
] |
07197be392724d16a6132b03d9eafb1d634749cf
|
https://github.com/jobec/django-auth-adfs/blob/07197be392724d16a6132b03d9eafb1d634749cf/django_auth_adfs/backend.py#L160-L206
|
16,270
|
jobec/django-auth-adfs
|
django_auth_adfs/backend.py
|
AdfsBaseBackend.update_user_flags
|
def update_user_flags(self, user, claims):
"""
Updates user boolean attributes based on the BOOLEAN_CLAIM_MAPPING setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): Claims from the access token
"""
if settings.GROUPS_CLAIM is not None:
if settings.GROUPS_CLAIM in claims:
access_token_groups = claims[settings.GROUPS_CLAIM]
if not isinstance(access_token_groups, list):
access_token_groups = [access_token_groups, ]
else:
logger.debug("The configured group claim was not found in the access token")
access_token_groups = []
for flag, group in settings.GROUP_TO_FLAG_MAPPING.items():
if hasattr(user, flag):
if group in access_token_groups:
value = True
else:
value = False
setattr(user, flag, value)
logger.debug("Attribute '{}' for user '{}' was set to '{}'.".format(user, flag, value))
else:
msg = "User model has no field named '{}'. Check ADFS boolean claims mapping."
raise ImproperlyConfigured(msg.format(flag))
for field, claim in settings.BOOLEAN_CLAIM_MAPPING.items():
if hasattr(user, field):
bool_val = False
if claim in claims and str(claims[claim]).lower() in ['y', 'yes', 't', 'true', 'on', '1']:
bool_val = True
setattr(user, field, bool_val)
logger.debug('Attribute "{}" for user "{}" was set to "{}".'.format(user, field, bool_val))
else:
msg = "User model has no field named '{}'. Check ADFS boolean claims mapping."
raise ImproperlyConfigured(msg.format(field))
|
python
|
def update_user_flags(self, user, claims):
"""
Updates user boolean attributes based on the BOOLEAN_CLAIM_MAPPING setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): Claims from the access token
"""
if settings.GROUPS_CLAIM is not None:
if settings.GROUPS_CLAIM in claims:
access_token_groups = claims[settings.GROUPS_CLAIM]
if not isinstance(access_token_groups, list):
access_token_groups = [access_token_groups, ]
else:
logger.debug("The configured group claim was not found in the access token")
access_token_groups = []
for flag, group in settings.GROUP_TO_FLAG_MAPPING.items():
if hasattr(user, flag):
if group in access_token_groups:
value = True
else:
value = False
setattr(user, flag, value)
logger.debug("Attribute '{}' for user '{}' was set to '{}'.".format(user, flag, value))
else:
msg = "User model has no field named '{}'. Check ADFS boolean claims mapping."
raise ImproperlyConfigured(msg.format(flag))
for field, claim in settings.BOOLEAN_CLAIM_MAPPING.items():
if hasattr(user, field):
bool_val = False
if claim in claims and str(claims[claim]).lower() in ['y', 'yes', 't', 'true', 'on', '1']:
bool_val = True
setattr(user, field, bool_val)
logger.debug('Attribute "{}" for user "{}" was set to "{}".'.format(user, field, bool_val))
else:
msg = "User model has no field named '{}'. Check ADFS boolean claims mapping."
raise ImproperlyConfigured(msg.format(field))
|
[
"def",
"update_user_flags",
"(",
"self",
",",
"user",
",",
"claims",
")",
":",
"if",
"settings",
".",
"GROUPS_CLAIM",
"is",
"not",
"None",
":",
"if",
"settings",
".",
"GROUPS_CLAIM",
"in",
"claims",
":",
"access_token_groups",
"=",
"claims",
"[",
"settings",
".",
"GROUPS_CLAIM",
"]",
"if",
"not",
"isinstance",
"(",
"access_token_groups",
",",
"list",
")",
":",
"access_token_groups",
"=",
"[",
"access_token_groups",
",",
"]",
"else",
":",
"logger",
".",
"debug",
"(",
"\"The configured group claim was not found in the access token\"",
")",
"access_token_groups",
"=",
"[",
"]",
"for",
"flag",
",",
"group",
"in",
"settings",
".",
"GROUP_TO_FLAG_MAPPING",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"user",
",",
"flag",
")",
":",
"if",
"group",
"in",
"access_token_groups",
":",
"value",
"=",
"True",
"else",
":",
"value",
"=",
"False",
"setattr",
"(",
"user",
",",
"flag",
",",
"value",
")",
"logger",
".",
"debug",
"(",
"\"Attribute '{}' for user '{}' was set to '{}'.\"",
".",
"format",
"(",
"user",
",",
"flag",
",",
"value",
")",
")",
"else",
":",
"msg",
"=",
"\"User model has no field named '{}'. Check ADFS boolean claims mapping.\"",
"raise",
"ImproperlyConfigured",
"(",
"msg",
".",
"format",
"(",
"flag",
")",
")",
"for",
"field",
",",
"claim",
"in",
"settings",
".",
"BOOLEAN_CLAIM_MAPPING",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"user",
",",
"field",
")",
":",
"bool_val",
"=",
"False",
"if",
"claim",
"in",
"claims",
"and",
"str",
"(",
"claims",
"[",
"claim",
"]",
")",
".",
"lower",
"(",
")",
"in",
"[",
"'y'",
",",
"'yes'",
",",
"'t'",
",",
"'true'",
",",
"'on'",
",",
"'1'",
"]",
":",
"bool_val",
"=",
"True",
"setattr",
"(",
"user",
",",
"field",
",",
"bool_val",
")",
"logger",
".",
"debug",
"(",
"'Attribute \"{}\" for user \"{}\" was set to \"{}\".'",
".",
"format",
"(",
"user",
",",
"field",
",",
"bool_val",
")",
")",
"else",
":",
"msg",
"=",
"\"User model has no field named '{}'. Check ADFS boolean claims mapping.\"",
"raise",
"ImproperlyConfigured",
"(",
"msg",
".",
"format",
"(",
"field",
")",
")"
] |
Updates user boolean attributes based on the BOOLEAN_CLAIM_MAPPING setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): Claims from the access token
|
[
"Updates",
"user",
"boolean",
"attributes",
"based",
"on",
"the",
"BOOLEAN_CLAIM_MAPPING",
"setting",
"."
] |
07197be392724d16a6132b03d9eafb1d634749cf
|
https://github.com/jobec/django-auth-adfs/blob/07197be392724d16a6132b03d9eafb1d634749cf/django_auth_adfs/backend.py#L208-L246
|
16,271
|
jobec/django-auth-adfs
|
django_auth_adfs/views.py
|
OAuth2CallbackView.get
|
def get(self, request):
"""
Handles the redirect from ADFS to our site.
We try to process the passed authorization code and login the user.
Args:
request (django.http.request.HttpRequest): A Django Request object
"""
code = request.GET.get("code")
if not code:
# Return an error message
return render(request, 'django_auth_adfs/login_failed.html', {
'error_message': "No authorization code was provided.",
}, status=400)
redirect_to = request.GET.get("state")
user = authenticate(request=request, authorization_code=code)
if user is not None:
if user.is_active:
login(request, user)
# Redirect to the "after login" page.
# Because we got redirected from ADFS, we can't know where the
# user came from.
if redirect_to:
redirect_to = base64.urlsafe_b64decode(redirect_to.encode()).decode()
else:
redirect_to = django_settings.LOGIN_REDIRECT_URL
url_is_safe = is_safe_url(
url=redirect_to,
allowed_hosts=[request.get_host()],
require_https=request.is_secure(),
)
redirect_to = redirect_to if url_is_safe else '/'
return redirect(redirect_to)
else:
# Return a 'disabled account' error message
return render(request, 'django_auth_adfs/login_failed.html', {
'error_message': "Your account is disabled.",
}, status=403)
else:
# Return an 'invalid login' error message
return render(request, 'django_auth_adfs/login_failed.html', {
'error_message': "Login failed.",
}, status=401)
|
python
|
def get(self, request):
"""
Handles the redirect from ADFS to our site.
We try to process the passed authorization code and login the user.
Args:
request (django.http.request.HttpRequest): A Django Request object
"""
code = request.GET.get("code")
if not code:
# Return an error message
return render(request, 'django_auth_adfs/login_failed.html', {
'error_message': "No authorization code was provided.",
}, status=400)
redirect_to = request.GET.get("state")
user = authenticate(request=request, authorization_code=code)
if user is not None:
if user.is_active:
login(request, user)
# Redirect to the "after login" page.
# Because we got redirected from ADFS, we can't know where the
# user came from.
if redirect_to:
redirect_to = base64.urlsafe_b64decode(redirect_to.encode()).decode()
else:
redirect_to = django_settings.LOGIN_REDIRECT_URL
url_is_safe = is_safe_url(
url=redirect_to,
allowed_hosts=[request.get_host()],
require_https=request.is_secure(),
)
redirect_to = redirect_to if url_is_safe else '/'
return redirect(redirect_to)
else:
# Return a 'disabled account' error message
return render(request, 'django_auth_adfs/login_failed.html', {
'error_message': "Your account is disabled.",
}, status=403)
else:
# Return an 'invalid login' error message
return render(request, 'django_auth_adfs/login_failed.html', {
'error_message': "Login failed.",
}, status=401)
|
[
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"code",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"code\"",
")",
"if",
"not",
"code",
":",
"# Return an error message",
"return",
"render",
"(",
"request",
",",
"'django_auth_adfs/login_failed.html'",
",",
"{",
"'error_message'",
":",
"\"No authorization code was provided.\"",
",",
"}",
",",
"status",
"=",
"400",
")",
"redirect_to",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"state\"",
")",
"user",
"=",
"authenticate",
"(",
"request",
"=",
"request",
",",
"authorization_code",
"=",
"code",
")",
"if",
"user",
"is",
"not",
"None",
":",
"if",
"user",
".",
"is_active",
":",
"login",
"(",
"request",
",",
"user",
")",
"# Redirect to the \"after login\" page.",
"# Because we got redirected from ADFS, we can't know where the",
"# user came from.",
"if",
"redirect_to",
":",
"redirect_to",
"=",
"base64",
".",
"urlsafe_b64decode",
"(",
"redirect_to",
".",
"encode",
"(",
")",
")",
".",
"decode",
"(",
")",
"else",
":",
"redirect_to",
"=",
"django_settings",
".",
"LOGIN_REDIRECT_URL",
"url_is_safe",
"=",
"is_safe_url",
"(",
"url",
"=",
"redirect_to",
",",
"allowed_hosts",
"=",
"[",
"request",
".",
"get_host",
"(",
")",
"]",
",",
"require_https",
"=",
"request",
".",
"is_secure",
"(",
")",
",",
")",
"redirect_to",
"=",
"redirect_to",
"if",
"url_is_safe",
"else",
"'/'",
"return",
"redirect",
"(",
"redirect_to",
")",
"else",
":",
"# Return a 'disabled account' error message",
"return",
"render",
"(",
"request",
",",
"'django_auth_adfs/login_failed.html'",
",",
"{",
"'error_message'",
":",
"\"Your account is disabled.\"",
",",
"}",
",",
"status",
"=",
"403",
")",
"else",
":",
"# Return an 'invalid login' error message",
"return",
"render",
"(",
"request",
",",
"'django_auth_adfs/login_failed.html'",
",",
"{",
"'error_message'",
":",
"\"Login failed.\"",
",",
"}",
",",
"status",
"=",
"401",
")"
] |
Handles the redirect from ADFS to our site.
We try to process the passed authorization code and login the user.
Args:
request (django.http.request.HttpRequest): A Django Request object
|
[
"Handles",
"the",
"redirect",
"from",
"ADFS",
"to",
"our",
"site",
".",
"We",
"try",
"to",
"process",
"the",
"passed",
"authorization",
"code",
"and",
"login",
"the",
"user",
"."
] |
07197be392724d16a6132b03d9eafb1d634749cf
|
https://github.com/jobec/django-auth-adfs/blob/07197be392724d16a6132b03d9eafb1d634749cf/django_auth_adfs/views.py#L16-L62
|
16,272
|
jobec/django-auth-adfs
|
django_auth_adfs/rest_framework.py
|
AdfsAccessTokenAuthentication.authenticate
|
def authenticate(self, request):
"""
Returns a `User` if a correct access token has been supplied
in the Authorization header. Otherwise returns `None`.
"""
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'bearer':
return None
if len(auth) == 1:
msg = 'Invalid authorization header. No credentials provided.'
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = 'Invalid authorization header. Access token should not contain spaces.'
raise exceptions.AuthenticationFailed(msg)
# Authenticate the user
# The AdfsAuthCodeBackend authentication backend will notice the "access_token" parameter
# and skip the request for an access token using the authorization code
user = authenticate(access_token=auth[1])
if user is None:
raise exceptions.AuthenticationFailed('Invalid access token.')
if not user.is_active:
raise exceptions.AuthenticationFailed('User inactive or deleted.')
return user, auth[1]
|
python
|
def authenticate(self, request):
"""
Returns a `User` if a correct access token has been supplied
in the Authorization header. Otherwise returns `None`.
"""
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'bearer':
return None
if len(auth) == 1:
msg = 'Invalid authorization header. No credentials provided.'
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = 'Invalid authorization header. Access token should not contain spaces.'
raise exceptions.AuthenticationFailed(msg)
# Authenticate the user
# The AdfsAuthCodeBackend authentication backend will notice the "access_token" parameter
# and skip the request for an access token using the authorization code
user = authenticate(access_token=auth[1])
if user is None:
raise exceptions.AuthenticationFailed('Invalid access token.')
if not user.is_active:
raise exceptions.AuthenticationFailed('User inactive or deleted.')
return user, auth[1]
|
[
"def",
"authenticate",
"(",
"self",
",",
"request",
")",
":",
"auth",
"=",
"get_authorization_header",
"(",
"request",
")",
".",
"split",
"(",
")",
"if",
"not",
"auth",
"or",
"auth",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"!=",
"b'bearer'",
":",
"return",
"None",
"if",
"len",
"(",
"auth",
")",
"==",
"1",
":",
"msg",
"=",
"'Invalid authorization header. No credentials provided.'",
"raise",
"exceptions",
".",
"AuthenticationFailed",
"(",
"msg",
")",
"elif",
"len",
"(",
"auth",
")",
">",
"2",
":",
"msg",
"=",
"'Invalid authorization header. Access token should not contain spaces.'",
"raise",
"exceptions",
".",
"AuthenticationFailed",
"(",
"msg",
")",
"# Authenticate the user",
"# The AdfsAuthCodeBackend authentication backend will notice the \"access_token\" parameter",
"# and skip the request for an access token using the authorization code",
"user",
"=",
"authenticate",
"(",
"access_token",
"=",
"auth",
"[",
"1",
"]",
")",
"if",
"user",
"is",
"None",
":",
"raise",
"exceptions",
".",
"AuthenticationFailed",
"(",
"'Invalid access token.'",
")",
"if",
"not",
"user",
".",
"is_active",
":",
"raise",
"exceptions",
".",
"AuthenticationFailed",
"(",
"'User inactive or deleted.'",
")",
"return",
"user",
",",
"auth",
"[",
"1",
"]"
] |
Returns a `User` if a correct access token has been supplied
in the Authorization header. Otherwise returns `None`.
|
[
"Returns",
"a",
"User",
"if",
"a",
"correct",
"access",
"token",
"has",
"been",
"supplied",
"in",
"the",
"Authorization",
"header",
".",
"Otherwise",
"returns",
"None",
"."
] |
07197be392724d16a6132b03d9eafb1d634749cf
|
https://github.com/jobec/django-auth-adfs/blob/07197be392724d16a6132b03d9eafb1d634749cf/django_auth_adfs/rest_framework.py#L20-L48
|
16,273
|
chemlab/chemlab
|
chemlab/qc/wavefunction.py
|
molecular_orbital
|
def molecular_orbital(coords, mocoeffs, gbasis):
'''Return a molecular orbital given the nuclei coordinates, as well as
molecular orbital coefficients and basis set specification as given by the cclib library.
The molecular orbital is represented as a function that takes x, y, z coordinates (in a vectorized fashion)
and returns a real number.
'''
# Making a closure
def f(x, y, z, coords=coords, mocoeffs=mocoeffs, gbasis=gbasis):
# The other functions take nanometers
return sum(c * bf(x * 10, y*10, z*10) for c, bf in zip(mocoeffs, getbfs(coords * 10, gbasis)))
return f
|
python
|
def molecular_orbital(coords, mocoeffs, gbasis):
'''Return a molecular orbital given the nuclei coordinates, as well as
molecular orbital coefficients and basis set specification as given by the cclib library.
The molecular orbital is represented as a function that takes x, y, z coordinates (in a vectorized fashion)
and returns a real number.
'''
# Making a closure
def f(x, y, z, coords=coords, mocoeffs=mocoeffs, gbasis=gbasis):
# The other functions take nanometers
return sum(c * bf(x * 10, y*10, z*10) for c, bf in zip(mocoeffs, getbfs(coords * 10, gbasis)))
return f
|
[
"def",
"molecular_orbital",
"(",
"coords",
",",
"mocoeffs",
",",
"gbasis",
")",
":",
"# Making a closure",
"def",
"f",
"(",
"x",
",",
"y",
",",
"z",
",",
"coords",
"=",
"coords",
",",
"mocoeffs",
"=",
"mocoeffs",
",",
"gbasis",
"=",
"gbasis",
")",
":",
"# The other functions take nanometers",
"return",
"sum",
"(",
"c",
"*",
"bf",
"(",
"x",
"*",
"10",
",",
"y",
"*",
"10",
",",
"z",
"*",
"10",
")",
"for",
"c",
",",
"bf",
"in",
"zip",
"(",
"mocoeffs",
",",
"getbfs",
"(",
"coords",
"*",
"10",
",",
"gbasis",
")",
")",
")",
"return",
"f"
] |
Return a molecular orbital given the nuclei coordinates, as well as
molecular orbital coefficients and basis set specification as given by the cclib library.
The molecular orbital is represented as a function that takes x, y, z coordinates (in a vectorized fashion)
and returns a real number.
|
[
"Return",
"a",
"molecular",
"orbital",
"given",
"the",
"nuclei",
"coordinates",
"as",
"well",
"as",
"molecular",
"orbital",
"coefficients",
"and",
"basis",
"set",
"specification",
"as",
"given",
"by",
"the",
"cclib",
"library",
"."
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/wavefunction.py#L4-L18
|
16,274
|
chemlab/chemlab
|
chemlab/qc/wavefunction.py
|
getbfs
|
def getbfs(coords, gbasis):
"""Convenience function for both wavefunction and density based on PyQuante Ints.py."""
sym2powerlist = {
'S' : [(0,0,0)],
'P' : [(1,0,0),(0,1,0),(0,0,1)],
'D' : [(2,0,0),(0,2,0),(0,0,2),(1,1,0),(0,1,1),(1,0,1)],
'F' : [(3,0,0),(2,1,0),(2,0,1),(1,2,0),(1,1,1),(1,0,2),
(0,3,0),(0,2,1),(0,1,2), (0,0,3)]
}
bfs = []
for i, at_coords in enumerate(coords):
bs = gbasis[i]
for sym,prims in bs:
for power in sym2powerlist[sym]:
bf = cgbf(at_coords,power)
for expnt,coef in prims:
bf.add_pgbf(expnt,coef)
bf.normalize()
bfs.append(bf)
return bfs
|
python
|
def getbfs(coords, gbasis):
"""Convenience function for both wavefunction and density based on PyQuante Ints.py."""
sym2powerlist = {
'S' : [(0,0,0)],
'P' : [(1,0,0),(0,1,0),(0,0,1)],
'D' : [(2,0,0),(0,2,0),(0,0,2),(1,1,0),(0,1,1),(1,0,1)],
'F' : [(3,0,0),(2,1,0),(2,0,1),(1,2,0),(1,1,1),(1,0,2),
(0,3,0),(0,2,1),(0,1,2), (0,0,3)]
}
bfs = []
for i, at_coords in enumerate(coords):
bs = gbasis[i]
for sym,prims in bs:
for power in sym2powerlist[sym]:
bf = cgbf(at_coords,power)
for expnt,coef in prims:
bf.add_pgbf(expnt,coef)
bf.normalize()
bfs.append(bf)
return bfs
|
[
"def",
"getbfs",
"(",
"coords",
",",
"gbasis",
")",
":",
"sym2powerlist",
"=",
"{",
"'S'",
":",
"[",
"(",
"0",
",",
"0",
",",
"0",
")",
"]",
",",
"'P'",
":",
"[",
"(",
"1",
",",
"0",
",",
"0",
")",
",",
"(",
"0",
",",
"1",
",",
"0",
")",
",",
"(",
"0",
",",
"0",
",",
"1",
")",
"]",
",",
"'D'",
":",
"[",
"(",
"2",
",",
"0",
",",
"0",
")",
",",
"(",
"0",
",",
"2",
",",
"0",
")",
",",
"(",
"0",
",",
"0",
",",
"2",
")",
",",
"(",
"1",
",",
"1",
",",
"0",
")",
",",
"(",
"0",
",",
"1",
",",
"1",
")",
",",
"(",
"1",
",",
"0",
",",
"1",
")",
"]",
",",
"'F'",
":",
"[",
"(",
"3",
",",
"0",
",",
"0",
")",
",",
"(",
"2",
",",
"1",
",",
"0",
")",
",",
"(",
"2",
",",
"0",
",",
"1",
")",
",",
"(",
"1",
",",
"2",
",",
"0",
")",
",",
"(",
"1",
",",
"1",
",",
"1",
")",
",",
"(",
"1",
",",
"0",
",",
"2",
")",
",",
"(",
"0",
",",
"3",
",",
"0",
")",
",",
"(",
"0",
",",
"2",
",",
"1",
")",
",",
"(",
"0",
",",
"1",
",",
"2",
")",
",",
"(",
"0",
",",
"0",
",",
"3",
")",
"]",
"}",
"bfs",
"=",
"[",
"]",
"for",
"i",
",",
"at_coords",
"in",
"enumerate",
"(",
"coords",
")",
":",
"bs",
"=",
"gbasis",
"[",
"i",
"]",
"for",
"sym",
",",
"prims",
"in",
"bs",
":",
"for",
"power",
"in",
"sym2powerlist",
"[",
"sym",
"]",
":",
"bf",
"=",
"cgbf",
"(",
"at_coords",
",",
"power",
")",
"for",
"expnt",
",",
"coef",
"in",
"prims",
":",
"bf",
".",
"add_pgbf",
"(",
"expnt",
",",
"coef",
")",
"bf",
".",
"normalize",
"(",
")",
"bfs",
".",
"append",
"(",
"bf",
")",
"return",
"bfs"
] |
Convenience function for both wavefunction and density based on PyQuante Ints.py.
|
[
"Convenience",
"function",
"for",
"both",
"wavefunction",
"and",
"density",
"based",
"on",
"PyQuante",
"Ints",
".",
"py",
"."
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/wavefunction.py#L21-L43
|
16,275
|
chemlab/chemlab
|
chemlab/qc/one.py
|
A_term
|
def A_term(i,r,u,l1,l2,PAx,PBx,CPx,gamma):
"""
THO eq. 2.18
>>> A_term(0,0,0,0,0,0,0,0,1)
1.0
>>> A_term(0,0,0,0,1,1,1,1,1)
1.0
>>> A_term(1,0,0,0,1,1,1,1,1)
-1.0
>>> A_term(0,0,0,1,1,1,1,1,1)
1.0
>>> A_term(1,0,0,1,1,1,1,1,1)
-2.0
>>> A_term(2,0,0,1,1,1,1,1,1)
1.0
>>> A_term(2,0,1,1,1,1,1,1,1)
-0.5
>>> A_term(2,1,0,1,1,1,1,1,1)
0.5
"""
return pow(-1,i)*binomial_prefactor(i,l1,l2,PAx,PBx)*\
pow(-1,u)*factorial(i)*pow(CPx,i-2*r-2*u)*\
pow(0.25/gamma,r+u)/factorial(r)/factorial(u)/factorial(i-2*r-2*u)
|
python
|
def A_term(i,r,u,l1,l2,PAx,PBx,CPx,gamma):
"""
THO eq. 2.18
>>> A_term(0,0,0,0,0,0,0,0,1)
1.0
>>> A_term(0,0,0,0,1,1,1,1,1)
1.0
>>> A_term(1,0,0,0,1,1,1,1,1)
-1.0
>>> A_term(0,0,0,1,1,1,1,1,1)
1.0
>>> A_term(1,0,0,1,1,1,1,1,1)
-2.0
>>> A_term(2,0,0,1,1,1,1,1,1)
1.0
>>> A_term(2,0,1,1,1,1,1,1,1)
-0.5
>>> A_term(2,1,0,1,1,1,1,1,1)
0.5
"""
return pow(-1,i)*binomial_prefactor(i,l1,l2,PAx,PBx)*\
pow(-1,u)*factorial(i)*pow(CPx,i-2*r-2*u)*\
pow(0.25/gamma,r+u)/factorial(r)/factorial(u)/factorial(i-2*r-2*u)
|
[
"def",
"A_term",
"(",
"i",
",",
"r",
",",
"u",
",",
"l1",
",",
"l2",
",",
"PAx",
",",
"PBx",
",",
"CPx",
",",
"gamma",
")",
":",
"return",
"pow",
"(",
"-",
"1",
",",
"i",
")",
"*",
"binomial_prefactor",
"(",
"i",
",",
"l1",
",",
"l2",
",",
"PAx",
",",
"PBx",
")",
"*",
"pow",
"(",
"-",
"1",
",",
"u",
")",
"*",
"factorial",
"(",
"i",
")",
"*",
"pow",
"(",
"CPx",
",",
"i",
"-",
"2",
"*",
"r",
"-",
"2",
"*",
"u",
")",
"*",
"pow",
"(",
"0.25",
"/",
"gamma",
",",
"r",
"+",
"u",
")",
"/",
"factorial",
"(",
"r",
")",
"/",
"factorial",
"(",
"u",
")",
"/",
"factorial",
"(",
"i",
"-",
"2",
"*",
"r",
"-",
"2",
"*",
"u",
")"
] |
THO eq. 2.18
>>> A_term(0,0,0,0,0,0,0,0,1)
1.0
>>> A_term(0,0,0,0,1,1,1,1,1)
1.0
>>> A_term(1,0,0,0,1,1,1,1,1)
-1.0
>>> A_term(0,0,0,1,1,1,1,1,1)
1.0
>>> A_term(1,0,0,1,1,1,1,1,1)
-2.0
>>> A_term(2,0,0,1,1,1,1,1,1)
1.0
>>> A_term(2,0,1,1,1,1,1,1,1)
-0.5
>>> A_term(2,1,0,1,1,1,1,1,1)
0.5
|
[
"THO",
"eq",
".",
"2",
".",
"18"
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/one.py#L203-L226
|
16,276
|
chemlab/chemlab
|
chemlab/qc/one.py
|
A_array
|
def A_array(l1,l2,PA,PB,CP,g):
"""
THO eq. 2.18 and 3.1
>>> A_array(0,0,0,0,0,1)
[1.0]
>>> A_array(0,1,1,1,1,1)
[1.0, -1.0]
>>> A_array(1,1,1,1,1,1)
[1.5, -2.5, 1.0]
"""
Imax = l1+l2+1
A = [0]*Imax
for i in range(Imax):
for r in range(int(floor(i/2)+1)):
for u in range(int(floor((i-2*r)/2)+1)):
I = i-2*r-u
A[I] = A[I] + A_term(i,r,u,l1,l2,PA,PB,CP,g)
return A
|
python
|
def A_array(l1,l2,PA,PB,CP,g):
"""
THO eq. 2.18 and 3.1
>>> A_array(0,0,0,0,0,1)
[1.0]
>>> A_array(0,1,1,1,1,1)
[1.0, -1.0]
>>> A_array(1,1,1,1,1,1)
[1.5, -2.5, 1.0]
"""
Imax = l1+l2+1
A = [0]*Imax
for i in range(Imax):
for r in range(int(floor(i/2)+1)):
for u in range(int(floor((i-2*r)/2)+1)):
I = i-2*r-u
A[I] = A[I] + A_term(i,r,u,l1,l2,PA,PB,CP,g)
return A
|
[
"def",
"A_array",
"(",
"l1",
",",
"l2",
",",
"PA",
",",
"PB",
",",
"CP",
",",
"g",
")",
":",
"Imax",
"=",
"l1",
"+",
"l2",
"+",
"1",
"A",
"=",
"[",
"0",
"]",
"*",
"Imax",
"for",
"i",
"in",
"range",
"(",
"Imax",
")",
":",
"for",
"r",
"in",
"range",
"(",
"int",
"(",
"floor",
"(",
"i",
"/",
"2",
")",
"+",
"1",
")",
")",
":",
"for",
"u",
"in",
"range",
"(",
"int",
"(",
"floor",
"(",
"(",
"i",
"-",
"2",
"*",
"r",
")",
"/",
"2",
")",
"+",
"1",
")",
")",
":",
"I",
"=",
"i",
"-",
"2",
"*",
"r",
"-",
"u",
"A",
"[",
"I",
"]",
"=",
"A",
"[",
"I",
"]",
"+",
"A_term",
"(",
"i",
",",
"r",
",",
"u",
",",
"l1",
",",
"l2",
",",
"PA",
",",
"PB",
",",
"CP",
",",
"g",
")",
"return",
"A"
] |
THO eq. 2.18 and 3.1
>>> A_array(0,0,0,0,0,1)
[1.0]
>>> A_array(0,1,1,1,1,1)
[1.0, -1.0]
>>> A_array(1,1,1,1,1,1)
[1.5, -2.5, 1.0]
|
[
"THO",
"eq",
".",
"2",
".",
"18",
"and",
"3",
".",
"1"
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/one.py#L228-L246
|
16,277
|
chemlab/chemlab
|
chemlab/qc/pgbf.py
|
pgbf._normalize
|
def _normalize(self):
"Normalize basis function. From THO eq. 2.2"
l,m,n = self.powers
self.norm = np.sqrt(pow(2,2*(l+m+n)+1.5)*
pow(self.exponent,l+m+n+1.5)/
fact2(2*l-1)/fact2(2*m-1)/
fact2(2*n-1)/pow(np.pi,1.5))
return
|
python
|
def _normalize(self):
"Normalize basis function. From THO eq. 2.2"
l,m,n = self.powers
self.norm = np.sqrt(pow(2,2*(l+m+n)+1.5)*
pow(self.exponent,l+m+n+1.5)/
fact2(2*l-1)/fact2(2*m-1)/
fact2(2*n-1)/pow(np.pi,1.5))
return
|
[
"def",
"_normalize",
"(",
"self",
")",
":",
"l",
",",
"m",
",",
"n",
"=",
"self",
".",
"powers",
"self",
".",
"norm",
"=",
"np",
".",
"sqrt",
"(",
"pow",
"(",
"2",
",",
"2",
"*",
"(",
"l",
"+",
"m",
"+",
"n",
")",
"+",
"1.5",
")",
"*",
"pow",
"(",
"self",
".",
"exponent",
",",
"l",
"+",
"m",
"+",
"n",
"+",
"1.5",
")",
"/",
"fact2",
"(",
"2",
"*",
"l",
"-",
"1",
")",
"/",
"fact2",
"(",
"2",
"*",
"m",
"-",
"1",
")",
"/",
"fact2",
"(",
"2",
"*",
"n",
"-",
"1",
")",
"/",
"pow",
"(",
"np",
".",
"pi",
",",
"1.5",
")",
")",
"return"
] |
Normalize basis function. From THO eq. 2.2
|
[
"Normalize",
"basis",
"function",
".",
"From",
"THO",
"eq",
".",
"2",
".",
"2"
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/pgbf.py#L77-L84
|
16,278
|
chemlab/chemlab
|
chemlab/mviewer/representations/ballandstick.py
|
BallAndStickRepresentation.hide
|
def hide(self, selections):
'''Hide objects in this representation. BallAndStickRepresentation
support selections of atoms and bonds.
To hide the first atom and the first bond you can use the
following code::
from chemlab.mviewer.state import Selection
representation.hide({'atoms': Selection([0], system.n_atoms),
'bonds': Selection([0], system.n_bonds)})
Returns the current Selection of hidden atoms and bonds.
'''
if 'atoms' in selections:
self.hidden_state['atoms'] = selections['atoms']
self.on_atom_hidden_changed()
if 'bonds' in selections:
self.hidden_state['bonds'] = selections['bonds']
self.on_bond_hidden_changed()
if 'box' in selections:
self.hidden_state['box'] = box_s = selections['box']
if box_s.mask[0]:
if self.viewer.has_renderer(self.box_renderer):
self.viewer.remove_renderer(self.box_renderer)
else:
if not self.viewer.has_renderer(self.box_renderer):
self.viewer.add_renderer(self.box_renderer)
return self.hidden_state
|
python
|
def hide(self, selections):
'''Hide objects in this representation. BallAndStickRepresentation
support selections of atoms and bonds.
To hide the first atom and the first bond you can use the
following code::
from chemlab.mviewer.state import Selection
representation.hide({'atoms': Selection([0], system.n_atoms),
'bonds': Selection([0], system.n_bonds)})
Returns the current Selection of hidden atoms and bonds.
'''
if 'atoms' in selections:
self.hidden_state['atoms'] = selections['atoms']
self.on_atom_hidden_changed()
if 'bonds' in selections:
self.hidden_state['bonds'] = selections['bonds']
self.on_bond_hidden_changed()
if 'box' in selections:
self.hidden_state['box'] = box_s = selections['box']
if box_s.mask[0]:
if self.viewer.has_renderer(self.box_renderer):
self.viewer.remove_renderer(self.box_renderer)
else:
if not self.viewer.has_renderer(self.box_renderer):
self.viewer.add_renderer(self.box_renderer)
return self.hidden_state
|
[
"def",
"hide",
"(",
"self",
",",
"selections",
")",
":",
"if",
"'atoms'",
"in",
"selections",
":",
"self",
".",
"hidden_state",
"[",
"'atoms'",
"]",
"=",
"selections",
"[",
"'atoms'",
"]",
"self",
".",
"on_atom_hidden_changed",
"(",
")",
"if",
"'bonds'",
"in",
"selections",
":",
"self",
".",
"hidden_state",
"[",
"'bonds'",
"]",
"=",
"selections",
"[",
"'bonds'",
"]",
"self",
".",
"on_bond_hidden_changed",
"(",
")",
"if",
"'box'",
"in",
"selections",
":",
"self",
".",
"hidden_state",
"[",
"'box'",
"]",
"=",
"box_s",
"=",
"selections",
"[",
"'box'",
"]",
"if",
"box_s",
".",
"mask",
"[",
"0",
"]",
":",
"if",
"self",
".",
"viewer",
".",
"has_renderer",
"(",
"self",
".",
"box_renderer",
")",
":",
"self",
".",
"viewer",
".",
"remove_renderer",
"(",
"self",
".",
"box_renderer",
")",
"else",
":",
"if",
"not",
"self",
".",
"viewer",
".",
"has_renderer",
"(",
"self",
".",
"box_renderer",
")",
":",
"self",
".",
"viewer",
".",
"add_renderer",
"(",
"self",
".",
"box_renderer",
")",
"return",
"self",
".",
"hidden_state"
] |
Hide objects in this representation. BallAndStickRepresentation
support selections of atoms and bonds.
To hide the first atom and the first bond you can use the
following code::
from chemlab.mviewer.state import Selection
representation.hide({'atoms': Selection([0], system.n_atoms),
'bonds': Selection([0], system.n_bonds)})
Returns the current Selection of hidden atoms and bonds.
|
[
"Hide",
"objects",
"in",
"this",
"representation",
".",
"BallAndStickRepresentation",
"support",
"selections",
"of",
"atoms",
"and",
"bonds",
"."
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/representations/ballandstick.py#L279-L310
|
16,279
|
chemlab/chemlab
|
chemlab/mviewer/representations/ballandstick.py
|
BallAndStickRepresentation.change_radius
|
def change_radius(self, selections, value):
'''Change the radius of each atom by a certain value
'''
if 'atoms' in selections:
atms = selections['atoms'].mask
if value is None:
self.radii_state.array[atms] = [vdw_radii.get(t) * 0.3 for t in self.system.type_array[atms]]
else:
self.radii_state.array[atms] = value
self.update_scale_factors(self.scale_factors)
|
python
|
def change_radius(self, selections, value):
'''Change the radius of each atom by a certain value
'''
if 'atoms' in selections:
atms = selections['atoms'].mask
if value is None:
self.radii_state.array[atms] = [vdw_radii.get(t) * 0.3 for t in self.system.type_array[atms]]
else:
self.radii_state.array[atms] = value
self.update_scale_factors(self.scale_factors)
|
[
"def",
"change_radius",
"(",
"self",
",",
"selections",
",",
"value",
")",
":",
"if",
"'atoms'",
"in",
"selections",
":",
"atms",
"=",
"selections",
"[",
"'atoms'",
"]",
".",
"mask",
"if",
"value",
"is",
"None",
":",
"self",
".",
"radii_state",
".",
"array",
"[",
"atms",
"]",
"=",
"[",
"vdw_radii",
".",
"get",
"(",
"t",
")",
"*",
"0.3",
"for",
"t",
"in",
"self",
".",
"system",
".",
"type_array",
"[",
"atms",
"]",
"]",
"else",
":",
"self",
".",
"radii_state",
".",
"array",
"[",
"atms",
"]",
"=",
"value",
"self",
".",
"update_scale_factors",
"(",
"self",
".",
"scale_factors",
")"
] |
Change the radius of each atom by a certain value
|
[
"Change",
"the",
"radius",
"of",
"each",
"atom",
"by",
"a",
"certain",
"value"
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/representations/ballandstick.py#L326-L337
|
16,280
|
chemlab/chemlab
|
chemlab/graphics/qt/qchemlabwidget.py
|
QChemlabWidget.paintGL
|
def paintGL(self):
'''GL function called each time a frame is drawn'''
if self.post_processing:
# Render to the first framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, self.fb0)
glViewport(0, 0, self.width(), self.height())
status = glCheckFramebufferStatus(GL_FRAMEBUFFER)
if (status != GL_FRAMEBUFFER_COMPLETE):
reason = dict(GL_FRAMEBUFFER_UNDEFINED='UNDEFINED',
GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT='INCOMPLETE_ATTACHMENT',
GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT='INCOMPLETE_MISSING_ATTACHMENT',
GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER='INCOMPLETE_DRAW_BUFFER',
GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER='INCOMPLETE_READ_BUFFER',
GL_FRAMEBUFFER_UNSUPPORTED='UNSUPPORTED',
)[status]
raise Exception('Framebuffer is not complete: {}'.format(reason))
else:
glBindFramebuffer(GL_FRAMEBUFFER, DEFAULT_FRAMEBUFFER)
# Clear color take floats
bg_r, bg_g, bg_b, bg_a = self.background_color
glClearColor(bg_r/255, bg_g/255, bg_b/255, bg_a/255)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
proj = self.camera.projection
cam = self.camera.matrix
self.mvproj = np.dot(proj, cam)
self.ldir = cam[:3, :3].T.dot(self.light_dir)
# Draw World
self.on_draw_world()
# Iterate over all of the post processing effects
if self.post_processing:
if len(self.post_processing) > 1:
newarg = self.textures.copy()
# Ping-pong framebuffer rendering
for i, pp in enumerate(self.post_processing[:-1]):
if i % 2:
outfb = self.fb1
outtex = self._extra_textures['fb1']
else:
outfb = self.fb2
outtex = self._extra_textures['fb2']
pp.render(outfb, newarg)
newarg['color'] = outtex
self.post_processing[-1].render(DEFAULT_FRAMEBUFFER, newarg)
else:
self.post_processing[0].render(DEFAULT_FRAMEBUFFER, self.textures)
# Draw the UI at the very last step
self.on_draw_ui()
|
python
|
def paintGL(self):
'''GL function called each time a frame is drawn'''
if self.post_processing:
# Render to the first framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, self.fb0)
glViewport(0, 0, self.width(), self.height())
status = glCheckFramebufferStatus(GL_FRAMEBUFFER)
if (status != GL_FRAMEBUFFER_COMPLETE):
reason = dict(GL_FRAMEBUFFER_UNDEFINED='UNDEFINED',
GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT='INCOMPLETE_ATTACHMENT',
GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT='INCOMPLETE_MISSING_ATTACHMENT',
GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER='INCOMPLETE_DRAW_BUFFER',
GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER='INCOMPLETE_READ_BUFFER',
GL_FRAMEBUFFER_UNSUPPORTED='UNSUPPORTED',
)[status]
raise Exception('Framebuffer is not complete: {}'.format(reason))
else:
glBindFramebuffer(GL_FRAMEBUFFER, DEFAULT_FRAMEBUFFER)
# Clear color take floats
bg_r, bg_g, bg_b, bg_a = self.background_color
glClearColor(bg_r/255, bg_g/255, bg_b/255, bg_a/255)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
proj = self.camera.projection
cam = self.camera.matrix
self.mvproj = np.dot(proj, cam)
self.ldir = cam[:3, :3].T.dot(self.light_dir)
# Draw World
self.on_draw_world()
# Iterate over all of the post processing effects
if self.post_processing:
if len(self.post_processing) > 1:
newarg = self.textures.copy()
# Ping-pong framebuffer rendering
for i, pp in enumerate(self.post_processing[:-1]):
if i % 2:
outfb = self.fb1
outtex = self._extra_textures['fb1']
else:
outfb = self.fb2
outtex = self._extra_textures['fb2']
pp.render(outfb, newarg)
newarg['color'] = outtex
self.post_processing[-1].render(DEFAULT_FRAMEBUFFER, newarg)
else:
self.post_processing[0].render(DEFAULT_FRAMEBUFFER, self.textures)
# Draw the UI at the very last step
self.on_draw_ui()
|
[
"def",
"paintGL",
"(",
"self",
")",
":",
"if",
"self",
".",
"post_processing",
":",
"# Render to the first framebuffer",
"glBindFramebuffer",
"(",
"GL_FRAMEBUFFER",
",",
"self",
".",
"fb0",
")",
"glViewport",
"(",
"0",
",",
"0",
",",
"self",
".",
"width",
"(",
")",
",",
"self",
".",
"height",
"(",
")",
")",
"status",
"=",
"glCheckFramebufferStatus",
"(",
"GL_FRAMEBUFFER",
")",
"if",
"(",
"status",
"!=",
"GL_FRAMEBUFFER_COMPLETE",
")",
":",
"reason",
"=",
"dict",
"(",
"GL_FRAMEBUFFER_UNDEFINED",
"=",
"'UNDEFINED'",
",",
"GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT",
"=",
"'INCOMPLETE_ATTACHMENT'",
",",
"GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",
"=",
"'INCOMPLETE_MISSING_ATTACHMENT'",
",",
"GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER",
"=",
"'INCOMPLETE_DRAW_BUFFER'",
",",
"GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER",
"=",
"'INCOMPLETE_READ_BUFFER'",
",",
"GL_FRAMEBUFFER_UNSUPPORTED",
"=",
"'UNSUPPORTED'",
",",
")",
"[",
"status",
"]",
"raise",
"Exception",
"(",
"'Framebuffer is not complete: {}'",
".",
"format",
"(",
"reason",
")",
")",
"else",
":",
"glBindFramebuffer",
"(",
"GL_FRAMEBUFFER",
",",
"DEFAULT_FRAMEBUFFER",
")",
"# Clear color take floats",
"bg_r",
",",
"bg_g",
",",
"bg_b",
",",
"bg_a",
"=",
"self",
".",
"background_color",
"glClearColor",
"(",
"bg_r",
"/",
"255",
",",
"bg_g",
"/",
"255",
",",
"bg_b",
"/",
"255",
",",
"bg_a",
"/",
"255",
")",
"glClear",
"(",
"GL_COLOR_BUFFER_BIT",
"|",
"GL_DEPTH_BUFFER_BIT",
")",
"proj",
"=",
"self",
".",
"camera",
".",
"projection",
"cam",
"=",
"self",
".",
"camera",
".",
"matrix",
"self",
".",
"mvproj",
"=",
"np",
".",
"dot",
"(",
"proj",
",",
"cam",
")",
"self",
".",
"ldir",
"=",
"cam",
"[",
":",
"3",
",",
":",
"3",
"]",
".",
"T",
".",
"dot",
"(",
"self",
".",
"light_dir",
")",
"# Draw World",
"self",
".",
"on_draw_world",
"(",
")",
"# Iterate over all of the post processing effects",
"if",
"self",
".",
"post_processing",
":",
"if",
"len",
"(",
"self",
".",
"post_processing",
")",
">",
"1",
":",
"newarg",
"=",
"self",
".",
"textures",
".",
"copy",
"(",
")",
"# Ping-pong framebuffer rendering",
"for",
"i",
",",
"pp",
"in",
"enumerate",
"(",
"self",
".",
"post_processing",
"[",
":",
"-",
"1",
"]",
")",
":",
"if",
"i",
"%",
"2",
":",
"outfb",
"=",
"self",
".",
"fb1",
"outtex",
"=",
"self",
".",
"_extra_textures",
"[",
"'fb1'",
"]",
"else",
":",
"outfb",
"=",
"self",
".",
"fb2",
"outtex",
"=",
"self",
".",
"_extra_textures",
"[",
"'fb2'",
"]",
"pp",
".",
"render",
"(",
"outfb",
",",
"newarg",
")",
"newarg",
"[",
"'color'",
"]",
"=",
"outtex",
"self",
".",
"post_processing",
"[",
"-",
"1",
"]",
".",
"render",
"(",
"DEFAULT_FRAMEBUFFER",
",",
"newarg",
")",
"else",
":",
"self",
".",
"post_processing",
"[",
"0",
"]",
".",
"render",
"(",
"DEFAULT_FRAMEBUFFER",
",",
"self",
".",
"textures",
")",
"# Draw the UI at the very last step",
"self",
".",
"on_draw_ui",
"(",
")"
] |
GL function called each time a frame is drawn
|
[
"GL",
"function",
"called",
"each",
"time",
"a",
"frame",
"is",
"drawn"
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qchemlabwidget.py#L153-L217
|
16,281
|
chemlab/chemlab
|
chemlab/graphics/qt/qchemlabwidget.py
|
QChemlabWidget.toimage
|
def toimage(self, width=None, height=None):
'''Return the current scene as a PIL Image.
**Example**
You can build your molecular viewer as usual and dump an image
at any resolution supported by the video card (up to the
memory limits)::
v = QtViewer()
# Add the renderers
v.add_renderer(...)
# Add post processing effects
v.add_post_processing(...)
# Move the camera
v.widget.camera.autozoom(...)
v.widget.camera.orbit_x(...)
v.widget.camera.orbit_y(...)
# Save the image
image = v.widget.toimage(1024, 768)
image.save("mol.png")
.. seealso::
https://pillow.readthedocs.org/en/latest/PIL.html#module-PIL.Image
'''
from .postprocessing import NoEffect
effect = NoEffect(self)
self.post_processing.append(effect)
oldwidth, oldheight = self.width(), self.height()
#self.initializeGL()
if None not in (width, height):
self.resize(width, height)
self.resizeGL(width, height)
else:
width = self.width()
height = self.height()
self.paintGL()
self.post_processing.remove(effect)
coltex = effect.texture
coltex.bind()
glActiveTexture(GL_TEXTURE0)
data = glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE)
image = pil_Image.frombuffer('RGBA', (width, height), data, 'raw', 'RGBA', 0, -1)
#self.resize(oldwidth, oldheight)
#self.resizeGL(oldwidth, oldheight)
return image
|
python
|
def toimage(self, width=None, height=None):
'''Return the current scene as a PIL Image.
**Example**
You can build your molecular viewer as usual and dump an image
at any resolution supported by the video card (up to the
memory limits)::
v = QtViewer()
# Add the renderers
v.add_renderer(...)
# Add post processing effects
v.add_post_processing(...)
# Move the camera
v.widget.camera.autozoom(...)
v.widget.camera.orbit_x(...)
v.widget.camera.orbit_y(...)
# Save the image
image = v.widget.toimage(1024, 768)
image.save("mol.png")
.. seealso::
https://pillow.readthedocs.org/en/latest/PIL.html#module-PIL.Image
'''
from .postprocessing import NoEffect
effect = NoEffect(self)
self.post_processing.append(effect)
oldwidth, oldheight = self.width(), self.height()
#self.initializeGL()
if None not in (width, height):
self.resize(width, height)
self.resizeGL(width, height)
else:
width = self.width()
height = self.height()
self.paintGL()
self.post_processing.remove(effect)
coltex = effect.texture
coltex.bind()
glActiveTexture(GL_TEXTURE0)
data = glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE)
image = pil_Image.frombuffer('RGBA', (width, height), data, 'raw', 'RGBA', 0, -1)
#self.resize(oldwidth, oldheight)
#self.resizeGL(oldwidth, oldheight)
return image
|
[
"def",
"toimage",
"(",
"self",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
")",
":",
"from",
".",
"postprocessing",
"import",
"NoEffect",
"effect",
"=",
"NoEffect",
"(",
"self",
")",
"self",
".",
"post_processing",
".",
"append",
"(",
"effect",
")",
"oldwidth",
",",
"oldheight",
"=",
"self",
".",
"width",
"(",
")",
",",
"self",
".",
"height",
"(",
")",
"#self.initializeGL()",
"if",
"None",
"not",
"in",
"(",
"width",
",",
"height",
")",
":",
"self",
".",
"resize",
"(",
"width",
",",
"height",
")",
"self",
".",
"resizeGL",
"(",
"width",
",",
"height",
")",
"else",
":",
"width",
"=",
"self",
".",
"width",
"(",
")",
"height",
"=",
"self",
".",
"height",
"(",
")",
"self",
".",
"paintGL",
"(",
")",
"self",
".",
"post_processing",
".",
"remove",
"(",
"effect",
")",
"coltex",
"=",
"effect",
".",
"texture",
"coltex",
".",
"bind",
"(",
")",
"glActiveTexture",
"(",
"GL_TEXTURE0",
")",
"data",
"=",
"glGetTexImage",
"(",
"GL_TEXTURE_2D",
",",
"0",
",",
"GL_RGBA",
",",
"GL_UNSIGNED_BYTE",
")",
"image",
"=",
"pil_Image",
".",
"frombuffer",
"(",
"'RGBA'",
",",
"(",
"width",
",",
"height",
")",
",",
"data",
",",
"'raw'",
",",
"'RGBA'",
",",
"0",
",",
"-",
"1",
")",
"#self.resize(oldwidth, oldheight)",
"#self.resizeGL(oldwidth, oldheight)",
"return",
"image"
] |
Return the current scene as a PIL Image.
**Example**
You can build your molecular viewer as usual and dump an image
at any resolution supported by the video card (up to the
memory limits)::
v = QtViewer()
# Add the renderers
v.add_renderer(...)
# Add post processing effects
v.add_post_processing(...)
# Move the camera
v.widget.camera.autozoom(...)
v.widget.camera.orbit_x(...)
v.widget.camera.orbit_y(...)
# Save the image
image = v.widget.toimage(1024, 768)
image.save("mol.png")
.. seealso::
https://pillow.readthedocs.org/en/latest/PIL.html#module-PIL.Image
|
[
"Return",
"the",
"current",
"scene",
"as",
"a",
"PIL",
"Image",
"."
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qchemlabwidget.py#L318-L377
|
16,282
|
chemlab/chemlab
|
chemlab/md/ewald.py
|
_real
|
def _real(coords1, charges1, coords2, charges2, rcut, alpha, box):
"""Calculate ewald real part. Box has to be a cuboidal box you should
transform any other box shape to a cuboidal box before using this.
"""
n = coords1.shape[0]
m = coords2.shape[0]
# Unit vectors
a = box[0]
b = box[1]
c = box[2]
# This is helpful to add the correct number of boxes
l_max = int(np.ceil(2.0 * rcut / np.min(np.trace(box))))
result = np.zeros(n)
for i in range(n):
q_i = charges1[i]
r_i = coords1[i]
for j in range(m):
q_j = charges2[j]
r_j = coords2[j]
for l_i in range(-l_max, l_max + 1):
for l_j in range(-l_max, l_max + 1):
for l_k in range(-l_max, l_max + 1):
nv = l_i * a + l_j * b + l_k * c
r_j_n = r_j + nv
r_ij = _dist(r_i, r_j_n)
if r_ij < 1e-10 or r_ij > rcut:
continue
value = q_i * q_j * math.erfc(alpha * r_ij) / r_ij
result[i] += value
return result
|
python
|
def _real(coords1, charges1, coords2, charges2, rcut, alpha, box):
"""Calculate ewald real part. Box has to be a cuboidal box you should
transform any other box shape to a cuboidal box before using this.
"""
n = coords1.shape[0]
m = coords2.shape[0]
# Unit vectors
a = box[0]
b = box[1]
c = box[2]
# This is helpful to add the correct number of boxes
l_max = int(np.ceil(2.0 * rcut / np.min(np.trace(box))))
result = np.zeros(n)
for i in range(n):
q_i = charges1[i]
r_i = coords1[i]
for j in range(m):
q_j = charges2[j]
r_j = coords2[j]
for l_i in range(-l_max, l_max + 1):
for l_j in range(-l_max, l_max + 1):
for l_k in range(-l_max, l_max + 1):
nv = l_i * a + l_j * b + l_k * c
r_j_n = r_j + nv
r_ij = _dist(r_i, r_j_n)
if r_ij < 1e-10 or r_ij > rcut:
continue
value = q_i * q_j * math.erfc(alpha * r_ij) / r_ij
result[i] += value
return result
|
[
"def",
"_real",
"(",
"coords1",
",",
"charges1",
",",
"coords2",
",",
"charges2",
",",
"rcut",
",",
"alpha",
",",
"box",
")",
":",
"n",
"=",
"coords1",
".",
"shape",
"[",
"0",
"]",
"m",
"=",
"coords2",
".",
"shape",
"[",
"0",
"]",
"# Unit vectors",
"a",
"=",
"box",
"[",
"0",
"]",
"b",
"=",
"box",
"[",
"1",
"]",
"c",
"=",
"box",
"[",
"2",
"]",
"# This is helpful to add the correct number of boxes",
"l_max",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"2.0",
"*",
"rcut",
"/",
"np",
".",
"min",
"(",
"np",
".",
"trace",
"(",
"box",
")",
")",
")",
")",
"result",
"=",
"np",
".",
"zeros",
"(",
"n",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"q_i",
"=",
"charges1",
"[",
"i",
"]",
"r_i",
"=",
"coords1",
"[",
"i",
"]",
"for",
"j",
"in",
"range",
"(",
"m",
")",
":",
"q_j",
"=",
"charges2",
"[",
"j",
"]",
"r_j",
"=",
"coords2",
"[",
"j",
"]",
"for",
"l_i",
"in",
"range",
"(",
"-",
"l_max",
",",
"l_max",
"+",
"1",
")",
":",
"for",
"l_j",
"in",
"range",
"(",
"-",
"l_max",
",",
"l_max",
"+",
"1",
")",
":",
"for",
"l_k",
"in",
"range",
"(",
"-",
"l_max",
",",
"l_max",
"+",
"1",
")",
":",
"nv",
"=",
"l_i",
"*",
"a",
"+",
"l_j",
"*",
"b",
"+",
"l_k",
"*",
"c",
"r_j_n",
"=",
"r_j",
"+",
"nv",
"r_ij",
"=",
"_dist",
"(",
"r_i",
",",
"r_j_n",
")",
"if",
"r_ij",
"<",
"1e-10",
"or",
"r_ij",
">",
"rcut",
":",
"continue",
"value",
"=",
"q_i",
"*",
"q_j",
"*",
"math",
".",
"erfc",
"(",
"alpha",
"*",
"r_ij",
")",
"/",
"r_ij",
"result",
"[",
"i",
"]",
"+=",
"value",
"return",
"result"
] |
Calculate ewald real part. Box has to be a cuboidal box you should
transform any other box shape to a cuboidal box before using this.
|
[
"Calculate",
"ewald",
"real",
"part",
".",
"Box",
"has",
"to",
"be",
"a",
"cuboidal",
"box",
"you",
"should",
"transform",
"any",
"other",
"box",
"shape",
"to",
"a",
"cuboidal",
"box",
"before",
"using",
"this",
"."
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/md/ewald.py#L19-L57
|
16,283
|
chemlab/chemlab
|
chemlab/md/ewald.py
|
_reciprocal
|
def _reciprocal(coords1, charges1, coords2, charges2, kmax, kappa, box):
"""Calculate ewald reciprocal part. Box has to be a cuboidal box you should
transform any other box shape to a cuboidal box before using this.
"""
n = coords1.shape[0]
m = coords2.shape[0]
result = np.zeros(n, dtype=np.float64)
need_self = np.zeros(n, dtype=np.uint8)
# Reciprocal unit vectors
g1, g2, g3 = reciprocal_vectors(box)
V = box_volume(box)
prefac = 1.0 / (np.pi * V)
for i in range(n):
q_i = charges1[i]
r_i = coords1[i]
for j in range(m):
q_j = charges2[j]
r_j = coords2[j]
r_ij = _dist(r_i, r_j)
if r_ij < 1e-10:
need_self[i] = 1
for k_i in range(-kmax, kmax + 1):
for k_j in range(-kmax, kmax + 1):
for k_k in range(-kmax, kmax + 1):
if k_i == 0 and k_j == 0 and k_k == 0:
continue
# Reciprocal vector
k = k_i * g1 + k_j * g2 + k_k * g3
k_sq = sqsum(k)
result[i] += (prefac * q_i * q_j *
4.0 * np.pi ** 2 / k_sq *
math.exp(-k_sq / (4.0 * kappa ** 2)) *
math.cos(np.dot(k, r_i - r_j)))
# Self-energy correction
# I had to do some FUCKED UP stuff because NUMBA SUCKS BALLS and
# breaks compatibility with simple expressions such as that one
# apparently doing result -= something is too hard in numba
self_energy = 2 * (need_self * kappa * charges1 ** 2) / (np.pi**0.5)
return result - self_energy
|
python
|
def _reciprocal(coords1, charges1, coords2, charges2, kmax, kappa, box):
"""Calculate ewald reciprocal part. Box has to be a cuboidal box you should
transform any other box shape to a cuboidal box before using this.
"""
n = coords1.shape[0]
m = coords2.shape[0]
result = np.zeros(n, dtype=np.float64)
need_self = np.zeros(n, dtype=np.uint8)
# Reciprocal unit vectors
g1, g2, g3 = reciprocal_vectors(box)
V = box_volume(box)
prefac = 1.0 / (np.pi * V)
for i in range(n):
q_i = charges1[i]
r_i = coords1[i]
for j in range(m):
q_j = charges2[j]
r_j = coords2[j]
r_ij = _dist(r_i, r_j)
if r_ij < 1e-10:
need_self[i] = 1
for k_i in range(-kmax, kmax + 1):
for k_j in range(-kmax, kmax + 1):
for k_k in range(-kmax, kmax + 1):
if k_i == 0 and k_j == 0 and k_k == 0:
continue
# Reciprocal vector
k = k_i * g1 + k_j * g2 + k_k * g3
k_sq = sqsum(k)
result[i] += (prefac * q_i * q_j *
4.0 * np.pi ** 2 / k_sq *
math.exp(-k_sq / (4.0 * kappa ** 2)) *
math.cos(np.dot(k, r_i - r_j)))
# Self-energy correction
# I had to do some FUCKED UP stuff because NUMBA SUCKS BALLS and
# breaks compatibility with simple expressions such as that one
# apparently doing result -= something is too hard in numba
self_energy = 2 * (need_self * kappa * charges1 ** 2) / (np.pi**0.5)
return result - self_energy
|
[
"def",
"_reciprocal",
"(",
"coords1",
",",
"charges1",
",",
"coords2",
",",
"charges2",
",",
"kmax",
",",
"kappa",
",",
"box",
")",
":",
"n",
"=",
"coords1",
".",
"shape",
"[",
"0",
"]",
"m",
"=",
"coords2",
".",
"shape",
"[",
"0",
"]",
"result",
"=",
"np",
".",
"zeros",
"(",
"n",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"need_self",
"=",
"np",
".",
"zeros",
"(",
"n",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"# Reciprocal unit vectors",
"g1",
",",
"g2",
",",
"g3",
"=",
"reciprocal_vectors",
"(",
"box",
")",
"V",
"=",
"box_volume",
"(",
"box",
")",
"prefac",
"=",
"1.0",
"/",
"(",
"np",
".",
"pi",
"*",
"V",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"q_i",
"=",
"charges1",
"[",
"i",
"]",
"r_i",
"=",
"coords1",
"[",
"i",
"]",
"for",
"j",
"in",
"range",
"(",
"m",
")",
":",
"q_j",
"=",
"charges2",
"[",
"j",
"]",
"r_j",
"=",
"coords2",
"[",
"j",
"]",
"r_ij",
"=",
"_dist",
"(",
"r_i",
",",
"r_j",
")",
"if",
"r_ij",
"<",
"1e-10",
":",
"need_self",
"[",
"i",
"]",
"=",
"1",
"for",
"k_i",
"in",
"range",
"(",
"-",
"kmax",
",",
"kmax",
"+",
"1",
")",
":",
"for",
"k_j",
"in",
"range",
"(",
"-",
"kmax",
",",
"kmax",
"+",
"1",
")",
":",
"for",
"k_k",
"in",
"range",
"(",
"-",
"kmax",
",",
"kmax",
"+",
"1",
")",
":",
"if",
"k_i",
"==",
"0",
"and",
"k_j",
"==",
"0",
"and",
"k_k",
"==",
"0",
":",
"continue",
"# Reciprocal vector",
"k",
"=",
"k_i",
"*",
"g1",
"+",
"k_j",
"*",
"g2",
"+",
"k_k",
"*",
"g3",
"k_sq",
"=",
"sqsum",
"(",
"k",
")",
"result",
"[",
"i",
"]",
"+=",
"(",
"prefac",
"*",
"q_i",
"*",
"q_j",
"*",
"4.0",
"*",
"np",
".",
"pi",
"**",
"2",
"/",
"k_sq",
"*",
"math",
".",
"exp",
"(",
"-",
"k_sq",
"/",
"(",
"4.0",
"*",
"kappa",
"**",
"2",
")",
")",
"*",
"math",
".",
"cos",
"(",
"np",
".",
"dot",
"(",
"k",
",",
"r_i",
"-",
"r_j",
")",
")",
")",
"# Self-energy correction",
"# I had to do some FUCKED UP stuff because NUMBA SUCKS BALLS and ",
"# breaks compatibility with simple expressions such as that one",
"# apparently doing result -= something is too hard in numba",
"self_energy",
"=",
"2",
"*",
"(",
"need_self",
"*",
"kappa",
"*",
"charges1",
"**",
"2",
")",
"/",
"(",
"np",
".",
"pi",
"**",
"0.5",
")",
"return",
"result",
"-",
"self_energy"
] |
Calculate ewald reciprocal part. Box has to be a cuboidal box you should
transform any other box shape to a cuboidal box before using this.
|
[
"Calculate",
"ewald",
"reciprocal",
"part",
".",
"Box",
"has",
"to",
"be",
"a",
"cuboidal",
"box",
"you",
"should",
"transform",
"any",
"other",
"box",
"shape",
"to",
"a",
"cuboidal",
"box",
"before",
"using",
"this",
"."
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/md/ewald.py#L80-L128
|
16,284
|
chemlab/chemlab
|
chemlab/graphics/renderers/cylinder.py
|
CylinderRenderer.update_bounds
|
def update_bounds(self, bounds):
'''Update cylinders start and end positions
'''
starts = bounds[:,0,:]
ends = bounds[:,1,:]
self.bounds = bounds
self.lengths = np.sqrt(((ends - starts)**2).sum(axis=1))
vertices, normals, colors = self._process_reference()
self.tr.update_vertices(vertices)
self.tr.update_normals(normals)
|
python
|
def update_bounds(self, bounds):
'''Update cylinders start and end positions
'''
starts = bounds[:,0,:]
ends = bounds[:,1,:]
self.bounds = bounds
self.lengths = np.sqrt(((ends - starts)**2).sum(axis=1))
vertices, normals, colors = self._process_reference()
self.tr.update_vertices(vertices)
self.tr.update_normals(normals)
|
[
"def",
"update_bounds",
"(",
"self",
",",
"bounds",
")",
":",
"starts",
"=",
"bounds",
"[",
":",
",",
"0",
",",
":",
"]",
"ends",
"=",
"bounds",
"[",
":",
",",
"1",
",",
":",
"]",
"self",
".",
"bounds",
"=",
"bounds",
"self",
".",
"lengths",
"=",
"np",
".",
"sqrt",
"(",
"(",
"(",
"ends",
"-",
"starts",
")",
"**",
"2",
")",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
")",
"vertices",
",",
"normals",
",",
"colors",
"=",
"self",
".",
"_process_reference",
"(",
")",
"self",
".",
"tr",
".",
"update_vertices",
"(",
"vertices",
")",
"self",
".",
"tr",
".",
"update_normals",
"(",
"normals",
")"
] |
Update cylinders start and end positions
|
[
"Update",
"cylinders",
"start",
"and",
"end",
"positions"
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/cylinder.py#L72-L85
|
16,285
|
chemlab/chemlab
|
chemlab/io/trajectory.py
|
make_trajectory
|
def make_trajectory(first, filename, restart=False):
'''Factory function to easily create a trajectory object'''
mode = 'w'
if restart:
mode = 'a'
return Trajectory(first, filename, mode)
|
python
|
def make_trajectory(first, filename, restart=False):
'''Factory function to easily create a trajectory object'''
mode = 'w'
if restart:
mode = 'a'
return Trajectory(first, filename, mode)
|
[
"def",
"make_trajectory",
"(",
"first",
",",
"filename",
",",
"restart",
"=",
"False",
")",
":",
"mode",
"=",
"'w'",
"if",
"restart",
":",
"mode",
"=",
"'a'",
"return",
"Trajectory",
"(",
"first",
",",
"filename",
",",
"mode",
")"
] |
Factory function to easily create a trajectory object
|
[
"Factory",
"function",
"to",
"easily",
"create",
"a",
"trajectory",
"object"
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/io/trajectory.py#L60-L67
|
16,286
|
chemlab/chemlab
|
chemlab/db/utils.py
|
InsensitiveDict.has_key
|
def has_key(self, key):
"""Case insensitive test whether 'key' exists."""
k = self._lowerOrReturn(key)
return k in self.data
|
python
|
def has_key(self, key):
"""Case insensitive test whether 'key' exists."""
k = self._lowerOrReturn(key)
return k in self.data
|
[
"def",
"has_key",
"(",
"self",
",",
"key",
")",
":",
"k",
"=",
"self",
".",
"_lowerOrReturn",
"(",
"key",
")",
"return",
"k",
"in",
"self",
".",
"data"
] |
Case insensitive test whether 'key' exists.
|
[
"Case",
"insensitive",
"test",
"whether",
"key",
"exists",
"."
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/db/utils.py#L44-L47
|
16,287
|
chemlab/chemlab
|
chemlab/graphics/renderers/sphere.py
|
SphereRenderer.update_positions
|
def update_positions(self, positions):
'''Update the sphere positions.
'''
sphs_verts = self.sphs_verts_radii.copy()
sphs_verts += positions.reshape(self.n_spheres, 1, 3)
self.tr.update_vertices(sphs_verts)
self.poslist = positions
|
python
|
def update_positions(self, positions):
'''Update the sphere positions.
'''
sphs_verts = self.sphs_verts_radii.copy()
sphs_verts += positions.reshape(self.n_spheres, 1, 3)
self.tr.update_vertices(sphs_verts)
self.poslist = positions
|
[
"def",
"update_positions",
"(",
"self",
",",
"positions",
")",
":",
"sphs_verts",
"=",
"self",
".",
"sphs_verts_radii",
".",
"copy",
"(",
")",
"sphs_verts",
"+=",
"positions",
".",
"reshape",
"(",
"self",
".",
"n_spheres",
",",
"1",
",",
"3",
")",
"self",
".",
"tr",
".",
"update_vertices",
"(",
"sphs_verts",
")",
"self",
".",
"poslist",
"=",
"positions"
] |
Update the sphere positions.
|
[
"Update",
"the",
"sphere",
"positions",
"."
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/sphere.py#L86-L93
|
16,288
|
chemlab/chemlab
|
chemlab/core/serialization.py
|
isnamedtuple
|
def isnamedtuple(obj):
"""Heuristic check if an object is a namedtuple."""
return isinstance(obj, tuple) \
and hasattr(obj, "_fields") \
and hasattr(obj, "_asdict") \
and callable(obj._asdict)
|
python
|
def isnamedtuple(obj):
"""Heuristic check if an object is a namedtuple."""
return isinstance(obj, tuple) \
and hasattr(obj, "_fields") \
and hasattr(obj, "_asdict") \
and callable(obj._asdict)
|
[
"def",
"isnamedtuple",
"(",
"obj",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"tuple",
")",
"and",
"hasattr",
"(",
"obj",
",",
"\"_fields\"",
")",
"and",
"hasattr",
"(",
"obj",
",",
"\"_asdict\"",
")",
"and",
"callable",
"(",
"obj",
".",
"_asdict",
")"
] |
Heuristic check if an object is a namedtuple.
|
[
"Heuristic",
"check",
"if",
"an",
"object",
"is",
"a",
"namedtuple",
"."
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/serialization.py#L10-L15
|
16,289
|
chemlab/chemlab
|
chemlab/md/analysis.py
|
running_coordination_number
|
def running_coordination_number(coordinates_a, coordinates_b, periodic,
binsize=0.002, cutoff=1.5):
"""This is the cumulative radial distribution
function, also called running coordination number"""
x, y = rdf(coordinates_a,
coordinates_b,
periodic=periodic,
normalize=False,
binsize=binsize,
cutoff=cutoff)
y = y.astype('float32') / len(coordinates_a)
y = np.cumsum(y)
return x, y
|
python
|
def running_coordination_number(coordinates_a, coordinates_b, periodic,
binsize=0.002, cutoff=1.5):
"""This is the cumulative radial distribution
function, also called running coordination number"""
x, y = rdf(coordinates_a,
coordinates_b,
periodic=periodic,
normalize=False,
binsize=binsize,
cutoff=cutoff)
y = y.astype('float32') / len(coordinates_a)
y = np.cumsum(y)
return x, y
|
[
"def",
"running_coordination_number",
"(",
"coordinates_a",
",",
"coordinates_b",
",",
"periodic",
",",
"binsize",
"=",
"0.002",
",",
"cutoff",
"=",
"1.5",
")",
":",
"x",
",",
"y",
"=",
"rdf",
"(",
"coordinates_a",
",",
"coordinates_b",
",",
"periodic",
"=",
"periodic",
",",
"normalize",
"=",
"False",
",",
"binsize",
"=",
"binsize",
",",
"cutoff",
"=",
"cutoff",
")",
"y",
"=",
"y",
".",
"astype",
"(",
"'float32'",
")",
"/",
"len",
"(",
"coordinates_a",
")",
"y",
"=",
"np",
".",
"cumsum",
"(",
"y",
")",
"return",
"x",
",",
"y"
] |
This is the cumulative radial distribution
function, also called running coordination number
|
[
"This",
"is",
"the",
"cumulative",
"radial",
"distribution",
"function",
"also",
"called",
"running",
"coordination",
"number"
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/md/analysis.py#L59-L71
|
16,290
|
chemlab/chemlab
|
chemlab/graphics/renderers/line.py
|
LineRenderer.update_colors
|
def update_colors(self, colors):
"""Update the colors"""
colors = np.array(colors, dtype=np.uint8)
self._vbo_c.set_data(colors)
self._vbo_c.unbind()
|
python
|
def update_colors(self, colors):
"""Update the colors"""
colors = np.array(colors, dtype=np.uint8)
self._vbo_c.set_data(colors)
self._vbo_c.unbind()
|
[
"def",
"update_colors",
"(",
"self",
",",
"colors",
")",
":",
"colors",
"=",
"np",
".",
"array",
"(",
"colors",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"self",
".",
"_vbo_c",
".",
"set_data",
"(",
"colors",
")",
"self",
".",
"_vbo_c",
".",
"unbind",
"(",
")"
] |
Update the colors
|
[
"Update",
"the",
"colors"
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/line.py#L71-L76
|
16,291
|
chemlab/chemlab
|
chemlab/mviewer/api/core.py
|
frames
|
def frames(skip=1):
'''Useful command to iterate on the trajectory frames. It can be
used in a for loop.
::
for i in frames():
coords = current_trajectory()[i]
# Do operation on coords
You can use the option *skip* to take every i :sup:`th` frame.
'''
from PyQt4 import QtGui
for i in range(0, viewer.traj_controls.max_index, skip):
viewer.traj_controls.goto_frame(i)
yield i
QtGui.qApp.processEvents()
|
python
|
def frames(skip=1):
'''Useful command to iterate on the trajectory frames. It can be
used in a for loop.
::
for i in frames():
coords = current_trajectory()[i]
# Do operation on coords
You can use the option *skip* to take every i :sup:`th` frame.
'''
from PyQt4 import QtGui
for i in range(0, viewer.traj_controls.max_index, skip):
viewer.traj_controls.goto_frame(i)
yield i
QtGui.qApp.processEvents()
|
[
"def",
"frames",
"(",
"skip",
"=",
"1",
")",
":",
"from",
"PyQt4",
"import",
"QtGui",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"viewer",
".",
"traj_controls",
".",
"max_index",
",",
"skip",
")",
":",
"viewer",
".",
"traj_controls",
".",
"goto_frame",
"(",
"i",
")",
"yield",
"i",
"QtGui",
".",
"qApp",
".",
"processEvents",
"(",
")"
] |
Useful command to iterate on the trajectory frames. It can be
used in a for loop.
::
for i in frames():
coords = current_trajectory()[i]
# Do operation on coords
You can use the option *skip* to take every i :sup:`th` frame.
|
[
"Useful",
"command",
"to",
"iterate",
"on",
"the",
"trajectory",
"frames",
".",
"It",
"can",
"be",
"used",
"in",
"a",
"for",
"loop",
"."
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/core.py#L59-L77
|
16,292
|
chemlab/chemlab
|
chemlab/mviewer/api/display.py
|
display_system
|
def display_system(system, autozoom=True):
'''Display a `~chemlab.core.System` instance at screen'''
viewer.clear()
viewer.add_representation(BallAndStickRepresentation, system)
if autozoom:
autozoom_()
viewer.update()
msg(str(system))
|
python
|
def display_system(system, autozoom=True):
'''Display a `~chemlab.core.System` instance at screen'''
viewer.clear()
viewer.add_representation(BallAndStickRepresentation, system)
if autozoom:
autozoom_()
viewer.update()
msg(str(system))
|
[
"def",
"display_system",
"(",
"system",
",",
"autozoom",
"=",
"True",
")",
":",
"viewer",
".",
"clear",
"(",
")",
"viewer",
".",
"add_representation",
"(",
"BallAndStickRepresentation",
",",
"system",
")",
"if",
"autozoom",
":",
"autozoom_",
"(",
")",
"viewer",
".",
"update",
"(",
")",
"msg",
"(",
"str",
"(",
"system",
")",
")"
] |
Display a `~chemlab.core.System` instance at screen
|
[
"Display",
"a",
"~chemlab",
".",
"core",
".",
"System",
"instance",
"at",
"screen"
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/display.py#L13-L22
|
16,293
|
chemlab/chemlab
|
chemlab/mviewer/api/display.py
|
display_molecule
|
def display_molecule(mol, autozoom=True):
'''Display a `~chemlab.core.Molecule` instance in the viewer.
This function wraps the molecule in a system before displaying
it.
'''
s = System([mol])
display_system(s, autozoom=True)
|
python
|
def display_molecule(mol, autozoom=True):
'''Display a `~chemlab.core.Molecule` instance in the viewer.
This function wraps the molecule in a system before displaying
it.
'''
s = System([mol])
display_system(s, autozoom=True)
|
[
"def",
"display_molecule",
"(",
"mol",
",",
"autozoom",
"=",
"True",
")",
":",
"s",
"=",
"System",
"(",
"[",
"mol",
"]",
")",
"display_system",
"(",
"s",
",",
"autozoom",
"=",
"True",
")"
] |
Display a `~chemlab.core.Molecule` instance in the viewer.
This function wraps the molecule in a system before displaying
it.
|
[
"Display",
"a",
"~chemlab",
".",
"core",
".",
"Molecule",
"instance",
"in",
"the",
"viewer",
"."
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/display.py#L24-L32
|
16,294
|
chemlab/chemlab
|
chemlab/mviewer/api/display.py
|
load_molecule
|
def load_molecule(name, format=None):
'''Read a `~chemlab.core.Molecule` from a file.
.. seealso:: `chemlab.io.datafile`
'''
mol = datafile(name, format=format).read('molecule')
display_system(System([mol]))
|
python
|
def load_molecule(name, format=None):
'''Read a `~chemlab.core.Molecule` from a file.
.. seealso:: `chemlab.io.datafile`
'''
mol = datafile(name, format=format).read('molecule')
display_system(System([mol]))
|
[
"def",
"load_molecule",
"(",
"name",
",",
"format",
"=",
"None",
")",
":",
"mol",
"=",
"datafile",
"(",
"name",
",",
"format",
"=",
"format",
")",
".",
"read",
"(",
"'molecule'",
")",
"display_system",
"(",
"System",
"(",
"[",
"mol",
"]",
")",
")"
] |
Read a `~chemlab.core.Molecule` from a file.
.. seealso:: `chemlab.io.datafile`
|
[
"Read",
"a",
"~chemlab",
".",
"core",
".",
"Molecule",
"from",
"a",
"file",
"."
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/display.py#L54-L61
|
16,295
|
chemlab/chemlab
|
chemlab/mviewer/api/display.py
|
write_system
|
def write_system(filename, format=None):
'''Write the system currently displayed to a file.'''
datafile(filename, format=format, mode='w').write('system',
current_system())
|
python
|
def write_system(filename, format=None):
'''Write the system currently displayed to a file.'''
datafile(filename, format=format, mode='w').write('system',
current_system())
|
[
"def",
"write_system",
"(",
"filename",
",",
"format",
"=",
"None",
")",
":",
"datafile",
"(",
"filename",
",",
"format",
"=",
"format",
",",
"mode",
"=",
"'w'",
")",
".",
"write",
"(",
"'system'",
",",
"current_system",
"(",
")",
")"
] |
Write the system currently displayed to a file.
|
[
"Write",
"the",
"system",
"currently",
"displayed",
"to",
"a",
"file",
"."
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/display.py#L102-L105
|
16,296
|
chemlab/chemlab
|
chemlab/mviewer/api/display.py
|
write_molecule
|
def write_molecule(filename, format=None):
'''Write the system displayed in a file as a molecule.'''
datafile(filename, format=format,
mode='w').write('molecule',current_system())
|
python
|
def write_molecule(filename, format=None):
'''Write the system displayed in a file as a molecule.'''
datafile(filename, format=format,
mode='w').write('molecule',current_system())
|
[
"def",
"write_molecule",
"(",
"filename",
",",
"format",
"=",
"None",
")",
":",
"datafile",
"(",
"filename",
",",
"format",
"=",
"format",
",",
"mode",
"=",
"'w'",
")",
".",
"write",
"(",
"'molecule'",
",",
"current_system",
"(",
")",
")"
] |
Write the system displayed in a file as a molecule.
|
[
"Write",
"the",
"system",
"displayed",
"in",
"a",
"file",
"as",
"a",
"molecule",
"."
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/display.py#L107-L110
|
16,297
|
chemlab/chemlab
|
chemlab/mviewer/api/display.py
|
load_trajectory
|
def load_trajectory(name, skip=1, format=None):
'''Load a trajectory file into chemlab. You should call this
command after you load a `~chemlab.core.System` through
load_system or load_remote_system.
'''
df = datafile(name, format=format)
dt, coords = df.read('trajectory', skip=skip)
boxes = df.read('boxes')
viewer.current_traj = coords
viewer.frame_times = dt
viewer.traj_controls.set_ticks(len(dt))
def update(index):
f = coords[index]
for fp in _frame_processors:
f = fp(coords, index)
# update the current representation
viewer.representation.update_positions(f)
viewer.representation.update_box(boxes[index])
current_system().r_array = f
current_system().box_vectors = boxes[index]
viewer.traj_controls.set_time(dt[index])
viewer.update()
viewer.traj_controls.show()
viewer.traj_controls.frame_changed.connect(update)
|
python
|
def load_trajectory(name, skip=1, format=None):
'''Load a trajectory file into chemlab. You should call this
command after you load a `~chemlab.core.System` through
load_system or load_remote_system.
'''
df = datafile(name, format=format)
dt, coords = df.read('trajectory', skip=skip)
boxes = df.read('boxes')
viewer.current_traj = coords
viewer.frame_times = dt
viewer.traj_controls.set_ticks(len(dt))
def update(index):
f = coords[index]
for fp in _frame_processors:
f = fp(coords, index)
# update the current representation
viewer.representation.update_positions(f)
viewer.representation.update_box(boxes[index])
current_system().r_array = f
current_system().box_vectors = boxes[index]
viewer.traj_controls.set_time(dt[index])
viewer.update()
viewer.traj_controls.show()
viewer.traj_controls.frame_changed.connect(update)
|
[
"def",
"load_trajectory",
"(",
"name",
",",
"skip",
"=",
"1",
",",
"format",
"=",
"None",
")",
":",
"df",
"=",
"datafile",
"(",
"name",
",",
"format",
"=",
"format",
")",
"dt",
",",
"coords",
"=",
"df",
".",
"read",
"(",
"'trajectory'",
",",
"skip",
"=",
"skip",
")",
"boxes",
"=",
"df",
".",
"read",
"(",
"'boxes'",
")",
"viewer",
".",
"current_traj",
"=",
"coords",
"viewer",
".",
"frame_times",
"=",
"dt",
"viewer",
".",
"traj_controls",
".",
"set_ticks",
"(",
"len",
"(",
"dt",
")",
")",
"def",
"update",
"(",
"index",
")",
":",
"f",
"=",
"coords",
"[",
"index",
"]",
"for",
"fp",
"in",
"_frame_processors",
":",
"f",
"=",
"fp",
"(",
"coords",
",",
"index",
")",
"# update the current representation",
"viewer",
".",
"representation",
".",
"update_positions",
"(",
"f",
")",
"viewer",
".",
"representation",
".",
"update_box",
"(",
"boxes",
"[",
"index",
"]",
")",
"current_system",
"(",
")",
".",
"r_array",
"=",
"f",
"current_system",
"(",
")",
".",
"box_vectors",
"=",
"boxes",
"[",
"index",
"]",
"viewer",
".",
"traj_controls",
".",
"set_time",
"(",
"dt",
"[",
"index",
"]",
")",
"viewer",
".",
"update",
"(",
")",
"viewer",
".",
"traj_controls",
".",
"show",
"(",
")",
"viewer",
".",
"traj_controls",
".",
"frame_changed",
".",
"connect",
"(",
"update",
")"
] |
Load a trajectory file into chemlab. You should call this
command after you load a `~chemlab.core.System` through
load_system or load_remote_system.
|
[
"Load",
"a",
"trajectory",
"file",
"into",
"chemlab",
".",
"You",
"should",
"call",
"this",
"command",
"after",
"you",
"load",
"a",
"~chemlab",
".",
"core",
".",
"System",
"through",
"load_system",
"or",
"load_remote_system",
"."
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/display.py#L128-L158
|
16,298
|
chemlab/chemlab
|
chemlab/core/system.py
|
System.from_arrays
|
def from_arrays(cls, **kwargs):
'''Initialize a System from its constituent arrays. It is the
fastest way to initialize a System, well suited for
reading one or more big System from data files.
**Parameters**
The following parameters are required:
- type_array: An array of the types
- maps: A dictionary that describes the relationships between
molecules in the system and atoms and bonds.
**Example**
This is how to initialize a System made of 3 water molecules::
# Initialize the arrays that contain 9 atoms
r_array = np.random.random((3, 9))
type_array = ['O', 'H', 'H', 'O', 'H', 'H', 'O', 'H', 'H']
# The maps tell us to which molecule each atom belongs to. In this
# example first 3 atoms belong to molecule 0, second 3 atoms
# to molecule 1 and last 3 atoms to molecule 2.
maps = {('atom', 'molecule') : [0, 0, 0, 1, 1, 1, 2, 2, 2]}
System.from_arrays(r_array=r_array,
type_array=type_array,
maps=maps)
# You can also specify bonds, again with the its map that specifies
# to to which molecule each bond belongs to.
bonds = [[0, 1], [0, 2], [3, 4], [3, 5], [6, 7], [6, 8]]
maps[('bond', 'molecule')] = [0, 0, 1, 1, 2, 2]
System.from_arrays(r_array=r_array,
type_array=type_array,
bonds=bonds,
maps=maps)
'''
if 'mol_indices' in kwargs:
raise DeprecationWarning('The mol_indices argument is deprecated, use maps instead. (See from_arrays docstring)')
return super(System, cls).from_arrays(**kwargs)
|
python
|
def from_arrays(cls, **kwargs):
'''Initialize a System from its constituent arrays. It is the
fastest way to initialize a System, well suited for
reading one or more big System from data files.
**Parameters**
The following parameters are required:
- type_array: An array of the types
- maps: A dictionary that describes the relationships between
molecules in the system and atoms and bonds.
**Example**
This is how to initialize a System made of 3 water molecules::
# Initialize the arrays that contain 9 atoms
r_array = np.random.random((3, 9))
type_array = ['O', 'H', 'H', 'O', 'H', 'H', 'O', 'H', 'H']
# The maps tell us to which molecule each atom belongs to. In this
# example first 3 atoms belong to molecule 0, second 3 atoms
# to molecule 1 and last 3 atoms to molecule 2.
maps = {('atom', 'molecule') : [0, 0, 0, 1, 1, 1, 2, 2, 2]}
System.from_arrays(r_array=r_array,
type_array=type_array,
maps=maps)
# You can also specify bonds, again with the its map that specifies
# to to which molecule each bond belongs to.
bonds = [[0, 1], [0, 2], [3, 4], [3, 5], [6, 7], [6, 8]]
maps[('bond', 'molecule')] = [0, 0, 1, 1, 2, 2]
System.from_arrays(r_array=r_array,
type_array=type_array,
bonds=bonds,
maps=maps)
'''
if 'mol_indices' in kwargs:
raise DeprecationWarning('The mol_indices argument is deprecated, use maps instead. (See from_arrays docstring)')
return super(System, cls).from_arrays(**kwargs)
|
[
"def",
"from_arrays",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mol_indices'",
"in",
"kwargs",
":",
"raise",
"DeprecationWarning",
"(",
"'The mol_indices argument is deprecated, use maps instead. (See from_arrays docstring)'",
")",
"return",
"super",
"(",
"System",
",",
"cls",
")",
".",
"from_arrays",
"(",
"*",
"*",
"kwargs",
")"
] |
Initialize a System from its constituent arrays. It is the
fastest way to initialize a System, well suited for
reading one or more big System from data files.
**Parameters**
The following parameters are required:
- type_array: An array of the types
- maps: A dictionary that describes the relationships between
molecules in the system and atoms and bonds.
**Example**
This is how to initialize a System made of 3 water molecules::
# Initialize the arrays that contain 9 atoms
r_array = np.random.random((3, 9))
type_array = ['O', 'H', 'H', 'O', 'H', 'H', 'O', 'H', 'H']
# The maps tell us to which molecule each atom belongs to. In this
# example first 3 atoms belong to molecule 0, second 3 atoms
# to molecule 1 and last 3 atoms to molecule 2.
maps = {('atom', 'molecule') : [0, 0, 0, 1, 1, 1, 2, 2, 2]}
System.from_arrays(r_array=r_array,
type_array=type_array,
maps=maps)
# You can also specify bonds, again with the its map that specifies
# to to which molecule each bond belongs to.
bonds = [[0, 1], [0, 2], [3, 4], [3, 5], [6, 7], [6, 8]]
maps[('bond', 'molecule')] = [0, 0, 1, 1, 2, 2]
System.from_arrays(r_array=r_array,
type_array=type_array,
bonds=bonds,
maps=maps)
|
[
"Initialize",
"a",
"System",
"from",
"its",
"constituent",
"arrays",
".",
"It",
"is",
"the",
"fastest",
"way",
"to",
"initialize",
"a",
"System",
"well",
"suited",
"for",
"reading",
"one",
"or",
"more",
"big",
"System",
"from",
"data",
"files",
"."
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/system.py#L145-L188
|
16,299
|
chemlab/chemlab
|
chemlab/core/system.py
|
System.minimum_image
|
def minimum_image(self):
"""Align the system according to the minimum image convention"""
if self.box_vectors is None:
raise ValueError('No periodic vectors defined')
else:
self.r_array = minimum_image(self.r_array, self.box_vectors.diagonal())
return self
|
python
|
def minimum_image(self):
"""Align the system according to the minimum image convention"""
if self.box_vectors is None:
raise ValueError('No periodic vectors defined')
else:
self.r_array = minimum_image(self.r_array, self.box_vectors.diagonal())
return self
|
[
"def",
"minimum_image",
"(",
"self",
")",
":",
"if",
"self",
".",
"box_vectors",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'No periodic vectors defined'",
")",
"else",
":",
"self",
".",
"r_array",
"=",
"minimum_image",
"(",
"self",
".",
"r_array",
",",
"self",
".",
"box_vectors",
".",
"diagonal",
"(",
")",
")",
"return",
"self"
] |
Align the system according to the minimum image convention
|
[
"Align",
"the",
"system",
"according",
"to",
"the",
"minimum",
"image",
"convention"
] |
c8730966316d101e24f39ac3b96b51282aba0abe
|
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/system.py#L196-L203
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.